General coding strategy to not cap out CPU while AI moves enemies (loop question)

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By eod


I have a turn based game. On the AI’s turn, I run a “for loop”, which goes through each of the enemy units, and then determines what action that enemy should do (e.g. move, attack, defend). There may be like 100-150 enemies max.

While it’s the AI’s turn, I am trying to move the Camera2d around the map (basically using physics_process to check for arrow key inputs, then updating the the Camera2d’s offset).

The Camera2d movement is sporadic and choppy at best. My guess is that the AI’s “for loop” is consuming so much resources that the Camera2d’s physics_process can’t update real-time, and so there is a big lag.

When it’s the Human’s turn, the Camera2d’s movement works perfectly.

I added a yield(create-timer for like 0.01 seconds) in the AI “for loop”, but that didn’t help.

Any suggestions on how to limit how much “processing power” the AI gets during their turn?

Open to any ideas, even out of the box…

:bust_in_silhouette: Reply From: AlexTheRegent

You need to use threads ( Most of the engines lifecycles can be split into next major segments:

  1. Handle user input.
  2. Process all methods.
  3. Render frame.
    So until all methods are processed, frame will not be drawn. In other words, until your “for” loop is not finished, image on screen will not be updated. This is why you experience freezes on enemy’s turn. Threads allow you to move your code from main thread to separate, making it possible to update frames before for loop is finished.
    Note that not all operations are thread-safe (

Thank you for putting me in the right direction. I’ll look into what AI method’s I can optimize by putting on a thread(s)

eod | 2022-06-25 11:46