3. Speak Function
In this video, you’ll add more dialogue to your story.
To do this, you’ll create a function by making your own block.
This will make it easier to create dialogue.
It takes three blocks to make Malik talk: “broadcast,” “say,” and “switch costume."
To create a long conversation, you would have to copy these blocks over and over.
That will make the code long, difficult to read, and hard to edit.
A function makes the same thing happen, but with a lot less code that is easier to read and work with.
Functions allow programmers to reuse code easily.
In this project, you will make it easier to reuse the code containing the “broadcast”, “say,” and “switch costume” blocks by combining these blocks into a function.
Make a function, and call it “Speak.”
To make the character say different things, add a string parameter.
Give the parameter a descriptive name, like “sentence."
Drag the code from under the "when flag clicked" block to under the define “speak” block.
Click on the “speak” block in the “more blocks” section.
The mouth moves, and the sprite says the words in the “say” block, just like it would if you clicked the block stack!
Place the new “speak” block under the “when flag clicked” event.
When you click the flag, the code you built in the last video runs.
The “speak” block has an input.
Type what you want Malik to say in that box.
This example says, “What do you want for lunch?”
The “define speak” block has an oval labeled “sentence.”
“Sentence” is a parameter that gets set to whatever gets passed in, which in this case is “What do you want for lunch?”
Malik will “say” the words in this “sentence” variable.
Replace the text in the “say” block with “sentence.”
To do this, drag “sentence” from the “define” block into the “say” block where the words Malik says used to be.
Test the code by clicking the flag.
Test again using another “speak” block.
This time, input a different sentence.
This example uses “I don't like peanut butter and jelly sandwiches!”
Try it out again.
The speak function now takes an input so the sprite can say different lines, instead of repeating the same phrase over and over.
Now, it’s your turn!
Make a function called "speak" with a string input called "sentence" to make Malik speak.
Replace the words in the “say” block with the “sentence” input variable.
Use another "speak" block to write a new line for Malik to say.