Starting the Function
In the Functions section, we need to Make a New Function called “trainerFunction”. This is where we will put our HP and our sprite selection.
We do this by creating a new variable called “partyPos” (party position) that will use the “ask for a number” game block and then become that number, which we will use to say what sprite we’re picking. Kind of like picking the Nike shoes out of the box if you picked your #1 pair.
Be sure to click the “+” on the “ask for number block” and to set the “max length” to be 1. This is to make sure the player can only put one number at a time.
Preventing an Error
This function can be hit by 2 errors: the first is that your player doesn’t pick a number that matches your array, the second is that you have no monsters left. The simple fix is to use an “if true then, else” Logic block to check if “partyPos” is a number from 1 to 3 using the Logic comparison and boolean blocks.
First, place the “if true then, else” block and fill it with the “__ and __” Logic boolean block. Then place two “0 < 0” comparison blocks on either side. Fill them as “partyPos > 1” and “partyPos ≤ 3”. Be careful here: The videos on the right show ≥ instead of >, this is a mistake; it should be “>”.
The “else” part doesn’t need any conditions because it checks for any other situation.
Setting Our Sprite
To set out sprite, we need the Sprites block “set mySprite to…” Let’s make a new variable called “trainer” to keep our skills sharp. Fill in the sprite box with the Arrays block “list get value at 0” similar to how we did our enemy. This time, change it to “playerTeam”.
Here’s where it gets tricky. An array counts its length starting at 1. However, it counts the position starting at 0 position. So if your player enters 1, it will actually pull the second monster in the array. To fix this, grab the Math block “0 – 0” and fill it with “partyPos – 1”.
Lastly, for our sprite, we need to set the trainer position to x 32 and y 64.
Or Else
The “else” part of the “if” blocks means “if anything else at all happens, do this.” What we want to do is give our players a warning that their input did not work and they need to try again.
Grab the “splash” Game block and write your warning.
Under the Game block, we want to call this whole function over again so it can be corrected. A function that calls on itself is called a recursive function (or recursion).