std.include("scripts/common.lua")

local this=nil
local ps=nil
local dir_vectors = { { 1,0 }, { 0,1 }, { -1,0 }, { 0,-1} }

function choose_direction()
   local tile_pos=get_tile_pos(this)
   local count=1
   while (count<5) do
      local v=dir_vectors[count]
      -- Check if the imp can walk that way
      local new_pos=add_vec2(tile_pos,v)
      local b=can_walk(new_pos)
      if (b) then
         return v
      end
      count=count+1
   end
   return { 0,0 }
end

function init(t)
   this=t
   
   set_sprite_max_speed(this,0.05)
   wait_time(random(500,2000))
   -- Do AI
   while (true) do
      coroutine.yield()
      -- Choose random direction
      local dir=choose_direction()

      set_movement_vector(this,{ 0.05*dir[1], 0, -0.05*dir[2] })

      local v=get_movement_vector(this)
      while ((v[1]~=0) or (v[3]~=0)) do
         coroutine.yield()
         v=get_movement_vector(this)
      end

      dir=neg_vec2(dir)
      set_movement_vector(this,{ 0.05*dir[1], 0, -0.05*dir[2] })

      local v=get_movement_vector(this)
      while ((v[1]~=0) or (v[3]~=0)) do
         coroutine.yield()
         v=get_movement_vector(this)
      end
   end
end
