lpc1

150
LPC For Dummies Book One Beta Draft Michael Heron ([email protected])

Transcript of lpc1

Page 1: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 1/150

LPC For DummiesBook One

Beta Draft

Michael Heron([email protected])

Page 2: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 2/150

LPC For Dummies 1, Second Edition

Table of Contents

Mojo The Monkey Says.......................................................................................................................5

Willkommen! Bien Venue! Welcome! ...............................................................................................6

Introduction .....................................................................................................................................6The Learning Scenario.....................................................................................................................6

The Structure o the ame .............................................................................................................."

#rogramming as a $once%t .............................................................................................................&

It's (ll )o*n To +ou....................................................................................................................,,

$onclusion.....................................................................................................................................,-

My irst /oom...................................................................................................................................,0

Introduction ...................................................................................................................................,0

+our 1*n Learn2ille.....................................................................................................................,0

The Basic Tem%late.......................................................................................................................,3

 4o* *hat does all o that mean .................................................................................................,5

My /oom Sucks.............................................................................................................................,6

It's a little too 7uiet........................................................................................................................,"

( Second /oom ............................................................................................................................,&

1ur 12erall #lan ...........................................................................................................................,8

#ro%erty Ladder ............................................................................................................................-9

$onclusion ....................................................................................................................................-,

My irst (rea.....................................................................................................................................--

Introduction ...................................................................................................................................--

The Structure .................................................................................................................................--

:;its and Maintaina<ility ..............................................................................................................-3

1ur :;itses ....................................................................................................................................-6$hain chain chain... .....................................................................................................................-8

$onclusion ....................................................................................................................................0,

Building The #erect Beast.................................................................................................................0-

Introduction ...................................................................................................................................0-

( irst 4#$ ..................................................................................................................................0-

Breathing Lie Into The Lieless ...................................................................................................03

$o2er +oursel =% +ou'll $atch ( $old .....................................................................................0"

/e7uest Item..................................................................................................................................39

$hatting (*ay ..............................................................................................................................3,

$onclusion ....................................................................................................................................3-

>ooking =%........................................................................................................................................30Introduction ...................................................................................................................................30

The #ath.h #ro<lem .......................................................................................................................30

Sorted!............................................................................................................................................35

I (t irst +ou )on't Succeed ......................................................................................................3"

$om%ound Interest ........................................................................................................................59

Mo2ing ..........................................................................................................................................5,

1ne inal Touch ...........................................................................................................................50

$onclusion ....................................................................................................................................50

Back To The Beginning......................................................................................................................55

Introduction ...................................................................................................................................55

$a%tain Beey's /eturn .................................................................................................................55

Michael >eron #age -

Page 3: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 3/150

LPC For Dummies 1, Second Edition

The /oad Less Tra2elled ..............................................................................................................56

Bigger Better aster ....................................................................................................................5&

#ro<ing )ark )e%ths ....................................................................................................................58

The Taskmaster .............................................................................................................................69

S*itching Things (round .............................................................................................................6-Sco%ing Things 1ut ......................................................................................................................60

$onclusion ....................................................................................................................................65

 4o* That We're (n Item...................................................................................................................66

Introduction ...................................................................................................................................66

Virtually Sel?:;%lanatory ............................................................................................................66

But *hat does it all mean ............................................................................................................68

Beey's Boots ................................................................................................................................"9

Bling ..............................................................................................................................................",

( Word 1 Warning (<out Items ................................................................................................"0

$onclusion ...................................................................................................................................."0

(n Inside @o<......................................................................................................................................"3Introduction ..................................................................................................................................."3

The Mysterious /oom .................................................................................................................."3

Modiying :;its ............................................................................................................................"5

Sho% 'Till +ou )ro% ......................................................................................................................"&

Sta<<y @oe .....................................................................................................................................&9

$onclusion ....................................................................................................................................&,

)ysunctional Beha2iour....................................................................................................................&-

Introduction ...................................................................................................................................&-

1ur Task .......................................................................................................................................&-

The Science Bit... $oncentrate! ....................................................................................................&-

The Structure o a unction ..........................................................................................................&3( Little Bit More... .......................................................................................................................&6

unction Sco%e .............................................................................................................................&"

1n*ards and =%*ards!.................................................................................................................&&

Violence Begets Violence .............................................................................................................8,

( Local Sho% or Local #eo%le ....................................................................................................83

$onclusion ....................................................................................................................................85

oing Loo%y.......................................................................................................................................86

Introduction ...................................................................................................................................86

( Basic #u< ..................................................................................................................................86

rum%y (l ....................................................................................................................................8"

rum%y (l oes Ballistic ...........................................................................................................,99$om%onents ................................................................................................................................,9,

Loo%s ..........................................................................................................................................,93

)oing While... .............................................................................................................................,95

or Loo%s.....................................................................................................................................,96

ire in the >ole! ..........................................................................................................................,9&

$onclusion ..................................................................................................................................,98

(rrays +ou say..............................................................................................................................,,9

Introduction .................................................................................................................................,,9

Slicey #ete ...................................................................................................................................,,9

The (rray ....................................................................................................................................,,0

(rray Inde;ing ............................................................................................................................,,5

Michael >eron #age 0

Page 4: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 4/150

LPC For Dummies 1, Second Edition

(rray management.......................................................................................................................,,6

Setting =% Stock L#$ Style .......................................................................................................,,"

The oreach Structure .................................................................................................................,,8

$onclusion ..................................................................................................................................,,8

>ooray or (rrays.............................................................................................................................,-,Introduction .................................................................................................................................,-,

( Secret To Be )isco2ered ........................................................................................................,-,

Item Matching .............................................................................................................................,-0

( rue Some ate! .....................................................................................................................,-6

etting To 1ur Sho% 1 >orror .................................................................................................,09

$onclusion ..................................................................................................................................,0,

Ma%%ing It 1ut.................................................................................................................................,00

Introduction .................................................................................................................................,00

The Ma%%ing ...............................................................................................................................,00

The Magic >ate Ball ...................................................................................................................,06

More Ma%%ing Mani%ulation Matey ..........................................................................................,39$onclusion ..................................................................................................................................,3-

So Long............................................................................................................................................,30

Introduction .................................................................................................................................,30

The #ast .......................................................................................................................................,30

The #resent .................................................................................................................................,35

The uture ...................................................................................................................................,36

$onclusion ..................................................................................................................................,36

/eader :;ercises..............................................................................................................................,3"

Introduction..................................................................................................................................,3"

:;ercises......................................................................................................................................,3"

Send Suggestions.........................................................................................................................,38

Michael >eron #age 3

Page 5: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 5/150

LPC For Dummies 1, Second Edition

Moo !he Monke" #a"s...(ll rights including co%yright in the

content o these documents are o*ned

or controlled <y the indicated author.

+ou are %ermitted to use this material

or your o*n %ersonal non?commercial

use. This material may <e used

ada%ted modiied and distri<uted <y

the administration o )isc*orld M=)

Ahtt%CCdisc*orld.atuin.net D try the

2ealE as necessary.

+ou are not other*ise %ermitted to

co%y distri<ute do*nload transmit

sho* in %u<lic ada%t or change in any

*ay the content o these *e< %ages or

any %ur%ose *hatsoe2er *ithout the

 %rior *ritten %ermission o the indicated authorAsE.

I you *ish to use this material or non?%ersonal use %lease contact the authors o the te;ts or

 %ermission.

I you ind these te;ts useul and *ant to gi2e less niche %rogramming languages a try come check

out htt%CC***.monkeys?at?key<oards.com or more ree instructional material.

My a%ologies or the unriendly legal <oiler%late <ut I ha2e had %eo%le attem%t to steal o*nershi%

o my material <eore.

#lease direct any comments a<out this material to drakkosFdisc*orld.atuin.net.

That's mojo at the to% right. >e's 2ery cle2er. >e has a B.( in 4anas!

Michael >eron #age 5

Page 6: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 6/150

LPC For Dummies 1, Second Edition

$illkommen% Bien &enue% $elcome%

'ntroduction

This is the Discworld – flat, circular, and carried through space on the back of four elephants who stand on the back of Great A'tuin, the only turtle ever to feature on the Hertzsprung!ussell Diagra", a turtle ten thousand "iles long,dusted with the frost of dead co"ets, "eteorpocked, albedoeyed# $ooneknows the reason for all this, but it's probably %uantu"#

 &uch that is weird could happen on a world on the back of a turtle like that###

... and it's now your job to ensure that it does!

In this set of introductory creator material, we are going to talk about the wayin which the gameworld of Discworld MUD is constructed. This is a bookabout coding, but don't worry about it we're going to introduce the toic asgently as we ossibly can. "ew toics will be introduced only when they helus make our code better and more interesting. #ou will find all of the sourcecode that goes along with this te$t a%ailable in the &d&learning&learn%ille&directory. It is broken u into chaters, so you can see e$actly what your codeshould look like at each stage of de%eloment. #ou can goto the room'accessoint' within this directory to e$lore all of these %ersions and see thedifferences between them.

 !he Learnin #cenario

(%er the course of this te$t, we'll be building a game area ) e$actly like thekind you ha%e e$erienced in the game. *e're going to create rooms, "+s,items, and shos. *e're going to sto short of adding uni-ue functionality or-uests, because that's a art of the followu creator te$t. y the end of thiste$t you should be comfortable with the basic building blocks of /+. 0longthe way you'll e%en learn a bit about code, but only a bit. eing a Discworld

creator in%ol%es working with code, but you don't need to be a coder to be acreator. 1nough to get by will take you far, although it's always good to learnmore if you can.

(ur learning scenario is the de%eloment of the %illage of /earn%ille. 0 fullycomleted %ersion of this may be found in the learning domain under&d&learning&learn%ille&chater23. I would like you though to construct thisste by ste in time with the teaching material ) you only get a fraction of thebenefit from reading comleted code that you do from writing the code as yougo along.

Michael >eron #age 6

Page 7: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 7/150

LPC For Dummies 1, Second Edition

/earn%ille is a simle %illage, with basic facilities. It also doesn't contain muchin the way of descritions if you want to see what good descritions look like,take a look at some of your fa%ourite game areas. (ur scenario is for teaching

 you how to ut an area together, it is assumed that you'll be able to write the

te$t yourself. 4ome guidance on the toic of writing descritions may be foundin eing 0 etter reator. *hat we're interested in here is the structure ofthe area, not how it looks.

*e're going to aroach this functionality according to a de%elomenttechni-ue called incremental de%eloment. I heartily recommend this forbeginners because it greatly simlifies the job of building comle$rogramming structures. This is a rocess of beginning with something %erysimle until you ha%e the %ery basic framework fitting together. (nce youha%e the skeleton, you can start adding features to it a little bit at a time. Inthis way, you a%oid becoming bogged down in the o%erwhelming comle$ity ofa roject ) you get to see it grow all around you from the most humblebeginnings to a comlete and fully featured area. To ut this in conte$t, westart with a single room that does nothing e$citing. *e then add a secondroom and connect these two skeleton rooms together. Then we add in another,and another, until we ha%e a whole framework of a %illage ready for us to fillin the blanks. *hat we don't do is create the whole framework to start withand then become flummo$ed when it doesn't work.

Incremental de%eloment is an e$citing and satisfying rocess, and one withwhich you are going to become entirely familiar as you work your way throughthis material. #ou can see your de%eloments shaing u in a %ery tangibleway, and that in%ites further de%eloment. Trying to do e%erything to startwith can be a soulcrushing way of de%eloing a roject.

 !he #tructure of the ame

1%erything on Discworld MUD is something called an object. This is -uite acomle$ toic in itself, so we're only going to scratch the surface of this fornow. 1%ery room is an object, e%ery item is an object, e%ery layer is anobject. onfusingly, object doesn't mean that it's necessarily something youcan touch or interact with in the game. #our guild commands for e$amle are

also objects. It's not an easy thing to get into your mind.

In rogramming terms, an object is a structure that contains some data, andinstructions for acting on that data. 4ome objects also take on the roertiesof other objects through a mechanism called inheritance. This is the samegeneral biological rincile you'll be familiar with in real life, only cast inrogramming terms. In real life, a cat inherits the roerties of being amammal, which in turn inherits the roerties of being an animal. *e'll seethis mechanism in action from the %ery first code we write our object inheritsthe roerties of being a room.

Michael >eron #age "

Page 8: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 8/150

LPC For Dummies 1, Second Edition

Most of the code you need to work with on Discworld has already been writtenfor you ) you just need to tell the MUD what things you want to haen, andwhen. Most of the things you'll want to do, at least in the short term, area%ailable for you. *hen you want to get a little more ad%enturous, then you'll

be looking at mo%ing onto the more ad%anced creator material.The MUD itself is built on three searate structures. The first of these is thedri%er, which is known as 5luff(4. #ou won't need to worry about that justnow. The second art is the mudlib, and it defines all of the code on which therest of the game the domain code is built. It's domain code that you will bebuilding in the short term, and that's all the code you'll find underneath the &d&directory. The mudlib is e%erything else, including code that will 4car andTerrify you if you read it too early.

 0s a basic guide to the relationshi between the mudlib and the dri%er, it canbe summed u like this ) the mudlib knows what to do, but doesn't know how

to do it, and the dri%er knows how to do it, but doesn't know what to do.Domain code includes all of the areas in which you ad%enture as a layer, allthe -uests you ha%e encountered 6and the ones you ha%en't7, and all the "+s

 you'%e slain.

*hen an object is made a%ailable in the game, it must first be loaded. 0t thatoint, it becomes a master object. Many objects remain as master objects,which means only one of them is e%er in lace in the game ) rooms and uni-ue"+s are good e$amles of these.

4ome objects are clones, and that means they are coies of the master object.

8eneric, common or garden "+s and items are e$amles of cloned objects.*hen we need a new irate for e$amle, we just take a coy of the masterobject and ut that coy in the game.

In order for an object to load, we use the udate command. If our code is all+resent and orrect, the object will load. *e'll look at this more in theucoming material. If an object has been incorrectly coded, you will beresented with lines of red te$t 6synta$ errors7 and blue te$t 6warnings7. *ecall these 'comile time' errors e%ery synta$ error in your code must be fi$edbefore an object will load, but it will load if warnings are resent. 5i$ themanyway. The rocess of writing code, udating an object, and then fi$ing the

synta$ errors will become second nature to you before too long.

Prorammin as a Conce*t

+rogramming is a difficult task, unlikely almost anything you may ha%elearned before ) it's like learning how to do mathematics in a foreign language) a confusingly new synta$ combined with a formally e$act %ocabulary. *hen

 you learn how to seak a different language, you can rely on your interlocutorto be able to di%ine meaning e%en when you make mistakes ) a comutercannot do that. 0nd worse, it does e$actly what you tell it to do ) that soundsgreat in theory, but it can be hugely roblematic in reality.

Michael >eron #age &

Page 9: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 9/150

LPC For Dummies 1, Second Edition

omuters don't understand much ) at their basest le%els, they are machinesfor maniulating electrical imulses. 0t the lowest le%el, these are interretedby the comuters as a collection of ones and 9eroes 6a numerical system calledbinary , but you don't need to know anything about that just yet7.

:owe%er, we don't want to write our rograms as ones and 9eroes ) it wouldtake a long time, re-uire a lot of tedious busy work, and generally be amassi%e drag. The first rogrammers howe%er did e$actly that, they wrotetheir rograms in the language of the comuter itself machine code.

 0s time has gone by, it has become simler to write rograms for comuters )in order to manage the comle$ity of rogramming as a task, comuter eolede%eloed successi%ely more abstracted rogramming languages, andintroduced the idea of compilation. ;ather than writing in machine code,rogrammers could write in an easier, simler system and then make thecomuter itself con%ert that into machine code. This con%ersion rocess is

called compilation.The first attemts to do this were through a language called assembler, whichis only a little bit better than machine code directly. 0ssembler is known as alow level language because it's not all that far remo%ed from the low le%elgrunts and snorts of machine code.

 0s the years ha%e gone on, more and more rogramming languages werede%eloed. 4uccessi%ely they abstracted writing rograms into more and more1nglishlike synta$. 1%entually a language named came along, andre%olutioni9ed how eole thought about rograms. was so successful thatmost of the successful rogramming languages of modern times use its style

of writing code in one way or another ) <, == and >a%a esecially.

These are known as high level languages because of the le%el of abstractionin%ol%ed. omuters do not understand the code written in these languages,but the rocess of comilation con%erts the code into something the comutercan understand.

(n Discworld, we use a language called LPC which was created by /ars+ensjoe. *hile it has %ery similar synta$ to all of the abo%e named languages,it has a host of unusual and useful features. *e'll get to what those featuresare as we go through the material.

+rogramming is essentially the task of taking a list of instructions, and writingthem in such a way that the comuter can follow your instructions to comletea task. To gi%e a simle, real world e$amle ) imagine the task of makingscrambled eggs. Imagine you ha%e an obedient, but simleminded kitchenassistant, and you would like them to make some scrambled eggs for you.They do e%erything you tell them to do, and they do it e$actly as you tell them.It sounds like an ideal situation, but consider the following instructions?

2. 8et two eggs from the fridge

@. 8et some milk from the fridge

Michael >eron #age 8

Page 10: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 10/150

LPC For Dummies 1, Second Edition

  3. 8et some butter from the fridge

A. reak the eggs into a jug

B. *hisk the eggs until they are well mi$ed.

C. :eat some milk and some butter in a ot.

. 0dd the egg mi$ture.

E. 4tir until scrambled eggs are made.

The instructions are retty simle, but your 4imle Minded 0ssistant falters atthe first instruction. :e, or she, stands %acantly at the fridge, awingineffectually at its surface. ursing, you amend your instructions a little?

2. Open the fridge, you insensitive clod.

  @. 8et two eggs from the fridge

3. 8et some milk from the fridge

A. 8et some butter from the fridge

B. Flose the fridgeF

C. reak the eggs into a jug

. *hisk the eggs until they are well mi$ed.

E. :eat some milk and some butter in a ot.G. 0dd the egg mi$ture.

2H. 4tir until scrambled eggs are made.

 #ou set your 4imle Minded 0ssistant back to work ) they oen the fridge.They get two eggs out... success! Then they stand there with a confused lookon their face. *hat does 'some' meanJ, they ask. #ou curse once more?

2. (en the fridge, you insensiti%e clod.

@. 8et two eggs from the fridge

3. 8et two tablespoons of  milk from the fridge

  A. 8et a knob of  butter from the fridge

  B. lose the fridge.

C. reak the eggs into a jug

. *hisk the eggs until they are well mi$ed.

E. :eat some milk and some butter in a ot.

Michael >eron #age ,9

Page 11: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 11/150

LPC For Dummies 1, Second Edition

  G. 0dd the egg mi$ture.

2H. 4tir until scrambled eggs are made.

 0nd then you start them on the task. Uh, the fridge is already oen, theysay, and then the metahysical comle$ity of the situation causes them to shutdown until you ammend the rogram a little further?

2. If the fridge door is shut, oen the fridge, you insensiti%e clod.

  @. 8et two eggs from the fridge

3. 8et two tablesoons of milk from the fridge

A. 8et a knob of  butter from the fridge

B. lose the fridge.

C. reak the eggs into a jug

. *hisk the eggs until they are well mi$ed.

E. :eat some milk and some butter in a ot.

G. 0dd the egg mi$ture.

2H. 4tir until scrambled eggs are made.

 0nd so on, until you ha%e a comletely correct, entirely unambiguous list ofinstructions that any dolt could follow. This is the essence of whatrogramming is all about. The only difference is, your instructions are gi%en in/+, and the 4imle Minded 0ssistant is the MUD itself. Trust me, it's e%enmore stuid than your kitchen assistant.

This is a much trickier task that I'm making out here ) and the only thing thatmakes it easier is ractice lots and lots of ractice. That leads us to thene$t section of this chater...

't+s ,ll Down !o -ou*hether you are learning to code on Discworld, or in a more formal settinglike a uni%ersity course, the basic ro%iso is the same ) nobody can teach

 you how to code. 4ure, eole can oint you in the right direction andro%ide you with amle reading and reference material. *hat they can't do ismake you understand, because you don't learn it by ha%ing someone e$lain itto you. The only way you learn how to code is by racticing.

Michael >eron #age ,,

Page 12: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 12/150

LPC For Dummies 1, Second Edition

ut more than that ) the only way you really learn is by trying and makingmistakes. If you get it right the first time, that's great ) but you would ha%elearned more by getting it wrong and working out what why your code didn'tfunction the way you hoed. I guess what I'm saying is ) don't get

discouraged. #ou are going to make mistakes, and sometimes you're not goingto know how to fi$ them. That's what the Mentats in the /earning Domain arethere to hel you with ) but lease do try to work it out first before you ask forhel. "ot because they don't want to hel you, because they do ) but because

 you'll learn more if you work out the answer yourself.

 #ou'%e got to be willing to erse%ere in this ) the easiest way to fail is to nottry. *e can suort you in your crusade to be a 8ood reator, but only if youmeet us half way. ;emember, your domain lord thinks you can make it as acreator, or you wouldn't ha%e been hired in the first lace.

Conclusion

In this chater we'%e gone o%er the %ery, %ery basics of what rogrammingactually in%ol%es, and how code on Discworld is ut together. 0ll of this isuseful knowledge, but it's not coding yet. That comes in the ne$t chater whenwe look at building our %ery first room. 0re you e$citedJ Touch your nose if

 you are!

Michael >eron #age ,-

Page 13: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 13/150

LPC For Dummies 1, Second Edition

M" First oom

'ntroduction

;ight, let's get started for real then ) we'%e got a lot to learn and you'%ealready read so much without getting your hands on a bit of code. "ow we'regoing to change that by creating our %ery first room and filling it with some ofthe simler elements a%ailable to a no%ice creator. This is a big ste e%en thelargest of our area domains started off at one oint with a single room.

(nce we'%e gotten that first achie%ement under our belt, we'll talk a little bitabout structuring an area so that we don't get hoelessly bogged down in theminutiae. *e're going to look at the basic skeleton of /earn%ille, and howmany rooms we're going to de%elo ) ha%ing a lan always makes it easier toschedule your time and effort. #ou should always sit down and sketch outwhat you are hoing to accomlish with an area before you start writing anycode. The easiest time to make corrections is at the concetion stage.

 -our Own Learn/ille

The assumtion throughout this material is that you are going to be buildingthis %illage alongside the tutorials. In order to link u what's done in these

documents to what you're doing on the MUD, we need to calibrate! That's justa fancyants way of saying that we're all using the same directory names.

5irst, you create a directory in your &w& dri%e called learn%ille. 0ll subse-uentdirectories will be created in here. #ou don't need one for each chater as isresent in &d&learning&learn%ille you should ha%e one coy of this that growsand changes as you de%elo it further.

mkdir /w/your_name_here/learnville

(nce you'%e gotten the directory, you want a subdirectory in there calledroo"s?

mkdir /w/your_name_here/learnville/rooms/

5rom this oint on, this chater will assume this is where you are uloading your files. Make sure it is, because otherwise you're going to ha%e lots ofroblems ensuring that the aths you use ma u to the aths we use in here.

Michael >eron #age ,0

Page 14: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 14/150

LPC For Dummies 1, Second Edition

 !he Basic !em*late

5irst of all, let's set u our basic temlate for creating a room. reate a newfile in your de%eloment en%ironment 64ee *elcome To The reatorbase for a

discussion on that if you ha%en't already done this7, and tye the following into your editor?

inherit "/std/room/outside";

void setup() {set_short ("simple village road");add_property ("determinate", "a ");set_long ("This is a simple road, leading to a simple village. There ""is very little of an excitement aout it, except that it represents ""your first steps to ecoming a creator!n");

set_light (#$$);%

4a%e this file in your &rooms& subdirectory, and call it streetH2.c.

"ow, in the last chater we soke a bit about loading objects ) this roomdoesn't yet e$ist on the MUD, e%en though it e$ists on the diskdri%e. To see ifit loads, we use the udate command?

update /&/your_name_here/learnville/rooms/street_$#.c

*hen you hit return, you should see a message something like this?

'pdated simple village road (/&/your_name_here/learnville/rooms/street_$#)

If it doesn't, then something has gone wrong with what you'%e tyed into theeditor. /ook %ery closely at the e$amle code abo%e and see where your codediffers ) it should be identical. If all else fails, simly coy and aste the codeabo%e into your editor don't get bogged down in the errors just yet. #ou'll get

 your fair share of those later when you try to do things without a safety net.

(nce your room has loaded, you need to mo%e to it with the goto command?

goto /&/your_name_here/learnville/rooms/street_$#

If all has gone well, you'll see the following?

/&/your_name_here/learnville/rooms/street_$# (unset)t is night and there is no moon.This is a simple road, leading to a simple village. There is verylittle of any excitement aout it, except that it represents your firststeps to ecoming a creator!

t is a freeing cold ac*spindle&inter+s night &ith a strong reee, thic*lac* clouds and heavy sno&.

Michael >eron #age ,3

Page 15: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 15/150

LPC For Dummies 1, Second Edition

There are no ovious exits.

ongratulations! #ou'%e just taken your first ste into a larger world!

0ow1 what does all of that mean2

/et's take a look at what you'%e done and e$lain what each of the differentbits mean. Most of them should be fairly ob%ious, but it's imortant that youknow the bits you don't need to worry about?

// This the oect that defines all of the functionality of &hich &e+re// going to ma*e use. -ll of the code that &e use in setup is defined in// this oect. n this case, it+s an outside room... so it gets all the// usual &eather strings and chats.

inherit "/std/room/outside";// This is a function (&e+ll come ac* to this topic later). -ll you need// to *no& for no& that the code in setup gets executed automatically y// the ' &hen your room is loaded.

void setup() {

// The short description is &hat you see &hen you +glance+ in a room.set_short ("simple village road");// The determinate is &hat gets appended to the short description// sometimes. n this case, this room ecomes +a simple village road+.// f &e &anted it to e +the simple village road+, &e+d change// the determinate here to +the+.add_property ("determinate", "a ");// This is the long, &ordy description of the room that you see &hen you// have the ' output on verose.set_long ("This is a simple road, leading to a simple village. There ""is very little of an excitement aout it, except that it represents ""your first steps to ecoming a creator!n");

// This sets the current light level for the room. #$$ e0uates// to +right sunlight+set_light (#$$);

%

The lines that start with the && symbol are comments. The MUD comletelyignores these when it is loading your room ) they are there urely for humans6and other creators7 to read. It's good ractice to comment your coderoerly, but that's a toic for a later day. #ou'll read more about commentingin *orking *ith (thers.

 0t the simlest le%el, all of the code that you incororate into your rooms goesinto the setu of a room. #ou need to ay articular attention here to the curlybraces ) it's easy to get these wrong when you first start ) all of your codegoes between the oening curly brace , and the closing curly brace !.

Michael >eron #age ,5

Page 16: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 16/150

LPC For Dummies 1, Second Edition

That's the basic structure of each room we're going to create ) you may wantto coy and aste this somewhere you ha%e easy access to so you can use itfor each room you start.

M" oom #ucks

 #es, yes it does! #our room is dull, boring, uninteresting... generally lame andhorrible. ut it loads ) let's take one ste at a time!

/et's look at adding some more interesting things to your room. The first thing you'll notice is that you can't look at anything... 'look %illage' gi%es a ratherdisheartening resonse?

1annot find "village", no match.

/et's start off simly and add some things for eole to look at. *e do this byusing additem?

add_item ("village", "The village is simple, ut eautiful ecause of it.");

This goes into the setu of your room ) as a matter of con%ention, it goes after you'%e set the long descrition for the room. Udate your room, and 'look %illage'. #our resonse will be much more encouraging?

The village is simple, ut eautiful ecause of it.

/ooking at the road will gi%e us the 'no match' message, so let's add an itemfor that too?

add_item ("road", "2ou+re standing on it, you dolt!");

 #ou can add as many items as you feel is aroriate. In general, more isbetter ) but at the %ery least e%ery noun in the main descrition, and e%erynoun in the additem descritions should ha%e an additem of its own.

ut wait! *e're not -uite safe here, because the long descrition refers to a'simle %illage', and what haens when we look at the simle %illageJ #e,'no match'.

*e get around that by being more secific in our additem definitions?

add_item ("simple village", "The village is simple, ut eautiful ecause""of it.");

add_item ("simple road", "2ou+re standing on it, you dolt!");

Michael >eron #age ,6

Page 17: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 17/150

LPC For Dummies 1, Second Edition

 0dditem is -uite cle%er ) by doing this, we get the root noun 6%illage7 lusany adjecti%es we define, in any order in which we want them... looking at'%illage' gi%es us the descrition, as does look at 'simle %illage'. If we had an

additem for 'shiny red simle %illage', we'd be able to look at 'shiny %illage','red %illage', 'shiny simle %illage' and any combination thereof.

*e'll return to additem intermittently as we go along ) it's much moreowerful than a lot of eole reali9e, and we'll ha%e good cause to make use ofthat ower in later chaters.

't+s a little too 3uiet...

Most rooms in the game ha%e a little more life to them than your first attemt.They ha%e "+s 6we'll get to those7, and they ha%e chats that aear at semirandom inter%als. These chats are a big art of making a room feel ali%e, solet's add some of those.

 0gain, in your setu function, add the following code. It's slightly comlicated,so you may want to coy and aste it?

room_chat ( ({ #3$, 34$,({"t+s 0uiet... a little too 0uiet.","t+s simple... a little too simple.",

"t+s exciting learning to develop rooms!",%)

%));

 #ikes! *hat's with all the brackets and bracesJ /et's retend we don't need toworry about that just now, because we don't ) it'll all come clear in laterdocuments.

Instead, we shall focus on the 4alient Details here ) the first are the twonumbers. These are retty straightforward ) the first is the minimum time thatmust ass before a chat is sent to the room, and the second is the longesteriod of time that will ass before a chat.

The strings of te$t are the actual chats that get echoed to the room ) you canha%e as many of these you like, inserted into the list. 1ach needs to besearated by a comma?

Michael >eron #age ,"

Page 18: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 18/150

LPC For Dummies 1, Second Edition

room_chat ( ({ #3$, 34$,({"t+s 0uiet... a little too 0uiet.","t+s simple... a little too simple.",

"This is a chat in a list!","t+s exciting learning to develop rooms!",

%)%));

"ote the -uotation marks ) we'll talk about why these are necessary in a laterchater of the material. >ust take my word for it now that they're needed.

The only thing missing from our most basic of rooms is an e$it to anotherroom. 5or that, we actually need a second room to mo%e to!

, #econd oom

/et's start with out basic temlate as before, changing the long descrition alittle to reflect the fact this is somewhere different. *e'll call this [email protected], so create a new file and sa%e it to the MUD?

inherit "/std/room/outside";

void setup() {set_short ("simple village road");

add_property ("determinate", "a ");set_long ("This is a little &ay along the path to the village of ""5earnville. The path continues a little to&ards the northeast "

"to&ards the ric*ety uildings of the mar*et s0uare. To the ""south&est, the path &ends a&ay from &hat passes as civiliation ""in this learning scenario.n");set_light (#$$);%

*e now want to link these two rooms u ) this is done using adde$it. 0dde$it re-uires three ieces of information before it can make u a

connection to a room ) the first of these is in what direction the e$it lies. Thesecond is what ath the ne$t room may be found at. The third is the tye ofe$it 6is it a door, a ath, or stairsJ7. (ur long descrition abo%e shows us whatour direction is going to be ) our first room lies off to the southwest of thisroom. It's going to be an e$it of tye 'ath'?

add_exit ("south&est", "/&/your_name_here/learnville/rooms/street_$#","path");

This goes into [email protected]. 4treetH2.c gets its own e$it leading to our secondroom?

Michael >eron #age ,&

Page 19: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 19/150

LPC For Dummies 1, Second Edition

add_exit ("northeast", "/&/your_name_here/learnville/rooms/street_$3","path");

Udate both of these rooms, and you'll be able to walk between them. That isretty nifty, I'm sure you'll agree!

(ne thing to bear in mind is that while we'%e ut the full ath of these roomsin our adde$its, that's not how we should do it 'In 0nger' because it makes itreally difficult to mo%e areas around as you need them. /ater, we'll talk aboutthe imortance of roerly structuring the architecture of your code so thatit's easy to mo%e things around %arious directories.

 #ou'll note that our second room is missing additems and roomchats )adding these is left as an e$ercise for the interested reader. #ou should be

able to do that yourself referring to the notes for how it is done in the firstroom.

Our O/erall Plan

4o, that's two simle rooms linked u. It's worth making sure we ha%e anactual lan here so that we know how each room fits into the whole. #ou mayha%e your own fa%ourite mechanisms for designing a ma for a new area, Iersonally fa%our the humble te$tfile. This is the ma of the area we're going

to de%elo together?

- 6  7 7  89:91  7 7  949<9  /  3  /  #

*e're using a number here for each outside room, and a letter for each insideroom. *e thus need a key so we know which number is which room?

Michael >eron #age ,8

Page 20: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 20/150

Page 21: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 21/150

LPC For Dummies 1, Second Edition

+roerties are used intermittently through the MUD, but you should be waryof them they ha%e a tendency to clutter objects. ecause they are so easy foreole to add 6there is no set list of roerties which are %alid7, it'stremendously easy for creators to write objects that attach roerties to

layers and items, and then ne%er write down why or what the roerty is for.efore too long, e%eryone is wandering around with roerties like gnah bagcheck, and noone e$cet the original creator 6who may ha%e left by thisoint7 has any idea where it came from.

+roerties are a -uick and easy hack, but you shouldn't use them too much. Incircumstances where you do, you should always make sure that they aretimed roerties. #ou can do this by ro%iding a third iece of information tothe addroerty call the number of seconds the roerty should e$ist for?

call add_property ("gills", #, #3$) me

:ere, the gills roerty will remain on you until 2@H seconds ha%e assed, atwhich oint it won't. These are 'selfcleaning' roerties and you shouldalways, always use them unless you are %ery sure indeed that you don't needto.

Conclusion

These simle rooms aren't %ery interesting ) we're going to change that as we

go along. *e ha%e taken a big ste though ) creating an actual real room youcan stand in, and another room you can mo%e to it's from these basicbuilding blocks that whole cities are built. *e're going to lea%e them lackingin additems and long descritions and such nothing is gained by writingthese rooms to the standard that would be e$ected in the game. (nce you'%eseen one additem, you'%e seen them all you don't learn more by ha%ingsomething reeated o%er and o%er again. 5illing in the blanks is left as ane$ercise for the interested reader I heartily encourage e$erimentation tosee what haens when you change things the fact that you ha%e easy accessto the original sourcecode from &d&learning&learn%ille means that there is nocost if you break e%erything utterly.

Michael >eron #age -,

Page 22: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 22/150

LPC For Dummies 1, Second Edition

M" First ,rea

'ntroduction

 #ou'%e taken your first stes to de%eloing a small room within the MUD. Inthis chater, we're going to e$tend this to an entire area. In the rocess, we'lltalk a little bit about how to de%elo an architecture that means we can easilymo%e things around as we need, and link them u with minimum fuss. This isan imortant asect of de%eloing an area ) things get mo%ed around a lot onDiscworld, esecially through de%eloment and laytesting. 0reas that aredifficult to maintain are a drain on e%eryone's time. /uckily your areas aren'tgoing to do that, because we're going to talk about how you can a%oid it.

(nce we'%e looked at the setu of the skeleton of the area, we're going tosend a little more time looking at the e$its we'%e setu. The more detail weut into our areas, the richer our game world seems. That's a goal I'm sure wecan all agree on being worthwhile.

 !he #tructure

 #ou'%e seen the ma from which we're going to be de%eloing. *e cande%elo room by room, only adding a room into the whole when it'scomleted. :owe%er, in order to get a feel for how things are going to link u,it's beneficial to ut skeleton imlementations of each room in lace, and thenincrementally add their descritions and features. That's what we're going todo now. It's easier than you may think.

;emember our ma?

- 6  7 7  89:91

  7 7  949<9  /  3  /  #

 0nd our key?

Michael >eron #age --

Page 23: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 23/150

LPC For Dummies 1, Second Edition

"umber #ilename

2 streetH2.c

@ [email protected]

3 streetH3.c

A marketsouthwest.c

B marketsoutheast.c

C marketnorthwest.c

marketnortheast.c

*e'%e got the basic outline of rooms 2 and @. *e ha%e another fi%e rooms thatwill be outside rooms, and then four that will be inside rooms. *e beginutting this framework together with a temlate. 4a%e it as streetH3.c?

inherit "/std/room/outside";

void setup() {set_short ("s*eleton room");add_property ("determinate", "a ");set_long ("This is a s*eleton room.n");set_light (#$$);

%

This is the room you're going to reeat for each of our outside rooms there'snothing in it, but that's fine we don't want to send time writing someintricate, beautiful descritions we are only going to ha%e to scra later. Thefour remaining rooms of our de%eloment are the market rooms. "ow comesthe magic!

 #ou don't need to ainstakingly create a new file for each of these rooms and

then sa%e it ) we make use of the c 6coy7 command to create the rest of thetemlate rooms?

cp street_$.c mar*et_south&est.ccp street_$.c mar*et_southeast.ccp street_$.c mar*et_north&est.ccp street_$.c mar*et_northeast.c

"ow when you ls 6list7 the directory, you'll find it full of your skeleton rooms.

# mar*et_northeast.c # mar*et_south&est.c # street_$.c=

# mar*et_north&est.c street_$#.c= # mar*et_southeast.c# street_$3.c

Michael >eron #age -0

Page 24: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 24/150

LPC For Dummies 1, Second Edition

*e ha%en't added the e$its to these new rooms, but that's okay ) we need totalk a little bit about e$its before we lea into that art.

45its and Maintaina6ilit"If you'%e been looking through the 'here's one that I made earlier' %ersions ofthese files in the &d&learning&learn%ille directory, you'll see that it's broken uby chater. 1ach directory contains the code as it stands by the end of thearoriate chater. I'm not writing this code e%ery time ) I'm coying itacross from the last %ersion.

:owe%er, the e$its from chaterH@ don't work after mo%ing it into thedirectory of chaterH3 ) e%ery time a mo%e is made, you end u in the roomfor chaterH@. #ou can change the filenames by hand, and that's not too bad

for two rooms. *e'%e got se%en now, and four more to come ) it would be anightmare to ha%e to change all of those aths by hand, for e%ery chater ofthis book. It's too much to ask of anyone, esecially me because I really don'twant to ha%e to do it.

The same thing is true with your code ) sometimes things get mo%ed aroundas directories are reshuffled, cities are redesigned, and generally treated withan incredible amount of casual disresect. 1%en the 8ods don't ick u citiesand rehouse them with the indifference we do. hanging e%ery e$it in a largecity by hand would be an imossibly annoying task, and one you'd just need toreeat when the city mo%ed directories in the future. It's not a sustainable

aroach.*e ha%e a way around that roblem though ) we make use of what is knownas a header  file.

reate a new file and sa%e it as ath.h 6note, .h on the end rather than .c7. It'sgoing to contain one single line?

>define ?-T@ "/&/your_name_here/learnville/rooms"

This is a secial kind of code statement in /+. Technically it's called apreprocessor directive ) it's something that /+ deals with before it e%ergets to your code. There is a subsystem in the dri%er called the preprocessor ,and it's kind of a souedu search and relace tool. 5or the code we ha%ehere, we ha%e gi%en the rerocessor a directi%e to define the te$t +0T: asbeing another string entirely.

*hen you create your ath.h file, make sure you hit return at the end of theline. If you don't, you'll get a worrying error saying something about <ragmastricttyes. If this haens, go back to your ath.h file and add a return atthe end.

Michael >eron #age -3

Page 25: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 25/150

LPC For Dummies 1, Second Edition

The rerocessor is essentially a sohisticated search and relace routine )ro%iding a <define statement tells the rerocessor that e%ery time it seesthe first term to relace it with the second term. Thus, any time you use thete$t +0T: in your rogram, it will relace it with the te$t

&w&yournamehere&learn%ille. This haens transarently, and e%ery timethe object is loaded. #ou see no imact on your code.

4imly creating a ath.h file is not enough though, we need to tell our roomsto use it. *e do this by using another directi%e called an include directi%e. 0tthe to of each of your room files, before your inherit line, add the following?

>include "path.h"

This tells the rerocessor to take the ath.h file you just created, and

incororate it into your rooms ) as such, each of your rooms gets the definethat is set. In your skeleton rooms, the code will now look like this?

>include "path.h"

inherit "/std/room/outside";

void setup() {set_short ("s*eleton room");add_property ("determinate", "a ");set_long ("This is a s*eleton room.n");set_light (#$$);

%

"ow, let's see what imact that has on our original two rooms. ;emember weha%e already set u their e$its, like so. In streetH2.c, we ha%e?

add_exit ("northeast", "/&/your_name_here/learnville/street_$3", "path");

In [email protected], we ha%e?

add_exit ("south&est", "/&/your_name_here/learnville/street_$#", "path");

*e're going to change these so that they read as follows. 5or streetH2.c, wewill ha%e?

add_exit ("northeast", ?-T@ A "street_$3", "path");

Michael >eron #age -5

Page 26: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 26/150

LPC For Dummies 1, Second Edition

5or [email protected], we will ha%e?

add_exit ("south&est", ?-T@ A "street_$#", "path");

"ow, udate your two rooms ) you'll see you can mo%e between them just aseasily as you were able to do before. That's because before /+ e%en begins totry and load your code, the rerocessor looks through your code for anyinstance of +0T: and relaces it with your define ) so what /+ sees when itcomes to load your room is the following?

add_exit ("northeast", "/&/your_name_here/learning" A "street_$3", "path");

/+ is erfectly caable of adding two strings together, and once it's donethat it ends u with the full ath to the room. The difference here though isthat if you change it in your ath.h file, it changes in e%ery file that makes useof that ath.h ) one change in the right lace and an entire city can be shiftedfrom one directory to another without anyone lifting a finger. It's %eryowerful, and an aroach to de%eloment into which you should definitelyget into the habit. heck with your domain administration to see how this getshandled in your own domain. 4ome domains ha%e a single .h file 6such asforn.h7 that ser%es as a master file for e%ery room. 4ome ha%e a more

distributed aroach whereby smaller .h files are a%ailable to subsectionswithin a de%eloment.

Our 45itses

"ow, we need to go back o%er our skeleton rooms and add in the e$its ) youshould be able to do this -uite easily by yourself now, as long as you knowwhich rooms are heading where 6and the ma will tell you that7. Don't add anye$its for the inside rooms yet ) we'll get to those later.

To make sure your e$its look the way they are suosed to, here's the code forthe e$its in each of your rooms?

street$%&

add_exit ("northeast", ?-T@ A "street_$3", "path");

Michael >eron #age -6

Page 27: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 27/150

LPC For Dummies 1, Second Edition

street$%'

add_exit ("northeast", ?-T@ A "street_$", "path"); add_exit ("south&est",?-T@ A "street_$#", "path");

street$%(

add_exit ("east", ?-T@ A "mar*et_south&est", "path"); add_exit ("south&est",?-T@ A "street_$3", "path");

market$northeast

add_exit ("south", ?-T@ A "mar*et_southeast", "path"); add_exit ("&est",?-T@ A "mar*et_north&est", "path");

market$northwest

add_exit ("south", ?-T@ A "mar*et_south&est", "path"); add_exit ("east",?-T@ A "mar*et_northeast", "path");

market$southeast

add_exit ("north", ?-T@ A "mar*et_northeast", "path"); add_exit ("&est",?-T@ A "mar*et_south&est", "path");

market$southwest

add_exit ("north", ?-T@ A "mar*et_north&est", "path"); add_exit ("east",?-T@ A "mar*et_southeast", "path"); add_exit ("&est", ?-T@ A "street_$","path");

There's a articular con%ention that is followed when adding multile e$its )when you walk around the game, the e$its are resented to you in the order inwhich they are added in code. To imro%e consistency, try to add rele%ante$its in the following order? north, south, east, west, northeast, northwest,southeast, southwest, and then any other e$its. "oone will shout at you if youdon't do this, but it's the con%ention.

Michael >eron #age -"

Page 28: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 28/150

LPC For Dummies 1, Second Edition

(ne thing you may ha%e noticed from other arts of the game, esecially inmarket s-uares, is that there are sometimes diagonal e$its you can take thataren't listed ) if you can go north and then east to get to a articular room,why can't you go northeastJ

There's no reason why we should e$clude this, so let's first add in the diagonale$its in the market rooms?

market$northeast

add_exit ("south&est", ?-T@ A "mar*et_south&est", "path");

market$northwest

add_exit ("southeast", ?-T@ A "mar*et_southeast", "path");

market$southeast

add_exit ("north&est", ?-T@ A "mar*et_north&est", "path");

market$southwest

add_exit ("northeast", ?-T@ A "mar*et_northeast", "path");

 0nd ne$t, we will set them to be hidden. *hy do we do thisJ Mainly it's toa%oid cluttering u the ob%ious e$its list whether you want to make youre$its hidden is entirely u to yourself, but there's no reason why you shouldn'tknow how to do it. *e make use of a new iece of code called modifye$it forthis ) modifye$it is tremendously owerful, and we'll return to it se%eraltimes in the future.

In each of the market rooms, we'll modify the e$it of the diagonal so that it isset as 'nonob%ious'. It's still there, just not listed. 5or e$amle, inmarketnortheast we'd just the following line of code?

modify_exit ("south&est", ({"ovious", $%));

Do the e-ui%alent of this in all four market rooms and udate ) you'll find thee$its disaear from the list, but you're still able to take them just as before.

Michael >eron #age -&

Page 29: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 29/150

LPC For Dummies 1, Second Edition

Chain1 chain1 chain...

 0nother thing you'll ha%e noticed as you wander around the game is that somearts of %arious cities gi%e you informs as to what's haening in another

art... for e$amle, you'll see something like

ra**os moves southeast onto the centre of Bator B0uare.

It would be cool if our market rooms did that too ) and they're going to bymaking use of a thing called the linker. 5irst though, we need to make suretheir shorts are set roerly, because that's what's used to build the message.In each of the market rooms, change the shorts as follows?

market$northeast

set_short ("northeast corner of the mar*etplace");

market$northwest

set_short ("north&est corner of the mar*etplace");

market$southeast

set_short ("southeast corner of the mar*etplace");

market$southwest

set_short ("south&est corner of the mar*etplace");

5or each of these, you should also set the determinate as 'the' instead of 'a'. Inthat way, eole will see, for e$amle, 'the northeast corner of themarketlace' when eole mo%e about. If it's set to 'a', then they'll see 'anortheast corner of the marketlace', which doesn't look right, not right at all!

4etting the shorts roerly ensures that the messages will be roerlyformed, but still need to tell the MUD we want it to haen. *e do this usingsetlinker. *e gi%e the MUD each room we want to link together e$cet forthe room in which we're defining the code.

5or marketnortheast then, the code would be as follows?

Michael >eron #age -8

Page 30: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 30/150

LPC For Dummies 1, Second Edition

set_lin*er ( ({?-T@ A "mar*et_north&est",?-T@ A"mar*et_south&est",?-T@ A "mar*et_southeast",

%) );

#or market$northwest)

set_lin*er ( ({?-T@ A "mar*et_northeast",?-T@ A "mar*et_south&est",?-T@ A "mar*et_southeast",

%) );

market$southeast)

set_lin*er ( ({?-T@ A "mar*et_north&est",?-T@ A "mar*et_northeast",?-T@ A "mar*et_south&est",%) );

 *nd market$southwest)

set_lin*er ( ({?-T@ A "mar*et_north&est",?-T@ A "mar*et_northeast",?-T@ A "mar*et_southeast",%) );

 #ou'll need to log on a test character to make sure that you'%e got this allsetu roerly, you can't test it from your own ersecti%e. reate a test

character, bring them into the world, and then set them as a test characterusing the testchar command?

testchar Ctestchar_nameD on

Trans your testchar to your %illage and make them dance around a bit for you.*hat you should see are messages along the lines of the following?

ra*test moves south into the south&est corner of the mar*etplace.

+ro%ided that message looks right from e%ery art of the marketlace, you'%egot it all configured roerly. *ell done!

Michael >eron #age 09

Page 31: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 31/150

LPC For Dummies 1, Second Edition

Conclusion

:a%ing a skeleton of an area is a great way to gi%e you a ersecti%e of how itall fits together, as well as a solid idea of how much work you ha%e to do.

There's nothing wrong with the 'write one room and link it in' aroach, but you get a much better idea of the bigger icture by architecting it all togetherand just seeing how it feels. That way, if you think that the layout needs tochange, you can do it before you'%e hooked too much of it together. It's just anice way to get some ersecti%e.

My ersonal reference is to do this and then watch as the area starts toe%ol%e in line with my de%eloment. It's %ery nice to be able to see an areataking shae before you. *hen we did the city of 8enua, the outer circle ofthe city was all created and linked together before anything had really beendone, and it was great to watch it slowly constructed around me as %arious

creators went about their business. #ou should howe%er find an aroach thatworks best for you. #our mileage may %ary, as they say.

Michael >eron #age 0,

Page 32: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 32/150

LPC For Dummies 1, Second Edition

Buildin !he Perfect Beast

'ntroduction

It's awfully lonely in our little %illage, isn't itJ I think it is, anyway ) and surely,like I, you cra%e some kind of comany on your -uest to become a fullycaable Discworld creator. In this chater we're going to build the firstinhabitant of our area, and ro%ide him with e-uiment, resonses, and chats.:e's going to be our little li%ing doll, for us to taunt and make dance for oursort.

In the rocess, we'll ha%e to look at some new synta$ and introduce a newconcet of /+ rogramming, that of the %ariable. *e'%e come -uite farwithout actually talking abut %ariables, but you'%e been using them all along )

 yes, that's right! That's the 4:(KI"8 T*I4T of this chater %ariables arethe Kaiser 4o9e of /+ rogramming!

, First 0PC

/et's start off by creating a new subdir in our learn%ille directory ) this one

will be called chars?

m*dir /&/your_name_here/learnville/chars/

It is in this directory that we will include the code that creates any "+s inour area. Keeing a clean di%ide between rooms, "+s and items is animortant art in ensuring it's easy to integrate your code into a largerdomain lan. This is going to cause some comlications for our ath.h file,which we'll talk about a bit later ) there is no roblem so great that we cannotsol%e together, though!

 0nyway, creating an "+ follows a %ery similar rocess to creating a room )what changes is the inherit we use, and the secific code that goes into thesetu of the object. onsider the following for a basic temlate ) sa%e it intochars with the filename catainbeefy.c.

inherit "/o/monster";

void setup() {set_name ("eefy");set_short ("1aptain 6eefy");add_adective ("captain");

add_alias ("captain");add_property ("determinate", "");

Michael >eron #age 0-

Page 33: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 33/150

LPC For Dummies 1, Second Edition

  set_gender (#);set_long("This is 1aptain 6eefy, a former officer in uchess Baturday+s ""us*eteers. @e retired from there after eing staed in the face y ""a marauding player. @e no& lives in 5earnville, hoping to the Eods ""that he &ill die in his sleep efore he is murdered for hisshoes.n");asic_setup ("human", "&arrior", #<$);

%

/et's go through that line by line, as we did for our first room?

// f &e &ant to create a asic F?1, this is the file &e inherit.inherit "/o/monster";

void setup() {

// The name of the F?1 is ho& it is identified y the '+s matching// system. This should e one single &ord 9 it should usually too e// the last &ord in the short, for simplicity+s sa*e.set_name ("eefy");

// This is &hat players see &hen they encounter the F?1.set_short ("1aptain 6eefy");

// This is &hat gets prepended to the short of the F?1. Bince 1aptain// 6eefy is a uni0ue person, he gets his determinate set to empty. f// he &as one of a numer of clones (for example, a eggar), then// the determinate could e set to +a+, or even +the+.add_property ("determinate", "");

// 1aptain 6eefy is a uni0ue F?1 9 there should only ever e one of him.// This code doesn+t ensure that, ut it does mean &hen he+s *illed he+ll// trigger a death inform.add_property ("uni0ue", #);// The name is used to match an F?1, ut &e also need to set valid// adectives. f &e don+t include this, our F?1 can e referred to as// +eefy+, ut not +captain eefy+. Ge &ant oth to e valid.add_adective ("captain");// Ge also &ant people to e ale to refer to him ust as +captain+, so// &e add an alias for him.add_alias ("captain");// @e needs a gender, ecause he+s a he. Betting the gender to # ma*es// him male. 3 ma*es him female. Hverything else ma*es him an +it+.

set_gender (#);// The long is &hat players see &hen they +loo*+ at him.set_long ("This is 1aptain 6eefy, a former officer in uchess Baturday+s ""us*eteers. @e retired from there after eing staed in the face y ""a marauding player. @e no& lives in 5earnville, hoping to the Eods ""that he &ill die in his sleep efore he is murdered for his shoes.n");

// 2ou need this in the code, or try as you might he &on+t clone &hen you// &ant him to. The first piece of information &e provide is his race.// The second is his guild. The third is his guild level.asic_setup ("human", "&arrior", #<$);

%

Michael >eron #age 00

Page 34: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 34/150

LPC For Dummies 1, Second Edition

4o, udate your code, and clone him ) he'll aear in the same room as you ifall has gone to lan?

The land is lit up y the eerie light of the &axing crescent moon. This isa s*eleton room.t is a freeing cold ac*spindle&inter+s night &ith a steady &ind, thic*lac* clouds and heavy sno&.There are t&o ovious exitsI south and &est.1aptain 6eefy is standing here.

*e can interact with him in the same way we can with any object in the game,but there's not much oint. :e doesn't do anything interesting at all. :e juststands there looking gormless. ut he loads! hant it like a mantra, 'ut :e/oads!'. That's always the first romising ste you take. 0fter that, the rest isine%itable.

Breathin Life 'nto !he Lifeless

5irst of all, let's make him emit some chats. Much like with our rooms, we canmake our "+s a little more interesting by adding chats. Moreo%er, we canmake these chats different deending on whether the "+ is being attackedor not. The mechanisms by which we do this are identical in terms of synta$and meaning, but they're -uite different from how it is handled in rooms. Thecode we need is called loadchat for normal chats, and loadachat for attackchat.

/et's add some chats into our "+, and talk about what the code means?

load_chat(3$, ({3, "+ ?lease don+t hurt me.",#, "Jco&er",#, "+ @ere come the drums!",#, "I stares into space.",

%));

This sets u the random chats for the "+. The first number dictates howoften a random chat is made. 1%ery two seconds, 6a eriod of time known as aheartbeat7 the mud rolls a onethousand sided dice 6metahorically7, and ifthe result is lower than the number set here, the "+ will make a chat. It'snot e$actly finegrained control, but control it is.

1ach of the chats has two arts a weighting, and a command string. Theweighting is the relati%e chance a chat will be selected. The string is thecommand that will be sent for the "+ to erform. If you want the "+ to saysomething, then start the command with an aostrohe. If you want the "+to emote, then start the command with a semicolon. If you want the "+ to

erform a soul, start the command with an at symbol.

Michael >eron #age 03

Page 35: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 35/150

LPC For Dummies 1, Second Edition

To understand the way the weightings work, think of it as a roulette wheel )add u the weightings of all the chats, and it'll come to B. *hen the MUDdetermines the "+ should make a chat, there is a @&B chance it'll be the firstchat, and a 2&B chance it'll be each of the others. 0s usual, there is more that

 you can do with loadchat than we'%e co%ered here ) we'll get to somead%anced stuff later in the tutorials.

(ne ro%iso here is that if you want your "+ to actually say things, it's goingto need a language and a nationality. *e can ro%ide that by using thesetunationality method ro%iding in an aroriate combination ofnationality and region. #our domain leader will be able to tell you which ofthese is aroriate for your domain, but for demonstration uroses we'llmake atain eefy a 8enuan. +ut it after basicsetu in your code?

setup_nationality ("/std/nationality/genua", "genua");

To add the attack chats, it works the same way ) we just use loadachatinstead?

load_a_chat(4$, ({#, "+ Kh please, not again!",#, "+ don+t get medical insurance!",#, "J&eep",

%));

*hen you make changes to eefy, you'll need to dest him before you udateand reclone. (nce you'%e added the chats, go on ) take a swing at him! #oumay find he doesn't swing back ) if you're in%isible, that'll be why. ut youshould find he leads itifully before your 0wesome Might?

2ou punch at 1aptain 6eefy ut he dodges out of the &ay.1aptain 6eefy exclaimsI Kh please, not again!

+oor fellow. :e doesn't know what 5resh :orrors we ha%e in store for him to

come.4o, that's fine for making him a little more interesting ) howe%er, we alsowant to be able to make him rely when we say things to him. /et's add someof that now using addresondtowith. The synta$ for this is a little comle$,so bear with me?

add_respond_to_&ith(({"Jsay",({"hello", "hi", "hiya"%),

%),"+ Hr, hello. ?lease don+t *ill me.");

Michael >eron #age 05

Page 36: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 36/150

LPC For Dummies 1, Second Edition

This sets u a resonse to a message that originates with the command 'say'.It will match on any string containing either the words 'hello', 'hi', or 'hiya',ro%ided it originates from a say command. eefy's resonse to this will be to

say 1r, hello. +lease don't kill me.

/et's add in a second resonse, since he's already oened us u to theossibility of killing him?

add_respond_to_&ith(({"Jsay",({"*ill", "murder"%),%),"+ Fo, please no. eg you!");

+itiful, isn't itJ :owe%er, it's also not -uite what we want ) because if we say 'Iam not going to murder you', he'll still beg for his life. ;eally we only wanthim to make this resonse if we suggest we are going to murder him. *e cando this by adding in a second set of keywords. The MUD will attemt toattern match based on the order we gi%e the sets of keywords? This kind ofattern matching is not easy ) the more comle$ you make the triggerconditions, the less likely eole will be able to hit on them roerly.

The MUD will also only e$ecute one match, so the order in which you add thetriggers will influence the way the "+ resonds ) if you ha%e a more secificresonse you want to catch before a more general one, it should go first in

 your code?

add_respond_to_&ith(({"Jsay",({"&on+t", "not", "can+t"%),({"*ill", "murder"%),

%),"+ Than* you, *ind sir!");

add_respond_to_&ith(({"Jsay",({"am", "&ill", "going"%),({"*ill", "murder"%),

%),"+ Fo, please no. eg you!");

 #ou'll get one resonses here to 'I am not going to kill you', and a differentone to 'I am going to kill you'. Try them the other way around, and you'll see a-uite different story unfold!

Michael >eron #age 06

Page 37: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 37/150

LPC For Dummies 1, Second Edition

These are, of course, terrible resonses because they don't really catchmeaning ) if I say 'I'm not going to not kill you', he'll still thank me for mymercy. Keeing your resonses simle will hel you manage that kind of thing con%incing con%ersations are not easy to do, and since we work on keyword

triggering, there is no way for us to deri%e semantic meaning. Make yourresonses as comle$ as they need to be, but no more comle$ than that.

*e can add a resonse that triggers on a %ariety of different triggers ) fore$amle, to get him to resond to some souls?

add_respond_to_&ith(({({"Jcomfort", "Jsoothe", "Jcalm"%),({"you"%),

%),"I ta*es a deep reath.");

"otice that the trigger te$t for this is the word 'you' ) that's because that'swhat the "+ sees from its ersecti%e.

*e can also make him gi%e random resonses by slightly changing the formatof the last art of the addresondtowith. 5or e$amle, let's change our lastaddresondtowith a little?

add_respond_to_&ith(({

({"Jcomfort", "Jsoothe", "Jcalm"%),({"you"%),

%),({"I ta*es a deep reath.","+ 2es, you+re right... shouldn+t let things get to me."

%));

:e'll now resond randomly with one of the two chats we'%e gi%en him.

Co/er -ourself 7*1 -ou+ll Catch , Cold

atain eefy will now chat with us a bit, but he's still horribly naked. That'sembarrassing for e%eryone concerned, so let's dress him u a bit, like the littledoll he is. This is where we counter our first real bit of /+ ) the %ariable, andthe first handler we'll deal with.

Michael >eron #age 0"

Page 38: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 38/150

LPC For Dummies 1, Second Edition

The handler is -uestion is called the armoury, and it's what we use to get holdof game objects. #our re-uest command makes use of the armoury, and youcan use it to ro%ide a list of the things a%ailable to you. efore we use thearmoury, we need to add something to the to of our code ) another <include

directi%e. This time, we need to tell our code where it can find the armoury?

>include Carmoury.hD

"otice that the name of the .h file is enclosed in angle brackets rather than-uotation marks. If you surround the name in angle brackets, the dri%er looksfor the file in &include& first, and then in its current working directory. If yousurround the name in -uotation marks, it looks in the working directory firstand FthenF in the &include& directory.

In this .h file is a define for 0;M(U;# ) this oints to the object in the mudlibthat manages keeing track of items and making them a%ailable to otherobjects. That's what a handler is ) an object that has resonsibility formanaging some asect of the game so that it's easier for other objects.

 0s mentioned elsewhere in this material, e%erything in Discworld is an object.atain eefy is an object, and so is e%ery item in the game. *hen we want torefer to one of these objects in code, we need to get a reference to it.

5irst of all, we need to define something to hold that reference ) we use a %ariable for that. 0t the to of your setu for atain eefy, add the followingline of code?

oect trousers;

This is a %ariable declaration. This re-uests a little ortion of the comuter'smemory from the dri%er, and that ortion of memory is e$actly big enough tohold a MUD object regardless of what kind of object it actually is.

It doesn't actually ha%e anything in it yet though ) we first ha%e to set itscontents through what is known as an assignment. 0ll %ariables are defined at

the to of whate%er function they haen to be in 6more on this later7 ) so theygo before any other code in your setu. They are usually assigned later in thecode ) so while the %ariable declaration occurs at the to of the code, we'll utsomething into that %ariable after we'%e done all the rest of the setu for the"+?

>include Carmoury.hD

inherit "/o/monster";

void setup() {

oect trousers;

Michael >eron #age 0&

Page 39: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 39/150

LPC For Dummies 1, Second Edition

  set_name ("eefy");set_short ("1aptain 6eefy");

// LHBT KM T@H 1KH @HLH

add_respond_to_&ith(({({"Jcomfort", "Jsoothe", "Jcalm"%),({"you"%),

%),({

"I ta*es a deep reath.","+ 2es, you+re right... shouldn+t let things get to me."

  %));

trousers N -LK'L29Dre0uest_item ("pirate trousers", #$$);trousers9Dmove (this_oect());

init_e0uip();%

/et's look at what our new code does?

trousers N -LK'L29Dre0uest_item ("pirate trousers", #$$);trousers9Dmove (this_oect());

init_e0uip();

The first line here sends a re-uest to the armoury for an item with the name'irate trousers'. #ou can find out all the trousers that the armoury hasa%ailable using the command?

re0uest list clothes trousers

These trousers were chosen at random ) feel free to ick whate%er airaeals to you. 0t this oint, a clone is made of these trousers, but they don'te$ist anywhere e$cet in the comuter's memory. The second line takes those

trousers and mo%es them into the in%entory of our "+.

The third line makes the "+ wear and hold all of the e-uiment it iscurrently carrying ) it makes him dress himself, essentially.

/et's do the same thing with a shirt. reate a %ariable at the to?

oect shirt;

 0nd then after we'%e re-uested our trousers, we re-uest a shirt?

Michael >eron #age 08

Page 40: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 40/150

LPC For Dummies 1, Second Edition

shirtN -LK'L29Dre0uest_item ("&hite ruffled shirt", #$$);shirt9Dmove (this_oect());

This should come before the inite-ui67, which we only need once.

 #ou can clone weaons, food, scabbards, jewellery ) ractically anything youmay like ) into your "+ in this way. :a%e a lay about with the re-uestcommand to see what's a%ailable to you.

e3uest 'tem

The abo%e synta$ is a little more comlicated than it needs to be we alsoha%e access to a iece of code called re-uestitem which does all of this work

for us. It still uses the armoury, it just does more of the work for us. It createsthe %ariable, re-uests the item from the armoury, and then mo%es it into our"+. *e don't need the <include, or the %ariables, we just need to usere-uestitem directly?

re0uest_item ("pirate trousers", #$$);re0uest_item ("&hite ruffled shirt", #$$);

init_e0uip();

:owe%er, you'll see an awful lot of "+s doing it the 'longhand' way, so youshould understand how both mechanisms work. #ou will often find situationson Discworld where there are easier ways to achie%e what a iece of code isdoing, and they are usually down to one of the following reasons?

•The creator in -uestion didn't know about the easier way.

•The easier way was added after the code was written

ecause there are so many creators who ha%e contributed so much code o%erso many years, there is a %eritable archaeological record in our mudlib anddomain code. #ou need to know how both ways work because you're just aslikely to encounter a comlicated way of doing things as you are an easierway.

Michael >eron #age 39

Page 41: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 41/150

LPC For Dummies 1, Second Edition

Chattin ,wa"

There's one thing left for us to talk about in this chater, and it's the secialcodes that can be used within loadchat and loadachat to make our "+s

more in%ol%ed in the world around them. *e can build secial strings that getinterreted by the MUD and turned into meaningful outut based on thethings around our "+. It's easier to see what that means in ractise thandescribe it, so let's add a loadchat to atain eefy?

load_chat(O$, ({3, "+ ?lease don+t hurt me.",#, "Jco&er",#, "+ @ere come the drums!",#, "I stares into space.",#, "+ Kh, hello there PlcnameP.",

%));

4ee the last chat thereJ The weird looking code is interreted by the MUD totake the form of the name of a li%ing object in the "+'s in%entory. The firstletter 6l7 defines what object will be the target of the chat, and the string thatfollows 6cname7 defines what is used to build the rest of the string. *hen thechat is selected, a random object is icked from the secified set, and then there-uested -uery method is called on it and substituted for the secial code wero%ide. The letters we ha%e a%ailable for choosing the set of objects is asfollows?

Letter Ob+ect

m The "+ itself.

l 0 random li%ing object in the "+'s en%ironment.

a 0 random attacker in the "+'s en%ironment.

o 0 random non li%ing object in the "+'s en%ironment.

i 0 random item in the "+'s in%entory.

5ollowing the initial letter comes the tye of information being re-uested.This gets called on the random object that is selected when the chat triggers.4ome of these are more useful than others, but you may find cause to use e%enthe more secialised ones on occasion?

Michael >eron #age 3,

Page 42: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 42/150

LPC For Dummies 1, Second Edition

Code e-uest

name The file name of the "+ used for targeting souls

cname The caitalised name of the object

gender The gender string of the object

oss The ossessi%e string

ronoun The ronoun of the selected object

ashort The ashort67 of the object

ossshort The ossshort of the object

theshort The theshort of the object

oneshort The oneshort of the object

 0s an e$amle, we could get the short of an object in the "+'s in%entory withLitheshortL. *e could get the name of a random attacker in loadachat withLacnameL. Unfortunately, we get no finegrained control o%er the objectselected if we choose the item set of objects, we can't further secialise it, soa chat like the following will not be aroriate?

"+ am going to sta you in the eyes &ith PipossshortP!"

It'll arse roerly, but he'll end u saying things like 'I am going to ste youin the eyes with my floy clown shows!' which, while surreal, is not reallysensible. Desite the limitations, combining these codes will allow for you tomake your "+ chats more dynamic and resonsi%e to the conte$t in which itfinds itself.

Conclusion

*e'%e come -uite far in this chater, ha%ing created an interacti%e "+ whois dressed in a fashion that does not offend our ictorian sense of decency.:owe%er, we need to manually clone atain eefy into our %illage each timewe want him there. In the ne$t chater we'll look at how we can get that tohaen automatically without our inter%ention.

 0t the moment we're making use of only those items that the armoury canro%ide, but we'll also look at ways in which we can write our own objects andmake them a%ailable to our "+s and our rooms.

Michael >eron #age 3-

Page 43: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 43/150

LPC For Dummies 1, Second Edition

Hookin 7*

'ntroduction

4o, we now ha%e a set of rooms, and we ha%e an "+. They're simle, but theywork. It's not aroriate though that you ha%e to clone the "+ directly into

 your room ) it should haen automatically, and we're going to talk about howthat works in this chater.

*e're also going to resol%e the ath.h roblem that we introduced in the lastchater by looking at relati%e and absolute directory referencing. 4o buckle

u, time to take /+ out for another sin!

 !he Path.h Pro6lem

/ook at where we'%e got our ath.h file stored ) it's in our rooms directory. 0lthough we ha%en't needed to refer to it in the "+ we created, we shouldstill be able to get access to it without too much comlication... the idea of aheader file is that it's shared between all rele%ant objects, after all.

*e ha%e a coule of ossibilities. (ne is to coy the ath.h file into each

directory that we are likely to need it. This is a bad solution because itreintroduces the roblem it was designed to fi$ ) we need to change thedefines in multile laces if we want to shuffle things around. That's not ideal) we want to be able to change things in one lace and ha%e it reflected in allaroriate locations.

(ur second ossibility is to make e%erything use the same ath.h file ) that's abetter solution, but it's going to need us to change all the references to theath.h in all our code. *e'll need to ut it in a central location, and then ha%eall of the files <include it from there. That's not a bad solution there arelenty of .h files in &include& that work this way, but you need secial file

access to ut files in there, and comarati%ely few creators ha%e that access.*e'd need to store it then in a set directory in our &w& dri%e. *e can do betterthan that though ) after all, if we mo%e our code from &w& to &d&, we're going toha%e to remember to mo%e the .h file along with it, and then change all thereferences to the ath.h file to reflect its new location Ideally it should just bea case of coying a directory across and ha%ing done with it.

:ow about this though ) we kee a ath.h in each subdirectory, but we ha%ethat ath.h in itself include a ath.h in a higher le%el directoryJ That way,ro%ided the basic structure of the directory remains intact, we ha%e a chainof ath files that define all the %alues we need.

Michael >eron #age 30

Page 44: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 44/150

LPC For Dummies 1, Second Edition

That may sound confusing, but let's see it in ractice ) it should become a bitclearer with an e$amle.

/et's start with a new ath.h file in our base learn%ille directory?

>define ?-T@ "/&/your_name_here/learnville/">define LKKB ?-T@ A "rooms/">define 1@-LB ?-T@ A "chars/"

In each of your subdirs, you add a further ath.h file that includes the ath.hfrom the higher le%el directory. *e can do that using the .. symbol to toreresent the higher le%el directory in the <include. The double eriod symbolhas a secial meaning in a <include it means 'go to the directory one u fromthe current directory'?

>include "../path.h"

"ow, we are going to ha%e to change our room code a bit because we'remaking a distinction between ;((M4 and :0;4. /uckily we don't need todo that by hand, we can use the sar command to do a search and relace. Ishall warn you in ad%ance though, be 1;# 0;15U/ when using thiscommand. (ne creator, who shall remain nameless 6Terano7 once mistakenlychanged e%ery instance of the letter a in all the riest rituals to the letter e.

*hile tremendously funny 6to e%eryone else7, it was hugely roblematic forhim to fi$.

 0nyway, the sar command needs three ieces of information ) the string ofte$t you want to relace 6surrounded in e$clamation marks7, the string of te$t

 you want to relace it with 6again, surrounded in e$clamation marks7, and thefiles you want the te$t relaced in. /et's run that uy o%er our code. 5irst,

 you change your your current directory to the rooms subdirectory, and then?

sar !?-T@! !LKKB! =.c

Uon uttering this mystical incantation, you'll find all of your rooms nowreflect the "ew ;egime. Udate them all 6you can do this using udate F.c7,and you'll find e%erything is :unky Dory.

If it's not, remember what we discussed about ath.h files in a re%iouschater if they don't work roerly, make sure there's a carriage return atthe last line. 4ometimes /+ chokes on a file if that's not the case.

*ith regards to sar, lease remember ) use this command with caution. It'sincredibly easy to do some really -uite imressi%e damage to your hard workwith only a few mislaced keystrokes. #ou :a%e een *arned!

Michael >eron #age 33

Page 45: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 45/150

LPC For Dummies 1, Second Edition

#orted%

;ight, now we'%e gotten that out of the way, let's look at how we can makeatain eefy aear in our rooms. *e're going to ick a room for him 6we'll

choose marketnorthwest7 and talk about how it works. 5irst of all, we need totalk about a new kind of rogramming concet the function. 0 function isessentially a little selfcontained arcel of code that gets triggered uonre-uest sometimes on our re-uest, sometimes on the re-uest of anotherobject in the MUD. *e don't need to worry too much about it just now, we justneed to know that's what we're about to do. 5unctions ha%e many differentnames they most common one you'll also see in this material is the word'method'. It's just another word for the same thing.

There are certain functions that the MUD e$ecutes on all Discworld objects atredetermined inter%als. (ne of these we're familiar with ) the code that

belongs to setu gets e$ecuted when we udate our objects. There's anotherfunction that gets called at regular inter%als, and that's the reset function. Thereset function is called on rooms when a room is loaded 6and it's called justafter setu7, and also at regular inter%als 6of around thirty minutes or so7 onall currently loaded rooms. >ust the lace to deal with loading an "+!

4o, we're going to add a new function to marketnorthwest, like so?

void reset() {IIreset();

%

This function e$ists outside of any code you'%e already got. 4o within yourroom, it will look like this?

void setup() {...

%

void reset(){

IIreset();%

 #ikes! *hat does that code inside it meanJ Don't worry too much about thatright now ) in brief, in the object you'%e inherited at the to of your object,there's already a reset function defined. *hat we're saying with that line ofcode is '(h, remember and e$ecute all the code that's in the other resetmethod too'.

"ow, we'%e already seen how to create a %ariable to hold an object. "+s are

objects too, and so inside our reset method we want a %ariable that can holdatain eefy?

Michael >eron #age 35

Page 46: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 46/150

LPC For Dummies 1, Second Edition

oect eefy;

;emember, this goes at the to of our function, before the ??reset67. 0fter the ??reset67, we start building our code. The rocess for loading an "+into a room is as follows?

5oad the F?1 and assign it to a variale. f there is something in thatvariale, and that variale+s location is not this room, then move the F?1into the room

*e don't load "+s in the same way we get items from the armoury ) instead,we use a iece of code called loadobject, assing it the filename of the object

we want to load.

eefy N load_oect (1@-LB A "captain_eefy");

*hat comes out of that code is the reference to the loaded %ersion of ataineefy, and we store that reference in our beefy %ariable. *e tie these togetherlike so?

void reset() {

oect eefy;IIreset();

eefy N load_oect (1@-LB A "captain_eefy");%

 0fterreset also e$ists searately from your e$isting functions, like so?

void setup() {...

%

void reset() {...

%

void after_reset() {...

%

This doesn't actually mo%e eefy into our room ) in order to do that, we need

to e$lore a new element of rogramming synta$ ) the if statement.

Michael >eron #age 36

Page 47: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 47/150

LPC For Dummies 1, Second Edition

'f ,t First -ou Don+t #ucceed

The if statement is the first rogramming structure we're going to learn howto use. It allows you to set a course of action that is contingent on some reset

factor. The basic structure is as follows?

if (some_condition) {some_code;

%

The condition is the imortant art of this ) it's what determines whether thecode between the braces is going to be e$ecuted. 0 condition in /+ is definedas any comarison between two %alues in which the comarison may be true

or false. If the comarison is true, then the code between the braces ise$ecuted. If the comarison is false, /+ skis o%er the code in the braces andinstead continues with the ne$t line of code after the if statement.

The tye of comarison deends on which of the comarison oerators areused... these go between the two %alues to be comared, and determine thekind of comarison to be used?

Comparisonoperator

Meaning

NN 1-ui%alence ) does the left hand side e-ual the right handsideJ

O Is the left hand side less than the right hand sideJ

P Is the left hand side greater than the right hand sideJ

ON Is the left hand side less than or e-ual to the right hand sideJ

PN Is the left hand side greater than or e-ual to the right handsideJ

!N Does the left hand side not e-ual the right hand sideJ

/et's look at a simle e$amle of this in ractise using whole numbers 6the int %ariable tye7?

int num#;int num3;

num# N #$;num3 N 3$;

Michael >eron #age 3"

Page 48: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 48/150

LPC For Dummies 1, Second Edition

if (num# C num3) {tell_creator ("your_name_here", "num# is less than num3!n");

%tell_creator ("your_name_here", "+m out of the if!n");

4o, if the %alue contained in the %ariable num2 is less than the %alue containedin the %ariable num@, then we see the message sent to our screen. If it isn't,then we don't. In either case, we'll see the I'm out of the if! message. 4o,with the %alues we'%e gi%en num2 and num@, our outut is?

num# is less than num3+m out of the if!

If we change the two %ariables around a bit?

num# N 3$;num3 N #$;

Then all we see is?

+m out of the if!

 0n if statement by itself allows for you to set a course of action that may ormay not occur. *e can also combine it with an else to gi%e two e$clusi%ecourses of action?

if (num# C num3) {tell_creator ("your_name", "num# is less than num3!n");

%else {tell_creator ("your_name", "num# is greater than or e0ual to num3!n");

%

tell_creator ("your_name", "+m out of the if!n");

4o now, if the condition is true, we'll see?

num# is less than num3+m out of the if!

 0nd if it's not, we'll see?

num# is greater than or e0ual to num3+m out of the if!

Michael >eron #age 3&

Page 49: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 49/150

LPC For Dummies 1, Second Edition

*e can also ro%ide a selection of e$clusi%e courses of action by making useof an elseif between our original if 6the one that starts the structure7 and theconcluding else 6if we want one ) else is always otional7?

if (num# C num3) {tell_creator ("your_name", "num# is less than num3!n");

%else if (num# NN num3){tell_creator ("your_name", "num# is e0ual to num3!n");

%else {tell_creator ("your_name", "num# is greater than num3n");

%

*e can add as many elseifs as we like into the structure until we get the

beha%iour we're looking for.

4o, that's what an if statement looks like. /et's tie that into our reset functionabo%e. 0ny %ariable that does not ha%e anything in will ha%e a null %alue 6wecan use H to reresent this in an if statement7. 4o if we want to know if ourbeefy %ariable contains an actual atain eefy?

if (o !N $) {some_code;

%

*e can e%en write this in a simler fashion ) /+ lets us check to see if a %ariable has a %alue set by simly including it as its own condition in an ifstatement?

if (o) {some_code;

%

4o, that uts us firmly in the osition of ha%ing met the first of ourre-uirements to mo%e our atain into the room. "ow, let's look at the secondre-uirement.

*e can do that too by utting an if statement inside our if statement ) this isknown as nesting. To tell whether or not atain eefy is in the same room asthe code we're working, we use the following check?

if (environment (eefy) !N this_oect()) {%

Michael >eron #age 38

Page 50: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 50/150

LPC For Dummies 1, Second Edition

If both of those things are true, then we can mo%e our Dear atain into theroom?

if (eefy) {

if (environment (eefy) !N this_oect()) {code_to_move_eefy;

%%

This is not ideal though ) in general, ha%ing nested structures leads to clunky,inelegant code. There are sometimes %ery good reasons for code to be nested,but if you don't ha%e to do it, you shouldn't. In this case, we wouldn't ha%e todo it if we could get one if statement to check for both things. /uckily, that'ssomething we can indeed do!

Com*ound 'nterest

*e're not restricted to ha%ing a single condition in an if statement ) we canlink two or more together into what's called a comound conditional. To dothat, we need to decide the nature of the link.

Things become more comlicated the more conditions that are art of acomound ) we can ha%e as many as we like, but let's start out as simly aswe can. ecause we only want to e$ecute the code in our if statement if both

conditionals are true, we use the and comound oerator. In /+, this isreresented by a double amersand? QQ. If we wanted the code to bee$ecuted if one condition or the other were true, we'd use the or  oerator,which is a double bar? RR.

*e can join our two if statements together into one eautiful *hole using ourand oerator?

 if (eefy QQ environment (eefy) !N this_oect()) {code_to_move_eefy;

%

That's much neater all around.

It's sometimes confusing to new coders which of the comound oerators theywant for a articular situations. There is a concise reresentation of whateach of these conditions means ) it's called a truth table. The truth table forand is as follows?

Michael >eron #age 59

Page 51: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 51/150

LPC For Dummies 1, Second Edition

#irst Condition econd Condition Overall Condition

false false false

true false false

false true false

true true true

This means that if both conditions in the comound e%aluate to true, only thenis the o%erall condition that go%erns the if statement e%aluated to true. In allother cases, it is e%aluated to false.

5or or, the truth table looks like this?

#irst Condition econd Condition Overall Condition

false false false

true false true

false true true

true true true

More comle$ conditionals can be built by linking together conditionaloerators. That's a discussion for a later chater though.

"ow that we ha%e our if statement, we can look at the code we actually needto mo%e atain eefy into our room.

Mo/in

There's a iece of code defined in all items, li%ing or otherwise, and that codeis called mo%e ) we use that to mo%e "+s from one lace to another. 5oratain eefy, it looks like this?

eefy9Dmove (this_oect(), "PF appearPs &ith a pop.", "PF disappearPs &itha pop.");

Michael >eron #age 5,

Page 52: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 52/150

LPC For Dummies 1, Second Edition

The first art, thisobject67 refers to where we want the "+ to mo%e. In thiscase, it's the room in which we're currently working. The second is themessage eole will see when the "+ mo%es into the room. I know it doesn'tlook like a normal message, but we'll come back to that. The third art is the

message eole who are currently with the "+ will see when it is mo%ed.The mo%e messages work using a secial kind of notation that is interretedby the MUD to form the outut roerly deending on the ersecti%e of theobser%er. The ersecti%e doesn't mean much to an "+, but it makes all ofthe difference when it comes to mo%ing layers around. To an outsideobser%er, L" gets dislayed as the short of the object being mo%ed. To theobject being mo%ed, it gets dislayed as '#ou'.

The word aearLs works in a similar way. 0n outside obser%er will see theword aear with the s aended to the end 6aears7. The object beingmo%ed will see only 'aear'.

4o, if atain eefy were a real erson, he'd see?

2ou appear &ith a pop.

1%eryone else sees?

1aptain 6eefy appears &ith a pop.

The same system is used for the message of him disaearing ) it just makesthe whole thing look much nicer.

+utting that all together in our reset function gi%es us the following?

void reset() {oect eefy;IIreset();

eefy N load_oect (1@-LB A "captain_eefy");

if (eefy QQ environment (eefy) !N this_oect()) {eefy9Dmove (this_oect(), "PF appearPs &ith a pop.","PF disappearPs &ith a pop.");

%%

Udate the room, and you'll see atain eefy is there with you! That's nice,but we ha%e one final cosmetic touch to include.

Michael >eron #age 5-

Page 53: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 53/150

LPC For Dummies 1, Second Edition

One Final !ouch

*hen the room is loaded, there is no entry message for atain eefy. #oucan ro%e it works by desting beefy and then using the call command to force

a reset?

call reset() here

 #ou'll see the message we set in our mo%e?

1aptain 6eefy appears &ith a pop.

*e want that to haen when the room is udated as well, but it doesn't. Inorder to make it haen, we ha%e to delay the creation of the "+ a little bit.

There is a secial function defined by the dri%er called 'callout' ) it lets youro%ide the name of a function, and a delay. 0fter the number of secondsindicated by the delay, the named function is called. The con%ention for thisbeha%iour in terms of reset is to ha%e the actual functionality mo%ed into afunction called afterreset. 0fter that's done, your code will look like this?

void reset() {IIreset();call_out ("after_reset", );

%

void after_reset() {oect eefy;eefy N load_oect (1@-LB A "captain_eefy");if (eefy QQ environment (eefy) !N this_oect()) {eefy9Dmove (this_oect(), "PF appearPs &ith a pop.","PF disappearPs &ith a pop.");

%%

It should be noted at this oint that we are not yet talking about why certain

arts of the code need to be in certain laces. *e'll get to that, don't fret.

Conclusion

*e'%e now hooked u our "+ and our rooms ) and in the rocessincororated a header file that sans multile directories. "ot only is our areastarting to shae u in terms of the contents and the features, we're doing itin such a way as to guarantee the maintainability of the code. That's incrediblyimortant, although I areciate it may aear underwhelming for now.

Michael >eron #age 50

Page 54: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 54/150

LPC For Dummies 1, Second Edition

*e're still not talking much about code, although you'%e now been introducedto the first of your rogramming structures ) the function, and the ifstatement. #ou'%e reached a oint where you now ha%e the caability to makeobjects react intelligently to the circumstances in which they find themsel%es )

that's tremendously owerful! (nwards and uwards!

Michael >eron #age 53

Page 55: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 55/150

LPC For Dummies 1, Second Edition

Back !o !he Beinnin

'ntroduction

In this chater, we're going to take a further look at the code we can makeuse of in our rooms. :ardly any of our rooms ha%e any descritions, and westill need to discuss some of the cooler things that can be done with additem,as well as the way in which we can ro%ide more realistic descritions byincororating the changes between night and day. This re-uires us to writerooms with two sets of descritions, but the effect is really %ery aealing.

*e're also going to make atain eefy wander around this fine %illage ofours, and add a secial skill based search to one of our rooms. It's all %erye$citing! Touch your nose!

Ca*tain Beef"+s eturn

5irst, we're going to make atain eefy wander around our %illage ) after all,it gets so lonely when we're left by oursel%es. "+s wander according to aseries of mo%e 9ones that are defined. They are defined firstly in themsel%es

6to determine what 9ones an "+ may roam within7 and secondly in the rooms6to define to which 9one a room belongs7. *e're going to define all of/earn%ille as a single 9one, so add this to each of your rooms, somewhere inthe setu function. It doesn't esecially matter where.

add_one ("learnville");

*e can add multile 9ones to a room, allowing for "+s to ha%e shared butdistinct wandering areas.

(nce you'%e added that 9one to each room, we need to add the correct 9onesto atain eefy. In his setu, add the following?

add_move_one ("learnville");set_move_after (8$, $);

Michael >eron #age 55

Page 56: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 56/150

LPC For Dummies 1, Second Edition

*e use addmo%e9one to setu which 9ones within which our "+ isermitted to roam. *e use setmo%eafter to set the seed eefy will wander) the first number sets the fi$ed delay, and the second sets the ma$imumnumber of random seconds that is added to that delay. *ith that code, eefy

will wander e%ery CH to EG seconds.That's enough to set eefy wandering around our %illage. It's -uite a hassle tomanually add a 9one to e%ery room ) there are ways and means by which theIndustrious reator can a%oid this hassle, but they're a bit too ad%anced for usat the moment. *e shall thus simly li%e with the incon%enience. /+ 5orDummies @ will oen u new worlds of shared functionality for us.

 !he oad Less !ra/elled

*e're going to return to streetH3 here ) it's still set as a skeleton room andhas no long descrition, or any items. *e're going to use this blank can%as asthe e$loration oint for some new functionality.

5irst of all, what we'%e done for the items and long in streetH2 isn't, strictlyseaking, correct. (h, it works and it does what we said it would, but itdoesn't cature the dynamism that we normally associate with DiscworldMUD. (n your tra%els, you ha%e undoubtedly noticed how in many areas theroom descritions, additems and e%en chats in a room are different when it'snight to when it's day. 0ll rooms on the MUD should include this basic le%el ofresonsi%eness to the world.

Instead of using setlong, we use a air of related methods ) setdaylong andsetnightlong. 5unctionally, they are identical to setlong e$cet that theyare time of day deendant. The MUD itself handles all the switching betweenthe right %ersion of the long, you just need to tell it what the long should be./ike so?

>include "path.h"

inherit "/std/room/outside";

void setup() {set_short ("simple village road");add_property ("determinate", "a ");set_day_long ("This path is lit y right, eautiful daylight. ""Mrom the sun. @igh aove. 6ecause it+s daytime, seeR.n");

set_night_long ("t+s dar* here, ecause it+s night9time. -s opposed ""to day time. o you understand &hat meanR");

set_light (#$$);add_one ("learnville");add_exit ("east", LKKB A "mar*et_south&est", "path");add_exit ("south&est", LKKB A "street_$3", "path");

%

Michael >eron #age 56

Page 57: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 57/150

LPC For Dummies 1, Second Edition

"ote that we don't use setlong at all ) we only use that for rooms in whichthe descrition does not change at all from day to night ) an undergroundassage, for e$amle, would fit that bill.

4imilarly, we can add day and night items to reflect the changing situations

described in our longs?

add_day_item ("right eautiful daylight", "t illuminates the &orld ""around you!");add_day_item ("sun", "t urns our eyes, precious!");add_day_item ("daytime", "That+s &hat it is.");add_day_item ("nighttime", "on+t &orry, it+ll proaly e daytime ""forever. Fo need to fret.");

add_night_item ("nighttime", "t+s night, alright. 2ou can tell y all ""the dar* around.");

add_night_item ("dar*", "2ou can+t see the dar*, ecause it+s too dar*.");add_night_item ("daytime", "Those halcyon hours are gone for good, or at "

"least until the sun comes up again.");add_day_item ("sun", "There+s no sun, ecause it+s FE@T.");

If we want things that are a%ailable for day and night, we just use a normaladditem but only if they shouldn't change their aearance.

*e can also enrich our rooms with alternating day and night chats?

room_day_chat ( ({ #3$, 34$, ({"The daytime is full of sunlight.",

"2ou can see everything around you, ecause of the sun.","The sun is shining in the s*y.",

%)%));

room_night_chat ( ({ #3$, 34$, ({"t is pitch lac*. 2ou are li*ely to e eaten y a grue.","Gas that a grueR t sounded li*e a grue.","f that+s not a grue you can hear, it might e Sashta Ferada.",

%)%));

(b%iously these are all terrible descritions and %iolate all con%entions of

what you should ut into long descritions, items and chats ) that doesn'tmatter for now because our focus is on function not form. 4imly ro%idingday and night descritions goes a long way to increasing the sense of richnesseole e$erience in your areas, and you should definitely get into the habit ofwriting them. It adds a fair bit of e$tra work to room de%eloment, but theayoff is worth it. It's one of the reasons why our MUD looks so much slickerthan many.

Michael >eron #age 5"

Page 58: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 58/150

LPC For Dummies 1, Second Edition

4adly, we ha%e to wait for the hours to tick by before the MUD swas fromnight to day, so let us lea%e our descritions there. #ou can use the checkcommand to %erify that they are resent, but you'll need to wait until the timeof day changes before you can come back and see them in their roer

conte$t. 4o let's mo%e on to a different toic while we wait for the cruel,unyielding sun to set on our de%eloment.

Bier1 Better1 Faster

1arlier in these documents, I mentioned that additem was tremendouslyowerful. It is ) it lets you do all sorts of things with your items that you maynot ha%e reali9ed. In this section, we're going to look at some of the thingsthat additem lets us do. "ote that we need to use a more comlicated %ersionof the additem synta$ to do all of these things ) rather than just gi%ing thename of the item and its descrition, we need to secifically state which artsof the additem we're setting.

5irst of all, if an item is large and solid enough for eole to sit, or stand, orkneel on ) we should let them do that. *e do that by adding a osition tag tothe item, gi%ing the string that should be aended to the osition, like so?

 add_item ("agged roc*",({"long", "This is a agged roc*.","position", "on the agged roc*"

%));

 0dd this to your streetH3 room, and then udate. #ou'll now find that you can'sit on jagged rock' ) but careful, that's bound to hurt. #ou can lie on it, standon it, kneel on it... the usual susects in terms of interaction choices. If you siton it, e%eryone will see something like 'Drakkos is sitting on the jagged rock..The te$t you set in the additem is what defines how that message aears.

 #ou can add interaction otions to the items too ) for e$amle, if I wanted tomake it ossible to kick the stone, I add a kick tag to the code?

add_item ("agged roc*",({"long", "This is a agged roc*.","position", "on the agged roc*","*ic*", "K&! That stung!n"

%));

Michael >eron #age 5&

Page 59: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 59/150

LPC For Dummies 1, Second Edition

"ote that you need to end any secific %erb resonse you define with anewline character. There's no limit to what %erbs you may include ) it's just astring of te$t that gets shown to the layer when they attemt to use that %erbon your item.

 #ou can ro%ide synonyms for %erbs too?

add_item ("agged roc*",({"long", "This is a agged roc*.","position", "on the agged roc*",({"*ic*", "punch"%), "K&! That stung!n",

%));

There is also a secial tag called searchable that lets you set an additem asresonding to the search command. This is a little more comlicated than just

ro%iding a string of te$t to resond with ) you need to define a function in your room to handle the searching. *e're going to do that ne$t, but let's addthe bit we need to the item first?

add_item ("agged roc*",({"long", "This is a agged roc*.","searchale", ">search_roc*","position", "on the agged roc*",({"*ic*", "punch"%), "K&! That stung!n",

%));

The <searchrock section tells the MUD what function it is to call whensomeone attemts to search the rock. Much like with reset and afterreset, weneed to ro%ide the code to handle this, but the MUD ensures it gets e$ecutedat the right time. #ou can do the same thing with any %erb ) the < notationlets you define a function for each of these.

Pro6in Dark De*ths

/et's start off with a %ery simle definition of the searchrock function ) itwon't do much at all, but it'll %erify that what we ha%e is correct so far?

int search_roc*() {tell_oect (this_player(), "There doesn+t seem to e anything in the ""roc*.n");

return #;%

Michael >eron #age 58

Page 60: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 60/150

LPC For Dummies 1, Second Edition

The tellobject function sends a message to the object ro%ided as its firstiece of information ) thislayer67 is a secial iece of code that refers towhate%er layer 6or "+7 was resonsible for causing the code to trigger.*e'll return to thislayer67 somewhat later ) it's a bit more comlicated than

I ha%e made out here.The second art of tellobject is the te$t we want to send to the secifiedobject.

Udate the room, and search the rock. #ou should see the message you setechoed back to you. That gi%es us our starting oint ) we're going to dosomething a bit more ad%enturous though. 4earching is no fun unless youha%e a chance of finding something interesting.

:ere's what we're going to do ) we're going to do a skill check on a layer tosee whether or not they find the secret hole in the rock. If they do, we willreward them with a 4hiny 8enuan ent. If they don't ass the check, theydon't get a thing. 0lso, we're going to make it so that this shiny coin can onlybe found once er reset eriod ) that stos eole continually searching therock for infinite 6albeit slowly accumulated7 money.

It's a fairly comle$ task, one that re-uires us to in%estigate a few new bits ofsynta$ and make use of a new MUD handler ) the taskmaster.

 !he !askmaster

The taskmaster is the thoroughly ingenious iece of code that is resonsiblefor determining whether or not skill checks ass or fail, and ro%iding skillawards where aroriate. In order to make use of it, we need to include theright header file at the to of our room?

>include Ctas*s.hD

The taskmaster has a number of methods that can be used to erform askillcheck. *e're going to in%estigate the simlest synta$, that which is used

to make a check against some reset difficulty factor.The code we need for this is erformtask, and is used like so?

int success;success N T-BHL9Dperform_tas* (this_player(), "other.perception", #$$,T_MUH);

Michael >eron #age 69

Page 61: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 61/150

LPC For Dummies 1, Second Edition

The first bit of information we ro%ide is the object against which we checkthe skill 6in this case, it's thislayer677. The second is the skill we want tocheck against 6other.ercetion7. The third is the bonus at which the task hasa chance of succeeding. The last is a secial %alue that determines how likely

a skill increase is... ignore that for now, we'll just ut it as TM5IS1D 6that's adefine set in tasks.h7.

The %alue that comes out of erformtask is a number that indicates the resultof the check ) at its most basic, it's either an 0*0;D 6a tm increase7,4U11D 6the check assed7, or 50I/ 6the check failed7. *e need to ro%idethe aroriate beha%iour to deal with the result. *e can do it using thesynta$ we already know, but it's a bit clumsy?

int search_roc*() {int success;

int found;

success N T-BHL9Dperform_tas* (this_player(), "other.perception",#$$, T_MUH);

if (success NN -G-L) {tell_oect (this_player(), "VW2H55KGVWVW6K5VW2ou feel a little more ""perceptive.nVWLHBHTVW");

found N #;%else if (success NN B'11HH) {found N #;

%

else {found N $;%

if (found) {tell_oect (this_player(), "2ou have found a shiny Eenuan cent!n");this_player()9Dadust_money (#, "Eenuan cent");

%else {tell_oect (this_player(), "2ou don+t find anything in the roc*.n");

%

return #;%

"ote that if we ha%e an award, we ro%ide the TM message and we also ha%eto colour it ) that weird looking collection of symbols 6known as +inkfisholour oding7 is how we add colour to a message. In general, you don't dothis. olour is roblematic for clean MUD design, so unless you ha%e a reason,

 you shouldn't. Taskmaster awards are one of the few areas that are ane$cetion to this general rule.

4ince we need to handle it for a taskmaster message, you surround the te$t you want to change the colour of in this secial code, and end it with a;141T. If you wanted to dislay something in red, you'd do?

Michael >eron #age 6,

Page 62: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 62/150

LPC For Dummies 1, Second Edition

VWLHVW6ing!VWLHBHTVW

This is something you should recogni9e rather than use yourself ) the solee$cetion in day to day creating life is in a TM message.

#witchin !hins ,round

The structure we ha%e in lace here is rather clunky ) luckily /+ ro%ides uswith a more elegant alternati%e ) the switch statement. 0 switch is essentiallya comact reresentation of a comle$ if, elseif, else structure. 5irst, wechoose a %ariable to switch on ) in this case, it's success. *e then define a

case for each of the ossible alternate %alues the switch %ariable may ha%e.The code that follows the case will be the code that is e$ecuted if the switch %ariable has the secified %alue.

success N T-BHL9Dperform_tas* (this_player(), "other.perception", #$$,T_MUH);

s&itch (success) {case -G-LItell_oect (this_player(), "VW2H55KGVWVW6K5VW2ou feel a little more ""perceptive.nVWLHBHTVW");

case B'11HHI

found N #;rea*;case M-5Ifound N $;

rea*;%

4witch statements are somewhat more fle$ible than if statements, becauseeach case is fall/through. That means that when the MUD finds a matchingcase statement, it e$ecutes that statement and e%ery statement that followsuntil it finds a line of code marked as break .

5or the abo%e code, if the result is an 0*0;D it will dislay the TM message,and then continue on to the ne$t case statement 64U1447. 4o getting an

 0*0;D gi%es the TM message and sets the found %ariable to 2. It then stos,because it hits a break. If the result is 4U144, it sets the found %ariable to2 and then stos. If it's a 50I/, then it sets the found to H.

*e can add a general catchall to a switch by adding a secial default case.*e can use this to deal with results we didn't anticiate.

Michael >eron #age 6-

Page 63: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 63/150

LPC For Dummies 1, Second Edition

s&itch (success) {case -G-LItell_oect (this_player(), "VW2H55KGVWVW6K5VW2ou feel a little more ""perceptive.nVWLHBHTVW");

case B'11HHIfound N #;

rea*;case M-5Ifound N $;

rea*;defaultItell_creator ("dra**os", "2eah, don+t *no& &hat happened here.n");

%

 0side from this new structure, the code should be fairly self e$lanatory ) if

the skill check succeeds, the layer gets a shiny 8enuan cent. If it failed, theyget nothing.

*e're almost there ) at the moment you can search this rock as many times as you like, finding a cent each time if you ass the skill check. This is a rock, nota "orthern ;ock 6teehee7. *e should make it so that we can only find the coinonce er reset.

#co*in !hins Out

4o, how do we do thatJ The ob%ious thought is to use a %ariable ) somethinglike found, in fact. :ow about if we just ut a check at the to to see if foundhas been set to 2... will that workJ

int search_roc*() {int success;int found;

if (found NN #) {tell_oect (this_player(), "t loo*s li*e the roc* has already ""een searched.n");

return #;%

success N T-BHL9Dperform_tas* (this_player(), "other.perception", #$$,T_MUH);

s&itch (success) {case -G-LItell_oect (this_player(), "VW2H55KGVWVW6K5VW2ou feel a little more ""perceptive.nVWLHBHTVW");

case B'11HHIfound N #;

rea*;

case M-5I

Michael >eron #age 60

Page 64: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 64/150

LPC For Dummies 1, Second Edition

  found N $;rea*;defaultI

tell_creator ("dra**os", "2eah, don+t *no& &hat happened here.n");%

if (found) {tell_oect (this_player(), "2ou have found a shiny Eenuan cent!n");this_player()9Dadust_money (#, "Eenuan cent");

%else {tell_oect (this_player(), "2ou don+t find anything in the roc*.n");

%

return #;%

 0las, it turns out no. The code doesn't seem to do anything. *hy is thatJ

The answer lies in a rogramming concet called scope. 1%ery %ariable that iscreated takes u memory on the comuter in which the rogram is running.This is true regardless of whether the code is on a MUD or on your owncomuter.

In order to ensure that this memory is made a%ailable when you are finishedwith it, the comuter frees u the memory it has allocated once the %ariablefalls out of scoe. ariables that are defined within a function are called local

 variables, and e$ist only as long as that function is e$ecuting. (nce yoursearchrock function has finished e$ecuting, the memory location occuied bythe found %ariable is released. Then, when it is searched again, a new %ariableis setu and starts with the %alue H until it is again set by later code. Thescoe of the %ariable is the function in which it is defined. That also meansthat you cannot make use of that %ariable in other functions.

*e can mo%e a %ariable declaration to the start of the object itself, after theinherit and before the setu?

>include Ctas*s.hD>include "path.h"

inherit "/std/room/outside";

int found;

void setup() {

This increases the scoe of the %ariable to be class/wide. It is a%ailable to allfunctions, and ersists as long as the object is loaded. 1%ery function canchange the state of the %ariable, but that %alue the %ariable gets ersists aslong as the object is loaded. 4ounds like just what we need!

Michael >eron #age 63

Page 65: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 65/150

LPC For Dummies 1, Second Edition

Udate your room and search the rock ) find the cent the first time, andsearch again ) you'll get the message that indicates the rock has already beensearched. 0 win!

The last art of getting this working roerly is to reset the %alue of found

e%ery time reset is called. That bit, at least, is easy?

void reset() {IIreset();found N $;

%

 #ou can test this -uite easily ) udate, search the rock, search it again and getthe 'already searched' message. Then, call reset on the room manually?

call reset() here

 0nd search once more. #ou'll find the cent again, as if the roer reset eriodhas assed. +retty nifty, ehJ

Conclusion

*e're starting to ick u seed in our discussion of /+ ) in this chater

we'%e learned about mo%ement 9ones, the taskmaster, search additems,switch statements and %ariable scoe. That's a lot to digest, and you may wantto ste away from the tutorials at this oint to allow the information to sink it.It's a good idea to ractice with all of this ) try setting u other searchableitems in other rooms. +ractise is the way to gain understanding, after all.

 #ou should be feeling -uite roud of yourself at this oint ) you're starting toadd some fairly sohisticated beha%iour to your rooms, and your caabilitiesare only going to grow as we continue.

Michael >eron #age 65

Page 66: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 66/150

LPC For Dummies 1, Second Edition

0ow !hat $e+re ,n 'tem

'ntroduction

4o, we'%e got an "+, and we'%e got some rooms ) the ne$t thing we need tolearn how to de%elo is an item. This is somewhat more comlicated thande%eloing either of the others because of the sheer %ariety of items that cane$ist ) clothes, weaons, armours, backacks ) all of them are created usingdifferent inherits and code. There are some commonalities to be sure, but theyeach ha%e their own little -uirks that you need to learn.

More than this, there are two entirely different ways of creating items ) oneway is a %ariation of what we'%e done before ) we write an object, and clone itwhen we need it. The other way is using the MUD's %irtual item system. *e'lldiscuss both of these in the course of this document.

&irtuall" #elf845*lanator"

In the long descrition we wrote for atain eefy, we mentioned his deearanoia about layers stealing his shoes ) we ha%e not, howe%er, ro%ided

him with any. That's because we're going to write a uni-ue air of shoes foreefy. The won't do anything secial, they'll just ha%e a uni-ue descrition.

1%ery object that is loaded on the MUD takes u memory on the system )because there are 4o Many Items carried by 4o Many "+s and +layers,there's a huge erformance gain to be had by reducing the memory re-uiredfor these items. The irtual Item system was introduced to reduce the memoryload on oor 0'Tuin.

;emember how we talked briefly about the idea of a master object from whichwe create clonesJ 1%ery .c file that is loaded on the MUD is a master object,and a master object comes with a memory burden. irtual objects are just

clones of an already e$isting master object, with all the functions we'dnormally associate with setu 6such as setting the name, short, and so on7 arehandled by the MUD as a series of calls. That may sound confusing, so I'll gi%ean actual e$amle of what this does when we'%e discussed our first %irtualobject.

 irtual object code files don't look like normal code files ) they ha%e their ownsynta$, and that can be -uite confusing. They also ha%e an e$tension otherthan .c, and the e$tension tells the MUD what kind of object we're workingwith. The basic e$tensions you'll be working with are as follows?

Michael >eron #age 66

Page 67: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 67/150

LPC For Dummies 1, Second Edition

01tension 2ype of Item In/3ame directory

.clo lothing &obj&clothes

.arm 0rmour and >ewellery &obj&armours and&obj&jewellery

.we *eaons &obj&weaons

.food 5ood &obj&food

.sca 4cabbards &obj&scabbards

There are more of these, but we're only going to discuss clothing in this

section. #ou should browse the indicated directories for e$amles of otherkinds of %irtual objects.

(kay, let's start by creating a new directory in our learn%ille directory ) thisone will be called items.

m*dir /&/your_name_here/learnville/items

 0nd we'll need to add a new entry to our base ath.h file in&w&yournamehere&learn%ille&?

>define THB ?-T@ A "items/"

"ow, create this file in your new directory, under the name beefyboots.clo?

IIFameII"oots"IIBhortII"pair of eefy leather oots"II-dectiveII({ "pair", "of", "eefy" %)IIain_pluralII"pairs of eef leather oots"II?luralII"oots"

II?lural -dectiveII "pairs"II5ongII"This is a pair of extremely eefy leather oots. - person &ould ""need to e very eefy indeed to &ear these!n"

IIaterialII"leather"IIGeightII8IISalueII3$$$$$IITypeII"oot"IIBetupII3$$$IIamage 1hanceII#<

Michael >eron #age 6"

Page 68: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 68/150

LPC For Dummies 1, Second Edition

That, my young friends, is a %irtual object. 0lthough it looks entirely differentfrom the /+ code with which you are slowly becoming accustomed, youshould be able to see commonalities. irtual files come as a list of settings,with the %alues those settings are to ha%e. *e udate these %irtual files in the

same way as we do normal files, and we likewise clone them in the same way )clone a air of them into your in%entory once you'%e udated them.

5rom the ersecti%e of the erson who has them in their in%entory, they areindistinguishable from normal /+ objects. That's because that's e$actly whatthey are ) they're just written in a different way, and the MUD creates them ina different, more efficient way.

*hen you tell the MUD to clone a %irtual item, it is the e$tension of the filethat tells it what base object it needs to make a clone of ) in the case ofclothing, it's &obj&clothing.c. It just takes a coy of this object, which has allthe functionality but none of the configuration details, and it takes your %irtual

file as a temlate for what it should do with it.It the goes o%er each of the lines in the %irtual file you ga%e it. The resence ofthe double colons gi%es a set attern for the MUD to arse ) It knows that thewhate%er comes between the first set of double colons and the second set isthe name of the setting it needs to change, and whate%er comes after thesecond set of double colons is the %alue that setting should ha%e.

*hen it encounters the setting marked name, it knows that it translates thatinto calling set$name on the object it has cloned. The %alue for the setnameis what follows the second set of double colons. /ikewise, when it gets to thesetting short, it knows to call set$short.

Don't coy the ne$t bit of code into your roject, it's for e$lanation only.1ssentially cloning this %irtual clothing file is the same thing to you doing thefollowing?

object ob = clone_object ("/obj/clothing");

ob->set_name ("boots");ob->set_short ("pair of beefy leather boots");ob->add_adjective (({"pair" "of" "beefy"!));ob->set_main_plral ("pairs of beefy leather boots");

ob->add_plral ("boots");ob->add_plral_adjective ("pairs");ob->set_long ("#his is a pair of e$tremely beefy leather boots% & ""person 'old need to be very beefy indeed to 'ear thesen"

ob->set_material ("leather");ob->set_'eight (*);ob->set_vale (+,,,,);ob->set_type ("boot");ob->setp_armor (+,,,);ob->set_damage_chance (.);

Michael >eron #age 6&

Page 69: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 69/150

LPC For Dummies 1, Second Edition

It robably won't be ob%ious at this oint why this is a good way to do things )trust me when I say though it sa%es on the memory the MUD uses, and that'sa %ery good thing. The MUD routinely sits at around two and a half gigabytesof memory usage, and it would be a great deal higher still if it weren't for

systems like this to kee the re-uirements low.

But what does it all mean2

I'm going to assume most of what these functions do is selfe$lanatory...there are some howe%er that are worth sending a little more time del%inginto so as to understand how to create effecti%e items.

The weight of an object is measured in weight units. 1%ery item that is to ha%eweight 6and e%ery item should7 will ha%e to weight a minimum of one weight

unit. In real terms, a weight unit translates into BH grams of weight. In thecase of our shoes then, they weight C F BHg for a total of 3HH grams.

The %alue of the boots is the %alue in money units ) one oint of currency ise-ui%alent to one brass coin. There are four brass coins to an 0M +enny, andthree brass coins to a 8enuan cent. heck help currency  for a full listing ofhow %aluable %arious currencies are. eefy's boots are worth @HHHHH brasscoins, which works out to BHH 0M dollars. "o wonder he was so afraid eolewould steal them!

lothes get damaged as their wearer takes damage, and so they need to ha%ea condition set ) it is setuarmour that gi%es the ma$imum condition of the

item. In this case, the clothing has @HHH condition oints. 5or comarison, theobsidian boots you may ha%e encountered in the game ha%e a condition ofCAHH.

The last bit, setdamagechance, sets how much damage the item absorbs. (rmore correctly, it sets how much damage the item lets through when it itselfis damaged. The following chart 6from hel setdamagechance7 gi%es youguidance on what those %alues should be?

Material 4amage Chance

loth @H

:ide 2

one 2C

/eather 2B

*ood 2@

oer 2H

ron9e E

Michael >eron #age 68

Page 70: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 70/150

LPC For Dummies 1, Second Edition

Iron C

4teel B

Klatchian 4teel 3

4tone 3

(ctiron H

Thus, the lower the damage chance, the better rotection the item offers. e %ery wary of de%iating from these %alues our standards e$ist for a reason.

The directory &obj&clothes is the reository for all the ingame clothing thathas been written, and you should consult the aroriate subdirectoy in therefor guidance as to what %alues you should set for your %alues. 8oing by what'salready there is always the best way to design new items in truth, you're notgoing to care about these %alues %ery much, so just coy %alues that ha%ealready been aro%ed.

 irtual files are erfect for ro%iding simle beha%iour, but they do not offer afacility for more comle$ beha%iour. 1ssentially anything that in%ol%es youadding commands, secial defences, or general 'less than usual' functionality.5or that, we must rely on a standard .c file. *e'll see that in ractise when werogress onto /+ 5or Dummies @.

Beef"+s Boots

"ow that we ha%e a air of delicious beefy boots for our "+, let's gi%e themto him! 4adly, we can't do this through the armoury. "ot yet.

The armoury works only on 'li%e' code ) in general we don't want ersonalcreator code 6residing in &w&7 to be handled through the armoury. Thearmoury makes a list 6and checks it twice7 of all the items in the in gamedirectories 6such as &obj&clothes, &obj&armour, and so on7 and then a list of allthe items a%ailable to the domain items directories 6&d&forn&items, d&am&items,

and so forth7. *hat it doesn't do is make the code in your home directorya%ailable, or code that is in nonsuorted directories 6all domain objects ha%eto be in &d&domain&items or a subdirectory, for e$amle7.

*e're thus going to ha%e to handle the ro%ision of a air of boots manually.5irst, we make oursel%es a container for the boots at the to of eefy's setu?

oect oots;

Then we clone the boots using the IT1M4 <define we added earlier. 5irstthough we'll need to add a <include to our ath.h at the to of his file, since

we currently don't ha%e one.

Michael >eron #age "9

Page 71: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 71/150

LPC For Dummies 1, Second Edition

oots N clone_oect (THB A "eefy_oots.clo");oots9Dmove (this_oect());

Dest and udate eefy and the room from which he is cloned, and you'll findhe's now wearing the lo%ely boots we created for him!

Blin

/et's ha%e a look at a second kind of item created using the %irtual objectnotation ) we're going to gi%e eefy a ring that was gi%en to him by his DearlyDearted wife. 0ny layer who kills him for his jewellery will thus feel like a;eal astard.

 >ewellery is created according to the same basic system, although thesecifics of the setu are slightly different?

IIFameII"ring"IIBhortII"eefy diamond ring"II-dectiveII({"eefy", "diamond"%)II?luralII"e&ellery"II-liasII "e&ellery"IIlongII"This is a eautiful golden ring set &ith a gleaming diamond. ""t smells vaguely of eef.n"

IIGeightII#IISalueIIO$$$$II?ropertyII"shop type", "e&ellers"IITypeII"ring"IIBetupII3$IIamage 1hanceII:IIaterialII"gold"

Most of this should be fairly ob%ious by now ) it shares most of the settingswith clothing. The +roerty tag here sets the item as being jewellery. Thischeck gets used in a few laces for e$amle, the wi9ard jewellery bloring

sell checks this roerty to see if it's a %alid target for the sell, and otherlaces use it to tell what kind of skills are used to reair, and so forth.

:ow do eole know this is a ring gi%en to him by his dead wifeJ *ell, let'sadd an engra%ing to it so that eole can read the lo%ing message she left forhim. *e can do this directly in the %irtual file, if we like?

IILead essII "Mrom your dead &ife.", "neat engraving", "morpor*ian"

Michael >eron #age ",

Page 72: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 72/150

LPC For Dummies 1, Second Edition

The first art is the deely mo%ing message. The second is how the writing isdescribed when someone reads it, and the third is the language in which themessage is written. ;eading this ring thus will gi%e the following?

D read eefy ring

2ou read the eefy diamond ringI Gritten in neat engravingI Mrom your dead&ife.

Tragically mo%ing, isn't itJ

It's not usually a good idea to include such a read message in the base file,because as far as ossible %irtual files should be entirely generic for what theyare. If we include it in the base file, then anyone who gets a eefy ;ing gets itinscribed with the beautiful oetry of eefy's wife.

Instead, we can configure this message after the ring has been cloned ) thatway the basic ring is defined and usable by anyone, but only eefy's ring hasthe engra%ing.

*e make the ring a%ailable to eefy in e$actly the same way as we made theboots a%ailable. *e define an object at the to of his setu?

oect ring

Then we clone and mo%e that ring into him?

ring N clone_oect (THB A "eefy_ring.arm"); ring9Dmove (this_oect());

 0nd then we manually add the read message afterwards?

ring9Dadd_read_mess ("Mrom your dead &ife.", "neat engraving", "morpor*ian");

 0lmost e%ery item in the game can ha%e a read message attached to it in thisway, and it's a nice way to add a little bit of sarkle to otherwise nonsecificitems.

Michael >eron #age "-

Page 73: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 73/150

LPC For Dummies 1, Second Edition

, $ord Of $arnin ,6out 'tems

In order to achie%e a measure of consistency across the Disc, there are somestrict guidelines about what the ma$imum accetable %alues for %arious

settings. 0s such, before they go into the game all such items ha%e to bearo%ed by a entral 0uthority. This makes sure that the little knife youcasually gi%e to an "+ isn't inad%ertently more owerful than the highendmagical dagger eole need to send hundreds of dollars to obtain.

In general, it's better to make use of the large number of items we alreadyha%e a%ailable than code one from scratch. (b%iously there are sometimes

 %ery secific uroses for new items to e$ist ) you'%e coded a new sho, or anarea has a thoroughly different feel from the rest of the areas on the Disc andneeds an infrastructure of items to suort that. "ew items are always goingto be a art of new de%eloment, and they should be ) ha%ing new and

interesting things a%ailable is art of what dri%es layers to e$lore newareas.

(n the other hand, we also want to make sure that the resources we alreadyha%e are roerly utilised. 4end some time becoming familiar with what thearmoury has a%ailable before you add your own 'black silk shirt' ) the chancesare something that meets your needs already e$ists.

If it doesn't, then write away ) it's worth consulting with whoe%er isresonsible for administering the aro%al of the tye of objects you arede%eloing to see what guidance they ha%e for you. They may be able to direct

 you to resources suitable for what you need, or let you know of currentaccetance criteria for new items. (r they may just be able to gi%e you usefulad%ice on how to ut them together.

Conclusion

*e'%e looked at two kinds of item here ) a air of boots, and a ring. 0ll %irtualobjects work on largely the same general rinciles ) a file contains a numberof settings and the %alues those settings ha%e. The MUD works out what kindof base object is needed from the e$tension the %irtual object has. It then

clones an instance of the base file and configures it with calls 6rather thancreating a new master object7. 0s far as anyone using the item is concerned, itworks identically to any other object written in /+.

There is a need for care in de%eloing items on Discworld, for it is %ery easy touset the delicate balance we ha%e between the items that e$ist currently andthe new items being introduced. 1%en comarati%ely minor changes to the

 %alues relati%e to other items can ha%e unusually large conse-uences. #our5riendly Item 0ro%al ;eresentati%e will be able to gi%e you formalguidance on what is, and is not, accetable.

Michael >eron #age "0

Page 74: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 74/150

LPC For Dummies 1, Second Edition

,n 'nside 9o6

'ntroduction

*e'%e got the skeleton of our outside rooms in lace already ) in this chaterwe're going to look at de%eloing our first inside room ) an item sho in whichwe can make a%ailable any further items we de%elo. 0s a rocess, this is alargely identical to creating an outside room, e$cet that we ha%e the e$traste of setting u stock. *e'll ha%e cause to encounter some new concets aswe go through this chater, so there's lenty for us to talk about.

*e're actually going to ut in the base code for two rooms ) one is a %anillaroom that has no secial functionality e$cet for a locked door leading to it.The second is the item sho. (n our %illage ma 6remember that fromchaters two and threeJ7, these will be rooms 0 and , and ha%e the followingfilenames?

Map 5ey #ilename

 0 mysteriousroom.c

stabbyjoe.c

4o, with no further ado, /et's 8et To It!

 !he M"sterious oom

5irstly, let's create the temlate for the mysterious room. 1%erything we'%etalked about for our outside rooms works for our inside rooms, but we inherit&std&room&basicroom instead of &std&room&outside. 4o, for the mysteriousroom?

>include "path.h"

inherit "/std/room/asic_room";

void setup() {set_short ("mysterious room");add_property ("determinate", "a ");set_day_long ("This is a mysterious room during the daytime. t fairly ""ree*s of mystery.n");

set_night_long ("This is a mysterious room during the nighttime. The "

Michael >eron #age "3

Page 75: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 75/150

LPC For Dummies 1, Second Edition

  "oppressive dar*ness hints mysteriously at mystery!n");

add_day_item ("mystery", "aytime all around, and yet you cannot see it.");add_night_item ("mystery", "2ou can+t see the mystery for all the ""dar*ness.");

room_day_chat ( ({ #3$, 34$, ({"The room emits a sense of mystery.","Fo dout aout it, this is a mysterious room.",

%)%));

room_night_chat ( ({ #3$, 34$, ({"Gas that a mystery there, glinting in the dar*nessR","aye the mystery is a grueR",

%)%));

set_light (#$$);

add_exit ("south", LKKB A "mar*et_north&est", "door");%

"otice here that the e$it we add is of tye 'door' ) that means retty muchwhat you'd e$ect it to mean ) the e$it is blocked by a door. *e need to matchthis u with a corresonding e$it in marketnorthwest.c?

add_exit ("north", LKKB A "mysterious_room", "door");

*e'%e created a door, but it isn't locked. In order to maintain the mystery ofthe door, we can use modifye$it to lock it shut. ;emember how I said earlierthat modifye$it had all sorts of cool and interesting owersJ *ell, let's take alook at what we can do with our mysterious e$it here, to heighten it's mystery!

Modif"in 45its

The settings to modifye$it come as a listing of airs of settings and %alues.*ith it, we can change the messages eole see when they mo%e through the

e$it, what they see when they look at the e$it, and how it beha%es wheneole try to walk through it. *e can e%en add comlicated code handlers toan e$it ) you can control e$tremely recisely under what conditions an e$itmay be taken. If you want it to be imossible to take an e$it while you'recarrying iron in your in%entory, you can do that. If you want to make it so thatentry is ermissible only on the @Bth day of (ffle +rime, you can do that too.*e won't talk about that in this section, but we will in a later section of /+for Dummies.

The simlest settings just re-uire some numbers and te$t to describe whatshould haen. /et's begin simly ) let's change how the door aears when

eole look at it. In marketnorthwest's setu, we add the following?

Michael >eron #age "5

Page 76: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 76/150

LPC For Dummies 1, Second Edition

modify_exit ("north",({"door long", "The door hints at mystery &ithin. Liches too, most ""li*ely.n",

%));

"ow, when we look north we'll see?

D loo* north

The door hints at mystery &ithin. Liches too, most li*ely. t is closed.

If you go north, and look south howe%er, you see?

D loo* south t+s ust the south door. t is closed.

The modify e$it thus must go in both rooms to which it alies ) that way youcan ha%e doors that ha%e one descrition on one side, and a different one onthe other. In mysteriousroom thus?

modify_exit ("south",({"door long", "The door hints at mystery &ithin. Liches too, most "

"li*ely.n",%));

If we want to lock it 6and we do7, we add the locked setting to our modifye$it) a 2 indicates the door is locked, a H indicates it is not. *e also need toro%ide the name of a key that will oen the door?

4o, in marketnorthwest?

modify_exit ("north",({"door long", "The door hints at mystery &ithin. Liches too, most ""li*ely.n",

"loc*ed", #,"*ey", "ysterious Loom ey",

%));

mysteriousroom will ha%e an identical modifye$it, e$cet that it will modifythe south e$it rather than the north one. Udate our rooms, and %oila! The

door is locked.

Michael >eron #age "6

Page 77: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 77/150

LPC For Dummies 1, Second Edition

/ocked doors can be a ain in the backside for a creator, so you can gi%e yourself the ability to walk through such doors by adding the demon roertyto yourself?

call add_property ("demon", #) me

The key to this door is something we're going to make a%ailable in our sho...a key is any object that has a roerty matching the name we'%e gi%en to thekey in our modify e$it. *hen the layer attemts to take the e$it, the MUDlooks through all the items on that layer for anything that unlocks the door.

 #ou can see this in action by icking any random item in your in%entory andusing the following call?

call add_property ("ysterious Loom ey", #) random oect

Make sure you remo%e the demon roerty from yourself though, or you'll justghost through the door as before?

call remove_property ("demon") me

Modifye$it lets us do much more than we'%e done here ) we can set a door toautomatically lock after we close it with the autolock setting 62 indicating itautolocks, and a H indicating it doesn't7. *e can set a difficulty for eoleattemting to lockick the door using the difficulty setting ) you gi%e this a

 %alue from 2 to 2H The lower the %alue, the easier the lock is to lockick.

*e can also change the messages eole see when objects ass through thedoor by setting three %alues in the same manner as we did for eefy's mo%emessage. 5or e$amle, we could do the following in marketnorthwest?

 "enter mess", "PF mysteriously enterPs the room. @o& mysterious!","exit mess", "PF exitPs through the mysterious door. Ghat &onders ""must e found &ithinR",

"move mess", "2ou &al* through the door, excited y the possiilities X&ithin!n",

 0nd in the mysteriousroom?

"enter mess", "PF mysteriously enterPs from the mysterious door. Ghat ""&onders &ere seen on the other side of that portalR",

"exit mess", "PF exitPs through the mysterious door.","move mess", "2ou leave the room, satisfied its mysteries have een ""revealed to you.n",

Michael >eron #age ""

Page 78: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 78/150

LPC For Dummies 1, Second Edition

1nter mess is what eole see when someone arri%es in a room through thee$it. 1$it mess is what eole see when someone lea%es through the e$it.Mo%e mess is what gets dislayed to the layer.

4o, we'%e gi%en the door to our mysterious room enough mystery for now.

/et's make the key a%ailable to those who may be temted to e$lore.

#ho* +!ill -ou Dro*

*e're going to create an item sho here, which is a sho that sells but doesnot buy. The inherit we use for this is &std&itemsho. /et's create the basictemlate for that room, and hook it u to our marketlace?

>include "path.h"

inherit "/std/item_shop";

void setup() {set_short ("Btay Yoe+s Hmporium of Gonder");add_property ("determinate", "");set_long ("This is Btay Yoe+s Hmporium of Gonder, &here he sells ""&onderful things. @e also stas people.n");

set_light (#$$);add_exit ("south", LKKB A "mar*et_northeast", "door");

%

 0nd in marketnortheast, we need an e$it linking back to the sho we'resetting u?

add_exit ("north", LKKB A "stay_oe", "door");

Udate both rooms, and wander into the sho. #ou'll find that you can 'list'and 'browse' e%en though you ha%en't written any code to do that ) all of thecode for handling the commerce is ro%ided by the inherit we selected.

*e can add stock to the room by including an addobject call in the setu,detailing the armoury name of the item we want to add, and how many of theitem should be in stock. The item's internal %alue will dictate how much theitem costs.

/et's add a long sword to the stock, to see this in action?

add_oect ("long s&ord", );

Udate and 'list', and you'll find that the sho now has three longswords forsale. 0las, they are on sale for ro%incial money?

The follo&ing items are for saleI-I a long s&ord for #3 silver coins (three left).

Michael >eron #age "&

Page 79: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 79/150

LPC For Dummies 1, Second Edition

The sho has no idea where in the game it actually is ) it could be in 0nkhMorork, it could be in 8enua... it could be a sho that trades only in 8enuanmoney but is found in /ancre Town. *e need to hel the sho with its identitycrisis by telling it what kind of money it should accet, and we do that by

adding a lace roerty?

add_property ("place", "Eenua");

(ther %alid laces that can be set?

Place Currency 6sed

/ancre rowns and 4hillings

8enua Ducats and /i%res

 0nkhMorork ;oyals and Dollars

ounterweight ontinent ;hinu and such

Djelibeybi Talents and Tooni

The caitalisation here is imortant ) you won't get the results you're lookingfor if your lace roerty doesn't match the area e$actly.

Udate again with one of these set and you'll see the urrency of the ;ealmchange according to where you tell the sho it may be found. 5or the urosesof the rest of this tutorial, I'm going to assume you'%e set the currency to be8enuan.

/et's add something else to our sho, to increase its interest a bit more.Unfortunately, the item sho only works with a restricted subsection of what'sa%ailable in the armoury ) it'll work for weaons, armours, scabbards, clothes,foods, jewellery and a few other things, but it won't automatically allow forobjects to be added if they reside in a domain . If we want to ull things out of

a secific domain, we can set an 'object domain' to comlement the selectiona%ailable. 5or e$amle?

set_oect_domain ("forn");

"ow, let's add something that's a%ailable in the forn domain ) secifically, the jack in the bo$. :owe%er, let's add it in a slightly different way by gi%ing thesho a slightly randomised amount of the object for sale. *ith the longsword,there will always be three of these until the sho stock resets. *e can add a

bit of randomness to this by using the MUD's random number generator, likeso?

Michael >eron #age "8

Page 80: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 80/150

LPC For Dummies 1, Second Edition

add_oect ("ac* in the ox", 3 A random (3));

The random number generator on Discworld generates a whole numberbetween H and the number you gi%e it, not inclusi%e) in this case, it'll generateeither H or 2 and add that to the @ we already ha%e. (ur sho thus has either @or 3 of these objects a%ailable.

#ta66" 9oe

The MUD won't force you to ha%e a shokeeer for the sho, but it's a goodidea to ha%e one ) it adds a sense of immersion that is otherwise lacking. 4o

let's create our second "+ ) 4tabby >oe! :e's going to be our shokeeerand resident sycho. *e're going to gi%e him an addresondtowith for hiscousin, but we're not going to do anything with it right away. 4a%e him in yourchars directory under the name joe.c?

void setup() {set_name ("oe");set_short ("Btay Yoe");add_property ("determinate", "");add_property ("uni0ue", #);add_adective ("stay");add_alias ("stay");

set_gender (#);set_long ("This is Btay Yoe, 5earnville+s main shop*eeper and ""resident psycho. Ghile generally at peace, he can e riled ""into fits of to&ering rage y ma*ing reference to his cousin, ""Blicey ?ete.n");

asic_setup ("human", "thief", #<$ A random (#$$));setup_nationality ("/std/nationality/genua", "genua");

load_chat(#$, ({#, "+ 6uy my stuff, or +ll *ill you.",#, "+ Eood prices on all my stuff! f you can find anything cheaper ""in all of 5earnville, +ll *ill you!",

#, "+ Batisfaction guaranteed, or +ll *ill you!",

%));

load_a_chat(3$, ({#, "+ cut cut cut cut cut cut cut cut!",#, "+ Eods, that &as violent! lame... the sea!",

%));

add_respond_to_&ith(({"Jsay",({"slicey"%),({"pete"%),

%),

">cousin_response");

Michael >eron #age &9

Page 81: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 81/150

LPC For Dummies 1, Second Edition

  re0uest_item ("lac* leather trousers", #$$);re0uest_item ("lac* sil* shirt", #$$);re0uest_item ("lac* soft9soled oots", #$$);

init_e0uip();%

1%erything here is 0s *e Know It. *e also know how to load 4tabby >oe ) weuse a %ariation of the code we'%e already seen for atain eefy. 0s such, wecan include the following in stabbyjoe.c 6the item sho7 to load him?

void reset() {IIreset();call_out ("after_reset", );

%

void after_reset() {oect stay;stay N load_oect (1@-LB A "oe");

if (stay QQ environment (stay) !N this_oect()) {stay9Dmove (this_oect(), "PF appearPs &ith a pop.","PF disappearPs &ith a pop.");

%%

Udate the room, and there's our shokeeer. The only roblem is, he's not

actually keeing the sho. :e's just in the room. *e can kill him, and yet stillinteract with the room erfectly normally. That's not -uite what we want ) wewant the fate of the sho to be tied to the fate of >oe. :owe%er, doing that is adiscussion for the ne$t section!

Conclusion

In this section of the notes we'%e e$lored a little more of the ower a%ailablein modifye$it, and set u an item sho comlete with stock. In the ne$t

section, we're going to look at filling out the functionality that's missing here )we're going to need to discuss a new toic in the ne$t section, one that'shoefully going to tie u a lot of what we'%e been doing into a cohesi%e whole.

Michael >eron #age &,

Page 82: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 82/150

LPC For Dummies 1, Second Edition

D"sfunctional Beha/iour

'ntroduction

In this chater we're going to talk about something that will hoefully clarifyhow e%erything on Discworld actually fits together. (f a necessity, we ha%e tobe -uite selecti%e in the theory we co%er in this te$t ) we only introducetheory as it imacts on what it is we're trying to do in the e$amles. 0s such,there's a lot of 'ut this thing here in this way, but don't worry about why'.

:oefully after you'%e worked your way through this chater, a whole lot of

what you're doing will make more sense.

Our !ask

*e'%e left our sho, and 4tabby >oe himself, in a state of incomleteness. *ewant the sho to be oen based on 4tabby's resence in the room, and we alsowant 4tabby to fly into a fit of aolectic rage when his cousin, 4licey +ete ismentioned. oth of those things re-uire us to do more than set a few %alues ina file ) they need us to write actual code.

There's one lace already you'%e written actual code, and that's in thesearching of the rock in streetH3. 4ometimes we want to do something %erysecific in our areas, and in order to do that we need to go beyond the genericfunctionality ro%ided by our inherits ) for that we need to make use of arogramming system called functions. They are also sometimes calledmethods, and in this chater we will use the two terms interchangeably.

 !he #cience Bit... Concentrate%

 0 function is a little section of code that you tag by a name. #ou'%e alreadybeen writing functions ) setu and reset are functions, as is afterreset andsearchrock. These are functions that you write so that your rooms do what

 you want them to. 0t certain oints, the MUD will e$ecute the code that goeswith your function ) in technical jargon, the MUD calls your function. *hen

 you room is created, setu is called. *hen the MUD wants to reset theinternal state of your room, reset is called. #ou ha%e no control o%er these twoe%ents ) if you change the name of your setu function to setmeu, you'llfind the room doesn't work. This is a con%ention to which you must adhere.

Michael >eron #age &-

Page 83: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 83/150

LPC For Dummies 1, Second Edition

:owe%er, afterreset and searchrock are functions that you told the MUD tocall. 0s such, it doesn't matter what name you gi%e them as long as the nameis meaningful. 5or e$amle, with your afterreset you called it like so?

call_out ("after_reset", );

That sent a message to the MUD, telling it to call the afterreset function afterthree seconds. If you change it thusly?

call_out ("create_npc", );

It would instead call the createnc method. It's our choice what we call this

function ) afterreset is just an informal con%ention.

/ikewise, in your additem for the rock in streetH3?

add_item ("agged roc*",({"long", "This is a agged roc*.","searchale", ">search_roc*","position", "on the agged roc*",({"*ic*", "punch"%), "K&! That stung!n",

%));

The <searchrock string is what tells the MUD that you want to call a function6indicated by the < at the start7 and that function is called searchrock. #oucould change the name of the function to anything you like ro%ided you linkthe two u roerly?

add_item ("agged roc*",({"long", "This is a agged roc*.","searchale", ">find_penny",

"position", "on the agged roc*",({"*ic*", "punch"%), "K&! That stung!n",%));

 0nd then for your function?

int find_penny() {...

%

Michael >eron #age &0

Page 84: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 84/150

LPC For Dummies 1, Second Edition

 0s long as the name of the function you define is the same as the function youtell the MUD to call, e%erything will be hunky dory. :owe%er, the con%entionswe adot for naming these functions were adoted for a reason they make itconsiderably easier for eole to read and maintain code if they know where

they are to look for certain ieces of functionality.

 !he #tructure of a Function

 0 function has a %ery articular structure to which it must adhere whenwritten.

return_type name_of_function (parameter_list) { %

5irst, it must declare its return tye ) that's the kind of information thatcomes out of the function when it's finished. (ur searchrock function returnsa 2 to indicate success, and a H to indicate failure ) thus, we must tell theMUD that our function returns an int.

"e$t comes the name of the function ) we'%e already seen this in action andshould be familiar with it by now.

The arameter list is something we ha%en't encountered yet ) it's informationthat is ro%ided to our function by the code that calls it. 4ometimes the MUDro%ides information for you when you tell it a function is to be called at someoint. (ther times you ha%e to ro%ide it yourself.

 0 arameter list consists of air of %ariable tyes and names, searated by acomma. 5or e$amle, consider a %ery simle function that takes two wholenumbers and adds them togetherV

int add_numers (int num#, int num3) {%

The braces indicate the ownershi of a function ) all code that e$ists betweenthese two braces consist of the code belonging to it. These are the body of themethod. *ithin the body of the method, we cam make use of %ariables definedin the arameter list just as if they had already been defined and assigned

 %alues?

int add_numer (int num#, int num3) {return num# A num3;

%

Michael >eron #age &3

Page 85: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 85/150

LPC For Dummies 1, Second Edition

*hen the MUD gets to a return statement in the function, it stos e$ecutingthe code that belongs to to the function and returns whate%er %alue wasindicated to the code resonsible for calling the method.

4ome functions don't return any %alue, and we indicate those as being of

return tye void 6like setu and reset7. They re-uire no return statement inthe body of their code, and if you wish to terminate them before e$ecuting allof the code, you can use a return statement by itself?

return;

*e add functions to our code whene%er we want to make a certain iece ofcode reeatable ) rather than coying and asting the code, we create afunction. This means that if the code is broken in one art of the rogram, we

don't need to fi$ it in all the other laces we asted it ) we fi$ it in thefunction, and it's fi$ed e%erywhere.

5inally, when we want to make use of a function, we simly tell the MUD tocall it by gi%ing its name, and any arameters we wish to send it?

add_numer (4, <);

Does that look %aguely familiarJ It should ) it's how you'%e been setting u allof your objects so far ) with a series of function calls in which you ro%idearameters to functions that ha%e already been written.

This function call won't do anything though, because although it will add thetwo numbers together, the sum of these numbers ne%er get stored anywhere.In the same way that you need an object %ariable to hold a air of trousers onthe MUD, you need an integer %ariable to hold the returned %alue of yourfunction?

int num;num N add_numer (4,<);

 0t the the end of this, the %ariable num will ha%e the %alue G.

This should hoefully be making it clearer what's haening in a lot of yourcode ) while we ha%en't done a lot with dealing with returned %ariables, rettymuch e%erything we'%e been doing has been through function calls. *hen wefirst setu the e-uiment for atain eefy, we went directly through thearmoury which re-uired us to hold the objects in a %ariable in technicalterms, we got an object reference returned to us and we needed to store thatso we could maniulate it. 1%erything you ha%e done so far has been built on

the use of functions. 5unctions are the engine that dri%e the MUD.

Michael >eron #age &5

Page 86: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 86/150

LPC For Dummies 1, Second Edition

, Little Bit More...

(kay, just a little bit more theory and then we'll actually go on to dosomething with these functions. 5unctions on Discworld are actually broken

u into three tyes.

The first of these are local functions, or lfuns. They are functions that aredefined inside a game object. 5or e$amle, addroerty is a function that isdefined in &std&basic&roerty.c, and any object that inherits that file will ha%eaccess to addroerty. (bjects that don't inherit that file will no ha%e accessto that method. /uckily the objects we're creating all ha%e that handled for

 you, so roerties are a%ailable to all your rooms, "+s and items.

/ocal functions can be called directly using the call command ) we'%e donethis a few times as a creator. all lets us manually call a function, ro%iding

the arameters as we do so. The returned %alue of a call is dislayed to us, butwe can't do anything with it. They can also be called in other objects using the/7 oerator, such as when we do something like?

eefy9Ddo_command ("ing madly");

The /7 oerator tells the MUD 'call the local function docommand on theobject referenced with the name beefy'.

The second tye of function are e$ternal functions, or efuns. These are hard

coded into the dri%er and are a%ailable to all objects regardless of what theyinherit. #ou cannot call these functions with the call command, but you canmake use of them with the e$ec command. They do not get used on objectswith the P oerator. These cannot be changed easily, as they re-uire a new

 %ersion of the dri%er to be de%eloed and installed. The en%ironment67function is an e$amle of such an efun. *e call it like this?

oect env N environment (eefy);

*e do not call it like this?

object env = beefy->environment();

Michael >eron #age &6

Page 87: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 87/150

LPC For Dummies 1, Second Edition

The last tye of function are simulated efuns, or sfuns. *hile they are nothardcoded into the dri%er they are defined in a MUD object that makes thema%ailable to all of our objects just like an efun. There is no difference to youwas a creator between an efun and an sfun ) the difference is in terms of

erformance. 4ince efuns are defined in the dri%er, they are e$ecuted muchmore -uickly than an e-ui%alent sfun would be. 4funs can also be changed andadded much easier than efuns can, although the set of eole who canactually add or change sfuns is fairly limited.

Function #co*e

/ike %ariables, functions ha%e a scoe ) you can't directly make use of afunction that is defined in an object other than your current object. #ou needto use the secial arrow notation we'%e seen ) for e$amle, on our 0;M(U;#?

 

-LK'L29Dre0uest_item ("pirate trousers", #$$);

 0;M(U;# is an object that is defined in armoury.h, and what this code istelling the MUD is 'call the method re-uestitem on the object defined as

 0;M(U;#'.

There is a secondary synta$ for this using an efun called callother. all otherworks like this?

call_other (eefy, "do_command", "say 1or, this is cool.");

5unctionally, this is identical to the following synta$?

eefy9Ddo_command ("say 1or, this is cool.");

The main benefit is that since the function to be called through callother isdefined as a string, we can actually ha%e %ariable method calls?

string str N "do_command";call_other (eefy, str, "say 1or, this is cool.");

I don't recommend you actually do this, but you may see it in use throughoutthe code you read and you should know what's haening when you see it.

Michael >eron #age &"

Page 88: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 88/150

LPC For Dummies 1, Second Edition

Onwards and 7*wards%

(kay, now we'%e gotten that out of the way let's incororate a few functionsinto our new objects. 5irst of all, let's define what 4tabby >oe is going to do

when you mention his cousin. 5irstly, we're going to kee an internal 'angercounter' for 4tabby. This is a number against which we'll roll a randomnumber. If the number we roll is less than his anger, he's angry! If it's more,then he's not -uite so angry.

+layers mentioning his cousin will recei%e one of two resonses ) %iolence or awarning. The e$act resonse a layer will recei%e will deend on the angercheck.

5irst of all, let's write a stub function ) a stub is a function that has no realcode in it, but is there so that our object will actually comile when we refer

to it?

int anger_chec*() {return #;

%

*e're going to tell addresondtowith that it should use a function todetermine how it resonds to eole mentioning his cousin ) we do this bygi%ing the name of the function as a resonse, with a < symbol at the start ofit.add_respond_to_&ith(({"Jsay",({"slicey"%),({"pete"%),

%),">cousin_response");

4o, whene%er this resonse is triggered, it will call the methodcousinresonse. e aware that you can't use this synta$ for e%erything ) fore$amle, the following Fwill not workF?

set_long ("random_long");

It only works in secific cases, and you should consult the documentation onthe function you are using to see whether or not this synta$ is suorted. Itdoes work as a chat in loadchat and loadachat though, which is %ery useful.

Michael >eron #age &&

Page 89: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 89/150

LPC For Dummies 1, Second Edition

 0nyway, back to cousinresonse ) we add in a stub for this to make him saywhat he did before. *e can't use the aostrohe notation for this, but there'sa function called docommand that lets you control your "+ just like youwere tying the commands in for him 5or e$amle?

call do_command ("dance") oe

This gi%es the following resonse?

=== function on +Btay Yoe+ found in /o/monster ===Btay Yoe dances the disco duc*. LeturnedI 938#

*e can make good use of that in any function we write to make >oe do e$actlywhat we want him to do?

void cousin_response() {do_command ("+ on+t mention my cousin!");

%

*e ut these in as stubs first to ensure that e%erything is working roerly )we need to ensure that the connection between our functions is set u beforewe start writing any more comlicated code. 5irst we check the link betweenour addresondtowith and our cousinresonse function. *e can easily seethis simly by mentioning the name to >oe to see if he resonds?

D 2ou sayI slicey peteBtay Yoe exclaimsI on+t mention my cousin!

;ight, that's working ) so now we link u cousinresonse and angercheck tosee if they connect u roerly?

void cousin_response() {if (anger_chec*() NN #) {do_command ("+ 55 2K'!");do_command ("*ill " A file_name (this_player()));

%else {do_command ("+ on+t mention my cousin!");

%%

int anger_chec*() {return #;

%

"ote the way in which we're handling the killin', using the filename efun?

Michael >eron #age &8

Page 90: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 90/150

LPC For Dummies 1, Second Edition

do_command ("*ill " A file_name (this_player()));

The filename of an object is an unambiguous uni-ue reference to the object.5ind our your own with the following command?

exec return file_name (this_player());

Then, using the reference it gi%es you, try interacting with yourself. 5ore$amle, if your reference was &global&lord<3E@EC2 6which mine was7, thentry?

smile /gloal/lord>O3O8#:2ou smile at yourself.

This means we don't need to worry about targeting secific objects by theirnames ) we target them by their references. This is imortant, it sol%esse%eral weird issues with targeting and means that your "+ can genuinelydifferentiate between two objects with the same name.

 0nyway, udate >oe, and... wait, what's thisJ

/d/learning/learnville/chapter_$Z/chars/oe.c line 88I 'ndefined functionanger_chec* around NN #) {

=Hrror in loading oect +/d/learning/learnville/chapter_$Z/chars/oe+KectI /secure/cmds/creator/upd_ate at line 83

*hat does it mean, undefined functionJ *e'%e defined it right there!

 0ctually, this is a layo%er from the rogramming language uon which /+is based ) the MUD reads in our file to to bottom, and it gets to theangercheck function call before it gets to the definition of the function itself.It anics, and halts the rocess saying ':ang on! I don't know anything aboutthis angercheck to which you refer! 0(;T, 0(;T!'

*e can simly swa the two functions around to sol%e the roblem?

int anger_chec*() {return #;

%

void cousin_response() {if (anger_chec*() NN #) {do_command ("+ 55 2K'!");do_command ("*ill " A file_name (this_player()));

%else {do_command ("+ on+t mention my cousin!");

%

%

Michael >eron #age 89

Page 91: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 91/150

LPC For Dummies 1, Second Edition

That's an inelegant solution though ) you shouldn't ha%e to dramatically alterthe layout of your code just to make it run. There's a better solution thatin%ol%es just telling the MUD 'Don't worry, this function is defined later in the

rogram'. It's called function rototying.

 0t the to of your code, just after the inherit 6but not before, or you'llintroduce a new error7 you simly ut the definition of the function ) its returntye, its name, and the arameters, like so?

int anger_chec*();

This is the function definition, and as long as /+ sees that before it gets tothe function call, it will be hay. There's no need to restructure your codearound such an error, just add a function rototye.

"ow when we mention >oe's cousin, he says he'll kill us. +rogress is beingmade!

&iolence Beets &iolence

4o, e%ery time someone mentions +ete's cousin, we want to increase ouranger counter. 5or that, we first need an anger counter!

void cousin_response() {int anger_counter;anger_counter N anger_counter A #;

if (anger_chec*() NN #) {do_command ("+ 55 2K'!");do_command ("*ill " A file_name (this_player()));

%else {do_command ("+ on+t mention my cousin!");

%

%

 0nd then in angercheck, we roll a random number against thatangercounter to see if he's angry?

int anger_chec*() {if (random (#$$) C anger_counter) {return #;

%return $;

%

Michael >eron #age 8,

Page 92: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 92/150

LPC For Dummies 1, Second Edition

:owe%er, when we udate >oe the MUD will once again comlain. It's our oldfriend, the scoe roblem. ecause angercounter is defined locally incousinresonse, angercheck doesn't ha%e access to it. *e could sol%e this by

assing it as a arameter. 5irst we'd need to change our function rototye?

int anger_chec*(int);

Then hook u the functions in the new way?

 void cousin_response() {int anger_counter;anger_counter N anger_counter A #;

if (anger_chec*(anger_counter) NN #) {do_command ("+ 55 2K'!");do_command ("*ill " A file_name (this_player()));

%else {do_command ("+ on+t mention my cousin!");

%%

int anger_chec*(int anger_counter) {if (random (#$$) C anger_counter) {return #;

%return $;

%

That sol%es our scoe roblem, but it doesn't sol%e our ersistence roblem ) just like with searching the rock, if we create the %ariable locally it getsrecreated e%ery time the function is called ) anger counter will ne%er increasebeyond one. *e sol%e the roblem then by ha%ing the code linked u in theoriginal way, but make angercounter a class wide %ariable instead?

>include Carmoury.hD>include "path.h"

inherit "/o/monster";

int anger_chec*();

int anger_counter;

void setup() {// 1ode for setting him up in here.

%

void cousin_response() {

Michael >eron #age 8-

Page 93: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 93/150

LPC For Dummies 1, Second Edition

  anger_counter N anger_counter A #;

if (anger_chec*() NN #) {do_command ("+ 55 2K'!");do_command ("*ill " A file_name (this_player()));

%else {do_command ("+ on+t mention my cousin!");

%%

int anger_chec*() {if (random (#$$) C anger_counter) {return #;

%return $;

%

*e won't add a reset for angercounter ) >oe just gets angrier, he ne%er calmsdown o%er time.

It can take a while before we can tell whether >oe is angry enough to strike, solet's add another function that we can call to tell us his internal state, just tomake sure?

call 0uery_anger() oe=== function on +Btay Yoe+ found in/d/learning/learnville/chapter_$Z/chars/oe

=== LeturnedI $

D say slicey pete2ou sayI slicey pete

D Btay Yoe exclaimsI on+t mention my cousin!

call 0uery_anger() oe=== function on +Btay Yoe+ found in/d/learning/learnville/chapter_$Z/chars/oe

=== LeturnedI #

D say slicey pete2ou sayI slicey pete

D Btay Yoe exclaimsI on+t mention my cousin!

call 0uery_anger() oe=== function on +Btay Yoe+ found in/d/learning/learnville/chapter_$Z/chars/oe

=== LeturnedI 3

:is anger is increasing nicely! /et's make it easier to test him by allowingoursel%es a way to set his anger high enough so that we don't need to reeatthe same thing o%er and o%er again?

Michael >eron #age 80

Page 94: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 94/150

LPC For Dummies 1, Second Edition

void set_anger (int val) {anger_counter N val;

%

"ow set it to something midway, such as fifty, and try saying the name a fewtimes?

call 0uery_anger() oe=== function on +Btay Yoe+ found in/d/learning/learnville/chapter_$Z/chars/oe

=== LeturnedI <3

D say slicey pete2ou sayI slicey pete

D Btay Yoe exclaimsI 55 2K'!

Btay Yoe moves aggressively to&ards you!

That's one sycho shokeeer, right there!

, Local #ho* For Local Peo*le

(nce >oe is dead, his sho is still usable. *e need to ro%ide a function here toset whether or not the sho is oen, and this is done in a slightly differentway. In the setu for the sho, add the following?

 set_open_function ( (I chec*_is_open I));

This is a new kind of synta$ for setting a function, and one that is both muchmore owerful than the < code, and much more roblematic. It's called afunction ointer. In a section of /+ 5or Dummies @, we'll talk about these inmore deth, but for now treat it with caution.

*hene%er anyone tries to interact with this sho, it'll check the checkisoenfunction ) if that returns a 2, the sho is oen. If it returns a H, the sho is not.Thus?

int chec*_is_open() {if (!stay) {return $;

%else if (environment (stay) !N this_oect()) {return $;

%return #;

%

Michael >eron #age 83

Page 95: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 95/150

LPC For Dummies 1, Second Edition

 #ou'll need to add a function rototye for checkisoen?

int chec*_is_open();

 #ou'll also need to make your stabby %ariable of classwide scoe rather thanlocal to afterreset, otherwise the reference is inaccessible insidecheckisoen *hat you'll get from this though is a sho that cannot beinteracted with if the shokeeer is not resent. *e could imro%e thefunction a bit more, such as making it so the sho is also considered closed ifhe's in the middle of a fight, but that's left as an e$ercise for the interestedreader.

Conclusion

This chater is somewhat 'think hea%y' because of the need for us to talkabout how functions work ) they are critical to gaining any real understandingof how bits of the MUD communicates with other bits, and so it's worth ourwhile talking about them roerly. :oefully by this oint you'%e now gaineda fairly strong understanding of why the magic words you're tying actuallymake the MUD do interesting things!

*e're not done yet of course, there's lenty more for us to talk about beforewe reach the end of /+ for Dummies one!

Michael >eron #age 85

Page 96: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 96/150

LPC For Dummies 1, Second Edition

oin Loo*"

'ntroduction

/et's mo%e on to the ne$t of the inside rooms in our area ) the %illage ubknown as the 'itter +ill' and its owner, '8rumy 0l'. 8rumy 0l is a retiredwi9ard from the Unseen Uni%ersity, and in writing his code we'll ha%e cause tolook at how to add more interesting combat otions to an "+. *e're notgoing to stress that oint at this time, we'll e$lore interesting combat moreas art of /+ 5or Dummies @.

4o, let's not send all day standing around and chatting ) let's get to work!(ur layers aren't going to kill themsel%es, they need us to ut the killingmachines in for them.

, Basic Pu6

(ur ub fits into osition on our %illage ma, and will ha%e the filenamebitterill.c?

>include "path.h">include Cshops/pu_shop.hD

inherit "/std/shops/pu_shop";

void setup() {set_short ("6itter ?ill");add_property("determinate", "");set_long ("This is the only pu to e found for miles 9 the ""6itter ?ill. They call it that ecause the prices are ""some&hat hard to s&allo&.n");

add_property( "place", "Eenua" );set_language ("morpor*ian");set_light (:<);add_exit ("&est", LKKB A "mar*et_northeast", "door");

%

This is all familiar territory e$cet for the call to setlanguage ) it's this %aluethat sets what language the menu will be written in. Don't forget it, or you'llget a runtime error any time you try to read the menu.

*e'll also need the e$it heading back here from marketnortheast?

add_exit ("east", LKKB A "itter_pill", "door");

Michael >eron #age 86

Page 97: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 97/150

LPC For Dummies 1, Second Edition

Much like with an item sho, ubs need to be oulated with items that arefor sale &obj&food contains a fairly substantial selection of edible and-uaffable delights with which to oulate our menu. *e use theaddmenuitem function to ro%ide choices. This function has a substantial

number of arameters that go with it, so we'll go o%er these one by one. 5or afirst e$amle, we're going to make a chicken sandwich a%ailable on the menu?

add_menu_item ("delicious chic*en sand&ich", ?'6_-F1K'LBH, 3$$$, "chic*ensand&ich");

The first arameter is the name the item will ha%e on the menu when layersread it. The second 6+UM0I"(U;41, a define that is to be found in&include&shos&ubsho.h7 is the category under which the item will bedislayed, The cost comes ne$t, and the fourth arameter is where the foodmay be found. If we ro%ide a name like this, it calls uon the armoury. *ecan also ro%ide a full ath name. 5or a ub, setobjectdomain does notwork.

Udate our room, and read the menu ) you'll find the sandwich listed thereare the e$tortionate rice we set. "o wonder this lace is called the itter +ill!

5ood items are fairly straightforward to setu. Drinks re-uire a little e$traconfiguration because they also need a container ) you can ro%ide it withoutone, but you ha%e to drink -uickly before it dribbles through your fingers.

*e use addmenuitem as before, e$cet we add a few e$tra arameters?

add_menu_item ("refreshing ale", ?'6_-51K@K5, #<$$, "eer", ?'6_BT_?FT, $,#);

The first four arameters work the same way as with the sandwich ) the ne$tarameter 6+U4TD+I"T7 tells the ub where it can find the container intowhich these beer should be laced 6again, defined in the include file for theub7. The ne$t arameter lets you set how much li-uid is going to be in theglass. *e use H because we're not going to o%erride the standard functionality

at all. The last arameter is how into$icating, on a scale from 2 to 2H, thedrink should be.

rum*" ,l

"ow that we ha%e a ub, let's add its rorietor, 8rumy 0l. *e'll do hisskeleton first, and then the ool 4tuff later?

Michael >eron #age 8"

Page 98: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 98/150

LPC For Dummies 1, Second Edition

>include "path.h"

inherit "/o/monster";

void setup() {set_name ("al");set_short ("Erumpy -l");add_property ("determinate", "");add_property ("uni0ue", #);add_adective ("grumpy");add_alias ("grumpy");set_gender (#);

set_long ("Erumpy -l is an ex9&iard, in that he no longer studies at ""'nseen 'niversity. @o&ever, his love of food and of petty ""ureaucratic politics has not departed. Thus, having no effective ""outlet to enoy either of his passions, he has ust ecome grumpy.n");

asic_setup ("human", "&iard", #<$ A random (#$$));setup_nationality ("/std/nationality/genua", "genua");

load_chat(#$, ({#, "+ Kh, go a&ay.",#, "+ Ghy can+t you leave me in peaceR",#, ({<$$,"+ &rote a nastily &orded memo to Btay the other day.","+ @e didn+t read it.","+ +m not sure he can read.",%)

%));

load_a_chat(3$, ({#, "+ +ll stic* my oot up yer ac*side!",#, "+ Ghen *ill you, +m going to eat you!",

#, "+ -rr num num num!"  %));

re0uest_item ("lue sil* roe", #$$);re0uest_item ("lac* sil* under&ear", #$$);re0uest_item ("croo*ed staff", #$$);

init_e0uip();%

The only new thing here is one of our loadchats has a more comlicated

synta$?

#, ({<$$,"+ &rote a nastily &orded memo to Btay the other day.","+ @e didn+t read it.","+ +m not sure he can read.",

%)

This is a story chat ) if this chat is selected, 0l will make each of the chats oneafter another, with a delay set by the number we ro%ide. "one of the other

chats will trigger while the story is being told.

Michael >eron #age 8&

Page 99: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 99/150

LPC For Dummies 1, Second Edition

There is nothing else new here, so let's just tie him into our room in theTraditional 5ashion?

>include "path.h"

>include Cshops/pu_shop.hD

inherit "/std/shops/pu_shop";

oect al;

void setup() {// 'sual setup code

%

void reset() {call_out ("after_reset", );

%

void after_reset() {al N load_oect (1@-LB A "grumpy_al");if (environment (al) !N this_oect()) {al9Dmove (this_oect(), "PF fallPs in from the roof!", "PF disappears ""through a door he dra&s in mid9air.");

al9Ddo_command ("I stands up and dusts himself do&n.");%

%

"ote that our reset function here doesn't ha%e the odd ??reset67 that our others

ha%e. That's because there is no reset function in any other object beinginherited by this one, and if we try to include that line we will get a synta$error along the lines of the following?

/d/learning/learnville/chapter_#$/rooms/itter_pill.c line <I Fo suchinherited function IIreset around ;=Hrror in loading oect+/d/learning/learnville/chapter_#$/rooms/itter_pill+ KectI /secure/cmds/creator/upd_ate at line 83

"othing to worry about, and easily fi$ed ) but it's one of the conse-uences

that comes from working with a code base that has been under constantde%eloment for o%er fifteen years ) there are inconsistencies in the waysthings are done, and the only way to deal with them is to learn what they are,and how to adat when the code you had working re%iously in one filedoesn't work in the new one.

Michael >eron #age 88

Page 100: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 100/150

LPC For Dummies 1, Second Edition

rum*" ,l oes Ballistic

8rumy 0l is not going to ha%e a hair trigger, but he is going to ha%e magicsells he can call on. *e can add a sell to an "+ using the addsell

function. *e first gi%e the name of the sell by which we want to refer to it,and the filename to where the sell resides. *i9ard and witch sells reside in &obj&sells, and riest rituals are to be found in &obj&rituals&

"+s oerate under e$actly the same constraints for erforming skills thatlayers do. They need comonents 6although we can cheat with this to adegree, if we want7. They need the aroriate skills, and they need guildoints before they can cast.

/et's gi%e 0l a simle sell to begin with 1ringyas' 4urrising ou-uet. 5orthose of you unfamiliar with the sell, it's the one that allows the wi9ard to

summon a bou-uet of flowers.In 0l's setu, we add the sell. *e need to gi%e it a name, but it's a name forour own ersonal use, not necessarily the formal name of the sell?

add_spell ("flo&ers", "/o/spells/flo&ers.c", $);

Udate 0l and then test his magical owers like so?

call do_command ("cast flo&ers") al

 0 coule of seconds will ass, and he'll begin casting the sell. That's rettycool, but we'%e just got that sell there to test his magic... it's not somethingwe're going to use in anger. Instead, we're going to gi%e him the fire bunniessell.

add_spell ("unnies", "/o/spells/fire_unny.c", $);

5or this sells, he needs comonents so we're faced with a game design

choice?

•heat, and gi%e him as many comonents as he wants when he needsthem.

•+lay nice, and gi%e him a set number of comonents when he is set u.

Michael >eron #age ,99

Page 101: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 101/150

LPC For Dummies 1, Second Edition

The second otion is both nicer and more interesting ) it oens u ossibilitiesfor strategy that the first otion doesn't 6ickocket all his comonents before

 you attack him, for e$amle7. That's the otion we're going to go for, becauseit also gi%es us a chance to talk about another kind of rogramming structure,

the loo!

Com*onents

*e're going to setu his comonents in searate function so as to more easilyslot it together with what we already ha%e. The function is going to be calledsetucomonents?

void setup_components() { %

:e'll need a torch, so we'll gi%e him one of those. :e also needs something inwhich he can store his comonents, and we're going to gi%e him a largesatchel for that. "otice here a slightly different synta$ for re-uesting thisitem?

void setup_components() {oect satchel;re0uest_item ("torch", #$$);satchel N re0uest_item ("large satchel", #$$);

%

This matches the synta$ we used to get hold of eefy's ring in earlier chater.*e're going to ut our comonents into 0l's satchel rather than into 0ldirectly. *e could make him do this with some docommand statements, butthat is inelegant. It's much better if he starts off with his comonents in thesatchel, without us needing to fiddle about with the low le%el details of howthey get there.

*e're going to start him off with between eight twel%e cured carrots and a

torch. That introduces our first roblem how do we gi%e him a randomnumber of items in that rangeJ *ell, let's start off simly let's just gi%e himone cured carrot and ut it in the satchel.

The re-uestitem method that we're currently using handles re-uesting theitem from the armoury and then mo%ing it into our "+. That's not -uite whatwe're wanting to do and if we try to use the synta$ with which we're alreadyfamiliar we'll get unusual beha%iour 6for one thing, the carrot will not mo%einto the satchel7. *e need to get the item directly from the armoury for this.5irst include Oarmoury.hP at the to of your file. This makes a%ailable the

 0;M(U;# define that tells the MUD where to find the armoury. Then?

Michael >eron #age ,9,

Page 102: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 102/150

LPC For Dummies 1, Second Edition

void setup_components() {oect satchel;oect carrot;

re0uest_item ("torch", #$$);

satchel N re0uest_item ("large satchel", #$$);carrot N -LK'L29Dre0uest_item ("carrot");carrot9Ddo_cure();carrot9Dmove (satchel);

%

 #ou may recognise this synta$ from the first way we dressed atain eefy.*e need to make a call to setucomonents in 0l to make the mud actuallyuse the code in our function, so ut a call just before inite-ui?

setup_components();init_e0uip();

 0nd add the function rototye after your inherit?

void setup_components();

Udate 0l and his room, and you'll see when you look at him?

Erumpy -l is an ex9&iard, in that he no longer studies at 'nseen 'niversity.  @o&ever, his love of food and of petty ureaucratic politics has notdeparted. Thus, having no effective outlet to enoy either of hispassions, he has ust ecome grumpy.

@e is in good shape.@e is standing.@olding I a croo*ed staff (left hand and right hand).Gearing I a lue sil* roe, a lightale torch and a large satchel.

To check what he has inside his satchel, we can use the following command?

inv satchel in al

*hich should gi%e something like the following?

nv of large satchel in Erumpy -lIcured carrot (/o/food/vegetales/carrot.food>84<8#:4)

That's e$citing! "ow, let's gi%e him eight carrots. *e'll worry about therandom number of carrots later.

The first way of doing this is ob%ious?

Michael >eron #age ,9-

Page 103: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 103/150

LPC For Dummies 1, Second Edition

void setup_components() {oect satchel;oect carrot#, carrot3, carrot, carrot4, carrot<, carrot8;

  oect carrot:, carrotO;

re0uest_item ("torch", #$$);satchel N re0uest_item ("large satchel", #$$);

carrot# N -LK'L29Dre0uest_item ("carrot");carrot#9Ddo_cure();carrot#9Dmove (satchel);

carrot3 N -LK'L29Dre0uest_item ("carrot");carrot39Ddo_cure();carrot39Dmove (satchel);

carrot N -LK'L29Dre0uest_item ("carrot");carrot9Ddo_cure();carrot9Dmove (satchel);

carrot4 N -LK'L29Dre0uest_item ("carrot");carrot49Ddo_cure();carrot49Dmove (satchel);

carrot< N -LK'L29Dre0uest_item ("carrot");carrot<9Ddo_cure();carrot<9Dmove (satchel);

carrot8 N -LK'L29Dre0uest_item ("carrot");carrot89Ddo_cure();carrot89Dmove (satchel);

carrot:N -LK'L29Dre0uest_item ("carrot");carrot:Ddo_cure();carrot:Dmove (satchel);

carrotO N -LK'L29Dre0uest_item ("carrot");carrotO9Ddo_cure();carrotO9Dmove (satchel);

%

oy and aste the code se%en times! It'll work but what if instead of carrotswe wanted to gi%e him cured eyesJ *e need to change the code in eight

laces. That may seem like a reasonable solution to you, but what if wewanted to gi%e him a hundred chicken feathersJ "o sir, that dog won't hunt!

 0dditionally, when you coy and aste you run the risk of introduction whatare known as transcrition errors you can lose count and ro%ide more orless carrots than you wanted. (r when making the same modification tomultile lines of reeated code, your attention will wander and you'llintroduce tyos. ;eally, this is the kind of thing the MUD should do for us.

Michael >eron #age ,90

Page 104: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 104/150

LPC For Dummies 1, Second Edition

In actual fact, it can there's a secial kind of rogramming structure calledthe loo that lets us reeat a section of code se%eral times. /oos come inthree fla%ours the while loo, the do while loo, and the for loo. *e'll talkabout all three of them, although we only need one for this articular

scenario.

Loo*s

*hen we want to reeat a iece of code a multile number of times, wero%ide the MUD with a loo to make it do the actual work for us. Thesimlest of these loos is called the while loo, and it will reeat code until aarticular continuation condition is no longer met. 5or e$amle, imagine thefollowing?

// eclaration of counter variale.int num_carrots N $;// Betting of the continuation condition.&hile (num_carrots C O) {// 'p*eep of counter variale.num_carrots N num_carrots A #;

%

The continuation condition works just like the condition in an if statement.The difference is that the while loo will kee doing the code in the braces

until the condition is no longer met. In this case, it will increase thenumcarrots %ariable to E and then it will sto looing 6because E is not lessthan E7.

That seems e$actly what we want, so let's try that in 8rumy 0l?

void setup_components() {oect satchel;oect carrot;int num_carrots N $;

re0uest_item ("torch", #$$);satchel N re0uest_item ("large satchel", #$$);

&hile (num_carrots C O) {carrot N -LK'L29Dre0uest_item ("carrot");carrot9Ddo_cure();carrot9Dmove (satchel);num_carrots N num_carrots A #;

%%

Michael >eron #age ,93

Page 105: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 105/150

LPC For Dummies 1, Second Edition

"ow, let's talk a little about what's haening in the while loo, because itmay not be e$actly what you may think. "otice here we ha%e one %ariablecalled carrot, and each time around the loo we're using that %ariable. This isoften a confusing oint when working with code, and so I'll send a little time

e$laining what's actually haening.*hen you assign an item to an object %ariable, you're not actually workingwith the item on the MUD. #our %ariable is just a shortcut to an item thate$ists elsewhere in the memory reresentation that the dri%er has ofDiscworld. *hen your %ariable loses its scoe, the item doesn't sto e$isting,it just stos being referenced by your own %ariable. The MUD still knowswhere it is, what it is, and how it can reference it later.

*hen you create a carrot here, it clones the object and the MUD itself has anote of that item. #ou then mo%e it into the satchel, and the satchel gets itsown reference to the carrot. If you then assign another carrot to the same

 %ariable, it doesn't change the first carrot, or the reference to that carrot inthe satchel you just lose your ersonal reference to the first one.

 0s such, we can use the same %ariable o%er and o%er again ro%ided we ha%eno cause to refer to it later. *e can't use satchel howe%er for the name of our

 %ariable because we need the reference to the satchel later we ha%e onesatchel into which we are utting many carrots we need that satchelreference so that all carrots go into the same lace.

This is a comlicated oint, and one you can't be e$ected to fully gras at themoment. >ust kee it at the back of your mind for now.

Udate grumy al and look in his satchel again you'll see there's one carrot.:ey, what gi%esJ

Much like with %irtual objects, the reason behind this is efficiency ratherthan store eight carrots, the mud stores one carrot and makes a note to treatit as if there are eight of them. This reduces the load on the MUD and is a8ood Thing. #ou can assure yourself there are eight of them like so?

call group_oect_count() carrots in satchel in al

1$ternally, as far as you are concerned, there is only one actual carrot object.

:owe%er, art of the code in that carrot object handles how the carrot shouldbeha%e, and that code says 'beha%e as if you were actually eight searatecarrots'.

Doin $hile...

 0 do while loo works in e$actly the same way as a while loo, e$cet that itsguaranteed that the code will be e$ecuted at least once. If we set numcarrotsto E, then the code belonging to our while loo abo%e would ne%er e$ecute.

*ith a dowhile, we can ensure that the code is run once before thecontinuation condition is checked?

Michael >eron #age ,95

Page 106: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 106/150

LPC For Dummies 1, Second Edition

do {carrot N -LK'L29Dre0uest_item ("carrot");carrot9Ddo_cure();carrot9Dmove (satchel);

num_carrots N num_carrots A #;% &hile (num_carrots C O);

Do while loos ha%e somewhat secialised use if you can't think of a reasonwhy you would want to do this, it's fine... you don't ha%e to use them unless

 you actually need to, but when you do need to they are in%aluable.

*hile loos and do while loos are e$amles of a set of structures calledunbounded loops  their continuation can be deendant on unknownconstraints. :ere we're working with numbers, but that's not where they are

best used. They are best used in situations where we don't know how manytime we're going to loo. 5or e$amle, consider the following?

&hile (there are enemies in the room) {*ill_them();*ill_them_all();

%

*e don't know when the enemies will lea%e the room they may be killed,they may choose to run away it's something o%er which we ha%e no control

and thus we manage that uncertainty by using a while loo.

For Loo*s

*e can use a for loo to deal with situations in which we know how manytimes a iece of code will be e$ecuted. That doesn't mean that we know whenwriting the code how many times we ha%e to e$ecute the loo, just that whenthe MUD gets to the loo, somewhere we ha%e a %ariable storing how manytimes it is going to need to loo o%er the code. This is a bounded loop. It has

all the arts of our first while loo, just resented in a slightly differentsynta$?

for (num_carrots N $; num_carrots C O; num_carrots N num_carrots A #) {  carrot N -LK'L29Dre0uest_item ("carrot");carrot9Ddo_cure(); carrot9Dmove (satchel);

%

The for loo handles keeing the counter %ariable correct for us we canconcentrate urely on the functionality we wish to reeat. It otherwise works

like a standard while loo?

Michael >eron #age ,96

Page 107: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 107/150

LPC For Dummies 1, Second Edition

for (initialisation ; continuation ; up*eep) {// code goes here;

%

 0 for loo can also declare a %ariable as art of its counter inside the loodeclaration, neatly encasulating e%erything into a single syntactic structure,like so?

for (int num_carrots N $; num_carrots C #$; num_carrots N num_carrots A #) {

// 1ode%

 #ou can also write the ukee in a more comact fashion?

num_carrotsAA;

(r?

num_carrots AN #;

oth of these lines of code do 6almost7 the same thing they increase the %alueof numcarrots by one. They actually do %ery subtly different things in the waythey increase the %alue, but that's of no conse-uence to us at the moment?

for (int num_carrots N $; num_carrots C O; num_carrotsAA) {carrot N -LK'L29Dre0uest_item ("carrot");carrot9Ddo_cure();carrot9Dmove (satchel);

%

"ow all that remains to do is make the loo reeat a random number of times,between eight and twel%e. 1asy to do, we ha%e all the code we just userandom to set the number of carrots we actually need?

void setup_components() {int num_to_clone;oect satchel;oect carrot;

num_to_clone N O A random (<);re0uest_item ("torch", #$$);

satchel N re0uest_item ("large satchel", #$$);

Michael >eron #age ,9"

Page 108: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 108/150

LPC For Dummies 1, Second Edition

  for (int num_carrots N $; num_carrots C num_to_clone; num_carrotsAA) {carrot N -LK'L29Dre0uest_item ("carrot");carrot9Ddo_cure();carrot9Dmove (satchel);

%%

4uer our codefu grows greater by the day! This isn't something that's justeasier to do with a loo it's actually imossible to do it without one.

Fire in the Hole%

5inally, let's make 8rumy 0l cast the sell during combat. *e useaddcombataction for this along with the function ointer synta$ we sawearlier. In his setu, include this?

add_comat_action (#<, "cast_spell", (I fire_in_the_hole I) );

The first arameter indicates the chance the action will occur. The second is aname we ha%e for the action we don't need to worry about that. The last bitis the function to be called when the action is to be taken. The MUD willautomatically choose a %alid target for us to concentrate our attention on, sowe don't need to worry about that. (ur function is going to ha%e twoarameters the first is the object attacking our object 6that'll be us7, and thesecond is the target of the attacker. Don't worry too much about this this isalso a toic for /+ 5or Dummies @. It's included here just because it's nice tosee our "+s hurling hot death at eole.

*e'll need a function rototye for this, but the code itself is -uite simle?

void fire_in_the_hole (oect attac*er, oect target) {do_command ("get carrot from satchel");do_command ("+ 5ight them up!");do_command ("cast unnies on " A file_name (attac*er));

%

Udate 0l and try to unload the hurts you'll find e%ery now and again he triesto set you alight. 1$cet, he fails horribly because he's not actually a %erygood wi9ard. #ou can see what his skills are by using the following command?

players*ills al

 0 word of warning this command also works on layers but they get an

inform that it's being done. Don't use it without ermission.

Michael >eron #age ,9&

Page 109: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 109/150

LPC For Dummies 1, Second Edition

 0nyway, you'll see that 0l is missing ractically all of the skills he'd need tosuccessfully cast the sell, so let's beef him u a bit in his setu?

add_s*ill_level ("magic", 3$$);

Udate and load him again and check his skills much beefier! *e can add asmany combat actions as we want to make him a challenging foe.

This is ob%iously -uite an unsohisticated action if he casts too many in arow he'll start suffering from misfires and set himself on fire. The core is therethough, and we can e$and on this as we choose!

Conclusion

In this chater we'%e looked at a new rogramming structure, the loo, andthe code we need to add secial attacks to an "+. *e're already caable ofcreating some -uite sohisticated areas, but our journey is not done yet. Inthis ne$t section we're going to look at a somewhat more comlicated %ariablecalled an array. /earning about and using arrays is the ne$t real eak of yourde%eloment as a creator, and from that oint onwards whole new worlds ofde%eloment are a%ailable to you!

Michael >eron #age ,98

Page 110: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 110/150

LPC For Dummies 1, Second Edition

,rra"s1 -ou sa"2

'ntroduction

In this chater we are going to discuss one of the most imortant coding toolsthat you ha%e a%ailable to you as a creator ) the array. 0rrays are one of themost imortant concets to understand if you want to ro%ide genuinelyinteresting code in your areas, and it's worth reading o%er this chaterobsessi%ely until it all makes sense. Then, ractice, ractice, ractice until youare entirely comfortable with the toic. I honestly can't stress this enough ) anunderstanding of arrays forms the most imortant skill of a creator, as allmore comle$ subjects are ine$tricably linked with it.

*e're going to e$lore arrays in this chater through the medium of 4licey+ete, >oe's cousin. 4licey +ete is a wandering merchant who roams the streetsof /earn%ille for its meager business oortunities. *e'll also continue withthe toic in the ne$t chater. 4o, with no more ado, on with the show!

#lice" Pete

+ete isn't just a normal "+ ) he's a wandering merchant, and thus he uses adifferent inherit. eyond that, he works like all of the other "+s we'%ede%eloed this far. /et's look at his temlate?

>include Carmoury.hD>include "path.h"

inherit "/o/peddler";

void setup() {set_name ("pete");set_short ("Blicey ?ete");

add_property ("determinate", "");add_property ("uni0ue", #);add_adective ("slicey");add_alias ("slicey");set_gender (#);

set_long ("This is Blicey ?ete, the cousin of Btay Yoe. Ghile people ""often assume the &orst ecause of his name, he+s not a violent man. ""@e &as ust orn in Blice.n");

asic_setup ("human", "&arrior", <$ A random (<$));setup_nationality ("/std/nationality/genua", "genua");

Michael >eron #age ,,9

Page 111: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 111/150

LPC For Dummies 1, Second Edition

  add_property ("place", "Eenua");add_move_one ("learnville");set_move_after ($, 8$);

load_chat(#$, ({#, "+ Btay+s real name is adeline, you *no&.",#, "+ ?oor adeline 9 he &as such a nice oy at one point.",#, "+ 6uy my stuff, or +ll... &ell, not e happy.",

%));

load_a_chat(3$, ({#, "+ Fo, +m ust from Blice! 5eave me alone!",#, "+ thin* ust had an accident!",

%));

add_respond_to_&ith(({"Jsay",({"stay"%),({"oe"%),

%),"+ @e &as a nice lad, once.");

re0uest_item ("lac* pinstripe trousers", #$$);re0uest_item ("crisp &hite shirt", #$$);re0uest_item ("leather dress shoes", #$$);

init_e0uip();%

"ote that he inherits &obj&eddler rather than &obj&monster ) this sets him uas an "+ you can buy things from. 0t the moment, he has nothing for us,none stock?

D list goods of pete

Blicey ?ete saysI am afraid have nothing for sale.

*e gi%e him stock in the same way we add stock to an item sho ) throughaddobject?

add_oect ("carrot", < A random (<));

4o far, so simle. +ete howe%er is a %ery good merchant and offers a wide %ariety of food for sale. The full list of things he's going to sell is as follows?

•ananas

•arrots

• 0les

Michael >eron #age ,,,

Page 112: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 112/150

LPC For Dummies 1, Second Edition

• 0ricots

•read

•Melons

•ream cakes

• >am rolls

•Meat rolls.

"ow, we can add each of those oursel%es in a list?

add_oect ("anana", < A random (<));add_oect ("carrot", < A random (<));

add_oect ("apple", < A random (<));add_oect ("apricot", < A random (<));add_oect ("read", < A random (<));add_oect ("melon", < A random (<));add_oect ("cream ca*e", < A random (<));add_oect ("am roll", < A random (<));add_oect ("meat roll", < A random (<));

 0gain, our roblem is one of scale ) it might be okay if we're working with thisnumber of items, but a roblem gets introduced when we're dealing withmore. *hat if you need to scale back his stock so that he only sells one or two

of eachJ #ou need to change it in each addobject call ) not a huge issue fornine objects, but a big deal for ninety. (ur code simly doesn't scale u here.

 #ou may be looking at this and thinking '0 loo of some kind would seem to bethe answer', and you're entirely correct ) the roblem is that we don't yetknow how to loo in a way that allows for the item to be re-uested to bechanged. (ur loos at the moment work by reeating the same good a certainnumber of times. *hat we need is a way to use a loo to do a slightly differentthing each time. *e know how to work with numbers, but strings are adifferent deal.

*e now need a new tool ) something that lets us define a list of strings andste o%er each of them. *ell, ask and ye shall recei%e!

*e're going to need to load +ete somewhere, so let's load him inmarketsoutheast. The code for this should be familiar to you by now, so Iwon't reeat it ) check atain eefy, 4tabby >oe or 8rumy 0l if you need arefresher.

Michael >eron #age ,,-

Page 113: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 113/150

LPC For Dummies 1, Second Edition

 !he ,rra"

4imly stated, arrays are just lists of data. #ou'%e been using them all along,although we ha%en't stressed then. #ou'%e encountered an array whene%er

 you'%e seen a line of code like?

({"some", "things", "here"%)

 0rrays are henomenally useful, and it's fair to say that until you ha%emastered them you are only addling around in the shallow end ofrogramming. /et's talk about how they work!

 0rrays are just %ariables, the difference is that they ha%e multile

comartments into which data can be inserted. 0ll the data has to be of thesame tye. *e declare them slightly differently from the %ariables we ha%eseen so far ) they are indicated with a star symbol by the %ariable's name. Tocreate an array of strings, we'd use the following synta$?

string =my_array;

*e also set it with a %alue in a slightly different way ) to create an emtyarray, we use the 6W X7 notation?

my_array N ({ %);

*e need to set the array to ha%e something before we use it, or we'll likely getTerrible 1rrors.

If we want to set an array u with some starting %alues, then we use a %ariation on that synta$?

my_array N ({"some", "things", "here"%);

*hen this code is interreted by the MUD, it sets u a %ariable with threecomartments?

Compartment Contents

H some

2 things

@ here

Michael >eron #age ,,0

Page 114: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 114/150

LPC For Dummies 1, Second Edition

The number of the comartment is called its inde1 , and the contents areknown as the element, as in '8i%e me the element at inde$ @'.

*e can ull information out of these comartments using a secial notation?

string ing N my_array[#\;

This code will ull out the element at inde$ 2 6in the case of our e$amle, itwill be the string things7. If we want to change a %alue, then we can do thattoo?

my_array[#\ N "pirates!";

 0fter this line of code is e$ecuted, our array will look like this?

Inde1 0lements

H some

2 irates!

@ here

In both cases you must be careful not to access an inde$ that is either largerthan the si9e of the array, or a negati%e number. If you do, the MUD willcomlain of an 'array inde$ out of bounds', which just means you tried toaccess an element that doesn't actually e$ist.

If we want to add in a fourth element, then we do that by adding anotherarray to our first?

my_array AN ({ "matey" %);

This adds the new element to the end of the array?

Inde1 0lements

H some

2 irates!

@ here

3 matey

Michael >eron #age ,,3

Page 115: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 115/150

LPC For Dummies 1, Second Edition

 0nd to remo%e an element, like so?

my_array 9N ({"here"%);

This will delete e%ery instance of the word 'here' in the array?

Inde1 0lements

H some

2 irates!

@ matey

,rra" 'nde5in

/+ ro%ides a number of ways in which we can inde$ elements withoutsimly using integers. *e can start inde$ing from the last element by usingthe O oerator within an array inde$ notation. If we want the last element inan array, we can do it like so?

string str N my_array[C#\;

(r if we want the second last?

string str N my_array[C3\;

*e can get a range out of an array by using the .. notation, like so?

string =su_array; su_array N my_array[#..3\;

The range notation is inclusi%e, so with the abo%e code you would getelements 2 and @ out of it. #ou can also combine these notations?

string =su_array; su_array N my_array[$..C3\;

Michael >eron #age ,,5

Page 116: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 116/150

LPC For Dummies 1, Second Edition

The effect of this array inde$ would be to get all of the elements from the firstelement 6inde$ed by H7 u until the second last element 6inde$ed with O@7.

 #ou can e%en lea%e off the end art of the range?

string =su_array; su_array N my_array[#..\;

This would get all of the elements of the array from the second one onwards.

There's a lot that we can do with this kind of inde$ing system, but don't worryabout it just yet. >ust know that when you see it, that's what's haening.

,rra" manaement

 0rrays ha%e concetual comle$ity to go with them, and as such there are anumber of 'management' functions that e$ist to hel you maniulate them.+erhas the most imortant of these is si9eof, which gi%es you the number ofelements in an array?

int num N sieof (my_array);

*ith our three elements, the %ariable num will contain the %alue 3. *e canthen use this as a basis for array maniulation ) after all, to maniulate anarray roerly we need to know how big it is that makes it amenable tomaniulation with a bounded loo.

+erhas the ne$t most imortant task we erform on a day to day basis withan array is to tell if a articular %alue is contained with. *e do that using thememberarray function. This take two arameters ) one is the %alue we wishto search for, and the second is the array through which we wish to search.The function returns a 2 if the item is not resent, or the inde$ of the firstmatch if it is?

int found N memer_array ("pirates!", my_array);

*ith this e$amle, found will be e-ual to 2 because that's where the searchte$t can be found. If we search instead for 'me hearties', found will be set to 2because that string is not resent in the array.

If we want to ull a random element out of the array, we can use theelementof function?

string random_element N element_of (my_array);

Michael >eron #age ,,6

Page 117: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 117/150

LPC For Dummies 1, Second Edition

 0nd we can get se%eral random elements out of the array using theelementsof function. The first arameter to this method is the number ofelements you want out of it. The second is the array from which you want toe$tract them.

string =some_elements N elements_of (3, my_array);

*e can randomise the order of the contents of an array, just like a ack ofcards, with the shuffle method?

my_array N shuffle (my_array);

 #ou can also sort the contents of an array into ascending or descending orderusing the sortarray function. The number you ro%ide to this methodindicates the direction of the sorting 2 indicates ascending order, and 2indicates descending order.

my_array N sort_array (my_array, #);

That should be enough of a start for us to start using them in our code ) likewith e%erything, the only way we e%er really start to understand code is when

we start to use it. 4o let's begin!

#ettin 7* #tock1 LPC #t"le

4o, let's get back to our merchant and his unwieldy list of stock. *e want allof that to be added in as comact a way as ossible. /et's start off by creatingan array of things to add. 5irst, at the to of setu, we create our array, and atemorary %ariable to hold things as they come off of the array?

string =items;string temp;

Then, we set items to e-ual our list of items to be created?

items N ({"anana", "carrot", "apple", "apricot", "read", "melon","cream ca*e", "am roll", "meat roll"%);

"ow, we need to go o%er each of these in turn, and add the object. (nce

again, we return to the idea of incremental de%eloment ) let's start by doingsomething easier. 5irst, let's re-uest whate%er is at inde$ H in our array?

Michael >eron #age ,,"

Page 118: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 118/150

LPC For Dummies 1, Second Edition

temp N items[$\; add_oect (temp, < A random (<));

That's not so bad ) what about getting the second itemJ

temp N items[#\;add_oect (temp, < A random (<));

That's not so bad either ) we could go all the way u to inde$ adding itemsin this way?

temp N items[$\;

add_oect (items[$\, < A random (<));temp N items[#\;add_oect (items[#\, < A random (<));temp N items[3\;add_oect (items[3\, < A random (<));temp N items[\;add_oect (items[\, < A random (<));temp N items[4\;add_oect (items[4\, < A random (<));temp N items[<\;add_oect (items[<\, < A random (<));temp N items[8\;add_oect (items[8\, < A random (<));

temp N items[:\;add_oect (items[:\, < A random (<));

:oefully though a better alternati%e resents itself ) using a loo! *e canuse the counter of a loo to ste through each element in an array, like so?

 for (int i N $; i C sieof (items); iAA) {temp N items[i\;add_oect (temp, < A random (<));

%

4uddenly all of that condenses down into a single rogramming structure thatis infinitely e$tensible ) add in a new item to the array, and that item becomesa%ailable in the stock. That's retty cool you ha%e to agree!

/et's try it out though ) let's add tomatoes to the stock?

items N ({"anana", "carrot", "apple", "apricot", "read", "melon","cream ca*e", "am roll", "meat roll", "tomato"%);

Michael >eron #age ,,&

Page 119: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 119/150

LPC For Dummies 1, Second Edition

Dest and udate +ete, and you'll find his stock is udated without you addinganother line of code?

Blicey ?ete says to youI have five plump tomatoes for #,El each.

 #ou sure do, +ete! #ou sure do.

 !he Foreach #tructure

There e$ists a secific kind of rogramming structure designed urely to steo%er each element in an array ) it's called foreach, and you'll see it -uite a lotas your read o%er e$isting code. It's just a neater way of doing what our looabo%e does ) we can disense with manually ulling each item off of the array

and let the code do it for us. 0 foreach loo starts at the beginning of thearray, and ends at the end, and at each stage it mo%es on one elementforwards through the array. It's not good for when we need fine grainedcontrol o%er how we work with an array, or when we need to know how manyiterations we ha%e gone o%er, or when we need to know where in an array wecurrently are. :owe%er, for straightforward steing o%er an array, it wouldlook like this?

foreach (temp in items) {add_oect (temp, < A random (<));

%

*e use the temp %ariable in the array synta$ as a condition for the structure )we don't need to manually -uery the si9e of the array or ull the %ariable off ofthe array. The loo will begin at the %ery first element, and ull that elementoff the array and store it in tem. "e$t time around the loo, it will take thesecond element and ut that into tem, and so on until all of the elements ofthe array ha%e been steed o%er.

This is a %ery lo%ely syntactic structure, and a feature that /+ had longbefore it made its way into more mainstream languages like >a%a. The sole

drawback is that it doesn't gi%e you access to a secific inde$ number ) if youneed that at any oint in your code, you'll need to rely on a standard for loo

 #ou'll find that a combination of for and foreach will be re-uired to make fulluse of arrays as you rogress through your rojects ) learning which is bestfor a articular task is something that will come with e$erience.

Michael >eron #age ,,8

Page 120: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 120/150

LPC For Dummies 1, Second Edition

Conclusion

 0rrays are a comlicated toic, and in the ne$t chater we're going to look atsome of the many %aried cool things we can do now that we'%e added them to

our rogramming toolbo$. I'm not kidding when I say that this is whatromotes you from the shallow end of the rogramming swimming ool )without e%en talking about any other data tyes, we can do racticallyanything we'd e%er need by relying urely on arrays.

There's one more standard data tye we're going to introduce in /+ forDummies, but our journey through introductory synta$ is starting to come to aconclusion ) we'%e co%ered some scary territory o%er the ast chaters and

 you are to be congratulated for reaching this far! "ow, go ractice arraysuntil your brain bleeds!

Michael >eron #age ,-9

Page 121: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 121/150

LPC For Dummies 1, Second Edition

Hoora" for ,rra"s

'ntroduction

In the last chater we looked at the basics of using arrays in /+ ) that was abig ste, and it oens u a lot of new things we can talk about. 0rrays areembedded deely in the mudlib, to the oint that you can't do anything ofconse-uence without working with them in one caacity or another. Most ofthe useful functions of the MUD return arrays rather than single bits of data,and in this chater we're going to look at some of these.

In the rocess, we'll add the last of the rooms to our %illage, adding ininteracti%ity based on what a layer has in their in%entory, among otherthings.

, #ecret !o Be Disco/ered

/ook back at our ma of /earn%ille ) there's one room we still ha%en't done,marked D on the ma. It's connected to marketsoutheast, but we don't ha%eanything for it yet. The room itself is going to be a general store ) that is, a

sho that buys what layers ha%e to sell. In the game roer, we try not toha%e too many of these because each one is an additional le%el of artificialityin an already broken game economy, but e%ery substantial new area usuallyhas one for layability reasons. :owe%er, this is no normal general sho ) it isa sho full of hungry grues!

*e'll start with the usual first ste, our skeleton imlementation. *e'll sa%ethis as magicsho.c?

>include "path.h";inherit "/std/shops/general_shop";

void setup() {set_short ("magic general shop");add_property ("determinate", "");set_day_long ("The fingers of sunlight do not touch this occult ""place. @ope has long deserted this room.n");

set_night_long ("n the dar*ness, it+s possile to send occult, ""eldritch energies see*ing entry. -nyone in the room at ""night &ithout the special magical safety item is li*ely ""to e eaten y a grue.n");

set_light (#$$);

add_day_item("occult place", "There+s a definite sense of occultness "

"in the air.");add_day_item (({"occult", "occultness"%), "2es, that sort of thing.");

Michael >eron #age ,-,

Page 122: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 122/150

LPC For Dummies 1, Second Edition

  add_night_item ("occult eldritch energies", "They are very olong.");add_night_item ("special magical safety item", "@oo9oy, you etter hope ""you have that &ith you!");

add_property ("place", "Eenua");

room_day_chat ( ({ #3$, 34$, ({"2ou are proaly safe here, for the time eing.","This room ma*es you sad.","2ou sense that the room doesn+t &ant you to e here.",

%)%));

room_night_chat ( ({ #3$, 34$, ({"2ou etter hope you have the magic item!"," feel sorry for anyone &ho doesn+t have that special item!",">eaten_y_grue",

%)%));

add_exit ("&est", LKKB A "mar*et_southeast", "door");%

void eaten_y_grue() {// Ge+ll fill in the code for this later.

%

"ote that one of the roomnightchat entries is to a function calledeatenbygrue. *e'll come back that one soon, but we'll just add in a stub forit now. 4tub methods are a great way to structure your code without needing

 you to ha%e to actually code e%erything at once.

8eneral shos are unusual in that they re-uire a second room to e$ist beforethey work roerly ) e%ery general store should ha%e a storeroom that layerscan't get into. It's kind of like a backack for the sho ) it's where e%erythinggets stored. The stock of a general store is entirely deendant on what is inthe storeroom ) so we need to ha%e whate%er stock we're interested insulying created inside the storeroom. *e do that just like we did for makingitems a%ailable within our "+ through the use of re-uestitem. *e'll need torestock the sho eriodically, so we'll handle that in reset.

(ur temlate for the file, which we will sa%e as magicstoreroom.c?

>include "path.h">include Carmoury.hD

inherit "/std/storeroom";

void setup() {set_short( "store room" );set_long( "This is a storeroom. 2ou shouldn+t e here. ""f you are, leave (or as* a creator to get you out) and ""ug report ho& you got in.n" );

add_exit( "south" , EHF'-_-SHF'H A "general_store" , "path" );set_light( #$$ );

%

Michael >eron #age ,--

Page 123: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 123/150

LPC For Dummies 1, Second Edition

void reset() {// To follo&

%

 0nd then we need to tell our general store to make use of the storeroom weha%e ro%ided ) in the setu for magicsho goes the following line of code?

set_store_room (LKKB A "magic_storeroom");

Udate the room and our general store works like we'd hoe ) there's noshokeeer here, and we're not going to add one because this is a magic sho.4ell an item to the sho and you'll find it functions like you'd e$ect an in

game store to work.It starts off with no stock ) we're going to ha%e to handle the stock generationoursel%es, and for that we need arrays.

'tem Matchin

(ur e$amle of an array in ractice from the last chater was somewhatartificial ) although we did gain a real imro%ement in the use of an array, wedidn't ha%e to use one. :owe%er, it was an instructi%e e$amle for what we're

going to do here.

*e want to setu new stock e%ery time reset is called, but we also don't wantto o%erstock items. Imagine the following?

void reset() {for (int i N $; i C 3; iAA) {re0uest_item ("torch", #$$);

%%

4eems fine, rightJ ;eset is called and we ro%ide two lightable torches to thesho. That will work just as we might e$ect, but o%er time and resets thatstock will grow, and grow, and grow, and grow. There is a oint where we justwant to be able to say 'sto, don't create any more of these'. 0round abouteight would be a reasonable number of torches.

In order to do that, we need to know how many torches there are in the room,and we don't yet know how to do that. *e could kee track of how many weha%e created, but that doesn't catch ones that get sold to the sho by layers,or bought, or sholifted, or that otherwise lea%e the storeroom. ;eally, we

want to be able to say in reset 'ount how many torches there are, and if thereare less than eight clone some in'.

Michael >eron #age ,-0

Page 124: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 124/150

LPC For Dummies 1, Second Edition

The function that lets us count how many items are in a articular container iscalled matchobjectsfore$istence, and it returns ) yes, you guessed it, anarray!

/et's see it in action by finding all the lightable torches in the room?

oect =torches;torches N match_oects_for_existence ("lightale torches", this_oect());num_torches N sieof (torches);

(ur matching function takes two arameters ) one is the string against whichwe're going to try to match against an object, and the second is the containerin which we're going to check 6in this case, it's the room itself7.

The matchobjectsfore$istence function makes ambiguous matches, which

means that it will match in the same way the game does when you try tointeract with items in your in%entory. Torches can be held as weaons, and soif you changed the check like so?

torches N match_oects_for_existence ("&eapons", this_oect());

 #ou'd still get the torches returned. "ote too that we search for a luralrather than a singular ) the following would get us one torch out of the lot?

torches N match_oects_for_existence ("lightale torch", this_oect());

(nce we ha%e list of items, we get the si9e of the array ) this gi%es us howmany items are in the storeroom. y doing this check, we can limit at whatoint we sto adding torches to the stock in a reset ) eole can still sell themto the sho and so the actual stock in the sho may be more than the %aluewe'%e set. The only thing our code does is make sure that we only add torchesif there are currently less than eight a%ailable, like so?

void reset() {oect =torches;torches N match_oects_for_existence ("lightale torches", this_oect());

num_torches N sieof (torches);if (num_torches C O) {for (int i N $; i C 3; iAA) {re0uest_item ("torch", #$$);

%%

%

Michael >eron #age ,-3

Page 125: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 125/150

LPC For Dummies 1, Second Edition

*e're also going to add another item to the store ) a secial item we createoursel%es ) it's the magic item that stos us being eaten by a grue. It's goingto be a secial amulet ) when the eatenbygrue function is called abo%e,we're going to eat anyone who doesn't ha%e this secial item in their

ossession. +oor souls! >ewellery has a .arm e$tension as we ha%e already seen, and ours is going tobe called blackbo$recorder.arm?

IIFameII"amulet"IIBhortII"lac* ox recorder amulet"II-dectiveII({"lac*", "ox", "recorder"%)II?luralII"e&ellery"II-liasII"e&ellery"IIain ?luralII"lac* ox recorder amulets"II5ongII"This is a special nec*lace that records information aout your "

"course and traectory ust in case you are eaten y a grue. Erues ""li*e to see these on people, ecause grues are all in love &ith ""Barah Fixey. Fo9one &earing one of these need fear a grue!n"

IITypeII"nec*lace"IIaterialII"gold"II?ropertyII"shop type", "e&ellers"IISalueIIO$$$IIamage 1hanceII4IIBetupII3$$IIGeightII#

 0nd so, in our sho reset, the full function is as follows??

void reset() {oect =torches;int num_torches;oect =amulets;int num_amulets;oect o;

torches N match_oects_for_existence ("lightale torches", this_oect());num_torches N sieof (torches);

if (num_torches C 4) {for (int i N $; i C 3; iAA) {re0uest_item ("torch", #$$);

%%

amulets N match_oects_for_existence ("lac* ox recorder amulets",this_oect());

num_amulets N sieof (amulets);if (num_amulets C #) {o N clone_oect (THB A "lac*_ox_recorder.arm");o9Dmove (this_oect());

%%

Michael >eron #age ,-5

Page 126: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 126/150

LPC For Dummies 1, Second Edition

"ow that our sho is setu and we ha%e our secial item a%ailable, let's dealwith eole getting eaten by grues!

, rue #ome Fate%

The criteria for being eaten by a grue is fairly simle ) if it's nighttime and you're not wearing the amulet, you get eaten, arr num num num. This is a fatefor e%eryone in the room, and so our function has to check, for e%ery layerand "+ in the room, if they ha%e rotection. /et that be a lesson, boys andgirls don't go out without some rotection on you.

/et's start by just getting all the objects that are currently in the room. *e dothis using allin%entory. This will get e%erything in the room ) layers, "+s,and items that haen to be lying on the ground.

void eaten_y_grue() {oect =room_contents;room_contents N all_inventory (this_oect());

%

There are more comact ways to do the ne$t few bits, but don't worry aboutthose ) we're going for simle, easily comrehensible code here so as each

ste is clearly understandable.(nce we ha%e our list of objects, we want to get the ones that are classed bythe MUD as li%ing 6"+s and layers7. *e use the li%ing efun for this ) if wewanted layers only, we'd use the interacti%e or user efuns instead?

void eaten_y_grue() {oect =room_contents;oect =living_oects N ({ %);oect o;

room_contents N all_inventory (this_oect());

foreach (o in room_contents) {if (living (o)) {living_oects AN ({ o %);

%%

%

"ow, we want to ste o%er each of those li%ing objects we'%e found, and detectwhether they ha%e the amulet. /et's slow down here and think about thisincrementally ) how would we do it for one li%ing objectJ

Michael >eron #age ,-6

Page 127: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 127/150

LPC For Dummies 1, Second Edition

*ell, first we'd need to see whether that object had an amulet on them ) that'seasy, that's what matchobjectsfore$istence does?

matches N match_oects_for_existence ("lac* ox recorder amulet",

living_oects[$\);

The amulet itself has a -uerywornby function that tells us who is wearing it,so we can use that. *e need to check o%er each of the amulets returned bymatchobjectsfore$istence, e%en we e$ect layers to just ha%e one. Theymay ha%e two, and it would be a little unfair if they were eaten because wehaened to check if they were wearing the wrong one.

*e're going to use a integer %ariable here called safe to determine if someoneis to be eaten. If safe is 2, that indi%idual doesn't get eaten. If it's H, they do.

safe N $;

matches N match_oects_for_existence ("lac* ox recorder amulet",living_oects[$\);

foreach (amulet in matches) {if (amulet9D0uery_&orn_y() NN living_oects[$\) {safe N #;

%%

*e can assume at the end of this foreach that any layer it is still dealing withis not rotected from our %icious grues. *e tell them they ha%e been foundwanting, and the unceremoniously slay them?

if (safe NN #) {tell_oect (living_oects[$\, "2ou are udged and found &orthy!n");

%else {tell_oect (living_oects[$\, "2ou are devoured y a grue!n");tell_room (this_oect(), living_oects[$\9D0uery_short()

A " is devoured y a grue!n", ({ living_oects[$\ %));living_oects[$\9Ddo_death();

%

There's a lot haening here, so let's look at it in conte$t?

safe N $;

matches N match_oects_for_existence ("lac* ox recorder amulet",living_oects[$\);

Michael >eron #age ,-"

Page 128: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 128/150

LPC For Dummies 1, Second Edition

foreach (amulet in matches) {if (amulet9D0uery_&orn_y() NN living_oects[$\) {safe N #;

%%

if (safe NN #) {tell_oect (living_oects[$\, "2ou are udged and found &orthy!n");

%else {tell_oect (living_oects[$\, "2ou are devoured y a grue!n");tell_room (this_oect(), living_oects[$\9D0uery_short()A " is devoured y a grue!n", ({ living_oects[$\ %));

living_oects[$\9Ddo_death();%

+lease make sure you understand each ste and how all the %ariables relate to

each other it's -uite comlicated. This is easily the most comlicated iece ofcode we'%e encountered thus far. :owe%er, it ro%ides a baseline for some

 %ery common functionality.

"ote that this only works for one single indi%idual in the room ) our last steis to do all of this in a foreach so it stes o%er each indi%idual and erformsthe same checks?

foreach (o in living_oects) {safe N $;

matches N match_oects_for_existence ("lac* ox recorder amulet",o);

foreach (amulet in matches) {if (amulet9D0uery_&orn_y() NN o) {safe N #;

%%

if (safe NN #) {tell_oect (o, "2ou are udged and found &orthy!n");

%else {

tell_oect (o, "2ou are devoured y a grue!n");tell_room (this_oect(), o9D0uery_short()A " is devoured y a grue!n", ({ o %));

o9Ddo_death();%

%

The tellroom and tellobject functions are new to us ) they're what's used tosend messages around the MUD. The first tells the layer secifically whathaened to them?

Michael >eron #age ,-&

Page 129: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 129/150

LPC For Dummies 1, Second Edition

tell_oect (o, "2ou are devoured y a grue!n");

The first arameter is the object to which we send the message, and thesecond is the message itself.

Tellroom is a little more comlicated ) it tells e%eryone in the secificcontainer object 6in this case, a room7, e$cet for those secified as beinge$cluded. The first arameter is the room to send the message to. The secondis the message itself, and the third is an array of objects that are not to seethe message. *e e$clude the current object from the tellroom, because theyalready get a tellobject sent to them.

Udate the room and call eatenbygrue to make sure it works ) try it whilewearing the amulet, and try it without.

*hen you'%e tried it without, you'll notice something disaointing ) the death

message is ery Dull?

[dra**os Cdra**osD *illed y dra**os (&ith a call)\

 >ee9, what is the oint of being eaten by a grue if you don't at least get to seean interesting death messageJ "o oint at all, I say... so let's make sure weha%e one. Death messages are based on a -uerydeathreason functiondefined in the object that is resonsible for calling dodeath. 4o let's add oneof those?

string 0uery_death_reason() {return "eing eaten y a grue";

%

This by itself is not enough, we also need to add the room to the indi%idual'slist of attackers so that the MUD knows what caused the death. *e use theattackby method for this, before we call dodeath?

o9Dattac*_y (this_oect()); o9Ddo_death();

 0nd that, as they say, is it! "e$t time the grues find you wanting, the followingdeath message will be triggered?

[dra**os Cdra**osD *illed y eing eaten y a grue C5earningD\

That's much more entertaining, and that's what we're all here for.

Michael >eron #age ,-8

Page 130: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 130/150

LPC For Dummies 1, Second Edition

ettin !o Our #ho* Of Horror

 0t the moment our sho is inaccessible. *e need to change that in ourmarketsoutheast file. To a%oid eole simly stumbling into the store with no

warning, we're going to make entrance based on an e$it function. 5irst, weadd the e$it as normal to our room?

add_exit ("east", LKKB A "magic_shop", "door");

 0nd then we modify that e$it ) in this case, to indicate a function that is to becalled when eole attemt to take the e$it?

modify_exit ("east", ({"function", "&arn_player"

%));

The e$it function will only be called if you are not currently sorting thedemon roerty, so make sure you remo%e that before you attemt to writethis art of the room.

*hene%er anyone tries to take this e$it, the MUD will call the functionwarnlayer. If that function returns a 2, the layer is ermitted to take thee$it. If that function returns a H, then they are stoed.

 0 secial word of warning ) don't use thislayer67 in an e$it function ) if alayer is following another layer through an e$it, only the first layer wille%er be returned from thislayer67. Instead, use the arameters assed to thefunction by the MUD?

int &arn_player (string direction, oect o, string special_mess) {%

The first arameter is the direction of the e$it. The second is the object takingthe e$it 6you use this rather than thislayer677, and the third is the messagethat will be dislayed to the destination room. Usually we don't need to worryabout either the first or third arameters, and can concentrate urely on thesecond.

*e're going to ro%ide a warning here when a layer is warned, they get atimed roerty laced on them. If they attemt to take the e$it while theyha%e the roerty, they get let through?

int &arn_player (string direction, oect o, string special_mess) {

if (o9D0uery_property ("een &arned aout grues") NN #) {return #;

Michael >eron #age ,09

Page 131: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 131/150

LPC For Dummies 1, Second Edition

  %tell_oect (o, "The room ahead smells of grues... are you sure you ""&ant to ris* itRn");

o9Dadd_property ("een &arned aout grues", #, #3$);return $;

%

:owe%er, when taking this e$it for the first time, we get an ugly bit outoutut?

The room ahead smells of grues... are you sure you &ant to ris* itRTry something else.

That 'try something else' is a conse-uence of the way the MUD deals witherror messages. *e want rid of that, so we need to add a little bit of black

magic to our function a notifyfail function, which can be used to o%erridethe normal 'try something else' error message as we see abo%e. This is theonly lace you should use notifyfail without a %ery good reason ) if you don'tknow what those reasons might be, then you don't ha%e one.

int &arn_player (string direction, oect o, string special_mess) {if (o9D0uery_property ("een &arned aout grues") NN #) {return #;

%tell_oect (o, "The room ahead smells of grues... are you sure you ""&ant to ris* itRn");

notify_fail ("");o9Dadd_property ("een &arned aout grues", #, #3$);return $;

%

"otifyfail lets you change the fail message that aears, and in this case wesimly suress it entirely we already gi%e them the information they needas art of the tellobject. Udate the room, and e%erything should fit togetherlike a greased u jigsaw.

Conclusion

 0rrays ha%e unlocked some truly owerful functionality for us, but themaniulation of arrays may still be confusing. 0ll I can recommend is ractice) it doesn't get any more imortant than understanding how arrays work, andif you are not one hundred ercent on how they work you should find code andread code and ask -uestions and shout and scream and stam your feet until

 you are. I'm not e%en kidding!

Michael >eron #age ,0,

Page 132: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 132/150

LPC For Dummies 1, Second Edition

The only bit of synta$ left for us in /+ for Dummies one is the maing, andthat's the toic for the ne$t chater. #ou'%e already come so far ) there's notlong left to go!

Michael >eron #age ,0-

Page 133: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 133/150

LPC For Dummies 1, Second Edition

Ma**in 't Out

'ntroduction

The last data tye we're going to e$lore as art of /+ for Dummies 2 is themaing. It goes by different names in different rogramming languages, butif you e%er hear eole talking about an 'associati%e array' or a 'hashtable' or'hashma', it's this data tye to which they are referring. Maings are aninternally comle$ data tye, but you don't need to worry about any of that )we just need to know how to maniulate them, and that's our toic for thissection.

4o, let's not dilly dally, let's get stuck in!

 !he Ma**in

Imagine you wanted a way to link together ieces of data. 5or e$amle, if wewanted to store the guild le%el and the name of layers, we'd need two arrays) one of strings containing names, and another of integers holding le%els, likeso?

int =guild_levels N ({ %);string =player_names N ({ %);

Then, when we wanted to add a layer's guild le%el, we'd add their name andle%el to the aroriate arrays?

player_names AN ({ "dra**os" %);guild_levels AN ({ #: %);

*e'd need to do this each time that we wanted to add a new airing of data?

Inde1 player$names guild$levels

H drakkos 233

2 taffyd CCC

@ terano 2@@

Michael >eron #age ,00

Page 134: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 134/150

LPC For Dummies 1, Second Edition

 0 maing is essentially a data structure that allows for that kind ofrelationshi between elements. *riting your own association between arraysis time consuming and rone to roblems when it comes to making suree%erything gets maniulated at the right time at the right way in both arrays,

and as soon as one mistake is made with this the entire set of data losesintegrity. Using a maing means that the MUD does all the Tedious usy*ork for you, and that's what we're looking to do as rogrammers ) offloadtedious busy work onto the comuter.

 0 maing is declared thusly?

mapping my_map;

 0nd set with an emty internal state using the maing notation?

my_map N ([ \);

"ote that this is subtly different from an array ) it's s-uare brackets withinrounded brackets rather than braces within rounded brackets.

If we want to setu a maing with some starting %alues, we use thefollowing?

my_map N (["dra**os" I #:,"taffyd"I 888,"terano"I #33:,

\);

"ote that each of the key%alue airs are searated by a colon rather than acomma.

 0s with the array, we need to know how to maniulate a maing before wecan really make use of it, and before we do that we need to talk about the

terminology of a maing. Unlike an array, a maing does not ha%e an inde$by which it can refer to elements. Instead, a maing has a key  and valueairing. 0 articular key is linked to a articular %alue. (ur e$amle abo%e, ina maing, would look like this?

5ey 8alue

drakkos 233

taffyd CCC

terano 2@@

Michael >eron #age ,03

Page 135: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 135/150

LPC For Dummies 1, Second Edition

Thus, the key drakkos will ha%e the %alue 233, and the key taffyd will

ha%e the %alue CCC.To ut a %alue into the maing, we use the following notation?

my_map ["*ey"\ N value;

4o, to add in a fourth entry?

my_map ["gruper"\ N 8Z;

 0t this oint, our maing looks like this?

5ey 8alue

drakkos 233

taffyd CCC

terano 2@@

gruer CG

To ull out a %alue, we use a similar notation?

 int value;value N my_map["terano"\;

*e don't need to know in what osition of the maing we need to look for %alues, because the maing does that for us. Indeed, you can't guaranteethat the order in which you add %alues has any relationshi to how they arestored internally for all sorts of omlicated Technical ;easons. #ou ha%e tothink of it a bit like a bag of data rather than a list.

To remo%e an element from the maing, we use the madelete function, likeso?

map_delete (my_map, "terano");

Michael >eron #age ,05

Page 136: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 136/150

LPC For Dummies 1, Second Edition

This looks through our keys in the maing for a match, and then remo%esthat match from the maing?

5ey 8alue

drakkos 233

taffyd CCC

gruer CG

 0lthough syntactically simle, they are -uite comlicated concetually ) soonce again, we're going to use an e$amle to illustrate how they actuallywork.

 !he Maic Hate Ball

*e're going to add a new item to our marketlace ) a magic hate ballmounted on a linth. This will be in marketnortheast?

>include "path.h"

inherit "/std/room/outside";

int do_hate();

void setup() {set_short ("northeast corner of the mar*etplace");add_property ("determinate", "the ");set_day_long ("This is the northeast corner of the mar*etplace. ""- magic hate all is mounted on a plinth, attached y a chain. ""Bunlight glints on its malevolent surface.n");

set_night_long ("This is the northeast corner of the mar*etplace. ""- magic hate all is mounted on a plinth, attached y a chain. ""Btarlight glints on its malevolent surface.n");

add_item ("magic hate all",({

"long", "The magic hate all gives &isdom &hen you sha*e it!",

"sha*e", (I do_hate I),%)

);

set_light (#$$);add_one ("learnville");

add_exit ("north", LKKB A "stay_oe", "door");add_exit ("south", LKKB A "mar*et_southeast", "path");add_exit ("east", LKKB A "itter_pill", "door");add_exit ("&est", LKKB A "mar*et_north&est", "path");add_exit ("south&est", LKKB A "mar*et_south&est", "path");

modify_exit ("south&est", ({"ovious", $%));

Michael >eron #age ,06

Page 137: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 137/150

LPC For Dummies 1, Second Edition

  set_lin*er ( ({LKKB A "mar*et_north&est",LKKB A "mar*et_south&est",LKKB A "mar*et_southeast",

%) );%

int do_hate() {return #;

%

"ote that we're using the function ointer notation for the additem ) we needto use that when we attach functions to %erbs in additems. In /+ 5orDummies @ it will become clear why, but for now you're going to ha%e toaccet that sometimes you can use the < notation, and sometimes you need touse the function ointer notation.

*hat we're going to get the magic hate ball to do is gi%e eole who shake it a %enomous message, and if they shake it again it reeats the same message.Thus, e%eryone gets a random message the first time they shake it, but theball is consistent with its ad%ice. *e need a classwide %ariable for this so thatit gets stored between e$ecutions of our function?

mapping previous_responses N ([ \);

In our function, we first need an array of ossible resonses?

string =random_responses N ({"Bhut up and die."," slept &ith your &ife.","Buicide is your only option.","Hveryone hates you.","2ou suc*.",

%);

ack to the idea of incremental de%eloment ) let's just follow through therocess of someone getting a resonse for the first time. *e select a randomresonse, and dislay it?

int do_hate() {string response;string =random_responses N ({"Bhut up and die."," slept &ith your &ife.","Buicide is your only option.","Hveryone hates you.","2ou suc*.",

%);

Michael >eron #age ,0"

Page 138: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 138/150

LPC For Dummies 1, Second Edition

  response N element_of (random_responses);tell_oect (this_player(), "The magic hate all saysI "A response A "n");

return #;%

That will gi%e a random resonse each time, but if we want to store theresonse we then need to ut it in our maing. 5irst, we need a key ) thiswill be the name of the layer. *e declare a string %ariable called layer atthe to of our function, and then set it to be whate%er the layer's name is?

 

player N this_player()9D0uery_name();

efore we get to generating a resonse, we need to check to see if there'sbeen a re%ious resonse by -uerying our maing with the key we justac-uired?

response N previous_responses[player\;

The resonse we then gi%e to the layer is deendant on whether there isanything in this %ariable, like so?

if (!response) {response N element_of (random_responses);previous_responses[player\ N response;

tell_oect (this_player(), "The magic hate all saysI "A response A "n");

%else {tell_oect (this_player(), "The magic hate all saysI already ""told youI " A response A "n");

%

+utting that all together gi%es us the following?

int do_hate() {string response;string player;string =random_responses N ({"Bhut up and die."," slept &ith your &ife.","Buicide is your only option.","Hveryone hates you.",

"2ou suc*.",

Michael >eron #age ,0&

Page 139: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 139/150

LPC For Dummies 1, Second Edition

  %);

player N this_player()9D0uery_name();response N previous_responses[player\;

if (!response) {response N element_of (random_responses);previous_responses[player\ N response;tell_oect (this_player(), "The magic hate all saysI "A response A "n");

%else {tell_oect (this_player(), "The magic hate all saysI already ""told youI " A response A "n");

%return #;

%

/et's ste through that rocess from the ersecti%e of a layer. +layer comesalong and says ':ey, cool eight ball. I am going to shake it 'till I break it!'.They shake the ball, and the first thing the function does, after setting u therandom resonses, is to get the layer's name, which is drakkos, and then-uery our maing to see if the key drakkos has a %alue associated with it.(ur maing though is comletely emty.

It's emty, so no resonse is to be found. The code then icks a randomresonse from our list, let's say it's #ou suck, and then uts that %alue intothe maing associated with the key of the layer name?

5ey 8alue

drakkos #ou suck.

It then rints out our message?

D sha*e allThe magic hate all saysI 2ou suc*. 2ou sha*e the magic hate all.

'My word!', e$claims Drakkos. 'That is rather rude, and no mistake! *hy, Ishall shake this little rascal again to see what it has to say!

Drakkos shakes the ball again ) this time, when it comes time to -uery themaing, there's already a resonse stored. That gets stored in the %ariable'resonse', and when we get to the if statement resonse is no longer emtyand so the else clause is e$ecuted?

The magic hate all saysI already told youI 2ou suc*.2ou sha*e the magic hate all.

Michael >eron #age ,08

Page 140: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 140/150

LPC For Dummies 1, Second Edition

4addened and aalled by this inhuman criticism, Drakkos wanders off into asho, and ends u eaten by a grue. This area, he decides, was not written by anice erson. *hy so mean, magic hate ballJ *hy so meanJ

More Ma**in Mani*ulation1 Mate"

There are three further things we might like to do with a maing in order tomaniulate it effecti%ely. (ne is to get a list of all the keys in a maing ) wecan do that with the keys function. It returns it as an array?

string =names;names N *eys (my_map);

This will gi%e us e%erything in the left hand column of the maing. 8oingback to our e$amle maing?

5ey 8alue

drakkos 233

taffyd CCC

terano 2@@

gruer CG

8etting the keys of this will return the following array?

({"dra**os", "taffyd", "terano", "gruper"%)

*e cannot guarantee that the elements will be returned in that articularorder, but all of those elements will be resent.

 0nother thing we might like to be able to do is get all of the %alues. This isdone in a similar way, using the %alues function?

int =levels;levels N values (my_map);

This will return the following array from our e$amle maing?

({ #:, 888, #33:, 8Z %)

Michael >eron #age ,39

Page 141: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 141/150

LPC For Dummies 1, Second Edition

 0gain, in no guaranteed order. If we want to enforce some kind of order onthis, the we must handle it oursel%es.

5inally, we may wish to ste o%er each of the key and %alue airings in turn,erforming some kind of oeration. *e can do that longhand like so?

string =*eys;string *ey, value;*eys N *eys (previous_responses);

foreach (*ey in *eys) {value N previous_responses[*ey\;tell_oect (this_player(), *ey A " &as told +" A value A "+n");

%

:owe%er, /+ is nice enough to gi%e us a foreach structure urely forhandling maings! The abo%e code rolls into a simle foreach, like so?

foreach (*ey, value in previous_responses) {tell_oect (this_player(), *ey A " &as told +" A value A "+n");

%

/et's try that out by adding a 'consult' otion to our ball?

add_item ("magic hate all", ({"long", "The magic hate all gives &isdom &hen you sha*e it!","sha*e", (I do_hate I),"consult", (I do_consult I),

%));

*e'll need a function rototye at the to of the code?

int do_hate();int do_consult();

 0nd folding in the code we just discussed?

int do_consult() {string *ey, value;foreach (*ey,value in previous_responses) {tell_oect (this_player(), *ey A " &as told +" A value A "+n");

%return #;

%

Michael >eron #age ,3,

Page 142: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 142/150

LPC For Dummies 1, Second Edition

"ow we can consult to see what e%eryone has been told by the hate ball?

D consult allra**os &as told +Bhut up and die.+ 2ou consult the magic hate all.

 0las though, if noone has been told anything, we get a fairly emty message?

D consult all2ou consult the magic hate all.

*e should ut a check to ensure that if the maing is emty, we get thearoriate message. /uckily si9eof works for maings as well ) it gi%es usthe number of keys in a articular maing, so we can fi$ that -uite easily?

int do_consult() {string *ey, value;if (sieof (previous_responses) NN $) {tell_oect (this_player(), "Fo9one &as told anything. Fo& curl up ""and die.n");

%else {foreach (*ey,value in previous_responses) {tell_oect (this_player(), *ey A " &as told +" A value A "+n");

%%return #;

%

"ow we get a much better e$erience when we try to consult an emty hateball?

D consult allFo9one &as told anything. Fo& curl up and die.2ou consult the magic hate all.

Thanks for the udate, magic hate ball!

Michael >eron #age ,3-

Page 143: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 143/150

LPC For Dummies 1, Second Edition

Conclusion

It's unlikely you're going to need to do much with maings at this stage of your reator areer ) they are usually a art of more comlicated

functionality. It's imortant though that you understand what they are andhow they are maniulated ) you'll likely encounter them -uite a lot as youread through e$amle code. They are -uite unseakably useful ) so useful infact that when working in an en%ironment where you don't ha%e easy accessto them, you miss them with a rimal yearning. /uckily that's not a roblemfor us on Discworld, for we are well suorted in our Maing Use;e-uirements!

Michael >eron #age ,30

Page 144: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 144/150

LPC For Dummies 1, Second Edition

#o Lon

'ntroduction

 #ou'%e done %ery well to get this far ) rogramming is not an easy taskregardless of what anyone tells you. +erhas the most frustrating thing thatgoes with learning how to do it is how easily some eole 'get it'. It'sunfortunate that not e%eryone finds it as easy as other eole, but thewillingness to erse%ere can trum that initial natural understanding. :a%ingthe ersonality to continue when it gets hard is what searates a rogrammerfrom a talented amateur.

 #ou may %ery well fall into the category of talented amateur yourself, in whichcase this should be a warning for you too ) e%eryone struggles at one oint oranother to get something working, and if it's been easy all the time then youneed to be willing to dig dee and find the will to go on when things start tobecome difficult.

 0nyway, in this brief chater we shall wra u our initial foray into /+ andtalk about what haens ne$t.

 !he Past

/earn%ille isn't e$actly what you'd call a finished area ) there are bits that arenot described, and other bits that ha%e no interesting functionality. That'sokay because it's not for the eyes of layers ) it's a roject so that you can seethe rocess by which an area can be built. There are bits of /earn%ille that are-uite sohisticated, and if you'%e managed to kee u with the code then youcan make use of %ariations of what we'%e talked about to great effect.

/earning how to de%elo on Discworld is a tworonged roblem. To beginwith, you need to know how rogramming code works, and this is in itself anentire te$tbook of knowledge. This is a transferable skill ) the coding

structures that you'%e learned as art of this introduction to /+ aretransferable to most rogramming languages. Indi%iduals interested in seeinghow transferable their skills actually are in%ited to e$lore my >a%a te$tbooksat Monkeys 0t Keyboards.

ombined with the understanding of generic coding structures, you need tolearn the secific code that is uni-ue to Discworld ) how to create rooms,"+s and items. Then you need to learn how to link them u, and make themdo interesting things.

Michael >eron #age ,33

Page 145: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 145/150

LPC For Dummies 1, Second Edition

 0 good creator is not just a coder ) a good creator has an unusual blend ofskills. 0 good creator can architect rojects, write well, and roduce robustcode. 0 beginner can only be e$ected to master one of these to start with,but you need to be able to do all three before you can think of yourself as a

wellrounded creator. It's not an easy task.4o, let's reca what you'%e learned so far, and ro%ide some conte$t... there'sbeen a lot of content, and so you may be forgi%en for ha%ing not really reali9edhow much you'%e actually done.

In terms of generic rogramming structures, you'%e learned?

• ariables and %ariable scoe

•If and 1lseif statements

•4witch statements

•5unctions and function scoe

•5or and 5oreach loos

•*hile loos

• 0rrays

•Maings

•:eader files

 0 substantial subset of these are resent in most modern rogramminglanguages, and understanding how these work in /+ is the first ste tounderstanding how they work in other en%ironments. The synta$ may bedifferent, but the concets are identical.

In terms of what you'%e learned about Discworld de%eloment, we can add tothat?

Inside and outside rooms•Day and night items, chats and long descritions

•:ow to use the linker

•"+s

•:ow to use the 0rmoury

•4earching items

•:ow to use the taskmaster

 irtual objects

Michael >eron #age ,35

Page 146: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 146/150

LPC For Dummies 1, Second Edition

•Modifying e$its

•Item and general shos

•"+ combat actions

• 0dding sells to "+s

•(bject matching with matchobjectsfore$istence

That's -uite a list of accomlishments, and a well deser%ed at on the back isdeser%ed for you for ha%ing learned all of these. I won't say mastered, becausethere's always more to learn about all of these things, and only diligente$loration of the MUD will re%eal the more obscure features of all the thingswe'%e discussed.

 !he Present

4o, what haens now you'%e learned all of thisJ *ell, you'%e undoubtedlybeen assigned a newbie roject by your domain administration, and your focusshould be on de%eloing that to as high a standard as you can. There are alsosmall rojects a%ailable for those who want to aly their new found skills to asmall, oen roject with the intention of it being slotted into an e$isting areaof the game to add richness.

ut more than simly your current rojects, you should be e$loring thecodebase. ertainly within your own domain, think of things you enjoyed whilelaying and hunt out the code that handled it. ;ead the code, and try tounderstand how it works. 0ll coding is, to a greater or lesser degree,lagiarism ) you can gain huge amounts of understanding by just readingwhat has come before.

The roblem with this of course is that you don't necessarily know if the codethat you find is 'good code'. *e'%e had many hundreds of creators of %aryingdegrees of ability o%er the long years of Discworld, and not all of the code issomething you should be emulating. If you wonder whether code is worthusing as a temlate, then feel free to contact me or one of the domain Mentatswho will be able to gi%e you guidance.

 0s far as e$loring code outside your domain goes, you should definitelyac-uaint yourself with the code in &obj& and &std&. 5or other domains, ask thedomain lord if they mind you scrutini9ing the code for insiration. :ardlyanyone will mind, but it's olite to ask. Talk to other creators, esecially thosewho may be as new as you. +art of what makes being a creator so much fun isthe social en%ironment in which you function, and you should take fullad%antage of that.

Michael >eron #age ,36

Page 147: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 147/150

LPC For Dummies 1, Second Edition

 #ou should also feel free to talk to members of the /earning domain,articularly the leader of the domain ) it's only by talking to eole like youthat we know what things you want to know about! 0sking for information ona articular toic is as helful to us as it 6hoefully7 is for you!

 !he Future

There will come a oint, hoefully not too far in the future, when you feel you're ready to learn new things. *e'%e only scratched the surface of the kindof things that get written on Discworld, and there is e$citing territory to come.5rom here, you can mo%e on to eing 0 etter reator, *orking *ith (thers,and /+ 5or Dummies @.

/+ for Dummies one is the first of four related te$ts. Two of these focus on

the softerside of Discworld creators, and the last is a more ad%anced guide to/+ de%eloment. #ou should familiarise yourself with all of them there's alot discussed across these te$ts #ou can think of them as your %ery ownDiscworld reator Manual.

It would be a good idea to at least finish your first domain roject before youworry about e$anding into this territory ) getting a feel for the comle$ity ofde%eloment and the things that you wish you knew how to do will make thelessons in later %ersions of the te$ts more %aluable.

ConclusionThat's us for now! #ou're done with /+ for Dummies and you can emergefrom the room in which you kee your comuter... the bright sunlight mayhurt at first, but that'll go away with time. *e'll see you again soon though, oh

 yes. *e'll see you soon...

Michael >eron #age ,3"

Page 148: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 148/150

LPC For Dummies 1, Second Edition

eader 45ercises

'ntroduction

"ow that weY%e reached the end of your introductory %oyage through /+,letYs gi%e you some homework to see how well youY%e learned your lessons.5ull answers to 6almost7 all of these e$ercises are a%ailable, but leaseattemt them yourself first ) you learn more by trying than by reading whatother eole ha%e done for you.

45ercises

Fill In The Blanks

*e ha%enYt done a lot of descriti%e work for /earn%ille, focusing instead onthe code we needed to build it. #ouYll learn a lot howe%er from going o%ereach of the rooms and filling in the blanks. 1nsure each room has thefollowing?

2. 0 day and night long descrition

@. Day and night additems

3. Day and night room chats

Imortantly, make sure e%ery noun in your long descrition and in youradditems is included. This is something eole will look for in your rooms belie%e me.

There is no worked e$amle for this, but if you go through this rocess andwould like to %olunteer it as an e$amle for other eole, then send it to meand we can make it so.

Connect To Your Workroom

:a%ing gone to the trouble of making this %illage, you should be able toadmire it whene%er you like ) it should connect into your workroom. :owe%er,

 youYre also at some oint hoefully going to rogress onto etter%ille. reatea new room in your directory and call it accessoint. /ink this room to yourworkroom, and link /earn%ille to it too. 0dd an e$it function to the /earn%ille

e$it that makes sure only creators can enter your de%eloment.

Michael >eron #age ,3&

Page 149: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 149/150

LPC For Dummies 1, Second Edition

Playing Dress-Up

Most of our "+s are scantily clad at best. #ou should imro%e this situationby making sure they are aroriately dressed. 1ach "+ should ha%e a shirt,a air of trousers, underwear, socks, and a air of shoes or boots. Make surethis is true of all of your "+s, and that you ick sensible instance of each asto befit their status.

The ery !o"el of a !o"ern !a#or $eneral

atain eefy has no weaon, which is somewhat out of theme for a man ofhis military background. Using the same kind of system as you did for his ringand his boots, create a beefysword. It will be sa%ed as a .we file, and youshould look at e$isting e$amles of %irtual weaons to ensure you set all theright %alues.

(nce youY%e done this, gi%e him a suitable scabbard 6.sca7, and make sureboth of these are ro%ided to him when he is setu. :is sword should becloned inside the scabbard, and he should be wearing the scabbard along withthe rest of his outfit.

%esponsi&eness

*hile our "+s ha%e se%eral resonses built into them, it would be nice ifthey were more resonsi%e generally. 0dd in code to each of them that makesthem resond ositi%ely to being greeted, both as a say and as a soul.

 0dditionally, make them resond to your name with an aroriate amount offear and cowering awe.

Make them all resond to the names of each other, with a little commentabout who they are 6those "+s that already ha%e such resonses can be leftalone7. 5or e$amle, if I say ZbeefyY they could say Z(h, eefy ) he was our first"+!Y.

5inally, when I ask where certain "+s are, such as Z*here is eefyJY, theyshould tell me where I am likely to find them.

'eashing

The code we ha%e for loading "+s has the imact of ZleashingY them to asecific room ) if eefy is found elsewhere in the %illage when afterreset iscalled, heYll be magically transorted somewhere else. hange this so that he6and all other rele%ant "+s7 get mo%ed into the room only if they ha%e noen%ironment. To make sure that they cannot then wander outside /earn%ille,ut a creator check on your e$it in accessoint

Michael >eron #age ,38

Page 150: lpc1

7/25/2019 lpc1

http://slidepdf.com/reader/full/lpc1 150/150

LPC For Dummies 1, Second Edition

(earching

 0dd in a mention of a Zit of sandY somewhere in the de%eloment, andincororate a new search function. This search function should allow thelayer to search fi%e times in a reset eriod ) the first time gi%es a sword, thesecond a shield, the third a helm, the fourth a breastlate, and the fifth a airof blue satin anties. The state of the it should be shared amongst layers, sothat if another layer comes in and searches, they ick u from where the lastone left off.

) !ountain Path

(ne of the things that changing the mo%e messages with modifye$it allows you to do is create a sense of conte$t to mo%ing. hange the ath leading tothe %illage s-uare so that it simulates climbing u a mountain trail. 5or

e$amle

2ou clim the &inding trail to the northeast

4imilarly, when heading back down the trail to accessoint, ha%e thatdescribed to the layer also.

)n *pen )n" (hut Case

Making use of the -ueryfighting lfun, make sure that our sho is notconsidered to be oen when its rorietor is currently engaged in combat.