Forest Jogging - how come 2nd loop runs

In the level Forest Jogging, there are two loops: one for the pet and another for the hero. The two loops are infinite and separate. How come the second While loop executes? The first loop, pet.on(“spawn”, onSpawn) event, should trigger an infinite loop. It should never reach the second While loop. Please let me know how this works.

def onSpawn(event):
    while True:
        # First, move to the left X mark:
        pet.moveXY(9, 24)
        # Next, move to the top X mark:
        pet.moveXY(30, 43)
        # Move your pet to the right X mark:
        pet.moveXY(51, 24)
        # Move your pet to the bottom X mark:
        pet.moveXY(30, 5)

# Use pet.on() to handle the "spawn" event with onSpawn
pet.on("spawn", onSpawn)

# Cheer on your pet!
# Don't remove the commands below.
while True:
    hero.say("Good dog!")
    hero.say("You can do it!")
    hero.say("Run Run Run!")
    hero.say("Almost!")
    hero.say("One more lap!")

You can run a function at the same time as a while loop

def onSpawn(event):

this is a function

Do functions always break the code sequence? For example, it does not matter if a function triggers an infinite loop… the code placed after the function will run?

I always thought codes run in order. If not, codes will go wrong when placed after functions… when they rely on the function to complete running.

Example:

  1. run function to loop a billion times and return a number
  2. next line of code is to use that returned number for a calculation
  3. calculation is wrong because the loop will not finish before simultaneously running the next line of code.

Where can I learn more about this?

I think that what’s happening here is, imagine that the hero and the pet have two separate “brains”, the pet triggers the function, so the pet runs that, and the hero sees the while True loop below it, and runs that code.
So both can run at the same time.

If you have two laptops, you can play a different video game on each one, at the same time.
That’s essentially what’s happening.

2 Likes