kpsewhich now expects "-var-value" instead of "-var".
[ibg.git] / chapters / 07.rst
1 ===============================
2  William Tell: the early years
3 ===============================
4
5 .. highlight:: inform
6
7 .. epigraph::
8
9    | |CENTER| *M was a miser, and hoarded up gold;*
10    | |CENTER| *N was a nobleman, gallant and bold.*
11
12 .. only:: html
13
14    .. image:: /images/picM.png
15       :align: left
16
17 |M|\oving along swiftly, we'll define the first two rooms and populate them
18 with assorted townspeople and street furniture, we'll equip Wilhelm with
19 his trusty bow and quiver of arrows, and we'll introduce Helga the friendly
20 stallholder.
21
22 Defining the street
23 ===================
24
25 This is the street room, the location where the game starts:
26
27 .. include:: /config/typethis.rst
28
29 ::
30
31    Room     street "A street in Altdorf"
32      with   description [;
33                  print "The narrow street runs north towards the town square.
34                      Local folk are pouring into the town through the gate to the
35                      south, shouting greetings, offering produce for sale,
36                      exchanging news, enquiring with exaggerated disbelief about
37                      the prices of the goods displayed by merchants whose stalls
38                      make progress even more difficult.^";
39                  if (self hasnt visited)
40                      print "^~Stay close to me, son,~ you say,
41                          ~or you'll get lost among all these people.~^";
42             ],
43             n_to below_square,
44             s_to
45                  "The crowd, pressing north towards the square,
46                   makes that impossible.";
47
48 We're using our new ``Room`` class, so there's no need for a :attr:`light`
49 attribute.  The :prop:`n_to` and :prop:`s_to` properties, whose values are
50 an internal ID and a string respectively, are techniques we've used before.
51 The only innovation is that the :prop:`description` property has an
52 embedded routine as its value.
53
54 The first thing in that routine is a ``print`` statement, displaying
55 details of the street surroundings.  If that was all that we wanted to do,
56 we could have supplied those details by making the :prop:`description`
57 value a string; that is, these two examples behave identically::
58
59    description [;
60        print "The narrow street runs north towards the town square.
61            Local folk are pouring into the town through the gate to the
62            south, shouting greetings, offering produce for sale,
63            exchanging news, enquiring with exaggerated disbelief about
64            the prices of the goods displayed by merchants whose stalls
65            make progress even more difficult.^";
66    ],
67
68    description
69        "The narrow street runs north towards the town square.
70         Local folk are pouring into the town through the gate to the
71         south, shouting greetings, offering produce for sale,
72         exchanging news, enquiring with exaggerated disbelief about
73         the prices of the goods displayed by merchants whose stalls
74         make progress even more difficult.",
75
76 However, that *isn't* all that we want to do.  Having presented the basic
77 description, we're going to display that little line of dialogue, where
78 Wilhelm tells his son to be careful.  And we want to do that only once, the
79 very first time that the street's description is displayed.  If the player
80 types LOOK a few times, or moves north and then returns south to the
81 street, we're happy to see the surroundings described -- but we don't want
82 that dialogue again.  This is the pair of statements that makes it happen::
83
84    if (self hasnt visited)
85        print "^~Stay close to me, son,~ you say,
86            ~or you'll get lost among all these people.~^";
87
88 The line of dialogue is produced by the ``print`` statement, the ``print``
89 statement is controlled by the ``if`` statement, and the ``if`` statement
90 is performing the test ``self hasnt visited``.  In detail:
91
92 .. Generated by autoindex
93 .. index::
94    pair: visited; library attribute
95
96 * :attr:`visited` is an attribute, but not one that you'd normally give to an
97   object yourself.  It's automatically applied to a room object by the
98   interpreter, but only after that room has been visited for the first
99   time by the player.
100
101 * ``hasnt`` (and ``has``) are available for testing whether a given
102   attribute is currently set for a given object.  :samp:`{X} has {Y}` is
103   true if object :samp:`{X}` currently has attribute :samp:`{Y}`, false if
104   it doesn't.  To make the test in reverse, :samp:`{X} hasnt {Y}` is true
105   if object :samp:`{X}` currently does not have attribute :samp:`{Y}`,
106   false if it does.
107
108 .. Generated by autoindex
109 .. index::
110    pair: self; library variable
111
112 * :var:`self`, which we met in the previous chapter, is that useful variable
113   which, within an object, always refers to that object.  Since we're using
114   it in the middle of the ``street`` object, that's what it refers to.
115
116 So, putting it all together, ``self hasnt visited`` is true (and therefore
117 the ``print`` statement is executed) only while the ``street`` object has
118 *not* got a :attr:`visited` attribute.  Because the interpreter
119 automatically gives rooms a :attr:`visited` attribute as soon as the player
120 has been there once, this test will be true only for one turn.  Therefore,
121 the line of dialogue will be displayed only once: the first time the player
122 visits the street, at the very start of the game.
123
124 Although the primary importance of :var:`self` is within class definitions,
125 it can also be convenient to use it simply within an object.  Why didn't we
126 just write this? ::
127
128    if (street hasnt visited)
129        print "^~Stay close to me, son,~ you say,
130            ~or you'll get lost among all these people.~^";
131
132 It's true that the effect is identical, but there are a couple of good
133 reasons for using :var:`self`.  One: it's an aid to understanding your code
134 days or weeks after writing it.
135
136 If you read the line ``if (street hasnt visited)``, you need to think for a
137 moment about which object is being tested; oh, it's this one.  When you
138 read ``if (self hasnt visited)``, you immediately *know* which object we're
139 talking about.
140
141 Another reason is auto-plagiarism.  Many times you'll find that a chunk of
142 code is useful in different situations (say, you want to repeat the
143 mechanics of the street description in another room).  Rather than writing
144 everything from scratch, you'll typically use copy-and-paste to repeat the
145 routine, and then all you have to do is compose the appropriate descriptive
146 strings for the new room.  If you've used :var:`self`, the line ``if (self
147 hasnt visited)`` is still good; if you've written instead ``if (street
148 hasnt visited)``, you'll have to change that as well.  Worse, if you
149 *forget* to change it, the game will still work -- but not in the way you'd
150 intended, and the resulting bug will be quite difficult to track down.
151
152 .. _adding-props:
153
154 Adding some props
155 =================
156
157 The street's description mentions various items -- the gate, the people,
158 etc. -- which ought to exist within the game (albeit only in minimal form)
159 to sustain the illusion of hustle and bustle.  Our ``Prop`` class is ideal
160 for this:
161
162 .. include:: /config/typethis.rst
163
164 ::
165
166    Prop     "south gate" street
167      with   name 'south' 'southern' 'wooden' 'gate',
168             description "The large wooden gate in the town walls is wide open.";
169
170    Prop     "assorted stalls"
171      with   name 'assorted' 'stalls',
172             description "Food, clothing, mountain gear; the usual stuff.",
173             found_in street below_square,
174      has    pluralname;
175
176    Prop     "produce"
177      with   name 'goods' 'produce' 'food' 'clothing' 'mountain' 'gear' 'stuff',
178             description "Nothing special catches your eye.",
179             found_in street below_square,
180      has    pluralname;
181
182    Prop     "merchants"
183      with   name 'merchant' 'merchants' 'trader' 'traders',
184             description
185                 "A few crooks, but mostly decent traders touting their wares
186                  with raucous overstatement.",
187             found_in street below_square,
188      has    animate pluralname;
189
190    Prop     "local people"
191      with   name 'people' 'folk' 'local' 'crowd',
192             description "Mountain folk, just like yourself.",
193             found_in [; return true; ],
194      has    animate pluralname;
195
196 .. note:: 
197
198    Because these objects are not referenced by other objects, we haven't
199    bothered to given them internal :samp:`{obj_ids}` (though we could have;
200    it wouldn't make any difference).  However, we *have* provided
201    :samp:`{external_names}`, because these are used by the ``Prop`` class's
202    ``print_ret ... (the) self`` statement.
203
204 .. Generated by autoindex
205 .. index::
206    pair: pluralname; library attribute
207
208 You'll see a couple of new attributes: :attr:`animate` marks an object as
209 being "alive", while :attr:`pluralname` specifies that its external name is
210 plural rather than singular.  The interpreter uses these attributes to
211 ensure that messages about such objects are grammatical and appropriate
212 (for example, it will now refer to "some merchants" rather than "a
213 merchants").  Because the library handles so many situations automatically,
214 it's hard to be sure exactly what messages players may trigger; the best
215 approach is to play safe and always give an object the relevant set of
216 attributes, even when, as here, they probably won't be needed.
217
218 .. Generated by autoindex
219 .. index::
220    pair: found_in; library property
221
222 You'll also see a new :prop:`found_in` property, which specifies the rooms
223 -- and only the rooms; :prop:`found_in` shouldn't be used to place objects
224 inside containers or supporters -- where this object is to appear.  The
225 stalls, for example, can be EXAMINEd both in the street and below the
226 square, so we *could* have created a ``Prop`` object in each room::
227
228    Prop       "assorted stalls" street
229      with     name 'assorted' 'stalls',
230               description "Food, clothing, mountain gear; the usual stuff.",
231       has     pluralname;
232
233    Prop       "assorted stalls" below_square
234      with     name 'assorted' 'stalls',
235               description "Food, clothing, mountain gear; the usual stuff.",
236       has     pluralname;
237
238 but :prop:`found_in` does the same job more neatly -- there's only one
239 object, but it appears in both the ``street`` and ``below_square`` rooms
240 while the player's there.  The local people are even more ubiquitous.  In
241 this case the :prop:`found_in` value is an embedded routine rather than a
242 list of rooms; such a routine would generally test the value of the current
243 location and ``return true`` if it wants to be present here, or
244 :const:`false` if not.  Since we'd like the local people *always* to be
245 present, in every room, we ``return true`` without bothering to examine
246 :var:`location`.  It's as though we'd written any of these, but simpler and
247 less error prone::
248
249    Prop       "local people"
250      with     name 'people' 'folk' 'local' 'crowd',
251               description "Mountain folk, just like yourself.",
252               found_in street below_square south_square mid_square north_square
253                   marketplace,
254       has     animate pluralname;
255
256    Prop       "local people"
257      with     name 'people' 'folk' 'local' 'crowd',
258               description "Mountain folk, just like yourself.",
259               found_in [;
260                   if (location == street       || location == below_square ||
261                       location == south_square || location == mid_square ||
262                       location == north_square || location == marketplace)
263                       return true;
264                   return false;
265               ],
266       has     animate pluralname;
267
268    Prop     "local people"
269      with   name 'people' 'folk' 'local' 'crowd',
270             description "Mountain folk, just like yourself.",
271             found_in [;
272                 if (location == street or below_square or south_square or
273                     mid_square or north_square or marketplace) return true;
274                 return false;
275             ],
276      has    animate pluralname;
277
278 In the second example, you'll see the ``||`` operator, to be read as "or",
279 which we mentioned near the end of "Heidi"; it combines the various
280 :samp:`location == {some_room}` comparisons so that the ``if`` statement is
281 true if *any* of those individual tests is true.  And in the third example
282 we introduce the ``or`` keyword, which is a more succinct way of achieving
283 exactly the same result.
284
285 .. _possessions:
286
287 The player's possessions
288 ========================
289
290 Since our ``Initialise`` routine has already mentioned them, we might as
291 well define Wilhelm's bow and arrows:
292
293 .. include:: /config/typethis.rst
294
295 ::
296
297    Object   bow "bow"
298      with   name 'bow',
299             description "Your trusty yew bow, strung with flax.",
300             before [;
301                Drop,Give,ThrowAt:
302                  print_ret "You're never without your trusty bow.";
303             ],
304      has    clothing;
305
306    Object   quiver "quiver"
307      with   name 'quiver',
308             description
309                  "Made of goatskin, it usually hangs over your left shoulder.",
310             before [;
311                Drop,Give,ThrowAt:
312                  print_ret "But it was a present from Hedwig, your wife.";
313             ],
314      has    container open clothing;
315
316 Both of these are straightforward objects, with the :act:`Drop`,
317 :act:`Give` and :act:`ThrowAt` actions being intercepted to ensure that
318 Wilhelm is never without them.  The :attr:`clothing` attribute makes its
319 first appearance, marking both the quiver and the bow as capable of being
320 worn (as the result of a WEAR BOW command, for instance); you'll remember
321 that our ``Initialise`` routine goes on to add a :attr:`worn` attribute to
322 the quiver.
323
324 An empty quiver is pretty useless, so here's the class used to define
325 Wilhelm's stock of arrows.  This class has some unusual features:
326
327 .. include:: /config/typethis.rst
328
329 ::
330
331    Class    Arrow
332      with   name 'arrow' 'arrows//p',
333             article "an",
334             plural "arrows",
335             description "Just like all your other arrows -- sharp and true.",
336             before [;
337                Drop,Give,ThrowAt:
338                  print_ret "Your arrows are sharp, and you guard them carefully.";
339             ];
340
341 The classes we've created so far -- ``Room``, ``Prop`` and ``Furniture`` --
342 are intended for objects which behave the same but are otherwise clearly
343 separate.  For example, a table, a bed and a wardrobe would generally have
344 their own individual characteristics -- a name, a description, maybe some
345 specialised properties -- while still inheriting the general behaviour of
346 ``Furniture`` objects.  The arrows aren't like this: not only do they
347 behave the same, but also they are indistinguishable one from another.
348 We're trying for this effect:
349
350 .. code-block:: transcript
351
352    >INVENTORY
353    You are carrying:
354      a quiver (being worn)
355        three arrows
356      a bow
357
358 where the interpreter lumps together our stock of three arrows, rather than
359 listing them individually in this clumsy fashion:
360
361 .. code-block:: transcript
362
363    >INVENTORY
364    You are carrying:
365      a quiver (being worn)
366        an arrow
367        an arrow
368        an arrow
369      a bow
370
371 The interpreter will do this for us if our objects are "indistinguishable",
372 best achieved by making them members of a class which includes both
373 :prop:`name` and :prop:`plural` properties.  We define the actual arrows
374 very simply, like this:
375
376 .. include:: /config/typethis.rst
377
378 ::
379
380    Arrow "arrow" quiver;
381    Arrow "arrow" quiver;
382    Arrow "arrow" quiver;
383
384 and you can see that we provide only two pieces of information for each
385 ``Arrow`` object: an external name in double quotes ("arrow" in each case)
386 which the interpreter uses when referring to the object, and an initial
387 location (in the quiver).  That's all: no block of properties, no set of
388 attributes, and no internal identifier, because we never need to refer to
389 the individual ``Arrow`` objects within the game.
390
391 The name property of the class definition has an odd-looking dictionary
392 word::
393
394    name 'arrow' 'arrows//p',
395
396 The word ``'arrow'`` refers to a single arrow.  So also would the word
397 ``'arrows'``, unless we specifically tell the interpreter that it's a
398 plural reference.  That ``//p`` marks ``'arrows'`` as being a potential
399 reference to more than one object at once, thus enabling players to type
400 TAKE ARROWS and thereby pick up as many arrows as happened to be available
401 (without it, TAKE ARROWS would have picked up one at random).
402
403 There are two other properties not seen previously::
404
405    article "an",
406    plural "arrows",
407
408 The :prop:`article` property lets you define the object's indefinite
409 article -- usually something like "a", "an" or "some" -- instead of letting
410 the library assign one automatically.  It's a belt-and-braces (OK,
411 belt-and-suspenders) precaution: because "arrow" starts with a vowel, we
412 need to display "an arrow" not "a arrow".  Most interpreters automatically
413 get this right, but just to be on the safe side, we explicitly define the
414 appropriate word.  And the :prop:`plural` property defines the word to be
415 used when lumping several of these objects together, as in the "three
416 arrows" inventory listing.  The interpreter can't just automatically slap
417 an "s" on the end; the plural of "slice of cake", for example, isn't "slice
418 of cakes".
419
420 Moving further along the street
421 ===============================
422
423 As Wilhelm moves north towards the square, he comes to this room:
424
425 .. include:: /config/typethis.rst
426
427 ::
428
429    Room     below_square "Further along the street"
430      with   description
431                 "People are still pushing and shoving their way from the southern
432                  gate towards the town square, just a little further north.
433                  You recognise the owner of a fruit and vegetable stall.",
434             n_to south_square,
435             s_to street;
436
437 No surprises there, nor in most of the supporting scenery objects.
438
439 .. include:: /config/typethis.rst
440
441 ::
442
443    Furniture   stall "fruit and vegetable stall" below_square
444      with name 'fruit' 'veg' 'vegetable' 'stall' 'table',
445            description
446                "It's really only a small table, with a big heap of potatoes,
447                 some carrots and turnips, and a few apples.",
448            before [; Search: <<Examine self>>; ],
449      has   scenery;
450
451    Prop     "potatoes" below_square
452      with   name 'potato' 'potatoes' 'spuds',
453             description
454                 "Must be a particularly early variety... by some 300 years!",
455      has    pluralname;
456
457    Prop     "fruit and vegetables" below_square
458      with   name 'carrot' 'carrots' 'turnip' 'turnips' 'apples' 'vegetables',
459             description "Fine locally grown produce.",
460      has    pluralname;
461
462 .. Generated by autoindex
463 .. index::
464    pair: before; library property
465
466 The only new thing here is the :prop:`before` property of the fruit'n'veg
467 stall.  The stall's description -- lots of items on a table -- may suggest
468 to players that they can SEARCH through the produce, maybe finding a lucky
469 beetroot or something else interesting.  No such luck -- and we might as
470 well trap the attempt.
471
472 .. Generated by autoindex
473 .. index::
474    pair: Examine; library action
475    pair: Search; library action
476
477 Having intercepted a :act:`Search` action, our plan is to respond with the
478 stall's description, as though the player has typed EXAMINE THE STALL.
479 There isn't an easy way for us to stealthily slide those literal words into
480 the interpreter, but we *can* simulate the effect which they'd cause: an
481 action of :act:`Examine` applied to the object stall.  This rather cryptic
482 statement does the job::
483
484    <Examine stall>;
485
486 Having diverted the :act:`Search` action into an :act:`Examine` action, we
487 must tell the interpreter that it doesn't need to do anything else, because
488 we've handled the action ourselves.  We've done that before -- using
489 ``return true`` -- and so a first stab at the :prop:`before` action looks
490 like this::
491
492    before [; Search: <Examine stall>; return true; ],
493
494 .. Generated by autoindex
495 .. index::
496    pair: self; library variable
497
498 The two-statement sequence ``<...>; return true`` is so common that there's
499 a single statement shortcut: ``<<...>>``.  Also, for exactly the same
500 reason as before, our code is clearer if we use :var:`self` instead of
501 ``stall``.  So this is how the property finally stands::
502
503    before [; Search: <<Examine self>>; ],
504
505 A couple of final observations before we leave this topic.  The example
506 here is of an action (:act:`Examine`) applied to an object (:var:`self`,
507 though ``stall`` or :var:`noun` would also work at this point).  You can
508 also use the ``<...>`` and ``<<...>>`` statements for actions which affect
509 no objects::
510
511    <<Look>>;
512
513 (representing the command LOOK), or which affect two.  For example, the
514 command PUT THE BIRD IN THE NEST can be simulated with this statement::
515
516    <<Insert bird nest>>;
517
518 Introducing Helga
519 =================
520
521 .. Generated by autoindex
522 .. index::
523    single: NPC
524
525 One of the trickiest aspects of designing a good game is to provide
526 satisfying interaction with other characters.  It's hard enough to code
527 inanimate objects which provoke appropriate responses to whatever actions
528 the player character (PC) might attempt.  That all gets much worse once
529 those "other objects" are living creatures -- non-player characters (NPCs)
530 -- with, supposedly, minds of their own.  A good NPC might move around
531 independently, perform actions with a purpose, initiate conversations,
532 respond to what you say and do (and even to what you *don't* say or do); it
533 can be a real nightmare.
534
535 But not here: we've kept our three NPCs -- Helga, Walter and the vogt -- as
536 simple as possible.  Nevertheless, we can establish some fundamental
537 principles; here's the class upon which we base our NPCs:
538
539 .. include:: /config/typethis.rst
540
541 ::
542
543    Class    NPC
544      with   life [;
545                Answer,Ask,Order,Tell:
546                  print_ret "Just use T[ALK] [TO ", (the) self, "].";
547             ],
548      has    animate;
549
550 The most important thing here is the :attr:`animate` attribute -- that's
551 what defines an object as an NPC, and causes the interpreter to treat it a
552 little differently -- for example, TAKE HELGA results in "I don't suppose
553 Helga would care for that".
554
555 .. Generated by autoindex
556 .. index::
557    pair: Ask; library action
558    pair: Attack; library action
559    pair: Kiss; library action
560    pair: Order; library action
561    pair: Show; library action
562    pair: Tell; library action
563    pair: ThrowAt; library action
564    pair: WakeOther; library action
565    pair: life; library property
566
567 The :attr:`animate` attribute also brings into play nine extra actions
568 which can be applied only to animate objects: :act:`Answer`, :act:`Ask`,
569 :act:`Order` and :act:`Tell` are all associated with speech, and
570 :act:`Attack`, :act:`Kiss`, :act:`Show`, :act:`ThrowAt` and
571 :act:`WakeOther` are associated with non-verbal interaction.  Additionally,
572 a new :prop:`life` property -- very similar to :prop:`before` -- can be
573 defined to intercept them.  Here we use it to trap speech-related commands
574 such as ASK HELGA ABOUT APPLE and TELL WALTER ABOUT BABIES, telling players
575 that in this game we've implemented only a simpler TALK verb (which we
576 describe in :ref:`verbs`).
577
578 Based on the NPC class we've created, here's Helga:
579
580 .. include:: /config/typethis.rst
581
582 ::
583
584    NPC      stallholder "Helga" below_square
585      with   name 'stallholder' 'greengrocer' 'monger' 'shopkeeper' 'merchant'
586                  'owner' 'Helga' 'dress' 'scarf' 'headscarf',
587             description
588                  "Helga is a plump, cheerful woman,
589                    concealed beneath a shapeless dress and a spotted headscarf.",
590             initial [;
591                  print "Helga pauses from sorting potatoes
592                       to give you a cheery wave.^";
593                  if (location hasnt visited) {
594                       move apple to player;
595                       print "^~Hello, Wilhelm, it's a fine day for trade! Is this
596                           young Walter? My, how he's grown. Here's an apple for him
597                           -- tell him to mind that scabby part, but the rest's good
598                           enough. How's Frau Tell? Give her my best wishes.~^";
599                  }
600             ],
601             times_spoken_to 0,         ! for counting the conversation topics
602             life [;
603                Talk:
604                  self.times_spoken_to = self.times_spoken_to + 1;
605                  switch (self.times_spoken_to) {
606                    1: score = score + 1;
607                       print_ret "You warmly thank Helga for the apple.";
608                    2: print_ret "~See you again soon.~";
609                    default:
610                       return false;
611                  }
612             ],
613      has    female proper;
614
615 The new attributes are :attr:`female` -- because we want the interpreter to
616 refer to Helga with the appropriate pronouns -- and :attr:`proper`.  The
617 latter signifies that this object's external name is a proper noun, and so
618 references to it should not be preceded by "a" or "the": you wouldn't want
619 to display "You can see a Helga here" or "I don't suppose the Helga would
620 care for that".  You may notice the library variable :var:`score` being
621 incremented.  This variable holds the number of points that the player has
622 scored; when it changes like this, the interpreter tells the player that
623 "Your score has just gone up by one point".
624
625 .. Generated by autoindex
626 .. index::
627    pair: initial; library property
628    pair: times_spoken_to; library property
629
630 There are also :prop:`life` and :prop:`times_spoken_to` properties (which
631 we'll talk about in :doc:`09`) and an :prop:`initial` property.
632
633 :prop:`initial` is used when the interpreter is describing a room and listing
634 the objects initial you can see there.  If we *didn't* define it, you'd get
635 this:
636
637 .. code-block:: transcript
638
639    Further along the street
640    People are still pushing and shoving their way from the southern gate towards
641    the town square, just a little further north.  You recognise the owner of a fruit
642    and vegetable stall.
643
644    You can see Helga here.
645
646    >
647
648 but we want to introduce Helga in a more interactive manner, and that's
649 what the :prop:`initial` property is for: it replaces the standard "You can see
650 *object* here" with a tailored message of your own design.  The value of an
651 :prop:`initial` property can be either a string which is to be displayed or, as
652 here, an embedded routine.  This one is pretty similar to the
653 :prop:`description` property that we defined for the street: something that's
654 *always* printed (Helga pauses...) and something that's printed only on the
655 first occasion ("Hello, Wilhelm, it's a fine day... "):
656
657 .. code-block:: transcript
658
659    Further along the street
660    People are still pushing and shoving their way from the southern gate towards
661    the town square, just a little further north. You recognise the owner of a fruit
662    and vegetable stall.
663
664    Helga pauses from sorting potatoes to give you a cheery wave.
665
666    "Hello, Wilhelm, it's a fine day for trade! Is this young Walter? My, how he's
667    grown. Here's an apple for him -- tell him to mind that scabby part, but the
668    rest's good enough. How's Frau Tell? Give her my best wishes."
669
670    >
671
672 But it's not quite the same as the street's description routine.  First, we
673 need a slightly different ``if`` test: ``self hasnt visited`` works fine
674 for a room object, but this routine is part of an object *in* a room;
675 instead we could use either ``below_square hasnt visited`` or (better)
676 ``location hasnt visited`` -- since :var:`location` is the library variable
677 that refers to the room where the player currently is.  And second, some
678 curly braces ``{...}`` have appeared: why?
679
680 On Wilhelm's first visit to this room, we need to do two things:
681
682 * ensure that Wilhelm is in possession of an apple, because that's
683   mentioned when we...
684
685 * display Helga's cheery greeting.
686
687 The ``move`` statement does the first of those, and the ``print`` statement
688 does the second.  And both statements need to be controlled by the ``if``
689 statement.  So far, we've used an ``if`` statement twice, in both cases to
690 control a single following statement. ::
691
692   if (nest in branch) deadflag = 2;
693
694   if (self hasnt visited)
695       print "^~Stay close to me, son,~ you say,
696           ~or you'll get lost among all these people.~^";
697
698 That's what an ``if`` does -- it controls whether the following statement
699 is executed or not.  So how can we control two statements at once?  Well,
700 we *could* write two ``if`` statements::
701
702   if (location hasnt visited)
703       move apple to player;
704   if (location hasnt visited)
705       print "^~Hello, Wilhelm, it's a fine day for trade! Is this
706           young Walter? My, how he's grown. Here's an apple for him
707           -- tell him to mind that scabby part, but the rest's good
708           enough. How's Frau Tell? Give her my best wishes.~^";
709
710 but that's unbearably clumsy; instead, we use the braces to group the
711 ``move`` and ``print`` statement into a :term:`statement block` (sometimes
712 known as a code block) which counts as a single statement for the purposes
713 of control by the ``if`` statement. ::
714
715   if (location hasnt visited) {
716       move apple to player;
717       print "^~Hello, Wilhelm, it's a fine day for trade! Is this
718           young Walter? My, how he's grown. Here's an apple for him
719           -- tell him to mind that scabby part, but the rest's good
720           enough. How's Frau Tell? Give her my best wishes.~^";
721   }
722
723 A statement block can contain one, two, ten, a hundred statements; it
724 doesn't matter -- they're all treated as one unit by ``if`` (and by
725 ``objectloop``, which we meet later, and by ``do``, ``for`` and ``while``,
726 all of them loop statements that we don't encounter in this guide).
727
728 .. note::
729
730    The exact positioning of the braces is a matter of personal choice.  We
731    use this style::
732
733       if (condition) {
734           statement;
735           statement;
736           ...
737       }
738
739    but other designers have their own preferences, including::
740
741       if (condition) {
742           statement;
743           statement;
744           ...
745           }
746
747       if (condition)
748       {   statement;
749           statement;
750           ...
751       }
752
753       if (condition)
754           {
755           statement;
756           statement;
757           ...
758           }
759
760 Although we've not yet needed to use it, now would probably be a good time
761 to mention the ``else`` extension to the ``if`` statement.  Sometimes we
762 want to execute one statement block if a certain condition is true, and a
763 different statement block if it's not true.  Again, we *could* write two
764 ``if`` statements::
765
766    if (location has visited) {
767        statement;
768        statement;
769        ...
770    }
771    if (location hasnt visited) {
772        statement;
773        statement;
774        ...
775    };
776
777 but that's hardly an elegant approach; an ``else`` clause does the job more
778 neatly::
779
780    if (location has visited) {
781        statement;
782        statement;
783        ...
784    }
785    else {
786        statement;
787        statement;
788        ...
789    };
790
791 We've done a lot of scene-setting, but the real action is still to come.
792 Next, it's time to define the town square, and create a confrontation
793 between Wilhelm and the vogt's soldiers.  (But first, see again
794 :ref:`compile-as-you-go` if you're typing in the game as you read through
795 the guide.)