Debian Codegraph @

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

raw
1 #charset "us-ascii"
2
3 /*
4 * Copyright (c) 2000, 2006 Michael J. Roberts. All Rights Reserved.
5 *
6 * TADS 3 Library - actors
7 *
8 * This module provides definitions related to actors, which represent
9 * characters in the game.
10 */
11
12 /* include the library header */
13 #include "adv3.h"
14
15
16 /* ------------------------------------------------------------------------ */
17 /*
18 * Implied command modes
19 */
20 enum ModePlayer, ModeNPC;
21
22
23 /* ------------------------------------------------------------------------ */
24 /*
25 * A Topic is an object representing some piece of knowledge in the
26 * story. Actors can use Topic objects in commands such as "ask" and
27 * "tell".
28 *
29 * A physical simulation object can be a Topic through multiple
30 * inheritance. In addition, a game can define Topic objects for
31 * abstract conversation topics that don't correspond to simulation
32 * objects; for example, a topic could be created for "the meaning of
33 * life" to allow a command such as "ask guru about meaning of life."
34 *
35 * The key distinction between Topic objects and regular objects is that
36 * a Topic can represent an abstract, non-physical concept that isn't
37 * connected to any "physical" object in the simulation.
38 */
39 class Topic: VocabObject
40 /*
41 * Is the topic known? If this is true, the topic is in scope for
42 * actions that operate on topics, such as "ask about" and "tell
43 * about." If this is nil, the topic isn't known.
44 *
45 * By default, we mark all topics as known to begin with, which
46 * allows discussion of any topic at any time. Some authors prefer
47 * to keep track of which topics the player character actually has
48 * reason to know about within the context of the game, making topics
49 * available for conversation only after they become known for some
50 * good reason, such as another character mentioning them in
51 * conversation.
52 *
53 * Note that, as with Thing.isKnown, this is only the DEFAULT 'known'
54 * property. Each actor can have its own separate 'known' property
55 * by defining the actor's 'knownProp' to a different property name.
56 */
57 isKnown = true
58
59 /*
60 * Topics are abstract objects, so they can't be sensed with any of
61 * the physical senses, even if they're ever included as part of a
62 * containment hierarchy (which might be convenient in some cases
63 * for purposes of associating a topic with a physical object, for
64 * example).
65 */
66 canBeSensed(sense, trans, ambient) { return nil; }
67
68 /* a topic cannot by default be used to resolve a possessive phrase */
69 canResolvePossessive = nil
70 ;
71
72
73 /* ------------------------------------------------------------------------ */
74 /*
75 * FollowInfo - this is an object that tracks an actor's knowledge of
76 * the objects that the actor can follow, which are objects that actor
77 * has witnessed leaving the current location. We keep track of each
78 * followable object and the direction we saw it depart.
79 */
80 class FollowInfo: object
81 /* the object we can follow */
82 obj = nil
83
84 /* the TravelConnector the object traversed to leave */
85 connector = nil
86
87 /*
88 * The source location - this is the location we saw the object
89 * depart. We keep track of this because an actor can follow an
90 * object only if the actor is starting from the same location where
91 * the actor saw the object depart.
92 */
93 sourceLocation = nil
94 ;
95
96
97 /* ------------------------------------------------------------------------ */
98 /*
99 * Postures. A posture describes how an actor is internally positioned:
100 * standing, lying, sitting. We represent postures with objects of
101 * class Posture to make it easier to add new game-specific postures.
102 */
103 class Posture: object
104 /*
105 * Try getting the current actor into this posture within the given
106 * location, by running an appropriate implied command.
107 */
108 tryMakingPosture(loc) { }
109
110 /* put the actor into our posture via a nested action */
111 setActorToPosture(actor, loc) { }
112 ;
113
114 /*
115 * Standing posture - this is the default posture, which an actor
116 * normally uses for travel. Actors are generally in this posture any
117 * time they are not sitting on something, lying on something, or
118 * similar.
119 */
120 standing: Posture
121 tryMakingPosture(loc) { return tryImplicitAction(StandOn, loc); }
122 setActorToPosture(actor, loc) { nestedActorAction(actor, StandOn, loc); }
123 ;
124
125 /*
126 * Sitting posture.
127 */
128 sitting: Posture
129 tryMakingPosture(loc) { return tryImplicitAction(SitOn, loc); }
130 setActorToPosture(actor, loc) { nestedActorAction(actor, SitOn, loc); }
131 ;
132
133 /*
134 * Lying posture.
135 */
136 lying: Posture
137 tryMakingPosture(loc) { return tryImplicitAction(LieOn, loc); }
138 setActorToPosture(actor, loc) { nestedActorAction(actor, LieOn, loc); }
139 ;
140
141
142 /* ------------------------------------------------------------------------ */
143 /*
144 * Conversation manager output filter. We look for special tags in the
145 * output stream:
146 *
147 * <.reveal key> - add 'key' to the knowledge token lookup table. The
148 * 'key' is an arbitrary string, which we can look up in the table to
149 * determine if the key has even been revealed. This can be used to make
150 * a response conditional on another response having been displayed,
151 * because the key will only be added to the table when the text
152 * containing the <.reveal key> sequence is displayed.
153 *
154 * <.convnode name> - switch the current responding actor to conversation
155 * node 'name'.
156 *
157 * <.convstay> - keep the responding actor in the same conversation node
158 * as it was in at the start of the current response
159 *
160 * <.topics> - schedule a topic inventory for the end of the turn (just
161 * before the next command prompt)
162 */
163 conversationManager: OutputFilter, PreinitObject
164 /*
165 * Custom extended tags. Games and library extensions can add their
166 * own tag processing as needed, by using 'modify' to extend this
167 * object. There are two things you have to do to add your own tags:
168 *
169 * First, add a 'customTags' property that defines a regular
170 * expression for your added tags. This will be incorporated into
171 * the main pattern we use to look for tags. Simply specify a
172 * string that lists your tags separated by "|" characters, like
173 * this:
174 *
175 * customTags = 'foo|bar'
176 *
177 * Second, define a doCustomTag() method to process the tags. The
178 * filter routine will call your doCustomTag() method whenever it
179 * finds one of your custom tags in the output stream.
180 */
181 customTags = nil
182 doCustomTag(tag, arg) { /* do nothing by default */ }
183
184 /* filter text written to the output stream */
185 filterText(ostr, txt)
186 {
187 local start;
188
189 /* scan for our special tags */
190 for (start = 1 ; ; )
191 {
192 local match;
193 local arg;
194 local actor;
195 local sp;
196 local tag;
197 local nxtOfs;
198
199 /* scan for the next tag */
200 match = rexSearch(tagPat, txt, start);
201
202 /* if we didn't find it, we're done */
203 if (match == nil)
204 break;
205
206 /* note the next offset */
207 nxtOfs = match[1] + match[2];
208
209 /* get the argument (the third group from the match) */
210 arg = rexGroup(3);
211 if (arg != nil)
212 arg = arg[3];
213
214 /* pick out the tag */
215 tag = rexGroup(1)[3].toLower();
216
217 /* check which tag we have */
218 switch (tag)
219 {
220 case 'reveal':
221 /* reveal the key by adding it to our database */
222 setRevealed(arg);
223 break;
224
225 case 'convbegin':
226 /*
227 * Internal tag - starting a conversational response for
228 * an actor, identified by an index in our idToActor
229 * vector. Get the actor.
230 */
231 actor = idToActor[toInteger(arg)];
232
233 /*
234 * since we're just starting a response, clear the flag
235 * in the actor indicating that a ConvNode has been set
236 * in the course of this response
237 */
238 actor.responseSetConvNode = nil;
239
240 /* remember the new responding actor */
241 respondingActor = actor;
242
243 /* done */
244 break;
245
246 case 'convend':
247 /*
248 * Ending a conversational response for a given actor,
249 * identified by the first argument, which is an index in
250 * our idToActor vector.
251 */
252 sp = arg.find(' ');
253 actor = idToActor[toInteger(arg.substr(1, sp - 1))];
254
255 /* the rest of the argument is the default new ConvNode */
256 arg = arg.substr(sp + 1);
257
258 /* if the new ConvNode is empty, it means no ConvNode */
259 if (arg == '')
260 arg = nil;
261
262 /*
263 * if we didn't explicitly set a new ConvNode in the
264 * course of this response, apply the default
265 */
266 if (!actor.responseSetConvNode)
267 actor.setConvNodeReason(arg, 'convend');
268
269 /*
270 * Since we've just finished showing a message that
271 * specifically refers to this actor, the player should
272 * be able to refer to this actor using a pronoun on the
273 * next command. Set the responding actor as the
274 * antecedent for the appropriate singular pronouns for
275 * the player character. Note that we do this at the end
276 * of the response, so that the antecedent is the last
277 * one if we have more than one.
278 */
279 gPlayerChar.setPronounObj(actor);
280
281 /* done */
282 break;
283
284 case 'convnode':
285 /*
286 * If there's a current responding actor, set its current
287 * conversation node.
288 */
289 if (respondingActor != nil)
290 {
291 /*
292 * Set the new node. While we're working, capture
293 * any output that occurs so that we can insert it
294 * into the output stream just after the <.convnode>
295 * tag, so that any text displayed within the
296 * ConvNode's activation method (noteActive) is
297 * displayed in the proper order.
298 */
299 local ctxt = mainOutputStream.captureOutput(
300 {: respondingActor.setConvNodeReason(arg, 'convnode') });
301
302 /* re-insert any text we captured */
303 txt = txt.substr(1, nxtOfs - 1)
304 + ctxt
305 + txt.substr(nxtOfs);
306 }
307 break;
308
309 case 'convstay':
310 /*
311 * leave the responding actor in the old conversation
312 * node - we don't need to change the ConvNode, but we do
313 * need to note that we've explicitly set it
314 */
315 if (respondingActor != nil)
316 respondingActor.responseSetConvNode = true;
317 break;
318
319 case 'topics':
320 /* schedule a topic inventory listing */
321 scheduleTopicInventory();
322 break;
323
324 default:
325 /* check for an extended tag */
326 doCustomTag(tag, arg);
327 break;
328 }
329
330 /* continue the search after this match */
331 start = nxtOfs;
332 }
333
334 /*
335 * remove the tags from the text by replacing every occurrence
336 * with an empty string, and return the result
337 */
338 return rexReplace(tagPat, txt, '', ReplaceAll);
339 }
340
341 /* regular expression pattern for our tags */
342 tagPat = static new RexPattern(
343 '<nocase><langle><dot>'
344 + '(reveal|convbegin|convend|convnode|convstay|topics'
345 + (customTags != nil ? '|' + customTags : '')
346 + ')'
347 + '(<space>+(<^rangle>+))?'
348 + '<rangle>')
349
350 /*
351 * Schedule a topic inventory request. Game code can call this at
352 * any time to request that the player character's topic inventory
353 * be shown automatically just before the next command prompt. In
354 * most cases, game code won't call this directly, but will request
355 * the same effect using the <.topics> tag in topic response text.
356 */
357 scheduleTopicInventory()
358 {
359 /* note that we have a request for a prompt-time topic inventory */
360 pendingTopicInventory = true;
361 }
362
363 /*
364 * Show or schedule a topic inventory request. If the current
365 * action has a non-default command report, schedule it; otherwise,
366 * show it now.
367 *
368 * If there's a non-default report, don't suggest the topics now;
369 * instead, schedule a topic inventory for the end of the turn.
370 * When we have a non-default report, the report could change the
371 * ConvNode for the actor, so we don't want to show the topic
372 * inventory until we've had a chance to process all of the reports.
373 */
374 showOrScheduleTopicInventory(actor, otherActor)
375 {
376 /* check for a non-default command report in the current action */
377 if (gTranscript.currentActionHasReport(
378 {x: x.ofKind(MainCommandReport)}))
379 {
380 /* we have a non-default report - defer the topic inventory */
381 scheduleTopicInventory();
382 }
383 else
384 {
385 /* we have only a default report, so show the inventory now */
386 actor.suggestTopicsFor(otherActor, nil);
387 }
388 }
389
390 /*
391 * Note that an actor is about to give a response through a
392 * TopicEntry object. We'll remember the actor so that we'll know
393 * which actor is involved in a <.convnode> operation.
394 */
395 beginResponse(actor)
396 {
397 /* if the actor doesn't have an ID yet, assign one */
398 if (actor.convMgrID == nil)
399 {
400 /* add the actor to our vector of actors */
401 idToActor.append(actor);
402
403 /* the ID is simply the index in this vector */
404 actor.convMgrID = idToActor.length();
405 }
406
407 /* output a <.convbegin> for the actor */
408 gTranscript.addReport(new ConvBeginReport(actor.convMgrID));
409 }
410
411 /*
412 * Finish the response - call this after we finish handling the
413 * response. There must be a subsequent matching call to this
414 * routine whenever beginResponse() is called.
415 *
416 * 'node' is the default new ConvNode the actor for the responding
417 * actor. If another ConvNode was explicitly set in the course of
418 * handling the response, this is ignored, since the explicit
419 * setting overrides this default.
420 */
421 finishResponse(actor, node)
422 {
423 local prv;
424 local oldNode;
425
426 /* if the node is a ConvNode object, use its name */
427 if (node != nil && node.ofKind(ConvNode))
428 node = node.name;
429
430 /*
431 * if the previous report was our ConvBeginReport, the
432 * conversation display was empty, so ignore the whole thing
433 */
434 if ((prv = gTranscript.getLastReport()) != nil
435 && prv.ofKind(ConvBeginReport)
436 && prv.actorID == actor.convMgrID)
437 {
438 /* remove the <.convbegin> report - we're canceling it out */
439 gTranscript.deleteLastReport();
440
441 /* we're done - do not generate the <.convend> */
442 return;
443 }
444
445 /*
446 * if the actor has a current ConvNode, and our default next
447 * node is nil, and the current node is marked as "sticky," stay
448 * in the current node rather than switching to a nil default
449 */
450 if (node == nil
451 && (oldNode = actor.curConvNode) != nil
452 && oldNode.isSticky)
453 {
454 /* it's sticky, so stay at this node */
455 node = oldNode.name;
456 }
457
458 /* output a <.convend> for the actor */
459 gTranscript.addReport(new ConvEndReport(actor.convMgrID, node));
460 }
461
462 /*
463 * The current responding actor. Actors should set this when they're
464 * about to show a response to an ASK, TELL, etc.
465 */
466 respondingActor = nil
467
468 /*
469 * Mark a tag as revealed. This adds an entry for the tag to the
470 * revealedNameTab table. We simply set the table entry to 'true';
471 * the presence of the tag in the table constitutes the indication
472 * that the tag has been revealed.
473 *
474 * (Games and library extensions can use 'modify' to override this
475 * and store more information in the table entry. For example, you
476 * could store the time when the information was first revealed, or
477 * the location where it was learned. If you do override this, just
478 * be sure to set the revealedNameTab entry for the tag to a non-nil
479 * and non-zero value, so that any code testing the presence of the
480 * table entry will see that the slot is indeed set.)
481 */
482 setRevealed(tag)
483 {
484 revealedNameTab[tag] = true;
485 }
486
487 /*
488 * The global lookup table of all revealed keys. This table is keyed
489 * by the string naming the revelation; the value associated with
490 * each key is not used (we always just set it to true).
491 */
492 revealedNameTab = static new LookupTable(32, 32)
493
494 /* a vector of actors, indexed by their convMgrID values */
495 idToActor = static new Vector(32)
496
497 /* preinitialize */
498 execute()
499 {
500 /* add every ConvNode object to our master table */
501 forEachInstance(ConvNode,
502 { obj: obj.getActor().convNodeTab[obj.name] = obj });
503
504 /*
505 * set up the prompt daemon that makes automatic topic inventory
506 * suggestions when appropriate
507 */
508 new PromptDaemon(self, &topicInventoryDaemon);
509 }
510
511 /*
512 * Prompt daemon: show topic inventory when appropriate. When a
513 * response explicitly asks us to show a topic inventory using the
514 * <.topics> tag, or when other game code asks us to show topic
515 * inventory by calling scheduleTopicInventory(), we'll show the
516 * inventory just before the command input prompt.
517 */
518 topicInventoryDaemon()
519 {
520 /* if we have a topic inventory scheduled, show it now */
521 if (pendingTopicInventory)
522 {
523 /*
524 * Show the player character's topic inventory. This is not
525 * an explicit inventory request, since the player didn't ask
526 * for it.
527 */
528 gPlayerChar.suggestTopics(nil);
529
530 /* we no longer have a pending inventory request */
531 pendingTopicInventory = nil;
532 }
533 }
534
535 /* flag: we have a pending prompt-time topic inventory request */
536 pendingTopicInventory = nil
537 ;
538
539 /* ------------------------------------------------------------------------ */
540 /*
541 * A plug-in topic database. The topic database is a set of TopicEntry
542 * objects that specify the responses to queries on particular topics.
543 * The exact nature of the queries that a particular topic database
544 * handles is up to the database subclass to define; we just provide the
545 * abstract mechanism for finding and displaying responses.
546 *
547 * This is a "plug-in" database in that it's meant to be added into other
548 * classes using multiple inheritance. This isn't meant to be used as a
549 * stand-alone abstract topic entry container.
550 */
551 class TopicDatabase: object
552 /*
553 * Is the topic group active? A TopicEntry always checks with its
554 * container to see if the children of the container are active. By
555 * default, everything in the database is active.
556 */
557 topicGroupActive = true
558
559 /*
560 * Get the score adjustment for all topic entries contained within.
561 * The default adjustment is zero; TopicGroup objects can use this to
562 * adjust the score for their nested entries.
563 */
564 topicGroupScoreAdjustment = 0
565
566 /*
567 * Handle a topic. Look up the topic in our topic list for the
568 * given conversational action type. If we find a match, we'll
569 * invoke the matching topic list entry to handle it. We'll return
570 * true if we find a match, nil if not.
571 */
572 handleTopic(fromActor, topic, convType, path)
573 {
574 local resp;
575
576 /* find the best response */
577 resp = findTopicResponse(fromActor, topic, convType, path);
578
579 /* if we found a match, let it handle the topic */
580 if (resp != nil)
581 {
582 /* show the response */
583 showTopicResponse(fromActor, topic, resp);
584
585 /* tell the caller we handled it */
586 return true;
587 }
588 else
589 {
590 /* tell the caller we didn't handle it */
591 return nil;
592 }
593 }
594
595 /* show the response we found for a topic */
596 showTopicResponse(fromActor, topic, resp)
597 {
598 /* let the response object handle it */
599 resp.handleTopic(fromActor, topic);
600 }
601
602 /*
603 * find the best response (a TopicEntry object) for the given topic
604 * (a ResolvedTopic object)
605 */
606 findTopicResponse(fromActor, topic, convType, path)
607 {
608 local topicList;
609 local best, bestScore;
610
611 /*
612 * Get the list of possible topics for this conversation type.
613 * The topic list is contained in one of our properties; exactly
614 * which property is determined by the conversation type.
615 */
616 topicList = self.(convType.topicListProp);
617
618 /* if the topic list is nil, we obviously won't find the topic */
619 if (topicList == nil)
620 return nil;
621
622 /* scan our topic list for the best match(es) */
623 best = new Vector();
624 bestScore = nil;
625 foreach (local cur in topicList)
626 {
627 /* get this item's score */
628 local score = cur.adjustScore(cur.matchTopic(fromActor, topic));
629
630 /*
631 * If this item has a score at all, and the topic entry is
632 * marked as active, and it's best (or only) score so far,
633 * note it. Ignore topics marked as not active, since
634 * they're in the topic database only provisionally.
635 */
636 if (score != nil
637 && cur.checkIsActive()
638 && (bestScore == nil || score >= bestScore))
639 {
640 /* clear the vector if we've found a better score */
641 if (bestScore != nil && score > bestScore)
642 best = new Vector();
643
644 /* add this match to the list of ties for this score */
645 best.append(cur);
646
647 /* note the new best score */
648 bestScore = score;
649 }
650 }
651
652 /*
653 * If the best-match list is empty, we have no matches. If
654 * there's just one match, we have a winner. If we found more
655 * than one match tied for first place, we need to pick one
656 * winner.
657 */
658 if (best.length() == 0)
659 {
660 /* no matches at all */
661 best = nil;
662 }
663 else if (best.length() == 1)
664 {
665 /* exactly one match - it's easy to pick the winner */
666 best = best[1];
667 }
668 else
669 {
670 /*
671 * We have multiple topics tied for first place. Run through
672 * the topic list and ask each topic to propose the winner.
673 */
674 local toks = topic.topicProd.getOrigTokenList().mapAll(
675 {x: getTokVal(x)});
676 local winner = nil;
677 foreach (local t in best)
678 {
679 /* ask this topic what it thinks the winner should be */
680 winner = t.breakTopicTie(best, topic, fromActor, toks);
681
682 /* if the topic had an opinion, we can stop searching */
683 if (winner != nil)
684 break;
685 }
686
687 /*
688 * If no one had an opinion, run through the list again and
689 * try to pick by vocabulary match strength. This is only
690 * possible when all of the topics are associated with
691 * simulation objects; if any topics have pattern matches, we
692 * can't use this method.
693 */
694 if (winner == nil)
695 {
696 local rWinner = nil;
697 foreach (local t in best)
698 {
699 /* get this topic's match object(s) */
700 local m = t.matchObj;
701 if (m == nil)
702 {
703 /*
704 * there's no match object - it's not comparable
705 * to others in terms of match strength, so we
706 * can't use this method to break the tie
707 */
708 winner = nil;
709 break;
710 }
711
712 /*
713 * If it's a list, search for an element with a
714 * ResolveInfo entry in the topic match, using the
715 * strongest match if we find more than one.
716 * Otherwise, just use the strength of this match.
717 */
718 local ri;
719 if (m.ofKind(Collection))
720 {
721 /* search for a ResolveInfo object */
722 foreach (local mm in m)
723 {
724 /* get this topic */
725 local riCur = topic.getResolveInfo(mm);
726
727 /* if this is the best match so far, keep it */
728 if (compareVocabMatch(riCur, ri) > 0)
729 ri = riCur;
730 }
731 }
732 else
733 {
734 /* get the ResolveInfo object */
735 ri = topic.getResolveInfo(m);
736 }
737
738 /*
739 * if we didn't find a match, we can't use this
740 * method to break the tie
741 */
742 if (ri == nil)
743 {
744 winner = nil;
745 break;
746 }
747
748 /*
749 * if this is the best match so far, elect it as the
750 * tentative winner
751 */
752 if (compareVocabMatch(ri, rWinner) > 0)
753 {
754 rWinner = ri;
755 winner = t;
756 }
757 }
758 }
759
760 /*
761 * if there's a tie-breaking winner, use it; otherwise just
762 * arbitrarily pick the first item in the list of ties
763 */
764 best = (winner != nil ? winner : best[1]);
765 }
766
767 /*
768 * If there's a hierarchical search path, AND this topic entry
769 * defines a deferToEntry() method, look for matches in the
770 * inferior databases on the path and check to see if we want to
771 * defer to one of them.
772 */
773 if (best != nil && path != nil && best.propDefined(&deferToEntry))
774 {
775 /* look for a match in each inferior database */
776 for (local i = 1, local len = path.length() ; i <= len ; ++i)
777 {
778 local inf;
779
780 /*
781 * Look up an entry in this inferior database. Pass in
782 * the remainder of the path, so that the inferior
783 * database can consider further deferral to its own
784 * inferior databases.
785 */
786 inf = path[i].findTopicResponse(fromActor, topic, convType,
787 path.sublist(i + 1));
788
789 /*
790 * if we found an entry in this inferior database, and
791 * our entry defers to the inferior entry, then ignore
792 * the match in our own database
793 */
794 if (inf != nil && best.deferToEntry(inf))
795 return nil;
796 }
797 }
798
799 /* return the best matching response object, if any */
800 return best;
801 }
802
803 /*
804 * Compare the vocabulary match strengths of two ResolveInfo objects,
805 * for the purposes of breaking ties in topic matching. Uses the
806 * usual comparison/sorting return value conventions: -1 means that a
807 * is weaker than b, 0 means they're equivalent, 1 means a is
808 * stronger than b.
809 */
810 compareVocabMatch(a, b)
811 {
812 /*
813 * If both are nil, they're equivalent. If one or the other is
814 * nil, the non-nil item is stronger.
815 */
816 if (a == nil && b == nil)
817 return 0;
818 if (a == nil)
819 return -1;
820 if (b == nil)
821 return 1;
822
823 /*
824 * Both are valid objects, so compare based on the vocabulary
825 * match flags.
826 */
827 local fa = a.flags_, fb = b.flags_;
828
829 /* check plural truncations - no plural truncation is better */
830 if ((fa & PluralTruncated) && !(fb & PluralTruncated))
831 return -1;
832 if (!(fa & PluralTruncated) && (fb & PluralTruncated))
833 return 1;
834
835 /* check any truncation - no truncation is better */
836 if ((fa & VocabTruncated) && !(fb & VocabTruncated))
837 return -1;
838 if (!(fa & VocabTruncated) && (fb & VocabTruncated))
839 return 1;
840
841 /* we can't find any reason to prefer one over the other */
842 return 0;
843 }
844
845 /* show our suggested topic list */
846 showSuggestedTopicList(lst, asker, askee, explicit)
847 {
848 /* get the asking actor's scope list for use later */
849 scopeList = asker.scopeList();
850
851 /* remove items that have redundant list groups and full names */
852 for (local i = 1, local len = lst.length() ; i <= len ; ++i)
853 {
854 local a = lst[i];
855
856 /* check for redundant elements */
857 for (local j = i + 1 ; j <= len ; ++j)
858 {
859 local b = lst[j];
860
861 /*
862 * If item 'a' matches item 'b', and both are active,
863 * remove item 'b'. We only need to remove redundant
864 items if they're both active, since inactive items
865 */
866 if (a.suggestionGroup == b.suggestionGroup
867 && a.fullName == b.fullName
868 && a.isSuggestionActive(asker, scopeList)
869 && b.isSuggestionActive(asker, scopeList))
870 {
871 /* delete item 'b' from the list */
872 lst.removeElementAt(j);
873
874 /* adjust our indices for the deletion */
875 --j;
876 --len;
877 }
878 }
879 }
880
881 /* show our list */
882 new SuggestedTopicLister(asker, askee, explicit)
883 .showList(asker, nil, lst, 0, 0, nil, nil);
884 }
885
886 /*
887 * Flag: this database level should limit topic suggestions (for the
888 * TOPICS and TALK TO commands) to its own topics, excluding any
889 * topics inherited from the "broader" context. If this property is
890 * set to true, then we won't include suggestions from any lower
891 * level of the database hierarchy. If this property is nil, we'll
892 * also include any topic suggestions from the broader context.
893 *
894 * Topic databases are arranged into a fixed hierarchy for an actor.
895 * At the top level is the current ConvNode object; at the next level
896 * is the ActorState; and at the bottom level is the Actor itself.
897 * So, if the ConvNode's limitSuggestions property is set to true,
898 * then the suggestions for the actor will include ONLY the ConvNode.
899 * If the ConvNode has the property set to nil, but the ActorState
900 * has it set to true, then we'll include the ConvNode and the
901 * ActorState suggestions.
902 *
903 * By default, we set this to nil. This should usually be set to
904 * true for any ConvNode or ActorState where the NPC won't allow the
905 * player to stray from the subject. For example, if a ConvNode only
906 * accepts a YES or NO response to a question, then this property
907 * should probably be set to true in the ConvNode, since other
908 * suggested topics won't be accepted as conversation topics as long
909 * as the ConvNode is active.
910 */
911 limitSuggestions = nil
912
913 /*
914 * Add a topic to our topic database. We'll add it to the
915 * appropriate list or lists as indicated in the topic itself.
916 * 'topic' is a TopicEntry object.
917 */
918 addTopic(topic)
919 {
920 /* add the topic to each list indicated in the topic */
921 foreach (local cur in topic.includeInList)
922 addTopicToList(topic, cur);
923 }
924
925 /* remove a topic from our topic database */
926 removeTopic(topic)
927 {
928 /* remove the topic from each of its lists */
929 foreach (local cur in topic.includeInList)
930 removeTopicFromList(topic, cur);
931 }
932
933 /* add a suggested topic */
934 addSuggestedTopic(topic)
935 {
936 /* add the topic to our suggestion list */
937 addTopicToList(topic, &suggestedTopics);
938 }
939
940 /* remove a suggested topic */
941 removeSuggestedTopic(topic)
942 {
943 /* add the topic to our suggestion list */
944 removeTopicFromList(topic, &suggestedTopics);
945 }
946
947 /*
948 * Add a topic to the given topic list. The topic list is given as a
949 * property point; for example, we'd specify &askTopics to add the
950 * topic to our ASK list.
951 */
952 addTopicToList(topic, listProp)
953 {
954 /* if we haven't created this topic list vector yet, create it now */
955 if (self.(listProp) == nil)
956 self.(listProp) = new Vector(8);
957
958 /* add the topic */
959 self.(listProp).append(topic);
960 }
961
962 /* remove a topic from the given topic list */
963 removeTopicFromList(topic, listProp)
964 {
965 /* if the list exists, remove the topic from it */
966 if (self.(listProp) != nil)
967 self.(listProp).removeElement(topic);
968 }
969
970 /*
971 * Our list of suggested topics. These are SuggestedTopic objects
972 * that describe things that another actor wants to ask or tell this
973 * actor about.
974 */
975 suggestedTopics = nil
976
977 /*
978 * Get the "owner" of the topics in this database. The meaning of
979 * "owner" varies according to the topic database type; for actor
980 * topic databases, for example, this is the actor. Generally, the
981 * owner is the object being queried about the topic, from the
982 * player's perspective. Each type of database should define this
983 * method to return the appropriate object.
984 */
985 getTopicOwner() { return nil; }
986 ;
987
988 /*
989 * A TopicDatabase for an Actor. This is used not only directly for an
990 * Actor but also for an actor's sub-databases, in ActorState and
991 * ConvNode.
992 *
993 * Actor topic databases field queries for the various types of
994 * topic-based interactions an actor can participate in: ASK, TELL, SHOW,
995 * GIVE, and so on.
996 *
997 * Each actor has its own topic database, which means each actor can have
998 * its own set of responses. Actor states can also have their own
999 * separate topic databases; this makes it easy to make an actor's
1000 * response to a particular question vary according to the actor's state.
1001 * Conversation nodes can also have their own separate databases, which
1002 * allows for things like threaded conversations.
1003 */
1004 class ActorTopicDatabase: TopicDatabase
1005 /*
1006 * Initiate conversation on the given simulation object. If we can
1007 * find an InitiateTopic matching the given object, we'll show its
1008 * topic response and return true; if we can't find a topic to
1009 * initiate, we'll simply return nil.
1010 */
1011 initiateTopic(obj)
1012 {
1013 /* find an initiate topic for the given object */
1014 if (handleTopic(gPlayerChar, obj, initiateConvType, nil))
1015 {
1016 /*
1017 * we handled the topic, so note that we're in conversation
1018 * with the player character now
1019 */
1020 getTopicOwner().noteConversation(gPlayerChar);
1021
1022 /* indicate that we found a topic to initiate */
1023 return true;
1024 }
1025
1026 /* we didn't find a topic to initiate */
1027 return nil;
1028 }
1029
1030 /* show a topic response */
1031 showTopicResponse(fromActor, topic, resp)
1032 {
1033 local actor = getTopicOwner();
1034 local newNode;
1035
1036 /*
1037 * note whether the response is conversational - we need to do
1038 * this ahead of time, since invoking the response can sometimes
1039 * have the side effect of changing the response's status
1040 */
1041 local isConv = resp.isConversational;
1042
1043 /* tell the conversation manager we're starting a response */
1044 conversationManager.beginResponse(actor);
1045
1046 /* let the response object handle it */
1047 resp.handleTopic(fromActor, topic);
1048
1049 /*
1050 * By default, after showing a response, we want to leave the
1051 * conversation node tree entirely if we didn't explicitly set
1052 * the next node in the course of the response. So, set the
1053 * default new node to 'nil'. However, if the topic is
1054 * non-conversational, it shouldn't affect the conversation
1055 * thread at all, so leave the current node unchanged.
1056 */
1057 if (isConv)
1058 newNode = nil;
1059 else
1060 newNode = actor.curConvNode;
1061
1062 /* tell the conversation manager we're done with the response */
1063 conversationManager.finishResponse(actor, newNode);
1064 }
1065
1066 /*
1067 * Our 'ask about', 'ask for', 'tell about', 'give', 'show',
1068 * miscellaneous, command, and self-initiated topic databases - these
1069 * are vectors we initialize as needed. Since every actor and every
1070 * actor state has its own separate topic database, it's likely that
1071 * the bulk of these databases will be empty, so we don't bother even
1072 * creating a vector for a topic list until the first topic is added.
1073 * This means we have to be able to cope with these being nil
1074 * anywhere we use them.
1075 */
1076 askTopics = nil
1077 askForTopics = nil
1078 tellTopics = nil
1079 showTopics = nil
1080 giveTopics = nil
1081 miscTopics = nil
1082 commandTopics = nil
1083 initiateTopics = nil
1084
1085 /* our special command database */
1086 specialTopics = nil
1087 ;
1088
1089 /* ------------------------------------------------------------------------ */
1090 /*
1091 * A "suggested" topic. These provide suggestions for things the player
1092 * might want to ASK or TELL another actor about. At certain times
1093 * (specifically, when starting a conversation with HELLO or TALK TO, or
1094 * when the player enters a TOPICS command to explicitly ask for a list
1095 * of topic suggestions), we'll look for these objects in the actor or
1096 * actor state for the actor to whom we're talking. We'll show a list
1097 * of each currently active suggestion we find. This gives the player
1098 * some guidance of what to talk about. For example:
1099 *
1100 * >talk to bob
1101 *. "Excuse me," you say.
1102 *
1103 * Bob looks up from his newspaper. "Yes? Oh, you again."
1104 *
1105 * (You'd like to ask him about the black book, the candle, and the
1106 * bell, and tell him about the crypt.)
1107 *
1108 * Topic suggestions are entirely optional. Some authors don't like the
1109 * idea, since they think it's too much like a menu system, and just
1110 * gives away the solution to the game. If you don't want to have
1111 * anything to do with topic suggestions, we won't force you - simply
1112 * don't define any SuggestedTopic objects, and the library will never
1113 * offer suggestions and will even disable the TOPICS command.
1114 *
1115 * If you do want to use topic suggestions, the easiest way to use this
1116 * class is to combine it using multiple inheritance with a TopicEntry
1117 * object. You just have to add SuggestedTopic to the superclass list
1118 * for your topic entry object, and give the suggested topic a name
1119 * string (using a property and format defined by the language-specific
1120 * library) to display in suggestions lists. Doing this, the suggestion
1121 * will automatically be enabled whenever the topic entry is available,
1122 * and will automatically be removed from the suggestions when the topic
1123 * is invoked in conversation (in other words, we'll only suggest asking
1124 * about the topic until it's been asked about once).
1125 *
1126 * Topic suggestions can be associated with an actor or an actor state;
1127 * these are topics that a given character would like to talk to the
1128 * associated actor about. The association is a bit tricky: suggested
1129 * topic objects are stored with the actor being *talked to*. For
1130 * example, if we want to suggest topics that the player character might
1131 * want to ASK BILL ABOUT, we store these suggestions with *Bill*. We
1132 * do NOT store the suggestions with the player character. This might
1133 * seem backwards at first glance, since fundamentally the suggestions
1134 * belong in the player character's "brain" - they are, after all,
1135 * things the player character wants to talk about. In practice,
1136 * though, there are two things that make it easier to keep the
1137 * information with the character being asked. First, in most games,
1138 * there's just one player character, so one of the two actors in each
1139 * association will always be the player character; by storing the
1140 * objects with the NPC, we can just let the PC be assumed as the other
1141 * actor as a default, saving us some typing that would be necessary if
1142 * we had to specify each object in the other direction. Second, we
1143 * keep the *response* objects associated with the character being asked
1144 * - that association is intuitive, at least. The thing is, we can
1145 * usually combine the suggestion and response into a single object,
1146 * saving another bunch of typing; if we didn't keep the suggestion with
1147 * the character being asked, we couldn't combine the suggestions and
1148 * responses this way, since they'd have to be associated with different
1149 * actors.
1150 */
1151 class SuggestedTopic: object
1152 /*
1153 * The name of the suggestion. The rules for setting this vary by
1154 * language; in the English version, we'll display the fullName when
1155 * we show a stand-alone item, and the groupName when we appear in a
1156 * list group (such as a group of ASK ABOUT or TELL ABOUT
1157 * suggestions).
1158 *
1159 * In English, the fullName should be suitable for use after
1160 * 'could': "You could <fullName>, <fullName>, or <fullName>".
1161 *
1162 * In English, the phrasing where the 'name' property is used
1163 * depends on the specific subclass, but it should usually be a
1164 * qualified noun phrase (that is, it should include a qualifier
1165 * such as "a" or "the" or a possessive). For ASK and TELL, for
1166 * example, the 'name' should be suitable for use after ABOUT: "You
1167 * could ask him about <the lighthouse>, <Bob's black book>, or <the
1168 * weather>."
1169 *
1170 * By default, we'll walk up our 'location' tree looking for another
1171 * suggested topic; if we find one, we'll use its corresponding name
1172 * values.
1173 */
1174 fullName = (fromEnclosingSuggestedTopic(&fullName, ''))
1175 name = (fromEnclosingSuggestedTopic(&name, ''))
1176
1177 /*
1178 * Our associated topic. In most cases, this will be initialized
1179 * automatically: if this suggested topic object is also a
1180 * TopicEntry object (using multiple inheritance), we'll set this
1181 * during start-up to 'self', or if our location is a TopicEntry,
1182 * we'll set this to our location. This only needs to be
1183 * initialized manually if neither of those conditions is true.
1184 */
1185 associatedTopic = nil
1186
1187 /*
1188 * Set the location to the actor to ask or tell about this topic.
1189 * This is the target of the ASK ABOUT or TELL ABOUT command, NOT
1190 * the actor who's doing the asking. This can also be set to a
1191 * TopicEntry object, in which case we'll be associated with the
1192 * actor with which the topic entry is associated, and we'll also
1193 * automatically tie the topic entry to this suggestion.
1194 *
1195 * Because we're using the location property, you can use the '+'
1196 * notation to add a suggested topic to the target actor, state
1197 * objects, or topic entry.
1198 */
1199 location = nil
1200
1201 /*
1202 * The actor who *wants* to ask or tell about this topic. Our
1203 * location property gives the actor to be asked or told, because
1204 * we're associated with the target actor - the same actor who has
1205 * the TopicEntry information for the topic. This property, in
1206 * contrast, gives the actor who's doing the asking.
1207 *
1208 * By default, we return the player character; in most cases, you
1209 * won't have to override this. In most games, only the player
1210 * character uses the suggested topic mechanism, because there's no
1211 * reason to suggest topics for NPC's - they're just automata, after
1212 * all, so if we want them to ask something, we can just program
1213 * them to ask it directly. Also, most games have only one player
1214 * character. Games that meet these criteria won't ever have to
1215 * override this. If you do have multiple player characters, you'll
1216 * probably want to override this for each suggested topic to
1217 * indicate which character wants to ask about the topic, as the
1218 * different player characters might have different things they'd
1219 * want to talk about.
1220 */
1221 suggestTo = (gPlayerChar)
1222
1223 /* the ListGroup with which we're to list this suggestion */
1224 suggestionGroup = []
1225
1226 /* find the nearest enclosing SuggestedTopic parent */
1227 findEnclosingSuggestedTopic()
1228 {
1229 /* walk up our location list */
1230 for (local loc = location ; loc != nil ; loc = loc.location)
1231 {
1232 /* if this is a suggested topic, it's what we're looking for */
1233 if (loc.ofKind(SuggestedTopic))
1234 return loc;
1235 }
1236
1237 /* didn't find anything */
1238 return nil;
1239 }
1240
1241 /* find the outermost enclosing SuggestedTopic parent */
1242 findOuterSuggestedTopic()
1243 {
1244 local outer;
1245
1246 /* walk up our location list */
1247 for (local loc = self, outer = nil ; loc != nil ; loc = loc.location)
1248 {
1249 /* if this is a suggested topic, it's the outermost so far */
1250 if (loc.ofKind(SuggestedTopic))
1251 outer = loc;
1252 }
1253
1254 /* return the outermost suggested topic we found */
1255 return outer;
1256 }
1257
1258 /*
1259 * get a property from the nearest enclosing SuggestedTopic, or
1260 * return the given default value if there is no enclosing
1261 * SuggestedTopic
1262 */
1263 fromEnclosingSuggestedTopic(prop, defaultVal)
1264 {
1265 /* look for the nearest enclosing suggested topic */
1266 local enc = findEnclosingSuggestedTopic();
1267
1268 /*
1269 * return the desired property from the enclosing suggested
1270 * topic object if we found one, or the default if there is no
1271 * enclosing object
1272 */
1273 return (enc != nil ? enc.(prop) : defaultVal);
1274 }
1275
1276 /*
1277 * Should we suggest this topic to the given actor? We'll return
1278 * true if the actor is the same actor for which this suggestion is
1279 * intended, and the associated topic entry is currently active, and
1280 * we haven't already satisfied our curiosity about the topic.
1281 */
1282 isSuggestionActive(actor, scopeList)
1283 {
1284 /*
1285 * Check to see if this is our target actor; that the associated
1286 * topic itself is active; that our curiosity hasn't already been
1287 * satisfied; and that it's at least possible to match the
1288 * associated topic right now. If all of these conditions are
1289 * met, we can make this suggestion.
1290 */
1291 return (actor == suggestTo
1292 && associatedTopicIsActive()
1293 && associatedTopicCanMatch(actor, scopeList)
1294 && !curiositySatisfied);
1295 }
1296
1297 /*
1298 * The number of times to suggest asking about our topic. When
1299 * we've asked about our associated topic this many times, we'll
1300 * have satisfied our curiosity. In most cases, we'll only want to
1301 * suggest a topic until it's asked about once, since most topics
1302 * only have a single meaningful response, so we'll use 1 as the
1303 * default. This should be overridden in cases where a topic will
1304 * reveal more information when asked several times. If this is
1305 * nil, it means that there's no limit to the number of times to
1306 * suggest asking about this.
1307 */
1308 timesToSuggest = 1
1309
1310 /*
1311 * Have we satisfied our curiosity about this topic? Returns true
1312 * if so, nil if not. We'll never suggest a topic when this returns
1313 * true, because this means that the player no longer feels the need
1314 * to ask about the topic.
1315 */
1316 curiositySatisfied = (timesToSuggest != nil
1317 && associatedTopicTalkCount() >= timesToSuggest)
1318
1319 /* initialize - this is called automatically during pre-initialization */
1320 initializeSuggestedTopic()
1321 {
1322 /* if we have a location, link up with our location */
1323 if (location != nil)
1324 location.addSuggestedTopic(self);
1325
1326 /*
1327 * if we're also a TopicEntry (using multiple inheritance), then
1328 * we are our own associated topic object
1329 */
1330 if (ofKind(TopicEntry))
1331 associatedTopic = self;
1332 }
1333
1334 /*
1335 * Methods that rely on the associated topic. We isolate these in a
1336 * few methods here so that the rest of class doesn't depend on the
1337 * exact nature of our topic association. In particular, this allows
1338 * for subclasses that don't have an associated topic at all, or that
1339 * have multiple associated topics. Subclasses with specialized
1340 * topic relationships can simply override these methods to define
1341 * these methods appropriately.
1342 */
1343
1344 /* is the associated topic active? */
1345 associatedTopicIsActive() { return associatedTopic.checkIsActive(); }
1346
1347 /* get the number of previous invocations of the associated topic */
1348 associatedTopicTalkCount() { return associatedTopic.talkCount; }
1349
1350 /* is it possible to match the associated topic? */
1351 associatedTopicCanMatch(actor, scopeList)
1352 { return associatedTopic.isMatchPossible(actor, scopeList); }
1353
1354 /*
1355 * Note that we're being shown in a topic inventory listing. By
1356 * default, we don't do anything here, but subclasses can use this to
1357 * do any extra work they want to do on being listed.
1358 */
1359 noteSuggestion() { }
1360 ;
1361
1362 /*
1363 * A suggested topic that applies to an entire AltTopic group.
1364 *
1365 * Normally, a suggestion is tied to an individual TopicEntry. This
1366 * means that when a topic has several AltTopic alternatives, each
1367 * AltTopic can be its own separate, independent suggestion. A
1368 * particular alternative can be a suggestion or not, independently of
1369 * the other alternatives for the same TopicEntry. Since each AltTopic
1370 * is a separate suggestion, asking about one of the alternatives won't
1371 * have any effect on the "curiosity" about the other alternatives - in
1372 * other words, the other alternatives will be separately suggested when
1373 * they become active.
1374 *
1375 * In many cases, it's better for an entire set of alternatives to be
1376 * treated as a single suggested topic. That is, we want to suggest the
1377 * topic when ANY of the alternatives is active, and asking about any one
1378 * of the alternatives will satisfy the PC's curiosity for ALL of the
1379 * alternatives. This sort of arrangement is usually better for cases
1380 * where the conditions that trigger the different alternatives aren't
1381 * things that ought to make the PC think to ask the same question again.
1382 *
1383 * Use this class by associating it with the *root* TopicEntry of the
1384 * group of alternatives. You can do this most simply by mixing this
1385 * class into the superclass list of the root TopicEntry:
1386 *
1387 *. + AskTellTopic, SuggestedTopicTree, SuggestedAskTopic
1388 *. // ...
1389 *. ;
1390 * ++ AltTopic ... ;
1391 * ++ AltTopic ... ;
1392 *
1393 * This makes the entire group of AltTopics part of the same suggestion.
1394 * Note that you must *also* include SuggestedAsk, SuggestedTellTopic, or
1395 * one of the other specialized types among the superclass, to indicate
1396 * which kind of suggestion this is.
1397 */
1398 class SuggestedTopicTree: SuggestedTopic
1399 /* is the associated topic active? */
1400 associatedTopicIsActive()
1401 {
1402 /* the topic is active if anything in the AltTopic group is active */
1403 return associatedTopic.anyAltIsActive;
1404 }
1405
1406 /* get the number of previous invocations of the associated topic */
1407 associatedTopicTalkCount()
1408 {
1409 /* return the number of invocations of any alternative */
1410 return associatedTopic.altTalkCount;
1411 }
1412 ;
1413
1414 /*
1415 * A suggested ASK ABOUT topic. We'll list ASK ABOUT topics together in
1416 * a subgroup ("you'd like to ask him about the book, the candle, and
1417 * the bell...").
1418 */
1419 class SuggestedAskTopic: SuggestedTopic
1420 suggestionGroup = [suggestionAskGroup]
1421 ;
1422
1423 /*
1424 * A suggested TELL ABOUT topic. We'll list TELL ABOUT topics together
1425 * in a subgroup.
1426 */
1427 class SuggestedTellTopic: SuggestedTopic
1428 suggestionGroup = [suggestionTellGroup]
1429 ;
1430
1431 /*
1432 * A suggested ASK FOR topic. We'll list ASK FOR topics together as a
1433 * group.
1434 */
1435 class SuggestedAskForTopic: SuggestedTopic
1436 suggestionGroup = [suggestionAskForGroup]
1437 ;
1438
1439 /*
1440 * A suggested GIVE TO topic.
1441 */
1442 class SuggestedGiveTopic: SuggestedTopic
1443 suggestionGroup = [suggestionGiveGroup]
1444 ;
1445
1446 /*
1447 * A suggested SHOW TO topic.
1448 */
1449 class SuggestedShowTopic: SuggestedTopic
1450 suggestionGroup = [suggestionShowGroup]
1451 ;
1452
1453 /*
1454 * A suggested YES/NO topic
1455 */
1456 class SuggestedYesTopic: SuggestedTopic
1457 suggestionGroup = [suggestionYesNoGroup]
1458 ;
1459 class SuggestedNoTopic: SuggestedTopic
1460 suggestionGroup = [suggestionYesNoGroup]
1461 ;
1462
1463 /* ------------------------------------------------------------------------ */
1464 /*
1465 * A conversation node. Conversation nodes are supplemental topic
1466 * databases that represent a point in time in a conversation - a
1467 * particular context that arises from what came immediately before in
1468 * the conversation. A conversation node is used to set up a group of
1469 * special responses that make sense only in a momentary context within a
1470 * conversation.
1471 *
1472 * A ConvNode object must be nested (via the 'location' property) within
1473 * an actor or an ActorState. This is how we associate the ConvNode with
1474 * its actor. Note that putting a ConvNode inside an ActorState doesn't
1475 * do anything different from putting the node directly inside the
1476 * ActorState's actor - we allow it only for convenience, to allow
1477 * greater flexibility arranging source code.
1478 */
1479 class ConvNode: ActorTopicDatabase
1480 /*
1481 * Every ConvNode must have a name property. This is a string
1482 * identifying the object. Use this name string instead of a regular
1483 * object name (so ConvNode instances can essentially always be
1484 * anonymous, as far as the compiler is concerned). This string is
1485 * used to find the ConvNode in the master ConvNode database
1486 * maintained in the conversationManager object.
1487 *
1488 * A ConvNode name should be unique with respect to all other
1489 * ConvNode objects - no two ConvNode objects should have the same
1490 * name string. Other than this, the name strings are arbitrary.
1491 * (However, they shouldn't contain any '>' characters, because this
1492 * would prevent them from being used in <.convnode> tags, which is
1493 * the main place ConvNode's are usually used.)
1494 */
1495 name = ''
1496
1497 /*
1498 * Is this node "sticky"? If so, we'll stick to this node if we
1499 * show a response that doesn't set a new node. By default, we're
1500 * not sticky, so if we show a response that doesn't set a new node
1501 * and doesn't use a <.convstay> tag, we'll simply forget the node
1502 * and set the actor to no current ConvNode.
1503 *
1504 * Sticky nodes are useful when you want the actor to stay
1505 * on-subject even when the player digresses to talk about other
1506 * things. This is useful when the actor has a particular thread
1507 * they want to drive the conversation along.
1508 */
1509 isSticky = nil
1510
1511 /*
1512 * Show our NPC-initiated greeting. This is invoked when our actor's
1513 * initiateConversation() method is called to cause our actor to
1514 * initiate a conversation with the player character. This method
1515 * should show what our actor says to initiate the conversation. By
1516 * default, we'll invoke our npcGreetingList's script, if the
1517 * property is non-nil.
1518 *
1519 * A greeting should always be defined for any ConvNode that's used
1520 * in an initiateConversation() call.
1521 *
1522 * To define a greeting when defining a ConvNode, you can override
1523 * this method with a simple double-quoted string message, or you can
1524 * define an npcGreetingList property as an EventList of some kind.
1525 */
1526 npcGreetingMsg()
1527 {
1528 /* if we have an npcGreetingList property, invoke the script */
1529 if (npcGreetingList != nil)
1530 npcGreetingList.doScript();
1531 }
1532
1533 /* an optional EventList containing our NPC-initiated greetings */
1534 npcGreetingList = nil
1535
1536 /*
1537 * Our NPC-initiated conversation continuation message. This is
1538 * invoked on each turn (during the NPC's takeTurn() daemon
1539 * processing) that we're in this conversation node and the player
1540 * character doesn't do anything conversational. This allows the NPC
1541 * to carry on the conversation of its own volition. Define this as
1542 * a double-quoted string if you want the NPC to say something to
1543 * continue the conversation.
1544 */
1545 npcContinueMsg = nil
1546
1547 /*
1548 * An optional EventList containing NPC-initiated continuation
1549 * messages. You can define an EventList here instead of defining
1550 * npcContinueMsg, if you want more than one continuation message.
1551 */
1552 npcContinueList = nil
1553
1554 /*
1555 * Flag: automatically show a topic inventory on activating this
1556 * conversation node. Some conversation nodes have sufficiently
1557 * obscure entries that it's desirable to show a topic inventory
1558 * automatically when the node becomes active.
1559 *
1560 * By default, we automatically show a topic inventory if the node
1561 * contains an active SpecialTopic entry. Since special topics are
1562 * inherently obscure, in that they use non-standard commands, we
1563 * always want to show topics when one of these becomes active.
1564 */
1565 autoShowTopics()
1566 {
1567 /* if we have an active special topic, show the topic inventory */
1568 return (specialTopics != nil
1569 && specialTopics.indexWhich({x: x.checkIsActive()}) != nil);
1570 }
1571
1572 /* our NPC is initiating a conversation starting with this node */
1573 npcInitiateConversation()
1574 {
1575 local actor = getActor();
1576
1577 /* tell the conversation manager we're the actor who's talking */
1578 conversationManager.beginResponse(actor);
1579
1580 /* note that we're in conversation with the player character now */
1581 getActor().noteConversation(gPlayerChar);
1582
1583 /* show our NPC greeting */
1584 npcGreetingMsg();
1585
1586 /* look for an ActorHelloTopic within the node */
1587 handleTopic(gPlayerChar, actorHelloTopicObj, helloConvType, nil);
1588
1589 /* end the response, staying in the current ConvNode by default */
1590 conversationManager.finishResponse(actor, self);
1591 }
1592
1593 /*
1594 * Continue the conversation of the NPC's own volition. Returns
1595 * true if we displayed anything, nil if not.
1596 */
1597 npcContinueConversation()
1598 {
1599 local actor = getActor();
1600 local disp;
1601
1602 /* tell the conversation manager we're starting a response */
1603 conversationManager.beginResponse(actor);
1604
1605 /* show our text, watching to see if we generate any output */
1606 disp = outputManager.curOutputStream.watchForOutput(function()
1607 {
1608 /*
1609 * if we have a continuation list, invoke it; otherwise if we
1610 * have a continuation message, show it; otherwise, just
1611 * return nil to let the caller know we have nothing to add
1612 */
1613 if (npcContinueList != nil)
1614 npcContinueList.doScript();
1615 else
1616 npcContinueMsg;
1617 });
1618
1619 /* end the response, staying in the current ConvNode by default */
1620 conversationManager.finishResponse(actor, self);
1621
1622 /*
1623 * if we actually said anything, note that we're in conversation
1624 * with the player character
1625 */
1626 if (disp)
1627 getActor().noteConversation(gPlayerChar);
1628
1629 /* return the display indication */
1630 return disp;
1631 }
1632
1633 /* our actor is our location, or our location's actor */
1634 getActor()
1635 {
1636 /* if our location is an actor state, return the state's actor */
1637 if (location.ofKind(ActorState))
1638 return location.getActor();
1639
1640 /* otherwise, our location must be our actor */
1641 return location;
1642 }
1643
1644 /* our actor is the "owner" of our topics */
1645 getTopicOwner() { return getActor(); }
1646
1647 /*
1648 * Handle a conversation topic. The actor state object will call
1649 * this to give the ConvNode the first crack at handling a
1650 * conversation command. We'll return true if we handle the command,
1651 * nil if not. Our default handling is to look up the topic in the
1652 * given database list property, and handle it through the TopicEntry
1653 * we find there, if any.
1654 */
1655 handleConversation(otherActor, topic, convType, path)
1656 {
1657 /* try handling it, returning the handled/not-handled result */
1658 return handleTopic(otherActor, topic, convType, path);
1659 }
1660
1661 /*
1662 * Can we end the conversation? If so, return true; our caller will
1663 * invoke our endConversation() to let us know that the conversation
1664 * is over.
1665 *
1666 * To prevent the conversation from ending, simply return nil.
1667 *
1668 * In most cases, you won't want to force the conversation to keep
1669 * going without any comment. Instead, you'll want to display some
1670 * message to let the player know what's going on - something like
1671 * "Hey! We're not through here!" If you do display a message, then
1672 * rather than returning nil, return the special value blockEndConv -
1673 * this tells the caller that the actor said something, so the caller
1674 * will call noteConvAction() to prevent further generated
1675 * conversation output on this same turn.
1676 *
1677 * 'reason' gives the reason the conversation is ending, as an
1678 * endConvXxx enum code.
1679 */
1680 canEndConversation(actor, reason) { return true; }
1681
1682 /*
1683 * Receive notification that our actor is ending a stateful
1684 * conversation. This is called before the normal
1685 * InConversationState disengagement operations. 'reason' is one of
1686 * the endConvXxx enums, indicating why the conversation is ending.
1687 *
1688 * Instances can override this for special behavior on terminating a
1689 * conversation. For example, an actor who just asked a question
1690 * could say something to indicate that the other actor is being
1691 * rude. By default, we do nothing.
1692 *
1693 * Note that there's no way to block the ending of the conversation
1694 * here. If you want to prevent the conversation from ending, use
1695 * canEndConversation() instead.
1696 */
1697 endConversation(actor, reason) { }
1698
1699 /*
1700 * Process a special command. Check the given command line string
1701 * against all of our topics, and see if we have a match to any topic
1702 * that takes a special command syntax. If we find a matching
1703 * special topic, we'll note the match, and turn the command into our
1704 * secret internal pseudo-command "XSPCLTOPIC". That command will
1705 * then go through the parser, which will recognize it and process it
1706 * using the normal conversational mechanisms, which will find the
1707 * SpecialTopic we noted earlier (in this method) and display its
1708 * response.
1709 *
1710 * 'str' is the original input string, exactly as entered by the
1711 * player, and 'procStr' is the "processed" version of the input
1712 * string. The nature of the processing varies by language, but
1713 * generally this involves things like removing punctuation marks and
1714 * any "noise words" that don't usually change the meaning of the
1715 * input, at least for the purposes of matching a special topic.
1716 */
1717 processSpecialCmd(str, procStr)
1718 {
1719 local match;
1720 local cnt;
1721
1722 /* we don't have an active special topic yet */
1723 activeSpecialTopic = nil;
1724
1725 /*
1726 * if we have no special topics, there's definitely no special
1727 * processing we need to do
1728 */
1729 if (specialTopics == nil)
1730 return str;
1731
1732 /* scan our special topics for a match */
1733 cnt = 0;
1734 foreach (local cur in specialTopics)
1735 {
1736 /* if this one is active, and it matches the string, note it */
1737 if (cur.checkIsActive() && cur.matchPreParse(str, procStr))
1738 {
1739 /* remember it as the last match */
1740 match = cur;
1741
1742 /* count the match */
1743 ++cnt;
1744 }
1745 }
1746
1747 /*
1748 * If we found exactly one match, then activate it. If we found
1749 * zero or more than one, ignore any special topics and proceed
1750 * on the assumption that this is a normal command. (We ignore
1751 * ambiguous matches because this probably means that the entire
1752 * command is some very common word that happens to be acceptable
1753 * as a keyword in one or more of our matches. In these cases,
1754 * the common word was probably meant as an ordinary command,
1755 * since the player would likely have been more specific if a
1756 * special topic were really desired.)
1757 */
1758 if (cnt == 1)
1759 {
1760 /*
1761 * remember the active SpecialTopic - we'll use this memory
1762 * to find it again when we get through the full command
1763 * processing
1764 */
1765 activeSpecialTopic = match;
1766
1767 /*
1768 * Change the command to our special internal pseudo-command
1769 * that triggers the active special topic. Include the
1770 * original string as a literal phrase, enclosed in double
1771 * quotes and specially coded to ensure that the tokenizer
1772 * doesn't become confused by any embedded quotes.
1773 */
1774 return 'xspcltopic "' + SpecialTopicAction.encodeOrig(str) + '"';
1775 }
1776 else
1777 {
1778 /* proceed, treating the original input as an ordinary command */
1779 return str;
1780 }
1781 }
1782
1783 patWhitespace = static new RexPattern('<space>+')
1784 patDelim = static new RexPattern('<punct|space>')
1785
1786 /*
1787 * Handle an XSPCLTOPIC command from the given actor. This is part
1788 * two of the two-phase processing of SpecialTopic matches. Our
1789 * pre-parser checks each SpecialTopic's custom syntax for a match
1790 * to the player's text input, and if it finds a match, it sets our
1791 * activeSpecialTopic property to the matching SpecialTopic, and
1792 * changes the user's command to XSPCLTOPIC for processing by the
1793 * regular parser. The regular parser sees the XSPCLTOPIC command,
1794 * which is a valid verb that calls the issuing actor's
1795 * saySpecialTopic() routine, which in turn forwards the request to
1796 * the issuing actor's interlocutor's current conversation node -
1797 * which is to say, 'self'. We complete the two-step procedure by
1798 * going back to the active special topic object that we previously
1799 * noted and showing its response.
1800 */
1801 saySpecialTopic(fromActor)
1802 {
1803 /* make sure we have an active special topic object */
1804 if (activeSpecialTopic != nil)
1805 {
1806 local actor = getTopicOwner();
1807
1808 /* tell the conversation manager we're starting a response */
1809 conversationManager.beginResponse(actor);
1810
1811 /* let the SpecialTopic handle the response */
1812 activeSpecialTopic.handleTopic(fromActor, nil);
1813
1814 /*
1815 * Tell the conversation manager we're done. By default, we
1816 * want to leave the conversation tree entirely, so set the
1817 * new default node to 'nil'.
1818 */
1819 conversationManager.finishResponse(actor, nil);
1820
1821 /* that wraps things up for the active special topic */
1822 activeSpecialTopic = nil;
1823 }
1824 else
1825 {
1826 /*
1827 * There is no active special topic, so the player must have
1828 * typed in the XSPCLTOPIC command explicitly - if we got
1829 * here through the normal two-step procedure then this
1830 * property would not be nil. Politely decline the command,
1831 * since it's not for the player's direct use.
1832 */
1833 gLibMessages.commandNotPresent;
1834 }
1835 }
1836
1837 /*
1838 * The active special topic. This is the SpecialTopic object that
1839 * we matched during pre-parsing, so it's the one whose response we
1840 * wish to show while processing the command we pre-parsed.
1841 */
1842 activeSpecialTopic = nil
1843
1844 /*
1845 * Note that we're becoming active, with a reason code. Our actor
1846 * will call this method when we're becoming active, as long as we
1847 * weren't already active.
1848 *
1849 * 'reason' is a string giving a reason code for why we're being
1850 * called. For calls from the library, this will be one of these
1851 * codes:
1852 *
1853 * 'convnode' - processing a <.convnode> tag
1854 *
1855 * 'convend' - processing a <.convend> tag
1856 *
1857 * 'initiateConversation' - a call to Actor.initiateConversation()
1858 *
1859 * 'endConversation' - a call to Actor.endConversation()
1860 *
1861 * The reason code is provided so that the node can adapt its action
1862 * for different trigger conditions, if desired. By default, we
1863 * ignore the reason code and just call the basic noteActive()
1864 * method.
1865 */
1866 noteActiveReason(reason)
1867 {
1868 noteActive();
1869 }
1870
1871 /*
1872 * Note that we're becoming active, with a reason code. Our actor
1873 * will call this method when we're becoming active, as long as we
1874 * weren't already active.
1875 *
1876 * Note that if you want to adapt the method's behavior according to
1877 * why the node was activated, you can override noteActiveReason()
1878 * instead of this method.
1879 */
1880 noteActive()
1881 {
1882 /* if desired, schedule a topic inventory whenever we're activated */
1883 if (autoShowTopics())
1884 conversationManager.scheduleTopicInventory();
1885 }
1886
1887 /*
1888 * Note that we're leaving this conversation node. This doesn't do
1889 * anything by default, but individual instances might find the
1890 * notification useful for triggering side effects.
1891 */
1892 noteLeaving() { }
1893 ;
1894
1895
1896 /* ------------------------------------------------------------------------ */
1897 /*
1898 * Pre-parser for special ConvNode-specific commands. When the player
1899 * character is talking to another character, and the NPC's current
1900 * ConvNode includes topics with their own commands, we'll check the
1901 * player's input to see if it matches any of these topics.
1902 */
1903 specialTopicPreParser: StringPreParser
1904 doParsing(str, which)
1905 {
1906 local actor;
1907 local node;
1908
1909 /*
1910 * don't handle this on requests for missing literals - these
1911 * responses are always interpreted as literal text, so there's
1912 * no way this could be a special ConvNode command
1913 */
1914 if (which == rmcAskLiteral)
1915 return str;
1916
1917 /*
1918 * if the player character isn't currently in conversation, or
1919 * the actor with whom the player character is conversing doesn't
1920 * have a current conversation node, there's nothing to do
1921 */
1922 if ((actor = gPlayerChar.getCurrentInterlocutor()) == nil
1923 || (node = actor.curConvNode) == nil)
1924 return str;
1925
1926 /* ask the conversation node to process the string */
1927 return node.processSpecialCmd(str, processInputStr(str));
1928 }
1929
1930 /*
1931 * Process the input string, as desired, for special-topic parsing.
1932 * This method is for the language module's use; by default, we do
1933 * nothing.
1934 *
1935 * Language modules should override this to remove punctuation marks
1936 * and to do any other language-dependent processing to make the
1937 * string parsable.
1938 */
1939 processInputStr(str) { return str; }
1940 ;
1941
1942 /* ------------------------------------------------------------------------ */
1943 /*
1944 * A conversational action type descriptor. This descriptor is used in
1945 * handleConversation() in Actor and ActorState to describe the type of
1946 * conversational action we're performing. The type descriptor object
1947 * encapsulates a set of information that tells us how to handle the
1948 * action.
1949 */
1950 class ConvType: object
1951 /*
1952 * The unknown interlocutor message property. This is used when we
1953 * try this conversational action without knowing whom we're talking
1954 * to. For example, if we just say HELLO, and there's no one around
1955 * to talk to, we'll use this as the default response. This can be a
1956 * library message property, or simply a single-quoted string to
1957 * display.
1958 */
1959 unknownMsg = nil
1960
1961 /*
1962 * The TopicDatabase topic-list property. This is the property of
1963 * the TopicDatabase object that we evaluate to get this list of
1964 * topic entries to search for a match to the topic.
1965 */
1966 topicListProp = nil
1967
1968 /* the default response property for this action */
1969 defaultResponseProp = nil
1970
1971 /*
1972 * Call the default response property on the given topic database.
1973 * This invokes the property given by defaultResponseProp(). We have
1974 * both the property and the method to call the property because this
1975 * allows us to test for the existence of the property and to call it
1976 * with the appropriate argument list.
1977 */
1978 defaultResponse(db, otherActor, topic) { }
1979
1980 /*
1981 * Perform any special follow-up action for this type of
1982 * conversational action.
1983 */
1984 afterResponse(actor, otherActor) { }
1985 ;
1986
1987 helloConvType: ConvType
1988 unknownMsg = &sayHelloMsg
1989 topicListProp = &miscTopics
1990 defaultResponseProp = &defaultGreetingResponse
1991 defaultResponse(db, other, topic)
1992 { db.defaultGreetingResponse(other); }
1993
1994 /* after an explicit HELLO, show any suggested topics */
1995 afterResponse(actor, otherActor)
1996 {
1997 /* show or schedule a topic inventory, as appropriate */
1998 conversationManager.showOrScheduleTopicInventory(actor, otherActor);
1999 }
2000 ;
2001
2002 byeConvType: ConvType
2003 unknownMsg = &sayGoodbyeMsg
2004 topicListProp = &miscTopics
2005 defaultResponseProp = &defaultGoodbyeResponse
2006 defaultResponse(db, other, topic)
2007 { db.defaultGoodbyeResponse(other); }
2008 ;
2009
2010 yesConvType: ConvType
2011 unknownMsg = &sayYesMsg
2012 topicListProp = &miscTopics
2013 defaultResponseProp = &defaultYesResponse
2014 defaultResponse(db, other, topic)
2015 { db.defaultYesResponse(other); }
2016 ;
2017
2018 noConvType: ConvType
2019 unknownMsg = &sayNoMsg
2020 topicListProp = &miscTopics
2021 defaultResponseProp = &defaultNoResponse
2022 defaultResponse(db, other, topic)
2023 { db.defaultNoResponse(other); }
2024 ;
2025
2026 askAboutConvType: ConvType
2027 topicListProp = &askTopics
2028 defaultResponseProp = &defaultAskResponse
2029 defaultResponse(db, other, topic)
2030 { db.defaultAskResponse(other, topic); }
2031 ;
2032
2033 askForConvType: ConvType
2034 topicListProp = &askForTopics
2035 defaultResponseProp = &defaultAskForResponse
2036 defaultResponse(db, other, topic)
2037 { db.defaultAskForResponse(other, topic); }
2038 ;
2039
2040 tellAboutConvType: ConvType
2041 topicListProp = &tellTopics
2042 defaultResponseProp = &defaultTellResponse
2043 defaultResponse(db, other, topic)
2044 { db.defaultTellResponse(other, topic); }
2045 ;
2046
2047 giveConvType: ConvType
2048 topicListProp = &giveTopics
2049 defaultResponseProp = &defaultGiveResponse
2050 defaultResponse(db, other, topic)
2051 { db.defaultGiveResponse(other, topic); }
2052 ;
2053
2054 showConvType: ConvType
2055 topicListProp = &showTopics
2056 defaultResponseProp = &defaultShowResponse
2057 defaultResponse(db, other, topic)
2058 { db.defaultShowResponse(other, topic); }
2059 ;
2060
2061 commandConvType: ConvType
2062 topicListProp = &commandTopics
2063 defaultResponseProp = &defaultCommandResponse
2064 defaultResponse(db, other, topic)
2065 { db.defaultCommandResponse(other, topic); }
2066 ;
2067
2068 /*
2069 * This type is for NPC-initiated conversations. It's not a normal
2070 * conversational action, since it doesn't involve handling a player
2071 * command, but is usually instead triggered by an agenda item,
2072 * takeTurn(), or other background activity.
2073 */
2074 initiateConvType: ConvType
2075 topicListProp = &initiateTopics
2076 ;
2077
2078 /*
2079 * CONSULT ABOUT isn't a true conversational action, since it's applied
2080 * to inanimate objects (such as books); but it's handled through the
2081 * conversation system, so it needs a conversation type object
2082 */
2083 consultConvType: ConvType
2084 topicListProp = &consultTopics
2085 ;
2086
2087 /* ------------------------------------------------------------------------ */
2088 /*
2089 * A topic database entry. Actors and actor state objects store topic
2090 * databases; a topic database is essentially a set of these entries.
2091 *
2092 * A TopicEntry can go directly inside an Actor, in which case it's part
2093 * of the actor's global set of topics; or, it can go inside an
2094 * ActorState, in which case it's part of the state's database and is
2095 * only active when the state is active; or, it can go inside a
2096 * TopicGroup, which is a set of topics with a common controlling
2097 * condition; or, it can go inside a ConvNode, in which case it's in
2098 * effect only when the conversation node is active.
2099 *
2100 * Each entry is a relationship between a topic, which is something that
2101 * can come up in an ASK or TELL action, and a handling for the topic.
2102 * In addition, each entry determines what kind or kinds of actions it
2103 * responds to.
2104 *
2105 * Note that TopicEntry objects are *not* simulation objects. Rather,
2106 * these are abstract objects; they can be associated with simulation
2107 * objects via the matching mechanism, but these are separate from the
2108 * actual simulation objects. The reason for this separation is that a
2109 * given simulation object might have many different response - the
2110 * response could vary according to who's being asked the question, who's
2111 * asking, and what else is happening in the game.
2112 *
2113 * An entry decides for itself if it matches a topic. By default, an
2114 * entry can match based on either a simulation object, which we'll match
2115 * to anything in the topic's "in scope" or "likely" match lists, or
2116 * based on a regular expression string, which we'll match to the actual
2117 * topic text entered in the player's command.
2118 *
2119 * An entry can decide how strongly it matches a topic. The database
2120 * will choose the strongest match when multiple entries match the same
2121 * topic. The strength of the match is given by a numeric score; the
2122 * higher the score, the stronger the match. The match strength makes it
2123 * easy to specify a hierarchy of topics from specific to general, so
2124 * that we provide general responses to general topic areas, but can
2125 * still respond to particular topics areas more specifically. For
2126 * example, we might want to provide a specific match to the FROBNOZ
2127 * SPELL object, talking about that particular magic spell, but provide a
2128 * generic '.* spell' pattern to response to questions about any old
2129 * spell. We'd give the generic pattern a lower score, so that the
2130 * specific FROBNOZ SPELL response would win when it matches, but we'd
2131 * fall back on the generic pattern in other cases.
2132 */
2133 class TopicEntry: object
2134 /*
2135 * My matching simulation object or objects. This can be either a
2136 * single object or a list of objects.
2137 */
2138 matchObj = nil
2139
2140 /*
2141 * Is this topic active? This can be used to control how an actor
2142 * can respond without have to worry about adding and removing topics
2143 * manually at key events, or storing the topics in state objects.
2144 * Sometimes, it's easier to just put a topic entry in the actor's
2145 * database from the start, and test some condition dynamically when
2146 * the topic is actually queried. To do this, override this method
2147 * to test the condition that determines when the topic entry should
2148 * become active. We'll never show the topic's response when
2149 * isActive returns nil. By default, we simply return true to
2150 * indicate that the topic entry is active.
2151 */
2152 isActive = true
2153
2154 /*
2155 * Flag: we are a "conversational" topic. This is true by default.
2156 * When this is set to nil, a ConversationReadyState will NOT show
2157 * its greeting and will not enter its InConversationState to show
2158 * this topic entry's response.
2159 *
2160 * This should be set to nil when the topic entry's response is
2161 * non-conversational, in which case a greeting would be
2162 * undesirable. This is appropriate for responses like "You don't
2163 * think he'd want to talk about that", where the response indicates
2164 * that the player character didn't even ask a question (or
2165 * whatever).
2166 */
2167 isConversational = true
2168
2169 /*
2170 * Do we imply a greeting? By default, all conversational topics
2171 * imply a greeting. We separate this out so that the implied
2172 * greeting can be controlled independently of whether or not we're
2173 * actually conversational, if desired.
2174 */
2175 impliesGreeting = (isConversational)
2176
2177 /*
2178 * Get the actor associated with the topic, if any. By default,
2179 * we'll return our enclosing database's topic owner, if it's an
2180 * actor - in almost all cases, if there's any actor associated with
2181 * a topic, it's simply the owner of the database containing the
2182 * topic.
2183 */
2184 getActor()
2185 {
2186 local owner;
2187
2188 /*
2189 * if we have an owner, and it's an actor, then it's our
2190 * associated actor; otherwise, we don't have any associated
2191 * actor
2192 */
2193 if ((owner = location.getTopicOwner()) != nil && owner.ofKind(Actor))
2194 return owner;
2195 else
2196 return nil;
2197 }
2198
2199 /*
2200 * Determine if this topic is active. This checks the isActive
2201 * property, and also takes into account our relationship to
2202 * alternative entries for the topic. Generally, you should *define*
2203 * (override) isActive, and *call* this method.
2204 */
2205 checkIsActive()
2206 {
2207 /*
2208 * if our isActive property indicates we're not active, we're
2209 * definitely not active, so there's no need to check for an
2210 * overriding alternative
2211 */
2212 if (!isActive)
2213 return nil;
2214
2215 /* if we have an active nested alternative, it overrides us */
2216 if (altTopicList.indexWhich({x: x.isActive}) != nil)
2217 return nil;
2218
2219 /* ask our container if its topics are active */
2220 return location.topicGroupActive();
2221 }
2222
2223 /*
2224 * Check to see if any alternative in the alternative group is
2225 * active. This returns true if we're active or if any of our nested
2226 * AltTopics is active.
2227 */
2228 anyAltIsActive()
2229 {
2230 /*
2231 * if all topics within our container are inactive, then there's
2232 * definitely no active alternative
2233 */
2234 if (!location.topicGroupActive())
2235 return nil;
2236
2237 /*
2238 * if we're active, or any of our nested AltTopics is active, our
2239 * alternative group is active
2240 */
2241 if (isActive || altTopicList.indexWhich({x: x.isActive}) != nil)
2242 return true;
2243
2244 /* we didn't find any active alternatives in the entire group */
2245 return nil;
2246 }
2247
2248 /*
2249 * Adjust my score value for any hierarchical adjustments. We'll add
2250 * the score adjustment for each enclosing object.
2251 */
2252 adjustScore(score)
2253 {
2254 /* the score is nil, it means there's no match, so don't adjust it */
2255 if (score == nil)
2256 return score;
2257
2258 /* add in the cumulative adjustment from my containers */
2259 return score + location.topicGroupScoreAdjustment;
2260 }
2261
2262 /*
2263 * Check to see if we want to defer to the given topic from an
2264 * inferior topic database. By default, we never defer to a topic
2265 * from an inferior database: we choose a matching topic from the top
2266 * database in the hierarchy where we find a match.
2267 *
2268 * The database hierarchy, for most purposes, starts with the
2269 * ConvNode at the highest level, then the ActorState, then the
2270 * Actor. We search those databases, in that order, and we take the
2271 * first match we find. By default, if there's another match in a
2272 * lower-level database, it doesn't matter what its matchScore is: we
2273 * always pick the one from the highest-level database where we find
2274 * a match. You can override this method to change this behavior.
2275 *
2276 * We don't actually define this method here, because the presence of
2277 * the method is significant. If the method isn't defined at all, we
2278 * won't bother looking for a possible deferral, saving the trouble
2279 * of searching the other databases in the hierarchy.
2280 */
2281 // deferToEntry(other) { return nil; }
2282
2283 /*
2284 * Our match strength score. By default, we'll use a score of 100,
2285 * which is just an arbitrary base score.
2286 */
2287 matchScore = 100
2288
2289 /*
2290 * The set of database lists we're part of. This is a list of
2291 * property pointers, giving the TopicDatabase properties of the
2292 * lists we participate in.
2293 */
2294 includeInList = []
2295
2296 /*
2297 * Our response. This is displayed when we're the topic entry
2298 * selected to handle an ASK or TELL. Each topic entry must override
2299 * this to show our response text (or, alternatively, an entry can
2300 * override handleTopic so that it doesn't call this property).
2301 */
2302 topicResponse = ""
2303
2304 /*
2305 * The number of times this topic has invoked by the player. Each
2306 * time the player asks/tells/etc about this topic, we'll increment
2307 * this count.
2308 */
2309 talkCount = 0
2310
2311 /*
2312 * The number of times this topic or any nested AltTopic has been
2313 * invoked by the player. Each time the player asks/tells/etc about
2314 * this topic OR any of its AltTopic children, we'll increment this
2315 * count.
2316 */
2317 altTalkCount = 0
2318
2319 /*
2320 * the owner of any AltTopic nested within me is the same as my own
2321 * topic owner, which we take from our location
2322 */
2323 getTopicOwner()
2324 {
2325 if (location != nil)
2326 return location.getTopicOwner();
2327 else
2328 return nil;
2329 }
2330
2331 /*
2332 * Initialize. If we have a location property, we'll assume that the
2333 * location is a topic database object, and we'll add ourselves to
2334 * that database.
2335 */
2336 initializeTopicEntry()
2337 {
2338 /* if we have a location, add ourselves to its topic database */
2339 if (location != nil)
2340 location.addTopic(self);
2341
2342 /* sort our list of AltTopic children */
2343 altTopicList = altTopicList.sort(
2344 SortAsc, {a, b: a.altTopicOrder - b.altTopicOrder});
2345 }
2346
2347 /* add a topic nested within us */
2348 addTopic(entry)
2349 {
2350 /* if we have a location, add the entry to its topic database */
2351 if (location != nil)
2352 location.addTopic(entry);
2353 }
2354
2355 /*
2356 * Add an AltTopic entry. This is called by our AltTopic children
2357 * during initialization; we'll simply add the entry to our list of
2358 * AltTopic children.
2359 */
2360 addAltTopic(entry)
2361 {
2362 /* add the entry to our list of alternatives */
2363 altTopicList += entry;
2364 }
2365
2366 /* get the topic group score adjustment (for AltTopics nested within) */
2367 topicGroupScoreAdjustment = (location.topicGroupScoreAdjustment)
2368
2369 /* check the group isActive status (for AltTopics nested within) */
2370 topicGroupActive = (location.topicGroupActive)
2371
2372 /* our list of AltTopic children */
2373 altTopicList = []
2374
2375 /*
2376 * Match a topic. This is abstract in this base class; it must be
2377 * defined by each concrete subclass. This returns nil if there's no
2378 * match, or an integer value if there's a match. The higher the
2379 * number's value, the stronger the match.
2380 *
2381 * This is abstract in the base class because the meaning of 'topic'
2382 * varies by subclass, according to which type of command it's used
2383 * with. For example, in ASK and TELL commands, 'topic' is a
2384 * ResolvedTopic describing the topic in the player's command; for
2385 * GIVE and SHOW commands, it's the resolved simulation object.
2386 */
2387 // matchTopic(fromActor, topic) { return nil; }
2388
2389 /*
2390 * Check to see if a match to this topic entry is *possible* right
2391 * now for the given actor. For most subclasses, this is inherently
2392 * imprecise, because the 'match' function simply isn't reversible in
2393 * general: to know if we can be matched, we'd have to determine if
2394 * there's a non-empty set of possible inputs that can match us.
2395 * This method is complementary to matchTopic(), so subclasses must
2396 * override with a corresponding implementation.
2397 *
2398 * 'actor' is the actor to whom we're making the suggestion.
2399 * 'scopeList' is the list of objects that are in scope for the
2400 * actor.
2401 *
2402 * The library only uses this to determine if a suggestion should be
2403 * offered. So, specialized topic instances with non-standard match
2404 * rules don't have to worry about this unless they're used as
2405 * suggestions, or unless the game itself needs this information for
2406 * some other reason.
2407 */
2408 // isMatchPossible(actor, scopeList) { return true; }
2409
2410 /*
2411 * Break a tie among matching topics entries. The topic database
2412 * searcher calls this on each matching topic entry when it finds
2413 * multiple entries tied for first place, based on their match
2414 * scores. This gives the entries a chance to figure out which one
2415 * is actually the best match for the input, given the other entries
2416 * that also matched.
2417 *
2418 * This method returns a TopicEntry object - one of the objects from
2419 * the match list - if it has an opinion as to which one should take
2420 * precedence. It returns nil if it doesn't know or doesn't care.
2421 * Returning nil gives the other topics in the match list a chance to
2422 * make the selection. If all of the objects in the list return nil,
2423 * the topic database searcher simply picks one of the topic matches
2424 * arbitrarily.
2425 *
2426 * 'matchList' is the list of tied TopicEntry objects. 'topic' is
2427 * the ResolvedTopic object from the parser, representing the
2428 * player's input phrase that we're matching. 'fromActor' is the
2429 * actor performing the command. 'toks' is a list of strings giving
2430 * the word tokens of the noun phrase.
2431 *
2432 * The topic database searcher calls this method for each matching
2433 * topic entry in the case of a tie, and simply accepts the opinion
2434 * of the first one that expresses an opinion by returning a non-nil
2435 * value. There's no voting; whoever happens to get *and use* the
2436 * first say also gets the last word. We expect that this won't be a
2437 * problem in practice: when this comes up at all, it's because there
2438 * are a couple of closely related topic entries that are active in a
2439 * particular context, and you need a special bit of tweaking to pick
2440 * the right one for a given input phrase. Simply pick one of the
2441 * involved entries and define this method there.
2442 */
2443 breakTopicTie(matchList, topic, fromActor, toks)
2444 {
2445 /*
2446 * we don't have an opinion - defer to the next object in the
2447 * list, or allow an arbitrary selection
2448 */
2449 return nil;
2450 }
2451
2452 /*
2453 * Set pronouns for the topic, if possible. If the topic corresponds
2454 * to a game-world object, then we should set the pronoun antecedent
2455 * to the game object. This must be handled per subclass because of
2456 * the range of possible meanings of 'topic'.
2457 */
2458 setTopicPronouns(fromActor, topic) { }
2459
2460 /*
2461 * Handle the topic. This is called when we find that this is the
2462 * best topic entry for the current topic.
2463 *
2464 * By default, we'll do one of two things:
2465 *
2466 * - If 'self' inherits from Script, then we'll simply invoke our
2467 * doScript() method. This makes it especially easy to set up a
2468 * topic entry that shows a series of responses: just add EventList
2469 * or one of its subclasses to the base class list when defining the
2470 * topic, and define the eventList property as a list of string
2471 * responses. For example:
2472 *
2473 *. + TopicEntry, StopEventList @blackBook
2474 *. ['<q>What makes you think I know anything about it?</q>
2475 *. he says, his voice shaking. ',
2476 *. '<q>No! You can\'t make me tell you!</q> he wails. ',
2477 *. '<q>All right, fine! I\'ll tell you, but I warn you,
2478 *. this is knowledge mortal men were never meant to know.</q> ',
2479 *. // and so on
2480 *. ]
2481 *. ;
2482 *
2483 * - Otherwise, we'll call our topicResponse property, which should
2484 * simply be a double-quoted string to display. This is the simplest
2485 * way to define a topic with just one response.
2486 *
2487 * Note that 'topic' will vary by subclass, depending on the type of
2488 * command used with the topic type. For example, for ASK and TELL
2489 * commands, 'topic' is a ResolvedTopic object; for GIVE and SHOW,
2490 * it's a simulation object (i.e., generally a Thing subclass).
2491 */
2492 handleTopic(fromActor, topic)
2493 {
2494 /* note the invocation */
2495 noteInvocation(fromActor);
2496
2497 /* set pronoun antecedents if possible */
2498 setTopicPronouns(fromActor, topic);
2499
2500 /* check to see if we're a Script */
2501 if (ofKind(Script))
2502 {
2503 /* we're a Script - invoke our script */
2504 doScript();
2505 }
2506 else
2507 {
2508 /* show our simple response string */
2509 topicResponse;
2510 }
2511 }
2512
2513 /* note that we've been invoked */
2514 noteInvocation(fromActor)
2515 {
2516 /*
2517 * we count as one of the alternatives in our alternative group,
2518 * so note the invocation of the group
2519 */
2520 noteAltInvocation(fromActor, self);
2521
2522 /* count the invocation */
2523 ++talkCount;
2524 }
2525
2526 /*
2527 * Note that something in our entire alternative group has been
2528 * invoked. We count as a member of our own group, so this is
2529 * invoked when we're invoked; this is also invoked when any AltTopic
2530 * child of ours is invoked.
2531 */
2532 noteAltInvocation(fromActor, alt)
2533 {
2534 local owner;
2535
2536 /* notify our owner of the topic invocation */
2537 if ((owner = location.getTopicOwner()) != nil)
2538 owner.notifyTopicResponse(fromActor, alt);
2539
2540 /* count the alternative invocation */
2541 ++altTalkCount;
2542 }
2543
2544 /*
2545 * Add a suggested topic. A suggested topic can be nested within a
2546 * topic entry; doing this associates the suggested topic with the
2547 * topic entry, and automatically associates the suggested topic
2548 * with the entry's actor or actor state.
2549 */
2550 addSuggestedTopic(t)
2551 {
2552 /*
2553 * If the SuggestedTopic is *directly* within us, we're the
2554 * SuggestedTopic object's associated TopicEntry. The nesting
2555 * could be deeper, if we have alternative topics nested within
2556 * us; in these cases, we're not directly associated with the
2557 * suggested topic.
2558 */
2559 if (t.location == self)
2560 t.associatedTopic = self;
2561
2562 /* add the suggestion to our location's topic database */
2563 if (location != nil)
2564 location.addSuggestedTopic(t);
2565 }
2566 ;
2567
2568 /*
2569 * A TopicGroup is an abstract container for a set of TopicEntry objects.
2570 * The purpose of the group object is to apply a common "is active"
2571 * condition to all of the topics within the group.
2572 *
2573 * The isActive condition of the TopicGroup is effectively AND'ed with
2574 * any other conditions on the nested TopicEntry's. In other words, a
2575 * TopicEntry within the TopicGroup is active if the TopicEntry would
2576 * otherwise be acive AND the TopicGroup is active.
2577 *
2578 * TopicEntry objects are associated with the group via the 'location'
2579 * property - set the location of the TopicEntry to point to the
2580 * containing TopicGroup.
2581 *
2582 * You can put a TopicGroup anywhere a TopicEntry could go - directly
2583 * inside an Actor, inside an ActorState, or within another TopicGroup.
2584 * The topic entries within a topic group act as though they were
2585 * directly in the topic group's container.
2586 */
2587 class TopicGroup: object
2588 /*
2589 * The group "active" condition - each instance should override this
2590 * to specify the condition that applies to all of the TopicEntry
2591 * objects within the group.
2592 */
2593 isActive = true
2594
2595 /*
2596 * The *adjustment* to the match score for topic entries contained
2597 * within this group. This is usually a positive number, so that it
2598 * boosts the match strength of the child topics.
2599 */
2600 matchScoreAdjustment = 0
2601
2602 /*
2603 * the topic owner for any topic entries within the group is the
2604 * topic owner taken from the group's own location
2605 */
2606 getTopicOwner() { return location.getTopicOwner(); }
2607
2608 /* are TopicEntry objects within the group active? */
2609 topicGroupActive()
2610 {
2611 /*
2612 * our TopicEntry objects are active if the group condition is
2613 * true and our container's contents are active
2614 */
2615 return isActive && location.topicGroupActive();
2616 }
2617
2618 /*
2619 * Get my score adjustment. We'll return our own basic score
2620 * adjustment plus the cumulative adjustment for our containers.
2621 */
2622 topicGroupScoreAdjustment = (matchScoreAdjustment
2623 + location.topicGroupScoreAdjustment)
2624
2625 /* add a topic - we'll simply add the topic directly to our container */
2626 addTopic(topic) { location.addTopic(topic); }
2627
2628 /* add a suggested topic - we'll pass this up to our container */
2629 addSuggestedTopic(topic) { location.addSuggestedTopic(topic); }
2630 ;
2631
2632 /*
2633 * An alternative topic entry. This makes it easy to define different
2634 * responses to a topic according to the game state; for example, we
2635 * might want to provide a different response for a topic after some
2636 * event has occurred, so that we can reflect knowledge of the event in
2637 * the response.
2638 *
2639 * A set of alternative topics is sort of like an inverted if-then-else.
2640 * You start by defining a normal TopicEntry (an AskTopic, or an
2641 * AskTellTopic, or whatever) for the basic response. Then, you add a
2642 * nested AltTopic located within the base topic; you can add another
2643 * AltTopic nested within the base topic, and another after that, and so
2644 * on. When we need to choose one of the topics, we'll choose the last
2645 * one that indicates it's active. So, the order of appearance is
2646 * essentially an override order: the first AltTopic overrides its parent
2647 * TopicEntry, and each subsequent AltTopic overrides its previous
2648 * AltTopic.
2649 *
2650 * + AskTellTopic @lighthouse "It's very tall.";
2651 *. ++ AltTopic "Not really..." isActive=(...);
2652 *. ++ AltTopic "Well, maybe..." isActive=(...);
2653 *. ++ AltTopic "One more thing..." isActive=(...);
2654 *
2655 * In this example, the response we'll show for ASK ABOUT LIGHTHOUSE will
2656 * always be the LAST entry of the group that's active. For example, if
2657 * all of the responses are active except for the very last one, then
2658 * we'll show the "Well, maybe" response, because it's the last active
2659 * response. If the main AskTellTopic is active, but none of the
2660 * AltTopics are active, we'll show the "It's very tall" main response,
2661 * because it's the last element of the group that's active.
2662 *
2663 * Note that an AltTopic takes its matching information from its parent,
2664 * so you don't need to specify a matchObj or any other matching
2665 * information in an AltTopic. You merely need to provide the response
2666 * text and the isActive test.
2667 */
2668 class AltTopic: TopicEntry
2669 /* we match if our parent matches, and with the same score */
2670 matchTopic(fromActor, topic)
2671 { return location.matchTopic(fromActor, topic); }
2672
2673 /* we can match if our parent can match */
2674 isMatchPossible(actor, scopeList)
2675 { return location.isMatchPossible(actor, scopeList); }
2676
2677 /* we can match a pre-parse string if our parent can */
2678 matchPreParse(str, pstr) { return location.matchPreParse(str, pstr); }
2679
2680 /* set pronouns for the topic */
2681 setTopicPronouns(fromActor, topic)
2682 { location.setTopicPronouns(fromActor, topic); }
2683
2684 /* include in the same lists as our parent */
2685 includeInList = (location.includeInList)
2686
2687 /* AltTopic initialization */
2688 initializeAltTopic()
2689 {
2690 /* add myself to our parent's child list */
2691 if (location != nil)
2692 location.addAltTopic(self);
2693 }
2694
2695 /*
2696 * Determine if this topic is active. An AltTopic is active if its
2697 * own isActive indicates true, AND none of its subsequent siblings
2698 * are active.
2699 */
2700 checkIsActive()
2701 {
2702 /* we can't be active if our own isActive says we're not */
2703 if (!isActive)
2704 return nil;
2705
2706 /*
2707 * Check for any active element after us in the parent's list.
2708 * To do this, scan from the end of the parent list backwards,
2709 * and look for an element that's active. If we reach our own
2710 * entry, then we'll know that there are no active entries
2711 * following us in the list. Note that we already know we're
2712 * active, or we wouldn't have gotten this far, so we can simply
2713 * look for the rightmost active element in the list.
2714 */
2715 if (location != nil
2716 && location.altTopicList.lastValWhich({x: x.isActive}) != self)
2717 {
2718 /*
2719 * we found an active element after ourself, so it overrides
2720 * us - we're therefore not active
2721 */
2722 return nil;
2723 }
2724
2725 /* ask our container if its topics are active */
2726 return location.topicGroupActive();
2727 }
2728
2729 /* take our implied-greeting status from our parent */
2730 impliesGreeting = (location.impliesGreeting)
2731
2732 /* take our conversational status from our parent */
2733 isConversational = (location.isConversational)
2734
2735 /*
2736 * Our relative order within our parent's list of alternatives. By
2737 * default, we simply return the source file ordering, which ensures
2738 * that static AltTopic objects (i.e., those defined directly in
2739 * source files, not dynamically created with 'new') will be ordered
2740 * just as they're laid out in the source file.
2741 */
2742 altTopicOrder = (sourceTextOrder)
2743
2744 /* note invocation */
2745 noteInvocation(fromActor)
2746 {
2747 /* count our own invocation */
2748 ++talkCount;
2749
2750 /* let our container know its AltTopic child is being invoked */
2751 if (location != nil)
2752 location.noteAltInvocation(fromActor, self);
2753 }
2754
2755 /* our AltTopic counter is the AltTopic counter for the enclosing topic */
2756 altTalkCount = (location != nil ? location.altTalkCount : talkCount)
2757 ;
2758
2759 /*
2760 * A "topic match" topic entry. This is a topic entry that matches topic
2761 * phrases in the grammar.
2762 *
2763 * Handling topic phrases is a bit tricky, because they can't be resolved
2764 * to definitive game-world objects the way ordinary noun phrases can.
2765 * Topic phrases can refer to things that aren't physically present, but
2766 * which are known to the actor performing the command; they can refer to
2767 * abstract Topic objects, that have no physical existence in the game
2768 * world at all; and they can ever be arbitrary text that doesn't match
2769 * any vocabulary defined by the game.
2770 *
2771 * Our strategy in matching topics is to first narrow the list down to
2772 * the physical and abstract game objects that both match the vocabulary
2773 * used in the command and are part of the memory of the actor performing
2774 * the command. That much is handled by the normal topic phrase
2775 * resolution rules, and gives us a list of possible matches. Then,
2776 * given this narrowed list of possibilities, we look through the list of
2777 * objects that we're associated with; we effectively intersect the two
2778 * lists, and if the result is non-empty, we consider it a match.
2779 * Finally, we also consider any regular expression that we're associated
2780 * with; if we have one, and the topic phrase text in the command matches
2781 * the input, we'll consider it a match.
2782 */
2783 class TopicMatchTopic: TopicEntry
2784 /*
2785 * A regular expression pattern that we'll match to the actual topic
2786 * text as entered in the command. If 'matchExactCase' is true,
2787 * we'll match the exact text in its original upper/lower case
2788 * rendering; otherwise, we'll convert the player input to lower-case
2789 * before matching it against the pattern. In most cases, we'll want
2790 * to match the input no matter what combination of upper and lower
2791 * case the player entered, so matchExactCase is nil by default.
2792 *
2793 * Note that both the object (or object list) and the regular
2794 * expression pattern can be included for a single topic entry
2795 * object. This allows a topic entry to match several different ways
2796 * of entering the topic name, or to match several different topics
2797 * with the same response.
2798 */
2799 matchPattern = nil
2800 matchExactCase = nil
2801
2802 /*
2803 * Match the topic. By default, we'll match to either the simulation
2804 * object or objects in matchObj, or the pattern in matchPattern.
2805 * Note that we always try both ways of matching, so a single
2806 * AskTellTopic can define both a pattern and an object list.
2807 *
2808 * 'topic' is a ResolvedTopic object describing the player's text
2809 * input and the list of objects that the parser matched to the text.
2810 *
2811 * Subclasses can override this as desired to use other ways of
2812 * matching.
2813 */
2814 matchTopic(fromActor, topic)
2815 {
2816 /*
2817 * if we have one or more match objects, try matching to the
2818 * topic's best simulation object match
2819 */
2820 if (matchObj != nil)
2821 {
2822 /*
2823 * we have a match object or match object list - if it's a
2824 * collection, check each element, otherwise just match the
2825 * single object
2826 */
2827 if (matchObj.ofKind(Collection))
2828 {
2829 /* try matching each object in the list */
2830 if (matchObj.indexWhich({x: findMatchObj(x, topic)}) != nil)
2831 return matchScore;
2832 }
2833 else
2834 {
2835 /* match the single object */
2836 if (findMatchObj(matchObj, topic))
2837 return matchScore;
2838 }
2839 }
2840
2841 /*
2842 * check for a match to the regular expression pattern, if we
2843 * have a pattern AND the resolved topic allows literal matches
2844 */
2845 if (matchPattern != nil && topic.canMatchLiterally())
2846 {
2847 local txt;
2848
2849 /*
2850 * There's no match object; try matching our regular
2851 * expression to the actual topic text. Get the actual text.
2852 */
2853 txt = topic.getTopicText();
2854
2855 /*
2856 * if they don't want an exact case match, convert the
2857 * original topic text to lower case
2858 */
2859 if (!matchExactCase)
2860 txt = txt.toLower();
2861
2862 /* if the regular expression matches, we match */
2863 if (rexMatch(matchPattern, txt) != nil)
2864 return matchScore;
2865 }
2866
2867 /* we didn't find a match - indicate this with a nil score */
2868 return nil;
2869 }
2870
2871 /*
2872 * Match an individual item from our match list to the given
2873 * ResolvedTopic object. We'll check each object in the resolved
2874 * topic's "in scope" and "likely" lists.
2875 */
2876 findMatchObj(obj, rt)
2877 {
2878 /* check the "in scope" list */
2879 if (rt.inScopeList.indexOf(obj) != nil)
2880 return true;
2881
2882 /* check the "likely" list */
2883 return (rt.likelyList.indexOf(obj) != nil);
2884 }
2885
2886 /*
2887 * It's possible for us to match if any of our matchObj objects are
2888 * known to the actor. If we have no matchObj objects, we must be
2889 * matching on a regular expression or on a custom condition, so we
2890 * can't speculate on matchability; we'll simply return true in those
2891 * cases.
2892 */
2893 isMatchPossible(actor, scopeList)
2894 {
2895 /* check what we have in our matchObj */
2896 if (matchObj == nil)
2897 {
2898 /*
2899 * we have no match object, so we must match on a regular
2900 * expression or a custom condition; we can't speculate on
2901 * our matchability, so just return true as a default
2902 */
2903 return true;
2904 }
2905 else if (matchObj.ofKind(Collection))
2906 {
2907 /*
2908 * we have a list of match objects - return true if any of
2909 * them are known or are currently in scope
2910 */
2911 return (matchObj.indexWhich(
2912 {x: actor.knowsAbout(x) || scopeList.indexOf(x)}) != nil);
2913 }
2914 else
2915 {
2916 /*
2917 * we have a single match object - return true if it's known
2918 * or it's in scope
2919 */
2920 return (actor.knowsAbout(matchObj)
2921 || scopeList.indexOf(matchObj) != nil);
2922 }
2923 }
2924
2925 /* set the topic pronouns */
2926 setTopicPronouns(fromActor, topic)
2927 {
2928 /* check to see what kind of match object we have */
2929 if (matchObj == nil)
2930 {
2931 /*
2932 * no match object, so we must match a regular expression
2933 * pattern; this gives us no clue what game object we might
2934 * match, so there's nothing we can do here
2935 */
2936 }
2937 else if (matchObj.ofKind(Collection))
2938 {
2939 local lst;
2940
2941 /*
2942 * We match a list of objects. Get the subset of the
2943 * in-scope list from the topic that we match. Consider only
2944 * the in-scope items for now, and consider only game-world
2945 * objects (Things).
2946 */
2947 lst = matchObj.subset(
2948 {x: x.ofKind(Thing) && topic.inScopeList.indexOf(x) != nil});
2949
2950 /* if that didn't turn up anything, consider the likelies, too */
2951 if (lst.length() == 0)
2952 lst = matchObj.subset(
2953 {x: (x.ofKind(Thing)
2954 && topic.likelyList.indexOf(x) != nil)});
2955
2956 /*
2957 * if that narrows it down to one match, make it the pronoun
2958 * antecedent
2959 */
2960 if (lst.length() == 1)
2961 fromActor.setPronounObj(lst[1]);
2962 }
2963 else
2964 {
2965 /*
2966 * we match a single object; if it's a game-world object (a
2967 * Thing), use it as the pronoun antecedent
2968 */
2969 if (matchObj.ofKind(Thing))
2970 fromActor.setPronounObj(matchObj);
2971 }
2972 }
2973 ;
2974
2975 /*
2976 * A dual ASK/TELL topic database entry. This type of topic is included
2977 * in both the ASK ABOUT and TELL ABOUT lists.
2978 *
2979 * Many authors have chosen to treat ASK and TELL as equivalent, or at
2980 * least, equivalent for most topics. Since these verbs only very weakly
2981 * suggest what the player character is actually saying, it's frequently
2982 * the case that a given topic response makes just as much sense coming
2983 * from TELL as from ASK, or vice versa. In these cases, it's best to
2984 * enter the topic under both ASK and TELL; which one the player tries
2985 * might simply depend on the player's frame of mind, and they might feel
2986 * cheated if one works and the other doesn't in cases where both are
2987 * equally valid.
2988 */
2989 class AskTellTopic: TopicMatchTopic
2990 /* include me in both the ASK and TELL lists */
2991 includeInList = [&askTopics, &tellTopics]
2992 ;
2993
2994 /*
2995 * An ASK ABOUT topic database entry. This type of topic is included in
2996 * the ASK ABOUT list only.
2997 */
2998 class AskTopic: AskTellTopic
2999 includeInList = [&askTopics]
3000 ;
3001
3002 /*
3003 * A TELL ABOUT topic database entry. This type of topic entry is
3004 * included in the TELL ABOUT list only.
3005 */
3006 class TellTopic: AskTellTopic
3007 includeInList = [&tellTopics]
3008 ;
3009
3010 /*
3011 * An ASK FOR topic database entry. This type of topic entry is
3012 * included in the ASK FOR list only.
3013 */
3014 class AskForTopic: AskTellTopic
3015 includeInList = [&askForTopics]
3016 ;
3017
3018 /*
3019 * A combination ASK ABOUT and ASK FOR topic.
3020 */
3021 class AskAboutForTopic: AskTellTopic
3022 includeInList = [&askTopics, &askForTopics]
3023 ;
3024
3025 /*
3026 * A combination ASK ABOUT, TELL ABOUT, and ASK FOR topic.
3027 */
3028 class AskTellAboutForTopic: AskTellTopic
3029 includeInList = [&askTopics, &tellTopics, &askForTopics]
3030 ;
3031
3032
3033 /*
3034 * A base class for topic entries that match simple simulation objects.
3035 */
3036 class ThingMatchTopic: TopicEntry
3037 /*
3038 * Match the topic. We'll match the simulation object in 'obj' to
3039 * our matchObj object or list.
3040 */
3041 matchTopic(fromActor, obj)
3042 {
3043 /*
3044 * if matchObj is a collection, check each element, otherwise
3045 * just match the single object
3046 */
3047 if (matchObj.ofKind(Collection))
3048 {
3049 /* try matching each object in the list */
3050 if (matchObj.indexOf(obj) != nil)
3051 return matchScore;
3052 }
3053 else
3054 {
3055 /* match the single object */
3056 if (matchObj == obj)
3057 return matchScore;
3058 }
3059
3060 /* didn't find a match - indicate this by returning a nil score */
3061 return nil;
3062 }
3063
3064 /*
3065 * It's possible for us to match if any of our matchObj objects are
3066 * in scope.
3067 */
3068 isMatchPossible(actor, scopeList)
3069 {
3070 /* check to see what kind of match object we have */
3071 if (matchObj.ofKind(Collection))
3072 {
3073 /* we can match if any of our match objects are in scope */
3074 return (matchObj.indexWhich({x: scopeList.indexOf(x)}) != nil);
3075 }
3076 else
3077 {
3078 /* we can match if our single match object is in scope */
3079 return scopeList.indexOf(matchObj);
3080 }
3081 }
3082
3083 /* set the topic pronouns */
3084 setTopicPronouns(fromActor, topic)
3085 {
3086 /*
3087 * the 'topic' is just an ordinary game object; as long as it's a
3088 * Thing, set it as the antecedent
3089 */
3090 if (topic.ofKind(Thing))
3091 fromActor.setPronounObj(topic);
3092 }
3093 ;
3094
3095 /*
3096 * A GIVE/SHOW topic database entry.
3097 *
3098 * Note that this base class is usable for any command that refers to a
3099 * simulation object. It's NOT suitable for ASK/TELL lists, or for other
3100 * commands that refer to topics, since we expect our 'topic' to be a
3101 * resolved simulation object.
3102 */
3103 class GiveShowTopic: ThingMatchTopic
3104 /* include me in both the GIVE and SHOW lists */
3105 includeInList = [&giveTopics, &showTopics]
3106 ;
3107
3108 /*
3109 * A GIVE TO topic database entry. This type of topic entry is included
3110 * in the GIVE TO list only.
3111 */
3112 class GiveTopic: GiveShowTopic
3113 includeInList = [&giveTopics]
3114 ;
3115
3116 /*
3117 * A SHOW TO topic database entry. This type of topic entry is included
3118 * in the SHOW TO list only.
3119 */
3120 class ShowTopic: GiveShowTopic
3121 includeInList = [&showTopics]
3122 ;
3123
3124 /*
3125 * A TopicEntry that can match a Thing or a Topic. This can be used to
3126 * combine ASK/TELL-type responses and GIVE/SHOW-type responses in a
3127 * single topic entry.
3128 *
3129 * When this kind of topic is used as a suggested topic, note that you
3130 * should name the suggestion according to the least restrictive verb.
3131 * This is important because the suggestion will be active if any of the
3132 * verbs would allow it; to ensure that we suggest a verb that will
3133 * actually work, we should thus use the least restrictive verb. In
3134 * practice, this means you should use ASK or TELL as the suggestion
3135 * name, because an object merely has to be known to be used as a topic;
3136 * it might be possible to ASK/TELL about an object but not GIVE/SHOW the
3137 * object, because the object is known but not currently in scope.
3138 */
3139 class TopicOrThingMatchTopic: ThingMatchTopic, TopicMatchTopic
3140 matchTopic(fromActor, obj)
3141 {
3142 /*
3143 * if we're being asked to match a ResolvedTopic, use the
3144 * inherited TopicMatchTopic handling; otherwise, use the
3145 * inherited ThingMatchTopic handling
3146 */
3147 if (obj.ofKind(ResolvedTopic))
3148 return inherited TopicMatchTopic(fromActor, obj);
3149 else
3150 return inherited ThingMatchTopic(fromActor, obj);
3151 }
3152
3153 isMatchPossible(actor, scopeList)
3154 {
3155 /* if a match is possible from either subclass, allow it */
3156 return (inherited TopicMatchTopic(actor, scopeList)
3157 || inherited ThingMatchTopic(actor, scopeList));
3158 }
3159
3160 setTopicPronouns(fromActor, obj)
3161 {
3162 /*
3163 * if the object is a ResolvedTopic, use the inherited
3164 * TopicMatchTopic handling, otherwise use the ThingMatchTopic
3165 * handling
3166 */
3167 if (obj.ofKind(ResolvedTopic))
3168 return inherited TopicMatchTopic(fromActor, obj);
3169 else
3170 return inherited ThingMatchTopic(fromActor, obj);
3171 }
3172 ;
3173
3174 /*
3175 * A combined ASK/TELL/SHOW topic. Players will sometimes want to point
3176 * something out when it's visible, rather than asking about it; this
3177 * allows SHOW TO to be used as a synonym for ASK ABOUT for these cases.
3178 */
3179 class AskTellShowTopic: TopicOrThingMatchTopic
3180 includeInList = [&askTopics, &tellTopics, &showTopics]
3181 ;
3182
3183 /*
3184 * A combined ASK/TELL/GIVE/SHOW topic.
3185 */
3186 class AskTellGiveShowTopic: TopicOrThingMatchTopic
3187 includeInList = [&askTopics, &tellTopics, &giveTopics, &showTopics]
3188 ;
3189
3190 /*
3191 * A command topic. This is used to respond to orders given to an NPC,
3192 * as in "BOB, GO EAST." The match object for this kind of topic entry
3193 * is an Action class; for example, to create a response to "BOB, LOOK",
3194 * we'd create a CommandTopic that matches LookAction.
3195 *
3196 * If you're designing a CommandTopic for a command can be accepted from
3197 * a remote location, such as by telephone, you should be aware that the
3198 * command will be running in the NPC's visual sense context. This means
3199 * that if the player character can't see the NPC, the topic result
3200 * message will be hidden - the NPC's visual sense context hides all
3201 * messages generated while it's in effect if the PC can't see the NPC.
3202 * This is usually desirable, since most messages relay visual
3203 * information that wouldn't be visible to the player character if the PC
3204 * can't see the subject of the message. However, if you've specifically
3205 * designed your CommandTopic to work remotely, this isn't at all what
3206 * you want, since you've already taken the remoteness into account in
3207 * the message and thus want the message to be displayed after all. The
3208 * way to handle this is to wrap the message in a callWithSenseContext()
3209 * with a nil sense context. For example:
3210 *
3211 * topicResponse()
3212 *. { callWithSenseContext(nil, nil, {: "Here's my message!" }); }
3213 */
3214 class CommandTopic: TopicEntry
3215 /* we go in the command topics list */
3216 includeInList = [&commandTopics]
3217
3218 /* match the topic */
3219 matchTopic(fromActor, obj)
3220 {
3221 /*
3222 * Check the collection or the single object, as needed. Note
3223 * that our match object is an Action base class, so we must
3224 * match if 'obj' is of the match object class.
3225 */
3226 if (matchObj.ofKind(Collection))
3227 {
3228 /* check each entry for a match */
3229 if (matchObj.indexWhich({x: obj.ofKind(x)}) != nil)
3230 return matchScore;
3231 }
3232 else
3233 {
3234 /* check our single object */
3235 if (obj.ofKind(matchObj))
3236 return matchScore;
3237 }
3238
3239 /* didn't find a match */
3240 return nil;
3241 }
3242
3243 /*
3244 * we can always match, since the player can always type in any
3245 * possible action
3246 */
3247 isMatchPossible(actor, scopeList) { return true; }
3248
3249 /* we have no pronouns to set */
3250 setTopicPronouns(fromActor, topic) { }
3251 ;
3252
3253 /*
3254 * A base class for simple miscellaneous topics. These handle things
3255 * like YES, NO, HELLO, and GOODBYE, where the topic is entirely
3256 * contained in the verb, and there's no separate noun phrase needed to
3257 * indicate the topic.
3258 */
3259 class MiscTopic: TopicEntry
3260 matchTopic(fromActor, obj)
3261 {
3262 /*
3263 * if it's one of our matching topics, return our match score,
3264 * otherwise return a nil score to indicate failure
3265 */
3266 return (matchList.indexOf(obj) != nil) ? matchScore : nil;
3267 }
3268
3269 /*
3270 * a match is always possible for simple verb topics (since the
3271 * player could always type the verb)
3272 */
3273 isMatchPossible(actor, scopeList) { return true; }
3274 ;
3275
3276 /*
3277 * A greeting topic - this handles a HELLO or TALK TO command, as well
3278 * as implied greetings (the kind of greeting generated when we jump
3279 * directly into a conversation with an actor that uses stateful
3280 * conversations, by typing a command like ASK ABOUT or TELL ABOUT
3281 * without first saying HELLO explicitly).
3282 */
3283 class HelloTopic: MiscTopic
3284 includeInList = [&miscTopics]
3285 matchList = [helloTopicObj, impHelloTopicObj]
3286
3287 /*
3288 * this is an explicit greeting, so it obviously shouldn't trigger
3289 * an implied greeting, regardless of how conversational we are
3290 */
3291 impliesGreeting = nil
3292
3293 /*
3294 * if we use this as a greeting upon entering a ConvNode, we'll want
3295 * to stay in the node afterward
3296 */
3297 noteInvocation(fromActor)
3298 {
3299 inherited(fromActor);
3300 "<.convstay>";
3301 }
3302 ;
3303
3304 /*
3305 * An implied greeting topic. This handles ONLY implied greetings.
3306 *
3307 * Note that we have a higher-than-normal score by default. This makes
3308 * it easy to program two common cases for conversational states.
3309 * First, the more common case, where you want a single message for both
3310 * implied and explicit greetings: just create a HelloTopic, since that
3311 * responds to both kinds. Second, the less common case, where we want
3312 * to differentiate, writing separate responses for implied and explicit
3313 * greetings: create a HelloTopic for the explicit kind, and ALSO create
3314 * an ImpHelloTopic for the implied kind. Since the ImpHelloTopic has a
3315 * higher score, it'll overshadow the HelloTopic object when it matches
3316 * an implied greeting; but since ImpHelloTopic doesn't match an
3317 * explicit greeting, we'll fall back on the HelloTopic for that.
3318 */
3319 class ImpHelloTopic: MiscTopic
3320 includeInList = [&miscTopics]
3321 matchList = [impHelloTopicObj]
3322 matchScore = 200
3323
3324 /*
3325 * this is itself a greeting, so we obviously don't want to trigger
3326 * another greeting to greet the greeting
3327 */
3328 impliesGreeting = nil
3329
3330 /*
3331 * if we use this as a greeting upon entering a ConvNode, we'll want
3332 * to stay in the node afterward
3333 */
3334 noteInvocation(fromActor)
3335 {
3336 inherited(fromActor);
3337 "<.convstay>";
3338 }
3339 ;
3340
3341 /*
3342 * Actor Hello topic - this handles greetings when an NPC initiates the
3343 * conversation.
3344 */
3345 class ActorHelloTopic: MiscTopic
3346 includeInList = [&miscTopics]
3347 matchList = [actorHelloTopicObj]
3348 matchScore = 200
3349
3350 /* this is a greeting, so we don't want to trigger another greeting */
3351 impliesGreeting = nil
3352
3353 /*
3354 * if we use this as a greeting upon entering a ConvNode, we'll want
3355 * to stay in the node afterward
3356 */
3357 noteInvocation(fromActor)
3358 {
3359 inherited(fromActor);
3360 "<.convstay>";
3361 }
3362 ;
3363
3364 /*
3365 * A goodbye topic - this handles both explicit GOODBYE commands and
3366 * implied goodbyes. Implied goodbyes happen when a conversation ends
3367 * without an explicit GOODBYE command, such as when the player character
3368 * walks away from the NPC, or the NPC gets bored and wanders off, or the
3369 * NPC terminates the conversation of its own volition.
3370 */
3371 class ByeTopic: MiscTopic
3372 includeInList = [&miscTopics]
3373 matchList = [byeTopicObj,
3374 leaveByeTopicObj, boredByeTopicObj, actorByeTopicObj]
3375
3376 /*
3377 * If we're not already in a conversation when we say GOODBYE, don't
3378 * bother saying HELLO implicitly - if the player is saying GOODBYE
3379 * explicitly, she probably has the impression that there's some kind
3380 * of interaction already going on with the NPC. If we didn't
3381 * override this, you'd get an automatic HELLO followed by the
3382 * explicit GOODBYE when not already in conversation, which is a
3383 * little weird.
3384 */
3385 impliesGreeting = nil
3386 ;
3387
3388 /*
3389 * An implied goodbye topic. This handles ONLY automatic (implied)
3390 * conversation endings, which happen when we walk away from an actor
3391 * we're talking to, or the other actor ends the conversation after being
3392 * ignored for too long, or the other actor ends the conversation of its
3393 * own volition via npc.endConversation().
3394 *
3395 * We use a higher-than-default matchScore so that any time we have both
3396 * a ByeTopic and an ImpByeTopic that are both active, we'll choose the
3397 * more specific ImpByeTopic.
3398 */
3399 class ImpByeTopic: MiscTopic
3400 includeInList = [&miscTopics]
3401 matchList = [leaveByeTopicObj, boredByeTopicObj, actorByeTopicObj]
3402 matchScore = 200
3403 ;
3404
3405 /*
3406 * A "bored" goodbye topic. This handles ONLY goodbyes that happen when
3407 * the actor we're talking terminates the conversation out of boredom
3408 * (i.e., after a period of inactivity in the conversation).
3409 *
3410 * Note that this is a subset of ImpByeTopic - ImpByeTopic handles
3411 * "bored" and "leaving" goodbyes, while this one handles only the
3412 * "bored" goodbyes. You can use this kind of topic if you want to
3413 * differentiate the responses to "bored" and "leaving" conversation
3414 * endings.
3415 */
3416 class BoredByeTopic: MiscTopic
3417 includeInList = [&miscTopics]
3418 matchList = [boredByeTopicObj]
3419 matchScore = 300
3420 ;
3421
3422 /*
3423 * A "leaving" goodbye topic. This handles ONLY goodbyes that happen
3424 * when the PC walks away from the actor they're talking to.
3425 *
3426 * Note that this is a subset of ImpByeTopic - ImpByeTopic handles
3427 * "bored" and "leaving" goodbyes, while this one handles only the
3428 * "leaving" goodbyes. You can use this kind of topic if you want to
3429 * differentiate the responses to "bored" and "leaving" conversation
3430 * endings.
3431 */
3432 class LeaveByeTopic: MiscTopic
3433 includeInList = [&miscTopics]
3434 matchList = [leaveByeTopicObj]
3435 matchScore = 300
3436 ;
3437
3438 /*
3439 * An "actor" goodbye topic. This handles ONLY goodbyes that happen when
3440 * the NPC terminates the conversation of its own volition via
3441 * npc.endConversation().
3442 */
3443 class ActorByeTopic: MiscTopic
3444 includeInList = [&miscTopics]
3445 matchList = [actorByeTopicObj]
3446 matchScore = 300
3447 ;
3448
3449 /* a topic for both HELLO and GOODBYE */
3450 class HelloGoodbyeTopic: MiscTopic
3451 includeInList = [&miscTopics]
3452 matchList = [helloTopicObj, impHelloTopicObj,
3453 byeTopicObj, boredByeTopicObj, leaveByeTopicObj,
3454 actorByeTopicObj]
3455
3456 /*
3457 * since we handle greetings, we don't want to trigger a separate
3458 * implied greeting
3459 */
3460 impliesGreeting = nil
3461 ;
3462
3463 /*
3464 * Topic singletons representing HELLO and GOODBYE topics. These are
3465 * used as the parameter to matchTopic() when we're looking for the
3466 * response to the corresponding verbs.
3467 */
3468 helloTopicObj: object;
3469 byeTopicObj: object;
3470
3471 /*
3472 * a topic singleton for implied greetings (the kind of greeting that
3473 * happens when we jump right into a conversation with a command like
3474 * ASK ABOUT or TELL ABOUT, rather than explicitly saying HELLO first)
3475 */
3476 impHelloTopicObj: object;
3477
3478 /*
3479 * a topic singleton for an NPC-initiated hello (this is the kind of
3480 * greeting that happens when the NPC is the one who initiates the
3481 * conversation, via actor.initiateConversation())
3482 */
3483 actorHelloTopicObj: object;
3484
3485
3486 /*
3487 * topic singletons for the two kinds of automatic goodbyes (the kind of
3488 * conversation ending that happens when we simply walk away from an
3489 * actor we're in conversation with, or when we ignore the other actor
3490 * for enough turns that the actor gets bored and ends the conversation
3491 * of its own volition)
3492 */
3493 boredByeTopicObj: object;
3494 leaveByeTopicObj: object;
3495
3496 /*
3497 * a topic singleton for an NPC-initiated goodbye (this is the kind of
3498 * goodbye that happens when the NPC is the one who breaks off the
3499 * conversation, via npc.endConversation())
3500 */
3501 actorByeTopicObj: object;
3502
3503 /*
3504 * A YES/NO topic. These handle YES and/or NO, which are normally used
3505 * as responses to questions posed by the NPC. YesNoTopic is the base
3506 * class, and can be used to create a single response for both YES and
3507 * NO; YesTopic provides a response just for YES; and NoTopic provides a
3508 * response just for NO. The only thing an instance of these classes
3509 * should normally need to specify is the response text (or a list of
3510 * response strings, by multiply inheriting from an EventList subclass as
3511 * usual).
3512 */
3513 class YesNoTopic: MiscTopic
3514 includeInList = [&miscTopics]
3515
3516 /*
3517 * our list of matching topic objects - we'll only ever be asked to
3518 * match 'yesTopicObj' (for YES inputs) or 'noTopicObj' (for NO
3519 * inputs)
3520 */
3521 matchList = [yesTopicObj, noTopicObj]
3522 ;
3523
3524 class YesTopic: YesNoTopic
3525 matchList = [yesTopicObj]
3526 ;
3527
3528 class NoTopic: YesNoTopic
3529 matchList = [noTopicObj]
3530 ;
3531
3532 /*
3533 * Topic singletons representing the "topic" of YES and NO commands. We
3534 * use these as the parameter to matchTopic() in the TopicEntry objects
3535 * when we're looking for a response to a YES or NO command.
3536 */
3537 yesTopicObj: object;
3538 noTopicObj: object;
3539
3540
3541 /*
3542 * A default topic entry. This is an easy way to create an entry that
3543 * will be used as a last resort, if no other entry is found. This kind
3544 * of entry will match *any* topic, but with the lowest possible score,
3545 * so it will only be used if there's no other match for the topic.
3546 *
3547 * It's a good idea to provide some variety in a character's default
3548 * responses, because it seems that in every real game session, the
3549 * player will at some point spend a while peppering an NPC with
3550 * questions on every topic that comes to mind. Usually, the player will
3551 * think of many things that the author didn't anticipate. The more
3552 * things the author covers, the better, but it's unrealistic to think
3553 * that an author can reasonably anticipate every topic, or even most
3554 * topics, that players will think of. So, we'll have a whole bunch of
3555 * ASK, ASK, ASK commands all at once, and much of the time we'll get a
3556 * bunch of default responses in a row. It gets tedious in these cases
3557 * when the NPC repeats the same default response over and over.
3558 *
3559 * A simple but effective trick is to provide three or four random
3560 * variations on "I don't know that," customized for the character. This
3561 * makes the NPC seem less like a totally predictable robot, and it can
3562 * also be a convenient place to flesh out the character a bit. An easy
3563 * way to do this is to add ShuffledEventList to the superclass list of
3564 * the default topic entry, and provide a eventList list with the various
3565 * random responses. For example:
3566 *
3567 * + DefaultAskTellTopic, ShuffledEventList
3568 *. ['Bob mutters something unintelligible and keeps fiddling with
3569 *. the radio. ',
3570 *. 'Bob looks up from the radio for a second, but then goes back
3571 *. to adjusting the knobs. ',
3572 *. 'Bob just keeps adjusting the radio, completely ignoring you. ']
3573 *. ;
3574 *
3575 * It's important to be rather generic in default responses; in
3576 * particular, it's a bad idea to suggest that the NPC doesn't know about
3577 * the topic. From the author's perspective, it's easy to make the
3578 * mistake of thinking "this is a default response, so it'll only be used
3579 * for topics that are completely off in left field." Wrong! Sometimes
3580 * the player will indeed ask about completely random stuff, but in
3581 * *most* cases, the player is only asking because they think it's a
3582 * reasonable thing to ask about. Defaults that say things like "I don't
3583 * know anything about that" or "What a crazy thing to ask about" or "You
3584 * must be stupid if you think I know about that!" can make a game look
3585 * poorly implemented, because these will inevitably be shown in response
3586 * to questions that the NPC really ought to know about:
3587 *
3588 *. >ask bob about his mother
3589 *. "I don't know anything about that!"
3590 *.
3591 *. >ask bob about his father
3592 *. "You'd have to be a moron to think I'd know about that!"
3593 *
3594 * It's better to use responses that suggest that the NPC is
3595 * uninterested, or is hostile, or is preoccupied with something else, or
3596 * doesn't understand the question, or something else appropriate to the
3597 * character. If you can manage to make the response about the
3598 * *character*, rather than the topic, it'll reduce the chances that the
3599 * response is jarringly illogical.
3600 */
3601 class DefaultTopic: TopicEntry
3602 /*
3603 * A list of objects to exclude from the default match. This can be
3604 * used to create a default topic that matches everything EXCEPT a
3605 * few specific topics that are handled in enclosing topic databases.
3606 * For example, if you want to create a catch-all in a ConvNode's
3607 * list of topics, but you want a particular topic to escape the
3608 * catch-all and be sent instead to the Actor's topic database, you
3609 * can put that topic in the exclude list for the catch-all, making
3610 * it a catch-almost-all.
3611 */
3612 excludeMatch = []
3613
3614 /* match anything except topics in our exclude list */
3615 matchTopic(fromActor, topic)
3616 {
3617 /*
3618 * If the topic matches anything in the exclusion list, do NOT
3619 * match the topic. If 'topic' is a ResolvedTopic, search its
3620 * in-scope and 'likely' lists; otherwise search for 'topic'
3621 * directly in the exclusion list.
3622 */
3623 if (topic.ofKind(ResolvedTopic))
3624 {
3625 /* it's a resolved topic, so search the in-scope/likely lists */
3626 if (topic.inScopeList.intersect(excludeMatch).length() != 0
3627 || topic.likelyList.intersect(excludeMatch).length() != 0)
3628 return nil;
3629 }
3630 else if (excludeMatch.indexOf(topic) != nil)
3631 return nil;
3632
3633 /* match anything else with our score */
3634 return matchScore;
3635 }
3636
3637 /* use a low default matching score */
3638 matchScore = 1
3639
3640 /* a match is always possible for a default topic */
3641 isMatchPossible(actor, scopeList) { return true; }
3642
3643 /* set the topic pronoun */
3644 setTopicPronouns(fromActor, topic)
3645 {
3646 /*
3647 * We're not matching anything, so we can get no guidance from
3648 * the match object. Instead, look at the topic itself. If it's
3649 * a Thing, set the Thing as the antecedent. If it's a
3650 * ResolvedTopic, and there's only one Thing match in scope, or
3651 * only one Thing match in the likely list, set that. Otherwise,
3652 * we have no grounds for guessing.
3653 */
3654 if (topic != nil)
3655 {
3656 if (topic.ofKind(Thing))
3657 {
3658 /* we have a Thing - use it as the antecedent */
3659 fromActor.setPronounObj(topic);
3660 }
3661 else if (topic.ofKind(ResolvedTopic))
3662 {
3663 local lst;
3664
3665 /*
3666 * if there's only one Thing in scope, or only one Thing
3667 * in the 'likely' list, use it
3668 */
3669 lst = topic.inScopeList.subset({x: x.ofKind(Thing)});
3670 if (lst.length() == 0)
3671 lst = topic.likelyList.subset({x: x.ofKind(Thing)});
3672
3673 /* if we got exactly one object, it's the antecedent */
3674 if (lst.length() == 1)
3675 fromActor.setPronounObj(lst[1]);
3676 }
3677 }
3678 }
3679 ;
3680
3681 /*
3682 * Default topic entries for different uses. We'll use a hierarchy of
3683 * low match scores, in descending order of specificity: 3 for
3684 * single-type defaults (ASK only, for example), 2 for multi-type
3685 * defaults (ASK/TELL), and 1 for the ANY default.
3686 */
3687 class DefaultCommandTopic: DefaultTopic
3688 includeInList = [&commandTopics]
3689 matchScore = 3
3690 ;
3691 class DefaultAskTopic: DefaultTopic
3692 includeInList = [&askTopics]
3693 matchScore = 3
3694 ;
3695 class DefaultTellTopic: DefaultTopic
3696 includeInList = [&tellTopics]
3697 matchScore = 3
3698 ;
3699 class DefaultAskTellTopic: DefaultTopic
3700 includeInList = [&askTopics, &tellTopics]
3701 matchScore = 2
3702 ;
3703 class DefaultGiveTopic: DefaultTopic
3704 includeInList = [&giveTopics]
3705 matchScore = 3
3706 ;
3707 class DefaultShowTopic: DefaultTopic
3708 includeInList = [&showTopics]
3709 matchScore = 3
3710 ;
3711 class DefaultGiveShowTopic: DefaultTopic
3712 includeInList = [&giveTopics, &showTopics]
3713 matchScore = 2
3714 ;
3715 class DefaultAskForTopic: DefaultTopic
3716 includeInList = [&askForTopics]
3717 matchScore = 3
3718 ;
3719 class DefaultAnyTopic: DefaultTopic
3720 includeInList = [&askTopics, &tellTopics, &showTopics, &giveTopics,
3721 &askForTopics, &miscTopics, &commandTopics]
3722
3723 /*
3724 * exclude these from actor-initiated hellos & goodbyes - those
3725 * should only match topics explicitly
3726 */
3727 excludeMatch = [actorHelloTopicObj, actorByeTopicObj]
3728 matchScore = 1
3729 ;
3730
3731
3732 /*
3733 * A "special" topic. This is a topic that responds to its own unique,
3734 * custom command input. In other words, rather than responding to a
3735 * normal command like ASK ABOUT or SHOW TO, we'll respond to a command
3736 * for which we define our own syntax. Our special syntax doesn't have
3737 * to follow any of the ordinary parsing conventions, because whenever
3738 * our ConvNode is active, we get a shot at parsing player input before
3739 * the regular parser gets to see it.
3740 *
3741 * A special topic MUST be part of a ConvNode, because these are
3742 * inherently meaningful only in context. A special topic is active
3743 * only when its conversation node is active.
3744 *
3745 * Special topics are automatically Suggested Topics as well as Topic
3746 * Entries. Because special topics use their own custom grammar, it's
3747 * unreasonable to expect a player to guess at the custom grammar, so we
3748 * should always provide a topic inventory suggestion for every special
3749 * topic.
3750 */
3751 class SpecialTopic: TopicEntry, SuggestedTopicTree
3752 /*
3753 * Our keyword list. Each special topic instance must define a list
3754 * of strings giving the keywords we match. The special topic will
3755 * match user input if the user input consists exclusively of words
3756 * from this keyword list. The user input doesn't have to include
3757 * all of the words defined here, but all of the words in the user's
3758 * input have to appear here to match.
3759 *
3760 * Alternatively, an instance can specifically define its own custom
3761 * regular expression pattern instead of using the keyword list; the
3762 * regular expression allows the instance to include punctuation in
3763 * the syntax, or apply more restrictive criteria than simply
3764 * matching the keywords.
3765 */
3766 keywordList = []
3767
3768 /*
3769 * Initialize the special topic. This runs during
3770 * pre-initialization, to give us a chance to do pre-game set-up.
3771 *
3772 * This routine adds the topic's keywords to the global dictionary,
3773 * under the 'special' token type. Since a special topic's keywords
3774 * are accepted when the special topic is active, it would be wrong
3775 * for the parser to claim that the words are unknown when the
3776 * special topic isn't active. By adding the keywords to the
3777 * dictionary, we let the parser know that they're valid words, so
3778 * that it won't claim that they're unknown.
3779 */
3780 initializeSpecialTopic()
3781 {
3782 /* add each keyword */
3783 foreach (local cur in keywordList)
3784 {
3785 /*
3786 * Add the keyword. Since we don't actually need the
3787 * word-to-object association that the dictionary stores,
3788 * simply associate the word with the SpecialTopic class
3789 * rather than with this particular special topic instance.
3790 * The dictionary only stores a given word-obj-prop
3791 * association once, even if it's entered repeatedly, so
3792 * tying all of the special topic keywords to the
3793 * SpecialTopic class ensures that we won't store redundant
3794 * entries if the same keyword is used in multiple special
3795 * topics.
3796 */
3797 cmdDict.addWord(SpecialTopic, cur, &specialTopicWord);
3798 }
3799 }
3800
3801 /*
3802 * our regular expression pattern - we'll build this automatically
3803 * from the keyword list if this isn't otherwise defined
3804 */
3805 matchPat = nil
3806
3807 /* our suggestion (topic inventory) base name */
3808 name = ''
3809
3810 /*
3811 * our suggestion (topic inventory) full name is usually the same as
3812 * the base name; special topics usually aren't grouped in topic
3813 * suggestion listings, since each topic usually has its own unique,
3814 * custom syntax
3815 */
3816 fullName = (name)
3817
3818 /* on being suggested, update the special topic history */
3819 noteSuggestion() { specialTopicHistory.noteListing(self); }
3820
3821 /* include in the specialTopics list of our parent topic database */
3822 includeInList = [&specialTopics]
3823
3824 /*
3825 * By default, don't limit the number of times we'll suggest this
3826 * topic. Since a special topic is valid only in a particular
3827 * ConvNode context, we normally want all of the topics in that
3828 * context to be available, even if they've been used before.
3829 */
3830 timesToSuggest = nil
3831
3832 /* check for a match */
3833 matchTopic(fromActor, topic)
3834 {
3835 /*
3836 * We match if and only if we're the current active topic for
3837 * our conversation node, as designated during our pre-parsing.
3838 * Because we're activated exclusively by our special syntax,
3839 * the only way we can ever match is by matching our special
3840 * syntax in pre-parsing; when that happens, the pre-parser
3841 * notes the matching SpecialTopic and sends a pseudo-command to
3842 * the parser to let it know to invoke the special topic's
3843 * response. We take this circuitous route to showing the
3844 * response because we do our actual matching in the pre-parse
3845 * step, but we want to do the actual command processing
3846 * normally; we can only accomplish both needs using this
3847 * two-step process, with the two steps tied together via our
3848 * memory of the topic selected in pre-parse.
3849 */
3850 if (getConvNode().activeSpecialTopic == self)
3851 return matchScore;
3852 else
3853 return nil;
3854 }
3855
3856 /*
3857 * a special topic is always matchable, since we match on literal
3858 * text
3859 */
3860 isMatchPossible(actor, scopeList) { return true; }
3861
3862 /*
3863 * Match a string during pre-parsing. By default, we'll match the
3864 * string if all of its words (as defined by the regular expression
3865 * parser) match our keywords.
3866 */
3867 matchPreParse(str, procStr)
3868 {
3869 /* build the regular expression pattern if there isn't one */
3870 if (matchPat == nil)
3871 {
3872 local pat;
3873
3874 /* start with the base pattern string */
3875 pat = '<nocase><space>*(%<';
3876
3877 /* add the keywords */
3878 for (local i = 1, local len = keywordList.length() ;
3879 i <= len ; ++i)
3880 {
3881 /* add this keyword to the pattern */
3882 pat += keywordList[i];
3883
3884 /* add the separator or terminator, as appropriate */
3885 if (i == len)
3886 pat += '%><space>*)+';
3887 else
3888 pat += '%><space>*|%<';
3889 }
3890
3891 /* create the pattern object */
3892 matchPat = new RexPattern(pat);
3893 }
3894
3895 /* we have a match if the pattern matches the processed input */
3896 return rexMatch(matchPat, procStr) == procStr.length();
3897 }
3898
3899 /* find our enclosing ConvNode object */
3900 getConvNode()
3901 {
3902 /* scan up the containment tree for a ConvNode */
3903 for (local loc = location ; loc != nil ; loc = loc.location)
3904 {
3905 /* if this is a ConvNode, it's what we're looking for */
3906 if (loc.ofKind(ConvNode))
3907 return loc;
3908 }
3909
3910 /* not found */
3911 return nil;
3912 }
3913 ;
3914
3915 /*
3916 * A history of special topics listed in topic inventories. This keeps
3917 * track of special topics that we've recently offered, so that we can
3918 * provide better feedback if the player tries to use a recently-listed
3919 * special topic after it's gone out of context.
3920 *
3921 * When the player types a command that the parser doesn't recognize, the
3922 * parser will check the special topic history to see if the command
3923 * matches a special topic that was suggested recently. If so, we'll
3924 * explain that the command isn't usable right now, rather than claiming
3925 * that the command is completely invalid. A player might justifiably
3926 * find it confusing to have the game suggest a command one minute, and
3927 * then claim that the very same command is invalid a minute later.
3928 *
3929 * Ideally, we'd search *every* special topic for a match each time the
3930 * player enters an invalid command, but that could take a long time in a
3931 * conversation-heavy game with a large number of special topics. As a
3932 * compromise, we keep track of the last few special commands that were
3933 * actually suggested, so that we can scan those. The reasoning is that
3934 * a player is more likely to try a recently-offered special command; the
3935 * player will probably eventually forget older suggestions, and in any
3936 * case it's much more jarring to see a "command not understood" response
3937 * to a suggestion that's still fresh in the player's memory.
3938 *
3939 * This is a transient object because we're interested in the special
3940 * topics that have been offered in the current session, irrespective of
3941 * things like 'undo' and 'restore'. From the player's perspective, the
3942 * recency of a special topic suggestion is a function of the transcript,
3943 * not of the internal story timeline. For example, if the game suggests
3944 * a special topic, then the player types UNDO, the player might still
3945 * think to try the special topic on the next turn simply because it's
3946 * right there on the screen a few lines up.
3947 */
3948 transient specialTopicHistory: object
3949 /*
3950 * Maximum number of topics to keep in our inventory. When the
3951 * history exceeds this number, we'll throw away the oldest entry
3952 * each time we need to add a new entry - thus, we'll always have the
3953 * N most recent suggestions.
3954 *
3955 * This can be configured as desired. The default setting tries to
3956 * strike a balance between speed and good feedback - we try to keep
3957 * track of enough entries that most players wouldn't think to try
3958 * anything that's aged out of the list, but not so many that it
3959 * takes a long time to scan them all.
3960 *
3961 * If you set this to nil, we won't keep a history at all, but
3962 * instead simply scan every special topic in the entire game when we
3963 * need to look for a match to an entered command - in a game with a
3964 * small number of special topics (on the order of, say, 30 or 40),
3965 * there should be no problem using this approach. Note that this
3966 * changes the behavior in one important way: when there's no history
3967 * limit, we can topics that *haven't even been offered yet*. In
3968 * some ways this is more desirable than only scanning past
3969 * suggestions, since it avoids weird situations where the game
3970 * claims that a command is unrecognized at one point, but later
3971 * suggests and then accepts the exact same command. It's
3972 * conceivably less desirable in that it could accidentally give away
3973 * information to the player, by letting them know that a randomly
3974 * typed command will be meaningful at some point in the game - but
3975 * the odds of this even happening seem minuscule, and the
3976 * possibility that it would give away meaningful information even if
3977 * it did happen seems very remote.
3978 */
3979 maxEntries = 20
3980
3981 /* note that a special topic 't' is being listed in a topic inventory */
3982 noteListing(t)
3983 {
3984 /*
3985 * If t's already in the list, delete it from its current
3986 * position, so that we can add it back at the end of the list,
3987 * reflecting its status as the most recent entry.
3988 */
3989 historyList.removeElement(t);
3990
3991 /*
3992 * if the list is already at capacity, remove the oldest entry,
3993 * which is the first entry in the list
3994 */
3995 if (maxEntries != nil && historyList.length() >= maxEntries)
3996 historyList.removeElementAt(1);
3997
3998 /* add the new entry at the end of the list */
3999 historyList.append(t);
4000 }
4001
4002 /*
4003 * Scan the history list (or, if there's no limit to the history,
4004 * scan all of the special topics in the entire game) for a match to
4005 * an unrecognized command. Returns true if we find a match, nil if
4006 * not.
4007 */
4008 checkHistory(toks)
4009 {
4010 local str, procStr;
4011
4012 /* get the original and processed version of the input string */
4013 str = cmdTokenizer.buildOrigText(toks);
4014 procStr = specialTopicPreParser.processInputStr(str);
4015
4016 /*
4017 * scan each special topic in the history - or, if the history is
4018 * unlimited, scan every special topic
4019 */
4020 if (maxEntries != nil)
4021 {
4022 /* scan each entry in our history list */
4023 for (local l = historyList, local i = 1, local len = l.length() ;
4024 i <= len ; ++i)
4025 {
4026 /* check this entry */
4027 if (l[i].matchPreParse(str, procStr))
4028 return true;
4029 }
4030 }
4031 else
4032 {
4033 /* no history limit - scan every special topic in the game */
4034 for (local o = firstObj(SpecialTopic) ; o != nil ;
4035 o = nextObj(o, SpecialTopic))
4036 {
4037 /* check this entry */
4038 if (o.matchPreParse(str, procStr))
4039 return true;
4040 }
4041 }
4042
4043 /* we didn't find a match */
4044 return nil;
4045 }
4046
4047 /*
4048 * The list of entries. Create it when we first need it, which
4049 * perInstance does for us.
4050 */
4051 historyList = perInstance(new transient Vector(maxEntries))
4052 ;
4053
4054 /*
4055 * An "initiate" topic entry. This is a rather different kind of topic
4056 * entry from the ones we've defined so far; an initiate topic is for
4057 * cases where the NPC itself wants to initiate a conversation in
4058 * response to something in the environment.
4059 *
4060 * One way to use initiate topics is to use the current location as the
4061 * topic key. This lets the NPC say something appropriate to the current
4062 * room, and can be coded simply as
4063 *
4064 *. actor.initiateTopic(location);
4065 */
4066 class InitiateTopic: ThingMatchTopic
4067 /* include in the initiateTopics list */
4068 includeInList = [&initiateTopics]
4069
4070 /*
4071 * since this kind of topic is triggered by internal calculations in
4072 * the game, and not on anything the player is doing, there's no
4073 * reason that our match object should be a pronoun antecedent
4074 */
4075 setTopicPronouns(fromActor, topic) { }
4076 ;
4077
4078 /* a catch-all default initiate topic */
4079 class DefaultInitiateTopic: DefaultTopic
4080 includeInList = [&initiateTopics]
4081 ;
4082
4083
4084 /* ------------------------------------------------------------------------ */
4085 /*
4086 * An ActorState represents the current state of an Actor.
4087 *
4088 * The main thing that makes actors special is that they're supposed to
4089 * be living, breathing people or creatures. That substantially
4090 * complicates the programming of one of these objects, because in order
4091 * to create the appearance of animation, many things about an actor have
4092 * to change over time.
4093 *
4094 * The ActorState is designed to make it easier to program this
4095 * variability that's needed to make an actor seem life-like. The idea
4096 * is to separate the parts of an actor that tend to change according to
4097 * what the actor is doing, moving all of those out of the Actor object
4098 * and into an ActorState object instead. Each ActorState object
4099 * represents one state of an actor (i.e., one thing the actor can be
4100 * doing). The Actor object becomes easier to program, because we've
4101 * reduced the Actor object to the character's constant, unchanging
4102 * features. The stateful part is also easier to program, because we
4103 * don't have to make it conditional on anything; we simply define all of
4104 * the stateful parts in an ActorState, and we define separate ActorState
4105 * objects for the different states.
4106 *
4107 * For example, suppose we want a shopkeeper actor, whose activities
4108 * include waiting behind the counter, sweeping the floor, and stacking
4109 * cans. We'd define one ActorState object for each of these activities.
4110 * When the shopkeeper switches from standing behind the counter to
4111 * sweeping, for example, we simply set the "curState" property in the
4112 * shopkeeper object so that it points to the "sweeping" state object.
4113 * When it's time to stack cans, we change "curState" to it points to the
4114 * "stacking cans" state object.
4115 */
4116 class ActorState: TravelMessageHandler, ActorTopicDatabase
4117 construct(actor) { location = actor; }
4118
4119 /*
4120 * Activate the state - this is called when we're about to become
4121 * the active state for an actor. We do nothing by default.
4122 */
4123 activateState(actor, oldState) { }
4124
4125 /*
4126 * Deactivate the state - this is called when we're the active state
4127 * for an actor, and the actor is about to switch to a new state.
4128 * We do nothing by default.
4129 */
4130 deactivateState(actor, newState) { }
4131
4132 /*
4133 * Is this the actor's initial state? If so, we'll automatically
4134 * set the actor's curState to point to 'self' during
4135 * pre-initialization. For obvious reasons, this should be set to
4136 * true for only one state for each actor; if multiple states are
4137 * all flagged as initial for the same actor, we'll pick on
4138 * arbitrarily as the actual initial state.
4139 */
4140 isInitState = nil
4141
4142 /*
4143 * Should we automatically suggest topics when the player greets our
4144 * actor? By default, we show our "topic inventory" (the list of
4145 * currently active topics marked as "suggested"). This can be set
4146 * to nil to suppress this automatic suggestion list.
4147 *
4148 * Some authors might not like the idea of automatically suggesting
4149 * topics every time we greet a character, but nonetheless wish to
4150 * keep the TOPICS command as a sort of hint mechanism. This flag
4151 * can be used for this purpose. Authors who don't like suggested
4152 * topics at all can simply skip defining any SuggestedTopic entries,
4153 * in which case there will never be anything to suggest, rendering
4154 * this flag moot.
4155 */
4156 autoSuggest = true
4157
4158 /*
4159 * The 'location' is the actor that we're associated with.
4160 *
4161 * ActorState objects aren't actual simulation objects, so the
4162 * 'location' property isn't used for containment. For convenience,
4163 * though, use it to indicate which actor we're associated with; this
4164 * lets us use the '+' notation to define the state objects
4165 * associated with an actor.
4166 */
4167 location = nil
4168
4169 /*
4170 * Get the actor associated with the state - this is simply the
4171 * 'location' property. If we're nested inside another ActorState,
4172 * then our actor is our enclosing ActorState's actor.
4173 */
4174 getActor()
4175 {
4176 if (location.ofKind(ActorState))
4177 return location.getActor();
4178 else
4179 return location;
4180 }
4181
4182 /* the owner of any topic entries within the state is just my actor */
4183 getTopicOwner() { return getActor(); }
4184
4185 /* initialize the actor state */
4186 initializeActorState()
4187 {
4188 /*
4189 * if we're the initial state for our actor, set the actor's
4190 * current state property to point to me
4191 */
4192 if (isInitState)
4193 getActor().setCurState(self);
4194 }
4195
4196 /*
4197 * Show the special description for the actor when the actor is
4198 * associated with this state. By default, we use the actor's
4199 * actorHereDesc message, which usually shows a generic message
4200 * (something like "Bob is here" or "Bob is sitting on the chair") to
4201 * indicate that the actor is present.
4202 *
4203 * States representing scripted activities should override these to
4204 * indicate what the actor is doing: "Bob is sweeping the floor," for
4205 * example.
4206 */
4207 specialDesc() { getActor().actorHereDesc; }
4208
4209 /* show the special description for the actor at a distance */
4210 distantSpecialDesc() { getActor().actorThereDesc; }
4211
4212 /* show the special description for the actor in a remote location */
4213 remoteSpecialDesc(actor) { getActor().actorThereDesc; }
4214
4215 /*
4216 * The list group(s) for the special description. By default, if
4217 * our specialDesc isn't overridden, we'll keep this in sync with
4218 * the specialDesc by returning our actor's actorListWith. And if
4219 * specialDesc *is* overridden, we'll just return an empty list to
4220 * indicate that we're not part of any list group. If you want to
4221 * provide your own listing group special to the state, simply
4222 * override this and speicfy the custom list group.
4223 */
4224 specialDescListWith()
4225 {
4226 /*
4227 * if specialDesc is inherited from ActorState, then use the
4228 * default handling from the actor; otherwise, use no grouping at
4229 * all by default
4230 */
4231 if (!overrides(self, ActorState, &specialDesc))
4232 return getActor().actorListWith;
4233 else
4234 return [];
4235 }
4236
4237 /* show the special description when we appear in a contents listing */
4238 showSpecialDescInContents(actor, cont)
4239 {
4240 /* by default, just show our posture in our container */
4241 getActor().listActorPosture(actor);
4242 }
4243
4244 /*
4245 * Our "state" description. This shows information on what the actor
4246 * is *currently* doing; we display this after the static part of the
4247 * actor's description on EXAMINE <ACTOR>. By default, we add
4248 * nothing here, but state objects that represent scripted activies
4249 * should override this to describe their scripted activities.
4250 */
4251 stateDesc = ""
4252
4253 /*
4254 * Should we obey an action? If so, returns true; if not, displays
4255 * an appropriate response and returns nil. This will only be
4256 * called when the issuing actor is different from our actor, since
4257 * a command to oneself is implicitly always obeyed.
4258 */
4259 obeyCommand(issuingActor, action)
4260 {
4261 /*
4262 * By default, we ignore all orders. We do need to generate a
4263 * response, though, so for this purpose, treat the order as a
4264 * conversational action, with the 'action' object as the topic.
4265 */
4266 handleConversation(issuingActor, action, commandConvType);
4267
4268 /* indicate that the order is refused */
4269 return nil;
4270 }
4271
4272 /*
4273 * Suggest topics for the given actor to talk to us about. This is
4274 * called when the given actor enters a TOPICS command (in which
4275 * case 'explicit' will be true) or enters a conversation with us
4276 * via TALK TO or the like (in which case 'explicit' will be nil).
4277 */
4278 suggestTopicsFor(actor, explicit)
4279 {
4280 /*
4281 * if this is not an explicit TOPICS request, and we're not in
4282 * "auto suggest" mode, don't show anything - we don't want any
4283 * automatic suggestions in this mode
4284 */
4285 if (!explicit && !autoSuggest)
4286 return;
4287
4288 /*
4289 * show a paragraph break, in case we're being tacked on to
4290 * another report; but make it cosmetic, so that this by itself
4291 * doesn't suppress a default report, in case we don't end up
4292 * displaying any topics
4293 */
4294 cosmeticSpacingReport('<.p>');
4295
4296 /* show our suggestion list */
4297 showSuggestedTopicList(getSuggestedTopicList(),
4298 actor, getActor(), explicit);
4299 }
4300
4301 /*
4302 * Get our suggested topic list. The suggested topic list consists
4303 * of the union of the current ConvNode's suggestion list, the
4304 * ActorState list, and the Actor's suggestion list. In each case,
4305 * the suggestion list is the list of all SuggestedTopic objects at
4306 * each database level.
4307 *
4308 * The suggestions are arranged in a hierarchy, and each hierarchy
4309 * level can prevent suggestions from a lower level from being
4310 * included. The top level of the hierarchy is the ConvNode; the
4311 * next level is the ActorState; and the last level is the Actor.
4312 * Suggestions are limited at each level with the 'limitSuggestions'
4313 * property: if true, suggestions from lower levels are not included.
4314 */
4315 getSuggestedTopicList()
4316 {
4317 local v = new Vector(16);
4318 local node;
4319 local lst;
4320
4321 /* add the actor's current conversation node topics */
4322 if ((node = getActor().curConvNode) != nil)
4323 {
4324 /* if there are any suggested topics in the node, include them */
4325 if ((lst = node.suggestedTopics) != nil)
4326 v.appendAll(lst);
4327
4328 /*
4329 * if this ConvNode is marked as limiting suggestions to
4330 * those defined within the node, return what we have
4331 * without adding anything from the broader context
4332 */
4333 if (node.limitSuggestions)
4334 return v;
4335 }
4336
4337 /* add our own topics */
4338 if ((lst = stateSuggestedTopics) != nil)
4339 v.appendAll(lst);
4340
4341 /*
4342 * if the ActorState is limiting suggestions, don't include any
4343 * suggestions from the broader context (i.e., from the Actor
4344 * itself)
4345 */
4346 if (limitSuggestions)
4347 return v;
4348
4349 /* if our actor has its own list, add those as well */
4350 if ((lst = getActor().suggestedTopics) != nil)
4351 v.appendAll(lst);
4352
4353 /* return the combined list */
4354 return v;
4355 }
4356
4357 /*
4358 * get the topic suggestions for this state - by default, we just
4359 * return our own suggestedTopics list
4360 */
4361 stateSuggestedTopics = (suggestedTopics)
4362
4363 /*
4364 * Get my implied in-conversation state. This is used when our actor
4365 * initiates a conversation without specifying a particular
4366 * conversation state to enter (i.e., actor.initiateConversation() is
4367 * called with 'state' set to nil). By default, we don't have an
4368 * implied conversation state, so we just return 'self' to indicate
4369 * that we want to stay in the current state. States that are
4370 * coupled with separate in-conversation states, such as
4371 * ConversationReadyState, should return their associated
4372 * conversation states here.
4373 */
4374 getImpliedConvState = (self)
4375
4376 /*
4377 * General conversation handler. This can be used to process most
4378 * conversational commands - ASK, TELL, GIVE, SHOW, etc. The
4379 * standard sequence of processing is as follows:
4380 *
4381 * - If our actor has a non-nil current conversation node (ConvNode)
4382 * object, and the ConvNode wants to handle the event, let the
4383 * ConvNode handle it.
4384 *
4385 * - Otherwise, check our own topic database to see if we can find a
4386 * TopicEntry that matches the topic; if we can find one, let the
4387 * TopicEntry handle it.
4388 *
4389 * - Otherwise, let the actor handle it.
4390 *
4391 * 'otherActor' is the actor who originated the conversation command
4392 * (usually the player character). 'topic' is the subject being
4393 * discussed (the indirect object of ASK ABOUT, for example).
4394 * convType' is a ConvType describing the type of conversational
4395 * action we're performing.
4396 */
4397 handleConversation(otherActor, topic, convType)
4398 {
4399 local actor = getActor();
4400 local hasDefault;
4401 local node;
4402 local path;
4403
4404 /* determine if I have a default response handler */
4405 hasDefault = propDefined(convType.defaultResponseProp);
4406
4407 /*
4408 * Figure the database search path for looking up the topics.
4409 * We'll start in the ConvNode database, then continue to the
4410 * ActorState database, then finally to the Actor database.
4411 * However, we won't reach the Actor database if there's a
4412 * default response handler in the state, because if we fail to
4413 * find it at the state, we'll take the default.
4414 *
4415 * Since the path we need to provide at each point is the
4416 * *remaining* path, don't bother including the ConvNode, since
4417 * we'd just have to take it right back out to get the remaining
4418 * path after the ConvNode.
4419 */
4420 path = [self];
4421 if (!hasDefault)
4422 path += actor;
4423
4424 /*
4425 * If our actor has a current conversation node, check to see if
4426 * the conversation node wants to handle it. If not, check our
4427 * own topic database, then the actor's.
4428 */
4429 if ((node = actor.curConvNode) == nil
4430 || !node.handleConversation(otherActor, topic, convType, path))
4431 {
4432 /* get the remaining database search path */
4433 path = path.sublist(2);
4434
4435 /*
4436 * Either we don't have a ConvNode, or the ConvNode isn't
4437 * interested in handling the operation. Check to see if we
4438 * can handle it through our own topic database.
4439 */
4440 if (!handleTopic(otherActor, topic, convType, path))
4441 {
4442 /*
4443 * We couldn't find anything in our topic database that's
4444 * interested in handling it. Check to see if the state
4445 * object defines the default response handler method,
4446 * and use that as the response if so.
4447 */
4448 if (hasDefault)
4449 {
4450 /*
4451 * the state object (i.e., self) does define the
4452 * default response method, so invoke that
4453 */
4454 convType.defaultResponse(self, otherActor, topic);
4455 }
4456 else
4457 {
4458 /*
4459 * We don't have a topic database entry and we don't
4460 * have our own definition of the default response
4461 * handler. All that remains is to let our actor
4462 * handle it.
4463 */
4464 actor.handleConversation(otherActor, topic, convType);
4465 }
4466 }
4467 }
4468
4469 /* whatever happened, run the appropriate after-response handling */
4470 convType.afterResponse(actor, otherActor);
4471 }
4472
4473 /*
4474 * Receive notification that a TopicEntry is being used (via its
4475 * handleTopic method) to respond to a command. The TopicEntry will
4476 * call this before it shows its message or takes any other action.
4477 * By default, we do nothing.
4478 */
4479 notifyTopicResponse(fromActor, entry) { }
4480
4481 /*
4482 * Handle a before-action notification for our actor. By default,
4483 * we do nothing.
4484 */
4485 beforeAction()
4486 {
4487 /* do nothing by default */
4488 }
4489
4490 /* handle an after-action notification for our actor */
4491 afterAction()
4492 {
4493 }
4494
4495 /* handle a before-travel notification */
4496 beforeTravel(traveler, connector)
4497 {
4498 local other = getActor().getCurrentInterlocutor();
4499
4500 /*
4501 * if our conversational partner is departing, break off the
4502 * conversation
4503 */
4504 if (connector != nil
4505 && other != nil
4506 && traveler.isActorTraveling(other))
4507 {
4508 /* end the conversation */
4509 if (!endConversation(gActor, endConvTravel))
4510 {
4511 /*
4512 * they don't want to allow the conversation to end, so
4513 * abort the travel action
4514 */
4515 exit;
4516 }
4517 }
4518 }
4519
4520 /* handle an after-travel notification */
4521 afterTravel(traveler, connector)
4522 {
4523 }
4524
4525 /*
4526 * End the current conversation. 'reason' indicates why we're
4527 * leaving the conversation - this is one of the endConvXxx enums
4528 * defined in adv3.h. beforeTravel() calls this automatically when
4529 * the other party is trying to depart, and they're talking to us.
4530 *
4531 * This returns true if we wish to allow the conversation to end,
4532 * nil if not.
4533 */
4534 endConversation(actor, reason)
4535 {
4536 local ourActor = getActor();
4537 local node;
4538
4539 /* tell the current ConvNode about it */
4540 if ((node = ourActor.curConvNode) != nil)
4541 {
4542 local ret;
4543
4544 /* the can-end call might show a response, so set our actor */
4545 conversationManager.beginResponse(ourActor);
4546
4547 /* ask the node if it's okay to end the conversation */
4548 ret = node.canEndConversation(actor, reason);
4549
4550 /*
4551 * If the result is blockEndConv, it means that the actor
4552 * said something to force the conversation to keep going.
4553 * Make a note that the other actor already said something on
4554 * this turn so that we don't generate another scripted
4555 * message later, and flag this as preventing the
4556 * conversation ending.
4557 */
4558 if (ret == blockEndConv)
4559 {
4560 /* flag that the other actor said something this turn */
4561 ourActor.noteConvAction(actor);
4562
4563 /* we're unable to end the conversation now */
4564 ret = nil;
4565 }
4566
4567 /* end the response, leaving the node unchanged by default */
4568 conversationManager.finishResponse(
4569 ourActor, ourActor.curConvNode);
4570
4571 /*
4572 * if the node said no, tell the caller we can't end the
4573 * conversation right now
4574 */
4575 if (!ret)
4576 return nil;
4577
4578 /* tell the node we are indeed ending the conversation */
4579 node.endConversation(actor, reason);
4580 }
4581
4582 /* forget any conversation tree position */
4583 ourActor.setConvNodeReason(nil, 'endConversation');
4584
4585 /* indicate that we are allowing the conversation to end */
4586 return true;
4587 }
4588
4589 /*
4590 * Take a turn. This is called when it's the actor's turn and
4591 * there's not something else the actor needs to be doing (such as
4592 * following another actor, or carrying out a command in the actor's
4593 * pending command queue).
4594 *
4595 * By default, we perform several steps automatically.
4596 *
4597 * First, we check to see if the actor is in a ConvNode. If so, the
4598 * ConvNode takes precedence. If we haven't been addressed already
4599 * in conversation on this turn, we'll let the ConvNode perform its
4600 * "continuation," which lets the NPC advance the conversation of its
4601 * own volition. In any case, if we have a current ConvNode, we're
4602 * done with the turn, since we assume the actor will want to proceed
4603 * with the conversation before pursuing its agenda or performing a
4604 * background action.
4605 *
4606 * Second, assuming there's no active ConvNode, we check for an
4607 * "agenda" item that's ready to execute. If we find one, we execute
4608 * it, and we're done. The agenda item takes precedence over any
4609 * other scripting we might have.
4610 *
4611 * Finally, if we also inherit from Script, and we didn't find an
4612 * active ConvNode or an agenda item that was ready to execute, we
4613 * invoke our doScript() method. This makes it especially easy to
4614 * define random background messages for the actor - just add an
4615 * EventList class (ShuffledEventList is usually the right one) to
4616 * the state's superclass list, and define a list of background
4617 * message strings.
4618 */
4619 takeTurn()
4620 {
4621 local actor = getActor();
4622
4623 /*
4624 * Check to see if we want to continue a conversation. If so,
4625 * and we haven't already conversed this turn, try the
4626 * continuing conversation. If that displays anything, consider
4627 * the turn done.
4628 *
4629 * Otherwise, try executing an agenda item. If we do, consider
4630 * the turn done.
4631 *
4632 * Otherwise, if we're of class Script, execute our scripted
4633 * action.
4634 */
4635 if (actor.curConvNode != nil
4636 && !actor.conversedThisTurn()
4637 && actor.curConvNode.npcContinueConversation())
4638 {
4639 /*
4640 * we displayed an NPC-motivated conversation continuation,
4641 * so we're done with this turn
4642 */
4643 }
4644 else if (actor.executeAgenda())
4645 {
4646 /* we executed an agenda item, so we need do nothing more */
4647 }
4648 else if (ofKind(Script))
4649 {
4650 /* we're a Script, so invoke our scripted action */
4651 doScript();
4652 }
4653 }
4654
4655 /*
4656 * Receive notification that we just followed another actor as part
4657 * of our programmed following behavior (in other words, due to our
4658 * 'followingActor' property, not due to an explicit FOLLOW command
4659 * directed to us). 'success' is true if we ended up in the actor's
4660 * location, nil if not.
4661 *
4662 * This can be used to update the actor's state after a 'follow'
4663 * operation occurs; for example, if the actor's state depends on
4664 * the actor's location, this can update the state accordingly. We
4665 * don't do anything by default.
4666 */
4667 justFollowed(success)
4668 {
4669 /* do nothing by default */
4670 }
4671
4672 /*
4673 * Our group-travel arrival description. By default, when we perform
4674 * an accompanying travel with another actor as the lead actor, the
4675 * accompanying travel state will display this message instead of our
4676 * specialDesc when the lead actor first arrives in the new location.
4677 * We'll just display our own specialDesc by default, but this should
4678 * usually be overridden to say something specific to the group
4679 * travel arrival. The actual message is entirely dependent on the
4680 * nature of the group travel, which is why we don't provide a
4681 * special message by default.
4682 *
4683 * For scripted behavior, it's sometimes better to use arrivingTurn()
4684 * rather than this method to describe the behavior.
4685 * arrivingWithDesc() is called as part of the room description, so
4686 * it's best for any message shown here to fit well into the usual
4687 * room description format. For more complex transitions into the
4688 * new room state, arrivingTurn() is sometimes more appropriate,
4689 * since it runs like a daemon, after the arrival (and thus the new
4690 * room description) is completed.
4691 */
4692 arrivingWithDesc() { specialDesc(); }
4693
4694 /*
4695 * Perform any special action on a group-travel arrival. When group
4696 * travel is performed using the AccompanyingInTravelState class,
4697 * this is essentially called in lieu of the regular takeTurn()
4698 * method on the state that is coming into effect after the group
4699 * travel. (Not really, but effectively: the accompanying travel
4700 * state will still be in effect, so its takeTurn() method is what's
4701 * really called, but that method will call this method explicitly.)
4702 * By default, we do nothing. Since this runs on our turn, it's a
4703 * good place to put any scripted behavior we perform on arriving at
4704 * our new destination after the group travel.
4705 */
4706 arrivingTurn() { }
4707
4708 /*
4709 * For our TravelMessageHandler implementation, the nominal traveler
4710 * is our actor. Note that this is all we need to implement for
4711 * travel message handling, since we simply inherit the default
4712 * handling for all of the arrival/departure messages.
4713 */
4714 getNominalTraveler() { return getActor(); }
4715 ;
4716
4717 /*
4718 * A "ready for conversation" state. This can be used as the base class
4719 * for actor states when the actor is receptive to conversation, and we
4720 * want to have the sense of a conversational context. The key feature
4721 * that this class provides is the ability to provide messages when
4722 * engaging and disengaging the conversation.
4723 *
4724 * Note that this state is NOT required for conversation, since the basic
4725 * ActorState object accepts conversational commands like ASK, TELL,
4726 * GIVE, and TAKE. The special feature of the "conversation ready" state
4727 * is that we explicitly move the actor to a separate state when
4728 * conversation begins. This is especially appropriate for states in
4729 * which the NPC is actively carrying on some other activity; the
4730 * conversation should interrupt those states, so that the actor stops
4731 * the other activity and gives us its full attention.
4732 *
4733 * This type of state can be associated with its in-conversation state
4734 * object in one of two ways. First, the inConvState property can be
4735 * explicitly set to point to the in-conversation state object. Second,
4736 * this object can be nested inside its in-conversation state object via
4737 * the 'location' property (so you can use the '+' syntax to put this
4738 * object inside its in-conversation state object). The 'ready' object
4739 * goes inside the 'conversing' object because a single 'conversing'
4740 * object can frequently be shared among several 'ready' states.
4741 */
4742 class ConversationReadyState: ActorState
4743 /*
4744 * The associated in-conversation state. This should be set to an
4745 * InConversationState object that controls the actor's behavior
4746 * while carrying on a conversation. Note that the library will
4747 * automatically set this if the instance is nested (via its
4748 * 'location' property) inside an InConversationState object.
4749 */
4750 inConvState = nil
4751
4752 /* my implied conversational state is my in-conversation state */
4753 getImpliedConvState = (inConvState)
4754
4755 /*
4756 * Show our greeting message. If 'explicit' is true, it means that
4757 * the player character is greeting us through an explicit greeting
4758 * command, such as HELLO or TALK TO. Otherwise, the greeting is
4759 * implied by some other conversational action, such a ASK ABOUT or
4760 * SHOW TO. We do nothing by default; this should be overridden in
4761 * most cases to show some sort of exchange of pleasantries -
4762 * something like this:
4763 *
4764 *. >bob, hello
4765 *. "Hi, there," you say.
4766 *
4767 * Bob looks up over his newspaper. "Oh, hello," he says, putting
4768 * down the paper. "What can I do for you?"
4769 *
4770 * Note that games shouldn't usually override this method. Instead,
4771 * you should simply create a HelloTopic entry and put it inside the
4772 * state object; we'll find the HelloTopic and show its message as
4773 * our greeting.
4774 *
4775 * If you want to distinguish between explicit and implicit
4776 * greetings, you can create an ImpHelloTopic entry for implied
4777 * greetings (i.e., the kind of greeting that occurs automatically
4778 * when the player jumps right into a conversation with our actor
4779 * using ASK ABOUT or the like, without explicitly saying HELLO
4780 * first). The regular HelloTopic will handle explicit greetings,
4781 * and the ImpHelloTopic will handle the implied kind.
4782 */
4783 showGreetingMsg(actor, explicit)
4784 {
4785 /* look for a HelloTopic in our topic database */
4786 if (handleTopic(actor, explicit ? helloTopicObj : impHelloTopicObj,
4787 helloConvType, nil))
4788 "<.p>";
4789 }
4790
4791 /*
4792 * Enter this state from a conversation. This should show any
4793 * message we want to display when we're ending a conversation and
4794 * switching from the conversation to this state. 'reason' is the
4795 * endConvXxx enum indicating what triggered the termination of the
4796 * conversation. 'oldNode' is the ConvNode we were in just before we
4797 * initiated the termination - we need this information because we
4798 * want to look in the ConvNode for a Bye topic message to display,
4799 * but we can't just look in the actor for the node because it will
4800 * already have been cleared out by the time we get here.
4801 *
4802 * Games shouldn't normally override this method. Instead, simply
4803 * create a ByeTopic entry and put it inside the state object; we'll
4804 * find the ByeTopic and show its message for the goodbye.
4805 *
4806 * If you want to distinguish between different types of goodbyes,
4807 * you can create an ImpByeTopic for any implied goodbye (i.e., the
4808 * kind where the other actor just walks away, or where we get bored
4809 * of the other actor ignoring us). You can also further
4810 * differentiate by creating BoredByeTopic and/or LeaveByeTopic
4811 * objects to handle just those cases. The regular ByeTopic will
4812 * handle explicit GOODBYE commands, and the others (ImpByeTopic,
4813 * BoredByeTopic, LeaveByeTopic) will handle the implied kinds.
4814 */
4815 enterFromConversation(actor, reason, oldNode)
4816 {
4817 local topic;
4818 local reasonMap = [endConvBye, byeTopicObj,
4819 endConvTravel, leaveByeTopicObj,
4820 endConvBoredom, boredByeTopicObj,
4821 endConvActor, actorByeTopicObj];
4822
4823 /* figure out which topic object we need, based on the reason code */
4824 topic = reasonMap[reasonMap.indexOf(reason) + 1];
4825
4826 /*
4827 * Look for a ByeTopic in the ConvNode; failing that, try our own
4828 * database.
4829 */
4830 if (oldNode == nil
4831 || !oldNode.handleConversation(actor, topic, byeConvType, nil))
4832 {
4833 /* there's no node handler; try our own database */
4834 handleTopic(actor, topic, byeConvType, nil);
4835 }
4836 }
4837
4838 /* handle a conversational action directed to our actor */
4839 handleConversation(otherActor, topic, convType)
4840 {
4841 /*
4842 * If this is a greeting, handle it ourselves. Otherwise, pass
4843 * it along to our associated in-conversation state.
4844 */
4845 if (convType == helloConvType)
4846 {
4847 /*
4848 * Switch to our associated in-conversation state and show a
4849 * greeting. Since we're explicitly entering the
4850 * conversation, we have no topic entry.
4851 */
4852 enterConversation(otherActor, nil);
4853
4854 /* show or schedule a topic inventory, as appropriate */
4855 conversationManager.showOrScheduleTopicInventory(
4856 getActor(), otherActor);
4857 }
4858 else
4859 {
4860 /*
4861 * it's not a greeting, so pass it to our in-conversation
4862 * state for handling
4863 */
4864 inConvState.handleConversation(otherActor, topic, convType);
4865 }
4866 }
4867
4868 /*
4869 * Initiate conversation based on the given simulation object. This
4870 * is an internal method that isn't usually called directly from game
4871 * code; game code usually calls the Actor's initiateTopic(), which
4872 * calls this routine to check for a topic that's part of the state
4873 * object.
4874 */
4875 initiateTopic(obj)
4876 {
4877 /* defer to our in-conversation state */
4878 return inConvState.initiateTopic(obj);
4879 }
4880
4881 /*
4882 * Receive notification that a TopicEntry is being used (via its
4883 * handleTopic method) to respond to a command. If the TopicEntry is
4884 * conversational, automatically enter our in-conversation state.
4885 */
4886 notifyTopicResponse(fromActor, entry)
4887 {
4888 if (entry.isConversational)
4889 enterConversation(fromActor, entry);
4890 }
4891
4892 /*
4893 * Enter a conversation with the given actor, either explicitly (via
4894 * HELLO or TALK TO) or implicitly (by directly asking a question,
4895 * etc). 'entry' gives the TopicEntry that's triggering the implicit
4896 * conversation entry; if this is nil, it means that we're being
4897 * triggered explicitly.
4898 */
4899 enterConversation(actor, entry)
4900 {
4901 local myActor = getActor();
4902 local explicit = (entry == nil);
4903
4904 /* if the actor can't talk to us, we can't enter the conversation */
4905 if (!actor.canTalkTo(myActor))
4906 {
4907 /* tell them we can't talk now */
4908 reportFailure(&objCannotHearActorMsg, myActor);
4909
4910 /* terminate the command */
4911 exit;
4912 }
4913
4914 /*
4915 * Show our greeting, if desired. We show a greeting if we're
4916 * being invoked explicitly (that is, there's no TopicEntry), or
4917 * if we're being invoked explicitly and the TopicEntry implies a
4918 * greeting.
4919 */
4920 if (explicit || entry.impliesGreeting)
4921 showGreetingMsg(actor, explicit);
4922
4923 /* activate the in-conversation state */
4924 myActor.setCurState(inConvState);
4925 }
4926
4927 /*
4928 * Get this state's suggested topic list. ConversationReady states
4929 * shouldn't normally have topic entries of their own, since a
4930 * ConvversationReady state usually forwards conversation handling
4931 * to its corresponding in-conversation state. So, simply return
4932 * the suggestion list from our in-conversation state object.
4933 */
4934 stateSuggestedTopics = (inConvState.suggestedTopics)
4935
4936 /* initialize the actor state object */
4937 initializeActorState()
4938 {
4939 /* inherit the default handling */
4940 inherited();
4941
4942 /*
4943 * if we're nested inside an in-conversation state object, the
4944 * containing in-conversation state is the one we'll use for
4945 * conversations
4946 */
4947 if (location.ofKind(InConversationState))
4948 inConvState = location;
4949 }
4950 ;
4951
4952 /*
4953 * The "in-conversation" state. This works with ConversationReadyState
4954 * to handle transitions in and out of conversations. In this state, we
4955 * are actively engaged in a conversation.
4956 *
4957 * Throughout this implementation, we assume that we only care about
4958 * conversations with a single character, specifically the player
4959 * character. There's generally no good reason to fully model
4960 * conversations between NPC's, since that kind of NPC activity is in
4961 * most cases purely pre-scripted and thus requires no special state
4962 * tracking. Since we generally only need to worry about tracking a
4963 * conversation with the player character, we don't bother with the
4964 * possibility that we're simultaneously in conversation with more than
4965 * one other character.
4966 */
4967 class InConversationState: ActorState
4968 /*
4969 * Our attention span, in turns. This is the number of turns that
4970 * we'll be willing to stay in the conversation while the other
4971 * character is ignoring us. After the conversation has been idle
4972 * this long, we'll assume the other actor is no longer talking to
4973 * us, so we'll terminate the conversation ourselves.
4974 *
4975 * If the NPC's doesn't have a limited attention span, set this
4976 * property to nil. This will prevent the NPC from ever disengaging
4977 * of its own volition.
4978 */
4979 attentionSpan = 4
4980
4981 /*
4982 * The state to switch to when the conversation ends. Instances can
4983 * override this to select the next state. By default, we'll return
4984 * to the state that we were in immediately before the conversation
4985 * started.
4986 */
4987 nextState = (previousState)
4988
4989 /*
4990 * End the current conversation. 'reason' indicates why we're
4991 * leaving the conversation - this is one of the endConvXxx enums
4992 * defined in adv3.h.
4993 *
4994 * This method is a convenience only; you aren't required to call
4995 * this method to end the conversation, since you can simply switch
4996 * to another actor state directly if you prefer. This method's
4997 * main purpose is to display an appropriate message terminating the
4998 * conversation while switching to the new state. If you want to
4999 * display your own message directly from the code that's changing
5000 * the state, there's no reason to call this.
5001 *
5002 * This returns true if we wish to allow the conversation to end,
5003 * nil if not.
5004 */
5005 endConversation(actor, reason)
5006 {
5007 local nxt;
5008 local myActor = getActor();
5009
5010 /*
5011 * note the current ConvNode for our actor - when we check with
5012 * the ConvNode to see about ending the conversation, this will
5013 * automatically exit the ConvNode, so we need to save this first
5014 * so that we can refer to it later to check for a Bye topic
5015 */
5016 local oldNode = myActor.curConvNode;
5017
5018 /*
5019 * Inherit the base behavior first - if it disallows the action,
5020 * return failure. The inherited version will check with the
5021 * current ConvNode to see if has any objection.
5022 */
5023 if (!inherited(actor, reason))
5024 return nil;
5025
5026 /* get the next state */
5027 nxt = nextState;
5028
5029 /* if there isn't one, stay in the actor's current state */
5030 if (nxt == nil)
5031 nxt = myActor.curState;
5032
5033 /*
5034 * If the next state is a 'conversation ready' state, tell it
5035 * we're entering from a conversation. We're ending the
5036 * conversation explicitly only if 'reason' is endConvBye. Pass
5037 * along the ConvNode we just exited (if any), so that we can
5038 * look for a response in the node.
5039 */
5040 if (nxt.ofKind(ConversationReadyState))
5041 nxt.enterFromConversation(actor, reason, oldNode);
5042
5043 /* switch our actor to the next state */
5044 myActor.setCurState(nxt);
5045
5046 /* indicate that we are allowing the conversation to end */
5047 return true;
5048 }
5049
5050 /* handle a conversational command */
5051 handleConversation(otherActor, topic, convType)
5052 {
5053 /* handle goodbyes specially */
5054 if (convType == byeConvType)
5055 {
5056 /*
5057 * If this is an implicit goodbye, run the normal
5058 * conversation handling in order to display any implied
5059 * ByeTopic message - but capture the output in case we
5060 * decide not to end the conversation after all. Only do
5061 * this in the case of an implicit goodbye, though - for an
5062 * explicit goodbye, there's no need for this as the explicit
5063 * BYE will do the same thing on its own.
5064 */
5065 local txt = nil;
5066 if (topic != byeTopicObj)
5067 {
5068 txt = mainOutputStream.captureOutput(
5069 {: inherited(otherActor, topic, convType) });
5070 }
5071
5072 /*
5073 * try to end the conversation; if we won't allow it,
5074 * terminate the action here
5075 */
5076 if (!endConversation(otherActor, endConvBye))
5077 exit;
5078
5079 /* show the captured ByeTopic output */
5080 if (txt != nil)
5081 say(txt);
5082 }
5083 else
5084 {
5085 /* use the inherited handling */
5086 inherited(otherActor, topic, convType);
5087 }
5088 }
5089
5090 /*
5091 * provide a default HELLO response, if we don't have a special
5092 * TopicEntry for it
5093 */
5094 defaultGreetingResponse(actor)
5095 {
5096 /*
5097 * As our default response, point out that we're already at the
5098 * actor's service. (This isn't an error, because the other
5099 * actor might not have been talking to us, even though we
5100 * thought we were talking to them.)
5101 */
5102 gLibMessages.alreadyTalkingTo(getActor(), actor);
5103 }
5104
5105 takeTurn()
5106 {
5107 local actor = getActor();
5108
5109 /* if we didn't interact this turn, increment our boredom counter */
5110 if (!actor.conversedThisTurn())
5111 actor.boredomCount++;
5112
5113 /* run the inherited handling */
5114 inherited();
5115 }
5116
5117 /* activate this state */
5118 activateState(actor, oldState)
5119 {
5120 /*
5121 * If the previous state was a ConversationReadyState, or we
5122 * have no other state remembered, remember the previous state -
5123 * this is the default we'll return to at the end of the
5124 * conversation, if the instance doesn't specify another state.
5125 *
5126 * We don't remember prior states that aren't conv-ready states
5127 * to make it easier to temporarily interrupt a conversation
5128 * with some other state, and later return to the conversation.
5129 * If we remembered every prior state, then we'd return to the
5130 * interrupting state when the conversation ended, which is
5131 * usually not what's wanted. Usually, we want to return to the
5132 * last conv-ready state when a conversation ends, ignoring any
5133 * other intermediate states that have been active since the
5134 * conv-ready state was last in effect.
5135 */
5136 if (previousState == nil || oldState.ofKind(ConversationReadyState))
5137 previousState = oldState;
5138
5139 /*
5140 * reset the actor's boredom counter, since we're just starting a
5141 * new conversation, and add our boredom agenda item to the
5142 * active list to monitor our boredom level
5143 */
5144 actor.boredomCount = 0;
5145 actor.addToAgenda(actor.boredomAgendaItem);
5146
5147 /* remember the time of the last conversation command */
5148 actor.lastConvTime = Schedulable.gameClockTime;
5149 }
5150
5151 /* deactivate this state */
5152 deactivateState(actor, newState)
5153 {
5154 /*
5155 * we're leaving the conversation state, so there's no need to
5156 * monitor our boredom level any longer
5157 */
5158 actor.removeFromAgenda(actor.boredomAgendaItem);
5159
5160 /* do the normal work */
5161 inherited(actor, newState);
5162 }
5163
5164 /*
5165 * The previous state - this is the state we were in before the
5166 * conversation began, and the one we'll return to by default when
5167 * the conversation ends. We'll set this automatically on
5168 * activation.
5169 */
5170 previousState = nil
5171 ;
5172
5173 /*
5174 * A special kind of agenda item for monitoring "boredom" during a
5175 * conversation. We check to see if our actor is in a conversation, and
5176 * the PC has been ignoring the conversation for too long; if so, our
5177 * actor initiates the end of the conversation, since the PC apparently
5178 * isn't paying any attention to us.
5179 */
5180 class BoredomAgendaItem: AgendaItem
5181 /* we construct these dynamically during actor initialization */
5182 construct(actor)
5183 {
5184 /* remember our actor as our location */
5185 location = actor;
5186 }
5187
5188 /*
5189 * we're ready to run if our actor is in an InConversationState and
5190 * its boredom count has reached the limit for the state
5191 */
5192 isReady()
5193 {
5194 local actor = getActor();
5195 local state = actor.curState;
5196
5197 return (inherited()
5198 && state.ofKind(InConversationState)
5199 && state.attentionSpan != nil
5200 && actor.boredomCount >= state.attentionSpan);
5201 }
5202
5203 /* on invocation, end the conversation */
5204 invokeItem()
5205 {
5206 local actor = getActor();
5207 local state = actor.curState;
5208
5209 /* tell the state to end the conversation */
5210 state.endConversation(actor.getCurrentInterlocutor(), endConvBoredom);
5211 }
5212
5213 /*
5214 * by default, handle boredom before other agenda items - we do this
5215 * because an ongoing conversation will be the first thing on the
5216 * NPC's mind
5217 */
5218 agendaOrder = 50
5219 ;
5220
5221
5222 /*
5223 * A "hermit" actor state is a state where the actor is unresponsive to
5224 * conversational overtures (ASK ABOUT, TELL ABOUT, HELLO, GOODBYE, YES,
5225 * NO, SHOW TO, GIVE TO, and any orders directed to the actor). Any
5226 * attempt at conversation will be met with the 'noResponse' message.
5227 */
5228 class HermitActorState: ActorState
5229 /*
5230 * Show our response to any conversational command. We'll simply
5231 * show the standard "there's no response" message by default, but
5232 * subclasses can (and usually should) override this to explain
5233 * what's really going on. Note that this routine will be invoked
5234 * for any sort of conversation command, so any override needs to be
5235 * generic enough that it's equally good for ASK, TELL, and
5236 * everything else.
5237 *
5238 * Note that it's fairly easy to create a shuffled list of random
5239 * messages, if you want to add some variety to the actor's
5240 * responses. To do this, use an embedded ShuffledEventList:
5241 *
5242 * myState: HermitActorState
5243 *. noResponse() { myList.doScript(); }
5244 *. myList: ShuffledEventList {
5245 *. ['message1', 'message2', 'message3'] }
5246 *. ;
5247 */
5248 noResponse() { mainReport(&noResponseFromMsg, getActor()); }
5249
5250 /* all conversation actions get the same default response */
5251 handleConversation(otherActor, topic, convType)
5252 {
5253 /* just show our standard default response */
5254 noResponse();
5255 }
5256
5257 /*
5258 * Since the hermit state blocks topics from outside the state, don't
5259 * offer suggestions for other topics while in this state.
5260 *
5261 * Note that you might sometimes want to override this to allow the
5262 * usual topic suggestions (by setting this to nil). In particular:
5263 *
5264 * - If it's not outwardly obvious that the actor is unresponsive,
5265 * you'll probably want to allow suggestions. Remember, TOPICS
5266 * suggests topics that the *PC* wants to talk about, not things the
5267 * NPC is interested in. If the PC doesn't necessarily know that the
5268 * NPC won't respond, the PC would still want to ask about those
5269 * topics.
5270 *
5271 * - If the hermit state is to be short-lived, you might want to show
5272 * the topic suggestions even in the hermit state, so that the player
5273 * is aware that there are still useful topics to explore with the
5274 * NPC. The player might otherwise assume that the NPC is out of
5275 * useful topics, and not bother trying again later when the NPC
5276 * becomes more responsive.
5277 */
5278 limitSuggestions = true
5279 ;
5280
5281 /*
5282 * The basic "accompanying" state. In this state, whenever the actor
5283 * we're accompanying travels to a location we want to follow, we'll
5284 * travel at the same time with the other actor.
5285 */
5286 class AccompanyingState: ActorState
5287 /*
5288 * Check to see if we are to accompany the given traveler on the
5289 * given travel. 'traveler' is the Traveler performing the travel,
5290 * and 'conn' is the connector that the traveler is about to take.
5291 *
5292 * Note that 'traveler' is a Traveler object. This will simply be an
5293 * Actor (which is a kind of Traveler) when the actor is performing
5294 * the travel directly, but it could also be another kind of
5295 * Traveler, such as a Vehicle. This routine must determine whether
5296 * to accompany other kinds of actors.
5297 *
5298 * By default, we'll return true to indicate that we want to
5299 * accompany any traveler anywhere they go. This should almost
5300 * always be overridden in practice to be more specific.
5301 */
5302 accompanyTravel(traveler, conn) { return true; }
5303
5304 /*
5305 * Get our accompanying state object. We'll create a basic
5306 * accompanying in-travel state object, returning to the current
5307 * state when we're done. 'traveler' is the Traveler object that's
5308 * performing the travel; this might be an Actor, but could also be a
5309 * Vehicle or other Traveler subclass.
5310 */
5311 getAccompanyingTravelState(traveler, connector)
5312 {
5313 /*
5314 * Create the default intermediate state for the travel. Note
5315 * that the lead actor is the actor performing the command - this
5316 * won't necessarily be the traveler, since the actor could be
5317 * steering a vehicle.
5318 */
5319 return new AccompanyingInTravelState(
5320 getActor(), gActor, getActor().curState);
5321 }
5322
5323 /*
5324 * handle a before-travel notification for my actor
5325 */
5326 beforeTravel(traveler, connector)
5327 {
5328 /*
5329 * If we want to accompany the given traveler on this travel, add
5330 * ourselves to the initiating actor's list of accompanying
5331 * actors. Never set an actor to accompany itself, since doing
5332 * so would lead to infinite recursion.
5333 */
5334 if (accompanyTravel(traveler, connector) && getActor() != gActor)
5335 {
5336 /*
5337 * Add me to the list of actors accompanying the actor
5338 * initiating the travel - that actor will run a nested
5339 * travel action on us before doing its own travel. Note
5340 * that the initiating actor is gActor, since that's the
5341 * actor performing the action that led to the travel.
5342 */
5343 gActor.addAccompanyingActor(getActor());
5344
5345 /* put my actor into the appropriate new group travel state */
5346 getActor().setCurState(
5347 getAccompanyingTravelState(traveler, connector));
5348 }
5349
5350 /* inherit the default handling */
5351 inherited(traveler, connector);
5352 }
5353 ;
5354
5355 /*
5356 * "Accompanying in-travel" state - this is an actor state used when an
5357 * actor is taking part in a group travel operation. This state lasts
5358 * only as long as the single turn - which belongs to the lead actor -
5359 * that it takes to carry out the group travel. Once our turn comes
5360 * around, we'll restore the actor to the previous state - or, we can set
5361 * the actor to a different state, if desired. Setting the actor to a
5362 * different state is useful when the group travel triggers a new
5363 * scripted activity in the new room.
5364 */
5365 class AccompanyingInTravelState: ActorState
5366 construct(actor, lead, next)
5367 {
5368 /* do the normal initialization */
5369 inherited(actor);
5370
5371 /* remember the lead actor and the next state */
5372 leadActor = lead;
5373 nextState = next;
5374 }
5375
5376 /* the lead actor of the group travel */
5377 leadActor = nil
5378
5379 /*
5380 * the next state - we'll switch our actor to this state after the
5381 * travel has been completed
5382 */
5383 nextState = nil
5384
5385 /*
5386 * Show our "I am here" description. By default, we'll use the
5387 * arrivingWithDesc of the *next* state object.
5388 */
5389 specialDesc() { nextState.arrivingWithDesc; }
5390
5391 /* take our turn */
5392 takeTurn()
5393 {
5394 /*
5395 * The group travel only takes the single turn in which the
5396 * travel is initiated, so by the time our turn comes around, the
5397 * group travel is done. Clear out the lead actor's linkage to
5398 * us as an accompanying actor.
5399 */
5400 leadActor.accompanyingActors.removeElement(getActor());
5401
5402 /* switch our actor to the next state */
5403 getActor().setCurState(nextState);
5404
5405 /*
5406 * call our next state's on-arrival turn-taking method, so that
5407 * it can carry out any desired scripted behavior for our arrival
5408 */
5409 nextState.arrivingTurn();
5410 }
5411
5412 /* initiate a topic - defer to the next state */
5413 initiateTopic(obj) { return nextState.initiateTopic(obj); }
5414
5415 /*
5416 * Override our departure messages. When we're accompanying another
5417 * actor on a group travel, the lead actor will, as part of its turn,
5418 * send each accompanying actor (including us) on ahead. This means
5419 * that the lead actor will see us departing from the starting
5420 * location, because we'll leave before the lead actor has itself
5421 * departed. Rather than using the normal "Bob leaves to the west"
5422 * departure report, customize the departure reports to indicate
5423 * specifically that we're going with the lead actor. (Note that we
5424 * only have to handle the departing messages, since group travel
5425 * always sends accompanying actors on ahead of the main actor, hence
5426 * the accompanying actors will always be seen departing, not
5427 * arriving.)
5428 *
5429 * Note that all of these call our generic sayDeparting() method by
5430 * default, so a subclass can catch all of the departure types at
5431 * once just by overriding sayDeparting(). Overriding the individual
5432 * methods is still desirable, of course, if you want separate
5433 * messages for the different departure types.
5434 */
5435 sayDeparting(conn)
5436 { gLibMessages.sayDepartingWith(getActor(), leadActor); }
5437 sayDepartingDir(dir, conn) { sayDeparting(conn); }
5438 sayDepartingThroughPassage(conn) { sayDeparting(conn); }
5439 sayDepartingViaPath(conn) { sayDeparting(conn); }
5440 sayDepartingUpStairs(conn) { sayDeparting(conn); }
5441 sayDepartingDownStairs(conn) { sayDeparting(conn); }
5442
5443 /*
5444 * Describe local travel using our standard departure message as
5445 * well. This is used to describe our travel when our origin and
5446 * destination locations are both visible to the PC; in these cases,
5447 * we don't describe the departure separately because the whole
5448 * process of travel from departure to arrival is visible to the PC
5449 * and thus is best handled with a single message, which we generate
5450 * here. In our case, since the "accompanying" state describes even
5451 * normal travel as though it were visible all along, we can use our
5452 * standard "departing" message to describe local travel as well.
5453 */
5454 sayArrivingLocally(dest, conn) { sayDeparting(conn); }
5455 sayDepartingLocally(dest, conn) { sayDeparting(conn); }
5456 ;
5457
5458 /* ------------------------------------------------------------------------ */
5459 /*
5460 * A pending conversation information object. An Actor keeps a list of
5461 * these for pending conversations.
5462 */
5463 class PendingConvInfo: object
5464 construct(state, node, turns)
5465 {
5466 /* remember how to start the conversation */
5467 state_ = state;
5468 node_ = node;
5469
5470 /* compute the game clock time when we can start the conversation */
5471 time_ = Schedulable.gameClockTime + turns;
5472 }
5473
5474 /*
5475 * our ActorState and ConvNode (or ConvNode name string), describing
5476 * how we're to start the conversation
5477 */
5478 state_ = nil
5479 node_ = nil
5480
5481 /* the minimum game clock time at which we can start the conversation */
5482 time_ = nil
5483 ;
5484
5485 /* ------------------------------------------------------------------------ */
5486 /*
5487 * An "agenda item." Each actor can have its own "agenda," which is a
5488 * list of these items. Each item represents an action that the actor
5489 * wants to perform - this is usually a goal the actor wants to achieve,
5490 * or a conversational topic the actor wants to pursue.
5491 *
5492 * On any given turn, an actor can carry out only one agenda item.
5493 *
5494 * Agenda items are a convenient way of controlling complex behavior.
5495 * Each agenda item defines its own condition for when the actor can
5496 * pursue the item, and each item defines what the actor does when
5497 * pursuing the item. Agenda items can improve the code structure for an
5498 * NPC's behavior, since they nicely isolate a single background action
5499 * and group it with the conditions that trigger it. But the main
5500 * benefit of agenda items is the one-per-turn pacing - by executing at
5501 * most one agenda item per turn, we ensure that the NPC will carry out
5502 * its self-initiated actions at a measured pace, rather than as a jumble
5503 * of random actions on a single turn.
5504 *
5505 * Note that NPC-initiated conversation messages override agendas. If an
5506 * actor has an active ConvNode, AND the ConvNode displays a
5507 * "continuation message" on a given turn, then the actor will not pursue
5508 * its agenda on that turn. In this way, ConvNode continuation messages
5509 * act rather like high-priority agenda items.
5510 */
5511 class AgendaItem: object
5512 /*
5513 * My actor - agenda items should be nested within the actor using
5514 * '+' so that we can find our actor. Note that this doesn't add the
5515 * item to the actor's agenda - that has to be done explicitly with
5516 * actor.addToAgenda().
5517 */
5518 getActor() { return location; }
5519
5520 /*
5521 * Is this item active at the start of the game? Override this to
5522 * true to make the item initially active; we'll add it to the
5523 * actor's agenda during the game's initialization.
5524 */
5525 initiallyActive = nil
5526
5527 /*
5528 * Is this item ready to execute? The actor will only execute an
5529 * agenda item when this condition is met. By default, we're ready
5530 * to execute. Items can override this to provide a declarative
5531 * condition of readiness if desired.
5532 */
5533 isReady = true
5534
5535 /*
5536 * Is this item done? On each turn, we'll remove any items marked as
5537 * done from the actor's agenda list. We remove items marked as done
5538 * before executing any items, so done-ness overrides readiness; in
5539 * other words, if an item is both 'done' and 'ready', it'll simply
5540 * be removed from the list and will not be executed.
5541 *
5542 * By default, we simply return nil. Items can override this to
5543 * provide a declarative condition of done-ness, or they can simply
5544 * set the property to true when they finish their work. For
5545 * example, an item that only needs to execute once can simply set
5546 * isDone to true in its invokeItem() method; an item that's to be
5547 * repeated until some success condition obtains can override isDone
5548 * to return the success condition.
5549 */
5550 isDone = nil
5551
5552 /*
5553 * The ordering of the item relative to other agenda items. When we
5554 * choose an agenda item to execute, we always choose the lowest
5555 * numbered item that's ready to run. You can leave this with the
5556 * default value if you don't care about the order.
5557 */
5558 agendaOrder = 100
5559
5560 /*
5561 * Execute this item. This is invoked during the actor's turn when
5562 * the item is the first item that's ready to execute in the actor's
5563 * agenda list. We do nothing by default.
5564 */
5565 invokeItem() { }
5566
5567 /*
5568 * Reset the item. This is invoked whenever the item is added to an
5569 * actor's agenda. By default, we'll set isDone to nil as long as
5570 * isDone isn't a method; this makes it easier to reuse agenda
5571 * items, since we don't have to worry about clearing out the isDone
5572 * flag when reusing an item.
5573 */
5574 resetItem()
5575 {
5576 /* if isDone isn't a method, reset it to nil */
5577 if (propType(&isDone) != TypeCode)
5578 isDone = nil;
5579 }
5580 ;
5581
5582 /*
5583 * An AgendaItem initializer. For each agenda item that's initially
5584 * active, we'll add the item to its actor's agenda.
5585 */
5586 PreinitObject
5587 execute()
5588 {
5589 forEachInstance(AgendaItem, function(item) {
5590 /*
5591 * If this item is initially active, add the item to its
5592 * actor's agenda.
5593 */
5594 if (item.initiallyActive)
5595 item.getActor().addToAgenda(item);
5596 });
5597 }
5598 ;
5599
5600 /*
5601 * A "conversational" agenda item. This type of item is ready to execute
5602 * only when the actor hasn't engaged in conversation during the same
5603 * turn. This type of item is ideal for situations where we want the
5604 * actor to pursue a conversational topic, because we won't initiate the
5605 * action until we get a turn where the player didn't directly talk to
5606 * us.
5607 */
5608 class ConvAgendaItem: AgendaItem
5609 isReady = (!getActor().conversedThisTurn()
5610 && getActor().canTalkTo(otherActor)
5611 && inherited())
5612
5613 /*
5614 * The actor we're planning to address - by default, this is the PC.
5615 * If the conversational overture will be directed to another NPC,
5616 * you can specify that other actor here.
5617 */
5618 otherActor = (gPlayerChar)
5619 ;
5620
5621 /*
5622 * A delayed agenda item. This type of item becomes ready to execute
5623 * when the game clock reaches a given turn counter.
5624 */
5625 class DelayedAgendaItem: AgendaItem
5626 /* we're ready if the game clock time has reached our ready time */
5627 isReady = (Schedulable.gameClockTime >= readyTime && inherited())
5628
5629 /* the turn counter on the game clock when we become ready */
5630 readyTime = 0
5631
5632 /*
5633 * Set our ready time based on a delay from the current time. We'll
5634 * become ready after the given number of turns elapses. For
5635 * convenience, we return 'self', so a delayed agenda item can be
5636 * initialized and added to an actor's agenda in one simple
5637 * operation, like so:
5638 *
5639 * actor.addToAgenda(item.setDelay(1));
5640 */
5641 setDelay(turns)
5642 {
5643 /*
5644 * initialize our ready time as the given number of turns in the
5645 * future from the current game clock time
5646 */
5647 readyTime = Schedulable.gameClockTime + turns;
5648
5649 /* return 'self' for the caller's convenience */
5650 return self;
5651 }
5652 ;
5653
5654
5655 /* ------------------------------------------------------------------------ */
5656 /*
5657 * An Actor is a living person, animal, or other entity with a will of
5658 * its own. Actors can usually be addressed with targeted commands
5659 * ("bob, go north"), and with commands like ASK ABOUT, TELL ABOUT, GIVE
5660 * TO, and SHOW TO.
5661 *
5662 * Note that, by default, an Actor can be picked up and moved with
5663 * commands like TAKE, PUT IN, and so on. This is suitable for some
5664 * kinds of actors but not for others: it might make sense with a cat or
5665 * a small dog, but not with a bank guard or an orc. For an actor that
5666 * can't be taken, use the UntakeableActor or one of its subclasses.
5667 *
5668 * An actor's contents are the things the actor is carrying or wearing.
5669 */
5670 class Actor: Thing, Schedulable, Traveler, ActorTopicDatabase
5671 /* flag: we're an actor */
5672 isActor = true
5673
5674 /*
5675 * Our current state. This is an ActorState object representing what
5676 * we're currently doing. Whenever the actor changes to a new state
5677 * (for example, because of a scripted activity), this can be changed
5678 * to reflect the actor's new state. The state object groups the
5679 * parts of the actor's description and other methods that tend to
5680 * vary according to what the actor's doing; it's easier to keep
5681 * everything related to scripted activities together in a state
5682 * object than it is to handle all of the variability with switch()
5683 * statements of the like in methods directly in the actor.
5684 *
5685 * It's not necessary to initialize this if the actor doesn't take
5686 * advantage of the ActorState mechanism. If this isn't initialized
5687 * for a particular actor, we'll automatically create a default
5688 * ActorState object during pre-initialization.
5689 */
5690 curState = nil
5691
5692 /* set the current state */
5693 setCurState(state)
5694 {
5695 /* if this isn't a change of state, there's nothing to do */
5696 if (state == curState)
5697 return;
5698
5699 /* if we have a previous state, tell it it's becoming inactive */
5700 if (curState != nil)
5701 curState.deactivateState(self, state);
5702
5703 /* notify the new state it's becoming active */
5704 if (state != nil)
5705 state.activateState(self, curState);
5706
5707 /* remember the new state */
5708 curState = state;
5709 }
5710
5711 /*
5712 * Our current conversation node. This is a ConvNode object that
5713 * keeps track of the flow of the conversation.
5714 */
5715 curConvNode = nil
5716
5717 /*
5718 * Our table of conversation nodes. At initialization, the
5719 * conversation manager scans all ConvNode instances and adds each
5720 * one to its actor's table. This table is keyed by the name of
5721 * node, and the value for each entry is the ConvNode object - this
5722 * lets us look up the ConvNode object by name. Because each actor
5723 * has its own lookup table, ConvNode names only have to be unique
5724 * within the actor's set of ConvNodes.
5725 */
5726 convNodeTab = perInstance(new LookupTable(32, 32))
5727
5728 /* set the current conversation node */
5729 setConvNode(node) { setConvNodeReason(node, nil); }
5730
5731 /* set the current conversation node, with a reason code */
5732 setConvNodeReason(node, reason)
5733 {
5734 /* remember the old node */
5735 local oldNode = curConvNode;
5736
5737 /* if the node was specified by name, look up the object */
5738 if (dataType(node) == TypeSString)
5739 node = convNodeTab[node];
5740
5741 /* remember the new node */
5742 curConvNode = node;
5743
5744 /*
5745 * If we're changing to a new node, notify the new and old
5746 * nodes. Note that these notifications occur after the new
5747 * node has been set, which ensures that any further node change
5748 * triggered by the node change won't redundantly issue the same
5749 * notifications: since the old node is no longer active, it
5750 * can't receive another departure notification, and since the
5751 * new node is already active, it can't receive another
5752 * activation.
5753 */
5754 if (node != oldNode)
5755 {
5756 /* if there's an old node, note that we're leaving it */
5757 if (oldNode != nil)
5758 oldNode.noteLeaving();
5759
5760 /* let the node know that it's becoming active */
5761 if (node != nil)
5762 node.noteActiveReason(reason);
5763 }
5764
5765 /*
5766 * note that we've explicitly set a ConvNode (even if it's not
5767 * actually changing), in case the conversation manager is
5768 * tracking what's happening during a response
5769 */
5770 responseSetConvNode = true;
5771 }
5772
5773 /*
5774 * conversation manager ID - this is assigned by the conversation
5775 * manager to map to and from output stream references to the actor;
5776 * this is only for internal use by the conversation manager
5777 */
5778 convMgrID = nil
5779
5780 /*
5781 * Flag indicating whether or not we've set a ConvNode in the course
5782 * of the current response. This is for use by the converstaion
5783 * manager.
5784 */
5785 responseSetConvNode = nil
5786
5787 /*
5788 * Initiate a conversation with the player character. This lets the
5789 * NPC initiate a conversation, in response to something the player
5790 * character does, or as part of the NPC's scripted activity. This
5791 * is only be used for situations where the NPC initiates the
5792 * conversation - if the player character initiates conversation with
5793 * TALK TO, ASK, TELL, etc., we handle the conversation through our
5794 * normal handlers for those commands.
5795 *
5796 * 'state' is the ActorState to switch to for the conversation. This
5797 * will normally be an InConversationState object, but doesn't have
5798 * to be.
5799 *
5800 * You can pass nil for 'state' to use the current state's implied
5801 * conversational state. The implied conversational state of a
5802 * ConversationReadyState is the associated InConversationState; the
5803 * implied conversation state of any other state is simply the same
5804 * state.
5805 *
5806 * 'node' is a ConvNode object, or a string naming a ConvNode object.
5807 * We'll make this our current conversation node. A valid
5808 * conversation node is required because we use this to generate the
5809 * initial NPC greeting of the conversation. In most cases, when the
5810 * NPC initiates a conversation, it's because the NPC wants to ask a
5811 * question or otherwise say something specific, so there should
5812 * always be a conversational context implied, thus the need for a
5813 * ConvNode. If there's no need for a conversational context, the
5814 * NPC script code might just as well display the conversational
5815 * exchange as a plain old message, and not bother going to all this
5816 * trouble.
5817 */
5818 initiateConversation(state, node)
5819 {
5820 /*
5821 * if there's no state provided, use the current state's implied
5822 * conversation state
5823 */
5824 if (state == nil)
5825 state = curState.getImpliedConvState;
5826
5827 /*
5828 * if there's an ActorHelloTopic for the old state, invoke it to
5829 * show the greeting
5830 */
5831 curState.handleTopic(self, actorHelloTopicObj, helloConvType, nil);
5832
5833 /* switch to the new state, if it's not the current state */
5834 if (state != nil && state != curState)
5835 setCurState(state);
5836
5837 /* we're now talking to the player character */
5838 noteConversation(gPlayerChar);
5839
5840 /* switch to the conversation node */
5841 setConvNodeReason(node, 'initiateConversation');
5842
5843 /* tell the conversation node that the NPC is initiating it */
5844 if (node != nil)
5845 curConvNode.npcInitiateConversation();
5846 }
5847
5848 /*
5849 * Initiate a conversation based on the given simulation object.
5850 * We'll look for an InitiateTopic matching the given object, and if
5851 * we can find one, we'll show its topic response.
5852 */
5853 initiateTopic(obj)
5854 {
5855 /* try our current state first */
5856 if (curState.initiateTopic(obj))
5857 return true;
5858
5859 /* we didn't find a state object; use the default handling */
5860 return inherited(obj);
5861 }
5862
5863 /*
5864 * Schedule initiation of conversation. This allows the caller to
5865 * set up a conversation to start on a future turn. The
5866 * conversation will start after (1) the given number of turns has
5867 * elapsed, and (2) the player didn't target this actor with a
5868 * conversational command on the same turn. This allows us to set
5869 * the NPC so that it *wants* to start a conversation, and will do
5870 * so as soon as it has a chance to get a word in.
5871 *
5872 * If 'turns' is zero, the conversation can start the next time the
5873 * actor takes a turn; so, if this is called during the PC's action
5874 * processing, the conversation can start on the same turn. Note
5875 * that if this is called during the actor's takeTurn() processing,
5876 * it won't actually start the conversation until the next turn,
5877 * because that's the next time we'll check the queue. If 'turns'
5878 * is 1, then the player will get at least one more command before
5879 * the conversation will begin, and so on with higher numbers.
5880 */
5881 scheduleInitiateConversation(state, node, turns)
5882 {
5883 /* add a new pending conversation to our list */
5884 pendingConv.append(new PendingConvInfo(state, node, turns));
5885 }
5886
5887 /*
5888 * Break off our current conversation, of the NPC's own volition.
5889 * This is the opposite number of initiateConversation: this causes
5890 * the NPC to effectively say BYE on its own, rather than waiting
5891 * for the PC to decide to end the conversation.
5892 *
5893 * This call is mostly useful when the actor's current state is an
5894 * InConversationState, since the main function of this routine is
5895 * to switch to an out-of-conversation state.
5896 */
5897 endConversation()
5898 {
5899 /*
5900 * tell the current state to end the conversation of the NPC's
5901 * own volition
5902 */
5903 curState.endConversation(self, endConvActor);
5904 }
5905
5906 /*
5907 * Our list of pending conversation initiators. In our takeTurn()
5908 * processing, we'll check this list for conversations that we can
5909 * initiate.
5910 */
5911 pendingConv = nil
5912
5913 /*
5914 * Hide actors from 'all' by default. The kinds of actions that
5915 * normally apply to 'all' and the kinds that normally apply to
5916 * actors have pretty low overlap.
5917 *
5918 * If a particular actor looks a lot like an inanimate object, it
5919 * might want to override this to participate in 'all' for most or
5920 * all actions.
5921 */
5922 hideFromAll(action) { return true; }
5923
5924 /*
5925 * don't hide actors from defaulting, though - it's frequently
5926 * convenient and appropriate to assume an actor by default,
5927 * especially for commands like GIVE TO and SHOW TO
5928 */
5929 hideFromDefault(action) { return nil; }
5930
5931 /*
5932 * We meet the objHeld precondition for ourself - that is, for any
5933 * verb that requires holding an object, we can be considered to be
5934 * holding ourself.
5935 */
5936 meetsObjHeld(actor) { return actor == self || inherited(actor); }
5937
5938 /*
5939 * Actors are not listed with the ordinary objects in a room's
5940 * description. However, an actor is listed as part of an inventory
5941 * description.
5942 */
5943 isListed = nil
5944 isListedInContents = nil
5945 isListedInInventory = true
5946
5947 /* the contents of an actor aren't listed in a room's description */
5948 contentsListed = nil
5949
5950 /*
5951 * Full description. By default, we'll show either the pcDesc or
5952 * npcDesc, depending on whether we're the current player character
5953 * or a non-player character.
5954 *
5955 * Generally, individual actors should NOT override this method.
5956 * Instead, customize pcDesc and/or npcDesc to describe the permanent
5957 * features of the actor.
5958 */
5959 desc
5960 {
5961 /*
5962 * show the appropriate messages, depending on whether we're the
5963 * player character or a non-player character
5964 */
5965 if (isPlayerChar())
5966 {
5967 /* show our as-player-character description */
5968 pcDesc;
5969 }
5970 else
5971 {
5972 /* show our as-non-player-character description */
5973 npcDesc;
5974 }
5975 }
5976
5977 /* show our status */
5978 examineStatus()
5979 {
5980 /*
5981 * If I'm an NPC, show where I'm sitting/standing/etc. (If I'm
5982 * the PC, we don't usually want to show this explicitly to avoid
5983 * redundancy. The player is usually sufficiently aware of the
5984 * PC's posture by virtue of being in control of the actor, and
5985 * the information also tends to show up often enough in other
5986 * places, such as on the status line and in the room
5987 * description.)
5988 */
5989 if (!isPlayerChar())
5990 postureDesc;
5991
5992 /* show the status from our state object */
5993 curState.stateDesc;
5994
5995 /* inherit the default handling to show our contents */
5996 inherited();
5997 }
5998
5999 /*
6000 * Show my posture, as part of the full EXAMINE description of this
6001 * actor. We'll let our nominal actor container handle it.
6002 */
6003 postureDesc() { descViaActorContainer(&roomActorPostureDesc, nil); }
6004
6005 /*
6006 * The default description when we examine this actor and the actor
6007 * is serving as the player character. This should generally not
6008 * include any temporary status information; just show constant,
6009 * fixed features.
6010 */
6011 pcDesc { gLibMessages.pcDesc(self); }
6012
6013 /*
6014 * Show the description of this actor when this actor is a non-player
6015 * character.
6016 *
6017 * This description should include only the constant, fixed
6018 * description of the character. Do not include information on what
6019 * the actor is doing right now, because that belongs in the
6020 * ActorState object instead. When we display the actor's
6021 * description, we'll show this text, and then we'll show the
6022 * ActorState description as well; this combination approach makes it
6023 * easier to keep the description synchronized with any scripted
6024 * activities the actor is performing.
6025 *
6026 * By default, we'll show this as a "default descriptive report,"
6027 * since it simply says that there's nothing special to say.
6028 * However, whenever this is overridden with an actual description,
6029 * you shouldn't bother to use defaultDescReport - simply display the
6030 * descriptive message directly:
6031 *
6032 * npcDesc = "He's wearing a gorilla costume. "
6033 */
6034 npcDesc { defaultDescReport(&npcDescMsg, self); }
6035
6036 /* examine my contents specially */
6037 examineListContents()
6038 {
6039 /* if I'm not the player character, show my inventory */
6040 if (!isPlayerChar())
6041 holdingDesc;
6042 }
6043
6044 /*
6045 * Always list actors specially, rather than as ordinary items in
6046 * contents listings. We'll send this to our current state object
6047 * for processing, since our "I am here" description tends to vary by
6048 * state.
6049 */
6050 specialDesc() { curState.specialDesc(); }
6051 distantSpecialDesc() { curState.distantSpecialDesc(); }
6052 remoteSpecialDesc(actor) { curState.remoteSpecialDesc(actor); }
6053 specialDescListWith() { return curState.specialDescListWith(); }
6054
6055 /*
6056 * By default, show the special description for an actor in the group
6057 * of special descriptions that come *after* the room's portable
6058 * contents listing. An actor's presence is usually a dynamic
6059 * feature of a room, and so we don't want to suggest that the actor
6060 * is a permanent feature of the room by describing the actor
6061 * directly with the room's main description.
6062 */
6063 specialDescBeforeContents = nil
6064
6065 /*
6066 * When we're asked to show a special description as part of the
6067 * description of a containing object (which will usually be a nested
6068 * room of some kind), just show our posture in our container, rather
6069 * than showing our full "I am here" description.
6070 */
6071 showSpecialDescInContents(actor, cont)
6072 {
6073 /* show our posture to indicate our container */
6074 listActorPosture(actor);
6075 }
6076
6077 /*
6078 * By default, put all of the actor special descriptions after the
6079 * special descriptions of ordinary objects, by giving actors a
6080 * higher listing order value.
6081 */
6082 specialDescOrder = 200
6083
6084 /*
6085 * Get my listing group for my special description as part of a room
6086 * description. By default, we'll let our immediate location decide
6087 * how we're grouped.
6088 */
6089 actorListWith()
6090 {
6091 local group;
6092
6093 /*
6094 * if our special desc is overridden, don't use any grouping by
6095 * default - this make a special description defined in the
6096 * actor override any grouping we'd otherwise do
6097 */
6098 if (overrides(self, Actor, &specialDesc))
6099 return [];
6100
6101 /* get the group for the posture */
6102 group = location.listWithActorIn(posture);
6103
6104 /*
6105 * if we have a group, return a list containing the group;
6106 * otherwise return an empty list
6107 */
6108 return (group == nil ? [] : [group]);
6109 }
6110
6111 /*
6112 * Actor "I am here" description. This is displayed as part of the
6113 * description of a room - it describes the actor as being present in
6114 * the room. By default, we let the "nominal actor container"
6115 * provide the description.
6116 */
6117 actorHereDesc { descViaActorContainer(&roomActorHereDesc, nil); }
6118
6119 /*
6120 * Actor's "I am over there" description. This is displayed in the
6121 * room description when the actor is visible, but is either in a
6122 * separate top-level room or is at a distance. By default, we let
6123 * the "nominal actor container" provide the description.
6124 */
6125 actorThereDesc { descViaActorContainer(&roomActorThereDesc, nil); }
6126
6127 /*
6128 * Show our status, as an addendum to the given room's name (this is
6129 * the room title, shown at the start of a room description and on
6130 * the status line). By default, we'll let our nominal actor
6131 * container provide the status, to indicate when we're
6132 * standing/sitting/lying in a nested room.
6133 *
6134 * In concrete terms, this generally adds a message such as "(sitting
6135 * on the chair)" to the name of a room if we're in a nested room
6136 * within the room. When we're standing in the main room, this
6137 * generally adds nothing.
6138 *
6139 * Note that we pass the room we're describing as the "container to
6140 * ignore" parameter, because we don't want to say something like
6141 * "Phone Booth (standing in the phone booth)" - that is, we don't
6142 * want to mention the nominal container again if the nominal
6143 * container is what we're naming in the first place.
6144 */
6145 actorRoomNameStatus(room)
6146 { descViaActorContainer(&roomActorStatus, room); }
6147
6148 /*
6149 * Describe the actor via the "nominal actor container." The nominal
6150 * container is determined by our direct location.
6151 *
6152 * 'contToIgnore' is a container to ignore. If our nominal container
6153 * is the same as this object, we'll generate a description without a
6154 * mention of a container at all.
6155 *
6156 * The reason we have the 'contToIgnore' parameter is that the caller
6157 * might already have reported our general location, and now merely
6158 * wants to add that we're standing or standing or whatever. In
6159 * these cases, if we were to say that we're sitting on or standing
6160 * on that same object, it would be redundant information: "Bob is in
6161 * the garden, sitting in the garden." The 'contToIgnore' parameter
6162 * tells us the object that the caller has already mentioned as our
6163 * general location so that we don't re-report the same thing. We
6164 * need to know the actual object, rather than just the fact that the
6165 * caller mentioned a general location, because our general location
6166 * and the specific place we're standing or sitting or whatever might
6167 * not be the same: "Bob is in the garden, sitting in the lawn
6168 * chair."
6169 *
6170 */
6171 descViaActorContainer(prop, contToIgnore)
6172 {
6173 local pov;
6174 local cont;
6175
6176 /* get our nominal container for our current posture */
6177 cont = location.getNominalActorContainer(posture);
6178
6179 /* get the point of view, using the player character by default */
6180 if ((pov = getPOV()) == nil)
6181 pov = gPlayerChar;
6182
6183 /*
6184 * if we have a nominal container, and it's not the one to
6185 * ignore, and the player character can see it, generate the
6186 * description via the container; otherwise, use a generic
6187 * library message that doesn't mention the container
6188 */
6189 if (cont not in (nil, contToIgnore) && pov.canSee(cont))
6190 {
6191 /* describe via the container */
6192 cont.(prop)(self);
6193 }
6194 else
6195 {
6196 /* use the generic library message */
6197 gLibMessages.(prop)(self);
6198 }
6199 }
6200
6201 /*
6202 * Describe my inventory as part of my description - this is only
6203 * called when we examine an NPC. If an NPC doesn't wish to have
6204 * its inventory listed as part of its description, it can simply
6205 * override this to do nothing.
6206 */
6207 holdingDesc
6208 {
6209 /*
6210 * show our contents as for a normal "examine", but using the
6211 * special contents lister for what an actor is holding
6212 */
6213 examineListContentsWith(holdingDescInventoryLister);
6214 }
6215
6216 /*
6217 * refer to the player character with my player character referral
6218 * person, and refer to all other characters in the third person
6219 */
6220 referralPerson { return isPlayerChar() ? pcReferralPerson : ThirdPerson; }
6221
6222 /* by default, refer to the player character in the second person */
6223 pcReferralPerson = SecondPerson
6224
6225 /*
6226 * The referral person of the current command targeting the actor.
6227 * This is meaningful only when a command is being directed to this
6228 * actor, and this actor is an NPC.
6229 *
6230 * The referral person depends on the specifics of the language. In
6231 * English, a command like "bob, go north" is a second-person
6232 * command, while "tell bob to go north" is a third-person command.
6233 * The only reason this is important is in interpreting what "you"
6234 * means if it's used as an object in the command. "tell bob to hit
6235 * you" probably means that Bob should hit the player character,
6236 * while "bob, hit you" probably means that Bob should hit himself.
6237 */
6238 commandReferralPerson = nil
6239
6240 /* determine if I'm the player character */
6241 isPlayerChar() { return libGlobal.playerChar == self; }
6242
6243 /*
6244 * Implicit command handling style for this actor. There are two
6245 * styles for handling implied commands: "player" and "NPC",
6246 * indicated by the enum codes ModePlayer and ModeNPC, respectively.
6247 *
6248 * In "player" mode, each implied command is announced with a
6249 * description of the command to be performed; DEFAULT responses are
6250 * suppressed; and failures are shown. Furthermore, interactive
6251 * requests for more information from the parser are allowed.
6252 * Transcripts like this result:
6253 *
6254 * >open door
6255 *. (first opening the door)
6256 *. (first unlocking the door)
6257 *. What do you want to unlock it with?
6258 *
6259 * In "NPC" mode, implied commands are treated as complete and
6260 * separate commands. They are not announced; default responses are
6261 * shown; failures are NOT shown; and interactive requests for more
6262 * information are not allowed. When an implied command fails in NPC
6263 * mode, the parser acts as though the command had never been
6264 * attempted.
6265 *
6266 * By default, we return ModePlayer if we're the player character,
6267 * ModeNPC if not (thus the respective names of the modes). Some
6268 * authors might prefer to use "player mode" for NPC's as well as for
6269 * the player character, which is why the various parts of the parser
6270 * that care about this mode consult this method rather than simply
6271 * testing the PC/NPC status of the actor.
6272 */
6273 impliedCommandMode() { return isPlayerChar() ? ModePlayer : ModeNPC; }
6274
6275 /*
6276 * Try moving the given object into this object. For an actor, this
6277 * will do one of two things. If 'self' is the actor performing the
6278 * action that's triggering this implied command, then we can achieve
6279 * the goal simply by taking the object. Otherwise, the way to get
6280 * an object into my possession is to have the actor performing the
6281 * command give me the object.
6282 */
6283 tryMovingObjInto(obj)
6284 {
6285 if (gActor == self)
6286 {
6287 /*
6288 * I'm performing the triggering action, so I merely need to
6289 * pick up the object
6290 */
6291 return tryImplicitAction(Take, obj);
6292 }
6293 else
6294 {
6295 /*
6296 * another actor is performing the action; since that actor
6297 * is the one who must perform the implied action, the way to
6298 * get an object into my inventory is for that actor to give
6299 * it to me
6300 */
6301 return tryImplicitAction(GiveTo, obj, self);
6302 }
6303 }
6304
6305 /* desribe our containment of an object as carrying the object */
6306 mustMoveObjInto(obj) { reportFailure(&mustBeCarryingMsg, obj, self); }
6307
6308 /*
6309 * You can limit the cumulative amount of bulk an actor can hold, and
6310 * the maximum bulk of any one object the actor can hold, using
6311 * bulkCapacity and maxSingleBulk. These properties are analogous to
6312 * the same ones in Container.
6313 *
6314 * A word of caution on these is in order. Many authors worry that
6315 * it's unrealistic if the player character can carry too much at one
6316 * time, so they'll fiddle with these properties to impose a carrying
6317 * limit that seems realistic. Be advised that authors love this
6318 * sort of "realism" a whole lot more than players do. Players
6319 * almost universally don't care about it, and in fact tend to hate
6320 * the inventory juggling it inevitably leads to. Juggling inventory
6321 * isn't any fun for the player. Don't fool yourself about this -
6322 * the thoughts in the mind of a player who's tediously carting
6323 * objects back and forth three at a time will not include admiration
6324 * of your prowess at simulational realism. In contrast, if you set
6325 * the carrying limit to infinity, it's a rare player who will even
6326 * notice, and a much rarer player who'll complain about it.
6327 *
6328 * If you really must insist on inventory limits, refer to the
6329 * BagOfHolding class for a solution that can salvage most of the
6330 * "realism" that the accountancy-inclined author craves, without
6331 * creating undue inconvenience for the player. BagOfHolding makes
6332 * inventory limits palatable for the player by essentially
6333 * automating the required inventory juggling. In fact, for most
6334 * players, an inventory limit in conjunction with a bag of holding
6335 * is actually better than an unlimited inventory, since it improves
6336 * readability by keeping the direct inventory list to a manageable
6337 * size.
6338 */
6339 bulkCapacity = 10000
6340 maxSingleBulk = 10
6341
6342 /*
6343 * An actor can limit the cumulative amount of weight being held,
6344 * using weightCapacity. By default we make this so large that
6345 * there is effectively no limit to how much weight an actor can
6346 * carry.
6347 */
6348 weightCapacity = 10000
6349
6350 /*
6351 * Can I own the given object? By default, an actor can own
6352 * anything.
6353 */
6354 canOwn(obj) { return true; }
6355
6356 /*
6357 * Get the preconditions for travel. By default, we'll add the
6358 * standard preconditions that the connector requires for actors.
6359 *
6360 * Note that these preconditions apply only when the actor is the
6361 * traveler. If the actor is in a vehicle, so that the vehicle is
6362 * the traveler in a given travel operation, the vehicle's
6363 * travelerPreCond conditions are used instead of ours.
6364 */
6365 travelerPreCond(conn) { return conn.actorTravelPreCond(self); }
6366
6367 /* by default, actors are listed when they arrive aboard a vehicle */
6368 isListedAboardVehicle = true
6369
6370 /*
6371 * Get the object that's actually going to move when this actor
6372 * travels via the given connector. In most cases this is simply the
6373 * actor; but when the actor is in a vehicle, travel commands move
6374 * the vehicle, not the actor: the actor stays in the vehicle while
6375 * the vehicle moves to a new location. We determine this by asking
6376 * our immediate location what it thinks about the situation.
6377 *
6378 * If we have a special traveler explicitly set, it overrides the
6379 * traveler indicated by the location.
6380 */
6381 getTraveler(conn)
6382 {
6383 /*
6384 * Return our special traveler if we have one; otherwise, if we
6385 * have a location, return the traveler indicated by our
6386 * location; otherwise, we're the traveler.
6387 */
6388 if (specialTraveler != nil)
6389 return specialTraveler;
6390 else if (location != nil)
6391 return location.getLocTraveler(self, conn);
6392 else
6393 return self;
6394 }
6395
6396 /*
6397 * Get the "push traveler" for the actor. This is the nominal
6398 * traveler that we want to use when the actor enters a command like
6399 * PUSH BOX NORTH. 'obj' is the object we're trying to push.
6400 */
6401 getPushTraveler(obj)
6402 {
6403 /*
6404 * If we already have a special traveler, just use the special
6405 * traveler. Otherwise, if we have a location, ask the location
6406 * what it thinks. Otherwise, we're the traveler.
6407 */
6408 if (specialTraveler != nil)
6409 return specialTraveler;
6410 else if (location != nil)
6411 return location.getLocPushTraveler(self, obj);
6412 else
6413 return self;
6414 }
6415
6416 /* is an actor traveling with us? */
6417 isActorTraveling(actor)
6418 {
6419 /* we're the only actor traveling when we're the traveler */
6420 return (actor == self);
6421 }
6422
6423 /* invoke a callback on each actor traveling with the traveler */
6424 forEachTravelingActor(func)
6425 {
6426 /* we're the only actor, so simply invoke the callback on myself */
6427 (func)(self);
6428 }
6429
6430 /*
6431 * Get the actors involved in travel, when we're acting in our role
6432 * as a Traveler. When the Traveler is simply the Actor, the only
6433 * actor involved in the travel is 'self'.
6434 */
6435 getTravelerActors = [self]
6436
6437 /* we're the self-motive actor doing the travel */
6438 getTravelerMotiveActors = [self]
6439
6440 /*
6441 * Set the "special traveler." When this is set, we explicitly
6442 * perform travel through this object rather than through the
6443 * traveler indicated by our location. Returns the old value, so
6444 * that the old value can be restored when the caller has finished
6445 * its need for the special traveler.
6446 */
6447 setSpecialTraveler(traveler)
6448 {
6449 local oldVal;
6450
6451 /* remember the old value so that we can return it */
6452 oldVal = specialTraveler;
6453
6454 /* remember the new value */
6455 specialTraveler = traveler;
6456
6457 /* return the old value */
6458 return oldVal;
6459 }
6460
6461 /* our special traveler */
6462 specialTraveler = nil
6463
6464 /*
6465 * Try moving the actor into the given room in preparation for
6466 * travel, using pre-condition rules.
6467 */
6468 checkMovingTravelerInto(room, allowImplicit)
6469 {
6470 /* try moving the actor into the room */
6471 return room.checkMovingActorInto(allowImplicit);
6472 }
6473
6474 /*
6475 * Check to ensure the actor is ready to enter the given nested
6476 * room, using pre-condition rules. By default, we'll ask the given
6477 * nested room to handle it.
6478 */
6479 checkReadyToEnterNestedRoom(dest, allowImplicit)
6480 {
6481 /* ask the destination to do the work */
6482 return dest.checkActorReadyToEnterNestedRoom(allowImplicit);
6483 }
6484
6485 /*
6486 * Travel within a location, as from a room to a contained nested
6487 * room. This should generally be used in lieu of travelTo when
6488 * traveling between locations that are related directly by
6489 * containment rather than with TravelConnector objects.
6490 *
6491 * Travel within a location is not restricted by darkness; we assume
6492 * that if the nested objects are in scope at all, travel among them
6493 * is allowed.
6494 *
6495 * This type of travel does not trigger calls to travelerLeaving()
6496 * or travelerArriving(). To mitigate this loss of notification, we
6497 * call actorTravelingWithin() on the source and destination
6498 * objects.
6499 */
6500 travelWithin(dest)
6501 {
6502 /* if I'm not going anywhere, ignore the operation */
6503 if (dest == location)
6504 return;
6505
6506 /*
6507 * Notify the traveler. Note that since this is local travel
6508 * within a single top-level location, there's no connector.
6509 */
6510 getTraveler(nil).travelerTravelWithin(self, dest);
6511 }
6512
6513 /*
6514 * Traveler interface: perform local travel, between nested rooms
6515 * within a single top-level location.
6516 */
6517 travelerTravelWithin(actor, dest)
6518 {
6519 local origin;
6520
6521 /* remember my origin */
6522 origin = location;
6523
6524 /* notify the source that we're traveling within a room */
6525 if (origin != nil)
6526 origin.actorTravelingWithin(origin, dest);
6527
6528 /*
6529 * if our origin and destination have different effective follow
6530 * locations, track the follow
6531 */
6532 if (origin != nil
6533 && dest != nil
6534 && origin.effectiveFollowLocation != dest.effectiveFollowLocation)
6535 {
6536 /*
6537 * notify observing objects of the travel; we're not moving
6538 * along a connector, so there is no connector associated
6539 * with the tracking information
6540 */
6541 connectionTable().forEachAssoc(
6542 {obj, val: obj.beforeTravel(self, nil)});
6543 }
6544
6545 /* move me to the destination */
6546 moveInto(dest);
6547
6548 /*
6549 * recalculate the global sense context for message generation
6550 * purposes, since we've moved to a new location
6551 */
6552 if (gAction != nil)
6553 gAction.recalcSenseContext();
6554
6555 /* notify the destination of the interior travel */
6556 if (dest != nil)
6557 dest.actorTravelingWithin(origin, dest);
6558 }
6559
6560 /*
6561 * Check for travel in the dark. If we're in a dark room, and our
6562 * destination is a dark room, ask the connector for guidance.
6563 *
6564 * Travel connectors normally call this before invoking our
6565 * travelTo() method to carry out the travel. The darkness check
6566 * usually must be made before any barrier checks.
6567 */
6568 checkDarkTravel(dest, connector)
6569 {
6570 local origin;
6571
6572 /*
6573 * If we're not in the dark in the current location, there's no
6574 * need to check for dark-to-dark travel; light-to-dark travel
6575 * is always allowed.
6576 */
6577 if (isLocationLit())
6578 return;
6579
6580 /* get the origin - this is the traveler's location */
6581 origin = getTraveler(connector).location;
6582
6583 /*
6584 * Check to see if the connector itself is visible in the dark.
6585 * If it is, then allow the travel without restriction.
6586 */
6587 if (connector.isConnectorVisibleInDark(origin, self))
6588 return;
6589
6590 /*
6591 * We are attempting dark-to-dark travel. We allow or disallow
6592 * this type of travel on a per-connector basis, so ask the
6593 * connector to handle it. If the connector wishes to disallow
6594 * the travel, it will display an appropriate failure report and
6595 * terminate the command with 'exit'.
6596 */
6597 connector.darkTravel(self, dest);
6598 }
6599
6600 /*
6601 * Travel to a new location.
6602 */
6603 travelTo(dest, connector, backConnector)
6604 {
6605 /* send the request to the traveler */
6606 getTraveler(connector)
6607 .travelerTravelTo(dest, connector, backConnector);
6608 }
6609
6610 /*
6611 * Perform scripted travel to the given adjacent location. This
6612 * looks for a directional connector in our current location whose
6613 * destination is the given location, and for a corresponding
6614 * back-connector in the destination location. If we can find the
6615 * connectors, we'll perform the travel using travelTo().
6616 *
6617 * The purpose of this routine is to simplify scripted travel for
6618 * simple cases where directional connectors are available for the
6619 * desired travel. This routine is NOT suitable for intelligent
6620 * goal-seeking NPC's who automatically try to find their own routes,
6621 * for two reasons. First, this routine only lets an NPC move to an
6622 * *adjacent* location; it won't try to find a path between arbitrary
6623 * locations. Second, this routine is "omniscient": it doesn't take
6624 * into account what the NPC knows about the connections between
6625 * locations, but simply finds a connector that actually provides the
6626 * desired travel.
6627 *
6628 * What this routine *is* suitable for are cases where we have a
6629 * pre-scripted series of NPC travel actions, where we have a list of
6630 * rooms we want the NPC to visit in order. This routine simplifies
6631 * this type of scripting by automatically finding the connectors;
6632 * the script only has to specify the next location for the NPC to
6633 * visit.
6634 */
6635 scriptedTravelTo(dest)
6636 {
6637 local conn;
6638
6639 /* find a connector from the current location to the new location */
6640 conn = location.getConnectorTo(self, dest);
6641
6642 /* if we found the connector, perform the travel */
6643 if (conn != nil)
6644 nestedActorAction(self, TravelVia, conn);
6645 }
6646
6647 /*
6648 * Remember the last door I traveled through. We use this
6649 * information for disambiguation, to boost the likelihood that an
6650 * actor that just traveled through a door is referring to the same
6651 * door in a subsequent "close" command.
6652 */
6653 rememberLastDoor(obj) { lastDoorTraversed = obj; }
6654
6655 /*
6656 * Remember our most recent travel. If we know the back connector
6657 * (i.e., the connector that reverses the travel we're performing),
6658 * then we'll be able to accept a GO BACK command to attempt to
6659 * return to the previous location.
6660 */
6661 rememberTravel(origin, dest, backConnector)
6662 {
6663 /* remember the destination of the travel, and the connector back */
6664 lastTravelDest = dest;
6665 lastTravelBack = backConnector;
6666 }
6667
6668 /*
6669 * Reverse the most recent travel. If we're still within the same
6670 * destination we reached in the last travel, and we know the
6671 * connector we arrived through (i.e., the "back connector" for the
6672 * last travel, which reverses the connector we took to get here),
6673 * then try traveling via the connector.
6674 */
6675 reverseLastTravel()
6676 {
6677 /*
6678 * If we don't know the connector back to our previous location,
6679 * we obviously can't reverse the travel. If we're not still in
6680 * the same location as the previous travel's destination, then
6681 * we can't reverse the travel either, because the back
6682 * connector isn't applicable to our current location. (This
6683 * latter condition could only happen if we've been moved
6684 * somewhere without ordinary travel occurring, but this is a
6685 * possibility.)
6686 */
6687 if (lastTravelBack == nil
6688 || lastTravelDest == nil
6689 || !isIn(lastTravelDest))
6690 {
6691 reportFailure(&cannotGoBackMsg);
6692 exit;
6693 }
6694
6695 /* attempt travel via our back connector */
6696 nestedAction(TravelVia, lastTravelBack);
6697 }
6698
6699 /* the last door I traversed */
6700 lastDoorTraversed = nil
6701
6702 /* the destination and back connector for our last travel */
6703 lastTravelDest = nil
6704 lastTravelBack = nil
6705
6706 /*
6707 * use a custom message for cases where we're holding a destination
6708 * object for BOARD, ENTER, etc
6709 */
6710 checkStagingLocation(dest)
6711 {
6712 /*
6713 * if the destination is within us, explain specifically that
6714 * this is the problem
6715 */
6716 if (dest.isIn(self))
6717 reportFailure(&invalidStagingContainerActorMsg, self, dest);
6718 else
6719 inherited(dest);
6720
6721 /* terminate the command */
6722 exit;
6723 }
6724
6725 /*
6726 * Travel arrival/departure messages. Defer to the current state
6727 * object on all of these.
6728 */
6729 sayArriving(conn)
6730 { curState.sayArriving(conn); }
6731 sayDeparting(conn)
6732 { curState.sayDeparting(conn); }
6733 sayArrivingLocally(dest, conn)
6734 { curState.sayArrivingLocally(dest, conn); }
6735 sayDepartingLocally(dest, conn)
6736 { curState.sayDepartingLocally(dest, conn); }
6737 sayTravelingRemotely(dest, conn)
6738 { curState.sayTravelingRemotely(dest, conn); }
6739 sayArrivingDir(dir, conn)
6740 { curState.sayArrivingDir(dir, conn); }
6741 sayDepartingDir(dir, conn)
6742 { curState.sayDepartingDir(dir, conn); }
6743 sayArrivingThroughPassage(conn)
6744 { curState.sayArrivingThroughPassage(conn); }
6745 sayDepartingThroughPassage(conn)
6746 { curState.sayDepartingThroughPassage(conn); }
6747 sayArrivingViaPath(conn)
6748 { curState.sayArrivingViaPath(conn); }
6749 sayDepartingViaPath(conn)
6750 { curState.sayDepartingViaPath(conn); }
6751 sayArrivingUpStairs(conn)
6752 { curState.sayArrivingUpStairs(conn); }
6753 sayArrivingDownStairs(conn)
6754 { curState.sayArrivingDownStairs(conn); }
6755 sayDepartingUpStairs(conn)
6756 { curState.sayDepartingUpStairs(conn); }
6757 sayDepartingDownStairs(conn)
6758 { curState.sayDepartingDownStairs(conn); }
6759
6760 /*
6761 * Get the current interlocutor. By default, we'll address new
6762 * conversational commands (ASK ABOUT, TELL ABOUT, SHOW TO) to the
6763 * last conversational partner, if that actor is still within range.
6764 */
6765 getCurrentInterlocutor()
6766 {
6767 /*
6768 * if we've talked to someone before, and we can still talk to
6769 * them now, return that actor; otherwise we have no default
6770 */
6771 if (lastInterlocutor != nil && canTalkTo(lastInterlocutor))
6772 return lastInterlocutor;
6773 else
6774 return nil;
6775 }
6776
6777 /*
6778 * Get the default interlocutor. If there's a current interlocutor,
6779 * and we can still talk to that actor, then that's the default
6780 * interlocutor. If not, we'll return whatever actor is the default
6781 * for a TALK TO command. Note that TALK TO won't necessarily have a
6782 * default actor; if it doesn't, we'll simply return nil.
6783 */
6784 getDefaultInterlocutor()
6785 {
6786 local actor;
6787
6788 /* check for a current interlocutor */
6789 actor = getCurrentInterlocutor();
6790
6791 /*
6792 * if we're not talking to anyone, or if the person we were
6793 * talking to can no longer hear us, look for a default object
6794 * for a TALK TO command and use it instead as the default
6795 */
6796 if (actor == nil || !canTalkTo(actor))
6797 {
6798 /* set up a TALK TO command and a resolver */
6799 local tt = new TalkToAction();
6800 local res = new Resolver(tt, gIssuingActor, gActor);
6801
6802 /* get the default direct object */
6803 actor = tt.getDefaultDobj(new EmptyNounPhraseProd(), res);
6804
6805 /* if that worked, get the object from the resolve info */
6806 if (actor != nil)
6807 actor = actor[1].obj_;
6808 }
6809
6810 /* return what we found */
6811 return actor;
6812 }
6813
6814 /*
6815 * The most recent actor that we've interacted with through a
6816 * conversational command (ASK, TELL, GIVE, SHOW, etc).
6817 */
6818 lastInterlocutor = nil
6819
6820 /*
6821 * Our conversational "boredom" counter. While we're in a
6822 * conversation, this tracks the number of turns since the last
6823 * conversational command from the actor we're talking to.
6824 *
6825 * Note that this state is part of the actor, even though it's
6826 * usually managed by the InConversationState object. The state is
6827 * stored with the actor rather than with the state object because
6828 * it really describes the condition of the actor, not of the state
6829 * object.
6830 */
6831 boredomCount = 0
6832
6833 /*
6834 * game-clock time (Schedulable.gameClockTime) of the last
6835 * conversational command addressed to us by the player character
6836 */
6837 lastConvTime = -1
6838
6839 /*
6840 * Did we engage in any conversation on the current turn? This can
6841 * be used as a quick check in background activity scripts when we
6842 * want to run a step only in the absence of any conversation on the
6843 * same turn.
6844 */
6845 conversedThisTurn() { return lastConvTime == Schedulable.gameClockTime; }
6846
6847 /*
6848 * Note that we're performing a conversational command targeting the
6849 * given actor. We'll make the actors point at each other with their
6850 * 'lastInterlocutor' properties. This is called on the character
6851 * performing the conversation command: if the player types ASK BOB
6852 * ABOUT BOOK, this will be called on the player character actor,
6853 * with 'other' set to Bob.
6854 */
6855 noteConversation(other)
6856 {
6857 /* note that we're part of a conversational action */
6858 noteConvAction(other);
6859
6860 /* let the other actor know we're conversing with them */
6861 other.noteConversationFrom(self);
6862 }
6863
6864 /*
6865 * Note that another actor is issuing a conversational command
6866 * targeting us. For example, if the player types ASK BOB ABOUT
6867 * BOOK, then this will be called on Bob, with the player character
6868 * actor as 'other'.
6869 */
6870 noteConversationFrom(other)
6871 {
6872 /* note that we're part of a conversational action */
6873 noteConvAction(other);
6874 }
6875
6876 /*
6877 * Note that we're taking part in a conversational action with
6878 * another character. This is symmetrical - it could mean we're the
6879 * initiator of the conversation action or the target. We'll
6880 * remember the person we're talking to, and reset our conversation
6881 * time counters so we know we've conversed on this turn.
6882 */
6883 noteConvAction(other)
6884 {
6885 /* note our last conversational partner */
6886 lastInterlocutor = other;
6887
6888 /* set the actor to be the pronoun antecedent */
6889 setPronounObj(other);
6890
6891 /*
6892 * reset our boredom counter, as the other actor has just spoken
6893 * to us
6894 */
6895 boredomCount = 0;
6896
6897 /* remember the time of our last conversation from the PC */
6898 lastConvTime = Schedulable.gameClockTime;
6899 }
6900
6901 /* note that we're consulting an item */
6902 noteConsultation(obj) { lastConsulted = obj; }
6903
6904 /*
6905 * Receive notification that a TopicEntry response in our database is
6906 * being invoked. We'll just pass this along to our current state.
6907 */
6908 notifyTopicResponse(fromActor, entry)
6909 {
6910 /* let our current state handle it */
6911 curState.notifyTopicResponse(fromActor, entry);
6912 }
6913
6914 /* the object we most recently consulted */
6915 lastConsulted = nil
6916
6917 /*
6918 * The actor's "agenda." This is a list of AgendaItem objects that
6919 * describe things the actor wants to do of its own volition on its
6920 * own turn.
6921 */
6922 agendaList = nil
6923
6924 /*
6925 * our special "boredom" agenda item - this makes us initiate an end
6926 * to an active conversation when the PC has ignored us for a given
6927 * number of consecutive turns
6928 */
6929 boredomAgendaItem = perInstance(new BoredomAgendaItem(self))
6930
6931 /* add an agenda item */
6932 addToAgenda(item)
6933 {
6934 /* if we don't have an agenda list yet, create one */
6935 if (agendaList == nil)
6936 agendaList = new Vector(10);
6937
6938 /* add the item */
6939 agendaList.append(item);
6940
6941 /*
6942 * keep the list in ascending order of agendaOrder values - this
6943 * will ensure that we'll always choose the earliest item that's
6944 * ready to run
6945 */
6946 agendaList.sort(SortAsc, {a, b: a.agendaOrder - b.agendaOrder});
6947
6948 /* reset the agenda item */
6949 item.resetItem();
6950 }
6951
6952 /* remove an agenda item */
6953 removeFromAgenda(item)
6954 {
6955 /* if we have an agenda list, remove the item */
6956 if (agendaList != nil)
6957 agendaList.removeElement(item);
6958 }
6959
6960 /*
6961 * Execute the next item in our agenda, if there are any items in the
6962 * agenda that are ready to execute. We'll return true if we found
6963 * an item to execute, nil if not.
6964 */
6965 executeAgenda()
6966 {
6967 local item;
6968
6969 /* if we don't have an agenda, there are obviously no items */
6970 if (agendaList == nil)
6971 return nil;
6972
6973 /* remove any items that are marked as done */
6974 while ((item = agendaList.lastValWhich({x: x.isDone})) != nil)
6975 agendaList.removeElement(item);
6976
6977 /*
6978 * Scan for an item that's ready to execute. Since we keep the
6979 * list sorted in ascending order of agendaOrder values, we can
6980 * just pick the earliest item in the list that's ready to run,
6981 * since that will be the ready-to-run item with the lowest
6982 * agendaOrder number.
6983 */
6984 item = agendaList.valWhich({x: x.isReady});
6985
6986 /* if we found an item, execute it */
6987 if (item != nil)
6988 {
6989 try
6990 {
6991 /* execute the item */
6992 item.invokeItem();
6993 }
6994 catch (RuntimeError err)
6995 {
6996 /*
6997 * If an error occurs while executing the item, mark the
6998 * item as done. This will ensure that we won't get
6999 * stuck in a loop trying to execute the same item over
7000 * and over, which will probably just run into the same
7001 * error on each attempt.
7002 */
7003 item.isDone = true;
7004
7005 /* re-throw the exception */
7006 throw err;
7007 }
7008
7009 /* tell the caller we found an item to execute */
7010 return true;
7011 }
7012 else
7013 {
7014 /* tell the caller we found no agenda item */
7015 return nil;
7016 }
7017 }
7018
7019 /*
7020 * Calculate the amount of bulk I'm holding directly. By default,
7021 * we'll simply add up the "actor-encumbering bulk" of each of our
7022 * direct contents.
7023 *
7024 * Note that we don't differentiate here based on whether or not an
7025 * item is being worn, or anything else - we deliberately leave such
7026 * distinctions up to the getEncumberingBulk routine, so that only
7027 * the objects are in the business of deciding how bulky they are
7028 * under different circumstances.
7029 */
7030 getBulkHeld()
7031 {
7032 local total;
7033
7034 /* start with nothing */
7035 total = 0;
7036
7037 /* add the bulks of directly-contained items */
7038 foreach (local cur in contents)
7039 total += cur.getEncumberingBulk(self);
7040
7041 /* return the total */
7042 return total;
7043 }
7044
7045 /*
7046 * Calculate the total weight I'm holding. By default, we'll add up
7047 * the "actor-encumbering weight" of each of our direct contents.
7048 *
7049 * Note that we deliberately only consider our direct contents. If
7050 * any of the items we are directly holding contain further items,
7051 * getEncumberingWeight will take their weights into account; this
7052 * frees us from needing any special knowledge of the internal
7053 * structure of any items we're holding, and puts that knowledge in
7054 * the individual items where it belongs.
7055 */
7056 getWeightHeld()
7057 {
7058 local total;
7059
7060 /* start with nothing */
7061 total = 0;
7062
7063 /* add the weights of directly-contained items */
7064 foreach (local cur in contents)
7065 total += cur.getEncumberingWeight(self);
7066
7067 /* return the total */
7068 return total;
7069 }
7070
7071 /*
7072 * Try making room to hold the given object. This is called when
7073 * checking the "room to hold object" pre-condition, such as for the
7074 * "take" verb.
7075 *
7076 * If holding the new object would exceed the our maximum holding
7077 * capacity, we'll go through our inventory looking for objects that
7078 * can reduce our held bulk with implicit commands. Objects with
7079 * holding affinities - "bags of holding", keyrings, and the like -
7080 * can implicitly shuffle the actor's possessions in a manner that
7081 * is neutral as far as the actor is concerned, thereby reducing our
7082 * active holding load.
7083 *
7084 * Returns true if an implicit command was attempted, nil if not.
7085 */
7086 tryMakingRoomToHold(obj, allowImplicit)
7087 {
7088 local objWeight;
7089 local objBulk;
7090 local aff;
7091
7092 /* get the amount of weight this will add if taken */
7093 objWeight = obj.getEncumberingWeight(self);
7094
7095 /*
7096 * If this object alone is too heavy for us, give up. We
7097 * distinguish this case from the case where the total (of
7098 * everything held plus the new item) is too heavy: in the
7099 * latter case we can tell the actor that they can pick this up
7100 * by dropping something else first, whereas if this item alone
7101 * is too heavy, no such advice is warranted.
7102 */
7103 if (objWeight > weightCapacity)
7104 {
7105 reportFailure(&tooHeavyForActorMsg, obj);
7106 exit;
7107 }
7108
7109 /*
7110 * if taking the object would push our total carried weight over
7111 * our total carrying weight limit, give up
7112 */
7113 if (obj.whatIfHeldBy({: getWeightHeld()}, self) > weightCapacity)
7114 {
7115 reportFailure(&totalTooHeavyForMsg, obj);
7116 exit;
7117 }
7118
7119 /* get the amount of bulk the object will add */
7120 objBulk = obj.getEncumberingBulk(self);
7121
7122 /*
7123 * if the object is simply too big to start with, we can't make
7124 * room no matter what we do
7125 */
7126 if (objBulk > maxSingleBulk || objBulk > bulkCapacity)
7127 {
7128 reportFailure(&tooLargeForActorMsg, obj);
7129 exit;
7130 }
7131
7132 /*
7133 * Test what would happen to our bulk if we were to move the
7134 * object into our directly held inventory. Do this by running
7135 * a "what if" scenario to test moving the object into our
7136 * inventory, and check what effect it has on our held bulk. If
7137 * it fits, we can let the caller proceed without further work.
7138 */
7139 if (obj.whatIfHeldBy({: getBulkHeld()}, self) <= bulkCapacity)
7140 return nil;
7141
7142 /*
7143 * if we're not allowed to run implicit commands, we won't be
7144 * able to accomplish anything, so give up
7145 */
7146 if (!allowImplicit)
7147 {
7148 reportFailure(&handsTooFullForMsg, obj);
7149 exit;
7150 }
7151
7152 /*
7153 * Get "bag of holding" affinity information for my immediate
7154 * contents. Consider only objects with encumbering bulk, since
7155 * it will do us no good to move objects without any encumbering
7156 * bulk. Also ignore objects that aren't being held (some direct
7157 * contents aren't considered to be held, such as clothing being
7158 * worn).
7159 */
7160 aff = getBagAffinities(contents.subset(
7161 {x: x.getEncumberingBulk(self) != 0 && x.isHeldBy(self)}));
7162
7163 /* if there are no bag affinities, we can't move anything around */
7164 if (aff.length() == 0)
7165 {
7166 reportFailure(&handsTooFullForMsg, obj);
7167 exit;
7168 }
7169
7170 /*
7171 * If we have at least four items, find the two that were picked
7172 * up most recently (according to the "holding index" value) and
7173 * move them to the end of the list. In most cases, we'll only
7174 * have to dispose of one or two items to free up enough space
7175 * in our hands, so we'll probably never get to the last couple
7176 * of items in our list, so we're effectively ruling out moving
7177 * these two most recent items; but they'll be in the list if we
7178 * do find we need to move them after all.
7179 *
7180 * The point of this rearrangement is to avoid annoying cases of
7181 * moving something we just picked up, especially if we just
7182 * picked it up in order to carry out the command that's making
7183 * us free up more space now. This looks especially stupid when
7184 * we perform some command that requires picking up two items
7185 * automatically: we pick up the first, then we put it away in
7186 * order to pick up the second, but then we find that we need
7187 * the first again.
7188 */
7189 if (aff.length() >= 4)
7190 {
7191 local a, b;
7192
7193 /* remove the two most recent items from the vector */
7194 a = BagAffinityInfo.removeMostRecent(aff);
7195 b = BagAffinityInfo.removeMostRecent(aff);
7196
7197 /* re-insert them at the end of the vector */
7198 aff.append(b);
7199 aff.append(a);
7200 }
7201
7202 /*
7203 * Move each object in the list until we have reduced the bulk
7204 * sufficiently.
7205 */
7206 foreach (local cur in aff)
7207 {
7208 /*
7209 * Try moving this object to its bag. If the bag is itself
7210 * inside this object, don't even try, since that would be an
7211 * attempt at circular containment.
7212 *
7213 * If the object we're trying to hold is inside this object,
7214 * don't move the object. That might put the object we're
7215 * trying to hold out of reach, since moving an object into a
7216 * bag could involve closing the object or making its
7217 * contents not directly accessible.
7218 */
7219 if (!cur.bag_.isIn(cur.obj_)
7220 && !obj.isIn(cur.obj_)
7221 && cur.bag_.tryPuttingObjInBag(cur.obj_))
7222 {
7223 /*
7224 * this routine tried tried to move the object into the
7225 * bag - check our held bulk to see if we're in good
7226 * enough shape yet
7227 */
7228 if (obj.whatIfHeldBy({: getBulkHeld()}, self) <= bulkCapacity)
7229 {
7230 /*
7231 * We've met our condition - there's no need to look
7232 * any further. Return, telling the caller we've
7233 * performed an implicit command.
7234 */
7235 return true;
7236 }
7237 }
7238 }
7239
7240 /*
7241 * If we get this far, it means that we tried every child object
7242 * but failed to find anything that could help. Explain the
7243 * problem and abort the command.
7244 */
7245 reportFailure(&handsTooFullForMsg, obj);
7246 exit;
7247 }
7248
7249 /*
7250 * Check a bulk change of one of my direct contents.
7251 */
7252 checkBulkChangeWithin(obj)
7253 {
7254 local objBulk;
7255
7256 /* get the object's new bulk */
7257 objBulk = obj.getEncumberingBulk(self);
7258
7259 /*
7260 * if this change would cause the object to exceed our
7261 * single-item bulk limit, don't allow it
7262 */
7263 if (objBulk > maxSingleBulk || objBulk > bulkCapacity)
7264 {
7265 reportFailure(&becomingTooLargeForActorMsg, obj);
7266 exit;
7267 }
7268
7269 /*
7270 * If our total carrying capacity is exceeded with this change,
7271 * don't allow it. Note that 'obj' is already among our
7272 * contents when this routine is called, so we can simply check
7273 * our current total bulk within.
7274 */
7275 if (getBulkHeld() > bulkCapacity)
7276 {
7277 reportFailure(&handsBecomingTooFullForMsg, obj);
7278 exit;
7279 }
7280 }
7281
7282 /*
7283 * Next available "holding index" value. Each time we pick up an
7284 * item, we'll assign it our current holding index value and then
7285 * increment our value. This gives us a simple way to keep track of
7286 * the order in which we picked up items we're carrying.
7287 *
7288 * Note that we make the simplifying assumption that an object can
7289 * be held by only one actor at a time (multi-location items are
7290 * generally not portable), which means that we can use a simple
7291 * property in each object being held to store its holding index.
7292 */
7293 nextHoldingIndex = 1
7294
7295 /* add an object to my contents */
7296 addToContents(obj)
7297 {
7298 /* assign the new object our next holding index */
7299 obj.holdingIndex = nextHoldingIndex++;
7300
7301 /* inherit default handling */
7302 inherited(obj);
7303 }
7304
7305 /*
7306 * Go to sleep. This is used by the 'Sleep' action to carry out the
7307 * command. By default, we simply say that we're not sleepy; actors
7308 * can override this to cause other actions.
7309 */
7310 goToSleep()
7311 {
7312 /* simply report that we can't sleep now */
7313 mainReport(&cannotSleepMsg);
7314 }
7315
7316 /*
7317 * My current "posture," which specifies how we're positioned with
7318 * respect to our container; this is one of the standard library
7319 * posture enum values (Standing, etc.) or another posture added by
7320 * the game.
7321 */
7322 posture = standing
7323
7324 /*
7325 * Get a default acknowledgment of a change to our posture. This
7326 * should acknowledge the posture so that it tells us the current
7327 * posture. This is used for a command such as "stand up" from a
7328 * chair, so that we can report the appropriate posture status in
7329 * our acknowledgment; we might end up being inside another nested
7330 * container after standing up from the chair, so we might not
7331 * simply be standing when we're done.
7332 */
7333 okayPostureChange()
7334 {
7335 /* get our nominal container for our current posture */
7336 local cont = location.getNominalActorContainer(posture);
7337
7338 /* if the container is visible, let it handle it */
7339 if (cont != nil && gPlayerChar.canSee(cont))
7340 {
7341 /* describe via the container */
7342 cont.roomOkayPostureChange(self);
7343 }
7344 else
7345 {
7346 /* use the generic library message */
7347 defaultReport(&okayPostureChangeMsg, posture);
7348 }
7349 }
7350
7351 /*
7352 * Describe the actor as part of the EXAMINE description of a nested
7353 * room containing the actor. 'povActor' is the actor doing the
7354 * looking.
7355 */
7356 listActorPosture(povActor)
7357 {
7358 /* get our nominal container for our current posture */
7359 local cont = location.getNominalActorContainer(posture);
7360
7361 /* if the container is visible, let it handle it */
7362 if (cont != nil && povActor.canSee(cont))
7363 cont.roomListActorPosture(self);
7364 }
7365
7366 /*
7367 * Stand up. This is used by the 'Stand' action to carry out the
7368 * command.
7369 */
7370 standUp()
7371 {
7372 /* if we're already standing, say so */
7373 if (posture == standing)
7374 {
7375 reportFailure(&alreadyStandingMsg);
7376 return;
7377 }
7378
7379 /* ask the location to make us stand up */
7380 location.makeStandingUp();
7381 }
7382
7383 /*
7384 * Disembark. This is used by the 'Get out' action to carry out the
7385 * command. By default, we'll let the room handle it.
7386 */
7387 disembark()
7388 {
7389 /* let the room handle it */
7390 location.disembarkRoom();
7391 }
7392
7393 /*
7394 * Set our posture to the given status. By default, we'll simply
7395 * set our posture property to the new status, but actors can
7396 * override this to handle side effects of the change.
7397 */
7398 makePosture(newPosture)
7399 {
7400 /* remember our new posture */
7401 posture = newPosture;
7402 }
7403
7404 /*
7405 * Display a description of the actor's location from the actor's
7406 * point of view.
7407 *
7408 * If 'verbose' is true, then we'll show the full description in all
7409 * cases. Otherwise, we'll show the full description if the actor
7410 * hasn't seen the location before, or the terse description if the
7411 * actor has previously seen the location.
7412 */
7413 lookAround(verbose)
7414 {
7415 /* turn on the sense cache while we're looking */
7416 libGlobal.enableSenseCache();
7417
7418 /* show a description of my immediate location, if I have one */
7419 if (location != nil)
7420 location.lookAroundPov(self, self, verbose);
7421
7422 /* turn off the sense cache now that we're done */
7423 libGlobal.disableSenseCache();
7424 }
7425
7426 /*
7427 * Get my "look around" location name as a string. This returns a
7428 * string containing the location name that we display in the status
7429 * line or at the start of a "look around" description of my
7430 * location.
7431 */
7432 getLookAroundName()
7433 {
7434 return mainOutputStream.captureOutput(
7435 {: location.lookAroundWithinName(self, getVisualAmbient()) })
7436 .specialsToText();
7437 }
7438
7439 /*
7440 * Adjust a table of visible objects for 'look around'. By default,
7441 * we remove any explicitly excluded objects.
7442 */
7443 adjustLookAroundTable(tab, pov, actor)
7444 {
7445 /* remove any explicitly excluded objects */
7446 foreach (local cur in excludeFromLookAroundList)
7447 tab.removeElement(cur);
7448
7449 /* inherit the base handling */
7450 inherited(tab, pov, actor);
7451 }
7452
7453 /*
7454 * Add an object to the 'look around' exclusion list. Returns true
7455 * if the object was already in the list, nil if not.
7456 */
7457 excludeFromLookAround(obj)
7458 {
7459 /*
7460 * if the object is already in the list, don't add it again -
7461 * just tell the caller it's already there
7462 */
7463 if (excludeFromLookAroundList.indexOf(obj) != nil)
7464 return true;
7465
7466 /* add it to the list and tell the caller it wasn't already there */
7467 excludeFromLookAroundList.append(obj);
7468 return nil;
7469 }
7470
7471 /* remove an object from the 'look around' exclusion list */
7472 unexcludeFromLookAround(obj)
7473 {
7474 excludeFromLookAroundList.removeElement(obj);
7475 }
7476
7477 /*
7478 * Our list of objects explicitly excluded from 'look around'. These
7479 * objects will be suppressed from any sort of listing (including in
7480 * the room's contents list and in special descriptions) in 'look
7481 * around' when this actor is doing the looking.
7482 */
7483 excludeFromLookAroundList = perInstance(new Vector(5))
7484
7485 /*
7486 * Get the location into which objects should be moved when the
7487 * actor drops them with an explicit 'drop' command. By default, we
7488 * return the drop destination of our current container.
7489 */
7490 getDropDestination(objToDrop, path)
7491 {
7492 return (location != nil
7493 ? location.getDropDestination(objToDrop, path)
7494 : nil);
7495 }
7496
7497 /*
7498 * The senses that determine scope for this actor. An actor might
7499 * possess only a subset of the defined sense.
7500 *
7501 * By default, we give each actor all of the human senses that we
7502 * define, except touch. In general, merely being able to touch an
7503 * object doesn't put the object in scope, because if an object
7504 * isn't noticed through some other sense, touch would only make an
7505 * object accessible if it's within arm's reach, which for our
7506 * purposes means that the object is being held directly by the
7507 * actor. Imagine an actor in a dark room: lots of things might be
7508 * touchable in the sense that there's no physical barrier to
7509 * touching them, but without some other sense to locate the
7510 * objects, the actor wouldn't have any way of knowing where to
7511 * reach to touch things, so they're not in scope. So, touch isn't
7512 * a scope sense.
7513 */
7514 scopeSenses = [sight, sound, smell]
7515
7516 /*
7517 * "Sight-like" senses: these are the senses that operate like sight
7518 * for the actor, and which the actor can use to determine the names
7519 * of objects and the spatial relationships between objects. These
7520 * senses should operate passively, in the sense that they should
7521 * tend to collect sensory input continuously and without explicit
7522 * action by the actor, the way sight does and the way touch, for
7523 * example, does not. These senses should also operate instantly,
7524 * in the sense that the sense can reasonably take in most or all of
7525 * a location at one time.
7526 *
7527 * These senses are used to determine what objects should be listed
7528 * in room descriptions, for example.
7529 *
7530 * By default, the only sight-like sense is sight, since other human
7531 * senses don't normally provide a clear picture of the spatial
7532 * relationships among objects. (Touch could with some degree of
7533 * effort, but it can't operate passively or instantly, since
7534 * deliberate and time-consuming action would be necessary.)
7535 *
7536 * An actor can have more than one sight-like sense, in which case
7537 * the senses will act effectively as one sense that can reach the
7538 * union of objects reachable through the individual senses.
7539 */
7540 sightlikeSenses = [sight]
7541
7542 /*
7543 * Hearing-like senses. These are senses that the actor can use to
7544 * hear objects.
7545 */
7546 hearinglikeSenses = [sound]
7547
7548 /*
7549 * Smell-like senses. These are senses that the actor can use to
7550 * smell objects.
7551 */
7552 smelllikeSenses = [smell]
7553
7554 /*
7555 * Communication senses: these are the senses through which the
7556 * actor can communicate directly with other actors through commands
7557 * and messages.
7558 *
7559 * Conceptually, these senses are intended to be only those senses
7560 * that the actors would *naturally* use to communicate, because
7561 * senses in this list allow direct communications via the most
7562 * ordinary game commands, such as "bob, go east".
7563 *
7564 * If some form of indirect communication is possible via a sense,
7565 * but that form is not something the actor would think of as the
7566 * most natural, default form of communication, it should *not* be
7567 * in this list. For example, two sighted persons who can see one
7568 * another but cannot hear one another could still communicate by
7569 * writing messages on pieces of paper, but they would ordinarily
7570 * communicate by talking. In such a case, sound should be in the
7571 * list but sight should not be, because sight is not a natural,
7572 * default form of communications for the actors.
7573 */
7574 communicationSenses = [sound]
7575
7576 /*
7577 * Determine if I can communicate with the given character via a
7578 * natural, default form of communication that we share with the
7579 * other character. This determines if I can talk to the other
7580 * character. We'll return true if I can talk to the other actor,
7581 * nil if not.
7582 *
7583 * In order for the player character to issue a command to a
7584 * non-player character (as in "bob, go east"), the NPC must be able
7585 * to sense the PC via at least one communication sense that the two
7586 * actors have in common.
7587 *
7588 * Likewise, in order for a non-player character to say something to
7589 * the player, the player must be able to sense the NPC via at least
7590 * one communication sense that the two actors have in common.
7591 */
7592 canTalkTo(actor)
7593 {
7594 local common;
7595
7596 /*
7597 * first, get a list of the communications senses that we have
7598 * in common with the other actor - we must have a sense channel
7599 * via this sense
7600 */
7601 common = communicationSenses.intersect(actor.communicationSenses);
7602
7603 /*
7604 * if there are no common senses, we can't communicate,
7605 * regardless of our physical proximity
7606 */
7607 if (common == [])
7608 return nil;
7609
7610 /*
7611 * Determine how well the other actor can sense me in these
7612 * senses. Note that all that matters it that the actor can
7613 * hear me, because we're determine if I can talk to the other
7614 * actor - it doesn't matter if I can hear the other actor.
7615 */
7616 foreach (local curSense in common)
7617 {
7618 local result;
7619
7620 /*
7621 * determine how well the other actor can sense me in this
7622 * sense
7623 */
7624 result = actor.senseObj(curSense, self);
7625
7626 /* check whether or not this is good enough */
7627 if (actor.canBeTalkedTo(self, curSense, result))
7628 return true;
7629 }
7630
7631 /*
7632 * if we get this far, we didn't find any senses with a clear
7633 * enough communications channel - we can't talk to the other
7634 * actor
7635 */
7636 return nil;
7637 }
7638
7639 /*
7640 * Determine whether or not I can understand an attempt by another
7641 * actor to talk to me. 'talker' is the actor doing the talking.
7642 * 'sense' is the sense we're testing; this will always be a sense
7643 * in our communicationSenses list, and will always be a
7644 * communications sense we have in common with the other actor.
7645 * 'info' is a SenseInfo object giving information on the clarity of
7646 * the sense path to the other actor.
7647 *
7648 * We return true if we can understand the communication, nil if
7649 * not. There is no middle ground where we can partially
7650 * understand; we can either understand or not.
7651 *
7652 * Note that this routine is concerned only with our ability to
7653 * sense the communication. The result here should NOT pay any
7654 * attention to whether or not we can actually communicate given a
7655 * clear sense path - for example, this routine should not reflect
7656 * whether or not we have a spoken language in common with the other
7657 * actor.
7658 *
7659 * This is a service method for canTalkTo. This is broken out as a
7660 * separate method so that individual actors can override the
7661 * necessary conditions for communications in particular senses.
7662 */
7663 canBeTalkedTo(talker, sense, info)
7664 {
7665 /*
7666 * By default, we allow communication if the sense path is
7667 * transparent or distant. We don't care what the sense is,
7668 * since we know we'll never be asked about a sense that's not
7669 * in our communicationSenses list.
7670 */
7671 return info.trans is in (transparent, distant);
7672 }
7673
7674 /*
7675 * Flag: we wait for commands issued to other actors to complete
7676 * before we get another turn. If this is true, then whenever we
7677 * issue a command to another actor ("bob, go north"), we will not
7678 * get another turn until the other actor has finished executing the
7679 * full set of commands we issued.
7680 *
7681 * By default, this is true, which means that we wait for other
7682 * actors to finish all of the commands we issue before we take
7683 * another turn.
7684 *
7685 * If this is set to nil, we'll continue to take turns while the
7686 * other actor carries out our commands. In this case, the only
7687 * time cost to us of issuing a command is given by orderingTime(),
7688 * which normally takes one turn for issuing a command, regardless
7689 * of the command's complexity. Some games might wish to use this
7690 * mode for interesting effects with NPC's carrying out commands in
7691 * parallel with the player, but it's an unconventional style that
7692 * some players might find confusing, so we don't use this mode by
7693 * default.
7694 */
7695 issueCommandsSynchronously = true
7696
7697 /*
7698 * Flag: the "target actor" of the command line automatically reverts
7699 * to this actor at the end of a sentence, when this actor is the
7700 * issuer of a command. If this flag is nil, an explicit target
7701 * actor stays in effect until the next explicit target actor (or the
7702 * end of the entire command line, if no other explicit target actors
7703 * are named); if this flag is true, a target actor is in effect only
7704 * until the end of a sentence.
7705 *
7706 * Consider this command line:
7707 *
7708 * >Bob, go north and get fuel cell. Get log tape.
7709 *
7710 * If this flag is nil, then the second sentence ("get log tape") is
7711 * interpreted as a command to Bob, because Bob is explicitly
7712 * designated as the target of the command, and this remains in
7713 * effect until the end of the entire command line.
7714 *
7715 * If this flag is true, on the other hand, then the second sentence
7716 * is interpreted as a command to the player character, because the
7717 * target actor designation ("Bob,") lasts only until the end of the
7718 * sentence. Once a new sentence begins, we revert to the issuing
7719 * actor (the player character, since the command came from the
7720 * player via the keyboard).
7721 */
7722 revertTargetActorAtEndOfSentence = nil
7723
7724 /*
7725 * The amount of time, in game clock units, it takes me to issue an
7726 * order to another actor. By default, it takes one unit (which is
7727 * usually equal to one turn) to issue a command to another actor.
7728 * However, if we are configured to wait for our issued commands to
7729 * complete in full, the ordering time is zero; we don't need any
7730 * extra wait time in this case because we'll wait the full length
7731 * of the issued command to begin with.
7732 */
7733 orderingTime(targetActor)
7734 {
7735 return issueCommandsSynchronously ? 0 : 1;
7736 }
7737
7738 /*
7739 * Wait for completion of a command that we issued to another actor.
7740 * The parser calls this routine after each time we issue a command
7741 * to another actor.
7742 *
7743 * If we're configured to wait for completion of orders given to
7744 * other actors before we get another turn, we'll set ourselves up
7745 * in waiting mode. Otherwise, we'll do nothing.
7746 */
7747 waitForIssuedCommand(targetActor)
7748 {
7749 /* if we can issue commands asynchronously, there's nothing to do */
7750 if (!issueCommandsSynchronously)
7751 return;
7752
7753 /*
7754 * Add an empty pending command at the end of the target actor's
7755 * queue. This command won't do anything when executed; its
7756 * purpose is to let us track whether or not the target is still
7757 * working on commands we have issued up to this point, which we
7758 * can tell by looking to see whether our empty command is still
7759 * in the actor's queue.
7760 *
7761 * Note that we can't simply wait until the actor's queue is
7762 * empty, because the actor could acquire new commands while
7763 * it's working on our pending commands, and we wouldn't want to
7764 * wait for those to finish. Adding a dummy pending command is
7765 * a reliable way of tracking the actor's queue, because any
7766 * changes to the target actor's command queue will leave our
7767 * dummy command in its proper place until the target actor gets
7768 * around to executing it, at which point it will be removed.
7769 *
7770 * Remember the dummy pending command in a property of self, so
7771 * that we can check later to determine when the command has
7772 * finished.
7773 */
7774 waitingForActor = targetActor;
7775 waitingForInfo = new PendingCommandMarker(self);
7776 targetActor.pendingCommand.append(waitingForInfo);
7777 }
7778
7779 /*
7780 * Synchronous command processing: the target actor and dummy
7781 * pending command we're waiting for. When these are non-nil, we
7782 * won't take another turn until the given PendingCommandInfo has
7783 * been removed from the given target actor's command queue.
7784 */
7785 waitingForActor = nil
7786 waitingForInfo = nil
7787
7788 /*
7789 * Add the given actor to the list of actors accompanying my travel
7790 * on the current turn. This does NOT set an actor in "follow mode"
7791 * or "accompany mode" or anything like that - don't use this to make
7792 * an actor follow me around. Instead, this makes the given actor go
7793 * with us for the CURRENT travel only - the travel we're already in
7794 * the process of performing to process the current TravelVia action.
7795 */
7796 addAccompanyingActor(actor)
7797 {
7798 /* if we don't have the accompanying actor vector yet, create it */
7799 if (accompanyingActors == nil)
7800 accompanyingActors = new Vector(8);
7801
7802 /* add the actor to my list */
7803 accompanyingActors.append(actor);
7804 }
7805
7806 /*
7807 * My vector of actors who are accompanying me.
7808 *
7809 * This is for internal bookkeeping only, and it applies to the
7810 * current travel only. This is NOT a general "follow mode" setting,
7811 * and it shouldn't be used to get me to follow another actor or
7812 * another actor to follow me. To make me accompany another actor,
7813 * simply override accompanyTravel() so that it returns a suitable
7814 * ActorState object.
7815 */
7816 accompanyingActors = nil
7817
7818 /*
7819 * Get the list of objects I can follow. This is a list of all of
7820 * the objects which I have seen departing a location - these are
7821 * all in scope for 'follow' commands.
7822 */
7823 getFollowables()
7824 {
7825 /* return the list of the objects we know about */
7826 return followables_.mapAll({x: x.obj});
7827 }
7828
7829 /*
7830 * Do I track departing objects for following the given object?
7831 *
7832 * By default, the player character tracks everyone, and NPC's track
7833 * only the actor they're presently tasked to follow. Most NPC's
7834 * will never accept 'follow' commands, so there's no need to track
7835 * everyone all the time; for efficiency, we take advantage of this
7836 * assumption so that we can avoid storing a bunch of tracking
7837 * information that will never be used.
7838 */
7839 wantsFollowInfo(obj)
7840 {
7841 /*
7842 * by default, the player character tracks everyone, and NPC's
7843 * track only the object (if any) they're currently tasked to
7844 * follow
7845 */
7846 return isPlayerChar() || followingActor == obj;
7847 }
7848
7849 /*
7850 * Receive notification that an object is leaving its current
7851 * location as a result of the action we're currently processing.
7852 * Actors (and possibly other objects) will broadcast this
7853 * notification to all Actor objects connected in any way by
7854 * containment when they move under their own power (such as with
7855 * Actor.travelTo) to a new location. We'll keep tracking
7856 * information if we are configured to keep tracking information for
7857 * the given object and we can see the given object. Note that this
7858 * is called when the object is still at the source end of the travel
7859 * - the important thing is that we see the object departing.
7860 *
7861 * 'obj' is the object that is seen to be leaving, and 'conn' is the
7862 * TravelConnector it is taking.
7863 *
7864 * 'conn' is the connector being traversed. If we're simply being
7865 * observed in this location (as in a call to setHasSeen), rather
7866 * than being observed to leave the location, the connector will be
7867 * nil.
7868 *
7869 * 'from' is the effective starting location of the travel. This
7870 * isn't necessarily the departing object's location, since the
7871 * departing object could be inside a vehicle or some other kind of
7872 * traveler object.
7873 *
7874 * Note that this notification is sent only to actors with some sort
7875 * of containment connection to the object that's moving, because a
7876 * containment connection is necessary for there to be a sense
7877 * connection.
7878 */
7879 trackFollowInfo(obj, conn, from)
7880 {
7881 local info;
7882
7883 /*
7884 * If we're not tracking the given object, or we can't see the
7885 * given object, ignore the notification. In addition, we
7886 * obviously have no need to track ourselves.x
7887 */
7888 if (obj == self || !wantsFollowInfo(obj) || !canSee(obj))
7889 return;
7890
7891 /*
7892 * If we already have a FollowInfo for the given object, re-use
7893 * the existing one; otherwise, create a new one and add it to
7894 * our tracking list.
7895 */
7896 info = followables_.valWhich({x: x.obj == obj});
7897 if (info == nil)
7898 {
7899 /* we don't have an existing one - create a new one */
7900 info = new FollowInfo();
7901 info.obj = obj;
7902
7903 /* add it to our list */
7904 followables_ += info;
7905 }
7906
7907 /* remember information about the travel */
7908 info.connector = conn;
7909 info.sourceLocation = from;
7910 }
7911
7912 /*
7913 * Get information on what to do to make this actor follow the given
7914 * object. This returns a FollowInfo object that reports our last
7915 * knowledge of the given object's location and departure, or nil if
7916 * we don't know anything about how to follow the actor.
7917 */
7918 getFollowInfo(obj)
7919 {
7920 return followables_.valWhich({x: x.obj == obj});
7921 }
7922
7923 /*
7924 * By default, all actors are followable.
7925 */
7926 verifyFollowable()
7927 {
7928 return true;
7929 }
7930
7931 /*
7932 * Verify a "follow" command being performed by this actor.
7933 */
7934 actorVerifyFollow(obj)
7935 {
7936 /*
7937 * check to see if we're in the same effective follow location
7938 * as the target; if we are, it makes no sense to follow the
7939 * target, since we're already effectively at the same place
7940 */
7941 if (obj.location != nil
7942 && (location.effectiveFollowLocation
7943 == obj.location.effectiveFollowLocation))
7944 {
7945 /*
7946 * We're in the same location as the target. If we're the
7947 * player character, this makes no sense, because the player
7948 * character can't go into follow mode (as that would take
7949 * away the player's ability to control the player
7950 * character). If we're an NPC, though, this simply tells
7951 * us to go into follow mode for the target, so there's
7952 * nothing wrong with it.
7953 */
7954 if (isPlayerChar)
7955 {
7956 /*
7957 * The target is right here, but we're the player
7958 * character, so it makes no sense for us to go into
7959 * follow mode. If we can see the target, complain that
7960 * it's already here; if not, we can only assume it's
7961 * here, but we can't know for sure.
7962 */
7963 if (canSee(obj))
7964 illogicalNow(&followAlreadyHereMsg);
7965 else
7966 illogicalNow(&followAlreadyHereInDarkMsg);
7967 }
7968 }
7969 else if (!canSee(obj))
7970 {
7971 /*
7972 * The target isn't here, and we can't see it from here, so
7973 * we must want to follow it to its current location. Get
7974 * information on how we will follow the target. If there's
7975 * no such information, we obviously can't do any following
7976 * because we never saw the target go anywhere in the first
7977 * place.
7978 */
7979 if (getFollowInfo(obj) == nil)
7980 {
7981 /* we've never heard of the target */
7982 illogicalNow(&followUnknownMsg);
7983 }
7984 }
7985 }
7986
7987 /*
7988 * Carry out a "follow" command being performed by this actor.
7989 */
7990 actorActionFollow(obj)
7991 {
7992 local canSeeObj;
7993
7994 /* note whether or not we can see the target */
7995 canSeeObj = canSee(obj);
7996
7997 /*
7998 * If we're not the PC, check to see if this is a follow-mode
7999 * request; otherwise, try to go to the location of the target.
8000 */
8001 if (!isPlayerChar && canSeeObj)
8002 {
8003 /*
8004 * If we're not already following this actor, acknowledge the
8005 * request and go into 'follow' mode. If we're already
8006 * following this actor, and we didn't issue the command to
8007 * ourself, let them know we're already in the requested
8008 * mode. Otherwise, ignore it silently - if we issued the
8009 * command to ourself, it's because we're just executing our
8010 * own 'follow' mode imperative.
8011 */
8012 if (followingActor != obj)
8013 {
8014 /* let them know we're going to follow the actor now */
8015 reportAfter(&okayFollowModeMsg);
8016
8017 /* go into follow mode */
8018 followingActor = obj;
8019 }
8020 else if (gIssuingActor != self)
8021 {
8022 /* let them know we're already in follow mode */
8023 reportAfter(&alreadyFollowModeMsg);
8024 }
8025
8026 /*
8027 * if we're already in the target's effective follow
8028 * location, that's all we need to do
8029 */
8030 if (location.effectiveFollowLocation
8031 == obj.location.effectiveFollowLocation)
8032 return;
8033 }
8034
8035 /*
8036 * If we can see the target, AND we're in the same top-level
8037 * location as the target, then simply use a "local travel"
8038 * operation to move into the same location. This only works
8039 * with targets that are within the same top-level location,
8040 * since that's the whole point of the local-travel routines.
8041 * For non-local travel, we need to perform a full-fledged travel
8042 * command instead.
8043 */
8044 if (canSeeObj && isIn(obj.getOutermostRoom()))
8045 {
8046 /*
8047 * We have no information, so we will only have made it past
8048 * verification if we can see the other actor from our
8049 * current location. Try moving to the other actor's
8050 * effective follow location.
8051 */
8052 obj.location.effectiveFollowLocation.checkMovingActorInto(true);
8053
8054 /*
8055 * Since checkMovingActorInto will do its work through
8056 * implicit actions, if we're the player character, then the
8057 * entire action will have been performed implicitly, so we
8058 * won't have a real report for the series of generated
8059 * actions, just implied action announcements. If we're an
8060 * NPC, on the other hand, we'll generate the full reports,
8061 * since NPC implied actions simply show what the actor is
8062 * doing. So, if we're the PC, generate an additional
8063 * default acknowledgment of the 'follow' action.
8064 */
8065 if (isPlayerChar)
8066 defaultReport(&okayFollowInSightMsg,
8067 location.effectiveFollowLocation);
8068 }
8069 else
8070 {
8071 local info;
8072 local srcLoc;
8073
8074 /* get the information on how to follow the target */
8075 info = getFollowInfo(obj);
8076
8077 /* get the effective follow location we have to be in */
8078 srcLoc = info.sourceLocation.effectiveFollowLocation;
8079
8080 /* if there's no connector, we can't go anywhere */
8081 if (info.connector == nil)
8082 {
8083 /*
8084 * We have no departure information, so we can't follow
8085 * the actor. If we're currently within sight of the
8086 * location where we last saw the actor, it means that we
8087 * saw the actor here, then went somewhere else, then
8088 * came back, and in our absence the actor itself
8089 * departed. In this case, report that we don't know
8090 * where the actor went.
8091 *
8092 * If we're not in sight of the location where we last
8093 * saw the actor, then instead remind the player of where
8094 * that was.
8095 */
8096 if (canSee(srcLoc))
8097 {
8098 /*
8099 * we're where we last saw the actor, but the actor
8100 * must have departed while we were away - so we
8101 * simply don't know where the actor went
8102 */
8103 reportFailure(&followUnknownMsg);
8104 }
8105 else
8106 {
8107 /*
8108 * we've gone somewhere else since we last saw the
8109 * actor, so remind the player of where it was that
8110 * we saw the actor
8111 */
8112 reportFailure(&cannotFollowFromHereMsg, srcLoc);
8113 }
8114
8115 /* in any case, that's all we can do now */
8116 return;
8117 }
8118
8119 /*
8120 * Before we can follow the target, we must be in the same
8121 * effective location that the target was in when we
8122 * observed the target leaving.
8123 */
8124 if (location.effectiveFollowLocation != srcLoc)
8125 {
8126 /*
8127 * If we can't even see the effective follow location, we
8128 * must have last observed the other actor traveling from
8129 * an unrelated location. In this case, simply say that
8130 * we don't know where the followee went.
8131 */
8132 if (!canSee(srcLoc))
8133 {
8134 reportFailure(&cannotFollowFromHereMsg, srcLoc);
8135 return;
8136 }
8137
8138 /*
8139 * Try moving into the same location, by invoking the
8140 * pre-condition handler for moving me into the
8141 * effective follow location from our memory of the
8142 * actor's travel. We *could* run this as an actual
8143 * precondition, but it's easier to run it here now that
8144 * we've sorted out exactly what we want to do.
8145 */
8146 srcLoc.checkMovingActorInto(true);
8147 }
8148
8149 /* perform a TravelVia action on the connector */
8150 nestedAction(TravelVia, info.connector);
8151 }
8152 }
8153
8154 /*
8155 * Our list of followable information. Each entry in this list is a
8156 * FollowInfo object that tracks a particular followable.
8157 */
8158 followables_ = []
8159
8160 /* determine if I've ever seen the given object */
8161 hasSeen(obj) { return obj.(seenProp); }
8162
8163 /* mark the object to remember that I've seen it */
8164 setHasSeen(obj) { obj.noteSeenBy(self, seenProp); }
8165
8166 /* receive notification that another actor is observing us */
8167 noteSeenBy(actor, prop)
8168 {
8169 /* do the standard work to remember that we've been seen */
8170 inherited(actor, prop);
8171
8172 /*
8173 * Update the follow tracking information with the latest
8174 * observed location. We're merely observing the fact that the
8175 * actor is here, not that the actor is departing, so the
8176 * connector is nil.
8177 *
8178 * The point of noting the actor's presence in the "follow info"
8179 * is that we want to replace any previous memory we have of the
8180 * actor departing from another location. Now that we know where
8181 * the actor is, any old memory of the actor having left another
8182 * location is now irrelevant. We only keep track of one "follow
8183 * info" record per actor, so this new record will replace any
8184 * older record.
8185 */
8186 actor.trackFollowInfo(self, nil, location);
8187 }
8188
8189 /*
8190 * Determine if I know about the given object. I know about an
8191 * object if it's specifically marked as known to me; I also know
8192 * about the object if I can see it now, or if I've ever seen it in
8193 * the past.
8194 */
8195 knowsAbout(obj) { return canSee(obj) || hasSeen(obj) || obj.(knownProp); }
8196
8197 /* mark the object as known to me */
8198 setKnowsAbout(obj) { obj.(knownProp) = true; }
8199
8200 /*
8201 * My 'seen' property. By default, this is simply 'seen', which
8202 * means that we don't distinguish who's seen what - in other words,
8203 * there's a single, global 'seen' flag per object, and if anyone's
8204 * ever seen something, then we consider that to mean everyone has
8205 * seen it.
8206 *
8207 * Some games might want to track each NPC's sight memory
8208 * separately, or at least they might want to track it individually
8209 * for a few specific NPC's. You can do this by making up a new
8210 * property name for each NPC whose sight memory you want to keep
8211 * separate, and simply setting 'seenProp' to that property name for
8212 * each such NPC. For example, for Bob, you could make the property
8213 * bobHasSeen, so in Bob you'd define 'sightProp = &bobHasSeen'.
8214 */
8215 seenProp = &seen
8216
8217 /*
8218 * My 'known' property. By default, this is simply 'known', which
8219 * means that we don't distinguish who knows what.
8220 *
8221 * As with 'seenProp' above, if you want to keep track of each NPC's
8222 * knowledge separately, you must override this property for each
8223 * NPC who's to have its own knowledge base to use a separate
8224 * property name. For example, if you want to keep track of what
8225 * Bob knows individually, you could define 'knownProp = &bobKnows'
8226 * in Bob.
8227 */
8228 knownProp = &isKnown
8229
8230 /*
8231 * Determine if the actor recognizes the given object as a "topic,"
8232 * which is an object that represents some knowledge the actor can
8233 * use in conversations, consultations, and the like.
8234 *
8235 * By default, we'll recognize any Topic object marked as known, and
8236 * we'll recognize any game object for which our knowsAbout(obj)
8237 * returns true. Games might wish to override this in some cases to
8238 * limit or expand an actor's knowledge according to what the actor
8239 * has experienced of the setting or story. Note that it's often
8240 * easier to control actor knowledge using the lower-level
8241 * knowsAbout() and setKnowsAbout() methods, though.
8242 */
8243 knowsTopic(obj)
8244 {
8245 /* we know the object as a topic if we know about it at all */
8246 return knowsAbout(obj);
8247 }
8248
8249 /*
8250 * Determine if the given object is a likely topic for a
8251 * conversational action performed by this actor. By default, we'll
8252 * return true if the topic is known, nil if not.
8253 */
8254 isLikelyTopic(obj)
8255 {
8256 /* if the object is known, it's a possible topic */
8257 return knowsTopic(obj);
8258 }
8259
8260 /* we are the owner of any TopicEntry objects contained within us */
8261 getTopicOwner() { return self; }
8262
8263 /*
8264 * Suggest topics of conversation. This is called by the TOPICS
8265 * command (in which case 'explicit' is true), and whenever we first
8266 * engage a character in a stateful conversation (in which case
8267 * 'explicit' is nil).
8268 *
8269 * We'll show the list of suggested topics associated with our
8270 * current conversational partner. If there are no topics, we'll say
8271 * nothing unless 'explicit' is true, in which case we'll simply say
8272 * that there are no topics that the player character is thinking
8273 * about.
8274 *
8275 * The purpose of this method is to let the game author keep an
8276 * "inventory" of topics with this actor for a given conversational
8277 * partner. This inventory is meant to represent the topics that on
8278 * the player character's mind - things the player character wants to
8279 * talk about with the other actor. Note that we're talking about
8280 * what the player *character* is thinking about - obviously we don't
8281 * know what's on the player's mind.
8282 *
8283 * When we enter conversation, or when the player asks for advice,
8284 * we'll show this inventory. The idea is to help guide the player
8285 * through a conversation without the more heavy-handed device of a
8286 * formal conversation menu system, so that conversations have a more
8287 * free-form feel without leaving the player hunting in the dark for
8288 * the magic ASK ABOUT topic.
8289 *
8290 * The TOPICS system is entirely optional. If a game doesn't specify
8291 * any SuggestedTopic objects, then this routine will simply never be
8292 * called, and the TOPICS command won't be allowed. Some authors
8293 * think it gives away too much to provide a list of topic
8294 * suggestions like this, and others don't like anything that smacks
8295 * of a menu system because they think it destroys the illusion
8296 * created by the text-input command line that the game is boundless.
8297 * Authors who feel this way can just ignore the TOPICS system. But
8298 * be aware that the illusion of boundlessness isn't always a good
8299 * thing for players; hunting around for ASK ABOUT topics can make
8300 * the game's limits just as obvious, if not more so, by exposing the
8301 * vast number of inputs for which the actor doesn't have a good
8302 * response. Players aren't stupid - a string of variations on "I
8303 * don't know about that" is just as obviously mechanistic as a
8304 * numbered list of menu choices. Using the TOPICS system might be a
8305 * good compromise for many authors, since the topic list can help
8306 * guide the player to the right questions without making the player
8307 * feel straitjacketed by a menu list.
8308 */
8309 suggestTopics(explicit)
8310 {
8311 local actor;
8312
8313 /*
8314 * if we're talking to someone, look up their suggested topics;
8315 * otherwise, we have nothing to suggest
8316 */
8317 if ((actor = getCurrentInterlocutor()) != nil)
8318 {
8319 /*
8320 * we're talking to someone - suggest topics appropriate to
8321 * the person we're talking to
8322 */
8323 actor.suggestTopicsFor(self, explicit);
8324 }
8325 else if (explicit)
8326 {
8327 /* we're not talking to anyone, so there's nothing to suggest */
8328 gLibMessages.noTopicsNotTalking;
8329 }
8330 }
8331
8332 /*
8333 * Suggest topics that the given actor might want to talk to us
8334 * about. The given actor is almost always the player character,
8335 * since generally NPC's don't talk to one another using
8336 * conversation commands (there'd be no point; they're simple
8337 * programmed automata, not full-blown AI's).
8338 */
8339 suggestTopicsFor(actor, explicit)
8340 {
8341 /* by default, let our state suggest topics */
8342 curState.suggestTopicsFor(actor, explicit);
8343 }
8344
8345 /*
8346 * Receive notification that a command is being carried out in our
8347 * presence.
8348 */
8349 beforeAction()
8350 {
8351 /*
8352 * If another actor is trying to take something in my inventory,
8353 * by default, do not allow it.
8354 */
8355 if (gActor != self
8356 && (gActionIs(Take) || gActionIs(TakeFrom))
8357 && gDobj.isIn(self))
8358 {
8359 /* check to see if we want to allow this action */
8360 checkTakeFromInventory(gActor, gDobj);
8361 }
8362
8363 /* let our state object take a look at the action */
8364 curState.beforeAction();
8365 }
8366
8367 /*
8368 * Perform any actor-specific processing for an action. The main
8369 * command processor invokes this on gActor after notifying nearby
8370 * objects via beforeAction(), but before carrying out the main
8371 * action of the command.
8372 */
8373 actorAction()
8374 {
8375 /* do nothing by default */
8376 }
8377
8378 /*
8379 * Receive notification that a command has just been carried out in
8380 * our presence.
8381 */
8382 afterAction()
8383 {
8384 /* let the state object handle it */
8385 curState.afterAction();
8386 }
8387
8388 /* receive a notification that someone is about to travel */
8389 beforeTravel(traveler, connector)
8390 {
8391 /* let the state object handle it */
8392 curState.beforeTravel(traveler, connector);
8393
8394 /*
8395 * If desired, track the departure so that we can follow the
8396 * traveler later. First, track the departure of each actor
8397 * traveling with the traveler.
8398 */
8399 traveler.forEachTravelingActor(
8400 {actor: trackFollowInfo(actor, connector, traveler.location)});
8401
8402 /*
8403 * if the traveler is distinct from the actors traveling, track
8404 * it as well
8405 */
8406 if (!traveler.isActorTraveling(traveler))
8407 trackFollowInfo(traveler, connector, traveler.location);
8408 }
8409
8410 /* receive a notification that someone has just traveled here */
8411 afterTravel(traveler, connector)
8412 {
8413 /* let the state object handle it */
8414 curState.afterTravel(traveler, connector);
8415 }
8416
8417 /*
8418 * Receive notification that I'm initiating travel. This is called
8419 * on the actor performing the travel action before the travel is
8420 * actually carried out.
8421 */
8422 actorTravel(traveler, connector)
8423 {
8424 /*
8425 * If other actors are accompanying me on this travel, run the
8426 * same travel action on the accompanying actors, using nested
8427 * actions.
8428 */
8429 if (accompanyingActors != nil
8430 && accompanyingActors.length() != 0)
8431 {
8432 /*
8433 * Run the same travel action as a nested action on each
8434 * accompanying actor. Skip this for any accompanying actor
8435 * we're carrying, as they'll naturally go with us as a
8436 * result of being carried.
8437 */
8438 foreach (local cur in accompanyingActors)
8439 {
8440 /* if the actor's not being carried, run the same action */
8441 if (!cur.isIn(self))
8442 nestedActorAction(cur, TravelVia, gDobj);
8443 }
8444
8445 /*
8446 * The accompanying actor list applies for this single group
8447 * travel command, so now that we've moved everyone, we have
8448 * no further need for the list. Clear it out.
8449 */
8450 accompanyingActors.removeRange(1, accompanyingActors.length());
8451 }
8452 }
8453
8454 /*
8455 * Check to see if we want to allow another actor to take something
8456 * from my inventory. By default, we won't allow it - we'll always
8457 * fail the command.
8458 */
8459 checkTakeFromInventory(actor, obj)
8460 {
8461 /* don't allow it - show an error and terminate the command */
8462 mainReport(&willNotLetGoMsg, self, obj);
8463 exit;
8464 }
8465
8466 /*
8467 * Build a list of the objects that are explicitly registered to
8468 * receive notification when I'm the actor in a command.
8469 */
8470 getActorNotifyList()
8471 {
8472 return actorNotifyList;
8473 }
8474
8475 /*
8476 * Add an item to our registered notification items. These items
8477 * are to receive notifications when we're the actor performing a
8478 * command.
8479 *
8480 * Items can be added here if they must be notified of actions
8481 * performed by the actor even when the items aren't connected by
8482 * containment with the actor at the time of the action. All items
8483 * connected to the actor by containment are automatically notified
8484 * of each action; only items that must receive notification even
8485 * when not in scope need to be registered here.
8486 */
8487 addActorNotifyItem(obj)
8488 {
8489 actorNotifyList += obj;
8490 }
8491
8492 /* remove an item from the registered notification list */
8493 removeActorNotifyItem(obj)
8494 {
8495 actorNotifyList -= obj;
8496 }
8497
8498 /* our list of registered actor notification items */
8499 actorNotifyList = []
8500
8501 /*
8502 * Get the ambient light level in the visual senses at this actor.
8503 * This is the ambient level at the actor.
8504 */
8505 getVisualAmbient()
8506 {
8507 local ret;
8508 local cache;
8509
8510 /* check for a cached value */
8511 if ((cache = libGlobal.actorVisualAmbientCache) != nil
8512 && (ret = cache[self]) != nil)
8513 {
8514 /* found a cached entry - use it */
8515 return ret;
8516 }
8517
8518 /* get the maximum ambient level at self for my sight-like senses */
8519 ret = senseAmbientMax(sightlikeSenses);
8520
8521 /* if caching is active, cache our result for next time */
8522 if (cache != nil)
8523 cache[self] = ret;
8524
8525 /* return the result */
8526 return ret;
8527 }
8528
8529 /*
8530 * Determine if my location is lit for my sight-like senses.
8531 */
8532 isLocationLit()
8533 {
8534 /*
8535 * Check for a simple, common case before doing the full
8536 * sense-path calculation: if our location is providing its own
8537 * light to its interior, then the location is lit. Most simple
8538 * rooms are always lit.
8539 */
8540 if (sightlikeSenses.indexOf(sight) != nil
8541 && location != nil
8542 && location.brightness > 1
8543 && location.transSensingOut(sight) == transparent)
8544 return true;
8545
8546 /*
8547 * We don't have the simple case of light directly from our
8548 * location, so run the full sense path check and get our
8549 * maximum visual ambience level. If it's above the "self-lit"
8550 * level of 1, then we can see.
8551 */
8552 return (getVisualAmbient() > 1);
8553 }
8554
8555 /*
8556 * Get the best (most transparent) sense information for one of our
8557 * visual senses to the given object.
8558 */
8559 bestVisualInfo(obj)
8560 {
8561 local best;
8562
8563 /* we don't have a best value yet */
8564 best = nil;
8565
8566 /* check each sight-like sense */
8567 foreach (local sense in sightlikeSenses)
8568 {
8569 /*
8570 * get the information for the object in this sense, and keep
8571 * the best (most transparent) info we've seen so far
8572 */
8573 best = SenseInfo.selectMoreTrans(best, senseObj(sense, obj));
8574 }
8575
8576 /* return the best one we found */
8577 return best;
8578 }
8579
8580 /*
8581 * Build a list of all of the objects of which an actor is aware.
8582 *
8583 * An actor is aware of an object if the object is within reach of
8584 * the actor's senses, and has some sort of presence in that sense.
8585 * Note that both of these conditions must be true for at least one
8586 * sense possessed by the actor; an object that is within earshot,
8587 * but not within reach of any other sense, is in scope only if the
8588 * object is making some kind of noise.
8589 *
8590 * In addition, objects that the actor is holding (i.e., those
8591 * contained by the actor directly) are always in scope, regardless
8592 * of their reachability through any sense.
8593 */
8594 scopeList()
8595 {
8596 local lst;
8597
8598 /* we have nothing in our master list yet */
8599 lst = new Vector(32);
8600
8601 /* oneself is always in one's own scope list */
8602 lst.append(self);
8603
8604 /* iterate over each sense */
8605 foreach (local sense in scopeSenses)
8606 {
8607 /*
8608 * get the list of objects with a presence in this sense
8609 * that can be sensed from our point of view, and and append
8610 * it to our master list
8611 */
8612 lst.appendUnique(sensePresenceList(sense));
8613 }
8614
8615 /* add all of the items we are directly holding */
8616 lst.appendUnique(contents);
8617
8618 /*
8619 * ask each of our direct contents to add any contents of their
8620 * own that are in scope by virtue of their containers being in
8621 * scope
8622 */
8623 foreach (local cur in contents)
8624 cur.appendHeldContents(lst);
8625
8626 /* add any items that are specially in scope in the location */
8627 if (location != nil)
8628 {
8629 /* get the extra scope items */
8630 local extra = location.getExtraScopeItems(self);
8631
8632 /* if this is a non-nil list, add it to our list */
8633 if (extra.length() != 0)
8634 lst.appendUnique(extra);
8635 }
8636
8637 /*
8638 * Finally, add anything extra each item already in scope wants
8639 * to add. Note that we keep going until we've visited each
8640 * element of the vector at its current length on each iteration,
8641 * so if we add any new items, we'll check them to see if they
8642 * want to add any new items, and so on.
8643 */
8644 for (local i = 1 ; i <= lst.length() ; ++i)
8645 {
8646 local extra;
8647
8648 /* get the extra scope items for this item */
8649 extra = lst[i].getExtraScopeItems(self);
8650
8651 /* if the extra item list is non-nil, add it to our list */
8652 if (extra.length() != 0)
8653 lst.appendUnique(extra);
8654 }
8655
8656 /* return the result */
8657 return lst.toList();
8658 }
8659
8660 /*
8661 * Determine if I can see the given object. This returns true if
8662 * the object can be sensed at all in one of my sight-like senses,
8663 * nil if not.
8664 */
8665 canSee(obj)
8666 {
8667 /* try each sight-like sense */
8668 foreach (local sense in sightlikeSenses)
8669 {
8670 /*
8671 * if I can sense the object in this sense, I can sense the
8672 * object
8673 */
8674 if (senseObj(sense, obj).trans != opaque)
8675 return true;
8676 }
8677
8678 /* we didn't find any sight-like sense where we can see the object */
8679 return nil;
8680 }
8681
8682 /*
8683 * Determine if I can hear the given object.
8684 */
8685 canHear(obj)
8686 {
8687 /* try each hearling-like sense */
8688 foreach (local sense in hearinglikeSenses)
8689 {
8690 /*
8691 * if I can sense the object in this sense, I can sense the
8692 * object
8693 */
8694 if (senseObj(sense, obj).trans != opaque)
8695 return true;
8696 }
8697
8698 /* we found no hearing-like sense that lets us hear the object */
8699 return nil;
8700 }
8701
8702 /*
8703 * Determine if I can smell the given object.
8704 */
8705 canSmell(obj)
8706 {
8707 /* try each hearling-like sense */
8708 foreach (local sense in smelllikeSenses)
8709 {
8710 /*
8711 * if I can sense the object in this sense, I can sense the
8712 * object
8713 */
8714 if (senseObj(sense, obj).trans != opaque)
8715 return true;
8716 }
8717
8718 /* we found no smell-like sense that lets us hear the object */
8719 return nil;
8720 }
8721
8722 /*
8723 * Find the object that prevents us from seeing the given object.
8724 */
8725 findVisualObstructor(obj)
8726 {
8727 /* try to find an opaque obstructor in one of our visual senses */
8728 foreach (local sense in sightlikeSenses)
8729 {
8730 local obs;
8731
8732 /* cache path information for this sense */
8733 cacheSenseInfo(connectionTable(), sense);
8734
8735 /* if we find an obstructor in this sense, return it */
8736 if ((obs = findOpaqueObstructor(sense, obj)) != nil)
8737 return obs;
8738 }
8739
8740 /* we didn't find any obstructor */
8741 return nil;
8742 }
8743
8744 /*
8745 * Build a table of full sensory information for all of the objects
8746 * visible to the actor through the actor's sight-like senses.
8747 * Returns a lookup table with the same set of information as
8748 * senseInfoTable().
8749 */
8750 visibleInfoTable()
8751 {
8752 /* return objects visible from my own point of view */
8753 return visibleInfoTableFromPov(self);
8754 }
8755
8756 /*
8757 * Build a table of full sensory information for all of the objects
8758 * visible to me from a particular point of view through my
8759 * sight-like senses.
8760 */
8761 visibleInfoTableFromPov(pov)
8762 {
8763 local tab;
8764
8765 /* we have no master table yet */
8766 tab = nil;
8767
8768 /* iterate over each sense */
8769 foreach (local sense in sightlikeSenses)
8770 {
8771 local cur;
8772
8773 /* get information for all objects for the current sense */
8774 cur = pov.senseInfoTable(sense);
8775
8776 /* merge the table so far with the new table */
8777 tab = mergeSenseInfoTable(cur, tab);
8778 }
8779
8780 /* return the result */
8781 return tab;
8782 }
8783
8784 /*
8785 * Build a lookup table of the objects that can be sensed for the
8786 * purposes of taking inventory. We'll include everything in the
8787 * normal visual sense table, plus everything directly held.
8788 */
8789 inventorySenseInfoTable()
8790 {
8791 local visInfo;
8792 local cont;
8793 local ambient;
8794 local info;
8795
8796 /*
8797 * Start with the objects visible to the actor through the
8798 * actor's sight-like senses.
8799 */
8800 visInfo = visibleInfoTable();
8801
8802 /* get the ambient light level at the actor */
8803 if ((info = visInfo[self]) != nil)
8804 ambient = info.ambient;
8805 else
8806 ambient = 0;
8807
8808 /*
8809 * We'll assume that, for each item that the actor is directly
8810 * holding AND knows about, the actor can still identify the item
8811 * by touch, even if it's not visible. This way, when we're in a
8812 * dark room, we'll still be able to refer to the objects we're
8813 * directly holding, as long as we already know about them.
8814 *
8815 * Likewise, add items within our direct contents that are
8816 * considered equally held.
8817 */
8818 cont = new Vector(32);
8819 foreach (local cur in contents)
8820 {
8821 /* add this item from our contents */
8822 cont.append(cur);
8823
8824 /* add its contents that are themselves equally as held */
8825 cur.appendHeldContents(cont);
8826 }
8827
8828 /*
8829 * Make a fully-sensible entry for each of our held items. We
8830 * can simply replace any existing entry in the table that we got
8831 * from the visual senses, since a fully transparent entry will
8832 * be at least as good as anything we got from the normal visual
8833 * list. Only include items that the actor knows about; we'll
8834 * assume that we can identify by touch anything we're holding if
8835 * we already know what it is, but not otherwise.
8836 */
8837 foreach (local cur in cont)
8838 {
8839 /* if we know about the object, make it effectively visible */
8840 if (knowsAbout(cur))
8841 visInfo[cur] = new SenseInfo(cur, transparent, nil, ambient);
8842 }
8843
8844 /* return the table */
8845 return visInfo;
8846 }
8847
8848 /*
8849 * Show what the actor is carrying.
8850 */
8851 showInventory(tall)
8852 {
8853 /*
8854 * show our inventory with our default listers as given by our
8855 * inventory/wearing lister properties
8856 */
8857 showInventoryWith(tall, inventoryLister);
8858 }
8859
8860 /*
8861 * Show what the actor is carrying, using the given listers.
8862 *
8863 * Note that this method must be overridden if the actor does not
8864 * use a conventional 'contents' list property to store its full set
8865 * of contents.
8866 */
8867 showInventoryWith(tall, inventoryLister)
8868 {
8869 local infoTab;
8870
8871 /* get the table of objects sensible for inventory */
8872 infoTab = inventorySenseInfoTable();
8873
8874 /* list in the appropriate mode ("wide" or "tall") */
8875 inventoryLister.showList(self, self, contents,
8876 ListRecurse | (tall ? ListTall : 0),
8877 0, infoTab, nil);
8878
8879 /* mention sounds coming from inventory items */
8880 inventorySense(sound, inventoryListenLister);
8881
8882 /* mention odors coming from inventory items */
8883 inventorySense(smell, inventorySmellLister);
8884 }
8885
8886 /*
8887 * Add to an inventory description a list of things we notice
8888 * through a specific sense.
8889 */
8890 inventorySense(sense, lister)
8891 {
8892 local infoTab;
8893 local presenceList;
8894
8895 /* get the information table for the desired sense */
8896 infoTab = senseInfoTable(sense);
8897
8898 /*
8899 * get the list of everything with a presence in this sense that
8900 * I'm carrying
8901 */
8902 presenceList = senseInfoTableSubset(infoTab,
8903 {obj, info: obj.isIn(self) && obj.(sense.presenceProp)});
8904
8905 /* add a paragraph break */
8906 cosmeticSpacingReport('<.p>');
8907
8908 /* list the items */
8909 lister.showList(self, nil, presenceList, 0, 0, infoTab, nil);
8910 }
8911
8912 /*
8913 * The Lister object that we use for inventory listings. By
8914 * default, we use actorInventoryLister, but this can be overridden
8915 * if desired to use a different listing style.
8916 */
8917 inventoryLister = actorInventoryLister
8918
8919 /*
8920 * The Lister for inventory listings, for use in a full description
8921 * of the actor. By default, we use the "long form" inventory
8922 * lister, on the assumption that most actors have relatively lengthy
8923 * descriptive text. This can be overridden to use other formats;
8924 * the short-form lister, for example, is useful for actors with only
8925 * brief descriptions.
8926 */
8927 holdingDescInventoryLister = actorHoldingDescInventoryListerLong
8928
8929 /*
8930 * Perform library pre-initialization on the actor
8931 */
8932 initializeActor()
8933 {
8934 /* set up an empty pending command list */
8935 pendingCommand = new Vector(5);
8936
8937 /* create a default inventory lister if we don't have one already */
8938 if (inventoryLister == nil)
8939 inventoryLister = actorInventoryLister;
8940
8941 /* create our antecedent tables */
8942 antecedentTable = new LookupTable(8, 8);
8943 possAnaphorTable = new LookupTable(8, 8);
8944
8945 /* if we don't have a state object, create a default */
8946 if (curState == nil)
8947 setCurState(new ActorState(self));
8948
8949 /* create our pending-conversation list */
8950 pendingConv = new Vector(5);
8951 }
8952
8953 /*
8954 * Note conditions before an action or other event. By default, we
8955 * note our location and light/dark status, so that we comment on
8956 * any change in the light/dark status after the event if we're
8957 * still in the same location.
8958 */
8959 noteConditionsBefore()
8960 {
8961 /* note our original location and light/dark status */
8962 locationBefore = location;
8963 locationLitBefore = isLocationLit();
8964 }
8965
8966 /*
8967 * Note conditions after an action or other event. By default, if
8968 * we are still in the same location we were in when
8969 * noteConditionsBefore() was last called, and the light/dark status
8970 * has changed, we'll mention the change in light/dark status.
8971 */
8972 noteConditionsAfter()
8973 {
8974 /*
8975 * If our location hasn't changed but our light/dark status has,
8976 * note the new status. We don't make any announcement if the
8977 * location has changed, since the travel routine will
8978 * presumably have shown us the new location's light/dark status
8979 * implicitly as part of the description of the new location
8980 * after travel.
8981 */
8982 if (location == locationBefore
8983 && isLocationLit() != locationLitBefore)
8984 {
8985 /* consider this the start of a new turn */
8986 "<.commandsep>";
8987
8988 /* note the change with a new 'NoteDarkness' action */
8989 newActorAction(self, NoteDarkness);
8990
8991 /*
8992 * start another turn, in case this occurred during an
8993 * implicit action or the like
8994 */
8995 "<.commandsep>";
8996 }
8997 }
8998
8999 /* conditions we noted in noteConditionsBefore() */
9000 locationBefore = nil
9001 locationLitBefore = nil
9002
9003 /* let the actor have a turn as soon as the game starts */
9004 nextRunTime = 0
9005
9006 /*
9007 * Scheduling order - this determines the order of execution when
9008 * several items are schedulable at the same game clock time.
9009 *
9010 * We choose a scheduling order that schedules actors in this
9011 * relative order:
9012 *
9013 * 100 player character, ready to execute
9014 *. 200 NPC, ready to execute
9015 *. 300 player character, idle
9016 *. 400 NPC, idle
9017 *
9018 * An "idle" actor is one that is waiting for another character to
9019 * complete a command, or an NPC with no pending commands to
9020 * perform. (For the player character, it doesn't matter whether or
9021 * not there's a pending command, because if the PC has no pending
9022 * command, we ask the player for one.)
9023 *
9024 * This ordering ensures that each actor gets a chance to run each
9025 * turn, but that actors with work to do go first, and other things
9026 * being equal, the player character goes ahead of NPC's.
9027 */
9028 scheduleOrder = 100
9029
9030 /* calculate the scheduling order */
9031 calcScheduleOrder()
9032 {
9033 /* determine if we're ready to run */
9034 if (readyForTurn())
9035 scheduleOrder = isPlayerChar() ? 100 : 200;
9036 else
9037 scheduleOrder = isPlayerChar() ? 300 : 400;
9038
9039 /* return the scheduling order */
9040 return scheduleOrder;
9041 }
9042
9043 /*
9044 * Determine if we're ready to do something on our turn. We're
9045 * ready to do something if we're not waiting for another actor to
9046 * finish doing something and either we're the player character or
9047 * we already have a pending command in our command queue.
9048 */
9049 readyForTurn()
9050 {
9051 /*
9052 * if we're waiting for another actor, we're not ready to do
9053 * anything
9054 */
9055 if (checkWaitingForActor())
9056 return nil;
9057
9058 /*
9059 * if we're the player character, we're always ready to take a
9060 * turn as long as we're not waiting for another actor (which we
9061 * now know we're not), because we can either execute one of our
9062 * previously queued commands, or we can ask for a new command
9063 * to perform
9064 */
9065 if (isPlayerChar())
9066 return true;
9067
9068 /*
9069 * if we have something other than placeholders in our command
9070 * queue, we're ready to take a turn, because we can execute the
9071 * next command in our queue
9072 */
9073 if (pendingCommand.indexWhich({x: x.hasCommand}) != nil)
9074 return true;
9075
9076 /*
9077 * we have no specific work to do, so we're not ready for our
9078 * next turn
9079 */
9080 return nil;
9081 }
9082
9083 /*
9084 * Check to see if we're waiting for another actor to do something.
9085 * Return true if so, nil if not. If we've been waiting for another
9086 * actor, and the actor has finished the task we've been waiting for
9087 * since the last time we checked, we'll clean up our internal state
9088 * relating to the wait and return nil.
9089 */
9090 checkWaitingForActor()
9091 {
9092 local cmdIdx;
9093 local idx;
9094
9095 /* if we're not waiting for an actor, simply return nil */
9096 if (waitingForActor == nil)
9097 return nil;
9098
9099 /*
9100 * We're waiting for an actor to complete a command. Check to
9101 * see if the completion marker is still in the actor's queue; if
9102 * it's not, then the other actor has already completed our task.
9103 * If the completion marker is in the other actor's queue, but
9104 * there are no command entries before it, then we're also done
9105 * waiting, because we're not actually waiting for the completion
9106 * marker but instead for the tasks that were ahead of it in the
9107 * main game execution loop.
9108 *
9109 * So, find the index of our marker in the queue, and find the
9110 * index of the first real command in the queue. If our marker
9111 * is still in the queue, and there's a command in the queue
9112 * before our marker, the actor we're waiting for still has
9113 * things to do before we're ready, so we're still waiting.
9114 */
9115 idx = waitingForActor.pendingCommand.indexOf(waitingForInfo);
9116 cmdIdx = waitingForActor.pendingCommand.indexWhich({x: x.hasCommand});
9117 if (idx != nil && cmdIdx != nil && idx > cmdIdx)
9118 {
9119 /*
9120 * The marker is still in the queue, and there's at least
9121 * one other command ahead of it, so the other actor hasn't
9122 * finished the task we've been waiting for. Tell the
9123 * caller that we are indeed still waiting for someone.
9124 */
9125 return true;
9126 }
9127
9128 /*
9129 * The other actor has disposed of our end-marker (or is about
9130 * to, because it's the next thing left in the actor's queue),
9131 * so it has finished with all of the commands we have been
9132 * waiting for. However, if I haven't caught up in game clock
9133 * time with the actor I've been waiting for, I'm still waiting.
9134 */
9135 if (waitingForActor.nextRunTime > nextRunTime)
9136 return true;
9137
9138 /* we're done waiting - forget our wait status information */
9139 waitingForActor = nil;
9140 waitingForInfo = nil;
9141
9142 /* tell the caller we're no longer waiting for anyone */
9143 return nil;
9144 }
9145
9146 /* the action the actor performed most recently */
9147 mostRecentAction = nil
9148
9149 /*
9150 * Add busy time. An action calls this when we are the actor
9151 * performing the action, and the action consumes game time. This
9152 * marks us as busy for the given time units.
9153 */
9154 addBusyTime(action, units)
9155 {
9156 /* note the action being performed */
9157 mostRecentAction = action;
9158
9159 /* adjust the next run time by the busy time */
9160 nextRunTime += units;
9161 }
9162
9163 /*
9164 * When it's our turn and we don't have any command to perform,
9165 * we'll call this routine, which can perform a scripted operation
9166 * if desired.
9167 */
9168 idleTurn()
9169 {
9170 local tCur = Schedulable.gameClockTime;
9171 local origNextRunTime = nextRunTime;
9172
9173 /*
9174 * if we haven't been targeted for conversation on this turn,
9175 * see if we have a conversation we want to start
9176 */
9177 if (lastConvTime < tCur)
9178 {
9179 /* check for a conversation that's ready to go */
9180 local info = pendingConv.valWhich({x: tCur >= x.time_});
9181
9182 /* if we found one, kick it off */
9183 if (info != nil)
9184 {
9185 /* remove it from the list */
9186 pendingConv.removeElement(info);
9187
9188 /* start the conversation */
9189 initiateConversation(info.state_, info.node_);
9190 }
9191 }
9192
9193 /* notify our state object that we're taking a turn */
9194 curState.takeTurn();
9195
9196 /*
9197 * If we haven't already adjusted our next run time, consume a
9198 * turn, so we're not ready to run again until the next game time
9199 * increment. In some cases, we'll already have made this
9200 * adjustment; for example, we might have run a nested command
9201 * within our state object's takeTurn() method.
9202 */
9203 if (nextRunTime == origNextRunTime)
9204 ++nextRunTime;
9205 }
9206
9207 /*
9208 * Receive notification that this is a non-idle turn. This is
9209 * called whenever a command in our pending command queue is about
9210 * to be executed.
9211 *
9212 * This method need not do anything at all, since the caller will
9213 * take care of running the pending command. The purpose of this
9214 * method is to take care of any changes an actor wants to make when
9215 * it receives an explicit command, as opposed to running its own
9216 * autonomous activity.
9217 *
9218 * By default, we cancel follow mode if it's in effect. It usually
9219 * makes sense for an explicit command to interrupt follow mode;
9220 * follow mode is usually started by an explicit command in the
9221 * first place, so it is usually sensible for a new command to
9222 * replace the one that started follow mode.
9223 */
9224 nonIdleTurn()
9225 {
9226 /* by default, cancel follow mode */
9227 followingActor = nil;
9228 }
9229
9230 /*
9231 * If we're following an actor, this keeps track of the actor we're
9232 * following. NPC's can use this to follow around another actor
9233 * whenever possible.
9234 */
9235 followingActor = nil
9236
9237 /*
9238 * Handle a situation where we're trying to follow an actor but
9239 * can't. By default, this simply cancels our follow mode.
9240 *
9241 * Actors might want to override this to be more tolerant. For
9242 * example, an actor might want to wait until five turns elapse to
9243 * give up on following, in case the target actor returns after a
9244 * brief digression; or an actor could stay in follow mode until it
9245 * received other instructions, or found something better to do.
9246 */
9247 cannotFollow()
9248 {
9249 /*
9250 * by default, simply cancel follow mode by forgetting about the
9251 * actor we're following
9252 */
9253 followingActor = nil;
9254 }
9255
9256 /*
9257 * Execute one "turn" - this is a unit of time passing. The player
9258 * character generally is allowed to execute one command in the
9259 * course of a turn; a non-player character with a programmed task
9260 * can perform an increment of the task.
9261 *
9262 * We set up an ActorTurnAction environment and invoke our
9263 * executeActorTurn() method. In most cases, subclasses should
9264 * override executeActorTurn() rather than this method, since
9265 * overriding executeTurn() directly will lose the action
9266 * environment.
9267 */
9268 executeTurn()
9269 {
9270 /* start a new command visually when a new actor is taking over */
9271 "<.commandsep>";
9272
9273 /*
9274 * Execute the turn in a daemon action context, and in the sight
9275 * context of the actor. The sense context will ensure that we
9276 * report the results of the action only if the actor is visible
9277 * to the player character; in most cases, the actor's
9278 * visibility is equivalent to the visibility of the effects, so
9279 * this provides a simple way of ensuring that the results of
9280 * the action are reported if and only if they're visible to the
9281 * player character.
9282 *
9283 * Note that if we are the player character, don't use the sense
9284 * context filtering -- we normally want full reports for
9285 * everything the player character does.
9286 */
9287 return withActionEnv(EventAction, self,
9288 {: callWithSenseContext(isPlayerChar() ? nil : self, sight,
9289 {: executeActorTurn() }) });
9290 }
9291
9292 /*
9293 * The main processing for an actor's turn. In most cases,
9294 * subclasses should override this method (rather than executeTurn)
9295 * to specialize an actor's turn processing.
9296 */
9297 executeActorTurn()
9298 {
9299 /*
9300 * If we have a pending response, and we're in a position to
9301 * deliver it, our next work is to deliver the pending response.
9302 */
9303 if (pendingResponse != nil && canTalkTo(pendingResponse.issuer_))
9304 {
9305 /*
9306 * We have a pending response, and the command issuer from
9307 * the pending response can hear us now, so we can finally
9308 * deliver the response.
9309 *
9310 * If the issuer is the player character, send to the player
9311 * using our deferred message generator; otherwise, call the
9312 * issuer's notification routine, since it's an NPC-to-NPC
9313 * notification.
9314 */
9315 if (pendingResponse.issuer_.isPlayerChar())
9316 {
9317 /*
9318 * we're notifying the player - use the deferred message
9319 * generator
9320 */
9321 getParserDeferredMessageObj().(pendingResponse.prop_)(
9322 self, pendingResponse.args_...);
9323 }
9324 else
9325 {
9326 /* it's an NPC-to-NPC notification - notify the issuer */
9327 pendingResponse.issuer_.notifyIssuerParseFailure(
9328 self, pendingResponse.prop_, pendingResponse.args_);
9329 }
9330
9331 /*
9332 * in either case, we've gotten this out of our system now,
9333 * so we can forget about the pending response
9334 */
9335 pendingResponse = nil;
9336 }
9337
9338 /* check to see if we're waiting for another actor */
9339 if (checkWaitingForActor())
9340 {
9341 /*
9342 * we're still waiting, so there's nothing for us to do; take
9343 * an idle turn and return
9344 */
9345 idleTurn();
9346 return true;
9347 }
9348
9349 /*
9350 * if we're the player character, and we have no pending commands
9351 * to execute, our next task will be to read and execute a
9352 * command
9353 */
9354 if (pendingCommand.length() == 0 && isPlayerChar())
9355 {
9356 local toks;
9357
9358 /* read a command line and get the resulting token list */
9359 toks = readMainCommandTokens(rmcCommand);
9360
9361 /*
9362 * re-activate the main transcript - reading the command
9363 * line will have deactivated the transcript, but we want it
9364 * active again now that we're about to start executing the
9365 * command
9366 */
9367 gTranscript.activate();
9368
9369 /*
9370 * If it came back nil, it means that the input was fully
9371 * processed in pre-parsing; this means that we don't have
9372 * any more work to do on this turn, so we can simply end our
9373 * turn now.
9374 */
9375 if (toks == nil)
9376 return true;
9377
9378 /* retrieve the token list from the command line */
9379 toks = toks[2];
9380
9381 /*
9382 * Add it to our pending command queue. Since we read the
9383 * command from the player, and we're the player character,
9384 * we treat the command as coming from myself.
9385 *
9386 * Since this is a newly-read command line, we're starting a
9387 * new sentence.
9388 */
9389 addPendingCommand(true, self, toks);
9390 }
9391
9392 /*
9393 * Check to see if we have any pending command to execute. If
9394 * so, our next task is to execute the pending command.
9395 */
9396 if (pendingCommand.length() != 0)
9397 {
9398 local cmd;
9399
9400 /* remove the first pending command from our queue */
9401 cmd = pendingCommand[1];
9402 pendingCommand.removeElementAt(1);
9403
9404 /* if this is a real command, note the non-idle turn */
9405 if (cmd.hasCommand)
9406 nonIdleTurn();
9407
9408 /* execute the first pending command */
9409 cmd.executePending(self);
9410
9411 /*
9412 * We're done with this turn. If we no longer have any
9413 * pending commands, tell the scheduler to refigure the
9414 * execution order, since another object might now be ready
9415 * to run ahead of our idle activity.
9416 */
9417 if (pendingCommand.indexWhich({x: x.hasCommand}) == nil)
9418 return nil;
9419 else
9420 return true;
9421 }
9422
9423 /*
9424 * If we're following an actor, and the actor isn't in sight, see
9425 * if we can catch up.
9426 */
9427 if (followingActor != nil
9428 && location != nil
9429 && (followingActor.location.effectiveFollowLocation
9430 != location.effectiveFollowLocation))
9431 {
9432 local info;
9433
9434 /* see if we have enough information to follow */
9435 info = getFollowInfo(followingActor);
9436
9437 /*
9438 * Check to see if we have enough information to follow the
9439 * actor. We can only follow if we saw the actor depart at
9440 * some point, and we're in the same location where we last
9441 * saw the actor depart. (We have to be in the same
9442 * location, because we follow by performing the same command
9443 * we saw the actor perform when we last saw the actor
9444 * depart. Repeating the command will obviously be
9445 * ineffective unless we're in the same location as the actor
9446 * was.)
9447 */
9448 if (info != nil)
9449 {
9450 local success;
9451
9452 /*
9453 * we know how to follow the actor, so simply perform
9454 * the same command we saw the actor perform.
9455 */
9456 newActorAction(self, Follow, followingActor);
9457
9458 /* note whether or not we succeeded */
9459 success = (location.effectiveFollowLocation ==
9460 followingActor.location.effectiveFollowLocation);
9461
9462 /* notify the state object of our attempt */
9463 curState.justFollowed(success);
9464
9465 /*
9466 * if we failed to track the actor, note that we are
9467 * unable to follow the actor
9468 */
9469 if (!success)
9470 {
9471 /* note that we failed to follow the actor */
9472 cannotFollow();
9473 }
9474
9475 /* we're done with this turn */
9476 return true;
9477 }
9478 else
9479 {
9480 /*
9481 * we don't know how to follow this actor - call our
9482 * cannot-follow handler
9483 */
9484 cannotFollow();
9485 }
9486 }
9487
9488 /* we have no pending work to perform, so take an idle turn */
9489 idleTurn();
9490
9491 /* no change in scheduling priority */
9492 return true;
9493 }
9494
9495 /*
9496 * By default, all actors are likely command targets. This should
9497 * be overridden for actors who are obviously not likely to accept
9498 * commands of any kind.
9499 *
9500 * This is used to disambiguate target actors in commands, so this
9501 * should provide an indication of what should be obvious to a
9502 * player, because the purpose of this information is to guess what
9503 * the player is likely to take for granted in specifying a target
9504 * actor.
9505 */
9506 isLikelyCommandTarget = true
9507
9508 /*
9509 * Determine if we should accept a command. 'issuingActor' is the
9510 * actor who issued the command: if the player typed the command on
9511 * the command line, this will be the player character actor.
9512 *
9513 * This routine performs only the simplest check, since it doesn't
9514 * have access to the specific action being performed. This is
9515 * intended as a first check, to allow us to bypass noun resolution
9516 * if the actor simply won't accept any command from the issuer.
9517 *
9518 * Returns true to accept a command, nil to reject it. If this
9519 * routine returns nil, and the command came from the player
9520 * character, a suitable message should be displayed.
9521 *
9522 * Note that most actors should not override this routine simply to
9523 * express the will of the actor to accept a command, since this
9524 * routine performs a number of checks for the physical ability of
9525 * the actor to execute a command from the issuer. To determine
9526 * whether or not the actor should obey physically valid commands
9527 * from the issuer, override obeyCommand().
9528 */
9529 acceptCommand(issuingActor)
9530 {
9531 /* if we're the current player character, accept any command */
9532 if (isPlayerChar())
9533 return true;
9534
9535 /* if we can't hear the issuer, we can't talk to it */
9536 if (issuingActor != self && !issuingActor.canTalkTo(self))
9537 {
9538 /* report that the target actor can't hear the issuer */
9539 reportFailure(&objCannotHearActorMsg, self);
9540
9541 /* tell the caller that the command cannot proceed */
9542 return nil;
9543 }
9544
9545 /* if I'm busy doing something else, say so */
9546 if (nextRunTime > Schedulable.gameClockTime)
9547 {
9548 /* tell the issuing actor I'm busy */
9549 notifyParseFailure(issuingActor, &refuseCommandBusy,
9550 [issuingActor]);
9551
9552 /* tell the caller to abandon the command */
9553 return nil;
9554 }
9555
9556 /* check to see if I have other work to perform first */
9557 if (!acceptCommandBusy(issuingActor))
9558 return nil;
9559
9560 /* we didn't find any reason to object, so allow the command */
9561 return true;
9562 }
9563
9564 /*
9565 * Check to see if I'm busy with pending commands, and if so,
9566 * whether or not I should accept a new command. Returns true if we
9567 * should accept a command, nil if not. If we return nil, we must
9568 * notify the issuer of the rejection.
9569 *
9570 * By default, we won't accept a command if we have any work
9571 * pending.
9572 */
9573 acceptCommandBusy(issuingActor)
9574 {
9575 /* if we have any pending commands, don't accept a new command */
9576 if (pendingCommand.length() != 0)
9577 {
9578 /*
9579 * if we have only commands from the same issuer pending,
9580 * cancel all of the pending commands and accept the new
9581 * command instead
9582 */
9583 foreach (local info in pendingCommand)
9584 {
9585 /*
9586 * if this is from a different issuer, don't accept a
9587 * new command
9588 */
9589 if (info.issuer_ != issuingActor)
9590 {
9591 /* tell the other actor that we're busy */
9592 notifyParseFailure(issuingActor, &refuseCommandBusy,
9593 [issuingActor]);
9594
9595 /* tell the caller to abandon the command */
9596 return nil;
9597 }
9598 }
9599
9600 /*
9601 * all of the pending commands were from the same issuer, so
9602 * presumably the issuer wants to override those commands;
9603 * remove the old ones from our pending queue
9604 */
9605 pendingCommand.removeRange(1, pendingCommand.length());
9606 }
9607
9608 /* we didn't find any problems */
9609 return true;
9610 }
9611
9612 /*
9613 * Determine whether or not we want to obey a command from the given
9614 * actor to perform the given action. We only get this far when we
9615 * determine that it's possible for us to accept a command, given
9616 * the sense connections between us and the issuing actor, and given
9617 * our pending command queue.
9618 *
9619 * When this routine is called, the action has been determined, and
9620 * the noun phrases have been resolved. However, we haven't
9621 * actually started processing the action yet, so the globals for
9622 * the noun slots (gDobj, gIobj, etc) are NOT available. If the
9623 * routine needs to know which objects are involved, it must obtain
9624 * the full list of resolved objects from the action (using, for
9625 * example, getResolvedDobjList()).
9626 *
9627 * When there's a list of objects to be processed (as in GET ALL),
9628 * we haven't started working on any one of them yet - this check is
9629 * made once for the entire command, and applies to the entire list
9630 * of objects. If the actor wants to respond specially to
9631 * individual objects, you can do that by overriding actorAction()
9632 * instead of this routine.
9633 *
9634 * This routine should display an appropriate message and return nil
9635 * if the command is not to be accepted, and should simply return
9636 * true to accept the command.
9637 *
9638 * By default, we'll let our state object handle this.
9639 *
9640 * Note that actors that override this might also need to override
9641 * wantsFollowInfo(), since an actor that accepts "follow" commands
9642 * will need to keep track of the movements of other actors if it is
9643 * to carry out any following.
9644 */
9645 obeyCommand(issuingActor, action)
9646 {
9647 /* note that the issuing actor is targeting me in conversation */
9648 issuingActor.noteConversation(self);
9649
9650 /* let the state object handle it */
9651 return curState.obeyCommand(issuingActor, action);
9652 }
9653
9654 /*
9655 * Say hello/goodbye/yes/no to the given actor. We'll greet the
9656 * target actor is the target actor was specified (i.e., actor !=
9657 * self); otherwise, we'll greet our current default conversational
9658 * partner, if we have one.
9659 */
9660 sayHello(actor) { sayToActor(actor, helloTopicObj, helloConvType); }
9661 sayGoodbye(actor) { sayToActor(actor, byeTopicObj, byeConvType); }
9662 sayYes(actor) { sayToActor(actor, yesTopicObj, yesConvType); }
9663 sayNo(actor) { sayToActor(actor, noTopicObj, noConvType); }
9664
9665 /* handle one of the conversational addresses */
9666 sayToActor(actor, topic, convType)
9667 {
9668 /*
9669 * If the target actor is the same as the issuing actor, then no
9670 * target actor was specified in the command, so direct the
9671 * address to our current conversational partner, if we have
9672 * one.
9673 */
9674 if (actor == self)
9675 actor = getDefaultInterlocutor();
9676
9677 /*
9678 * if we found an actor, send the address to the actor's state
9679 * object; otherwise, handle it with the given default message
9680 */
9681 if (actor != nil)
9682 {
9683 /* make sure we can talk to the other actor */
9684 if (!canTalkTo(actor))
9685 {
9686 /* can't talk to them - say so and give up */
9687 reportFailure(&objCannotHearActorMsg, actor);
9688 exit;
9689 }
9690
9691 /* remember our current conversational partner */
9692 noteConversation(actor);
9693
9694 /* handle it as a topic */
9695 actor.curState.handleConversation(self, topic, convType);
9696 }
9697 else
9698 {
9699 /*
9700 * we don't know whom we're addressing; just show the default
9701 * message for an unknown interlocutor
9702 */
9703 mainReport(convType.unknownMsg);
9704 }
9705 }
9706
9707 /*
9708 * Handle the XSPCLTOPIC pseudo-command. This command is generated
9709 * by the SpecialTopic pre-parser when it recognizes the player's
9710 * input as matching an active SpecialTopic's custom syntax. Our
9711 * job is to route this back to our current interlocutor's active
9712 * ConvNode, so that it can find the SpecialTopic that it matched in
9713 * pre-parsing and show its response.
9714 */
9715 saySpecialTopic()
9716 {
9717 local actor;
9718
9719 /* send it to our interlocutor */
9720 if ((actor = getCurrentInterlocutor()) == nil
9721 || actor.curConvNode == nil)
9722 {
9723 /*
9724 * We don't seem to have a current interlocutor, or the
9725 * interlocutor doesn't have a current conversation node.
9726 * This is inconsistent; there's no way we could have
9727 * generated XSPCLTOPIC from our pre-parser under these
9728 * conditions. The most likely thing is that the player
9729 * tried typing in XSPCLTOPIC manually. Politely ignore it.
9730 */
9731 gLibMessages.commandNotPresent;
9732 }
9733 else
9734 {
9735 /* note the conversation directed to the other actor */
9736 noteConversation(actor);
9737
9738 /* send the request to the ConvNode for processing */
9739 actor.curConvNode.saySpecialTopic(self);
9740 }
9741 }
9742
9743 /*
9744 * Add a command to our pending command list. The new command is
9745 * specified as a list of tokens to be parsed, and it is added after
9746 * any commands already in our pending list.
9747 */
9748 addPendingCommand(startOfSentence, issuer, toks)
9749 {
9750 /* add a descriptor to the pending command list */
9751 pendingCommand.append(
9752 new PendingCommandToks(startOfSentence, issuer, toks));
9753 }
9754
9755 /*
9756 * Insert a command at the head of our pending command list. The
9757 * new command is specified as a list of tokens to parse, and it is
9758 * inserted into our pending command list before any commands
9759 * already in the list.
9760 */
9761 addFirstPendingCommand(startOfSentence, issuer, toks)
9762 {
9763 /* add a descriptor to the start of our list */
9764 pendingCommand.insertAt(
9765 1, new PendingCommandToks(startOfSentence, issuer, toks));
9766 }
9767
9768 /*
9769 * Add a resolved action to our pending command list. The new
9770 * command is specified as a resolved Action object; it is added
9771 * after any commands already in our list.
9772 */
9773 addPendingAction(startOfSentence, issuer, action, [objs])
9774 {
9775 /* add a descriptor to the pending command list */
9776 pendingCommand.append(new PendingCommandAction(
9777 startOfSentence, issuer, action, objs...));
9778 }
9779
9780 /*
9781 * Insert a resolved action at the start of our pending command
9782 * list. The new command is specified as a resolved Action object;
9783 * it is added before any commands already in our list.
9784 */
9785 addFirstPendingAction(startOfSentence, issuer, action, [objs])
9786 {
9787 /* add a descriptor to the pending command list */
9788 pendingCommand.insertAt(1, new PendingCommandAction(
9789 startOfSentence, issuer, action, objs...));
9790 }
9791
9792
9793 /* pending commands - this is a list of PendingCommandInfo objects */
9794 pendingCommand = nil
9795
9796 /*
9797 * pending response - this is a single PendingResponseInfo object,
9798 * which we'll deliver as soon as the issuing actor is in a position
9799 * to hear us
9800 */
9801 pendingResponse = nil
9802
9803 /*
9804 * get the library message object for a parser message addressed to
9805 * the player character
9806 */
9807 getParserMessageObj()
9808 {
9809 /*
9810 * If I'm the player character, use the player character message
9811 * object; otherwise, use the default non-player character
9812 * message object.
9813 *
9814 * To customize parser messages from a particular actor, create
9815 * an object based on npcMessages, and override this routine in
9816 * the actor so that it returns the custom object rather than
9817 * the standard npcMessages object. To customize messages for
9818 * ALL of the NPC's in a game, simply modify npcMessages itself,
9819 * since it's the default for all non-player characters.
9820 */
9821 return isPlayerChar() ? playerMessages : npcMessages;
9822 }
9823
9824 /*
9825 * Get the deferred library message object for a parser message
9826 * addressed to the player character. We only use this to generate
9827 * messages deferred from non-player characters.
9828 */
9829 getParserDeferredMessageObj() { return npcDeferredMessages; }
9830
9831 /*
9832 * Get the library message object for action responses. This is
9833 * used to generate library responses to verbs.
9834 */
9835 getActionMessageObj()
9836 {
9837 /*
9838 * return the default player character or NPC message object,
9839 * depending on whether I'm the player or not; individual actors
9840 * can override this to supply actor-specific messages for
9841 * library action responses
9842 */
9843 return isPlayerChar() ? playerActionMessages: npcActionMessages;
9844 }
9845
9846 /*
9847 * Notify an issuer that a command sent to us resulted in a parsing
9848 * failure. We are meant to reply to the issuer to let the issuer
9849 * know about the problem. messageProp is the libGlobal message
9850 * property describing the error, and args is a list with the
9851 * (varargs) arguments to the message property.
9852 */
9853 notifyParseFailure(issuingActor, messageProp, args)
9854 {
9855 /*
9856 * In case the actor is in a remote location but in scope for the
9857 * purposes of the conversation only (such as over a phone or
9858 * radio), run this in a neutral sense context. Since we're
9859 * reporting a parser failure, we want the message to be
9860 * displayed no matter what the scope situation is.
9861 */
9862 callWithSenseContext(nil, nil, function()
9863 {
9864 /* check who's talking to whom */
9865 if (issuingActor.isPlayerChar())
9866 {
9867 /*
9868 * The player issued the command. If the command was
9869 * directed to an NPC (i.e., we're not the player), check
9870 * to see if the player character is in scope from our
9871 * perspective.
9872 */
9873 if (issuingActor != self && !canTalkTo(issuingActor))
9874 {
9875 /*
9876 * The player issued the command to an NPC, but the
9877 * player is not capable of hearing the NPC's
9878 * response.
9879 */
9880 cannotRespondToCommand(issuingActor, messageProp, args);
9881 }
9882 else
9883 {
9884 /*
9885 * generate a message using the appropriate message
9886 * generator object
9887 */
9888 getParserMessageObj().(messageProp)(self, args...);
9889 }
9890 }
9891 else
9892 {
9893 /*
9894 * the command was issued from one NPC to another -
9895 * notify the issuer of the problem, but don't display
9896 * any messages, since this interaction is purely among
9897 * the NPC's
9898 */
9899 issuingActor.
9900 notifyIssuerParseFailure(self, messageProp, args);
9901 }
9902 });
9903 }
9904
9905 /*
9906 * We have a parser error to report to the player, but we cannot
9907 * respond at the moment because the player is not capable of
9908 * hearing us (there is no sense path for our communications senses
9909 * from us to the player actor). Defer reporting the message until
9910 * later.
9911 */
9912 cannotRespondToCommand(issuingActor, messageProp, args)
9913 {
9914 /*
9915 * Remember the problem for later deliver. If we already have a
9916 * deferred response, forget it - just report the latest
9917 * problem.
9918 */
9919 pendingResponse =
9920 new PendingResponseInfo(issuingActor, messageProp, args);
9921
9922 /*
9923 * Some actors might want to override this to start searching
9924 * for the player character. We don't have any generic
9925 * mechanism to conduct such a search, but a game that
9926 * implements one might want to make use of it here.
9927 */
9928 }
9929
9930 /*
9931 * Receive notification that a command we sent to another NPC
9932 * failed. This is only called when one NPC sends a command to
9933 * another NPC; this is called on the issuer to let the issuer know
9934 * that the target can't perform the command because of the given
9935 * resolution failure.
9936 *
9937 * By default, we don't do anything here, because we don't have any
9938 * default code to send a command from one NPC to another. Any
9939 * custom NPC actor that sends a command to another NPC actor might
9940 * want to use this to deal with problems in processing those
9941 * commands.
9942 */
9943 notifyIssuerParseFailure(targetActor, messageProp, args)
9944 {
9945 /* by default, we do nothing */
9946 }
9947
9948 /*
9949 * Antecedent lookup table. Each actor keeps its own table of
9950 * antecedents indexed by pronoun type, so that we can
9951 * simultaneously have different antecedents for different pronouns.
9952 */
9953 antecedentTable = nil
9954
9955 /*
9956 * Possessive anaphor lookup table. In almost all cases, the
9957 * possessive anaphor for a given pronoun will be the same as the
9958 * corresponding regular pronoun: HIS indicates possession by HIM,
9959 * for example. In a few cases, though, the anaphoric quality of
9960 * possessives takes precedence, and these will differ. For
9961 * example, in TELL BOB TO DROP HIS BOOK, "his" refers back to Bob,
9962 * while in TELL BOB TO HIT HIM, "him" refers to whatever it
9963 * referred to before the command.
9964 */
9965 possAnaphorTable = nil
9966
9967 /*
9968 * set the antecedent for the neuter singular pronoun ("it" in
9969 * English)
9970 */
9971 setIt(obj)
9972 {
9973 setPronounAntecedent(PronounIt, obj);
9974 }
9975
9976 /* set the antecedent for the masculine singular ("him") */
9977 setHim(obj)
9978 {
9979 setPronounAntecedent(PronounHim, obj);
9980 }
9981
9982 /* set the antecedent for the feminine singular ("her") */
9983 setHer(obj)
9984 {
9985 setPronounAntecedent(PronounHer, obj);
9986 }
9987
9988 /* set the antecedent list for the ungendered plural pronoun ("them") */
9989 setThem(lst)
9990 {
9991 setPronounAntecedent(PronounThem, lst);
9992 }
9993
9994 /* look up a pronoun's value */
9995 getPronounAntecedent(typ)
9996 {
9997 /* get the stored antecedent for this pronoun */
9998 return antecedentTable[typ];
9999 }
10000
10001 /* set a pronoun's antecedent value */
10002 setPronounAntecedent(typ, val)
10003 {
10004 /* remember the value in the antecedent table */
10005 antecedentTable[typ] = val;
10006
10007 /* set the same value for the possessive anaphor */
10008 possAnaphorTable[typ] = val;
10009 }
10010
10011 /* set a possessive anaphor value */
10012 setPossAnaphor(typ, val)
10013 {
10014 /* set the value in the possessive anaphor table only */
10015 possAnaphorTable[typ] = val;
10016 }
10017
10018 /* get a possessive anaphor value */
10019 getPossAnaphor(typ) { return possAnaphorTable[typ]; }
10020
10021 /* forget the possessive anaphors */
10022 forgetPossAnaphors()
10023 {
10024 /* copy all of the antecedents to the possessive anaphor table */
10025 antecedentTable.forEachAssoc(
10026 {key, val: possAnaphorTable[key] = val});
10027 }
10028
10029 /*
10030 * Copy pronoun antecedents from the given actor. This should be
10031 * called whenever an actor issues a command to us, so that pronouns
10032 * in the command are properly resolved relative to the issuer.
10033 */
10034 copyPronounAntecedentsFrom(issuer)
10035 {
10036 /* copy every element from the issuer's table */
10037 issuer.antecedentTable.forEachAssoc(
10038 {key, val: setPronounAntecedent(key, val)});
10039 }
10040
10041 /* -------------------------------------------------------------------- */
10042 /*
10043 * Verb processing
10044 */
10045
10046 /* show a "take from" message as indicating I don't have the dobj */
10047 takeFromNotInMessage = &takeFromNotInActorMsg
10048
10049 /* verify() handler to check against applying an action to 'self' */
10050 verifyNotSelf(msg)
10051 {
10052 /* check to make sure we're not trying to do this to myself */
10053 if (self == gActor)
10054 illogicalSelf(msg);
10055 }
10056
10057 /* macro to verify we're not self, and inherit the default behavior */
10058 #define verifyNotSelfInherit(msg) \
10059 verify() \
10060 { \
10061 verifyNotSelf(msg); \
10062 inherited(); \
10063 }
10064
10065 /*
10066 * For the basic physical manipulation verbs (TAKE, DROP, PUT ON,
10067 * etc), it's illogical to operate on myself, so check for this in
10068 * verify(). Otherwise, handle these as we would ordinary objects,
10069 * since we might be able to manipulate other actors in the normal
10070 * manner, especially actors small enough that we can pick them up.
10071 */
10072 dobjFor(Take) { verifyNotSelfInherit(&takingSelfMsg) }
10073 dobjFor(Drop) { verifyNotSelfInherit(&droppingSelfMsg) }
10074 dobjFor(PutOn) { verifyNotSelfInherit(&puttingSelfMsg) }
10075 dobjFor(PutUnder) { verifyNotSelfInherit(&puttingSelfMsg) }
10076 dobjFor(Throw) { verifyNotSelfInherit(&throwingSelfMsg) }
10077 dobjFor(ThrowAt) { verifyNotSelfInherit(&throwingSelfMsg) }
10078 dobjFor(ThrowDir) { verifyNotSelfInherit(&throwingSelfMsg) }
10079 dobjFor(ThrowTo) { verifyNotSelfInherit(&throwingSelfMsg) }
10080
10081 /* customize the message for THROW TO <actor> */
10082 iobjFor(ThrowTo)
10083 {
10084 verify()
10085 {
10086 /* by default, we don't want to catch anything */
10087 illogical(&willNotCatchMsg, self);
10088 }
10089 }
10090
10091 /* treat PUT SELF IN FOO as GET IN FOO */
10092 dobjFor(PutIn)
10093 {
10094 verify()
10095 {
10096 /* the target actor is always unsuitable as a default */
10097 if (gActor == self)
10098 nonObvious;
10099 }
10100
10101 check()
10102 {
10103 /* if I'm putting myself somewhere, treat it as GET IN */
10104 if (gActor == self)
10105 replaceAction(Enter, gIobj);
10106
10107 /* do the normal work */
10108 inherited();
10109 }
10110 }
10111
10112 dobjFor(Kiss)
10113 {
10114 preCond = [touchObj]
10115 verify()
10116 {
10117 /* cannot kiss oneself */
10118 verifyNotSelf(&cannotKissSelfMsg);
10119 }
10120 action() { mainReport(&cannotKissActorMsg); }
10121 }
10122
10123 dobjFor(AskFor)
10124 {
10125 preCond = [canTalkToObj]
10126 verify()
10127 {
10128 /* it makes no sense to ask myself for something */
10129 verifyNotSelf(&cannotAskSelfForMsg);
10130 }
10131 action()
10132 {
10133 /* note that the issuer is targeting us with conversation */
10134 gActor.noteConversation(self);
10135
10136 /* let the state object handle it */
10137 curState.handleConversation(gActor, gTopic, askForConvType);
10138 }
10139 }
10140
10141 dobjFor(TalkTo)
10142 {
10143 preCond = [canTalkToObj]
10144 verify()
10145 {
10146 /* it's generally illogical to talk to oneself */
10147 verifyNotSelf(&cannotTalkToSelfMsg);
10148 }
10149 action()
10150 {
10151 /* note that the issuer is targeting us in conversation */
10152 gActor.noteConversation(self);
10153
10154 /* handle it as a 'hello' topic */
10155 curState.handleConversation(gActor, helloTopicObj, helloConvType);
10156 }
10157 }
10158
10159 iobjFor(GiveTo)
10160 {
10161 verify()
10162 {
10163 /* it makes no sense to give something to myself */
10164 verifyNotSelf(&cannotGiveToSelfMsg);
10165
10166 /* it also makes no sense to give something to itself */
10167 if (gDobj == gIobj)
10168 illogicalSelf(&cannotGiveToItselfMsg);
10169 }
10170 action()
10171 {
10172 /* take note that I've seen the direct object */
10173 noteObjectShown(gDobj);
10174
10175 /* note that the issuer is targeting us with conversation */
10176 gActor.noteConversation(self);
10177
10178 /* let the state object handle it */
10179 curState.handleConversation(gActor, gDobj, giveConvType);
10180 }
10181 }
10182
10183 iobjFor(ShowTo)
10184 {
10185 verify()
10186 {
10187 /* it makes no sense to show something to myself */
10188 verifyNotSelf(&cannotShowToSelfMsg);
10189
10190 /* it also makes no sense to show something to itself */
10191 if (gDobj == gIobj)
10192 illogicalSelf(&cannotShowToItselfMsg);
10193 }
10194 action()
10195 {
10196 /* take note that I've seen the direct object */
10197 noteObjectShown(gDobj);
10198
10199 /* note that the issuer is targeting us with conversation */
10200 gActor.noteConversation(self);
10201
10202 /* let the actor state object handle it */
10203 curState.handleConversation(gActor, gDobj, showConvType);
10204 }
10205 }
10206
10207 /*
10208 * Note that the given object has been explicitly shown to me. By
10209 * default, we'll mark the object and its visible contents as having
10210 * been seen by me. This is called whenever we're the target of a
10211 * SHOW TO or GIVE TO, since presumably such an explicit act of
10212 * calling our attention to an object would make us consider the
10213 * object as having been seen in the future.
10214 */
10215 noteObjectShown(obj)
10216 {
10217 local info;
10218
10219 /* get the table of things we can see */
10220 info = visibleInfoTable();
10221
10222 /* if the object is in the table, mark it as seen */
10223 if (info[obj] != nil)
10224 setHasSeen(obj);
10225
10226 /* also mark the visible contents of the object as having been seen */
10227 obj.setContentsSeenBy(info, self);
10228 }
10229
10230 dobjFor(AskAbout)
10231 {
10232 preCond = [canTalkToObj]
10233 verify()
10234 {
10235 /* it makes no sense to ask oneself about something */
10236 verifyNotSelf(&cannotAskSelfMsg);
10237 }
10238 action()
10239 {
10240 /* note that the issuer is targeting us with conversation */
10241 gActor.noteConversation(self);
10242
10243 /* let our state object handle it */
10244 curState.handleConversation(gActor, gTopic, askAboutConvType);
10245 }
10246 }
10247
10248 dobjFor(TellAbout)
10249 {
10250 preCond = [canTalkToObj]
10251 verify()
10252 {
10253 /* it makes no sense to tell oneself about something */
10254 verifyNotSelf(&cannotTellSelfMsg);
10255 }
10256 check()
10257 {
10258 /*
10259 * If the direct object is the issuing actor, rephrase this
10260 * as "issuer, ask actor about iobj".
10261 *
10262 * Note that we do this in 'check' rather than 'action',
10263 * because this will ensure that we'll rephrase the command
10264 * properly even if the subclass overrides with its own
10265 * check, AS LONG AS the overriding method inherits this base
10266 * definition first. If we did the rephrasing in the
10267 * 'action', then an overriding 'check' might incorrectly
10268 * disqualify the operation on the assumption that it's an
10269 * ordinary TELL ABOUT rather than what it really is, which
10270 * is a rephrased ASK ABOUT.
10271 */
10272 if (gDobj == gIssuingActor)
10273 replaceActorAction(gIssuingActor, AskAbout, gActor, gTopic);
10274
10275 }
10276 action()
10277 {
10278 /* note that the issuer is targeting us with conversation */
10279 gActor.noteConversation(self);
10280
10281 /* let the state object handle it */
10282 curState.handleConversation(gActor, gTopic, tellAboutConvType);
10283 }
10284 }
10285
10286 /*
10287 * Handle a conversational command. All of the conversational
10288 * actions (HELLO, GOODBYE, YES, NO, ASK ABOUT, ASK FOR, TELL ABOUT,
10289 * SHOW TO, GIVE TO) are routed here when we're the target of the
10290 * action (for example, we're BOB in ASK BOB ABOUT TOPIC) AND the
10291 * ActorState doesn't want to handle the action.
10292 */
10293 handleConversation(actor, topic, convType)
10294 {
10295 /* try handling the topic from our topic database */
10296 if (!handleTopic(actor, topic, convType, nil))
10297 {
10298 /* the topic database didn't handle it; use a default response */
10299 defaultConvResponse(actor, topic, convType);
10300 }
10301 }
10302
10303 /*
10304 * Show a default response to a conversational action. By default,
10305 * we'll show the default response for our conversation type.
10306 */
10307 defaultConvResponse(actor, topic, convType)
10308 {
10309 /* call the appropriate default response for the ConvType */
10310 convType.defaultResponse(self, actor, topic);
10311 }
10312
10313 /*
10314 * Show our default greeting message - this is used when the given
10315 * another actor greets us with HELLO or TALK TO, and we don't
10316 * otherwise handle it (such as via a topic database entry).
10317 *
10318 * By default, we'll just show "there's no response" as a default
10319 * message. We'll show this in default mode, so that if the caller
10320 * is going to show a list of suggested conversation topics (which
10321 * the 'hello' and 'talk to' commands will normally try to do), the
10322 * topic list will override the "there's no response" default. In
10323 * other words, we'll have one of these two types of exchanges:
10324 *
10325 *. >talk to bob
10326 *. There's no response
10327 *
10328 *. >talk to bill
10329 *. You could ask him about the candle, the book, or the bell, or
10330 *. tell him about the crypt.
10331 */
10332 defaultGreetingResponse(actor)
10333 { defaultReport(&noResponseFromMsg, self); }
10334
10335 /* show our default goodbye message */
10336 defaultGoodbyeResponse(actor)
10337 { mainReport(&noResponseFromMsg, self); }
10338
10339 /*
10340 * Show the default answer to a question - this is called when we're
10341 * the actor in ASK <actor> ABOUT <topic>, and we can't find a more
10342 * specific response for the given topic.
10343 *
10344 * By default, we'll show the basic "there's no response" message.
10345 * This isn't a very good message in most cases, because it makes an
10346 * actor pretty frustratingly un-interactive, which gives the actor
10347 * the appearance of a cardboard cut-out. But there's not much
10348 * better that the library can do; the potential range of actors
10349 * makes a more specific default response impossible. If the default
10350 * response were "I don't know about that," it wouldn't work very
10351 * well if the actor is someone who only speaks Italian. So, the
10352 * best we can do is this generally rather poor default. But that
10353 * doesn't mean that authors should resign themselves to a poor
10354 * default answer; instead, it means that actors should take care to
10355 * override this when defining an actor, because it's usually
10356 * possible to find a much better default for a *specific* actor.
10357 *
10358 * The *usual* way of providing a default response is to define a
10359 * DefaultAskTopic (or a DefaultAskTellTopic) and put it in the
10360 * actor's topic database.
10361 */
10362 defaultAskResponse(fromActor, topic)
10363 { mainReport(&noResponseFromMsg, self); }
10364
10365 /*
10366 * Show the default response to being told of a topic - this is
10367 * called when we're the actor in TELL <actor> ABOUT <topic>, and we
10368 * can't find a more specific response for the topic.
10369 *
10370 * As with defaultAskResponse, this should almost always be
10371 * overridden by each actor, since the default response ("there's no
10372 * response") doesn't make the actor seem very dynamic.
10373 *
10374 * The usual way of providing a default response is to define a
10375 * DefaultTellTopic (or a DefaultAskTellTopic) and put it in the
10376 * actor's topic database.
10377 */
10378 defaultTellResponse(fromActor, topic)
10379 { mainReport(&noResponseFromMsg, self); }
10380
10381 /* the default response for SHOW TO */
10382 defaultShowResponse(byActor, topic)
10383 { mainReport(&notInterestedMsg, self); }
10384
10385 /* the default response for GIVE TO */
10386 defaultGiveResponse(byActor, topic)
10387 { mainReport(&notInterestedMsg, self); }
10388
10389 /* the default response for ASK FOR */
10390 defaultAskForResponse(byActor, obj)
10391 { mainReport(&noResponseFromMsg, self); }
10392
10393 /* default response to being told YES */
10394 defaultYesResponse(fromActor)
10395 { mainReport(&noResponseFromMsg, self); }
10396
10397 /* default response to being told NO */
10398 defaultNoResponse(fromActor)
10399 { mainReport(&noResponseFromMsg, self); }
10400
10401 /* default refusal of a command */
10402 defaultCommandResponse(fromActor, topic)
10403 { mainReport(&refuseCommand, self, fromActor); }
10404 ;
10405
10406 /* ------------------------------------------------------------------------ */
10407 /*
10408 * An UntakeableActor is one that can't be picked up and moved.
10409 */
10410 class UntakeableActor: Actor, Immovable
10411 /* use customized messages for some 'Immovable' methods */
10412 cannotTakeMsg = &cannotTakeActorMsg
10413 cannotMoveMsg = &cannotMoveActorMsg
10414 cannotPutMsg = &cannotPutActorMsg
10415
10416 /* TASTE tends to be a bit rude */
10417 dobjFor(Taste)
10418 {
10419 action() { mainReport(&cannotTasteActorMsg); }
10420 }
10421
10422 /*
10423 * even though we act like an Immovable, we don't count as an
10424 * Immovable for listing purposes
10425 */
10426 contentsInFixedIn(loc) { return nil; }
10427 ;
10428
10429
10430 /*
10431 * A Person is an actor that represents a human character. This is just
10432 * an UntakeableActor with some custom versions of the messages for
10433 * taking and moving the actor.
10434 */
10435 class Person: UntakeableActor
10436 /* customize the messages for trying to take or move me */
10437 cannotTakeMsg = &cannotTakePersonMsg
10438 cannotMoveMsg = &cannotMovePersonMsg
10439 cannotPutMsg = &cannotPutPersonMsg
10440 cannotTasteActorMsg = &cannotTastePersonMsg
10441
10442 /*
10443 * use a fairly large default bulk, since people are usually fairly
10444 * large compared with the sorts of items that one carries around
10445 */
10446 bulk = 10
10447 ;
10448
10449 /* ------------------------------------------------------------------------ */
10450 /*
10451 * Pending response information structure
10452 */
10453 class PendingResponseInfo: object
10454 construct(issuer, prop, args)
10455 {
10456 issuer_ = issuer;
10457 prop_ = prop;
10458 args_ = args;
10459 }
10460
10461 /* the issuer of the command (and target of the response) */
10462 issuer_ = nil
10463
10464 /* the message property and argument list for the message */
10465 prop_ = nil
10466 args_ = []
10467 ;
10468
10469 /*
10470 * Pending Command Information structure. This is an abstract base class
10471 * that we subclass for particular ways of representing the command to be
10472 * executed.
10473 */
10474 class PendingCommandInfo: object
10475 construct(issuer) { issuer_ = issuer; }
10476
10477 /*
10478 * Check to see if this pending command item has a command to
10479 * perform. This returns true if we have a command, nil if we're
10480 * just a queue placeholder without any actual command to execute.
10481 */
10482 hasCommand = true
10483
10484 /* execute the command */
10485 executePending(targetActor) { }
10486
10487 /* the issuer of the command */
10488 issuer_ = nil
10489
10490 /* we're at the start of a "sentence" */
10491 startOfSentence_ = nil
10492 ;
10493
10494 /* a pending command based on a list of tokens from an input string */
10495 class PendingCommandToks: PendingCommandInfo
10496 construct(startOfSentence, issuer, toks)
10497 {
10498 inherited(issuer);
10499
10500 startOfSentence_ = startOfSentence;
10501 tokens_ = toks;
10502 }
10503
10504 /*
10505 * Execute the command. We'll parse our tokens and execute the
10506 * parsed results.
10507 */
10508 executePending(targetActor)
10509 {
10510 /* parse and execute the tokens */
10511 executeCommand(targetActor, issuer_, tokens_, startOfSentence_);
10512 }
10513
10514 /* the token list for the command */
10515 tokens_ = nil
10516 ;
10517
10518 /* a pending command based on a pre-resolved Action and its objects */
10519 class PendingCommandAction: PendingCommandInfo
10520 construct(startOfSentence, issuer, action, [objs])
10521 {
10522 inherited(issuer);
10523
10524 startOfSentence_ = startOfSentence;
10525 action_ = action;
10526 objs_ = objs;
10527 }
10528
10529 /* execute the pending command */
10530 executePending(targetActor)
10531 {
10532 /* invoke the action's main execution method */
10533 try
10534 {
10535 /* run the action */
10536 newActionObj(CommandTranscript, issuer_,
10537 targetActor, action_, objs_...);
10538 }
10539 catch (TerminateCommandException tcExc)
10540 {
10541 /*
10542 * the command cannot proceed; simply abandon the command
10543 * action here
10544 */
10545 }
10546 }
10547
10548 /* the resolved Action to perform */
10549 action_ = nil
10550
10551 /* the resolved objects for the action */
10552 objs_ = nil
10553 ;
10554
10555 /*
10556 * A pending command marker. This is not an actual pending command;
10557 * rather, it's just a queue marker. We sometimes want to synchronize
10558 * some other activity with an actor's progress through its command
10559 * queue; for example, we might want one actor to wait until another
10560 * actor has executed a particular pending action. These markers can be
10561 * used for this kind of synchronization; they move through the queue
10562 * like ordinary pending commands, so we can tell if an actor has reached
10563 * a particular command by observing the marker's progress through the
10564 * queue.
10565 */
10566 class PendingCommandMarker: PendingCommandInfo
10567 /* I have no command to execute */
10568 hasCommand = nil
10569 ;
10570
10571 /* ------------------------------------------------------------------------ */
10572 /*
10573 * Set the current player character
10574 */
10575 setPlayer(actor)
10576 {
10577 /* remember the new player character */
10578 libGlobal.playerChar = actor;
10579
10580 /* set the root global point of view to this actor */
10581 setRootPOV(actor, actor);
10582 }
10583