llamazing, your version looks awesome, but when I try it, self[random_choice](self) is calling a nil value. Maybe I did something wrong, but I didn't think I could mess much up with what little I added to it:
local enemy = ...
function enemy:on_created()
enemy:set_life(3)
enemy:set_damage(2)
enemy:create_sprite("enemies/" .. enemy:get_breed())
end
local choices = {
pause = 25,
jump = 75,
}
-- these are functions the enemy will choose from randomly proportional to the value associated with each one
local random_max = 0 --sum of all choice values, calculate once when script is first run (in this example, radom_max = 25 + 75 = 100)
for _,weight in pairs(choices) do random_max = random_max + weight end
--this function could be moved to a different script for common utility functions
local function random_choice()
local choice_value = math.random(1, random_max) --choose random number between 1 and random_max
--step through list of choices to find which choice correspondes to the randomly chosen value
local cumulative = 0 --sum of current choice entry plus all previous
for choice,weight in pairs(choices) do
cumulative = cumulative + weight
if choice_value <= cumulative then
return choice --current entry corresponds to the randomly chosen value
end
end
--should have returned a value before getting to this line, as contingency returns some choice (undefined which one)
--you may prefer to throw an error here instead
local choice = next(choices)
return choice
end
function enemy:random_action()
self[random_choice](self) --this line calls a random function from the "choices" table at the top
end
function enemy:on_restarted()
self:random_action()
end
function enemy:pause()
local sprite = enemy:get_sprite()
--sprite:set_animation("idle")
enemy:stop_movement()
sol.timer.start(enemy, math.random(1, 2000), function()
self:random_action()
end)
end
function enemy:jump()
local sprite = enemy:get_sprite()
enemy:stop_movement()
--sprite:set_animation("jumping")
local movement = sol.movement.create("jump")
movement:set_direction8(math.random(0, 7))
movement:set_distance(math.random(24, 64))
movement:start(enemy)
sol.timer.start(enemy, 800, function()
self:random_action()
end)
end