Coding and optimizing a power system

I have a 2d tile-based game. I plan to add a power system in the near future, something along the lines of Oxygen Not Included’s power system with wires.

The wires will be tiles in a seperate tilemap in the game, but in the code they will be something else.
What I plan to do is to make the “wires” some nodes in an array (which corresponds to the map) and have the connections be stored in another array, basically a graph. There will be power sources and all power consumers that are connected to a wire system with a power source will be powered. Issue is, I wouldn’t want the power consumers to constantly check whether they are connected to a power producer or vice versa.

I think I’d do this by making the consumers memorize whether they are connected to a power source, but I don’t know how to make this check fast enough considering there can be multiple power consumers/sources…

The map (at the current state) consists of 300 tiles horizontally and 190 tiles vertically. I’ll attach an image of the game too:


(entire map):

If more details are required, I’ll gladly provide some!
Any help is appreciated!

Well, it seems like you could use any graph traversal algorithm. You don’t need to constantly check connection. You could do that check when you change your graph, and you could optimize it further by reevaluating connection only for nodes that are reachable for changed.
Let’s say you add or remove node, you go to all its neighbours until you find any power producer and then find all reachable consumers and set them as active or not active.
I believe that could be optimized further, but these are just first ideas that came to my mind.
If you need many producers for many consumers I think you could make some kind of node cost which will say how many producers are connected.
You could possibly use multithreading to improve performance, even if it means running the check over a couple of frames.

2 Likes