Procedures in Scratch

Scratch provides the means to create your blocks. These new blocks are the Scratch equivalent of procedures with parameters. To illustrate how to create blocks in Scratch, let’s recreate the different walk procedures from the previous section in Scratch.

Example: walk

PROCEDURE walk
    1. Lift left leg.
    2. Move left leg forward.
    3. Set left leg down.
    4. Lift right leg.
    5. Move right leg forward.
    6. Set right leg down.

To create a block with the same functionality as walk in Scratch, first navigate to the More Blocks tab. Clicking Make a Block allows you to create and name a new block of your own:

Once you have created it, you can define what it does. To do this, create a block script as you would for any other event:

Using it is as simple as using any other pre-made block. Simply drag your block into a sprite’s script pane:

Now, when the program is executed, the sprite takes a step!

Example: walk n steps

walk is a simple example of a procedure. Let’s extend the idea to create the take n steps procedure from the last section:

PROCEDURE take n steps
    REPEAT n times
        1. Lift left leg.
        2. Move left leg forward.
        3. Set left leg down.
        4. Lift right leg.
        5. Move right leg forward.
        6. Set right leg down.

The take n steps procedure uses a parameter, so when the block is created, you can add a number input as an optional component, and call it n:

When you define what it does, you can use the n parameter within the block the same way you would use any other block:

Using the block with a parameter of 1 duplicates the original walk block:

Using the block with a parameter of 8 causes the sprite to take eight steps:

However, you are not limited to using pre-determined values in your blocks! As with any of the pre-defined blocks you have used, you may also include variable parameters. The following code asks the user how many steps to take,

and then behaves accordingly:

Assignment: Regular Polygon Generator Revisited

Remix the Scratch program you created in Regular Polygon Generator to work for a variable number of sides.

  1. Create a procedure that will define a parameter sides, and draw the polygon with that many sides. Your block should be named DrawRegularPolygon. Example:
  2. The procedure’s script should draw the regular polygon matching the given parameter sides. In other words, will draw a triangle, and will draw a square. You procedure should draw all regular polygons with number of sides in the range 3–10. For an extra challenge, ensure that your procedure works for any number of sides ≥ 3.

  3. Include an ask block, so that the user may direct which shapes the program draws.