How to Write a Populate Procedure in MicroWorld EX - dummies

How to Write a Populate Procedure in MicroWorld EX

By Camille McCue

To create a population quickly in a MicroWorld EX game around a main character like Wallace the walrus, you need to write a populate procedure and make a button to execute that procedure.

On the project Procedures pane, type the following populate procedure:


to populate
newturtle "t1
repeat Number [clone "t1 setsh pick [earmuffs scarf hat goggles]]
remove "t1
everyone [setx random 640 sety random 480]

The populate procedure works as follows:

  • A newturtle is added to the searchpage and named t1. It then makes t1 visible with the command st (show turtle). t1 is wearing a special shape — it just appears as the default turtle shape.

  • repeat executes Number times the commands inside the square brackets. The value of Number is set by the slider and represents the number of distracter turtles who hang out with Wallace. On each repetition, the t1 turtle is cloned so that a new numbered turtle is added (t2, t3, t4, and so on).

    As each new turtle is added, a shape is picked randomly from the distracter shapes: earmuffs, scarf, hat, or goggles and applied to the turtle. Note: Don’t forget that Wallace the walrus turtle is still sitting there nicely in the workspace — he is the only turtle with a special name.

  • Following completion of the repeat, the t1 turtle is removed using the command remove “t1. The t1 turtle serves only as a seed for cloning the distracter turtles.

  • Finally, the command everyone [setx random 640 sety random 480] gives everyone in the workspace a random coordinate position. Wallace and each of the distracters set their x-coordinate to random 640, the width of the workspace. Wallace and all distracters also set their y-coordinate to random 480, the height of the workspace.

Many games and simulations require objects to be scattered into random positions. Examples include distributing cows in a field, people in a mall, or battleships in the ocean. You will likely find yourself writing code to generate a random x-coordinate and a random y-coordinate for each object so that the entire group appears scattered. See Project 10 for details on randomly scattering objects.

Coding languages typically feature primitives for executing loops. MicroWorlds EX uses repeat in a similar way that many languages use a for command.

Other languages employ a do command, which is also used for looping and usually provides a way to exit the loop when a certain condition is met (do until). MicroWorlds EX features a related command, called dotimes. Choose Help→Vocabulary from the menu bar for additional information on using this command in your code.