Chapter 4

Design Patterns

Design Patterns are commonly-used combinations of blocks

Subsections of Design Patterns

Ask and Set

For many Scratch programs we find ourselves needing to ask the user questions and use thier answers later. If we need to ask more than one question, only the last answer is available in the answer block. The ask and set design pattern meets this need by prompting the user for an answer, then storing it in a variable:

ask and set design pattern ask and set design pattern

Example

For example, we might prompt the user for thier first and last names, and then greet them by both:

ask and set design pattern example ask and set design pattern example

Animated Move

The move () steps immediately moves a sprite the specified number of steps. But what if we want that movement to be slower, animated over time? The various glide blocks provide smooth movement, but not in the direction the sprite is facing. Instead, we can emulate this movement with a combination of repeat (), move () steps, and wait () seconds blocks:

Repeat-Move-Wait design pattern Repeat-Move-Wait design pattern

The total number of units moved is the product of the number of repeats and the movement in the block (i.e. repeating a movement of 2 units five times is $$2 * 5 = 10$$ total units moved). The value of the wait () block determines how fast the sprite moves. A small value (i.e. 0.06, roughly 1/16 a second) will give good results.

A slighly more sophisticated version adds sprite animaiton, swapping frames each step forward:

Repeat-Move-Wait-Next-Costume Repeat-Move-Wait-Next-Costume