Broadcasting and Receiving Messages (Part 2)
-
Prerequisite
Introduction
On another wiki page, you learned how to broadcast and receive messages.
There are some more advanced ways to use messages. We will discuss them on this page.
Messages with Parameters
When we broadcast a message, we can choose to attach a parameter to it. It allows us to reuse the same message type.
For example, in this project, the Cody sprite asks the user to specify how many turns to make. If the user’s answers “1”, then Cody will broadcast “turn 1”, and the other 2 sprites will make 1 turn. Similarly, if the user’s answer is “2” or “3”, Cody will broadcast “turn 2” or “turn 3”, and the other 2 sprites handle those messages as well.
Although this program works fine, there is a problem. The user might input any number, such as 10 or 100. To handle all answers correctly, we would need to add many message types: “turn 4”, “turn 5”, … “turn 10”, … “turn 100” …
Fortunately, you do not need to do that. You can just send a message “turn”, then add another parameter to it, which would be the number of turns in this case:
When the other sprites receive this message, they can specify a variable, and the parameter will be stored in that variable. For example, if Cody broadcasts the message “turn” with a parameter of 10, then the Apple sprite will receive the “turn” message, and the value 10 will be stored in a new variable. After that, this variable can be used to control how many turns to make.
Similarly, the Beachball sprite can store this parameter in another variable when it receives the “turn” message:
Now our program is not only more concise, but also able to handle any number of turns!
Note that you can combine the option of “waiting” and “parameters” by using this block:
Send Message to Only One Sprite
For another more advanced option, you can choose to send the message only to one other sprite, as opposed to every sprite. This is useful when you want to keep some private messages to be only visible between 2 sprites.
For example, in the example above, you can replace the “broadcast” block with a “send” block:
As a result, only the Apple sprite will react to this message: