Skip to main content

Using the Logic category: conditions and loops

June 13, 2024

Using the Logic category: conditions and loops

The Logic category has vital blocks that allow you to code your gameplay logic: conditions and loops.

Conditions (If-Else blocks)

Conditions control which blocks execute and which don't by checking a boolean value. It is a powerful tool to further narrow down the logic of your events. If the value passed into block's condition slot is true, the "then" part of the command will execute. If you use an extended If-Else block and if the passed boolean value returns false, then the "else" part will run. This allows making different things!

Tips

You can turn an "if" block into "If-Else" block and back by right-clicking it.

For example, here is how you can code a simple purchase logic:

If money price
Decrease money by price Note Play a sound UI_Train
store in
Advanced
Copy a template Worker x of base y of base
store in
Advanced

You can make more complex conditions by using "AND" and "OR" logical operators: they allow checking several variables at once without adding new If-Else blocks. For example, when coding a jump in a platformer, you need to make sure that a player presses the jump button and their character is currently positioned on ground:

Note Set onGround value place occupied this x y + If onGround and is action pressed MoveY
Note Set vertical speed to

Loops

Loops are usually used for doing repetitive stuff with one set of operations, and can also be used to map elements of an array to a new one. For example, While loops with a simple counter variable can be used for basic procedural generation:

Set count value While count <
Copy a template Tree random range width random range height
store in
Advanced
Increment count

The same can be done with "Repeat N times":

Repeat times
store index in
Copy a template Tree random range width random range height
store in
Advanced

You can also walk over a known array of values with "For each X of array" block:

Note For each ally of array templates list Heroes
If 2-point distance x y x of ally y of ally
Increase read from ally by Note If read from ally > read from ally
Write ally property value read from ally

If you need to stop a loop prematurely, you can use the "Stop this loop" block. For example, this code searches for a record in the content subsystem and finds a price of a searched building.

For each building of array buildings
If read from building is
Decrease money by read from building Stop this loop

The "Stop this loop" block interrupts the execution of the loop, and any blocks after this block will not execute. Thus "Stop this loop" is usually the last block in its loop or condition.

What's next?

Learn how to execute blocks in copies outside your current event to allow communications between copies in the next chapter.