Create your functions (Python)

Create your functions

> Tutorial

Create a function

We have already used several functions and methods (setWeapon, moveToward, etc.). You can also create your own custom functions, with the following syntax:

The optional return keyword makes the function return a value. In the previous example, the function takes the parameters x and y and returns their sum: x + y.

In Python, a function must be defined before it is used. So we put our functions at the top of the file, before the main code.

Creating a canFinish(enemy) function

Our previous code for the "finish" condition on the enemy is rather long and hard to reuse, so we'll put it in a function.

We'll create a custom function canFinish(enemy), which takes an enemy and returns a boolean telling whether we can finish it off or not.

We copy the finisher code into a function, written like this:

Now we can use our canFinish function in our main code, which makes it much simpler to write:

Did you know? Moving code that appears several times into a function is called factoring.

Creating a getClosestCellToUseWeapon(enemy) function

You may have noticed that to use the Machine Gun or, later on, the Laser, you have to be in line with the enemy.

So you'll need to go to a cell from which you can use your weapon, instead of simply moving toward the enemy as with the Pistol.

For this, the me.weaponCells(enemy) method returns all the cells from which you can use your weapon on a target. You then have to pick one: the closest!

So we'll create a getClosestCellToUseWeapon function and use a for in loop to find the cell with the shortest distance to us:

We use it to replace the movement:

To get a better view of the terrain and the cells, feel free to use tactical mode by pressing T during a fight.

In the next chapters, we'll tackle harder topics, so take the time to play around with your functions and the concepts we've covered: they're already enough to climb the rankings!

❓ Quiz

Which function correctly returns the square of a number?

def square(x): return x * x def square(x): x * x def square(): return x * x function square(x): return x * x

Which function calculates the maximum of a list?

def maximum(my_list): maxi = -99999 for e in my_list: if e > maxi: maxi = e return maxi def maximum(my_list): maxi = 99999 for e in my_list: if e < maxi: maxi = e return maxi def maximum(my_list): maxi = 99999 for e in my_list: if e > maxi: maxi = e return maxi def maximum(my_list): maxi = -99999 for e in my_list: if e < maxi: maxi = e return maxi

Full AI