--IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII --II Games on Cellular Spaces for studying mobility II --II II --II Last change: 20080827 II --IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII VAG__ = {} -- vector of agents VQU__ = {} -- vector of quarentine agents, waiting for synchronization function InitAgents(cs) for i, cell in pairs( cs.cells ) do cell.agindex = i; VAG__[i] = { agents={} }; end end function NumberOfCells(cs) return table.getn(cs.cells) end function GetRandomCell(cs) return cs.cells[math.random(1, NumberOfCells(cs))] end function GetAgents(cell) return VAG__[cell.agindex].agents end function NumberOfAgents(cell) return table.getn( GetAgents(cell) ) end function AddAgent(cell, agent) table.insert(VAG__[cell.agindex].agents, NumberOfAgents(cell) + 1, agent) end function RemoveAgent(cell, agent) local ags = GetAgents(cell) for i = 1, NumberOfAgents(cell), 1 do if agent == ags[i] then table.remove(ags, i) return end end end -- remove the agent from the cell, but waits for the synchronize to put it in the new cell function MoveTo(cell, agent, newcell) local todo = {agent = agent, cell = newcell} table.insert(VQU__, table.getn(VQU__) + 1, todo) RemoveAgent(cell, agent) --print ("move "..cell.agindex.." to "..newcell.agindex) end function SynchronizeAgents() for i = table.getn(VQU__), 1, -1 do data = VQU__[i] AddAgent(data.cell, data.agent) table.remove(VQU__, i) end end function ForEachAgent(cell, func) local ags = GetAgents(cell) for i = 1, NumberOfAgents(cell), 1 do func(cell, ags[i]) end end function GetRandomAgent(cell) return GetAgents(cell)[ math.random( 1, NumberOfAgents(cell) ) ] end function NumberOfNeighbors(cell) local count = 0 ForEachNeighbor(cell, function(cell, neigh) count = count + 1 end, "myneigh") return count end function GetRandomNeighbor(cell) local pos = math.random(1, NumberOfNeighbors(cell)) local ct = 0 ForEachNeighbor(cell, function(c, n) ct = ct + 1 end) local count = 1 local neighborhood = cell:getNeighborhood("myneigh") neighborhood:first() while( not neighborhood:isLast() )do neigh = neighborhood:getNeighbor() if count == pos then return neigh end neighborhood:next() count = count + 1 end print "ERROR: GET RANDOM NEIGHBOUR" end -- creates a neighborhood based on a previous one function ApplyNeighborhoodConstraint(cs, func) for i, cell in ipairs( cs.cells ) do local neigh = Neighborhood() ForEachNeighbor(cell, function(c, n) if func(c, n) then local index = Coord{ x = (n.x), y = (n.y)} neigh:addCell( index, cs, 1 ) end end) cell:addNeighborhood( neigh, "myneigh" ) end end