> Tutorial
We have already used several functions and methods (setWeapon, moveToward, etc.). You can also create your own functions, with the following syntax:
function keywordsum( x, y ){ return x + y }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.
canFinish(enemy) functionOur 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 our own 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:
Did you know? Moving code that is repeated in several places into a single function is called factoring.
getClosestCellToUseWeapon(enemy) functionYou may have noticed that to use the Machine Gun or, later on, the Laser, you need to be in line with the enemy.
So you'll have to move 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. We'll have to pick one of them: the closest!
So we'll create a getClosestCellToUseWeapon function and use a for of loop to find the cell that is the shortest distance from us:
We use it to replace the movement:
To get a better view of the terrain and its 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 so far: they're already enough to climb the ranking!
Which of these functions correctly returns the square of a number?
function square(x) { return x * x } function square(x) { x * x } function square() { return x * x } fonction square(x) { return x * x }
Which function computes 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.