In this section we will be exploring how to group objects together so that we can perform the same action on many objects all at the same time. To be able to do this we are going to use lists.
Download TheHerd.a2w the from the bottom of this page. In this world you will see 5 boars who want to move as a herd. Now we could have one DoTogether tile that contains one call for each boar to move forward:
But the code would grow very large if we were to have them do something more complex (for example, move a little, jump up, spin in the air, land on their hind legs and keep walking) and it would be a hassle if we wanted to add a sixth boar to also do that with the other boars. To make it easier, we will put the boars in a list and then we will iterate over the list, meaning we will go through the list and have them each do something.
Let's build this up together. First let's identify what we want to happen in English:
Each boar, at the same time, should move forward 5 meters
The first thing we need is a way to group all the boars. Click on World, then properties, then create new variable.
You should see something like this:
The name should be herd because we are treating the boars like a herd. The type should be object because we want to have a list of the boars. Then check the make a List box. You should see this:
Now click on the new item button and add each of the 5 boars to the list:
Then click OK. Now you should have a list of the boars:
Now we need to iterate through that list and tell each of the boars to move forward 5 meters, but all at the same time. To do this, go back to my first method then drag a for all together tile into the method, when you drop it you will be asked to choose the herd list from the expressions menu:
The code will then look like:
Now we need to have each item from the herd list move forward 5 meters. To do this, drag item_from_herd into the Do Nothing part of the for all together tile, then choose the move method from the menu:
Drag item_from_herd:
Choose move forward 5 meters:
Your code should then look like:
Click play. Did it work?
[Q11.2.1]: Given the code below, will all the Ballerinas spin?