Module:Crop Profit Table

From Sun Haven Wiki
Jump to navigation Jump to search
Bouncer shiny.gif

This article is a candidate for deletion.
Reason: I think this has been replaced by {{Crop profit}}/Module:Crops by category and can be deleted.
Disagree? Discuss here.

Check what links here and the page history before deletion.


Subpages

-- {{#dpl:
-- |namespace   =
-- |category    = Crops
-- |category    = Withergate crops
-- |ordermethod = title
-- |uses        = Template:Harvest summary
-- |include     = {Harvest summary}:name:growth:regrowthRate:cropYield:season:seed,{Item infobox}:region:sell
-- |format      = ~,,,
-- |secseparators={{!}}
-- }}
--
-- ~|Demon Orb |3 | |1 |Any |Demon Seeds|Withergate |24 |Tickets|Eggplant |4 | |1 |Any |Eggplant Seeds|Withergate |18 |Tickets|Kraken Kale |4 | |1 |Any |Kraken Kale Seeds|Withergate |6 |Tickets|Moonplant |6 | |1 |Any |Moonplant Seeds|Withergate |11 |Tickets|Razorstalk |6 | |1 |Any |Razorstalk Seeds|Withergate |9 |Tickets|Snappy Plant |7 | |1 |Any |Snappy Seeds|Withergate |22 |Tickets|Suckerstem |6 | |1 |Any |Suckerstem Seeds|Withergate |18 |Tickets|Tombmelon |3 | |1 |Any |Tombmelon Seeds|Withergate |10 |Tickets 
--
--
-- {{#dpl:
-- |category=Stores
-- |category=Sells Eggplant Seeds
-- |uses=Template:Shop
-- |include={Shop}:1:2:3
-- |format=~,,,
-- |secseparators={{!}}
-- |ordermethod=sortkey
-- }}

-- ~|Kraken Kale Seeds |3 |Tickets|Razorstalk Seeds |4 |Tickets|Moonplant Seeds |6 |Tickets|Tombmelon Seeds |8 |Tickets|Suckerstem Seeds |10 |Tickets|Snappy Seeds |13 |Tickets|Eggplant Seeds |13 |Tickets|Demon Seeds |17 |Tickets|Withergate Fishing Rod |250 |Tickets 
local p = {}
local lib = require('Module:Feature')

function p.main(frame)
	local args = require('Module:Arguments').getArgs(frame)
	return p._main(args)
end

function p._main(args)
	local crops = args.crops or ''
	local shop_availability = args.shop_availability or ''
  local season = args.season or ''

  crop_data = parse_crops(crops)
  shop_data = parse_shop_availability(shop_availability, crop_data)
	
  local profit_data = calculate_profit(shop_data)
  local profit_table = format_into_table(profit_data)
  return profit_table
end


function splitstring(inputstr, delim)
  local t={}
  for str in string.gmatch(inputstr, "([^"..delim.."]+)") do
    table.insert(t, str)
  end
  return t
end

function parse_crops(crop_string)
  local result = {}
  local pieces = splitstring(crop_string, '|')
  
  local index = 0
  local total_parts = 9
  
  local current_data = {}
  
  for k,v in ipairs(pieces) do
    --,name,growth,regrowthRate,cropYield,season,seed,region,sell,currency
    if v ~= "~" then
      local trimmed_value = string.gsub(v, '^%s*(.-)%s*$', '%1')
      -- print("parsing index", index, v)
      if index >= total_parts then
        if current_data["name"] ~= "" then
          result[current_data["name"]] = current_data
        end
        index = 0
        current_data = {}
      end

      if index == 0 then
        current_data["name"] = trimmed_value
      elseif index == 1 then
        current_data["growth"] = tonumber(v)
      elseif index == 2 then
        current_data["regrowthRate"] = tonumber(v)
      elseif index == 3 then
        current_data["cropYield"] = tonumber(v)
      elseif index == 4 then
        current_data["season"] = trimmed_value
        local length = 0
        for _ in pairs(splitstring(string.gsub(trimmed_value, " and ", "@"), "@")) do length = length + 1 end
        current_data["totalSeasons"] = length
      elseif index == 5 then
        current_data["seed"] = trimmed_value
      elseif index == 6 then
        current_data["region"] = trimmed_value
      elseif index == 7 then
        current_data["sell"] = tonumber(v)
      elseif index == 8 then
        current_data["selltype"] = trimmed_value
      end
      
      index = index + 1
      
    end
  end
  
  result=current_data
  
  -- Insert last item into table, otherwise it gets skipped
  result[current_data["name"]] = current_data
  
  return result
  end


function parse_shop_availability(shop_string, crop_data)
  local result = crop_data
  local pieces = splitstring(shop_string, '|')
  
  local index = 0
  local total_parts = 3

  local current_plant = ""
  
  for k,v in ipairs(pieces) do
    --,name,sell price,currency type
    if v ~= "~" then
      local trimmed_value = string.gsub(v, '^%s*~?;?(.-)~?%s*$', '%1')
      if index >= total_parts then
        index = 0
      end
      

      if index == 0 then
        current_plant = ""
        for plant_k, plant_v in pairs(crop_data) do
          if plant_v["seed"] == trimmed_value then
            current_plant = plant_k
          end
        end
      elseif current_plant ~= "" and index == 1 then
        result[current_plant]["seedPrice"] = tonumber(v)
      elseif current_plant ~= "" and index == 2 then
        result[current_plant]["currency"] = trimmed_value
      end
      
      index = index + 1
      
    end
  end
  
  for k,v in pairs(crop_data) do
    if v["seedPrice"] == nil then
      for inner_k, inner_v in pairs(crop_data) do
        if inner_v["seed"] == v["seed"] then
          v["seedPrice"] = inner_v["seedPrice"]
        end
    
        if v["seedPrice"] == nil then
          v["seedPrice"] = 0
        end
      end
    end
  end

  return result
