Hello!

The topic of today’s post loops. The game maker has loops such as while, until, and repeat. We explored the for loop in the topic about arrays, you can read about in post about game maker arrays.

While loop

The while loop works as long as the condition returns true. The while keyword is followed by a condition in parentheses, and as long as this condition returns true, the loop will continue. As soon as it becomes false, the loop ends immediately

while (<expression>)
{
    <statement>;
    <statement>;
    ...
}

First, I create the parameter i, which has a value of 0, and then I start a loop in which I specify that it should work as long as i is less than 5. In the loop, using draw_text, I display the value of i on the screen and increase i by one. If this is not done, i will always have the value 0 and our loop will never end and the game will not start. I added this code to the Draw Event.

i = 0
while (i < 5){
    draw_text(10+70*i, 10, i)
    i++
}

while

Do until loop

The next loop is named do until. Unlike while, it works until the condition returns false, as soon as it becomes true, the loop ends immediately

do
{
    <statement>;
    <statement>;
    ...
}
until (<expression>);

The result of this loop will be the same as the previous one within a while. But the condition here is different. We again have i, which has a value of 0. Then we start a loop in which we display the value of i on the screen and increase the value of i, and then we check whether i is greater than 5. If so, then we end the loop, and if not, then we continue.

i = 0

do {
    draw_text(10+70*i, 10, i)
    i++
} until (i > 5)

The peculiarity of this loop is that even if i initially has a value greater than 5. For example, 6, the loop will work once, because checking whether i is greater than 5 occurs at the end of the loop, and thus the loop has time to complete one iteration.

Repeat

The last type of loop is a repeat. Unlike the previous options, there are no conditions here, and we simply indicate how many times to go through the loop

repeat (<expression>)
{
    <statement>;
    <statement>;
    ...
}

Let’s try to implement the same thing that we implemented with the while and do loops. After the key repeat, we indicate in parentheses how many times the loop should be repeated, and in the body itself we execute the same code as before, output the value of i, and increase it by one

i = 0

repeat(5) {
    draw_text(10+70*i, 10, i)
    i++
}

Video