repeat

Drag & Drop equivalent : GM067

 

repeat (value)

{

       coding;

}

 

The block will be executed value amount of times.  The repeat statement repeats the expression after value, value amount of times.  If value is 0 then coding will not be executed at all, and if value is a negative number coding will not be executed.  If value is not an integer, then value will be rounded to the nearest whole number, meaning if value was 1.3 then coding would be executed once and if value was 1.6 then coding would be executed twice.

 

--oOo--

 

Example:

We are making another game, in this one we want the first level to have 10 trees in random places.  We could make the tree object, and in it's create event set it's x and y values to random numbers, but that would be cumbersome, and much less simple then having a controller object which in it's create event creates 10 trees in random positions.  Again we could bypass the need for the repeat statement by just writing the code for creating a tree in a random position, and copying and pasting it 10 times, but we decide to use the repeat statement.  We looked up the function for creating an instance and found instance_create(x,y,object), we want the tree's x and y values to be random, this means we will also need the function random(x) to get some randomness in the x and y values.  The function random(x) gets a number between 0 and x, in this case we want the instance to be created somewhere between 0 and the other side of the room, fortunately room_width is the spot on the other side of the room for x values.  room_height is the same for y values.  Now that we have everything we need all that is left is to write the correct code.

 

repeat (10)

{

instance_create(random(room_width),random(room_height),obj_tree);

}

 

This code creates an instance of obj_tree at a random x position between 0 and room_width and at a random y position between 0 and room_height.  What's more is that it repeats this 10 times.  Now say that we actually want 15 trees all we have to do is change 10 to 15 and we now have 15 trees.  Perhaps we want a random amount of trees, well we can do that now too, all we need to do is put a random() function in the place of 10.  Creating a random amount of trees is something which would have been horribly more difficult without using the repeat statement (and other more powerful statements).

 

Abyssal_Nuclei - Revision #1