end

function calculate_profit(crop_data) 
  for k, v in pairs(crop_data) do
    local max_harvest = 0
    local regrowth_rate = v["regrowthRate"]
    local total_seasons = 1
    local growth = v["growth"] or 0
    local crop_yield = v["cropYield"] or 1   
    local seed_price = v["seedPrice"] or 0   
    local sell = v["sell"] or 0
    
    local growing_days = 28 * total_seasons

    -- ((28 - (Days to Grow + 1) ) / regrowth rate) + 1 (Rounded Down)
    if regrowth_rate ~= "" and regrowth_rate ~= nil then
      max_harvest = math.floor((growing_days - growth - 1) / regrowth_rate) + 1
    else 
      max_harvest = math.floor(growing_days / (growth + 1))
    end

    crop_data[k]["maxHarvest"] = max_harvest
    
    -- Single Yield Profit = (Crop Sell * Crop Yield) - Seed Buy Price
    crop_data[k]["singleYieldProfit"] = sell * crop_yield - seed_price
    
    -- Profit for all harvests = ((Crop Sell * Crop Yield) * Max Harvest) - Seed Buy Price
    if regrowth_rate ~= "" and regrowth_rate ~= nil then
      crop_data[k]["allHarvestProfit"] = ((sell * crop_yield) * max_harvest) - seed_price
    else
      crop_data[k]["allHarvestProfit"] = crop_data[k]["singleYieldProfit"] * max_harvest
    end
    
    -- not regrows:
      -- profit / (28 * seasons)
    -- else:
      -- profit / initial_growth
    if regrowth_rate ~= "" and regrowth_rate ~= nil then
      local profit = (max_harvest * sell * crop_yield) - seed_price
      crop_data[k]["profitPerDay"] = math.floor(profit / growing_days)
    else
      crop_data[k]["profitPerDay"] = math.floor(crop_data[k]["singleYieldProfit"] / growth)
    end
    
  end

  return crop_data
end

function format_into_table(profit_data)
  local profit_table = {}

  local formatted_table = mw.html.create('table')
  
  formatted_table
    :addClass('sortable article-table table-large')
    :css('text-align','center')
    :newline()

    -- TABLE HEADER
    :tag('tr')
        :tag('th')
            :css('width','140x')
            :wikitext('Crop')
        :done()
        :tag('th')
            :attr('data-sort-type', "number")
            :wikitext('Seed Price')
        :done()
        :tag('th')
            :attr('data-sort-type', "number")
            :wikitext('Sell Price')
        :done()
        :tag('th')
            :attr('data-sort-type', "number")
            :wikitext('Max harvests')
        :done()
        :tag('th')
            :attr('data-sort-type', "number")
            :wikitext('Single Yield Profit')
        :done()
        :tag('th')
            :attr('data-sort-type', "number")
            :wikitext('Harvest Profit')
        :done()
        :tag('th')
            :attr('data-sort-type', "number")
            :wikitext('Profit Per Day')
        :done()
    :done()
    :newline()

  for crop_name, profit_data in pairs(crop_data) do
    local row_node = mw.html.create('tr')
    local crop = mw.html.create("td")
    local seed_price = mw.html.create("td")
    local sell_price = mw.html.create("td")
    local max_harvest = mw.html.create("td")
    local single_yield_profit = mw.html.create("td")
    local season_profit = mw.html.create("td")
    local profit_per_day = mw.html.create("td")

    local sell_type = string.lower(profit_data["selltype"])
    if string.find(sell_type, "orb") then
      sell_type = "Mana Orbs"
    elseif string.find(sell_type, "ticket") then
      sell_type = "Tickets"
    else
      sell_type = "Coins"
    end

    row_node
      :tag('td')
        :attr('data-sort-value', crop_name)
        :css('text-align', 'left')
        :wikitext('[[File:', crop_name, '.png|30px]] [[', crop_name, ']]')
      :done()
   
         
    seed_price
      :attr('data-sort-value', profit_data["seedPrice"])
      :wikitext(profit_data["seedPrice"])
      :done()

    row_node:wikitext(tostring(seed_price))
    
      
    sell_price
      :attr('data-sort-value', profit_data["sell"])
      :wikitext(profit_data["sell"])
      :done()

    row_node:wikitext(tostring(sell_price))

    max_harvest
      :attr('data-sort-value', profit_data["maxHarvest"])
      :wikitext(profit_data["maxHarvest"])
      :done()

    row_node:wikitext(tostring(max_harvest))
    
    single_yield_profit
      :attr('data-sort-value', profit_data["singleYieldProfit"])
      :wikitext(profit_data["singleYieldProfit"], '[[File:', sell_type, '.png|24px]]')
      :done()
    
    row_node:wikitext(tostring(single_yield_profit))
    
    season_profit
      :attr('data-sort-value', profit_data["allHarvestProfit"])
      :wikitext(profit_data["allHarvestProfit"], '[[File:', sell_type, '.png|24px]]')
      :done()
    
    row_node:wikitext(tostring(season_profit))
    
    profit_per_day
      :attr('data-sort-value', profit_data["profitPerDay"])
      :wikitext(profit_data["profitPerDay"], '[[File:', sell_type, '.png|24px]]')
      :done()
    
    row_node:wikitext(tostring(profit_per_day))
    
    -- Add row to the table
    row_node:done()
    formatted_table
      :newline()
      :wikitext(tostring(row_node))

  end
  
  formatted_table:allDone()
  return tostring(formatted_table)

end

return p