Module:CampsData: Difference between revisions

From Against the Storm Official Wiki
(added function to get all IDs; removed outdated comment at top)
m (changing grade to 2 for mine (affects wood camp too, but that's not shown in game anyway))
 
(6 intermediate revisions by the same user not shown)
Line 1: Line 1:
--- @module CampsData
---@module CampsData.lua
local CampsData = {}
---
 
---This module does not define an _actual_ derived class, but it creates an instance of one via prototyping patterns. Understand this file as a big procedure, top-to-bottom, rather than a class definition.
---
---Initializes a BaseDataModel with the data file associated with this module. Makes necessary modifications to the basic data, including schema and method overrides, to permit the exceptions associated with data in this model.




--region Dependencies
local GATHERER_HUTS_DATA_TEMPLATE_NAME = "Template:GathererHuts_csv"
local CAMPS_DATA_TEMPLATE_NAME = "Template:Camps_csv"
local CsvUtils = require("Module:CsvUtils")
-- Some dependencies are loaded lazily
local GoodsData


--region Localization string constants
local ERROR_MESSAGE_INSTANCE_NOT_INITIALIZED = "This instance's data table was never initialized. Please check how and where this method was called to diagnose the problem"
--endregion
--endregion






--region Private member variables
--Create instance
local BaseDataModel = require("Module:BaseDataModel")
local DATA_FILE = "Module:CampsData/Camps.json"


--- Main data tables, like this: table[ID] = table containing data for that ID
---@type BaseDataModel
local campsTable
local campsDataModel = BaseDataModel.new(DATA_FILE)


--- Supporting table, list of names table[i] = name.
local campsNames


--- Lookup map. Built once and reused on subsequent calls within this session,
--- like this: table[display name] = campID
local mapNamesToIDs
--- Lookup map. Built once and reused on subsequent calls within this session,
--- like this: table[goodID] = { campName1, campName2, ... }
local mapRecipeGoodIDsToCampNames


--endregion
--Begin instance overrides
 
for _, building in pairs(campsDataModel.dataTable) do
 
    building[campsDataModel.schema.CATEGORY2] = "Gathering Camp"
 
    building[campsDataModel.schema.IS_PROVIDING_SERVICES] = false
--region Private constants
end


local INDEX_ID = "id"
campsDataModel.schema.RECIPE.PRODUCTION_TIME = "gatheringTime"
local INDEX_NAME = "displayName"
local INDEX_DESCRIPTION = "description"
local INDEX_CATEGORY = "category"
local INDEX_SIZE_X = "sizeX"
local INDEX_SIZE_Y = "sizeY"
local INDEX_CONSTRUCTION_TIME = "constructionTime"
local INDEX_CITY_SCORE = "cityScore"
local INDEX_MOVABLE = "movable"
local INDEX_INITIALLY_ESSENTIAL = "initiallyEssential"
local INDEX_AREA = "area"
local INDEX_STORAGE = "storage"
local INDEX_REQUIRED_GOODS = "requiredGoods" -- table
local INDEX_WORKPLACES = "workplaces" -- table
local INDEX_RECIPES = "recipes" -- table


local INDEX_CONSTRUCTION_GOODS_STACK_SIZE = "stackSize"
--IMPORTANT: The data structure has one fewer levels, like RECIPE > PRODUCT_ID
local INDEX_CONSTRUCTION_GOODS_GOOD_ID = "goodID"
campsDataModel.schema.RECIPE.PRODUCT.ID = "seekedResource"


local INDEX_RECIPE_GOOD_ID = "goodID"
local INDEX_RECIPE_GRADE = "grade"
local INDEX_RECIPE_GATHERING_TIME = "gatheringTime"


local PATTERN_SPLIT_STACK_AND_ID = "(%d+)%s([%[%]%s%a]+)"
local PATTERN_CAPTURE_END_NUMBER = "Grade(%d)"
local WOODCUTTER_ID_WOOD = "[Mat Raw] Wood"
local WOODCUTTER_GRADE = 1
local WOODCUTTER_GATHERING_TIME = 2


--/** Function definitions follow. **/
--Collapse the regions in the IDE to see the procedure pick up with the assignments of these functions to override the associated member methods of BaseDataModel.
--region Public building interface
--no overrides!
--endregion
--endregion


--region Public building recipe query interface


local INDEX_PAIR_BUILDING_ID = "buildingID"
local INDEX_PAIR_RECIPE = "recipe"


--region Private methods
---@public
 
---`Overrides BaseDataModel`
---
---
--- Creates a new subtable containing the construction goods required for the
---Gets all this instance's buildings' recipes that have the specified product. Returns an array of pairs of building IDs and recipe data.
--- specified camp.
---
---
--- @param originalCamp table camp data record from which to make subtable
---@param self BaseDataModel this instance, with specific data
--- @param campsHeaderLookup table header lookup built from the CSV data
---@param productID string the product
--- @return table subtable with the required construction goods
---@return table array of pairs of building IDs and recipe data, or {} if none found
local function makeRequiredGoodsSubtable(originalCamp, campsHeaderLookup)
function getIDsAndRecipesWhereProductID(self, productID)
 
    -- A constant we'll need only within this function.
    local REQ_GOOD_HEADER_BASE_STRING = "requiredGood"
 
    -- Copy the originals directly into a subtable.
    local requiredIndex1 = campsHeaderLookup[REQ_GOOD_HEADER_BASE_STRING .. "1"]
    local requiredIndex2 = campsHeaderLookup[REQ_GOOD_HEADER_BASE_STRING .. "2"]
    local requiredIndex3 = campsHeaderLookup[REQ_GOOD_HEADER_BASE_STRING .. "3"]
 
    local number1, id1 = originalCamp[requiredIndex1]:match(PATTERN_SPLIT_STACK_AND_ID)
    local number2, id2 = originalCamp[requiredIndex2]:match(PATTERN_SPLIT_STACK_AND_ID)
    local number3, id3 = originalCamp[requiredIndex3]:match(PATTERN_SPLIT_STACK_AND_ID)


     -- don't add subtables that would just contain nils
     if not self.dataTable then
    local requiredGoods = {
         error(ERROR_MESSAGE_INSTANCE_NOT_INITIALIZED)
        number1 and id1 and { [INDEX_CONSTRUCTION_GOODS_STACK_SIZE] = tonumber(number1), [INDEX_CONSTRUCTION_GOODS_GOOD_ID] = id1 } or nil,
        number2 and id2 and { [INDEX_CONSTRUCTION_GOODS_STACK_SIZE] = tonumber(number2), [INDEX_CONSTRUCTION_GOODS_GOOD_ID] = id2 } or nil,
        number3 and id3 and { [INDEX_CONSTRUCTION_GOODS_STACK_SIZE] = tonumber(number3), [INDEX_CONSTRUCTION_GOODS_GOOD_ID] = id3 } or nil
    }
 
    return requiredGoods
end
 
 
 
---
--- Creates a new subtable containing the workplaces available in the specified
--- camp.
---
--- @param originalCamp table camp data record from which to make subtable
--- @param campsHeaderLookup table header lookup built from the CSV data
--- @return table subtable with the workplaces
local function makeWorkplacesSubtable(originalCamp, campsHeaderLookup)
 
    -- A constant we'll need only within this function.
    local WORKPLACE_HEADER_BASE_STRING = "workplace"
 
    -- Copy the originals directly into a subtable.
    local workplaceIndex1 = campsHeaderLookup[WORKPLACE_HEADER_BASE_STRING .. "1"]
    local workplaceIndex2 = campsHeaderLookup[WORKPLACE_HEADER_BASE_STRING .. "2"]
    local workplaceIndex3 = campsHeaderLookup[WORKPLACE_HEADER_BASE_STRING .. "3"]
    local workplaceIndex4 = campsHeaderLookup[WORKPLACE_HEADER_BASE_STRING .. "4"]
 
    local workplace1 = originalCamp[workplaceIndex1]
    local workplace2 = originalCamp[workplaceIndex2]
    local workplace3 = originalCamp[workplaceIndex3]
    local workplace4 = originalCamp[workplaceIndex4]
 
    -- if it's not an empty string, then save that to the table, otherwise nil
    local workplaces = {
        (workplace1 ~= "" and workplace1) or nil,
        (workplace2 ~= "" and workplace2) or nil,
         (workplace3 ~= "" and workplace3) or nil,
        (workplace4 ~= "" and workplace4) or nil
    }
 
    return workplaces
end
 
 
 
---
--- Creates a new subtable containing the recipes available in the specified
--- camp.
---
--- @param campName string the display name of the camp
--- @param originalCamp table camp data record from which to make subtable
--- @param campsHeaderLookup table header lookup built from the CSV data
--- @return table subtable with the recipe IDs
local function makeRecipesSubtable(campName, originalCamp, campsHeaderLookup)
 
    -- A constant we'll need only within this function.
    local MAX_RECIPES = 3
    local LOOKUP_RECIPE_BASE_STRING = "recipe"
    local LOOKUP_GOOD_BASE_STRING = "SeekedDeposits"
    local LOOKUP_GRADE_BASE_STRING = "Grade"
    local LOOKUP_GATHERING_TIME_BASE_STRING = "GatheringTime"
 
    if not mapRecipeGoodIDsToCampNames then
        mapRecipeGoodIDsToCampNames = {}
     end
     end


    -- Copy the originals directly into a subtable.
     local ret = {}
     local recipes = {}
     for id, building in pairs(self.dataTable) do
     for i = 1, MAX_RECIPES do
         for _, recipe in ipairs(building[self.schema.RECIPES]) do
 
         -- A subtable for this recipe
        newRecipe = {}
        local originalGoodIndex = campsHeaderLookup[LOOKUP_RECIPE_BASE_STRING .. i
                .. LOOKUP_GOOD_BASE_STRING]
        local originalGradeIndex = campsHeaderLookup[LOOKUP_RECIPE_BASE_STRING .. i
                .. LOOKUP_GRADE_BASE_STRING]
        local originalGatheringTimeIndex = campsHeaderLookup[LOOKUP_RECIPE_BASE_STRING .. i
                .. LOOKUP_GATHERING_TIME_BASE_STRING]


        local originalGoodID = originalCamp[originalGoodIndex]
            --If there's a matching seeked deposit
 
            if recipe[self.schema.RECIPE.PRODUCT.ID] == productID then
        -- Skip blank recipes.
                -- Add as an buildingID-recipe pair
        if originalGoodID and originalGoodID ~= "" then
                table.insert(ret, {
            newRecipe[INDEX_RECIPE_GOOD_ID] = originalGoodID
                    [INDEX_PAIR_BUILDING_ID] = id,
            newRecipe[INDEX_RECIPE_GRADE] = tonumber(originalCamp[originalGradeIndex]:match(PATTERN_CAPTURE_END_NUMBER))
                    [INDEX_PAIR_RECIPE] = recipe,
            newRecipe[INDEX_RECIPE_GATHERING_TIME] = tonumber(originalCamp[originalGatheringTimeIndex])
                })
 
            table.insert(recipes,newRecipe)
 
            if not mapRecipeGoodIDsToCampNames[originalGoodID] then
                mapRecipeGoodIDsToCampNames[originalGoodID] = {}
             end
             end
            table.insert(mapRecipeGoodIDsToCampNames[originalGoodID], campName)
         end
         end
     end
     end
 
     return ret
     return recipes
end
end


 
---@public
 
---`Overrides BaseDataModel`
---
---
--- Transforms the originalCampsTable returned from CSV processing to be
---Gets all this instance's specified building's recipes that produce the specified product. Returns an array of pairs of building IDs and recipe data.
--- more conducive to member functions looking up data. Converts text strings
--- into subtables. Converts header row into field keys on every record and
--- stores records by id rather than arbitrary integer.
---
---
--- @param originalCampsTable table of CSV-based data, with header row, data rows
---@param self BaseDataModel this instance, with specific data
--- @param campsHeaderLookup table lookup table of headers to get indexes
---@param productID string the product
--- @return table better structured with IDs as keys
---@param buildingID string the building
local function restructureGathererHuts(originalCampsTable, campsHeaderLookup)
---@return table array of pairs of building IDs and recipe data, or {} if none found
function getIDsAndRecipesWhereProductIDAndBuildingID(self, productID, buildingID)


     -- A few constants we need only in this function.
     --Can't findID from here, but that's okay, this is a small data file: just loop.
     local DATA_ROWS = 2
     local ret = {}
    local INDEX_ORIGINAL_ID = 1
     for id, building in pairs(self.dataTable) do
    local INDEX_ORIGINAL_NAME = 2
    local INDEX_ORIGINAL_DESCRIPTION = 3
    local INDEX_ORIGINAL_CATEGORY = 4
    local INDEX_ORIGINAL_SIZE_X = 5
    local INDEX_ORIGINAL_SIZE_Y = 6
     -- Required goods are indexes 7, 8, 9
    local INDEX_ORIGINAL_CONSTRUCTION_TIME = 10
    local INDEX_ORIGINAL_CITY_SCORE = 11
    local INDEX_ORIGINAL_MOVABLE = 12
    local INDEX_ORIGINAL_ESSENTIAL = 13
    local INDEX_ORIGINAL_AREA = 14
    local INDEX_ORIGINAL_STORAGE = 15


    mapNamesToIDs = {}
        if building[self.schema.ID] == buildingID then
    campsNames = {}


    local newCampsTable = {}
            for _, recipe in ipairs(building[self.schema.RECIPES]) do
    for _, originalCamp in ipairs(originalCampsTable[DATA_ROWS]) do


        -- Copy over the content, mapping unhelpful indexes into headers keys.
                --If there's a matching seeked deposit
        local newCamp = {}
                if recipe[self.schema.RECIPE.PRODUCT.ID] == productID then
        newCamp[INDEX_ID] = originalCamp[INDEX_ORIGINAL_ID]
                    -- Add as an buildingID-recipe pair
        newCamp[INDEX_NAME] = originalCamp[INDEX_ORIGINAL_NAME]
                    table.insert(ret, {
        newCamp[INDEX_DESCRIPTION] = originalCamp[INDEX_ORIGINAL_DESCRIPTION]
                        [INDEX_PAIR_BUILDING_ID] = id,
        newCamp[INDEX_CATEGORY] = originalCamp[INDEX_ORIGINAL_CATEGORY]
                        [INDEX_PAIR_RECIPE] = recipe,
        newCamp[INDEX_SIZE_X] = tonumber(originalCamp[INDEX_ORIGINAL_SIZE_X])
                    })
        newCamp[INDEX_SIZE_Y] = tonumber(originalCamp[INDEX_ORIGINAL_SIZE_Y])
                end
        newCamp[INDEX_CITY_SCORE] = tonumber(originalCamp[INDEX_ORIGINAL_CITY_SCORE])
            end
        newCamp[INDEX_MOVABLE] = originalCamp[INDEX_ORIGINAL_MOVABLE] == "True"
        newCamp[INDEX_INITIALLY_ESSENTIAL] = originalCamp[INDEX_ORIGINAL_ESSENTIAL] == "True"
        newCamp[INDEX_AREA] = tonumber(originalCamp[INDEX_ORIGINAL_AREA])
        newCamp[INDEX_STORAGE] = tonumber(originalCamp[INDEX_ORIGINAL_STORAGE])
        newCamp[INDEX_CONSTRUCTION_TIME] = tonumber(originalCamp[INDEX_ORIGINAL_CONSTRUCTION_TIME])


         newCamp[INDEX_REQUIRED_GOODS] = makeRequiredGoodsSubtable(originalCamp, campsHeaderLookup)
         end
        newCamp[INDEX_WORKPLACES] = makeWorkplacesSubtable(originalCamp, campsHeaderLookup)
        newCamp[INDEX_RECIPES] = makeRecipesSubtable(newCamp[INDEX_NAME], originalCamp, campsHeaderLookup)
 
        newCampsTable[ newCamp[INDEX_ID] ] = newCamp
 
        table.insert(campsNames, newCamp[INDEX_NAME])
 
        -- Also populate the map for looking up IDs with display names
        mapNamesToIDs[ newCamp[INDEX_NAME] ] = newCamp[INDEX_ID]
     end
     end
 
     return ret
     return newCampsTable
end
 
 
 
---
--- Creates a row for the only record in this table, the woodcutters' camp, in
--- a way that matches the other gathering camps or huts.
---
---@param originalCampsTable table the one-record table
---@param campsHeaderLookup table lookup table of headers to get indexes
---@return table one record to add to campsTable
local function addWoodcuttersCampRow(originalCampsTable, campsHeaderLookup)
 
    -- A few constants we need only in this function.
    local DATA_ROWS = 2
    local INDEX_ORIGINAL_ID = 1
    local INDEX_ORIGINAL_NAME = 2
    local INDEX_ORIGINAL_DESCRIPTION = 3
    local INDEX_ORIGINAL_CATEGORY = 4
    local INDEX_ORIGINAL_SIZE_X = 5
    local INDEX_ORIGINAL_SIZE_Y = 6
    -- Required goods are indexes 7, 8, 9
    local INDEX_ORIGINAL_CONSTRUCTION_TIME = 10
    local INDEX_ORIGINAL_CITY_SCORE = 11
    local INDEX_ORIGINAL_MOVABLE = 12
    local INDEX_ORIGINAL_ESSENTIAL = 13
    local INDEX_ORIGINAL_AREA = 14
    local INDEX_ORIGINAL_STORAGE = 15
 
    -- The woodcutters' camp is at index 1 in the data rows.
    local originalCamp = originalCampsTable[DATA_ROWS][1]
 
    local newCamp = {}
    newCamp[INDEX_ID] = originalCamp[INDEX_ORIGINAL_ID]
    newCamp[INDEX_NAME] = originalCamp[INDEX_ORIGINAL_NAME]
    newCamp[INDEX_DESCRIPTION] = originalCamp[INDEX_ORIGINAL_DESCRIPTION]
    newCamp[INDEX_CATEGORY] = originalCamp[INDEX_ORIGINAL_CATEGORY]
    newCamp[INDEX_SIZE_X] = tonumber(originalCamp[INDEX_ORIGINAL_SIZE_X])
    newCamp[INDEX_SIZE_Y] = tonumber(originalCamp[INDEX_ORIGINAL_SIZE_Y])
    newCamp[INDEX_CONSTRUCTION_TIME] = tonumber(originalCamp[INDEX_ORIGINAL_CONSTRUCTION_TIME])
    newCamp[INDEX_CITY_SCORE] = tonumber(originalCamp[INDEX_ORIGINAL_CITY_SCORE])
    newCamp[INDEX_MOVABLE] = originalCamp[INDEX_ORIGINAL_MOVABLE]
    newCamp[INDEX_INITIALLY_ESSENTIAL] = originalCamp[INDEX_ORIGINAL_ESSENTIAL]
    newCamp[INDEX_AREA] = tonumber(originalCamp[INDEX_ORIGINAL_AREA])
    newCamp[INDEX_STORAGE] = tonumber(originalCamp[INDEX_ORIGINAL_STORAGE])
 
    newCamp[INDEX_REQUIRED_GOODS] = makeRequiredGoodsSubtable(originalCamp, campsHeaderLookup)
    newCamp[INDEX_WORKPLACES] = makeWorkplacesSubtable(originalCamp, campsHeaderLookup)
 
    -- Create a subtable of one recipe. This part of the record does not exist
    -- in the data and needs to be fabricated to match the other camps.
    local oneRecipe = {}
    local recipe = {}
    recipe[INDEX_RECIPE_GOOD_ID] = WOODCUTTER_ID_WOOD
    recipe[INDEX_RECIPE_GRADE] = WOODCUTTER_GRADE
    recipe[INDEX_RECIPE_GATHERING_TIME] = WOODCUTTER_GATHERING_TIME
    table.insert(oneRecipe, recipe)
    newCamp[INDEX_RECIPES] = oneRecipe
 
    campsTable[newCamp[INDEX_ID]] = newCamp
 
    mapNamesToIDs[newCamp[INDEX_NAME]] = newCamp[INDEX_ID]
 
    -- This is the only camp that harvests wood.
    mapRecipeGoodIDsToCampNames[WOODCUTTER_ID_WOOD] = {}
    table.insert(mapRecipeGoodIDsToCampNames[WOODCUTTER_ID_WOOD], newCamp[INDEX_NAME])
end
 
 
 
---
--- Data loader function that uses the utility module and restructures the data
--- to be easier to access for invoking methods and later method calls. This
--- method is automatically called by all public member functions if the main
--- data table has not yet been populated in the current session.
local function loadData()
 
    -- Utility module retrieves the data as basic, flat lua tables.
    local originalGathererHutsTable, gathererHutsHeaderLookup = CsvUtils.extractTables(GATHERER_HUTS_DATA_TEMPLATE_NAME)
 
    -- Now restructure to be more conducive.
    campsTable = restructureGathererHuts(originalGathererHutsTable, gathererHutsHeaderLookup)
 
    -- Now append the woodcutters' camp and fake recipe records for its
    local originalCampsTable, campsHeaderLookup = CsvUtils.extractTables(CAMPS_DATA_TEMPLATE_NAME)
 
    -- Now restructure and append a row for the camp, since there is only one record right now.
    addWoodcuttersCampRow(originalCampsTable, campsHeaderLookup)
end
 
 
 
local function load()
    if not campsTable then
        loadData()
    end
end
 
 
 
---
--- Uses the display name, which people are more familiar with, to find the
--- encoded ID of the camp. Useful for retrieving the  data that is
--- indexed by ID.
---
--- Returns nil if the camp with the specified name is not found.
---
--- @param displayName string plain-language name of the camp to find
--- @return string ID of the camp found, or nil if not found
local function findCampIDByName(displayName)
 
    -- At runtime, this should never be nil or empty, so throw an error.
    if not displayName or displayName == "" then
        error("Parameter is nil or empty for the camp's name: " .. displayName .. ".")
    end
 
    if not campsTable then
        loadData()
    end
 
    return mapNamesToIDs[displayName]
end
end


--endregion
--endregion


--region Public recipe data retrieval interface


 
---@public
--region Public methods
---`Overrides BaseDataModel`
 
--- Retrieve the whole table of data for the specified camp. Instead of
--- this, you should probably be calling the individual getter methods.
---
---
--- Throws an error if called with nil or empty string. Returns nil if the
---Gets the efficiency grade from the provided recipe.
--- specified camp cannot be found.
---
---
--- @param campID string ID of the camp
---Parameters
--- @return table containing the data with key-value pairs, or nil if not found
function CampsData.getAllDataForCampByID(campID)
 
    -- At runtime, this should never be nil or empty.
    if not campID or campID == "" then
        error("Parameter is nil or empty for the camp's ID.")
    end
 
    if not campsTable then
        loadData()
    end
 
    return campsTable[campID]
end
 
 
 
--- Retrieve the whole table of data for the specified camp. Instead of
--- this, you should probably be calling the individual getter methods.
---
---
--- Throws an error if called with nil or empty string. Returns nil if the
---`self:BaseDataModel` - ignored
--- specified camp cannot be found.
---
---
--- @param displayName string plain language name of the camp
---`recipeData:recipePairTable` - ignored
--- @return table containing the data with key-value pairs, or nil if not found
function CampsData.getAllDataForCamp(displayName)
 
    -- At runtime, this should never be nil or empty.
    if not displayName or displayName == "" then
        error("Parameter is nil or empty for the camp's name.")
    end
 
    if not campsTable then
        loadData()
    end
 
    local campID = findCampIDByName(displayName)
    if not campID then
        return nil
    end
 
    return campsTable[campID]
end
 
 
 
---
--- Retrieves the ID for the camp specified by its plain language
--- display name.
---
--- Returns nil if the camp named was not found.
---
---@param displayName string the plain language name of the camp
---@return string the ID of the specified camp
function CampsData.getCampID(displayName)
 
    local camp = CampsData.getAllDataForCamp(displayName)
 
    if not camp then
        return nil
    end
 
    return camp[INDEX_ID]
end
 
 
 
---
--- Retrieves the description for the camp specified by its plain
--- language display name.
---
--- Returns nil if the camp named was not found.
---
---@param displayName string the plain language name of the camp
---@return string the in-game description of the specified camp
function CampsData.getCampDescription(displayName)
 
    local camp = CampsData.getAllDataForCamp(displayName)
 
    if not camp then
        return nil
    end
 
    return camp[INDEX_DESCRIPTION]
end
 
 
 
---
--- Retrieves the construction toolbar category for the camp specified
--- by its plain language display name.
---
--- Returns nil if the camp named was not found.
---
---@param displayName string the plain language name of the camp
---@return string the category of the specified camp
function CampsData.getCampCategory(displayName)
 
    local camp = CampsData.getAllDataForCamp(displayName)
 
    if not camp then
        return nil
    end
 
    return camp[INDEX_CATEGORY]
end
 
 
 
---
--- Retrieves the 2x2 size for the camp specified by its plain language
--- display name.
---
--- Returns nil if the camp named was not found.
---
---@param displayName string the plain language name of the camp
---@return number the X-size of the camp
---@return number the Y-size of the camp
function CampsData.getCampSize(displayName)
 
    local camp = CampsData.getAllDataForCamp(displayName)
 
    if not camp then
        return nil
    end
 
    return camp[INDEX_SIZE_X], camp[INDEX_SIZE_Y]
end
 
 
 
---
---
--- Retrieves the goods required for construction for the camp specified
---@return number efficiency grade
--- by its plain language display name, in a table that looks like this:
function getRecipeGrade()
---
     return 2
--- ["requiredGoods"] = {
---    [1] = { ["stackSize"] = 99, ["goodID"] = "good1_ID" },
---    [2] = { ["stackSize"] = 99, ["goodID"] = "good2_ID" },
---    [3] = { ... } or missing if fewer
--- }
---
--- Returns nil if the camp named was not found.
---
---@param displayName string the plain language name of the camp
---@return table of required goods
function CampsData.getAllCampRequiredGoods(displayName)
 
    local camp = CampsData.getAllDataForCamp(displayName)
 
    if not camp then
        return nil
    end
 
     return camp[INDEX_REQUIRED_GOODS]
end
end


 
---@public
 
---`Overrides BaseDataModel`
---
--- Retrieves the specified required construction good for the camp
--- specified by its plain language display name.
---
--- Returns nil if the camp named was not found.
---
---@param displayName string the plain language name of the camp
---@param requirementIndex number which construction good to retrieve
---@return string the ID of the good that is required, or nil if none
---@return number the stack size of that good, or nil if none
function CampsData.getCampRequiredGood(displayName, requirementIndex)
 
    local requiredGoods = CampsData.getAllCampRequiredGoods(displayName)
 
    if not requiredGoods then
        return nil
    end
 
    local requirement = requiredGoods[requirementIndex]
    if not requirement then
        return nil
    end
 
    return requirement[INDEX_CONSTRUCTION_GOODS_GOOD_ID], requirement[INDEX_CONSTRUCTION_GOODS_STACK_SIZE]
end
 
 
 
---
--- Retrieves the construction time for the camp specified by its plain
--- language display name.
---
---
--- Returns nil if the camp named was not found.
---Gets the product ID from the provided recipe.
---
---
---@param displayName string the plain language name of the camp
---@param self BaseDataModel this instance, with specific data
---@return number of seconds it takes to construct the camp
---@param recipeData recipePairTable
function CampsData.getCampConstructionTime(displayName)
---@return string product ID
 
function getRecipeProductID(self, recipeData)
     local camp = CampsData.getAllDataForCamp(displayName)
     return recipeData.recipe[self.schema.RECIPE.PRODUCT.ID]
 
    if not camp then
        return nil
    end
 
    return camp[INDEX_CONSTRUCTION_TIME]
end
end


 
---@public
 
---`Overrides BaseDataModel`
---
---
--- Retrieves the city score awarded for the camp specified by its plain
---Gets the amount of product produced by the provided recipe.
--- language display name.
---
---
--- Returns nil if the camp named was not found.
---Parameters
---
---
---@param displayName string the plain language name of the camp
---`self:BaseDataModel` - ignored
---@return number of points for city score from having the camp
function CampsData.getCampCityScore(displayName)
 
    local camp = CampsData.getAllDataForCamp(displayName)
 
    if not camp then
        return nil
    end
 
    return camp[INDEX_CITY_SCORE]
end
 
 
 
---
--- Retrieves whether the camp specified by its plain language display
--- name can be moved, at any cost.
---
---
--- Returns nil if the camp named was not found.
---`recipeData:recipePairTable` - ignored
---
---
---@param displayName string the plain language name of the camp
---@return number stack size
---@return boolean of whether the camp can be moved
function getRecipeProductAmount()
function CampsData.isCampMovable(displayName)
     return 1
 
    local camp = CampsData.getAllDataForCamp(displayName)
 
    if not camp then
        return nil
    end
 
    return camp[INDEX_MOVABLE]
end
 
 
 
---
--- Retrieves whether the camp specified by its plain language display
--- name has an essential starting blueprint for a new game profile.
---
--- Returns nil if the camp named was not found.
---
---@param displayName string the plain language name of the camp
---@return boolean of whether the camp's blueprint is essential
function CampsData.isCampInitiallyEssential(displayName)
 
    local camp = CampsData.getAllDataForCamp(displayName)
 
    if not camp then
        return nil
    end
 
    return camp[INDEX_INITIALLY_ESSENTIAL]
end
 
 
 
---
--- Retrieves the gathering area for the camp specified by its plain
--- language display name.
---
--- Returns nil if the camp named was not found.
---
---@param displayName string the plain language name of the camp
---@return number of tiles of gathering radius
function CampsData.getCampArea(displayName)
 
    local camp = CampsData.getAllDataForCamp(displayName)
 
    if not camp then
        return nil
    end
 
    return camp[INDEX_AREA]
end
 
 
 
---
--- Retrieves the storage capacity of the camp specified by its plain
--- language display name.
---
--- Returns nil if the camp named was not found.
---
---@param displayName string the plain language name of the camp
---@return number of storage capacity at the camp
function CampsData.getCampStorage(displayName)
 
    local camp = CampsData.getAllDataForCamp(displayName)
 
    if not camp then
        return nil
    end
 
    return camp[INDEX_STORAGE]
end
 
 
 
---
--- Retrieves the table of workplaces for the camp specified by its
--- plain language display name.
---
--- Returns nil if the camp named was not found.
---
---@param displayName string the plain language name of the camp
---@return table of workplaces
function CampsData.getAllCampWorkplaces(displayName)
 
    local camp = CampsData.getAllDataForCamp(displayName)
 
    if not camp then
        return nil
    end
 
    return camp[INDEX_WORKPLACES]
end
 
 
 
---
--- Retrieves the number of workplaces for the camp specified by its
--- plain language display name.
---
--- Returns nil if the camp named was not found.
---
---@param displayName string the plain language name of the camp
---@return number of workplaces
function CampsData.getCampNumberOfWorkplaces(displayName)
 
    local camp = CampsData.getAllDataForCamp(displayName)
 
    if not camp then
        return nil
    end
 
    return #camp[INDEX_WORKPLACES]
end
 
 
 
---
--- Retrieves the table of recipes for the camp specified by its
--- plain language display name, in a table that looks like this:
---
--- ["recipes"] = {
--- [1] = "recipe1_ID",
--- [2] = "recipe2_ID",
--- [3] = "recipe3_ID",
--- [4] = ... or missing if fewer
--- }
---
--- Returns nil if the camp named was not found.
---
---@param displayName string the plain language name of the camp
---@return table of recipe IDs
function CampsData.getAllCampRecipes(displayName)
 
    local camp = CampsData.getAllDataForCamp(displayName)
 
    if not camp then
        return nil
    end
 
    return camp[INDEX_RECIPES]
end
 
 
 
---
--- Retrieves the number of recipes for the camp specified by its
--- plain language display name, in a table that looks like this:
---
--- Returns nil if the camp named was not found.
---
---@param displayName string the plain language name of the camp
---@return number of recipes at the camp
function CampsData.getCampNumberOfRecipes(displayName)
 
    local camp = CampsData.getAllDataForCamp(displayName)
 
    if not camp then
        return 0
    end
 
    local recipes = camp[INDEX_RECIPES]
    if not recipes then
        return 0
    end
 
    return #recipes
end
 
 
 
---
--- Retrieves the product's ID and the stack size produced by the specified
--- recipe at the camp specified by its plain language display name.
---
--- Returns nil if the camp named was not found.
---
---@param displayName string the plain language name of the camp
---@param recipeIndex number the index of the recipe ID
---@return string the ID of the good produced by the specified recipe
function CampsData.getCampRecipeProduct(displayName, recipeIndex)
 
    local recipes = CampsData.getAllCampRecipes(displayName)
 
    if not recipes then
        return nil
    end
 
    local recipe = recipes[recipeIndex]
    if not recipe then
        return nil
    end
 
    return recipe[INDEX_RECIPE_GOOD_ID]
end
 
 
 
---
--- Retrieves the other stats for specified recipe at the camp specified by
--- its plain language display name: the efficiency grade and the gathering
--- time.
---
--- Returns nil if the camp named was not found.
---
---@param displayName string the plain language name of the camp
---@param recipeIndex number the index of the recipe ID
---@return number of stars, the grade of the specified recipe
---@return number of seconds for gathering
function CampsData.getCampRecipeStats(displayName, recipeIndex)
 
    local recipes = CampsData.getAllCampRecipes(displayName)
 
    if not recipes then
        return nil
    end
 
    local recipe = recipes[recipeIndex]
    if not recipe then
        return nil
    end
 
     return recipe[INDEX_RECIPE_GRADE], recipe[INDEX_RECIPE_GATHERING_TIME]
end
 
 
 
---
--- Retrieves the icon filename for the camp specified by its plain
--- language display name.
---
--- Returns nil if the camp named was not found.
---
---@param displayName string the plain language name of the camp
---@return string the camp's icon filename, including the extension
function CampsData.getCampIcon(displayName)
 
    local camp = CampsData.getAllDataForCamp(displayName)
 
    if not camp then
        return nil
    end
 
    -- the base string of the icon is the ID. It has to be not nil to
    -- concatenate
    if camp[INDEX_ID] then
        return camp[INDEX_ID] .. "_icon.png"
    else
        return nil
    end
end
 
 
 
---
--- Retrieves the plain language display name for the camp specified by
--- its ID.
---
--- Returns nil if the camp named was not found.
---
---@param campID string the ID of the camp
---@return string the camp's name as seen in-game
function CampsData.getCampNameByID(campID)
 
    local camp = CampsData.getAllDataForCampByID(campID)
 
    if not camp then
        return nil
    end
 
    return camp[INDEX_NAME]
end
 
 
 
---
--- Retrieves the icon filename for the the camp specified by its ID.
---
--- Returns nil if the camp named was not found.
---
---@param campID string the ID of the camp
---@return string the camp's icon filename, including the extension
function CampsData.getCampIconByID(campID)
 
    local camp = CampsData.getAllDataForCampByID(campID)
 
    if not camp then
        return nil
    end
 
    -- the base string of the icon is the ID. It has to be not nil to
    -- concatenate
    if camp[INDEX_ID] then
        return camp[INDEX_ID] .. "_icon.png"
    else
        return nil
    end
end
 
 
 
---
--- Retrieve all display names of camps that have a recipe that produces the
--- specified product ID.
---
---@param productID string the ID of the good to produce
---@return table of camp names that produce the specified good
function CampsData.getCampNamesWithRecipeProductID(productID)
 
    -- At runtime, this should never be nil or empty.
    if not productID or productID == "" then
        error("Parameter is nil or empty for product ID.")
    end
 
    if not campsTable then
        loadData()
    end
 
    return mapRecipeGoodIDsToCampNames[productID]
end
 
 
 
---
--- Retrieves the name of the camp at the specified index.
---
---@param index number index
---@return string name of the building at the specified index
function CampsData.getCampNameFromDatabase(index)
 
    if not index then
        return nil
    end
 
    if not campsTable then
        loadData()
    end
 
    return campsNames[index]
end
 
 
 
---
--- Returns the number of buildings that can be retrieved from this
--- module's database.
---
---@return number of records
function CampsData.getNumberOfCampsInDatabase()
 
    if not campsTable then
        loadData()
    end
 
    return #campsNames
end
end


--endregion
--endregion
--/** End Function definitions. Procedure resumes. **/






--region Public Building interface
--Override building recipe query interface
--getID(displayName)
campsDataModel.getIDsAndRecipesWhereProductID = getIDsAndRecipesWhereProductID
-- getCategory
campsDataModel.getIDsAndRecipesWhereProductIDAndBuildingID = getIDsAndRecipesWhereProductIDAndBuildingID
-- getCityScore
-- getConstructionCosts (as [goodName] = stack size)
-- getConstructionTime
-- getDescription
-- getIcon
-- isMovable
-- getName
-- getNumberOfWorkplaces
-- getSize (as "X x Y")
-- getStorage
 
function CampsData.getID(displayName)
    load()
    return mapNamesToIDs[displayName]
end
 
function CampsData.getCategory(id)
    load()
    return campsTable[id] ~= nil and campsTable[id][INDEX_CATEGORY]
end
 
function CampsData.getCityScore(id)
    load()
    return campsTable[id] ~= nil and campsTable[id][INDEX_CITY_SCORE]
end
 
function CampsData.getConstructionCosts(id)
 
    load()
    GoodsData = require("Module:GoodsData")


    camp = campsTable[id]
--Override recipe data retrieval interface
    if not camp then
campsDataModel.getRecipeGrade = getRecipeGrade
        return false
campsDataModel.getRecipeProductID = getRecipeProductID
    end
campsDataModel.getRecipeProductAmount = getRecipeProductAmount


    local constructionCosts = {}
    for _, stacks in ipairs(camp[INDEX_REQUIRED_GOODS]) do
        local goodName = GoodsData.getGoodNameByID(stacks[INDEX_CONSTRUCTION_GOODS_GOOD_ID])
        constructionCosts[goodName] = stacks[INDEX_CONSTRUCTION_GOODS_STACK_SIZE]
    end


    return constructionCosts
end
function CampsData.getConstructionTime(id)
    load()
    return campsTable[id] ~= nil and campsTable[id][INDEX_CONSTRUCTION_TIME]
end
function CampsData.getDescription(id)
    load()
    return campsTable[id] ~= nil and campsTable[id][INDEX_DESCRIPTION]
end
function CampsData.getIcon(id)
    load()
    return campsTable[id] ~= nil and id .. "_icon.png"
end
function CampsData.isMovable(id)
    load()
    return campsTable[id] ~= nil and campsTable[id][INDEX_MOVABLE]
end
function CampsData.getName(id)
    load()
    return campsTable[id] ~= nil and campsTable[id][INDEX_NAME]
end
function CampsData.getNumberOfWorkplaces(id)
    load()
    return campsTable[id] ~= nil and #campsTable[id][INDEX_WORKPLACES]
end
function CampsData.getSize(id)
    load()
    camp = campsTable[id]
    if not camp then
        return false
    end
    return camp[INDEX_SIZE_X] .. " × " .. camp[INDEX_SIZE_Y]
end
function CampsData.getStorage(id)
    load()
    return campsTable[id] ~= nil and campsTable[id][INDEX_STORAGE]
end
--endregion


return CampsData
return campsDataModel

Latest revision as of 19:53, 9 November 2024

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

---@module CampsData.lua
---
---This module does not define an _actual_ derived class, but it creates an instance of one via prototyping patterns. Understand this file as a big procedure, top-to-bottom, rather than a class definition.
---
---Initializes a BaseDataModel with the data file associated with this module. Makes necessary modifications to the basic data, including schema and method overrides, to permit the exceptions associated with data in this model.



--region Localization string constants
local ERROR_MESSAGE_INSTANCE_NOT_INITIALIZED = "This instance's data table was never initialized. Please check how and where this method was called to diagnose the problem"
--endregion



--Create instance
local BaseDataModel = require("Module:BaseDataModel")
local DATA_FILE = "Module:CampsData/Camps.json"

---@type BaseDataModel
local campsDataModel = BaseDataModel.new(DATA_FILE)



--Begin instance overrides
for _, building in pairs(campsDataModel.dataTable) do
    building[campsDataModel.schema.CATEGORY2] = "Gathering Camp"
    building[campsDataModel.schema.IS_PROVIDING_SERVICES] = false
end

campsDataModel.schema.RECIPE.PRODUCTION_TIME = "gatheringTime"

--IMPORTANT: The data structure has one fewer levels, like RECIPE > PRODUCT_ID
campsDataModel.schema.RECIPE.PRODUCT.ID = "seekedResource"



--/** Function definitions follow. **/
--Collapse the regions in the IDE to see the procedure pick up with the assignments of these functions to override the associated member methods of BaseDataModel.
--region Public building interface
--no overrides!
--endregion

--region Public building recipe query interface

local INDEX_PAIR_BUILDING_ID = "buildingID"
local INDEX_PAIR_RECIPE = "recipe"

---@public
---`Overrides BaseDataModel`
---
---Gets all this instance's buildings' recipes that have the specified product. Returns an array of pairs of building IDs and recipe data.
---
---@param self BaseDataModel this instance, with specific data
---@param productID string the product
---@return table array of pairs of building IDs and recipe data, or {} if none found
function getIDsAndRecipesWhereProductID(self, productID)

    if not self.dataTable then
        error(ERROR_MESSAGE_INSTANCE_NOT_INITIALIZED)
    end

    local ret = {}
    for id, building in pairs(self.dataTable) do
        for _, recipe in ipairs(building[self.schema.RECIPES]) do

            --If there's a matching seeked deposit
            if recipe[self.schema.RECIPE.PRODUCT.ID] == productID then
                -- Add as an buildingID-recipe pair
                table.insert(ret, {
                    [INDEX_PAIR_BUILDING_ID] = id,
                    [INDEX_PAIR_RECIPE] = recipe,
                })
            end
        end
    end
    return ret
end

---@public
---`Overrides BaseDataModel`
---
---Gets all this instance's specified building's recipes that produce the specified product. Returns an array of pairs of building IDs and recipe data.
---
---@param self BaseDataModel this instance, with specific data
---@param productID string the product
---@param buildingID string the building
---@return table array of pairs of building IDs and recipe data, or {} if none found
function getIDsAndRecipesWhereProductIDAndBuildingID(self, productID, buildingID)

    --Can't findID from here, but that's okay, this is a small data file: just loop.
    local ret = {}
    for id, building in pairs(self.dataTable) do

        if building[self.schema.ID] == buildingID then

            for _, recipe in ipairs(building[self.schema.RECIPES]) do

                --If there's a matching seeked deposit
                if recipe[self.schema.RECIPE.PRODUCT.ID] == productID then
                    -- Add as an buildingID-recipe pair
                    table.insert(ret, {
                        [INDEX_PAIR_BUILDING_ID] = id,
                        [INDEX_PAIR_RECIPE] = recipe,
                    })
                end
            end

        end
    end
    return ret
end

--endregion

--region Public recipe data retrieval interface

---@public
---`Overrides BaseDataModel`
---
---Gets the efficiency grade from the provided recipe.
---
---Parameters
---
---`self:BaseDataModel` - ignored
---
---`recipeData:recipePairTable` - ignored
---
---@return number efficiency grade
function getRecipeGrade()
    return 2
end

---@public
---`Overrides BaseDataModel`
---
---Gets the product ID from the provided recipe.
---
---@param self BaseDataModel this instance, with specific data
---@param recipeData recipePairTable
---@return string product ID
function getRecipeProductID(self, recipeData)
    return recipeData.recipe[self.schema.RECIPE.PRODUCT.ID]
end

---@public
---`Overrides BaseDataModel`
---
---Gets the amount of product produced by the provided recipe.
---
---Parameters
---
---`self:BaseDataModel` - ignored
---
---`recipeData:recipePairTable` - ignored
---
---@return number stack size
function getRecipeProductAmount()
    return 1
end

--endregion
--/** End Function definitions. Procedure resumes. **/



--Override building recipe query interface
campsDataModel.getIDsAndRecipesWhereProductID = getIDsAndRecipesWhereProductID
campsDataModel.getIDsAndRecipesWhereProductIDAndBuildingID = getIDsAndRecipesWhereProductIDAndBuildingID

--Override recipe data retrieval interface
campsDataModel.getRecipeGrade = getRecipeGrade
campsDataModel.getRecipeProductID = getRecipeProductID
campsDataModel.getRecipeProductAmount = getRecipeProductAmount



return campsDataModel