14.9k views
2 votes
You are creating a game in which an enemy sprite performs a certain action for five seconds and then stops. Which type of loop would be the best choice for this function?

1) a while loop
2) an infinite loop

1 Answer

6 votes

Final answer:

For a game where an enemy sprite performs an action for five seconds, a while loop within a function is the best option as it can run based on a time condition.

Step-by-step explanation:

When creating a game where an enemy sprite is meant to perform a certain action for a fixed period, such as five seconds, and then stop, a while loop is typically the best choice.

This is because a while loop can run for a certain condition — in this case, the duration of five seconds. An infinite loop would not be suitable because it does not have a built-in mechanism to stop after a set period and would require additional logic to break out of the loop, risking potential errors if not handled correctly.

Therefore, for timed actions, a function with a while loop that checks the elapsed time would allow you to perform the action repeatedly until the five seconds have passed.

User Kevinvanleer
by
7.9k points