MooWP Guide: Random and If-Else-Endif


Sometimes one doesn't want the same action to happen every time. The answer to this lies in a built-in verb called random (). This will return a number between 1 and the number inside the parenthesis: random (3), for example, will sometimes be 1, sometimes 2, and sometimes 3. You can use this to pick out a random action from a list of actions. For another possibility, let's suppose that you want people who cook in your kitchen to be successful sometimes and not at others. Look at the following:
if (random (4) == 1)
$you:say_action ("%N %<cooks> a delicious meal.");
else
$you:say_action ("%N %<burns> the dinner and %p hands.");
endif
Notice first that the lines beginning with if, else, and endif do not end in semicolons. The first line is a way of saying if the statement in the following parentheses is true, then do what follows. The statement in the parentheses here is that a random number between 1 and 4 turns out to be 1. Notice that you have == and not just =. English uses "is" both to assign values and to talk about what is, but the moo uses x = 1 to say "let x equal 1" and x == 1 when one wants to test whether "x equals 1" is already true. The effect of the first line is to say that about 1 time in 4 your cook is going to make a good meal.

The else and what follows is optional. It is included in this verb because it would seem odd if nothing happened when one tried to cook. We could also have included elseif and an action in between the if and else sections of the verb. For an example, let's rewrite the verb above to allows for three possibilities.

x = random (4);
if (x == 1)
$you:say_action ("%N %<cooks> a delicious meal.");
elseif (x == 2)
$you:say_action ("%N %<starts> but %<winds> up chugging the cooking wine.");
else
$you:say_action ("%N %<burns> the dinner and %p hands.");
endif
Our new first line means that we don't keep on checking for random numbers; we just set the value of xonce in the beginning. The moo has some other conditionals, like while/endwhile, but if you can master if/else/endif and for-loops, you can do a lot of programming. One good way is to imitate models, verbs others have written that you like. Most moo verbs can be read by any programmer. If someone's room has a plonk verb you especially like, go to the room and type @list here:plonk

Other pages on moo programming may be found in the MooWP Guide.