Debian Codegraph @

terps/tads/tads3/lib/adv3/extras.t

raw
1 #charset "us-ascii"
2
3 /*
4 * Copyright (c) 2000, 2006 Michael J. Roberts. All Rights Reserved.
5 *
6 * TADS 3 Library - extras: special-purpose object classes
7 *
8 * This module defines classes for specialized simulation objects.
9 *
10 * Portions are based on original work by Eric Eve, incorporated by
11 * permission.
12 */
13
14 /* include the library header */
15 #include "adv3.h"
16
17
18 /* ------------------------------------------------------------------------ */
19 /*
20 * A "complex" container is an object that can have multiple kinds of
21 * contents simultaneously. For example, a complex container could act
22 * as both a surface, so that some objects are sitting on top of it, and
23 * simultaneously as a container, with objects inside.
24 *
25 * The standard containment model only allows one kind of containment per
26 * container, because the nature of the containment is a feature of the
27 * container itself. The complex container handles multiple simultaneous
28 * containment types by using one or more sub-containers: for example, if
29 * we want to be able to act as both a surface and a regular container,
30 * we use two sub-containers, one of class Surface and one of class
31 * Container, to hold the different types of contents. When we need to
32 * perform an operation specific to a certain containment type, we
33 * delegate the operation to the sub-container of the appropriate type.
34 *
35 * Note that the complex container itself treats its direct contents as
36 * components, so any component parts can be made direct contents of the
37 * complex container object.
38 *
39 * If you want to include objects in your source code that are initially
40 * located within the component sub-containers, define them as directly
41 * within the ComplexContainer object, but give each one a 'subLocation'
42 * property set to the property of the component sub-container that will
43 * initially contain it. For example, here's how you'd place a blanket
44 * inside a washing machine, and a laundry basket on top of it:
45 *
46 *. + washingMachine: ComplexContainer 'washing machine' 'washing machine'
47 *. subContainer: ComplexComponent, Container { etc }
48 *. subSurface: ComplexComponent, Surface { etc }
49 *. ;
50 *.
51 *. ++ Thing 'big cotton blanket' 'blanket'
52 *. subLocation = &subContainer
53 *. ;
54 *.
55 *. ++ Container 'laundry basket' 'laundry basket'
56 *. subLocation = &subSurface
57 *. ;
58 *
59 * The subLocation setting is only used for initialization, and we
60 * automatically set it to nil right after we use it to set up the
61 * initial location. If you want to move something into one of the
62 * sub-containers on the fly, simply refer to the desired component
63 * directly:
64 *
65 * pants.moveInto(washingMachine.subContainer);
66 */
67 class ComplexContainer: Thing
68 /*
69 * Our inner container, if any. This is a "secret" object (in other
70 * words, it doesn't appear to players as a separate named object)
71 * that we use to store the contents that are meant to be within the
72 * complex container. If this is to be used, it should be set to a
73 * Container object - the most convenient way to do this is by using
74 * the nested object syntax to define a ComplexComponent Container
75 * instance, like so:
76 *
77 * washingMachine: ComplexContainer
78 *. subContainer: ComplexComponent, Container { etc }
79 *. ;
80 *
81 * Note that we use the ComplexComponent class (as well as
82 * Container) for the sub-container object. This makes the
83 * sub-container automatically use the name of its enclosing object
84 * in messages (in this case, the sub-container will use the same
85 * name as the washing machine).
86 *
87 * Note that the sub-containers don't have to be of class
88 * ComplexComponent, but using that class makes your job a little
89 * easier because the class sets the location and naming
90 * automatically. If you prefer to define your sub-containers as
91 * separate objects, not nested in the ComplexContainer's
92 * definition, there's no need to make them ComplexComponents; just
93 * make them ordinary Component objects.
94 *
95 * If this property is left as nil, then we don't have an inner
96 * container.
97 */
98 subContainer = nil
99
100 /*
101 * Our inner surface, if any. This is a secret object like the
102 * inner container; this object acts as our surface.
103 */
104 subSurface = nil
105
106 /*
107 * Our underside, if any. This is a secret object like the inner
108 * container; this object can act as the space underneath us, or as
109 * our bottom surface.
110 */
111 subUnderside = nil
112
113 /*
114 * Our rear surface or container, if any. This is a secret internal
115 * object like the inner container; this object can act as our back
116 * surface, or as the space just behind us.
117 */
118 subRear = nil
119
120 /* a list of all of our component objects */
121 allSubLocations = [subContainer, subSurface, subUnderside, subRear]
122
123 /*
124 * Show our status. We'll show the status for each of our
125 * sub-objects, so that we list any contents of our sub-container or
126 * sub-surface along with our description.
127 */
128 examineStatus()
129 {
130 /* if we have a sub-container, show its status */
131 if (subContainer != nil)
132 subContainer.examineStatus();
133
134 /* if we have a sub-surface, show its status */
135 if (subSurface != nil)
136 subSurface.examineStatus();
137
138 /* if we have a sub-rear, show its status */
139 if (subRear != nil)
140 subRear.examineStatus();
141
142 /* if we have a sub-underside, show its status */
143 if (subUnderside != nil)
144 subUnderside.examineStatus();
145 }
146
147 /*
148 * In most cases, the open/closed and locked/unlocked status of a
149 * complex container refer to the status of the sub-container.
150 */
151 isOpen = (subContainer != nil ? subContainer.isOpen : inherited)
152 isLocked = (subContainer != nil ? subContainer.isLocked : inherited)
153
154 makeOpen(stat)
155 {
156 if (subContainer != nil)
157 subContainer.makeOpen(stat);
158 else
159 inherited(stat);
160 }
161
162 makeLocked(stat)
163 {
164 if (subContainer != nil)
165 subContainer.makeLocked(stat);
166 else
167 inherited(stat);
168 }
169
170
171 /*
172 * route all commands that treat us as a container to our
173 * sub-container object
174 */
175 dobjFor(Open) maybeRemapTo(subContainer != nil, Open, subContainer)
176 dobjFor(Close) maybeRemapTo(subContainer != nil, Close, subContainer)
177 dobjFor(LookIn) maybeRemapTo(subContainer != nil, LookIn, subContainer)
178 iobjFor(PutIn) maybeRemapTo(subContainer != nil,
179 PutIn, DirectObject, subContainer)
180 dobjFor(Lock) maybeRemapTo(subContainer != nil, Lock, subContainer)
181 dobjFor(LockWith) maybeRemapTo(subContainer != nil,
182 LockWith, subContainer, IndirectObject)
183 dobjFor(Unlock) maybeRemapTo(subContainer != nil, Unlock, subContainer)
184 dobjFor(UnlockWith) maybeRemapTo(subContainer != nil,
185 UnlockWith, subContainer, IndirectObject)
186
187 /* route commands that treat us as a surface to our sub-surface */
188 iobjFor(PutOn) maybeRemapTo(subSurface != nil,
189 PutOn, DirectObject, subSurface)
190
191 /* route commands that affect our underside to our sub-underside */
192 iobjFor(PutUnder) maybeRemapTo(subUnderside != nil,
193 PutUnder, DirectObject, subUnderside)
194 dobjFor(LookUnder) maybeRemapTo(subUnderside != nil,
195 LookUnder, subUnderside)
196
197 /* route commands that affect our rear to our sub-rear-side */
198 iobjFor(PutBehind) maybeRemapTo(subRear != nil,
199 PutBehind, DirectObject, subRear)
200 dobjFor(LookBehind) maybeRemapTo(subRear != nil, LookBehind, subRear)
201
202 /* route commands relevant to nested rooms to our components */
203 dobjFor(StandOn) maybeRemapTo(getNestedRoomDest(StandOnAction) != nil,
204 StandOn, getNestedRoomDest(StandOnAction))
205 dobjFor(SitOn) maybeRemapTo(getNestedRoomDest(SitOnAction) != nil,
206 SitOn, getNestedRoomDest(SitOnAction))
207 dobjFor(LieOn) maybeRemapTo(getNestedRoomDest(LieOnAction) != nil,
208 LieOn, getNestedRoomDest(LieOnAction))
209 dobjFor(Board) maybeRemapTo(getNestedRoomDest(BoardAction) != nil,
210 Board, getNestedRoomDest(BoardAction))
211 dobjFor(Enter) maybeRemapTo(getNestedRoomDest(EnterAction) != nil,
212 Enter, getNestedRoomDest(EnterAction))
213
214 /* map GET OUT/OFF to whichever complex component we're currently in */
215 dobjFor(GetOutOf) maybeRemapTo(getNestedRoomSource(gActor) != nil,
216 GetOutOf, getNestedRoomSource(gActor))
217 dobjFor(GetOffOf) maybeRemapTo(getNestedRoomSource(gActor) != nil,
218 GetOffOf, getNestedRoomSource(gActor))
219
220 /*
221 * Get the destination for nested travel into this object. By
222 * default, we'll look at the sub-container and sub-surface
223 * components to see if either is a nested room, and if so, we'll
224 * return that. The surface takes priority if both are nested rooms.
225 *
226 * You can override this to differentiate by verb, if desired; for
227 * example, you could have SIT ON and LIE ON refer to the sub-surface
228 * component, while ENTER and BOARD refer to the sub-container
229 * component.
230 *
231 * Note that if you do need to override this method to distinguish
232 * between a sub-container ("IN") and a sub-surface ("ON") for nested
233 * room purposes, there's a subtlety to watch out for. The English
234 * library maps "sit on" and "sit in" to the single Action SitOn;
235 * likewise with "lie in/on" for LieOn and "stand in/on" for StandOn.
236 * If you're distinguishing the sub-container from the sub-surface,
237 * you'll probably want to distinguish SIT IN from SIT ON (and
238 * likewise for LIE and STAND). Fortunately, even though the action
239 * class is the same for both phrasings, you can still find out
240 * exactly which preposition the player typed using
241 * action.getEnteredVerbPhrase().
242 */
243 getNestedRoomDest(action)
244 {
245 /*
246 * check the sub-surface first to see if it's a nested room;
247 * failing that, check the sub-container; failing that, we don't
248 * have a suitable component destination
249 */
250 if (subSurface != nil && subSurface.ofKind(NestedRoom))
251 return subSurface;
252 else if (subContainer != nil && subContainer.ofKind(NestedRoom))
253 return subContainer;
254 else
255 return nil;
256 }
257
258 /*
259 * Get the source for nested travel out of this object. This is used
260 * for GET OUT OF <self> - we figure out which nested room component
261 * the actor is in, so that we can remap the command to GET OUT OF
262 * <that component>.
263 */
264 getNestedRoomSource(actor)
265 {
266 /* figure out which child the actor is in */
267 foreach (local chi in allSubLocations)
268 {
269 if (chi != nil && actor.isIn(chi))
270 return chi;
271 }
272
273 /* the actor doesn't appear to be in one of our component locations */
274 return nil;
275 }
276
277 /*
278 * Get a list of objects suitable for matching ALL in TAKE ALL FROM
279 * <self>. By default, if we have a sub-surface and/or
280 * sub-container, we return everything in scope that's inside either
281 * one of those. Otherwise, if we have a sub-rear-surface and/or an
282 * underside, we'll return everything from those.
283 */
284 getAllForTakeFrom(scopeList)
285 {
286 local containers;
287
288 /*
289 * Make a list of the containers in which we're going to look.
290 * If we have a sub-container or sub-surface, look only in those.
291 * Otherwise, if we have a rear surface or underside, look in
292 * those.
293 */
294 containers = [];
295 if (subContainer != nil)
296 containers += subContainer;
297 if (subSurface != nil)
298 containers += subSurface;
299 if (containers == [])
300 {
301 if (subRear != nil)
302 containers += subRear;
303 if (subUnderside != nil)
304 containers += subUnderside;
305 }
306
307 /*
308 * return the list of everything in scope that's directly in one
309 * of the selected containers, but isn't a component of its
310 * direct container
311 */
312 return scopeList.subset(
313 {x: (x != self
314 && containers.indexOf(x) == nil
315 && containers.indexWhich(
316 {c: x.isDirectlyIn(c) && !x.isComponentOf(c)}) != nil)});
317 }
318
319 /*
320 * Add an object to my contents. If the object has a subLocation
321 * setting, take it as indicating which of my subcontainers is to
322 * contain the object.
323 */
324 addToContents(obj)
325 {
326 local sub;
327
328 /*
329 * if the object has a subLocation, add it to my appropriate
330 * component object; if not, add to my own contents as usual
331 */
332 if ((sub = obj.subLocation) != nil)
333 {
334 /*
335 * It specifies a subLocation - add it to the corresponding
336 * component's contents. Note that subLocation is a property
337 * pointer - &subContainer for my container component,
338 * &subSurface for my surface component, etc.
339 */
340 self.(sub).addToContents(obj);
341
342 /*
343 * The object's present location is merely for set-up
344 * purposes, so that the '+' object definition notation can
345 * be used to give the object its initial location. The
346 * object really wants to be in the sub-container, to whose
347 * contents list we've just added it. Set its location to
348 * the sub-container.
349 */
350 obj.location = self.(sub);
351
352 /*
353 * Now that we've moved the object into its sub-location,
354 * forget the subLocation setting, since this property is
355 * only for initialization.
356 */
357 obj.subLocation = nil;
358 }
359 else
360 {
361 /* there's no subLocation, so use the default handling */
362 inherited(obj);
363 }
364 }
365
366 /*
367 * If we have any SpaceOverlay children, abandon the contents of the
368 * overlaid spaces as needed.
369 */
370 mainMoveInto(newCont)
371 {
372 /*
373 * If any of our components are SpaceOverlays, notify them. We
374 * only worry about the rear and underside components, since it's
375 * never appropriate for our container and surface components to
376 * act as space overlays.
377 */
378 notifyComponentOfMove(subRear);
379 notifyComponentOfMove(subUnderside);
380
381 /* do the normal work */
382 inherited(newCont);
383 }
384
385 /*
386 * if we're being pushed into a new location (as a PushTraveler),
387 * abandon the contents of any SpaceOverlay components
388 */
389 beforeMovePushable(traveler, connector, dest)
390 {
391 /*
392 * notify our SpaceOverlay components that we're being moved, if
393 * we're going to end up in a new location
394 */
395 if (dest != location)
396 {
397 /* notify our rear and underside components of the move */
398 notifyComponentOfMove(subRear);
399 notifyComponentOfMove(subUnderside);
400 }
401
402 /* do the normal work */
403 inherited(traveler, connector, dest);
404 }
405
406 /*
407 * if the given component is a SpaceOverlay, notify it that we're
408 * moving, so that it can abandon its contents as needed
409 */
410 notifyComponentOfMove(sub)
411 {
412 /* if it's a SpaceOverlay, abandon its contents if necessary */
413 if (sub != nil && sub.ofKind(SpaceOverlay))
414 sub.abandonContents();
415 }
416
417 /* pass bag-of-holding operations to our sub-container */
418 tryPuttingObjInBag(target)
419 {
420 /* if we have a subcontainer, let it handle the operation */
421 return (subContainer != nil
422 ? subContainer.tryPuttingObjInBag(target)
423 : nil);
424 }
425
426 /* pass implicit PUT x IN self operations to our subcontainer */
427 tryMovingObjInto(obj)
428 {
429 /* if we have a subcontainer, let it handle the operation */
430 return (subContainer != nil
431 ? subContainer.tryMovingObjInto(obj)
432 : nil);
433 }
434 ;
435
436 /*
437 * we don't actually define any subLocation property values anywhere, so
438 * declare it to make sure the compiler knows it's a property name
439 */
440 property subLocation;
441
442 /*
443 * A component object of a complex container. This class can be used as
444 * a mix-in for sub-objects of a complex container (the subContainer or
445 * subSurface) defined as nested objects.
446 *
447 * This class is based on Component, which is suitable for complex
448 * container sub-objects because it makes them inseparable from the
449 * complex container. It's also based on NameAsParent, which makes the
450 * object automatically use the same name (in messages) as the lexical
451 * parent object. This is usually what one wants for a sub-object of a
452 * complex container, because it makes the sub-object essentially
453 * invisible to the user by referring to the sub-object in messages as
454 * though it were the complex container itself: "The washing machine
455 * contains...".
456 *
457 * This class also automatically initializes our location to our lexical
458 * parent, during the pre-initialization process. Any of these that are
459 * dynamically created at run-time (using 'new') must have their
460 * locations set manually, because initializeLocation() won't be called
461 * automatically in those cases.
462 */
463 class ComplexComponent: Component, NameAsParent
464 initializeLocation()
465 {
466 /* set our location to our lexical parent */
467 location = lexicalParent;
468
469 /* inherit default so we initialize our container's 'contents' list */
470 inherited();
471 }
472
473 /*
474 * Get our "identity" object. We take our identity from our parent
475 * object, if we have one. Note that our identity isn't simply our
476 * parent, but rather is our parent's identity, recursively defined.
477 */
478 getIdentityObject()
479 {
480 return (location != nil ? location.getIdentityObject() : self);
481 }
482
483 /* don't participate in 'all', since we're a secret internal object */
484 hideFromAll(action) { return true; }
485
486 /*
487 * In case this component is being used to implement a nested room of
488 * some kind (a platform, booth, etc), use the complex container's
489 * location as the staging location. Normally our staging location
490 * would be our direct container, but as with other aspects of
491 * complex containers, the container/component are meant to act as a
492 * single combined object, so we'd want to bypass the complex
493 * container and move directly between the enclosing location and
494 * 'self'.
495 */
496 stagingLocations = [lexicalParent.location]
497 ;
498
499 /*
500 * A container door. This is useful for cases where you want to create
501 * the door to a container as a separate object in its own right.
502 */
503 class ContainerDoor: Component
504 /*
505 * In most cases, you should create a ContainerDoor as a component of
506 * a ComplexContainer. It's usually necessary to use a
507 * ComplexContainer in order to use a door, since the door has to go
508 * somewhere, and it can't go inside the container it controls
509 * (because if it were inside, it wouldn't be accessible when the
510 * container is closed).
511 *
512 * By default, we assume that our immediate location is a complex
513 * container, and its subContainer is the actual container for which
514 * we're the door. You can override this property to create a
515 * different relationship if necessary.
516 */
517 subContainer = (location.subContainer)
518
519 /* we're open if our associated sub-container is open */
520 isOpen = (subContainer.isOpen)
521
522 /* our status description mentions our open status */
523 examineStatus()
524 {
525 /* add our open status */
526 say(isOpen
527 ? gLibMessages.currentlyOpen : gLibMessages.currentlyClosed);
528
529 /* add the base class behavior */
530 inherited();
531 }
532
533 /* looking in or behind a door is like looking inside the container */
534 dobjFor(LookIn) remapTo(LookIn, subContainer)
535 dobjFor(LookBehind) remapTo(LookIn, subContainer)
536
537 /* door-like operations on the door map to the container */
538 dobjFor(Open) remapTo(Open, subContainer)
539 dobjFor(Close) remapTo(Close, subContainer)
540 dobjFor(Lock) remapTo(Lock, subContainer)
541 dobjFor(LockWith) remapTo(LockWith, subContainer, IndirectObject)
542 dobjFor(Unlock) remapTo(Unlock, subContainer)
543 dobjFor(UnlockWith) remapTo(UnlockWith, subContainer, IndirectObject)
544 ;
545
546
547 /* ------------------------------------------------------------------------ */
548 /*
549 * A "space overlay" is a special type of container whose contents are
550 * supposed to be adjacent to the container object (i.e., self), but are
551 * not truly contained in the usual sense. This is used to model spatial
552 * relationships such as UNDER and BEHIND, which aren't directly
553 * supported in the normal containment model.
554 *
555 * The special feature of a space overlay is that the contents aren't
556 * truly attached to the container object, so they don't move with it the
557 * way that the contents of an ordinary container do. For example,
558 * suppose we have a space overlay representing a bookcase and the space
559 * behind it, so that we can hide a painting behind the bookcase: in this
560 * case, moving the bookcase should leave the painting where it was,
561 * because it was just sitting there in that space. In the real world,
562 * of course, the painting was sitting on the floor all along, so moving
563 * the bookcase would have no effect on it; but our spatial relationship
564 * model isn't quite as good as reality's, so we have to resort to an
565 * extra fix-up step. Specifically, when we move a space overlay, we
566 * always check to see if its contents need to be relocated to the place
567 * where they were really supposed to be all along.
568 */
569 class SpaceOverlay: BulkLimiter
570 /*
571 * If we move this object, the objects we contain might stay put
572 * rather than moving along with the container. For example, if we
573 * represent the space behind a bookcase, moving the bookcase would
574 * leave objects that were formerly behind the bookcase just sitting
575 * on the floor (or attached to the wall, or whatever).
576 */
577 mainMoveInto(newContainer)
578 {
579 /* check to see if our objects need to be left behind */
580 abandonContents();
581
582 /* now do the normal work */
583 inherited(newContainer);
584 }
585
586 /*
587 * when we're being pushed to a new location via push-travel, abandon
588 * our contents before we're moved
589 */
590 beforeMovePushable(traveler, connector, dest)
591 {
592 /* check to see if our objects need to be left behind */
593 if (dest != getIdentityObject().location)
594 abandonContents();
595
596 /* do the normal work */
597 inherited(traveler, connector, dest);
598 }
599
600 /*
601 * abandonLocation is where the things under me end up when I'm
602 * moved.
603 *
604 * An Underside or RearContainer represents an object that has a
605 * space underneath or behind it, respectively, but the space itself
606 * isn't truly part of the container object (i.e., self). This
607 * means that when the container moves, the objects under/behind it
608 * shouldn't move. For example, if there's a box under a bed,
609 * moving the bed out of the room should leave the box sitting on
610 * the floor where the bed used to be.
611 *
612 * By default, our abandonLocation is simply the location of our
613 * "identity object" - that is, the location of our nearest
614 * enclosing object that isn't a component.
615 *
616 * This can be overridden if the actual abandonment location should
617 * be somewhere other than our assembly location. In addition, you
618 * can set this to nil to indicate that objects under/behind me will
619 * NOT be abandoned when I move; instead, they'll simply stay with
620 * me, as though they're attached to my underside/back surface.
621 */
622 abandonLocation = (getIdentityObject().location)
623
624 /*
625 * By default we list our direct contents the first time we're
626 * moved, and ONLY the first time. If alwaysListOnMove is
627 * overridden to true, then we'll list our contents EVERY time we're
628 * moved. If neverListOnMove is set to true, then we'll NEVER list
629 * our contents automatically when moved; this can be used in cases
630 * where the game wants to produce its own listing explicitly,
631 * rather than using the default listing we generate. (Obviously,
632 * setting both 'always' and 'never' is meaningless, but in case
633 * you're wondering, 'never' overrides 'always' in this case.)
634 *
635 * Setting abandonLocation to nil overrules alwaysListOnMove: if
636 * there's no abandonment, then we consider nothing to be revealed
637 * when we're moved, since my contents move along with me.
638 */
639 alwaysListOnMove = nil
640 neverListOnMove = nil
641
642 /*
643 * The lister we use to describe the objects being revealed when we
644 * move the SpaceOverlay object and abandon the contents. Each
645 * concrete kind of SpaceOverlay must provide a lister that uses
646 * appropriate language; the list should be roughly of the form
647 * "Moving the armoire reveals a rusty can underneath." Individual
648 * objects can override this to customize the message further.
649 */
650 abandonContentsLister = nil
651
652 /*
653 * Abandon my contents when I'm moved. This is called whenever we're
654 * moved to a new location, to take care of leaving behind the
655 * objects that were formerly under me.
656 *
657 * We'll move my direct contents into abandonLocation, unless that's
658 * set to nil. We don't move any Component objects within me, since
659 * we assume those to be attached.
660 */
661 abandonContents()
662 {
663 local dest;
664
665 /*
666 * if there's no abandonment location, our contents move with us,
667 * so there's nothing to do
668 */
669 if ((dest = abandonLocation) == nil)
670 return;
671
672 /*
673 * If we've never been moved before, or we always reveal my
674 * contents when moved, list our contents now. In any case, if
675 * we *never* list on move, don't generate the listing.
676 */
677 if ((alwaysListOnMove || !getIdentityObject().moved)
678 && !neverListOnMove)
679 {
680 local marker1, marker2;
681
682 /*
683 * We want to generate a listing of what is revealed by
684 * moving the object, which we can do by generating a
685 * listing of what we would normally see by looking in the
686 * overlay interior. We want the listing as it stands now,
687 * but in most cases, we don't actually want to generate the
688 * list quite yet, because we want the action that's moving
689 * the object to complete and show all of its messages first.
690 *
691 * However, if the action leaves the actor in a new
692 * location, do generate the listing before the rest of the
693 * action output, since the listing won't make any sense
694 * after we've moved to (and displayed the description of)
695 * the new location.
696 *
697 * To accomplish all of this, generate the listing now,
698 * before the rest of the action output, but insert special
699 * report markers into the transcript before and after the
700 * listing. Then, register to receive after-action
701 * notification; at the end of the action, we'll go back and
702 * move the range of transcript output between the markers
703 * to the end of the command's transcript entries, if we
704 * haven't moved to a new room.
705 *
706 * One final complication: we don't want our listing here to
707 * hide any default report from the main command, so run it
708 * as a sub-action. A sub-action doesn't override the
709 * visibility of its parent's default report.
710 */
711
712 /* first, add a marker to the transcript before the listing */
713 marker1 = gTranscript.addMarker();
714
715 /* generate the listing, using a generic sub-action context */
716 withActionEnv(Action, gActor, {: listContentsForMove() });
717
718 /* add another transcript marker after the listing */
719 marker2 = gTranscript.addMarker();
720
721 /*
722 * create our special handler object to receive notification
723 * at the end of the command - it'll move the reports to the
724 * end of the command output if need be
725 */
726 new SpaceOverlayAbandonFinisher(marker1, marker2);
727 }
728
729 /* now move my non-Component contents to the abandonment location */
730 foreach(obj in contents)
731 {
732 /* if it's not a component, move it */
733 if(!obj.ofKind(Component))
734 obj.moveInto(dest);
735 }
736 }
737
738 /*
739 * My weight does NOT include my "contents" if we abandon our
740 * contents on being moved. Our contents are not attached to us as
741 * they are in a normal sort of container; instead, they're merely
742 * colocated, so when we're moved, that colocation relationship ends.
743 */
744 getWeight()
745 {
746 /*
747 * if we abandon our contents on being moved, our weight doesn't
748 * include them, because they're not attached; otherwise, they do
749 * act like they're attached, and hence must be included in our
750 * weight as for any ordinary container
751 */
752 if (abandonLocation != nil)
753 {
754 /*
755 * our contents are not included in our weight, so our total
756 * weight is simply our own intrinsic weight
757 */
758 return weight;
759 }
760 else
761 {
762 /* our contents are attached, so include their weight as normal */
763 return inherited();
764 }
765 }
766
767 /*
768 * List our contents for moving the object. By default, we examine
769 * our interior using our abandonContentsLister.
770 */
771 listContentsForMove()
772 {
773 /* examine our contents with the abandonContentsLister */
774 examineInteriorWithLister(abandonContentsLister);
775 }
776 ;
777
778 /*
779 * Space Overlay Abandon Finisher - this is an internal object that we
780 * create in SpaceOverlay.abandonContents(). Its purpose is to receive
781 * an afterAction notification and clean up the report order if
782 * necessary.
783 */
784 class SpaceOverlayAbandonFinisher: object
785 construct(m1, m2)
786 {
787 /* remember the markers */
788 marker1 = m1;
789 marker2 = m2;
790
791 /* remember the actor's starting location */
792 origLocation = gActor.location;
793
794 /* register for afterAction notification */
795 gAction.addBeforeAfterObj(self);
796 }
797
798 /* the transcript markers identifying the listing reports */
799 marker1 = nil
800 marker2 = nil
801
802 /* the actor's location at the time we generated the listing */
803 origLocation = nil
804
805 /* receive our after-action notification */
806 afterAction()
807 {
808 /*
809 * If the actor hasn't changed locations, move the reports we
810 * generated for the listing to the end of the transcript.
811 */
812 if (gActor.location == origLocation)
813 gTranscript.moveRangeAppend(marker1, marker2);
814 }
815 ;
816
817 /*
818 * An "underside" is a special type of container that describes its
819 * contents as being under the object. This is appropriate for objects
820 * that have a space underneath, such as a bed or a table.
821 */
822 class Underside: SpaceOverlay
823 /*
824 * Can actors put new objects under self, using the PUT UNDER
825 * command? By default, we allow it. Override this property to nil
826 * if new objects cannot be added by player commands.
827 */
828 allowPutUnder = true
829
830 /* we need to LOOK UNDER this object to see its contents */
831 nestedLookIn() { nestedAction(LookUnder, self); }
832
833 /* use custom contents listers, for our special "under" wording */
834 contentsLister = undersideContentsLister
835 descContentsLister = undersideDescContentsLister
836 lookInLister = undersideLookUnderLister
837 inlineContentsLister = undersideInlineContentsLister
838 abandonContentsLister = undersideAbandonContentsLister
839
840 /* customize the message for taking something from that's not under me */
841 takeFromNotInMessage = &takeFromNotUnderMsg
842
843 /* customize the message indicating another object is already in me */
844 circularlyInMessage = &circularlyUnderMsg
845
846 /* message phrase for objects put under me */
847 putDestMessage = &putDestUnder
848
849 /* message when we don't have room to put another object under me */
850 tooFullMsg = &undersideTooFull
851
852 /* message when an object is too large (all by itself) to fit under me */
853 tooLargeForContainerMsg = &tooLargeForUndersideMsg
854
855 /* can't put self under self */
856 cannotPutInSelfMsg = &cannotPutUnderSelfMsg
857
858 /* can't put something under me when it's already under me */
859 alreadyPutInMsg = &alreadyPutUnderMsg
860
861 /* our implied containment verb is PUT UNDER */
862 tryMovingObjInto(obj) { return tryImplicitAction(PutUnder, obj, self); }
863
864 /* -------------------------------------------------------------------- */
865 /*
866 * Handle putting things under me
867 */
868 iobjFor(PutUnder)
869 {
870 verify()
871 {
872 /* use the standard put-in-interior verification */
873 verifyPutInInterior();
874 }
875 check()
876 {
877 /* only allow it if PUT UNDER commands are allowed */
878 if (!allowPutUnder)
879 {
880 reportFailure(&cannotPutUnderMsg);
881 exit;
882 }
883 }
884 action()
885 {
886 /* move the direct object onto me */
887 gDobj.moveInto(self);
888
889 /* issue our default acknowledgment */
890 defaultReport(&okayPutUnderMsg);
891 }
892 }
893
894 /*
895 * Looking "under" a surface simply shows the surface's contents.
896 */
897 dobjFor(LookUnder)
898 {
899 verify() { }
900 action() { examineInterior(); }
901 }
902 ;
903
904 /*
905 * A special kind of Underside that only accepts specific contents.
906 */
907 class RestrictedUnderside: RestrictedHolder, Underside
908 /*
909 * A message that explains why the direct object can't be put under
910 * this object. In most cases, the rather generic default message
911 * should be overridden to provide a specific reason that the dobj
912 * can't be put under me. The rejected object is provided as a
913 * parameter in case the message needs to vary by object, but we
914 * ignore this and just use a single blanket failure message by
915 * default.
916 */
917 cannotPutUnderMsg(obj) { return &cannotPutUnderRestrictedMsg; }
918
919 /* override PutUnder to enforce our contents restriction */
920 iobjFor(PutUnder) { check() { checkPutDobj(&cannotPutUnderMsg); } }
921 ;
922
923 /*
924 * A "rear container" is similar to an underside: it models the space
925 * behind an object.
926 */
927 class RearContainer: SpaceOverlay
928 /*
929 * Can actors put new objects behind self, using the PUT BEHIND
930 * command? By default, we allow it. Override this property to nil
931 * if new objects cannot be added by player commands.
932 */
933 allowPutBehind = true
934
935 /* we need to LOOK BEHIND this object to see its contents */
936 nestedLookIn() { nestedAction(LookBehind, self); }
937
938 /* use custom contents listers */
939 contentsLister = rearContentsLister
940 descContentsLister = rearDescContentsLister
941 lookInLister = rearLookBehindLister
942 inlineContentsLister = rearInlineContentsLister
943 abandonContentsLister = rearAbandonContentsLister
944
945 /* the message for taking things from me that aren't behind me */
946 takeFromNotInMessage = &takeFromNotBehindMsg
947
948 /*
949 * my message indicating that another object x cannot be put into me
950 * because I'm already in x
951 */
952 circularlyInMessage = &circularlyBehindMsg
953
954 /* message phrase for objects put under me */
955 putDestMessage = &putDestBehind
956
957 /* message when we're too full for another object */
958 tooFullMsg = &rearTooFullMsg
959
960 /* message when object is too large to fit behind me */
961 tooLargeForContainerMsg = &tooLargeForRearMsg
962
963 /* customize the verification messages */
964 cannotPutInSelfMsg = &cannotPutBehindSelfMsg
965 alreadyPutInMsg = &alreadyPutBehindMsg
966
967 /* our implied containment verb is PUT BEHIND */
968 tryMovingObjInto(obj) { return tryImplicitAction(PutBehind, obj, self); }
969
970 /* -------------------------------------------------------------------- */
971 /*
972 * Handle the PUT UNDER command
973 */
974 iobjFor(PutBehind)
975 {
976 verify() { verifyPutInInterior(); }
977 check()
978 {
979 /* only allow it if PUT BEHIND commands are allowed */
980 if (!allowPutBehind)
981 {
982 reportFailure(&cannotPutBehindMsg);
983 exit;
984 }
985 }
986 action()
987 {
988 /* move the direct object behind me */
989 gDobj.moveInto(self);
990
991 /* issue our default acknowledgment */
992 defaultReport(&okayPutBehindMsg);
993 }
994 }
995
996 /*
997 * Looking "behind" a surface simply shows the surface's contents.
998 */
999 dobjFor(LookBehind)
1000 {
1001 verify() { }
1002 action() { examineInterior(); }
1003 }
1004 ;
1005
1006 /*
1007 * A special kind of RearContainer that only accepts specific contents.
1008 */
1009 class RestrictedRearContainer: RestrictedHolder, RearContainer
1010 /*
1011 * A message that explains why the direct object can't be put behind
1012 * this object. In most cases, the rather generic default message
1013 * should be overridden to provide a specific reason that the dobj
1014 * can't be put behind me. The rejected object is provided as a
1015 * parameter in case the message needs to vary by object, but we
1016 * ignore this and just use a single blanket failure message by
1017 * default.
1018 */
1019 cannotPutBehindMsg(obj) { return &cannotPutBehindRestrictedMsg; }
1020
1021 /* override PutBehind to enforce our contents restriction */
1022 iobjFor(PutBehind) { check() { checkPutDobj(&cannotPutBehindMsg); } }
1023 ;
1024
1025 /*
1026 * A "rear surface" is essentially the same as a "rear container," but
1027 * models the contents as being attached to the back of the object rather
1028 * than merely sitting behind it.
1029 *
1030 * The only practical difference between the "container" and the
1031 * "surface" is that moving a surface moves its contents along with it,
1032 * whereas moving a container abandons the contents, leaving them behind
1033 * where the container used to be.
1034 */
1035 class RearSurface: RearContainer
1036 /*
1037 * We're a surface, not a space, so our contents stay attached when
1038 * we move.
1039 */
1040 abandonLocation = nil
1041 ;
1042
1043 /*
1044 * A restricted-contents RearSurface
1045 */
1046 class RestrictedRearSurface: RestrictedHolder, RearSurface
1047 /* explain the problem */
1048 cannotPutBehindMsg(obj) { return &cannotPutBehindRestrictedMsg; }
1049
1050 /* override PutBehind to enforce our contents restriction */
1051 iobjFor(PutBehind) { check() { checkPutDobj(&cannotPutBehindMsg); } }
1052 ;
1053
1054 /* ------------------------------------------------------------------------ */
1055 /*
1056 * A "stretchy container." This is a simple container subclass whose
1057 * external bulk changes according to the bulks of the contents.
1058 */
1059 class StretchyContainer: Container
1060 /*
1061 * Our minimum bulk. This is the minimum bulk we'll report, even
1062 * when the aggregate bulks of our contents are below this limit.
1063 */
1064 minBulk = 0
1065
1066 /* get my total external bulk */
1067 getBulk()
1068 {
1069 local tot;
1070
1071 /* start with my own intrinsic bulk */
1072 tot = bulk;
1073
1074 /* add the bulk contribution from my contents */
1075 tot += getBulkForContents();
1076
1077 /* return the total, but never less than the minimum */
1078 return tot >= minBulk ? tot : minBulk;
1079 }
1080
1081 /*
1082 * Calculate the contribution to my external bulk of my contents.
1083 * The default for a stretchy container is to conform exactly to the
1084 * contents, as though the container weren't present at all, hence
1085 * we simply sum the bulks of our contents. Subclasses can override
1086 * this to define other aggregate bulk effects as needed.
1087 */
1088 getBulkForContents()
1089 {
1090 local tot;
1091
1092 /* sum the bulks of the items in our contents */
1093 tot = 0;
1094 foreach (local cur in contents)
1095 tot += cur.getBulk();
1096
1097 /* return the total */
1098 return tot;
1099 }
1100
1101 /*
1102 * Check what happens when a new object is inserted into my
1103 * contents. This is called with the new object already tentatively
1104 * added to my contents, so we can examine our current status to see
1105 * if everything works.
1106 *
1107 * Since we can change our own size when a new item is added to our
1108 * contents, we'll trigger a full bulk change check.
1109 */
1110 checkBulkInserted(insertedObj)
1111 {
1112 /*
1113 * inherit the normal handling to ensure that the new object
1114 * fits within this container
1115 */
1116 inherited(insertedObj);
1117
1118 /*
1119 * since we can change our own shape when items are added to our
1120 * contents, trigger a full bulk check on myself
1121 */
1122 checkBulkChange();
1123 }
1124
1125 /*
1126 * Check a bulk change of one of my direct contents. Since my own
1127 * bulk changes whenever the bulk of one of my contents changes, we
1128 * must propagate the bulk change of our contents as a change in our
1129 * own bulk.
1130 */
1131 checkBulkChangeWithin(changingObj)
1132 {
1133 /*
1134 * Do any inherited work, in case we have a limit on our own
1135 * internal bulk.
1136 */
1137 inherited(changingObj);
1138
1139 /*
1140 * This might cause a change in my own bulk, since my bulk
1141 * depends on the bulks of my contents. When this is called,
1142 * obj is already set to indicate its new bulk; since we
1143 * calculate our own bulk by looking at our contents' bulks,
1144 * this means that our own getBulk will now report the latest
1145 * value including obj's new bulk.
1146 */
1147 checkBulkChange();
1148 }
1149 ;
1150
1151
1152 /* ------------------------------------------------------------------------ */
1153 /*
1154 * "Bag of Holding." This is a mix-in that actively moves items from the
1155 * holding actor's direct inventory into itself when the actor's hands
1156 * are too full.
1157 *
1158 * The bag of holding offers a solution to the conflict between "realism"
1159 * and playability. On the one hand, in real life, you can only hold so
1160 * many items at once, so at first glance it seems a simulation ought to
1161 * have such a limit in order to be more realistic. On the other hand,
1162 * most players justifiably hate having to deal with a carrying limit,
1163 * because it forces the player to spend a lot of time doing tedious
1164 * inventory management.
1165 *
1166 * The Bag of Holding is a compromise solution. The concept is borrowed
1167 * from live role-playing games, where it's usually a magical item that
1168 * can hold objects of unlimited size and weight, thereby allowing
1169 * characters to transport impossibly large objects. In text IF, a bag
1170 * of holding isn't usually magical - it's usually just something like a
1171 * large backpack, or a trenchcoat with lots of pockets. And it usually
1172 * isn't meant as a solution to an obvious puzzle; rather, it's meant to
1173 * invisibly prevent inventory management from becoming a puzzle in the
1174 * first place, by shuffling objects out of the PC's hands automatically
1175 * to free up space as needed.
1176 *
1177 * This Bag of Holding implementation works by automatically moving
1178 * objects from an actor's hands into the bag object, whenever the actor
1179 * needs space to pick up a new item. Whenever an action has a
1180 * "roomToHoldObj" precondition, the precondition will automatically look
1181 * for a BagOfHolding object within the actor's inventory, and then move
1182 * as many items as necessary from the actor's hands to the bag.
1183 */
1184 class BagOfHolding: object
1185 /*
1186 * Get my bags of holding. Since we are a bag of holding, we'll add
1187 * ourselves to the vector, then we'll inherit the normal handling
1188 * to pick up our contents.
1189 */
1190 getBagsOfHolding(vec)
1191 {
1192 /* we're a bag of holding */
1193 vec.append(self);
1194
1195 /* inherit the normal handling */
1196 inherited(vec);
1197 }
1198
1199 /*
1200 * Get my "affinity" for the given object. This is an indication of
1201 * how strongly this bag wants to contain the object. The affinity
1202 * is a number in arbitrary units; higher numbers indicate stronger
1203 * affinities. An affinity of zero means that the bag does not want
1204 * to contain the object at all.
1205 *
1206 * The purpose of the affinity is to support specialized holders
1207 * that are designed to hold only specific types of objects, and
1208 * allow these specialized holders to implicitly gather their
1209 * specific objects. For example, a key ring might only hold keys,
1210 * so it would have a high affinity for keys and a zero affinity for
1211 * everything else. A lunchbox might have a higher affinity for
1212 * things like sandwiches than for anything else, but might be
1213 * willing to serve as a general container for other small items as
1214 * well.
1215 *
1216 * The units of affinity are arbitrary, but the library uses the
1217 * following values for its own classes:
1218 *
1219 * 0 - no affinity at all; the bag cannot hold the object
1220 *
1221 * 50 - willing to hold the object, but not of the preferred type
1222 *
1223 * 100 - default affinity; willing and able to hold the object, but
1224 * just as willing to hold most other things
1225 *
1226 * 200 - special affinity; this object is of a type that we
1227 * especially want to hold
1228 *
1229 * We intentionally space these loosely so that games can use
1230 * intermediate levels if desired.
1231 *
1232 * When we are looking for bags of holding to consolidate an actor's
1233 * directly-held inventory, note that we always move the object with
1234 * the highest bag-to-object affinity out of all of the objects
1235 * under consideration. So, if you want to give a particular kind
1236 * of bag priority so that the library uses that bag before any
1237 * other bag, make this routine return a higher affinity for the
1238 * bag's objects than any other bags do.
1239 *
1240 * By default, we'll return the default affinity of 100.
1241 * Specialized bags that don't hold all types of objects must
1242 * override this to return zero for objects they can't hold.
1243 */
1244 affinityFor(obj)
1245 {
1246 /*
1247 * my affinity for myself is zero, for obvious reasons; for
1248 * everything else, use the default affinity
1249 */
1250 return (obj == self ? 0 : 100);
1251 }
1252 ;
1253
1254
1255 /* ------------------------------------------------------------------------ */
1256 /*
1257 * Keyring - a place to stash keys
1258 *
1259 * Keyrings have some special properties:
1260 *
1261 * - A keyring is a bag of holding with special affinity for keys.
1262 *
1263 * - A keyring can only contain keys.
1264 *
1265 * - Keys are considered to be on the outside of the ring, so a key can
1266 * be used even if attached to the keyring (in other words, if the ring
1267 * itself is held, a key attached to the ring is also considered held).
1268 *
1269 * - If an actor in possession of a keyring executes an "unlock" command
1270 * without specifying what key to use, we will automatically test each
1271 * key on the ring to find the one that works.
1272 *
1273 * - When an actor takes one of our keys, and the actor is in possession
1274 * of this keyring, we'll automatically attach the key to the keyring
1275 * immediately.
1276 */
1277 class Keyring: BagOfHolding, Thing
1278 /* lister for showing our contents in-line as part of a list entry */
1279 inlineContentsLister = keyringInlineContentsLister
1280
1281 /* lister for showing our contents as part of "examine" */
1282 descContentsLister = keyringExamineContentsLister
1283
1284 /*
1285 * Determine if a key fits our keyring. By default, we will accept
1286 * any object of class Key. However, subclasses might want to
1287 * override this to associate particular keys with particular
1288 * keyrings rather than having a single generic keyring. To allow
1289 * only particular keys onto this keyring, override this routine to
1290 * return true only for the desired keys.
1291 */
1292 isMyKey(key)
1293 {
1294 /* accept any object of class Key */
1295 return key.ofKind(Key);
1296 }
1297
1298 /* we have high affinity for our keys */
1299 affinityFor(obj)
1300 {
1301 /*
1302 * if the object is one of my keys, we have high affinity;
1303 * otherwise we don't accept it at all
1304 */
1305 if (isMyKey(obj))
1306 return 200;
1307 else
1308 return 0;
1309 }
1310
1311 /* implicitly put a key on the keyring */
1312 tryPuttingObjInBag(target)
1313 {
1314 /* we're a container, so use "put in" to get the object */
1315 return tryImplicitActionMsg(&announceMoveToBag, PutOn, target, self);
1316 }
1317
1318 /* on taking the keyring, attach any loose keys */
1319 dobjFor(Take)
1320 {
1321 action()
1322 {
1323 /* do the normal work */
1324 inherited();
1325
1326 /* get the list of loose keys */
1327 local lst = getLooseKeys(gActor);
1328
1329 /* consider only the subset that are my valid keys */
1330 lst = lst.subset({x: isMyKey(x)});
1331
1332 /* if there are any, move them onto the keyring */
1333 if (lst.length() != 0)
1334 {
1335 /* put each loose key on the keyring */
1336 foreach (local cur in lst)
1337 cur.moveInto(self);
1338
1339 /* announce what happened */
1340 extraReport(&movedKeysToKeyringMsg, self, lst);
1341 }
1342 }
1343 }
1344
1345 /*
1346 * Get the loose keys in the given actor's possession. On taking the
1347 * keyring, we'll attach these loose keys to the keyring
1348 * automatically. By default, we return any keys the actor is
1349 * directly holding.
1350 */
1351 getLooseKeys(actor) { return actor.contents; }
1352
1353 /* allow putting a key on the keyring */
1354 iobjFor(PutOn)
1355 {
1356 /* we can only put keys on keyrings */
1357 verify()
1358 {
1359 /* we'll only allow our own keys to be attached */
1360 if (gDobj == nil)
1361 {
1362 /*
1363 * we don't know the actual direct object yet, but we
1364 * can at least check to see if any of the possible
1365 * dobj's is my kind of key
1366 */
1367 if (gTentativeDobj.indexWhich({x: isMyKey(x.obj_)}) == nil)
1368 illogical(&objNotForKeyringMsg);
1369 }
1370 else if (!isMyKey(gDobj))
1371 {
1372 /* the dobj isn't a valid key for this keyring */
1373 illogical(&objNotForKeyringMsg);
1374 }
1375 }
1376
1377 /* put a key on me */
1378 action()
1379 {
1380 /* move the key into me */
1381 gDobj.moveInto(self);
1382
1383 /* show the default "put on" response */
1384 defaultReport(&okayPutOnMsg);
1385 }
1386 }
1387
1388 /* treat "attach x to keyring" as "put x on keyring" */
1389 iobjFor(AttachTo) remapTo(PutOn, DirectObject, self)
1390
1391 /* treat "detach x from keyring" as "take x from keyring" */
1392 iobjFor(DetachFrom) remapTo(TakeFrom, DirectObject, self)
1393
1394 /* receive notification before an action */
1395 beforeAction()
1396 {
1397 /*
1398 * Note whether or not we want to consider moving the direct
1399 * object to the keyring after a "take" command. We will
1400 * consider doing so only if the direct object isn't already on
1401 * the keyring - if it is, we don't want to move it back right
1402 * after removing it, obviously.
1403 *
1404 * Skip the implicit keyring attachment if the current command
1405 * is implicit, because they must be doing something that
1406 * requires holding the object, in which case taking it is
1407 * incidental. It could be actively annoying to attach the
1408 * object to the keyring in such cases - for example, if the
1409 * command is "put key on keyring," attaching it as part of the
1410 * implicit action would render the explicit command redundant
1411 * and cause it to fail.
1412 */
1413 moveAfterTake = (!gAction.isImplicit
1414 && gDobj != nil
1415 && !gDobj.isDirectlyIn(self));
1416 }
1417
1418 /* flag: consider moving to keyring after this "take" action */
1419 moveAfterTake = nil
1420
1421 /* receive notification after an action */
1422 afterAction()
1423 {
1424 /*
1425 * If the command was "take", and the direct object was a key,
1426 * and the actor involved is holding the keyring and can touch
1427 * it, and the command succeeded in moving the key to the
1428 * actor's direct inventory, then move the key onto the keyring.
1429 * Only consider this if we decided to during the "before"
1430 * notification.
1431 */
1432 if (moveAfterTake
1433 && gActionIs(Take)
1434 && isMyKey(gDobj)
1435 && isIn(gActor)
1436 && gActor.canTouch(self)
1437 && gDobj.isDirectlyIn(gActor))
1438 {
1439 /* move the key to me */
1440 gDobj.moveInto(self);
1441
1442 /*
1443 * Mention what we did. If the only report for this action
1444 * so far is the default 'take' response, then use the
1445 * combined taken-and-attached message. Otherwise, append
1446 * our 'attached' message, which is suitable to use after
1447 * other messages.
1448 */
1449 if (gTranscript.currentActionHasReport(
1450 {x: (x.ofKind(CommandReportMessage)
1451 && x.messageProp_ != &okayTakeMsg)}))
1452 {
1453 /*
1454 * we have a non-default message already, so add our
1455 * message indicating that we added the key to the
1456 * keyring
1457 */
1458 reportAfter(&movedKeyToKeyringMsg, self);
1459 }
1460 else
1461 {
1462 /* use the combination taken-and-attached message */
1463 mainReport(&takenAndMovedToKeyringMsg, self);
1464 }
1465 }
1466 }
1467
1468 /* find among our keys a key that works the direct object */
1469 findWorkingKey(lock)
1470 {
1471 /* try each key on the keyring */
1472 foreach (local key in contents)
1473 {
1474 /*
1475 * if this is the key that unlocks the lock, replace the
1476 * command with 'unlock lock with key'
1477 */
1478 if (lock.keyFitsLock(key))
1479 {
1480 /* note that we tried keys and found the right one */
1481 extraReport(&foundKeyOnKeyringMsg, self, key);
1482
1483 /* return the key */
1484 return key;
1485 }
1486 }
1487
1488 /* we didn't find the right key - indicate failure */
1489 reportFailure(&foundNoKeyOnKeyringMsg, self);
1490 return nil;
1491 }
1492
1493 /*
1494 * Append my directly-held contents to a vector when I'm directly
1495 * held. We consider all of the keys on the keyring to be
1496 * effectively at the same containment level as the keyring, so if
1497 * the keyring is held, so are its attached keys.
1498 */
1499 appendHeldContents(vec)
1500 {
1501 /* append all of our contents, since they're held when we are */
1502 vec.appendUnique(contents);
1503 }
1504
1505 /*
1506 * Announce myself as a default object for an action.
1507 *
1508 * Do not announce a keyring as a default for "lock with" or "unlock
1509 * with". Although we can use a keyring as the indirect object of a
1510 * lock/unlock command, we don't actually do the unlocking with the
1511 * keyring; so, when we're chosen as the default, suppress the
1512 * announcement, since it would imply that we're being used to lock
1513 * or unlock something.
1514 */
1515 announceDefaultObject(whichObj, action, resolvedAllObjects)
1516 {
1517 /* if it's not a lock-with or unlock-with, use the default message */
1518 if (!action.ofKind(LockWithAction)
1519 && !action.ofKind(UnlockWithAction))
1520 {
1521 /* for anything but our special cases, use the default handling */
1522 return inherited(whichObj, action, resolvedAllObjects);
1523 }
1524
1525 /* use no announcement */
1526 return '';
1527 }
1528
1529 /*
1530 * Allow locking or unlocking an object with a keyring. This will
1531 * automatically try each key on the keyring to see if it fits the
1532 * lock.
1533 */
1534 iobjFor(LockWith)
1535 {
1536 verify()
1537 {
1538 /* if we don't have any keys, we're not locking anything */
1539 if (contents.length() == 0)
1540 illogical(&cannotLockWithMsg);
1541
1542 /*
1543 * if we know the direct object, and we don't have any keys
1544 * that are plausible for the direct object, we're an
1545 * unlikely match
1546 */
1547 if (gDobj != nil)
1548 {
1549 local foundPlausibleKey;
1550
1551 /*
1552 * try each of my keys to see if it's plausible for the
1553 * direct object
1554 */
1555 foundPlausibleKey = nil;
1556 foreach (local cur in contents)
1557 {
1558 /*
1559 * if this is a plausible key, note that we have at
1560 * least one plausible key
1561 */
1562 if (gDobj.keyIsPlausible(cur))
1563 {
1564 /* note that we found a plausible key */
1565 foundPlausibleKey = true;
1566
1567 /* no need to look any further - one is good enough */
1568 break;
1569 }
1570 }
1571
1572 /*
1573 * If we didn't find a plausible key, we're an unlikely
1574 * match.
1575 *
1576 * If we did find a plausible key, increase the
1577 * likelihood that this is the indirect object so that
1578 * it's greater than the likelihood for any random key
1579 * that's plausible for the lock (which has the default
1580 * likelihood of 100), but less than the likelihood of
1581 * the known good key (which is 150). This will cause a
1582 * keyring to be taken as a default over any ordinary
1583 * key, but will cause the correct key to override the
1584 * keyring as the default if the correct key is known to
1585 * the player already.
1586 */
1587 if (foundPlausibleKey)
1588 logicalRank(140, 'keyring with plausible key');
1589 else
1590 logicalRank(50, 'no plausible key');
1591 }
1592 }
1593
1594 action()
1595 {
1596 local key;
1597
1598 /*
1599 * Try finding a working key. If we find one, replace the
1600 * command with 'lock <lock> with <key>, so that we have the
1601 * full effect of the 'lock with' command using the key
1602 * itself.
1603 */
1604 if ((key = findWorkingKey(gDobj)) != nil)
1605 replaceAction(LockWith, gDobj, key);
1606 }
1607 }
1608
1609 iobjFor(UnlockWith)
1610 {
1611 /* verify the same as for LockWith */
1612 verify()
1613 {
1614 /* if we don't have any keys, we're not unlocking anything */
1615 if (contents.length() == 0)
1616 illogical(&cannotUnlockWithMsg);
1617 else
1618 verifyIobjLockWith();
1619 }
1620
1621 action()
1622 {
1623 local key;
1624
1625 /*
1626 * if we can find a working key, run an 'unlock with' action
1627 * using the key
1628 */
1629 if ((key = findWorkingKey(gDobj)) != nil)
1630 replaceAction(UnlockWith, gDobj, key);
1631 }
1632 }
1633 ;
1634
1635 /*
1636 * Key - this is an object that can be used to unlock things, and which
1637 * can be stored on a keyring. The key that unlocks a lock is
1638 * identified with a property on the lock, not on the key.
1639 */
1640 class Key: Thing
1641 /*
1642 * A key on a keyring that is being held by an actor is considered
1643 * to be held by the actor, since the key does not have to be
1644 * removed from the keyring in order to be manipulated as though it
1645 * were directly held.
1646 */
1647 isHeldBy(actor)
1648 {
1649 /*
1650 * if I'm on a keyring, I'm being held if the keyring is being
1651 * held; otherwise, use the default definition
1652 */
1653 if (location != nil && location.ofKind(Keyring))
1654 return location.isHeldBy(actor);
1655 else
1656 return inherited(actor);
1657 }
1658
1659 /*
1660 * Try making the current command's actor hold me. If we're on a
1661 * keyring, we'll simply try to make the keyring itself held, rather
1662 * than taking the key off the keyring; otherwise, we'll inherit the
1663 * default behavior to make ourselves held.
1664 */
1665 tryHolding()
1666 {
1667 if (location != nil && location.ofKind(Keyring))
1668 return location.tryHolding();
1669 else
1670 return inherited();
1671 }
1672
1673 /* -------------------------------------------------------------------- */
1674 /*
1675 * Action processing
1676 */
1677
1678 /* treat "detach key" as "take key" if it's on a keyring */
1679 dobjFor(Detach)
1680 {
1681 verify()
1682 {
1683 /* if I'm not on a keyring, there's nothing to detach from */
1684 if (location == nil || !location.ofKind(Keyring))
1685 illogical(&keyNotDetachableMsg);
1686 }
1687 remap()
1688 {
1689 /* if I'm on a keyring, remap to "take self" */
1690 if (location != nil && location.ofKind(Keyring))
1691 return [TakeAction, self];
1692 else
1693 return inherited();
1694 }
1695 }
1696
1697 /* "lock with" */
1698 iobjFor(LockWith)
1699 {
1700 verify()
1701 {
1702 /*
1703 * if we know the direct object is a LockableWithKey, we can
1704 * perform some additional checks on the likelihood of this
1705 * key being the intended key for the lock
1706 */
1707 if (gDobj != nil
1708 && gDobj.ofKind(LockableWithKey))
1709 {
1710 /*
1711 * If the player should know that we're the key for the
1712 * lock, boost our likelihood so that we'll be picked
1713 * out automatically from an ambiguous set of keys.
1714 */
1715 if (gDobj.isKeyKnown(self))
1716 logicalRank(150, 'known key');
1717
1718 /*
1719 * if this isn't a plausible key for the lockable, it's
1720 * unlikely that this is a match
1721 */
1722 if (!gDobj.keyIsPlausible(self))
1723 illogical(keyNotPlausibleMsg);
1724 }
1725 }
1726 }
1727
1728 /*
1729 * the message to use when the key is obviously not plausible for a
1730 * given lock
1731 */
1732 keyNotPlausibleMsg = &keyDoesNotFitLockMsg
1733
1734 /* "unlock with" */
1735 iobjFor(UnlockWith)
1736 {
1737 verify()
1738 {
1739 /* use the same key selection we use for "lock with" */
1740 verifyIobjLockWith();
1741 }
1742 }
1743 ;
1744
1745 /* ------------------------------------------------------------------------ */
1746 /*
1747 * A Dispenser is a container for a special type of item, such as a book
1748 * of matches or a box of candy.
1749 */
1750 class Dispenser: Container
1751 /*
1752 * Can we return one of our items to the dispenser once the item is
1753 * dispensed? Books of matches wouldn't generally allow this, since
1754 * a match must be torn out to be removed, but simple box dispensers
1755 * probably would. By default, we won't allow returning an item
1756 * once dispensed.
1757 */
1758 canReturnItem = nil
1759
1760 /*
1761 * Is the item one of the types of items we dispense? Normally, we
1762 * dispense identical items, so our default implementation simply
1763 * determines if the item is an instance of our dispensable class.
1764 * If the dispenser can hand out items of multiple, unrelated
1765 * classes, this can be overridden to use a different means of
1766 * identifying the dispensed items.
1767 */
1768 isMyItem(obj) { return obj.ofKind(myItemClass); }
1769
1770 /*
1771 * The class of items we dispense. This is used by the default
1772 * implementation of isMyItem(), so subclasses that inherit that
1773 * implementation should provide the appropriate base class here.
1774 */
1775 myItemClass = Dispensable
1776
1777 /* "put in" indirect object handler */
1778 iobjFor(PutIn)
1779 {
1780 verify()
1781 {
1782 /* if we know the direct object, consider it further */
1783 if (gDobj != nil)
1784 {
1785 /* if we don't allow returning our items, don't allow it */
1786 if (!canReturnItem && isMyItem(gDobj))
1787 illogical(&cannotReturnToDispenserMsg);
1788
1789 /* if it's not my dispensed item, it can't go in here */
1790 if (!isMyItem(gDobj))
1791 illogical(&cannotPutInDispenserMsg);
1792 }
1793
1794 /* inherit default handling */
1795 inherited();
1796 }
1797 }
1798 ;
1799
1800 /*
1801 * A Dispensable is an item that comes from a Dispenser. This is in
1802 * most respects an ordinary item; the only special thing about it is
1803 * that if we're still in our dispenser, we're an unlikely match for any
1804 * command except "take" and the like.
1805 */
1806 class Dispensable: Thing
1807 /*
1808 * My dispenser. This is usually my initial location, so by default
1809 * we'll pre-initialize this to our location.
1810 */
1811 myDispenser = nil
1812
1813 /* pre-initialization */
1814 initializeThing()
1815 {
1816 /* inherit the default initialization */
1817 inherited();
1818
1819 /*
1820 * We're usually in our dispenser initially, so assume that our
1821 * dispenser is simply our initial location. If myDispenser is
1822 * overridden in a subclass, don't overwrite the inherited
1823 * value.
1824 */
1825 if (propType(&myDispenser) == TypeNil)
1826 myDispenser = location;
1827 }
1828
1829 dobjFor(All)
1830 {
1831 verify()
1832 {
1833 /*
1834 * If we're in our dispenser, and the command isn't "take"
1835 * or "take from", reduce our disambiguation likelihood -
1836 * it's more likely that the actor is referring to another
1837 * equivalent item that they've already removed from the
1838 * dispenser.
1839 */
1840 if (isIn(myDispenser)
1841 && !gActionIs(Take) && !gActionIs(TakeFrom))
1842 {
1843 /* we're in our dispenser - reduce the likelihood */
1844 logicalRank(60, 'in dispenser');
1845 }
1846 }
1847 }
1848 ;
1849
1850
1851 /* ------------------------------------------------------------------------ */
1852 /*
1853 * A Matchbook is a special dispenser for matches.
1854 */
1855 class Matchbook: Collective, Openable, Dispenser
1856 /* we cannot return a match to a matchbook */
1857 canReturnItem = nil
1858
1859 /*
1860 * we dispense matches (subclasses can override this if they want to
1861 * dispense a specialized match subclass)
1862 */
1863 myItemClass = Matchstick
1864
1865 /*
1866 * Act as a collective for any items within me. This will have no
1867 * effect unless we also have a plural name that matches that of the
1868 * contained items.
1869 *
1870 * It is usually desirable for a matchbook to act as a collective
1871 * for the contained items, so that a command like "take matches"
1872 * will be taken to apply to the matchbook rather than the
1873 * individual matches.
1874 */
1875 isCollectiveFor(obj) { return obj.isIn(self); }
1876
1877 /*
1878 * Append my directly-held contents to a vector when I'm directly
1879 * held. When the matchbook is open, append our matches, because we
1880 * consider the matches to be effectively attached to the matchbook
1881 * (rather than contained within it).
1882 */
1883 appendHeldContents(vec)
1884 {
1885 /* if we're open, append our contents */
1886 if (isOpen)
1887 vec.appendUnique(contents);
1888 }
1889 ;
1890
1891 /*
1892 * A FireSource is an object that can set another object on fire. This
1893 * is a mix-in class that can be used with other classes.
1894 */
1895 class FireSource: object
1896 /*
1897 * We can use a fire source to light another object, provided the
1898 * fire source is itself burning. We don't provide any action
1899 * handling - we leave that to the direct object.
1900 */
1901 iobjFor(BurnWith)
1902 {
1903 preCond = [objHeld, objBurning]
1904 verify()
1905 {
1906 /* don't allow using me to light myself */
1907 if (gDobj == self)
1908 illogicalNow(&cannotBurnDobjWithMsg);
1909
1910 /*
1911 * If we're already lit, make this an especially good choice
1912 * for lighting other objects - this will ensure that we
1913 * choose this over a match that isn't already lit, which is
1914 * what you'd normally want to do to avoid wasting a match.
1915 *
1916 * Note that our ranking is specifically coordinated with
1917 * that used by Matchstick. We'll use a lit match over any
1918 * normal FireSource (rank 160); we'll use a lit FireSource
1919 * (rank 150) over an unlit match (rank 140).
1920 *
1921 * If we're not lit, make the action non-obvious so that
1922 * we're not taken as a default to light another object on
1923 * fire. We *could* light something once we're lit, but that
1924 * presumes there's a way to light me in the first place,
1925 * which might require yet another object (a match, for
1926 * example) - so ignore me as a default if we're not already
1927 * lit, and go directly to some other object. This should be
1928 * overridden for self-lighting objects such as matches.
1929 */
1930 if (isLit)
1931 logicalRank(150, 'fire source');
1932 else
1933 nonObvious;
1934 }
1935 }
1936 ;
1937
1938 /*
1939 * A Matchstick is a self-igniting match from a matchbook. (We use this
1940 * lengthy name rather than simply "Match" because the latter is too
1941 * generic, and could be taken by a casual reader for an object
1942 * representing a successful search result or the like.)
1943 */
1944 class Matchstick: FireSource, LightSource
1945 /* matches have fairly feeble light */
1946 brightnessOn = 2
1947
1948 /* not lit initially */
1949 isLit = nil
1950
1951 /* amount of time we burn, in turns */
1952 burnLength = 2
1953
1954 /* default long description describes burning status */
1955 desc()
1956 {
1957 if (isLit)
1958 gLibMessages.litMatchDesc(self);
1959 else
1960 gLibMessages.unlitMatchDesc(self);
1961 }
1962
1963 /* get our state */
1964 getState = (isLit ? matchStateLit : matchStateUnlit)
1965
1966 /* get a list of all states */
1967 allStates = [matchStateLit, matchStateUnlit]
1968
1969 /* "burn" action */
1970 dobjFor(Burn)
1971 {
1972 preCond = [objHeld]
1973 verify()
1974 {
1975 /* can't light a match that's already burning */
1976 if (isLit)
1977 illogicalAlready(&alreadyBurningMsg);
1978 }
1979 action()
1980 {
1981 local t;
1982
1983 /* describe it */
1984 defaultReport(&okayBurnMatchMsg);
1985
1986 /* make myself lit */
1987 makeLit(true);
1988
1989 /* get our default burn length */
1990 t = burnLength;
1991
1992 /*
1993 * if this is an implicit command, reduce the burn length by
1994 * one turn - this ensures that the player can't
1995 * artificially extend the match's useful life by doing
1996 * something that implicitly lights the match
1997 */
1998 if (gAction.isImplicit)
1999 --t;
2000
2001 /* start our burn-out timer going */
2002 new SenseFuse(self, &matchBurnedOut, t, self, sight);
2003 }
2004 }
2005
2006 iobjFor(BurnWith)
2007 {
2008 verify()
2009 {
2010 /*
2011 * Whether or not a match is burning, it's an especially
2012 * good choice to light something else on fire. Make it
2013 * even more likely when it's burning already.
2014 *
2015 * Note that this is specifically coordinated with the base
2016 * FireSource ranking. We'll pick a lit match (160) over an
2017 * ordinary lit FireSource (150), but we'll pick a lit
2018 * FireSource (150) over an unlit match (140). This will
2019 * avoid consuming a match that's not already lit when
2020 * another fire source is already available.
2021 */
2022 logicalRank(isLit ? 160 : 140, 'fire source');
2023 }
2024 }
2025
2026 /* "extinguish" */
2027 dobjFor(Extinguish)
2028 {
2029 verify()
2030 {
2031 /* can't extinguish a match that isn't burning */
2032 if (!isLit)
2033 illogicalAlready(&matchNotLitMsg);
2034 }
2035 action()
2036 {
2037 /* describe the match going out */
2038 defaultReport(&okayExtinguishMatchMsg);
2039
2040 /* no longer lit */
2041 makeLit(nil);
2042
2043 /* remove the match from the game */
2044 moveInto(nil);
2045 }
2046 }
2047
2048 /* fuse handler for burning out */
2049 matchBurnedOut()
2050 {
2051 /*
2052 * if I'm not still burning, I must have been extinguished
2053 * explicitly already, so there's nothing to do
2054 */
2055 if (!isLit)
2056 return;
2057
2058 /* make sure we separate any output from other commands */
2059 "<.p>";
2060
2061 /* report that we're done burning */
2062 gLibMessages.matchBurnedOut(self);
2063
2064 /*
2065 * remove myself from the game (for simplicity, a match simply
2066 * disappears when it's done burning)
2067 */
2068 moveInto(nil);
2069 }
2070
2071 /* matches usually come in bunches of equivalents */
2072 isEquivalent = true
2073 ;
2074
2075 /*
2076 * A light source that produces light using a fuel supply. This kind of
2077 * light source uses a daemon to consume fuel whenever it's lit.
2078 */
2079 class FueledLightSource: LightSource
2080 /* provide a bright light by default */
2081 brightnessOn = 3
2082
2083 /* not lit initially */
2084 isLit = nil
2085
2086 /*
2087 * Our fuel source object. If desired, this can be set to a
2088 * separate object to model the fuel supply separately from the
2089 * light source itself; for example, you could set this to point to
2090 * a battery, or to a vial of oil. By default, for simplicity, the
2091 * fuel supply and light source are the same object.
2092 *
2093 * The fuel supply object must expose two methods: getFuelLevel()
2094 * and consumeFuel().
2095 */
2096 fuelSource = (self)
2097
2098 /*
2099 * Get my fuel level, and consume fuel. We use these methods only
2100 * when we're our own fuelSource (which we are by default). When
2101 * we're not our own fuel source, the fuel source object must
2102 * provide these methods instead of us.
2103 *
2104 * Our fuel level is the number of turns that we can continue to
2105 * burn. Each turn we're lit, we'll reduce the fuel level by one.
2106 * We'll automatically extinguish ourself when the fuel level
2107 * reaches zero.
2108 *
2109 * If the light source can burn forever, simply return nil as the
2110 * fuel level.
2111 */
2112 getFuelLevel() { return fuelLevel; }
2113 consumeFuel(amount) { fuelLevel -= amount; }
2114
2115 /* our fuel level - we use this when we're our own fuel source */
2116 fuelLevel = 20
2117
2118 /* light or extinguish */
2119 makeLit(lit)
2120 {
2121 /* if the current fuel level is zero, we can't be lit */
2122 if (lit && fuelSource.getFuelLevel() == 0)
2123 return;
2124
2125 /* inherit the default handling */
2126 inherited(lit);
2127
2128 /* if we're lit, activate our daemon; otherwise, stop our daemon */
2129 if (isLit)
2130 {
2131 /* start our burn daemon going */
2132 burnDaemonObj =
2133 new SenseDaemon(self, &burnDaemon, 1, self, sight);
2134 }
2135 else
2136 {
2137 /* stop our daemon */
2138 eventManager.removeEvent(burnDaemonObj);
2139
2140 /* forget out daemon */
2141 burnDaemonObj = nil;
2142 }
2143 }
2144
2145 /* burn daemon - this is called on each turn while we're burning */
2146 burnDaemon()
2147 {
2148 local level = fuelSource.getFuelLevel();
2149
2150 /* if we use fuel, consume one increment of fuel for this turn */
2151 if (level != nil)
2152 {
2153 /*
2154 * If our fuel level has reached zero, stop burning. Note
2155 * that the daemon is called on the first turn after we
2156 * start burning, so we must go through a turn with the fuel
2157 * level at zero before we stop burning.
2158 */
2159 if (level == 0)
2160 {
2161 /* make sure we separate any output from other commands */
2162 "<.p>";
2163
2164 /* mention that the candle goes out */
2165 sayBurnedOut();
2166
2167 /*
2168 * Extinguish the candle. Note that we do this *after*
2169 * we've already displayed the message about the candle
2170 * burning out, because that message is displayed in our
2171 * own sight context. If we're the only light source
2172 * present, then we're invisible once we're not providing
2173 * light, so our message about burning out would be
2174 * suppressed if we displayed it after cutting off our
2175 * own light. To make sure we can see the message, wait
2176 * until after the message to cut off our light.
2177 */
2178 makeLit(nil);
2179 }
2180 else
2181 {
2182 /* reduce our fuel level by one */
2183 fuelSource.consumeFuel(1);
2184 }
2185 }
2186 }
2187
2188 /* mention that we've just burned out */
2189 sayBurnedOut() { gLibMessages.objBurnedOut(self); }
2190
2191 /* our daemon object, valid while we're burning */
2192 burnDaemonObj = nil
2193 ;
2194
2195 /*
2196 * A candle is an item that can be set on fire for a controlled burn.
2197 * Although we call this a candle, this class can be used for other types
2198 * of fuel burners, such as torches and oil lanterns.
2199 *
2200 * Ordinary candles are usually fire sources as well, in that you can
2201 * light one candle with another once the first one is lit. To get this
2202 * effect, mix FireSource into the superclass list (but put it before
2203 * Candle, since FireSource is specifically designed as a mix-in class).
2204 */
2205 class Candle: FueledLightSource
2206 /*
2207 * The message we display when we try to light the candle and we're
2208 * out of fuel. This message can be overridden by subclasses that
2209 * don't fit the default message.
2210 */
2211 outOfFuelMsg = &candleOutOfFuelMsg
2212
2213 /* the message we display when we successfully light the candle */
2214 okayBurnMsg = &okayBurnCandleMsg
2215
2216 /* show a message when the candle runs out fuel while burning */
2217 sayBurnedOut()
2218 {
2219 /* by default, show our standard library message */
2220 gLibMessages.candleBurnedOut(self);
2221 }
2222
2223 /*
2224 * Determine if I can be lit with the specific indirect object. By
2225 * default, we'll allow any object to light us if the object passes
2226 * the normal checks applied by its own iobjFor(BurnWith) handlers.
2227 * This can be overridden if we can only be lit with specific
2228 * sources of fire; for example, a furnace with a deeply-recessed
2229 * burner could refuse to be lit by anything but particular long
2230 * matches, or a particular type of fuel could refuse to be lit
2231 * except by certain especially hot flames.
2232 */
2233 canLightWith(obj) { return true; }
2234
2235 /*
2236 * Default long description describes burning status. In most
2237 * cases, this should be overridden to provide more details, such as
2238 * information on our fuel level.
2239 */
2240 desc()
2241 {
2242 if (isLit)
2243 gLibMessages.litCandleDesc(self);
2244 else
2245 inherited();
2246 }
2247
2248 /* "burn with" action */
2249 dobjFor(BurnWith)
2250 {
2251 preCond = [touchObj]
2252 verify()
2253 {
2254 /* can't light it if it's already lit */
2255 if (isLit)
2256 illogicalAlready(&alreadyBurningMsg);
2257 }
2258 check()
2259 {
2260 /*
2261 * make sure the object being used to light us is a valid
2262 * source of fire for us
2263 */
2264 if (!canLightWith(obj))
2265 {
2266 reportFailure(&cannotBurnDobjWithMsg);
2267 exit;
2268 }
2269
2270 /* if the fuel level is zero, we can't be lit */
2271 if (fuelSource.getFuelLevel() == 0)
2272 {
2273 reportFailure(outOfFuelMsg);
2274 exit;
2275 }
2276 }
2277 action()
2278 {
2279 /* make myself lit */
2280 makeLit(true);
2281
2282 /* describe it */
2283 defaultReport(okayBurnMsg);
2284 }
2285 }
2286
2287 /* "extinguish" */
2288 dobjFor(Extinguish)
2289 {
2290 verify()
2291 {
2292 /* can't extinguish a match that isn't burning */
2293 if (!isLit)
2294 illogicalAlready(&candleNotLitMsg);
2295 }
2296 action()
2297 {
2298 /* describe the match going out */
2299 defaultReport(&okayExtinguishCandleMsg);
2300
2301 /* no longer lit */
2302 makeLit(nil);
2303 }
2304 }
2305 ;
2306
2307 /* ------------------------------------------------------------------------ */
2308 /*
2309 * "Tour Guide" is a mix-in class for Actors. This class can be
2310 * multiply inherited by objects along with Actor or a subclass of
2311 * Actor. This mix-in makes the Follow action, when applied to the tour
2312 * guide, initiate travel according to where the tour guide wants to go
2313 * next. So, if the tour guide is here and is waving us through the
2314 * door, FOLLOW GUIDE will initiate travel through the door.
2315 *
2316 * This class should appear in the superclass list ahead of Actor or the
2317 * Actor subclass.
2318 */
2319 class TourGuide: object
2320 dobjFor(Follow)
2321 {
2322 verify()
2323 {
2324 /*
2325 * If the actor can see us, and we're in a "guided tour"
2326 * state, we can definitely perform the travel. Otherwise,
2327 * use the standard "follow" behavior.
2328 */
2329 if (gActor.canSee(self) && getTourDest() != nil)
2330 {
2331 /*
2332 * we're waiting to show the actor to the next stop on
2333 * the tour, so we can definitely proceed with this
2334 * action
2335 */
2336 }
2337 else
2338 {
2339 /* we're not in a tour state, so use the standard handling */
2340 inherited();
2341 }
2342 }
2343
2344 action()
2345 {
2346 local dest;
2347
2348 /*
2349 * if we're in a guided tour state, initiate travel to our
2350 * escort destination; otherwise, use the standard handling
2351 */
2352 if (gActor.canSee(self) && (dest = getTourDest()) != nil)
2353 {
2354 /* initiate travel to our destination */
2355 replaceAction(TravelVia, dest);
2356 return;
2357 }
2358 else
2359 {
2360 /* no tour state; use the standard handling */
2361 inherited();
2362 }
2363 }
2364 }
2365
2366 /*
2367 * Get the travel connector that takes us to our next guided tour
2368 * destination. By default, this returns the escortDest from our
2369 * current actor state if our state is a guided tour state, or nil
2370 * if our state is any other kind of state. Subclasses must
2371 * override this if they use other kinds of states to represent
2372 * guided tours, since we'll only detect that we're in a guided tour
2373 * state if our current actor state object is of class
2374 * GuidedTourState (or any subclass).
2375 */
2376 getTourDest()
2377 {
2378 return (curState.ofKind(GuidedTourState)
2379 ? curState.escortDest
2380 : nil);
2381 }
2382 ;
2383
2384 /*
2385 * Guided Tour state. This provides a simple way of defining a "guided
2386 * tour," which is a series of locations to which we try to guide the
2387 * player character. We don't force the player character to travel as
2388 * specified; we merely try to lead the player. The actual travel is up
2389 * to the player.
2390 *
2391 * Here's how this works. For each location on the guided tour, create
2392 * one of these state objects. Set escortDest to the travel connector
2393 * to which we're attempting to guide the player character from the
2394 * current location. Set stateAfterEscort to the state object for the
2395 * next location on the tour. Set stateDesc to something indicating
2396 * that we're trying to show the player to the next stop - something
2397 * along the lines of "Bob waits for you by the door." Set
2398 * arrivingWithDesc to a message indicating that we just showed up in
2399 * the current location and are ready to show the player to the next -
2400 * "Bob goes to the door and waits for you to follow him."
2401 */
2402 class GuidedTourState: AccompanyingState
2403 /* the travel connector we're trying to show the player into */
2404 escortDest = nil
2405
2406 /*
2407 * The next state for our actor to assume after the travel. This
2408 * should be overridden and set to the state object for the next
2409 * stop on the tour.
2410 */
2411 stateAfterEscort = nil
2412
2413 /* the actor we're escorting - this is usually the player character */
2414 escortActor = (gPlayerChar)
2415
2416 /*
2417 * The class we use for our actor state during the escort travel.
2418 * By default, we use the basic guided-tour accompanying travel
2419 * state class, but games will probably want to use a customized
2420 * subclass of this basic class in most cases. The main reason to
2421 * use a custom subclass is to provide customized messages to
2422 * describe the departure of the escorting actor.
2423 */
2424 escortStateClass = GuidedInTravelState
2425
2426 /*
2427 * we should accompany the travel if the actor we're guiding will be
2428 * traveling, and they're traveling to the next stop on our tour
2429 */
2430 accompanyTravel(traveler, conn)
2431 {
2432 return (traveler.isActorTraveling(escortActor) && conn == escortDest);
2433 }
2434
2435 /*
2436 * get our accompanying state object - we'll create an instance of
2437 * the class specified in our escortStateClass property
2438 */
2439 getAccompanyingTravelState(traveler, conn)
2440 {
2441 return escortStateClass.createInstance(
2442 location, gActor, stateAfterEscort);
2443 }
2444 ;
2445
2446 /*
2447 * A subclass of the basic accompanying travel state specifically
2448 * designed for guided tours. This is almost the same as the basic
2449 * accompanying travel state, but provides customized messages to
2450 * describe the departure of our associated actor, which is the actor
2451 * serving as the tour guide.
2452 */
2453 class GuidedInTravelState: AccompanyingInTravelState
2454 sayDeparting(conn)
2455 { gLibMessages.sayDepartingWithGuide(location, leadActor); }
2456 ;
2457
2458 /* ------------------------------------------------------------------------ */
2459 /*
2460 * An Attachable is an object that can be attached to another, using an
2461 * ATTACH X TO Y command. This is a mix-in class that is meant to be
2462 * combined with a Thing-derived class to create an attachable object.
2463 *
2464 * Attachment is symmetrical: we can only attach to other Attachable
2465 * objects. As a result, the verb handling for ATTACH can be performed
2466 * symmetrically - ATTACH X TO Y is handled the same way as ATTACH Y TO
2467 * X. Sometimes reversing the roles makes the command nonsensical, but
2468 * when the reversal makes sense, it seems unlikely that it'll ever
2469 * change the meaning of the command. This makes it program the verb
2470 * handling, because it means that we can designate one of X or Y as the
2471 * handler for the verb, and just write the code once there. Refer to
2472 * the handleAttach() method to see how this works.
2473 *
2474 * There's an important detail that we leave to instances, because
2475 * there's no good general rule we can implement. Specifically, there's
2476 * the matter of imposing appropriate constraints on the relative
2477 * locations of objects once they're attached to one another. There are
2478 * numerous anomalies that become possible once two objects are attached.
2479 * Consider the example of a battery connected to a jumper cable that's
2480 * in turn connected to a lamp:
2481 *
2482 * - if we put the battery in a box but leave the lamp outside the box,
2483 * we shouldn't be able to close the lid of the box all the way without
2484 * breaking the cables
2485 *
2486 * - if we're carrying the battery but not the lamp, traveling to a new
2487 * room should drag the lamp along
2488 *
2489 * - if we drop the battery down a well, the lamp should be dragged down
2490 * with it
2491 *
2492 * Our world model isn't sophisticated enough to properly model an
2493 * attachment relationship, so it can't deal with these contingencies by
2494 * proper physical simulation. Which is why we have to leave these for
2495 * the game to handle.
2496 *
2497 * There are two main strategies you can apply to handle these problems.
2498 *
2499 * First, you can impose limits that prevent these sorts of situations
2500 * from coming up in the first place, either by carefully designing the
2501 * scenario so they simply don't come up, or by imposing more or less
2502 * artificial constraints. For example, you could solve all of the
2503 * problems above by eliminating the jumper cable and attaching the lamp
2504 * directly to the battery, or by making the jumper cable very short.
2505 * Anything attached to the battery would effectively become located "in"
2506 * the battery, so it would move everywhere along with the battery
2507 * automatically. Detaching the lamp would move the lamp back outside
2508 * the battery, and conversely, moving the lamp out of the battery would
2509 * detach the objects.
2510 *
2511 * Second, you can detect the anomalous cases and handle them explicitly
2512 * with special-purpose code. You could use beforeAction and afterAction
2513 * methods on one of the attached objects, for example, to detect the
2514 * various problematic actions, either blocking them or implementing
2515 * appropriate consequences.
2516 *
2517 * Given the number of difficult anomalies possible with rope-like
2518 * objects, the second approach is challenging on its own. However, it
2519 * often helps to combine it with the first approach, limiting the
2520 * scenario. In other words, you'd limit the scenario to some extent,
2521 * but not totally: rather than completely excising the difficult
2522 * behavior, you'd narrow it down to a manageable subset of the full
2523 * range of real-world possibilities; then, you'd deal with the remaining
2524 * anomalies on a case-by-case basis. For example, you could make the
2525 * battery too heavy to carry, which would guarantee that it would never
2526 * be put in a box, thrown down a well, or carried out of the room. That
2527 * would only leave a few issues: walking away while carrying the plugged
2528 * in lamp, which could be handled with an afterAction that severs the
2529 * attachment; putting the lamp in a box and closing the box, which could
2530 * be handled with a beforeAction by blocking Close actions whenever the
2531 * lamp is inside the object being closed.
2532 */
2533 class Attachable: object
2534 /*
2535 * The list of objects I'm currently attached to. Note that each of
2536 * the objects in this list must usually be an Attachable, and we
2537 * must be included in the attachedObjects list in each of these
2538 * objects.
2539 */
2540 attachedObjects = []
2541
2542 /*
2543 * Perform programmatic attachment, without any notifications. This
2544 * simply updates my attachedObjects list and the other object's list
2545 * to indicate that we're attached to the other object (and vice
2546 * versa).
2547 */
2548 attachTo(obj)
2549 {
2550 attachedObjects += obj;
2551 obj.attachedObjects += self;
2552 }
2553
2554 /* perform programmatic detachment, without any notifications */
2555 detachFrom(obj)
2556 {
2557 attachedObjects -= obj;
2558 obj.attachedObjects -= self;
2559 }
2560
2561 /* get the subset of my attachments that are non-permanent */
2562 getNonPermanentAttachments()
2563 {
2564 /* return the subset of objects not permanently attached */
2565 return attachedObjects.subset({x: !isPermanentlyAttachedTo(x)});
2566 }
2567
2568 /* am I attached to the given object? */
2569 isAttachedTo(obj)
2570 {
2571 /* we are attached to the other object if it's in our list */
2572 return (attachedObjects.indexOf(obj) != nil);
2573 }
2574
2575 /*
2576 * Am I the "major" item in my attachment relationship to the given
2577 * object? This affects how our relationship is described in our
2578 * status message: in an asymmetrical relationship, where one object
2579 * is the "major" item, we will always describe the minor item as
2580 * being attached to the major item rather than vice versa. This
2581 * allows you to ensure that the message is always "the sign is
2582 * attached to the wall", and never "the wall is attached to the
2583 * sign": the wall is the major item in this relationship, so it's
2584 * always the sign that's attached to it.
2585 *
2586 * By default, we always return nil here, which means that
2587 * attachment relationships are symmetrical by default. In a
2588 * symmetrical relationship, we'll describe the other things as
2589 * attached to 'self' when describing self.
2590 */
2591 isMajorItemFor(obj) { return nil; }
2592
2593 /*
2594 * Am I *listed* as attached to the given object? If this is true,
2595 * then our examineStatus() will list 'obj' among the things I'm
2596 * attached to: "Self is attached to obj." If this is nil, I'm not
2597 * listed as attached.
2598 *
2599 * By default, we're listed if (1) we're not permanently attached to
2600 * 'obj', AND (2) we're not the "major" item in the attachment
2601 * relationship. The reason we're not listed if we're permanently
2602 * attached is that the attachment information is presumably better
2603 * handled via the fixed description of the object rather than in
2604 * the extra status message; this is analogous to the way immovable
2605 * items (such as Fixtures) aren't normally listed in the
2606 * description of a room. The reason we're not listed if we're the
2607 * "major" item in the relationship is that the "major" status
2608 * reverses the relationship: when we're the major item, the other
2609 * item is described as attached to *us*, rather than vice versa.
2610 */
2611 isListedAsAttachedTo(obj)
2612 {
2613 /*
2614 * only list the item if it's not permanently attached, and
2615 * we're not the "major" item for the object
2616 */
2617 return (!isPermanentlyAttachedTo(obj) && !isMajorItemFor(obj));
2618 }
2619
2620 /*
2621 * Is 'obj' listed as attached to me when I'm described? If this is
2622 * true, then our examineStatus() will list 'obj' among the things
2623 * attached to me: "Attached to self is obj." If this is nil, then
2624 * 'obj' is not listed among the things attached to me when I'm
2625 * described.
2626 *
2627 * This routine is simply the "major" list counterpart of
2628 * isListedAsAttachedTo().
2629 *
2630 * By default, we list 'obj' among my attachments if (1) I'm the
2631 * "major" item for 'obj', AND (2) 'obj' is listed as attached to
2632 * me, as indicated by obj.isListedAsAttachedTo(self). We only list
2633 * our minor attachments here, because we list all of our other
2634 * listable attachments separately, as the things I'm attached to.
2635 * We also only list items that are themselves listable as
2636 * attachments, for obvious reasons.
2637 */
2638 isListedAsMajorFor(obj)
2639 {
2640 /*
2641 * only list the item if we're the "major" item for the object,
2642 * and the object is itself listable as an attachment
2643 */
2644 return (isMajorItemFor(obj) && obj.isListedAsAttachedTo(self));
2645 }
2646
2647 /*
2648 * Can I attach to the given object? This returns true if the other
2649 * object is allowable as an attachment, nil if not.
2650 *
2651 * By default, we look to see if the other side is an Attachable, and
2652 * if so, if it overrides canAttachTo(); if so, we'll call its
2653 * canAttachTo to ask whether it thinks it can attach to us. If the
2654 * other side doesn't override this, we'll simply return nil. This
2655 * arrangement is convenient because it means that only one side of
2656 * an attachable pair needs to implement this; the other side will
2657 * automatically figure it out by calling the first side and relying
2658 * on the symmetry of the relationship.
2659 */
2660 canAttachTo(obj)
2661 {
2662 /*
2663 * if the other side's an Attachable, and it overrides this
2664 * method, call the override; if not, it's by default not one of
2665 * our valid attachments
2666 */
2667 if (overrides(obj, Attachable, &canAttachTo))
2668 {
2669 /*
2670 * the other side is an Attachable that defines a specific
2671 * attachment rule, so ask the other side if it thinks we're
2672 * one of its attachments; by the symmetry of the
2673 * relationship, if we're one of its attachments, then it's
2674 * one of ours
2675 */
2676 return obj.canAttachTo(self);
2677 }
2678 else
2679 {
2680 /*
2681 * the other side doesn't want to tell us, so we're on our
2682 * own; we don't recognize any attachments on our own, so
2683 * it's not a valid attachment
2684 */
2685 return nil;
2686 }
2687 }
2688
2689 /*
2690 * Explain why we can't attach to the given object. This should
2691 * simply display an appropriate mesage. We use reportFailure to
2692 * flag it as a failure report, but that's not actually required,
2693 * since we call this from our 'check' routine, which will mark the
2694 * action as having failed even if we don't here.
2695 */
2696 explainCannotAttachTo(obj) { reportFailure(&wrongAttachmentMsg); }
2697
2698 /*
2699 * Is it possible for me to detach from the given object? This asks
2700 * whether a given attachment relationship can be dissolved with
2701 * DETACH FROM.
2702 *
2703 * By default, we'll use similar logic to canAttachTo: if the other
2704 * object overrides canDetachFrom(), we'll let it make the
2705 * determination. Otherwise, we'll return nil if one or the other
2706 * side is a PermanentAttachment, true if not. This lets you prevent
2707 * detachment by overriding canDetachFrom() on just one side of the
2708 * relationship.
2709 */
2710 canDetachFrom(obj)
2711 {
2712 /* if the other object overrides canDetachFrom, defer to it */
2713 if (overrides(obj, Attachable, &canDetachFrom))
2714 {
2715 /* let the other side make the judgment */
2716 return obj.canDetachFrom(self);
2717 }
2718 else
2719 {
2720 /*
2721 * the other side doesn't override it, so assume we can
2722 * detach unless one or the other side is a
2723 * PermanentAttachment
2724 */
2725 return !isPermanentlyAttachedTo(obj);
2726 }
2727 }
2728
2729 /*
2730 * Am I permanently attached to the other object? This returns true
2731 * if I'm a PermanentAttachment or the other object is.
2732 */
2733 isPermanentlyAttachedTo(obj)
2734 {
2735 /*
2736 * if either one of us is a PermanentAttachment, we're
2737 * permanently attached to each other
2738 */
2739 return ofKind(PermanentAttachment) || obj.ofKind(PermanentAttachment);
2740 }
2741
2742
2743 /*
2744 * A message explaining why we can't detach from the given object.
2745 * Note that 'obj' can be nil, because we could be attempting a
2746 * DETACH command with no indirect object.
2747 */
2748 cannotDetachMsgFor(obj)
2749 {
2750 /*
2751 * if we have an object, it must be the wrong one; otherwise, we
2752 * simply can't detach generically, since the object to detach
2753 * from wasn't specified, and there's nothing obvious we can
2754 * detach from
2755 */
2756 return obj != nil ? &wrongDetachmentMsg : &cannotDetachMsg;
2757 }
2758
2759 /*
2760 * Process attachment to a new object. This routine is called on
2761 * BOTH the direct and indirect object during the attachment process
2762 * - that is, it's called on the direct object with the indirect
2763 * object as the argument, and then it's called on the indirect
2764 * object with the direct object as the argument.
2765 *
2766 * This symmetrical handling makes it easy to handle the frequent
2767 * cases where the player might say ATTACH X TO Y or ATTACH Y TO X
2768 * and mean the same thing either way. Because this method is called
2769 * for both X and Y in either phrasing, you can simply choose to
2770 * write the handler code in either X or Y - you only have to write
2771 * it once, because the handler will be called on each of the
2772 * objects, regardless of the phrasing. So, if you choose to
2773 * designate X as the official ATTACH handler, write a handleAttach()
2774 * method on X, and leave the one on Y doing nothing: during
2775 * execution, the X method will do its work, and the Y method will do
2776 * nothing, so regardless of phrasing order, the net result will be
2777 * the same.
2778 *
2779 * By default we do nothing. Each instance should override this to
2780 * display any extra message and take any extra action needed to
2781 * process the attachment status change. Note that the override
2782 * doesn't need to worry about managing the attachedObjects list, as
2783 * the main action handler does that automatically.
2784 *
2785 * Note that handleAttach() is always called after both objects have
2786 * updated their attachedObjects lists. This means that you can turn
2787 * right around and detach the objects here, if you don't want to
2788 * leave them attached.
2789 */
2790 handleAttach(other)
2791 {
2792 /* do nothing by default */
2793 }
2794
2795 /*
2796 * Receive notification that this object or one of its attachments
2797 * is being moved to a new container. When an attached object is
2798 * moved, we'll call this on the object being moved AND on every
2799 * object attached to it. 'movedObj' is the object being moved, and
2800 * 'newCont' is the new container it's being moved into.
2801 *
2802 * By default we do nothing. Instances can override this as needed.
2803 * For example, if you wish to enforce a rule that this object and
2804 * all of its attached objects share a common direct container, you
2805 * could either block the move (by displaying an error and using
2806 * 'exit') or run a nested DetachFrom action to sever the attachment
2807 * with the object being moved.
2808 */
2809 moveWhileAttached(movedObj, newCont)
2810 {
2811 /* do nothing by default */
2812 }
2813
2814 /*
2815 * Receive notification that this object or one of its attachments is
2816 * being moved in the course of an actor traveling to a new location.
2817 * Whenever anyone travels while carrying an attachable object
2818 * (directly or indirectly), we'll call this on the object being
2819 * moved AND on every object attached to it. 'movedObj' is the
2820 * object being carried by the traveling actor, 'traveler' is the
2821 * Traveler performing the travel, and 'connector' is the
2822 * TravelConnector that the traveler is traversing.
2823 *
2824 * By default, we do nothing. Instances can override this as needed.
2825 */
2826 travelWhileAttached(movedObj, traveler, connector)
2827 {
2828 /* do nothing by default */
2829 }
2830
2831 /*
2832 * Handle detachment. This works like handleAttach(), in that this
2833 * routine is invoked symmetrically for both sides of a DETACH X FROM
2834 * Y commands.
2835 *
2836 * As with handleAttach(), we do nothing by default, so instances
2837 * should override as needed. Note that the override doesn't need to
2838 * worry about managing the attachedObjects list, as the main action
2839 * handler does that automatically. As with handleAttach(), this is
2840 * called after the attachedObjects lists for both objects are
2841 * updated.
2842 */
2843 handleDetach(other)
2844 {
2845 /* do nothing by default */
2846 }
2847
2848 /* the Lister we use to show our list of attached objects */
2849 attachmentLister = perInstance(new SimpleAttachmentLister(self))
2850
2851 /*
2852 * the Lister we use to list the items attached to us (i.e., the
2853 * items for which we're the "major" item in the attachment
2854 * relationship)
2855 */
2856 majorAttachmentLister = perInstance(new MajorAttachmentLister(self))
2857
2858 /* add a list of our attachments to the desription */
2859 examineStatus()
2860 {
2861 local tab;
2862
2863 /* inherit the normal status description */
2864 inherited();
2865
2866 /* get the actor's visual sense table */
2867 tab = gActor.visibleInfoTable();
2868
2869 /* add our list of attachments */
2870 attachmentLister.showList(gActor, self, attachedObjects,
2871 0, 0, tab, nil);
2872
2873 /* add our list of major attachments */
2874 majorAttachmentLister.showList(gActor, self, attachedObjects,
2875 0, 0, tab, nil);
2876 }
2877
2878 /*
2879 * Move into a new container. If I'm attached to anything, we'll
2880 * notify ourself and our attachments.
2881 */
2882 mainMoveInto(newCont)
2883 {
2884 /* if I'm attached to anything, notify everyone */
2885 if (attachedObjects.length() != 0)
2886 {
2887 /* notify myself */
2888 moveWhileAttached(self, newCont);
2889
2890 /* notify my attachments */
2891 attachedObjects.forEach({x: x.moveWhileAttached(self, newCont)});
2892 }
2893
2894 /* inherit the base handling */
2895 inherited(newCont);
2896 }
2897
2898 /*
2899 * Receive notification of travel. If I'm involved in the travel,
2900 * and I'm attached to anything, we'll notify ourself and our
2901 * attachments.
2902 */
2903 beforeTravel(traveler, connector)
2904 {
2905 /*
2906 * If we're traveling with the traveler, and we're attached to
2907 * anything, notify everything that's attached.
2908 */
2909 if (attachedObjects.length() != 0
2910 && traveler.isTravelerCarrying(self))
2911 {
2912 /* notify myself */
2913 travelWhileAttached(self, traveler, connector);
2914
2915 /* notify each of my attachments */
2916 attachedObjects.forEach(
2917 {x: x.travelWhileAttached(self, traveler, connector)});
2918 }
2919 }
2920
2921 /*
2922 * during initialization, make sure the attachedObjects list is
2923 * symmetrical for both sides of the attachment relationship
2924 */
2925 initializeThing()
2926 {
2927 /* do the normal work */
2928 inherited();
2929
2930 /*
2931 * check to make sure that each of our attached objects points
2932 * back at us
2933 */
2934 foreach (local cur in attachedObjects)
2935 {
2936 /*
2937 * if we're not in this one's attachedObjects list, add
2938 * ourselves to the list, so that everyone's consistent
2939 */
2940 if (cur.attachedObjects.indexOf(self) == nil)
2941 cur.attachedObjects += self;
2942 }
2943 }
2944
2945 /* handle attachment on the direct object side */
2946 dobjFor(AttachTo)
2947 {
2948 /* require that the actor can touch the direct object */
2949 preCond = [touchObj]
2950
2951 verify()
2952 {
2953 /*
2954 * it makes sense to attach to anything but myself, or things
2955 * we're already attached to
2956 */
2957 if (gIobj != nil)
2958 {
2959 if (isAttachedTo(gIobj))
2960 illogicalAlready(&alreadyAttachedMsg);
2961 else if (gIobj == self)
2962 illogicalSelf(&cannotAttachToSelfMsg);
2963 }
2964 }
2965
2966 check()
2967 {
2968 /* only allow it if we can attach to the other object */
2969 if (!canAttachTo(gIobj))
2970 {
2971 explainCannotAttachTo(gIobj);
2972 exit;
2973 }
2974 }
2975
2976 action()
2977 {
2978 /* add the other object to our list of attached objects */
2979 attachedObjects += gIobj;
2980
2981 /* add our default acknowledgment */
2982 defaultReport(&okayAttachToMsg);
2983
2984 /* fire the handleAttach event if we're ready */
2985 maybeHandleAttach(gIobj);
2986 }
2987 }
2988
2989 /* handle attachment on the indirect object side */
2990 iobjFor(AttachTo)
2991 {
2992 /*
2993 * Require that the direct object can touch the indirect object.
2994 * This ensures that the two objects to be attached can touch
2995 * one another. Note that we don't also require that the actor
2996 * be able to touch the indirect object directly, since it's
2997 * good enough that (1) the actor can touch the direct object
2998 * (which we enforce with the dobj precondition), and (2) the
2999 * direct object can touch the indirect object. This allows for
3000 * odd things like plugging something into a recessed outlet,
3001 * where the recessed bit can't be reached directly but can be
3002 * reached using the plug.
3003 */
3004 preCond = [dobjTouchObj]
3005
3006 verify()
3007 {
3008 /*
3009 * it makes sense to attach to anything but myself, or things
3010 * we're already attached to
3011 */
3012 if (gDobj != nil)
3013 {
3014 if (isAttachedTo(gDobj))
3015 illogicalAlready(&alreadyAttachedMsg);
3016 else if (gDobj == self)
3017 illogicalSelf(&cannotAttachToSelfMsg);
3018 }
3019 }
3020
3021 check()
3022 {
3023 /* only allow it if we can attach to the other object */
3024 if (!canAttachTo(gDobj))
3025 {
3026 explainCannotAttachTo(gDobj);
3027 exit;
3028 }
3029 }
3030
3031 action()
3032 {
3033 /* add the other object to our list of attached objects */
3034 attachedObjects += gDobj;
3035
3036 /* fire the handleAttach event if we're ready */
3037 maybeHandleAttach(gIobj);
3038 }
3039 }
3040
3041 /*
3042 * Fire the handleAttach event - we'll notify both sides as soon as
3043 * both sides are hooked up with each other. This ensures that both
3044 * lists are updated before we notify either side, so the ordering
3045 * doesn't depend on whether we handle the dobj or iobj first.
3046 */
3047 maybeHandleAttach(other)
3048 {
3049 /* if both lists are hooked up, send the notifications */
3050 if (attachedObjects.indexOf(other) != nil
3051 && other.attachedObjects.indexOf(self) != nil)
3052 {
3053 /* notify our side */
3054 handleAttach(other);
3055
3056 /* notify the other side */
3057 other.handleAttach(self);
3058 }
3059 }
3060
3061 /* handle simple, unspecified detachment (DETACH OBJECT) */
3062 dobjFor(Detach)
3063 {
3064 verify()
3065 {
3066 /* if I'm not attached to anything, this is illogical */
3067 if (attachedObjects.length() == 0)
3068 illogicalAlready(cannotDetachMsgFor(nil));
3069 }
3070 action()
3071 {
3072 local lst;
3073
3074 /* get the non-permanent attachment subset */
3075 lst = getNonPermanentAttachments();
3076
3077 /* check what that leaves us */
3078 if (lst.length() == 0)
3079 {
3080 /*
3081 * we're not attached to anything that we can detach
3082 * from, so simply report that we can't detach
3083 * generically
3084 */
3085 reportFailure(cannotDetachMsgFor(nil));
3086 }
3087 else if (lst.length() == 1)
3088 {
3089 /*
3090 * we have exactly one attached object from which we can
3091 * detach, so they must want to detach from that -
3092 * process this as DETACH FROM my one attached object
3093 */
3094 replaceAction(DetachFrom, self, lst[1]);
3095 }
3096 else
3097 {
3098 /*
3099 * we have more than one detachable attachment, so ask
3100 * which one they mean
3101 */
3102 askForIobj(DetachFrom);
3103 }
3104 }
3105 }
3106
3107 /* handle detaching me from a specific other object */
3108 dobjFor(DetachFrom)
3109 {
3110 verify()
3111 {
3112 /* it only makes sense to try detaching us from our attachments */
3113 if (gIobj != nil && !isAttachedTo(gIobj))
3114 illogicalAlready(&notAttachedToMsg);
3115 }
3116 check()
3117 {
3118 /* make sure I'm allowed to detach from the given object */
3119 if (!canDetachFrom(gIobj))
3120 {
3121 reportFailure(cannotDetachMsgFor(gIobj));
3122 exit;
3123 }
3124 }
3125 action()
3126 {
3127 /* remove the other object from our list of attached objects */
3128 attachedObjects -= gIobj;
3129
3130 /* add our default acknowledgment */
3131 defaultReport(&okayDetachFromMsg);
3132
3133 /* fire the handleDetach event if appropriate */
3134 maybeHandleDetach(gIobj);
3135 }
3136 }
3137
3138 /* handle detachment on the indirect object side */
3139 iobjFor(DetachFrom)
3140 {
3141 verify()
3142 {
3143 /* it only makes sense to try detaching my attachments */
3144 if (gDobj == nil)
3145 {
3146 /*
3147 * we don't know the dobj yet, but we can check the
3148 * tentative list for the possible set
3149 */
3150 if (gTentativeDobj
3151 .indexWhich({x: isAttachedTo(x.obj_)}) == nil)
3152 illogicalAlready(&notAttachedToMsg);
3153 }
3154 else if (gDobj != nil && !isAttachedTo(gDobj))
3155 illogicalAlready(&notAttachedToMsg);
3156 }
3157 check()
3158 {
3159 /* make sure I'm allowed to detach from the given object */
3160 if (!canDetachFrom(gDobj))
3161 {
3162 reportFailure(cannotDetachMsgFor(gDobj));
3163 exit;
3164 }
3165 }
3166 action()
3167 {
3168 /* remove the other object from our list of attached objects */
3169 attachedObjects -= gDobj;
3170
3171 /* fire the handleDetach event if appropriate */
3172 maybeHandleDetach(gDobj);
3173 }
3174 }
3175
3176 /*
3177 * Fire the handleDetach event - we'll notify both sides as soon as
3178 * both sides are un-hooked up. This ensures that both lists are
3179 * updated before we notify either side, so the ordering doesn't
3180 * depend on whether we handle the dobj or iobj first.
3181 */
3182 maybeHandleDetach(other)
3183 {
3184 /* if both lists are un-hooked up, send the notifications */
3185 if (attachedObjects.indexOf(other) == nil
3186 && other.attachedObjects.indexOf(self) == nil)
3187 {
3188 /* notify our side */
3189 handleDetach(other);
3190
3191 /* notify the other side */
3192 other.handleDetach(self);
3193 }
3194 }
3195
3196 /*
3197 * TAKE X FROM Y is the same as DETACH X FROM Y for things we're
3198 * attached to, but use the inherited handling otherwise
3199 */
3200 dobjFor(TakeFrom)
3201 {
3202 verify()
3203 {
3204 /*
3205 * use the inherited handling only if we're not attached -
3206 * if we're attached, consider it logical, overriding any
3207 * containment relationship check we might otherwise make
3208 */
3209 if (gIobj == nil || !isAttachedTo(gIobj))
3210 inherited();
3211 }
3212 check()
3213 {
3214 /* inherit the default check only if we're not attached */
3215 if (!isAttachedTo(gIobj))
3216 inherited();
3217 }
3218 action()
3219 {
3220 /*
3221 * if we're attached, change this into a DETACH FROM action;
3222 * otherwise, use the inherited TAKE FROM handling
3223 */
3224 if (isAttachedTo(gIobj))
3225 replaceAction(DetachFrom, self, gIobj);
3226 else
3227 inherited();
3228 }
3229 }
3230 iobjFor(TakeFrom)
3231 {
3232 verify()
3233 {
3234 /* use the inherited handling only if we're not attached */
3235 if (gDobj == nil || !isAttachedTo(gDobj))
3236 inherited();
3237 }
3238 check()
3239 {
3240 /* inherit the default check only if we're not attached */
3241 if (!isAttachedTo(gDobj))
3242 inherited();
3243 }
3244 action()
3245 {
3246 /* inherit the default action only if we're not attached */
3247 if (!isAttachedTo(gDobj))
3248 inherited();
3249 }
3250 }
3251 ;
3252
3253 /*
3254 * An Attachable-specific precondition: the Attachable isn't already
3255 * attached to something else. This can be added to the preCond list for
3256 * an Attachable (for iobjFor(AttachTo) and dobjFor(AttachTo)) to ensure
3257 * that any existing attachment is removed before a new attachment is
3258 * formed. This is useful when the Attachable can connect to only one
3259 * thing at a time.
3260 */
3261 objNotAttached: PreCondition
3262 checkPreCondition(obj, allowImplicit)
3263 {
3264 /*
3265 * if we don't already have any non-permanent attachments, we're
3266 * fine (as we don't require removing permanent attachments)
3267 */
3268 if (obj.attachedObjects.indexWhich(
3269 {x: !obj.isPermanentlyAttachedTo(x)}) == nil)
3270 return nil;
3271
3272 /*
3273 * Try an implicit Detach command. It should be safe to use the
3274 * form that doesn't specify what we're detaching from, since the
3275 * whole point of this condition is that the object can have only
3276 * one non-permanent attachment, hence the vague Detach handler
3277 * should be able to figure out what we mean.
3278 */
3279 if (allowImplicit && tryImplicitAction(Detach, obj))
3280 {
3281 /* if we're still attached to anything, we failed, so abort */
3282 if (obj.attachedObjects.indexWhich(
3283 {x: !obj.isPermanentlyAttachedTo(x)}) != nil)
3284 exit;
3285
3286 /* tell the caller we executed an implied action */
3287 return true;
3288 }
3289
3290 /* we must detach first */
3291 reportFailure(&mustDetachMsg, obj);
3292 exit;
3293 }
3294 ;
3295
3296 /*
3297 * A "nearby" attachable is a subclass of Attachable that adds a
3298 * requirement that the attached objects be in a given location. By
3299 * default, we simply require that they have a common immediate
3300 * container, but this can be overridden so that each object's location
3301 * is negotiated separately. This is a simple and effective pattern that
3302 * avoids many of the potential anomalies with attachment (see the
3303 * Attachable comments for examples).
3304 *
3305 * In AttachTo actions, we enforce the nearby requirement with a
3306 * precondition requiring the direct object to be in the same immediate
3307 * container as the indirect object, and vice versa. In
3308 * moveWhileAttached(), we enforce the rule by detaching the objects if
3309 * one is being moved away from the other's immediate container.
3310 */
3311 class NearbyAttachable: Attachable
3312 dobjFor(AttachTo)
3313 {
3314 /* require that the objects be in the negotiated locations */
3315 preCond = (inherited() + nearbyAttachableCond)
3316 }
3317 iobjFor(AttachTo)
3318 {
3319 /* require that the objects be in the negotiated locations */
3320 preCond = (inherited() + nearbyAttachableCond)
3321 }
3322
3323 /*
3324 * Get the target locations for attaching to the given other object.
3325 * The "target locations" are the locations where the objects are
3326 * required to be in order to carry out the ATTACH command to attach
3327 * this object to the other object (or vice versa).
3328 *
3329 * This method returns a list with three elements. The first
3330 * element is the target location for 'self', and the second is the
3331 * target location for 'other', the object we're attaching to. The
3332 * third element is an integer giving the priority; a higher number
3333 * means higher priority.
3334 *
3335 * The priority is an arbitrary value that we use to determine which
3336 * of the two objects involved in the attach gets to decide on the
3337 * target locations. We call this method on both of the two objects
3338 * being attached to one another, then we use the target locations
3339 * returned by the object that claims the higher priority. If the
3340 * two priorities are equal, we pick one arbitrarily.
3341 *
3342 * The default implementation chooses my own immediate container as
3343 * the target location for both objects. However, if the other
3344 * object is non-portable, we'll choose its immediate location
3345 * instead, since we obviously can't move it to our container.
3346 */
3347 getNearbyAttachmentLocs(other)
3348 {
3349 /*
3350 * If the other object is portable, use our immediate container
3351 * as the proposed location for both objects; otherwise, use the
3352 * other object's immediate container. In any case, use a low
3353 * priority, since we're just the default base class
3354 * implementation; any override will generally have higher
3355 * priority.
3356 */
3357 if (other.ofKind(NonPortable))
3358 {
3359 /* the other can't be moved, so use its location */
3360 return [other.location, other.location, 0];
3361 }
3362 else
3363 {
3364 /*
3365 * the other can be moved, so use our own location, in a
3366 * paraphrase of the realty agent's favorite mantra
3367 */
3368 return [location, location, 0];
3369 }
3370 }
3371
3372 /* when an attached object is being moved, detach the objects */
3373 moveWhileAttached(movedObj, newCont)
3374 {
3375 /*
3376 * If I'm the one being moved, detach me from all of my
3377 * non-permanent attachments; otherwise, just detach me from the
3378 * other object, since it's the only one of my attachments being
3379 * moved.
3380 */
3381 if (movedObj == self)
3382 {
3383 /* I'm being moved - detach from everything */
3384 foreach (local cur in attachedObjects)
3385 {
3386 /*
3387 * If we're not permanently attached to this one, and
3388 * it's not inside me, detach from it. We don't need to
3389 * detach from objects inside this one, because they'll
3390 * be moved along with us automatically.
3391 */
3392 if (!cur.isIn(self) && !isPermanentlyAttachedTo(cur))
3393 nestedDetachFrom(cur);
3394 }
3395 }
3396 else
3397 {
3398 /* just detach from the one object */
3399 nestedDetachFrom(movedObj);
3400 }
3401 }
3402
3403 /* perform a nested DetachFrom action on the given object */
3404 nestedDetachFrom(obj)
3405 {
3406 /* run the nested DetachFrom as an implied action */
3407 tryImplicitAction(DetachFrom, self, obj);
3408
3409 /*
3410 * if we're still attached to this object, the implied command
3411 * must have failed, so abort the entire action
3412 */
3413 if (attachedObjects.indexOf(obj) != nil)
3414 exit;
3415 }
3416 ;
3417
3418 /*
3419 * Precondition for nearby-attachables. This ensures that the two
3420 * objects being attached are in their negotiated locations.
3421 */
3422 nearbyAttachableCond: PreCondition
3423 /* carry out the precondition */
3424 checkPreCondition(obj, allowImplicit)
3425 {
3426 local dobjProposal, iobjProposal;
3427 local dobjTargetLoc, iobjTargetLoc;
3428 local iobjRet, dobjRet;
3429
3430 /*
3431 * Ask each of the NearbyAttachable objects (the direct and
3432 * indirect objects) what it thinks. If an object isn't a
3433 * NearbyAttachable, it won't have any opinion, so use a
3434 * placeholder result with an extremely negative priority
3435 * (ensuring that it won't be chosen). In order for this
3436 * precondition to have been triggered, one or the other of the
3437 * objects must have been a nearby-attachable.
3438 */
3439 dobjProposal = (gDobj.ofKind(NearbyAttachable)
3440 ? gDobj.getNearbyAttachmentLocs(gIobj)
3441 : [nil, nil, -2147483648]);
3442 iobjProposal = (gIobj.ofKind(NearbyAttachable)
3443 ? gIobj.getNearbyAttachmentLocs(gDobj)
3444 : [nil, nil, -2147483648]);
3445
3446 /*
3447 * If the direct object claims higher priority, use its
3448 * attachment locations; otherwise, use the direct object's
3449 * locations. (This means that we take the indirect object's
3450 * proposed locations if the priorites are equal.)
3451 */
3452 if (dobjProposal[3] > iobjProposal[3])
3453 {
3454 /* the direct object claims higher priority, so use its results */
3455 dobjTargetLoc = dobjProposal[1];
3456 iobjTargetLoc = dobjProposal[2];
3457 }
3458 else
3459 {
3460 /*
3461 * The direct object doesn't have a higher priority, so use
3462 * the indirect object's results. Note that the iobj
3463 * results list has the iobj in the first position, since it
3464 * was the 'self' when we asked it for its proposal.
3465 */
3466 dobjTargetLoc = iobjProposal[2];
3467 iobjTargetLoc = iobjProposal[1];
3468 }
3469
3470 /* carry out the pair of moves as needed */
3471 dobjRet = moveObject(gDobj, dobjTargetLoc, allowImplicit);
3472 iobjRet = moveObject(gIobj, iobjTargetLoc, allowImplicit);
3473
3474 /*
3475 * Return the indication of whether or not we carried out an
3476 * implied command. (Note that we can't call moveObject in this
3477 * 'return' expression directly, because of the short-circuit
3478 * behavior of the '||' operator. We must call both, even if
3479 * both carry out an action.)
3480 */
3481 return (dobjRet || iobjRet);
3482 }
3483
3484 /* carry out an implied action to move an object to a location */
3485 moveObject(obj, loc, allowImplicit)
3486 {
3487 /* if the object is already there, we have nothing to do */
3488 if (obj.location == loc)
3489 return nil;
3490
3491 /* try the implied move */
3492 if (allowImplicit && loc.tryMovingObjInto(obj))
3493 {
3494 /* make sure it worked */
3495 if (obj.location != loc)
3496 exit;
3497
3498 /* we performed an implied action */
3499 return true;
3500 }
3501
3502 /* we can't move it - report failure and abort */
3503 loc.mustMoveObjInto(obj);
3504 exit;
3505 }
3506 ;
3507
3508 /*
3509 * A PlugAttachable is a mix-in class that turns PLUG INTO into ATTACH TO
3510 * and UNPLUG FROM into DETACH FROM. This can be combined with
3511 * Attachable or an Attachable subclass for objects that can be attached
3512 * with PLUG INTO commands.
3513 */
3514 class PlugAttachable: object
3515 /* PLUG IN - to what? */
3516 dobjFor(PlugIn)
3517 {
3518 verify() { }
3519 action() { askForIobj(PlugInto); }
3520 }
3521
3522 /* PLUG INTO is the same as ATTACH TO for us */
3523 dobjFor(PlugInto) remapTo(AttachTo, self, IndirectObject)
3524 iobjFor(PlugInto) remapTo(AttachTo, DirectObject, self)
3525
3526 /* UNPLUG FROM is the same as DETACH FROM */
3527 dobjFor(Unplug) remapTo(Detach, self)
3528 dobjFor(UnplugFrom) remapTo(DetachFrom, self, IndirectObject)
3529 iobjFor(UnplugFrom) remapTo(DetachFrom, DirectObject, self)
3530 ;
3531
3532 /* ------------------------------------------------------------------------ */
3533 /*
3534 * Permanent attachments. This class is for things that are described
3535 * in the story text as attached to one another, but which can never be
3536 * separated. This is a mix-in class that can be combined with a Thing
3537 * subclass.
3538 *
3539 * Descriptions of attachment tend to invite the player to try detaching
3540 * the parts; the purpose of this class is to provide responses that are
3541 * better than the defaults. A good custom message for this class
3542 * should usually acknowledge the attachment relationship, and explain
3543 * why the parts can't be separated.
3544 *
3545 * There are two ways to express the attachment relationship.
3546 *
3547 * First, the more flexible way: in each PermanentAttachment object,
3548 * define the 'attachedObjects' property to contain a list of the
3549 * attached objects. All of those other attached objects should usually
3550 * be PermanentAttachment objects themselves, because the real-world
3551 * relationship we're modeling is obviously symmetrical. Because of the
3552 * symmetrical relationship, it's only necessary to include the list
3553 * entry on one side of a pair of attached objects - each side will
3554 * automatically link itself to the other at start-up if it appears in
3555 * the other's attachedObjects list.
3556 *
3557 * Second, the really easy way: if one of the attached objects is
3558 * directly inside the other (which often happens for permanent
3559 * attachments, because one is a component of the other), make the
3560 * parent a PermanentAttachment, make the inner one a
3561 * PermanentAttachmentChild, and you're done. The two will
3562 * automatically link up their attachment lists at start-up.
3563 *
3564 * Note that this is a subclass of Attachable. Note also that a
3565 * PermanentAttachment can be freely combined with a regular Attachable;
3566 * for example, you could create a rope with a hook permanently
3567 * attached, but stil allow the rope to be attached to other things as
3568 * well: you'd make the rope a regular Attachable, and make the hook a
3569 * PermanentAttachment. The hook would be unremovable because of its
3570 * permanent status, and this would symmetrical prevent the rope from
3571 * being removed from the hook. But the rope could still be attached to
3572 * and detached from other objects.
3573 */
3574 class PermanentAttachment: Attachable
3575 /*
3576 * Get the message explaining why we can't detach from 'obj'.
3577 *
3578 * By default, if our container is also a PermanentAttachment, and
3579 * we're attached to it, we'll simply return its message. This
3580 * makes it really easy to define symmetrical permanent attachment
3581 * relationships using containment, since all you have to do is make
3582 * the container and the child both be PermanentAttachments, and
3583 * then just define the cannot-detach message in the container. If
3584 * the container isn't a PermanentAttachment, or we're not attached
3585 * to it, we'll return our default library message.
3586 */
3587 cannotDetachMsgFor(obj)
3588 {
3589 if (location != nil
3590 && location.ofKind(PermanentAttachment)
3591 && isAttachedTo(location))
3592 return location.cannotDetachMsgFor(obj);
3593 else
3594 return baseCannotDetachMsg;
3595 }
3596
3597 /* basic message to use when we try to detach something from self */
3598 baseCannotDetachMsg = &cannotDetachPermanentMsg
3599 ;
3600
3601 /*
3602 * A permanent attachment "child" - this is an attachment that's
3603 * explicitly attached to its container object. This is a convenient
3604 * way of setting up an attachment relationship between container and
3605 * contents when the contents object isn't a Component.
3606 */
3607 class PermanentAttachmentChild: PermanentAttachment
3608 /* we're attached directly to our container */
3609 attachedObjects = perInstance([location])
3610 ;
3611
3612 /* ------------------------------------------------------------------------ */
3613 /*
3614 * A mix-in class for objects that don't come into play until some
3615 * future event. This class lets us initialize these objects with their
3616 * *eventual* location, using the standard '+' syntax, but they won't
3617 * actually appear in the given location until later in the game.
3618 * During pre-initialization, we'll remember the starting location, then
3619 * set the actual location to nil; later, the object can be easily moved
3620 * to its eventual location by calling makePresent().
3621 */
3622 class PresentLater: object
3623 /*
3624 * My "key" - this is an optional property you can add to a
3625 * PresentLater object to associate it with a group of objects. You
3626 * can then use makePresentByKey() to move every object with a given
3627 * key into the game world at once. This is useful when an event
3628 * triggers a whole set of objects to come into the game world:
3629 * rather than having to write a method that calls makePresent() on
3630 * each of the related objects individually, you can simply give each
3631 * related object the same key value, then call makePresentByKey() on
3632 * that key.
3633 *
3634 * You don't need to define this for an object unless you want to use
3635 * makePresentByKey() with the object.
3636 */
3637 plKey = nil
3638
3639 /*
3640 * Flag: are we present initially? By default, we're only present
3641 * later, as that's the whole point. In some cases, though, we have
3642 * objects that come and go, but start out present. Setting this
3643 * property to true makes the object present initially, but still
3644 * allows it to come and go using the standard PresentLater
3645 * mechanisms.
3646 */
3647 initiallyPresent = nil
3648
3649 initializeLocation()
3650 {
3651 /*
3652 * Save the initial location for later, and then clear out the
3653 * current location. We want to start out being out of the game,
3654 * but remember where we'll appear when called upon. To
3655 * accommodate MultiLoc objects, check locationList first.
3656 */
3657 if (locationList != nil)
3658 {
3659 /* save the location list */
3660 eventualLocation = locationList;
3661
3662 /*
3663 * clear my location list if I'm not initially present; if I
3664 * am initially present, inherit the normal initialization
3665 */
3666 if (!initiallyPresent)
3667 locationList = [];
3668 else
3669 inherited();
3670 }
3671 else
3672 {
3673 /* save my eventual location */
3674 eventualLocation = location;
3675
3676 /*
3677 * clear my location if I'm not initially present; if I am
3678 * present initially, inherit the normal set-up
3679 */
3680 if (!initiallyPresent)
3681 location = nil;
3682 else
3683 inherited();
3684 }
3685 }
3686
3687 /* bring the object into the game world in its eventual location(s) */
3688 makePresent()
3689 {
3690 local pc;
3691
3692 /*
3693 * If we have a list, add ourself to each location in the list;
3694 * otherwise, simply move ourself to the single location.
3695 */
3696 if (eventualLocation != nil && eventualLocation.ofKind(Collection))
3697 eventualLocation.forEach({loc: moveIntoAdd(loc)});
3698 else
3699 moveInto(eventualLocation);
3700
3701 /* if the player character can now see me, mark me as seen */
3702 pc = gPlayerChar;
3703 if (pc.canSee(self))
3704 {
3705 /* mark me as seen */
3706 pc.setHasSeen(self);
3707
3708 /* mark my visible contents as seen */
3709 setContentsSeenBy(pc.visibleInfoTable(), pc);
3710 }
3711 }
3712
3713 /*
3714 * make myself present if the given condition is true; otherwise,
3715 * remove me from the game world (i.e. move me into nil)
3716 */
3717 makePresentIf(cond)
3718 {
3719 if (cond)
3720 makePresent();
3721 else
3722 moveInto(nil);
3723 }
3724
3725 /*
3726 * Bring every PresentLater object with the given key into the game.
3727 * Note that this is a "class" method that you call on PresentLater
3728 * itself:
3729 *
3730 * PresentLater.makePresentByKey('foo');
3731 */
3732 makePresentByKey(key)
3733 {
3734 /*
3735 * scan every PresentLater object, and move each one with the
3736 * given key into the game
3737 */
3738 forEachInstance(PresentLater, function(obj) {
3739 if (obj.plKey == key)
3740 obj.makePresent();
3741 });
3742 }
3743
3744 /*
3745 * Bring every PresentLater object with the given key into the game,
3746 * or move every one out of the game, according to the condition
3747 * 'cond'.
3748 *
3749 * If 'cond' is a function pointer, we'll invoke it once per object
3750 * with the given key, passing the object as the parameter, and use
3751 * the return value as the in game/out of game setting. For example,
3752 * if you wanted to show every object with key 'foo' AND with the
3753 * property 'showObj' set to true, you could write this:
3754 *
3755 * PresentLater.makePresentByKeyIf('foo', {x: x.showObj});
3756 *
3757 * Note that this is a "class" method that you call on PresentLater
3758 * itself.
3759 */
3760 makePresentByKeyIf(key, cond)
3761 {
3762 /*
3763 * scan every PresentLater object, check each one's key, and make
3764 * each one with the given key present
3765 */
3766 forEachInstance(PresentLater, function(obj) {
3767 /* consider this object if its key matches */
3768 if (obj.plKey == key)
3769 {
3770 local flag = cond;
3771
3772 /*
3773 * evaluate the condition - if it's a function pointer,
3774 * invoke it on the current object, otherwise just take
3775 * it as a pre-evaluated condition value
3776 */
3777 if (dataTypeXlat(cond) == TypeFuncPtr)
3778 flag = (cond)(obj);
3779
3780 /* show or hide the object according to the condition */
3781 obj.makePresentIf(flag);
3782 }
3783 });
3784 }
3785
3786 /* our eventual location */
3787 eventualLocation = nil
3788 ;
3789