for loop seems to not work quite right
Posted: Wed Nov 28, 2012 11:38 am
What is intended here is that each animal in the table spawned moves once, either left, right, up, or down. Seems simple, code works fine with a couple animals, but once I get to a larger number, say 30 animals, they will begin moving at diagonals and skipping spaces. `test` was something I threw in to track this problem, but it has not helped. Hoping some more experienced eyes can see me through this one.
Seems simple. Am I wrong? Thanks in advance, you guys are all awesome.
Code: Select all
function aimove()
if state == "map" then
for i in ipairs(spawned) do
an = spawned[i]
if an.x > 2 and an.y > 2 and an.x < mapWidth - 3 and an.y < mapHeight - 3 then
dir = math.random(1,4)
if dir == 1 then an.x = an.x-1 test = test+1 end
if dir == 2 then an.x = an.x+1 test = test+1 end
if dir == 3 then an.y = an.y-1 test = test+1 end
if dir == 4 then an.y = an.y+1 test = test+1 end
elseif an.x > 2 and an.y > 2 and an.x < mapWidth - 3 and an.y == mapHeight - 3 then
dir = math.random(3)
if dir == 1 then an.x = an.x-1 end
if dir == 2 then an.x = an.x+1 end
if dir == 3 then an.y = an.y-1 end
test = test+1
elseif an.x > 2 and an.y == 2 and an.x < mapWidth - 3 and an.y < mapHeight - 3 then
dir = math.random(3)
if dir == 1 then an.x = an.x-1 end
if dir == 2 then an.x = an.x+1 end
if dir == 3 then an.y = an.y+1 end
test = test+1
elseif an.x > 2 and an.y > 2 and an.x == mapWidth - 3 and an.y < mapHeight - 3 then
dir = math.random(3)
if dir == 1 then an.x = an.x-1 end
if dir == 2 then an.y = an.y-1 end
if dir == 3 then an.y = an.y+1 end
test = test+1
elseif an.x == 2 and an.y > 2 and an.x < mapWidth - 3 and an.y < mapHeight - 3 then
dir = math.random(3)
if dir == 1 then an.x = an.x+1 end
if dir == 2 then an.y = an.y-1 end
if dir == 3 then an.y = an.y+1 end
test = test+1
an.oldx = an.x
an.oldy = an.y
end
end
end
end