refactor turn-order

i should leave this peace of oxygen etc etc

Co-authored-by: Ivan Yuriev <ivanyr44@gmail.com>
This commit is contained in:
neckrat 2025-11-09 01:43:06 +03:00
parent 242b37de83
commit 4169aa4b61

View File

@ -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 --- @class TurnOrder
--- @field walked integer[] --- @field characterIds Id[]
--- @field notWalked integer[] --- @field walked PriorityQueue
--- @field notWalked PriorityQueue
--- @field isTurnsEnabled boolean --- @field isTurnsEnabled boolean
local turnOrder = {} local turnOrder = {}
turnOrder.__index = turnOrder turnOrder.__index = turnOrder
local function new() local function new()
return setmetatable({ return setmetatable({
walked = {}, walked = PriorityQueue.new(sortInitiative),
notWalked = {}, notWalked = PriorityQueue.new(sortInitiative),
isTurnsEnabled = true isTurnsEnabled = true
}, turnOrder) }, turnOrder)
end 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() function turnOrder:next()
table.insert(self.walked, self.notWalked[1]) local cur = self.notWalked:pop()
self.notWalked[1] = nil self.walked:insert(cur)
end
local notWalked = {} function turnOrder:reorder()
for i = 1, #self.notWalked do local _walked, _notWalked = PriorityQueue.new(sortInitiative), PriorityQueue.new(sortInitiative)
notWalked[i] = self.notWalked[i + 1] local charId = self.walked:pop()
print(notWalked[i], i) while charId do
_walked:insert(charId)
charId = self.walked:pop()
end end
self.notWalked = notWalked charId = self.notWalked:pop()
while charId do
Tree.level.selector:select(nil) _notWalked:insert(charId)
charId = self.notWalked:pop()
print('[Level]: Triggered next turn')
print('[Level]:', next(self.notWalked))
if #self.notWalked == 0 then
self:updateOrder()
self.walked = {}
end end
end end
function turnOrder:toggleTurns() --- @param count number
self.isTurnsEnabled = not self.isTurnsEnabled function turnOrder:getOrder(count)
end
--- @param id Id
function turnOrder:add(id)
table.insert(self.characterIds, id)
end end
return { new = new } return { new = new }