Design Patterns
Design Patterns are commonly-used combinations of blocks
Design Patterns are commonly-used combinations of blocks
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:
For example, we might prompt the user for thier first and last names, and then greet them by both:
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:
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:
Sprites in Scratch maintain thier state - which means that if the program was stopped with a sprite in a certain position, the next time the program is run, it will begin in that position. But for many Scratch projects, we want every sprite to start in a known position, regardless of where it last was.
One common pattern to accomplish this using messages is the Get Ready and Go design pattern. This pattern helps ensure that all sprites start at the intended position on stage, with the desired visibility, size, and effects before the program continues.
In this design pattern, a broadcast () and wait block triggers the initialization sequence by broadcasting a Get Ready
message, and waits until all when I receive () stacks finish their work before using a broadcast () block to send a Go
message (note, the names of the messages can be anything, “Get Ready” and “Go” were chosen for the ease of understanding thier meaning). The script looks like:
This script is often placed in the Stage (as it is more central to the program than sprites). Then, individual sprites (and the stage) can listen for the two messages with when I recieve () to trigger thier corresponding Get Ready and Go routines, i.e.: