Right, this is where things get complicated and slow. Every star (particle) is affected by every
other, so you will have to have 2 nested loops, each looping through every star. This means that
the time taken to process the movement of the stars is proportional to the square of the number
of stars. So, double the number of stars, and it can take four times longer to calculate.
Every star is attracted to every other by a force which lessens with distance. The force is
proportional to 1/(distance squared) between two stars. The force is also affected by the mass
of each star.
Loop a from 1 to n
x_acceleration = 0
y_acceleration = 0
Loop b from 1 to n
Xvector = star_x(b) - star_x(a)
Yvector = star_y(b) - star_y(a)
Distance = square_root_of (Xvector*Xvector + Yvector*Yvector)
Xvector = Xvector / Distance
Yvector = Yvector / Distance
Force = (Mass(a) * Mass(b)) / (Distance * Distance)
Xvector = Xvector * Force / Mass(a)
Yvector = Yvector * Force / Mass(a)
X_acceleration = X_acceleration + Xvector
Y_acceleration = Y_acceleration + Yvector
End of b loop
Star_Xvel(a) = Star_Xvel(a) + X_acceleration
Star_Yvel(a) = Star_Yvel(a) + Y_acceleration
End of a loop
You may notice that the above loop is slightly innefficient. Twice the necessary number of comparisons are done. Say you had two stars. That code would compare star 1 to star 2, then compare star 2 to star 1. With a slight ammendment, it is possible to double the speed of this algorithm. Note, however, that this is still an n-squared algorithm. Double the number of stars, four times the calculations.
Loop a from 1 to n
Loop b from a+1 to n
Xvector = star_x(b) - star_x(a)
Yvector = star_y(b) - star_y(a)
Distance = square_root_of (Xvector*Xvector + Yvector*Yvector)
Xvector = Xvector / Distance
Yvector = Yvector / Distance
Force = (Mass(a) * Mass(b)) / (Distance * Distance)
Xvector = Xvector * Force / Mass(a)
Yvector = Yvector * Force / Mass(a)
X_acceleration = Xvector
Y_acceleration = Yvector
Star_Xvel(a) = Star_Xvel(a) + X_acceleration
Star_Yvel(a) = Star_Yvel(a) + Y_acceleration
Star_Xvel(b) = Star_Xvel(b) - X_acceleration
Star_Yvel(b) = Star_Yvel(b) - Y_acceleration
End of b loop
End of a loop