nodes[0].setPosition([int(screensize[0]/2),int(screensize[1]/2)]) #fixing central node
damping = 0.2
repulsion = 180
attraction = 0.01
last40 = [0 for x in range(40)] #just for checking when we're done
lastKE = 0
correcting = True
running = True
while running:
screen.fill(white)
if correcting:
#print "correcting"
totalKE = 0
for index,node in enumerate(nodes):
if index == 0:
node.setVelocity((0,0))
continue
node.setVelocity((0,0))
netForce = (0,0)
for otherNode in nodes:
if otherNode == node:
pass
else: # repulsion force
dsqrd = (node.rect.center[0]-otherNode.rect.center[0])**2+(node.rect.center[1]-otherNode.rect.center[1])**2
netForce = vadd( netForce,(repulsion*(node.rect.center[0]-otherNode.rect.center[0])/float(dsqrd),
repulsion*(node.rect.center[1]-otherNode.rect.center[1])/float(dsqrd)))
for spring in node.attachedEdges: #spring attraction
oN = spring.attachedNodes[0]
if oN == node:
oN = spring.attachedNodes[1]
netForce = vadd(netForce, ((node.weight+oN.weight)*attraction*(oN.rect.center[0]-node.rect.center[0]),
(node.weight+oN.weight)*attraction*(oN.rect.center[1]-node.rect.center[1])))
node.setVelocity(((node.velocity[0]+netForce[0])*damping,
(node.velocity[1]+netForce[1])*damping))
totalKE += node.weight*((node.velocity[0]**2+node.velocity[1]**2))
last40.remove(last40[0])
last40.append(abs(totalKE-lastKE)) #append delta_KE
lastKE = totalKE
averageDE = sum(last40)/40.0
if averageDE < 0.00005:
print "Nothing changed for 40 iterations, done."
correcting = False
for index, node in enumerate(nodes):
if index == 0:
node.setVelocity((0,0))
node.setPosition((screensize[0]/2,screensize[1]/2))
else:
node.setPosition((int(node.rect.center[0]+node.velocity[0]),
int(node.rect.center[1]+node.velocity[1])))
for node in nodes:
for spring in node.attachedEdges:
spring.update()
for node in nodes:
node.update()
pygame.display.flip()