First, if you have performance problems. Put the events in groups, the less events in one group the better. Then check the CPU-Usage in the Profile-Tab in the Debug-Layout
Your performance problem is the function call. You're calling the function from a loop and in the function there is another loop. You have up to 250 sprites and for each sprite you call the function, which is going again trough all sprites. That's an a amount of up to 62500 loops in one tick! (1/60 sec).
I made a little change, don't know if that's still exactly what you want, but you will see I only check 2 sprites a tick, that will be call the function. So this are only 500 loops a tick.
The change in the function you can ignore, it was only a test and it seems you're gaining nothing from this change.
I hope I could explain this well enough, sorry for bad english.
https://drive.google.com/uc?export=down ... TdYaFM2aHc
Your code works but it has a problem. A Square can only connect to one square at a time, but I want squares to connect to all the squares that are in the distance of 50 or less pixels