Skip to content

Instantly share code, notes, and snippets.

@ashblue ashblue/movement.lua
Last active Dec 17, 2015

Embed
What would you like to do?
Shows all possible movement tiles.Written in Lua for Corona SDK
cs = cs or {}
local StepSimple = require('scripts.models.step-simple')
local Movement = {}
function Movement:new()
local o = display.newGroup()
o.open = nil
o.discovered = nil
o.valid = nil
function o:getMovement(x, y, z, speed, eType, jump)
local c, n, tentative, cost
self:reset()
-- Insert starting step
local tileStart = StepSimple:new(x, y, z, 0)
table.insert(self.open, tileStart)
table.insert(self.discovered, tileStart)
while o.open[1] do
-- current
c = table.remove(self.open)
-- get neighbors
n = cs.map:getNeighbors(c.x, c.y, c.z, eType, jump)
-- for each neighbor
for i = 1, #n do
-- if neighbor isn't in discovered
if not self:isDiscovered(n[i].x, n[i].y, n[i].z) then
-- get cost to move to this tile from current
cost = cs.map:getCost(c.x, c.y, c.z, n[i].x, n[i].y, n[i].z) + c.g
-- get tentative tile
tentative = StepSimple:new(n[i].x, n[i].y, n[i].z, cost)
-- push tile into discovered
table.insert(self.discovered, tentative)
-- if distance is not exceeded record the tile
--print('cost', cost, c.g)
if cost <= speed then
-- push tile to open
table.insert(self.open, tentative)
-- push tile to valid
table.insert(self.valid, tentative)
end
end
end
end
return self.valid
end
function o:isDiscovered(x, y, z)
for i = 1, #self.discovered do
if self.discovered[i].x == x and
self.discovered[i].y == y and
self.discovered[i].z == z then
return true
end
end
return false
end
function o:reset()
self.open = {}
self.discovered = {}
self.valid = {}
end
function o:printValid()
for i = 1, #self.valid do
print(self.valid[i].x, self.valid[i].y, self.valid[i].z, self.valid[i].g)
end
return self
end
function o:destroy()
self:removeSelf()
self = nil
end
return o
end
return Movement
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.