diff --git a/data/scripts/classes/duck.lua b/data/scripts/classes/duck.lua index 7212d18..9c698e4 100644 --- a/data/scripts/classes/duck.lua +++ b/data/scripts/classes/duck.lua @@ -99,7 +99,7 @@ end function Duck:start_chase(feed) if self.state == States.CHASE then return end - print("duck " .. self.index .. " starting chase") + -- print("duck " .. self.index .. " starting chase") self.state = States.CHASE self.target = feed feed.occupied = true diff --git a/data/scripts/game.lua b/data/scripts/game.lua index 566b7f4..0f332c0 100644 --- a/data/scripts/game.lua +++ b/data/scripts/game.lua @@ -10,16 +10,8 @@ local Duck = require "classes.duck" local ducks = List() local function create_feed(position, direction) - print("?") local f = Feed.new(position, direction) feed:push(f) - local eligible_ducks = ducks:filter( - function (duck) - return duck.state ~= duck.STATES.CHASE - end - ) - if eligible_ducks:is_empty() then return end - eligible_ducks[1]:start_chase(f) end local function delete_feed(f) @@ -29,11 +21,17 @@ end local function duck_seek_feed(duck) local eligible_feeds = feed:filter( function (f) - return feed.occupied == false + return f.occupied == false end ) if eligible_feeds:is_empty() then return end - duck:start_chase(eligible_feeds[1]) + duck:start_chase( + eligible_feeds:sorted( + function(a, b) + return a.position:distance_squared_to(duck.position) < b.position:distance_squared_to(duck.position) + end + ):pop_front() + ) end -- called every frame, with constant delta time @@ -54,8 +52,6 @@ function game_tick() duck.SeekFeed:connect(duck_seek_feed) duck.index = i end - print(ducks[1].AteFeed._connections) - print(ducks[2].AteFeed._connections) end diff --git a/data/scripts/types/list.lua b/data/scripts/types/list.lua index e58c97a..47f6525 100644 --- a/data/scripts/types/list.lua +++ b/data/scripts/types/list.lua @@ -126,4 +126,33 @@ function List:is_empty() return #self == 0 end +---Returns a (shallow) copy of this list. +---@return List +function List:copy() + return List.create(self) +end + +---Returns a new copy of this list with the order of the elements shuffled around. +---@return List +function List:shuffled() + -- https://gist.github.com/Uradamus/10323382 + local list = self:copy() + + for i = #list, 2, -1 do + local j = math.random(i) + list[i], list[j] = list[j], list[i] + end + + return list +end + +---Returns a sorted copy of this list. +---@param f? fun(a: any, b: any) +---@return List +function List:sorted(f) + local list = self:copy() + table.sort(list, f) + return list +end + return List \ No newline at end of file