Post by warspyking on Jan 21, 2016 19:08:11 GMT
Tap to create nodes, tap nodes to remove them
Drag a node to somewhere else to move it
Drag from one node to another to connect them
Drag again from one node to another to disconnect the previously created connection
Drag a node to somewhere else to move it
Drag from one node to another to connect them
Drag again from one node to another to disconnect the previously created connection
draw.setscreen(1)
draw.settitle("Nodes")
local Node = {}
Node.List = {}
Node.Connections = {}
function Node.new(self,x,y,rad,col)
local node = setmetatable({
x=x,
y=y,
rad=rad or 15,
col=col or draw.blue,
Parent = self,
Connections={},
List={}
},{__index = self})
self.List[#self.List+1] = node
return node
end
function Node.ConnectTo(self, node)
self.Connections[#self.Connections + 1] = node
node.Connections[#node.Connections+1] = self
end
function Node.DisconnectFrom(self, node)
for i,v in ipairs(self.Connections) do
if v == node then
table.remove(self.Connections, i)
break
end
end
for i,v in ipairs(node.Connections) do
if v == self then
table.remove(node.Connections,i)
break
end
end
end
function Node.IsConnectedTo(self,node)
for i,v in ipairs(self.Connections) do
if v == node then
return true
end
end
return false
end
function Node.Remove(self)
for i,v in ipairs(self.Connections) do
table.remove(self.Connections, i)
for ii,vv in ipairs(v.Connections) do
if vv == self then
table.remove(v.Connections, ii)
break
end
end
break
end
for i,v in ipairs(self.Parent.List) do
if v == self then
table.remove(self.Parent.List, i)
break
end
end
end
function Node.FindNode(self,x,y)
for i,v in ipairs(self.List) do
local d = math.abs(math.sqrt((x-v.x)^2+(y-v.y)^2))
if d < v.rad then
return v
end
end
end
function Node.Draw(self)
draw.fillcircle(self.x,self.y,self.rad,self.col)
end
do
local moved
local start = {}
draw.tracktouches(function(x,y)
start.x,start.y= x,y
end,
function(x,y)
moved = true
end,
function(x,y)
local s = Node:FindNode(start.x,start.y)
if not moved then
if s then
s:Remove()
else
Node:new(x,y)
end
else
moved = false
local f = Node:FindNode(x,y)
if s then
if f then
if s:IsConnectedTo(f) then
s:DisconnectFrom(f)
else
s:ConnectTo(f)
end
else
s.x,s.y = x,y
end
end
end
end)
end
while true do
sleep(100)
draw.doevents()
draw.clear()
draw.beginframe()
for i,v in ipairs(Node.List) do
v:Draw()
for ii,vv in ipairs(v.Connections) do
draw.line(v.x, v.y, vv.x, vv.y, draw.red)
end
end
draw.endframe()
end