Module:BATTD costs

From Blooncyclopedia, the independent Bloons knowledge base
Revision as of 12:10, 10 January 2026 by Polavux (talk | contribs)
Jump to navigation Jump to search

Documentation for this module may be created at Module:BATTD costs/doc

local p = {}

local function upgrade(towerName, upgradeName)
	local sFormat = string.format
	local query = mw.ext.cargo.query
	
	-- build key:values table of upgrades where id=key
	local upgradesById = {}
	local upgradeId = ""
	local upgrades = query("battd_upgrades", "id, name, tower, cost", {
		where=sFormat("tower='%s'", towerName)
	})

	for i, upgrade in ipairs(upgrades) do
		if upgrade.name == upgradeName then upgradeId = upgrade.id end
		upgradesById[upgrade.id] = upgrade
	end
	
	-- build key:values table of upgrade prereqs where id=current and values=previous
	local upgradePrereqsById = {}
	local roots = {}
	local upgradePrereqs = query("battd_upgrades=main, battd_upgrades__previous=prev", "main.id=thisId, prev._value=nextId", {
		where=sFormat("main.tower='%s'", towerName),
		join="main._ID=prev._RowID",
	})

	for i, upgrade in ipairs(upgradePrereqs) do
		if not upgrade.nextId then roots[#roots+1] = upgrade.thisId end
		if upgradePrereqsById[upgrade.thisId] then upgradePrereqsById[upgrade.thisId][#upgradePrereqsById[upgrade.thisId]+1] = upgrade.nextId end
		upgradePrereqsById[upgrade.thisId] = {upgrade.nextId}
	end
	
	-- build key:values table of upgrade locks where id=current and values=previous
	local upgradeLocksById = {}
	local upgradeLocks = query("battd_upgrades=main, battd_upgrades__locked_by_upgrades=lock", "main.id=thisId, lock._value=lockId", {
		where=sFormat("main.tower='%s'", towerName),
		join="main._ID=lock._RowID",
	})

	for i, upgrade in ipairs(upgradeLocks) do
		if upgradeLocksById[upgrade.thisId] then upgradePrereqsById[upgrade.thisId][#upgradePrereqsById[upgrade.thisId]+1] = upgrade.lockId end
		upgradeLocksById[upgrade.thisId] = {upgrade.lockId}
	end
	
	local function recursiveGetCost(id)
		local cost = upgradesById[id].cost
		for i, v in ipairs(upgradePrereqsById[id]) do
			cost = cost + recursiveGetCost(v)
		end
		return cost
	end
	
	-- tower cost + total cost of this upgrade and all its prereqs
	local baseCost = recursiveGetCost(upgradeId) + query("battd_characters", "cost", {
		where=sFormat("name='%s'", towerName)
	})[1].cost

	return baseCost
end

function p.upgrade(frame)
	return upgrade(frame.args[1], frame.args[2])
end

return p