> Tutorial
We have already used several functions and methods (setWeapon, moveToward, etc.). It is also possible to create your own personal functions, with the following syntax:
functionsum( x, y ){ return x + y }The return keyword, optional, is used to make the function return a value. In the previous example, the function takes the parameters x and y and returns their sum: x + y.
canFinish(enemy) functionOur previous code for the "finish" condition of the enemy is quite large and not very reusable, so we will put it in a function.
We will create a personal function canFinish(enemy), which takes an enemy and returns a boolean indicating whether we can finish it or not.
We copy the finisher code into a function written this way:
Now, we can use our canFinish function in our main code to write it much more simply:
Did you know? Moving the same code multiple times into a function is called Factorization.
getClosestCellToUseWeapon(enemy) functionYou may have noticed that to use the Machine Gun weapon or later the Laser, you must be in line with the enemy.
You will therefore have 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 possible cells to use your weapon on a target. You will therefore have to choose one: the closest!
So we will create a getClosestCellToUseWeapon function and use a for of loop to calculate the cell whose distance to us is the shortest:
We use it to replace the movement:
To better see the terrain and the cells, do not hesitate to use the tactical mode by pressing T in combat.
In the following chapters we will tackle more difficult aspects, so take the time to play with your functions and the concepts we have seen, which are already enough to climb in the ranking!
Which function that returns the square of a number is correct?
function square(x) { return x * x } function square(x) { x * x } function square() { return x * x } fonction square(x) { return x * x }
Which function calculates the maximum of a list?
function maximum(list) { let maxi = -99999 for (const e of list) { if (e > maxi) { maxi = e } } return maxi } function maximum(list) { let maxi = 99999 for (const e of list) { if (e < maxi) { maxi = e } } return maxi } function maximum(list) { let maxi = 99999 for (const e of list) { if (e > maxi) { maxi = e } } return maxi } function maximum(list) { let maxi = -99999 for (const e of list) { if (e < maxi) { maxi = e } } return maxi }
Impossible de charger les données du jeu.
Vérifiez votre connexion et réessayez.