## Sunday, October 13, 2013

### n body simulation

# this is a n-body simulation , use arrow keys to keep it centered
# Number of inital particles

graphsize 600,600
fastgraphics
n=100
dim x(n+1)
dim y(n+1)
dim xspeed(n+1)
dim yspeed(n+1)
dim xac(n+1)
dim yac(n+1)
dim mass(n+1)
# initializing variables ##############
for p = 1 to n
a=rand*2*pi
r=rand*300
x[p]=r*cos(a)+300
y[p]=r*sin(a)+300
s=rand*2*pi/20
xspeed[p]=cos(a+s)-cos(a)
yspeed[p]=sin(a+s)-sin(a)
next p

gravity=0
dist=0
colision = 0
dx=0
dy=0
v=0
h=0

loop:
# arrow keys####################
a = key
if 16777234=a then h=h-5
if 16777236 =a then h=h+5
if 16777237=a then v=v-5
if 16777235=a then v=v+5

for u = 1 to n
for t = 1 to n
if u<>t and mass[t]>0 and mass[u]>0 then
dx=x[u]-x[t]
dy=y[u]-y[t]
dist=(dx^2 + dy^2)^(1/2)
collide = false
# gravity code################
if collide = true then
x[u]=(x[u]*mass[u]+x[t]*mass[t])/(mass[u]+mass[t])
y[u]=(y[u]*mass[u]+y[t]*mass[t])/(mass[u]+mass[t])
xspeed[u]=(xspeed[u]*mass[u]+xspeed[t]*mass[t])/(mass[u]+mass[t])
yspeed[u]=(yspeed[u]*mass[u]+yspeed[t]*mass[t])/(mass[u]+mass[t])
mass[u]=mass[u]+mass[t]
mass[t]=0
end if

# colision code################
if collide = false then
gravity = mass[t]*mass[u]/dist^2
xac[u]= gravity*dx/(1000*mass[u])
yac[u]= gravity*dy/(1000*mass[u])
xspeed[u]=xspeed[u]-xac[u]
yspeed[u]=yspeed[u]-yac[u]
x[u]=x[u]+xspeed[u]
y[u]=y[u]+yspeed[u]
end if
###############################
end if
next t
color white