Loops in depth

Loops in depth

> LeekScript Tutorial

Sooner or later, once you start coding, you'll need to repeat the same piece of code several times:

var enemy = getNearestEnemy();

useWeapon(enemy); useWeapon(enemy); useWeapon(enemy); useWeapon(enemy);

That may not be a problem when you only need to shoot 3 or 4 times, but once you want to write more advanced algorithms, you'll probably have to repeat instructions dozens of times, or even a variable number of times, which can't be done this way. That's where loops come in. A loop is a piece of code that repeats a sequence of instructions as many times as needed. Each time the code inside a loop is repeated, it's called an iteration.

var enemy = getNearestEnemy();

for(var i = 0 ; i 5) { moveTowardCell(enemyCell, 1); }

To find all the cells within a distance of 3 of your leek:

var cell = getCell(); var x0 = getCellX(cell); var y0 = getCellY(cell);

var cells = [];

for(var x = -3 ; x <= 3 ; x ++) { for(var y = -3 ; y <= 3 ; y ++) { if(abs(x) + abs(y) <= 3) { var cell = getCellFromXY(x+x0, y+y0); if(cell != null) { push(cells, cell); } } } }