diff --git a/lib/level/turn_order.lua b/lib/level/turn_order.lua index 1fd5ff4..427228f 100644 --- a/lib/level/turn_order.lua +++ b/lib/level/turn_order.lua @@ -1,65 +1,59 @@ +local PriorityQueue = require "lib.utils.priority_queue" + +local sortInitiative = function(id_a, id_b) + local res = Tree.level.characters[id_a]:try(Tree.behaviors.stats, function(astats) + local res = Tree.level.characters[id_b]:try(Tree.behaviors.stats, function(bstats) + return astats.initiative > bstats.initiative + end) + return res + end) + return res or false +end + --- @class TurnOrder ---- @field walked integer[] ---- @field notWalked integer[] +--- @field characterIds Id[] +--- @field walked PriorityQueue +--- @field notWalked PriorityQueue --- @field isTurnsEnabled boolean local turnOrder = {} turnOrder.__index = turnOrder local function new() return setmetatable({ - walked = {}, - notWalked = {}, + walked = PriorityQueue.new(sortInitiative), + notWalked = PriorityQueue.new(sortInitiative), isTurnsEnabled = true }, turnOrder) end -function turnOrder:updateOrder() - local notWalked = {} - local count = 1 - for id, char in ipairs(Tree.level.characters) do - char:try(Tree.behaviors.stats, function(stats) - notWalked[count] = id - count = count + 1 - end) - end - table.sort(notWalked, function(id_a, id_b) - local res = Tree.level.characters[id_a]:try(Tree.behaviors.stats, function(astats) - local res = Tree.level.characters[id_b]:try(Tree.behaviors.stats, function(bstats) - return astats.initiative > bstats.initiative - end) - return res - end) - return res or false - end) - self.notWalked = notWalked - - print('[Level]: Turn order has been updated!') -end - function turnOrder:next() - table.insert(self.walked, self.notWalked[1]) - self.notWalked[1] = nil + local cur = self.notWalked:pop() + self.walked:insert(cur) +end - local notWalked = {} - for i = 1, #self.notWalked do - notWalked[i] = self.notWalked[i + 1] - print(notWalked[i], i) +function turnOrder:reorder() + local _walked, _notWalked = PriorityQueue.new(sortInitiative), PriorityQueue.new(sortInitiative) + local charId = self.walked:pop() + while charId do + _walked:insert(charId) + charId = self.walked:pop() end - self.notWalked = notWalked - - Tree.level.selector:select(nil) - - print('[Level]: Triggered next turn') - print('[Level]:', next(self.notWalked)) - if #self.notWalked == 0 then - self:updateOrder() - self.walked = {} + charId = self.notWalked:pop() + while charId do + _notWalked:insert(charId) + charId = self.notWalked:pop() end end -function turnOrder:toggleTurns() - self.isTurnsEnabled = not self.isTurnsEnabled +--- @param count number +function turnOrder:getOrder(count) + +end + +--- @param id Id +function turnOrder:add(id) + table.insert(self.characterIds, id) end return { new = new }