scenarios making Help: script.on_init

Place to get help with not working mods / modding interface.
Post Reply
User avatar
Xagros
Inserter
Inserter
Posts: 40
Joined: Thu Jul 20, 2017 4:11 pm
Contact:

scenarios making Help: script.on_init

Post by Xagros »

I'm working on a multiplayer campaign. I tried to market on script.on_init. but autofill, autodeconstruct and some require lua don't work with script.on_init. Somebody please help me.

control.lua

Code: Select all

require "util"
require "locale/utils/event"
require "config"
require "locale/utils/utils"
require "goal"

require "locale/autofill/autofill"
require "autodeconstruct"
require "locale/market/spot"
require "showhealth"
require "poll"

require "tag"
require "announcements"

require "locale/utils/player-logging"
require "locale/utils/undecorator"

function player_joined(event)
	local player = game.players[event.player_index]
	player.insert { name = "iron-plate", count = 100 }
	player.insert { name = "copper-plate", count = 100 }
	player.insert { name = "pistol", count = 1 }
	player.insert { name = "firearm-magazine", count = 100 }
end
function player_respawned(event)
end

script.on_init(function()
	tightspot_init(shops)
end)

Event.register(defines.events.on_player_created, player_joined)
Event.register(defines.events.on_player_respawned, player_respawned)
spot.lua

Code: Select all

tightspot_prices =
{
  ["coal"]=5,
  ["crude-oil-barrel"]=150,
  ["raw-wood"]=1,
  ["raw-fish"]=1,
  ["transport-belt"]=5,
  ["underground-belt"]=20,
  ["fast-transport-belt"]=50,
  ["fast-underground-belt"]=200,
  ["express-transport-belt"]=150,
  ["express-underground-belt"]=500,
  ["splitter"]=25,
  ["fast-splitter"]=50,
  ["express-splitter"]=200,
  ["burner-inserter"]=10,
  ["inserter"]=10,
  ["long-handed-inserter"]=15,
  ["fast-inserter"]=20,
  ["filter-inserter"]=35,
  ["loader"]=100,
  ["fast-loader"]=500,
  ["express-loader"]=1000,
  ["player-port"]=3000,
  ["red-wire"]=2,
  ["green-wire"]=2,
  ["wooden-chest"]=5,
  ["iron-chest"]=10,
  ["steel-chest"]=25,
  ["stone-furnace"]=10,
  ["steel-furnace"]=50,
  ["electric-furnace"]=70,
  ["offshore-pump"]=10,
  ["pipe"]=5,
  ["pipe-to-ground"]=20,
  ["boiler"]=15,
  ["steam-engine"]=50,
  ["steam-turbine"]=250,
  ["small-electric-pole"]=10,
  ["medium-electric-pole"]=50,
  ["big-electric-pole"]=100,
  ["solar-panel"]=150,
  ["substation"]=150,
  ["accumulator"]=150,
  ["assembling-machine-1"]=30,
  ["assembling-machine-2"]=50,
  ["assembling-machine-3"]=100,
  ["electric-mining-drill"]=50,
  ["burner-mining-drill"]=10,
  ["pumpjack"]=50,
  ["oil-refinery"]=100,
  ["chemical-plant"]=50,
  ["storage-tank"]=40,
  ["pump"]=20,
  ["logistic-robot"]=150,
  ["logistic-chest-passive-provider"]=50,
  ["logistic-chest-requester"]=50,
  ["radar"]=500,
  ["light-armor"]=10,
  ["heavy-armor"]=50,
  ["modular-armor"]=100,
  ["power-armor"]=500,
  ["power-armor-mk2"]=1500,
  ["rail"]=5,
  ["stone-wall"]=10,
  ["gate"]=25,
  ["landfill"]=50,
}

shops =
{
    fishhut_items =
  {
    "raw-fish",
    "stone-wall",
    "gate",
	"rail",
    "radar",
    "player-port",
    "power-armor"
  },
    base_items =
  {
    "raw-wood",
    "transport-belt",
    "underground-belt",
    "burner-inserter",
    "inserter",
    "splitter",
	"loader",
    "stone-furnace",
    "offshore-pump",
    "pipe",
    "boiler",
    "steam-engine",
    "solar-panel",
    "wooden-chest",
	"iron-chest",
    "small-electric-pole",
    "assembling-machine-1",
    "burner-mining-drill",
	"light-armor",
	"heavy-armor"
  },
    mid_items =
  {
    "coal",
    "fast-transport-belt",
    "fast-underground-belt",
    "burner-inserter",
    "long-handed-inserter",
    "fast-splitter",
	"fast-loader",
    "steel-furnace",
    "pumpjack",
    "pipe",
    "oil-refinery",
    "chemical-plant",
    "pump",
	"pipe-to-ground",
    "storage-tank",
    "medium-electric-pole",
    "big-electric-pole",
    "assembling-machine-2",
    "electric-mining-drill",
	"modular-armor"
  },
    last_items =
  {
    "crude-oil-barrel",
    "express-transport-belt",
    "express-underground-belt",
    "filter-inserter",
    "fast-inserter",
    "express-splitter",
	"express-loader",
    "electric-furnace",
    "red-wire",
    "green-wire",
    "logistic-robot",
    "logistic-chest-passive-provider",
    "logistic-chest-requester",
	"steel-chest",
	"accumulator",
    "substation",
    "steam-turbine",
    "assembling-machine-3",
	"landfill",
    "power-armor-mk2"
  },
}

function tightspot_make_offer(item)
  if not tightspot_prices[item] then game.print(item.." price is not defined. Please report this on the factorio bug forum") return end
  return { price={{"coin", tightspot_prices[item]}}, offer={type="give-item", item=item}}
end

function tightspot_init(shops)
  global.market1 = {game.get_entity_by_tag("fishhut").name, game.get_entity_by_tag("fishhut").position}
  global.market2 = {game.get_entity_by_tag("basemarket").name, game.get_entity_by_tag("basemarket").position}
  global.market3 = {game.get_entity_by_tag("midmarket").name, game.get_entity_by_tag("midmarket").position}
  global.market4 = {game.get_entity_by_tag("lastmarket").name, game.get_entity_by_tag("lastmarket").position}
  
  local market1 = game.surfaces[1].find_entity(global.market1[1], global.market1[2])
  local market2 = game.surfaces[1].find_entity(global.market2[1], global.market2[2])
  local market3 = game.surfaces[1].find_entity(global.market3[1], global.market3[2])
  local market4 = game.surfaces[1].find_entity(global.market4[1], global.market4[2])

  for index, item in pairs(shops.offers1) do
	market1.add_market_item(item)
  end
  
  for index, item in pairs(shops.offers2) do
	market2.add_market_item(item)
  end
  
  for index, item in pairs(shops.offers3) do
	market3.add_market_item(item)
  end
  
  for index, item in pairs(shops.offers4) do
	market4.add_market_item(item)
  end
end
autofill.lua

Code: Select all

-- Automatically fill certain entities with fuel when placed
-- A 3Ra Gaming revision
-- Original Author: Nexela

require "util"
MOD = { NAME = "Autofill", IF = "af" }
require "autofill_loader"
local order = {
	default = 1,
	opposite = 2,
	itemcount = 3
}

local vanilla_sets = {
	["car"] = { priority = order.default, "fuels-all", "ammo-bullets" },
	["tank"] = { priority = order.default, slots = { 2, 1, 1, 1 }, "fuels-all", "ammo-bullets", "ammo-shells",  "ammo-flamethrower"},
	["locomotive"] = { priority = order.default, group = "locomotives", slots = { 1 }, "fuels-all" },
	["boiler"] = { priority = order.default, group = "burners", limits = { 5 }, "fuels-all" },
	["nuclear-reactor"] = { priority = order.default, group = "burners", limits = { 5 }, "fuels-nuclear" },
	["burner-inserter"] = { priority = order.default, group = "burners", limits = { 2 }, "fuels-all" },
	["burner-mining-drill"] = { priority = order.default, group = "burners", limits = { 10 }, "fuels-all" },
	["stone-furnace"] = { priority = order.default, group = "burners", limits = { 10 }, "fuels-all" },
	["steel-furnace"] = { priority = order.default, group = "burners", limits = { 10 }, "fuels-all" },
	["gun-turret"] = { priority = order.default, group = "turrets", limits = { 25 }, "ammo-bullets" }
}


local vanilla_items = {
	["ammo-bullets"] = { "uranium-rounds-magazine","piercing-rounds-magazine", "firearm-magazine" },
	["ammo-rockets"] = { "atomic-bomb", "rocket", "explosive-rocket" },
	["ammo-shells"] = { "explosive-uranium-cannon-shell", "uranium-cannon-shell", "explosive-cannon-shell", "cannon-shell" },
	["ammo-shotgun"] = { "shotgun-shell", "piercing-shotgun-shell" },
	["ammo-flamethrower"] = { "flamethrower-ammo" },
}

loader.addItemArray(vanilla_items)
loader.addSets(vanilla_sets)

--flying text colors
local RED = { r = 0.9 }
local GREEN = { g = 0.7 }
local YELLOW = { r = 0.8, g = 0.8 }

local order = {
	default = 1,
	opposite = 2,
	itemcount = 3
}

--
--Events
--

Event.register(-3, function()
	initMod()
end)

Event.register(-1, function()
	initMod()
end)

Event.register(defines.events.on_built_entity, function(event)
	local player = game.players[event.player_index]
	local global = global
	if global.personalsets[player.name] and global.personalsets[player.name].active then
		local fillset = global.personalsets[player.name][event.created_entity.name] or global.defaultsets[event.created_entity.name]
		if fillset ~= 0 and fillset ~= nil then
			autoFill(event.created_entity, player, fillset)
		end
	end
end)

Event.register(defines.events.on_player_created, function(event)
	local username = game.players[event.player_index].name
	if global.personalsets[username] == nil then
		global.personalsets[username] = { active = true }
	end
end)

--
--Funtions
--

function autoFill(entity, player, fillset)
	local textpos = entity.position
	local maininv = player.get_inventory(defines.inventory.player_main)

	local vehicleinv
	local ok, err = pcall(function() vehicleinv = player.vehicle.get_inventory(2) end)
	if not ok then vehicleinv = false end

	local quickbar = player.get_inventory(defines.inventory.player_quickbar)
	local array, item, count, groupsize, slots, totalitemcount, color, inserted, removed
	for i = 1, #fillset do
		array = fillset[i]
		item = false
		count = 0
		color = RED

		if fillset.priority == order.itemcount then -- Pick item with highest count
		for j = 1, #array do
			if vehicleinv then
				if maininv.get_item_count(array[j]) + vehicleinv.get_item_count(array[j]) > count then
					item = array[j]
					count = maininv.get_item_count(array[j]) + vehicleinv.get_item_count(array[j])
				end
			else
				if maininv.get_item_count(array[j]) > count then
					item = array[j]
					count = maininv.get_item_count(array[j])
				end
			end
		end
		elseif fillset.priority == order.opposite then --Pick last available item
		for j = #array, 1, -1 do
			if maininv.get_item_count(array[j]) > 0 or vehicleinv and vehicleinv.get_item_count(array[j]) > 0 then
				item = array[j]
				count = maininv.get_item_count(array[j])
				count = not vehicleinv and count or count + vehicleinv.get_item_count(array[j])
				break
			end
		end
		else --Pick first available item
		for j = 1, #array do
			if maininv.get_item_count(array[j]) > 0 or vehicleinv and vehicleinv.get_item_count(array[j]) > 0 then
				item = array[j]
				count = maininv.get_item_count(array[j])
				count = not vehicleinv and count or count + vehicleinv.get_item_count(array[j])
				break
			end
		end
		end

		if not item or count < 1 then
			text({ "autofill.out-of-item", game.item_prototypes[array[1]].localised_name }, textpos, color)
			textpos.y = textpos.y + 1
		else
			-- Divide stack between group (only items in quickbar are part of group)
			if fillset.group then
				if player.cursor_stack.valid_for_read then
					groupsize = player.cursor_stack.count + 1
				else
					groupsize = 1
				end

				for k, v in pairs(global.personalsets[player.name]) do
					if type(v) == "table" and v.group == fillset.group then
						groupsize = groupsize + quickbar.get_item_count(k)
					end
				end
				for k, v in pairs(global.defaultsets) do
					if not global.personalsets[player.name][k] and v.group == fillset.group then
						groupsize = groupsize + quickbar.get_item_count(k)
					end
				end

				totalitemcount = 0
				for j = 1, #array do
					totalitemcount = totalitemcount + maininv.get_item_count(array[j])
				end
				if vehicleinv then
					for j = 1, #array do
						totalitemcount = totalitemcount + vehicleinv.get_item_count(array[j])
					end
				end
				count = math.max(1, math.min(count, math.floor(totalitemcount / groupsize)))
			end

			-- Limit insertion if has limit value
			if fillset.limits and fillset.limits[i] then
				if count > fillset.limits[i] then
					count = fillset.limits[i]
				end
			end

			-- Determine insertable stack count if has slot count
			if fillset.slots and fillset.slots[i] then
				slots = fillset.slots[i]
			else
				slots = 1
			end

			if count < game.item_prototypes[item].stack_size * slots then
				color = YELLOW
			else
				count = game.item_prototypes[item].stack_size * slots
				color = GREEN
			end

			-- Insert, count the difference and remove the difference
			inserted = entity.get_item_count(item)
			entity.insert({ name = item, count = count })
			inserted = entity.get_item_count(item) - inserted
			if inserted > 0 then
				if vehicleinv then
					removed = vehicleinv.get_item_count(item)
					vehicleinv.remove({ name = item, count = inserted })
					removed = removed - vehicleinv.get_item_count(item)
					if inserted > removed then
						maininv.remove({ name = item, count = inserted - removed })
					end
				else
					maininv.remove({ name = item, count = inserted })
				end
				if removed then
					text({ "autofill.insertion-from-vehicle", inserted, game.item_prototypes[item].localised_name, removed, game.entity_prototypes[player.vehicle.name].localised_name }, textpos, color)
					textpos.y = textpos.y + 1
				else
					text({ "autofill.insertion", inserted, game.item_prototypes[item].localised_name }, textpos, color)
					textpos.y = textpos.y + 1
				end
			end
		end -- if not item or count < 1 then
	end -- for i=1, #fillset do
end

function getDefaultSets()
	return {
		["car"] = { priority = order.default, global.fuels.all, global.ammo.bullets },
		["tank"] = { priority = order.default, slots = { 2, 1, 1 }, global.fuels.all, global.ammo.bullets, global.ammo.shells },
		["locomotive"] = { priority = order.default, slots = { 1 }, global.fuels.high },
		["boiler"] = { priority = order.default, group = "burners", limits = { 5 }, global.fuels.high },
	    ["nuclear-reactor"] = { priority = order.default, group = "burners", limits = { 5 }, "fuels-nuclear" },
		["burner-inserter"] = { priority = order.default, group = "burners", limits = { 1 }, global.fuels.high },
		["burner-mining-drill"] = { priority = order.default, group = "burners", limits = { 5 }, global.fuels.high },
		["stone-furnace"] = { priority = order.default, group = "burners", limits = { 5 }, global.fuels.high },
		["steel-furnace"] = { priority = order.default, group = "burners", limits = { 5 }, global.fuels.high },
		["gun-turret"] = { priority = order.default, group = "turrets", limits = { 10 }, global.ammo.bullets }
	} -- if group is defined, then insertable items are divided for buildable
	-- items in quickbar (and in hand).
end

function getLiteSets()
	return {
		["burner-inserter"] = { priority = order.default, group = "burners", limits = { 1 }, global.fuels.high },
		["gun-turret"] = { priority = order.default, group = "turrets", limits = { 10 }, global.ammo.bullets }
	}
end

function makePersonalLiteSets()
	local personalsets = {}
	for k, v in pairs(global.defaultsets) do
		personalsets[k] = 0
	end

	personalsets["burner-inserter"] = { priority = order.default, group = "burners", limits = { 1 }, global.item_arrays["fuels-high"] }
	personalsets["gun-turret"] = { priority = order.default, group = "turrets", limits = { 10 }, global.item_arrays["ammo-bullets"] }

	return personalsets
end

function globalPrint(msg)
	local players = game.players
	msg = { "autofill.msg-template", msg }
	for i = 1, #players do
		players[i].print(msg)
	end
end

function initMod(reset)
	if not global.defaultsets or not global.personalsets or not global.item_arrays or reset then -- Clears global

	loader.loadBackup()

	global.personalsets = {}
	for k, player in pairs(game.players) do
		global.personalsets[player.name] = { active = true }
	end

	global.has_init = true

	else
		loader.updateFuelArrays(global.item_arrays)
	end
end

function isValidEntity(name)
	if game.entity_prototypes[name] then
		return true
	end

	globalPrint({ "autofill.invalid-entityname", tostring(name) })
	return false
end

-- This fuction not just verifies the set, but also links strings into item arrays (replaces).
function isValidSet(set)
	if set == nil or set == 0 then
		return true
	elseif type(set) == "table" then
		for i = 1, #set do

			if type(set[i]) == "string" then

				if global.item_arrays[set[i]] then -- replace name with array
				set[i] = global.item_arrays[set[i]]
				else
					if game.item_prototypes[set[i]] then
						set[i] = { set[i] }
					else
						globalPrint({ "autofill.invalid-itemname", tostring(set[i]) })
						return false
					end
				end

			elseif type(set[i]) == "table" then

				for j = 1, #set[i] do
					if game.item_prototypes[set[i][j]] == nil then
						globalPrint({ "autofill.invalid-itemname", tostring(set[i][j]) })
						return false
					end
				end

			else
				globalPrint({ "autofill.invalid-form" })
				return false
			end
		end -- for i = 1, #set do

		return true
	end
	globalPrint({ "autofill.invalid-parameter" })
	return false
end

function isValidUser(name)
	local players = game.players
	for i = 1, #players do
		if players[i].name == name then
			return players[i].name
		end
	end

	if game.player then -- for single player game
	return game.player.name
	end

	globalPrint({ "autofill.invalid-username", tostring(name) })
	return false
end


function printToFile(line, path)
	path = path or "log"
	path = table.concat({ MOD.IF, "/", path, ".txt" })
	game.makefile(path, line)
end

function text(line, pos, colour) --colour as optional
local surface = game.surfaces[1]
if colour == nil then
	surface.create_entity({ name = "flying-text", position = pos, text = line })
else
	surface.create_entity({ name = "flying-text", position = pos, text = line, color = colour })
end
end

--
-- Mod interface
--

remote.add_interface(MOD.IF,
	{
		insertset = function(username, entityname, set) --this fuction is for inserting personal sets.
		username = isValidUser(username)
		if username and isValidEntity(entityname) and isValidSet(set) then
			global.personalsets[username][entityname] = set
		end
		end,
		addToDefaultSets = function(entityname, set)
			if isValidEntity(entityname) and isValidSet(set) then
				global.defaultsets[entityname] = set
			end
		end,
		getDefaultSets = function()
			local sets = table.deepcopy(global.defaultsets)
			for entity_name, set in pairs(sets) do
				for i = 1, #set do
					for name, array in pairs(global.item_arrays) do
						if global.defaultsets[entity_name][i] == array then
							set[i] = name
							break
						end
					end
				end
			end
			return sets
		end,
		setDefaultSets = function(sets)
			for entity_name, set in pairs(sets) do
				if not isValidSet(set) then
					return
				end
			end
			global.defaultsets = sets
		end,
		getBackupLog = function()
			local tbl = loader.getBackupLog()
			local block = table.concat(tbl, "\n")
			log(block)
		end,
		getItemArray = function(name)
			return global.item_arrays[name]
		end,
		setItemArray = function(name, new_array)
			if global.item_arrays[name] == nil then
				global.item_arrays[name] = new_array
			else -- replaces content of table without creating new table to maintain referers
			local old_array = global.item_arrays[name]
			local max = #old_array < #new_array and #new_array or #old_array
			for i = 1, max do
				old_array[i] = new_array[i]
			end
			end
		end,
		logGlobal = function(key)
			key = key or "global"
			if _G[key] then
				log(serpent.block(_G[key]))
			else
				globalPrint("Global not found.")
			end
		end,
		resetMod = function()
			initMod(true)
		end,
		resetUser = function(setname, username)
			username = isValidUser(username)
			if username then
				if setname == "lite" then
					global.personalsets[username] = makePersonalLiteSets()
				else
					global.personalsets[username] = { active = true }
				end
			end
		end,
		toggleUsage = function(username)
			username = isValidUser(username)
			if username then
				if global.personalsets[username] then
					global.personalsets[username].active = not global.personalsets[username].active
				else
					global.personalsets[username] = { active = true }
				end
			end
		end
	})
autodeconstruct.lua

Code: Select all

-- Automatically deconstruct mines when no more ore is available
-- A 3Ra Gaming revision
-- Original Author: mindmix

autodeconstruct = autodeconstruct or {}
autodeconstruct.remove_target = true

-- Find ore resources in a given area
-- @param surface target surface
-- @param position center position
-- @param range range to search around center
-- @param resource_category type of resources to find
-- @return array of resources that match the category
local function find_resources(surface, position, range, resource_category)
    local resource_category = resource_category or 'basic-solid'
    local top_left = {x = position.x - range, y = position.y - range}
    local bottom_right = {x = position.x + range, y = position.y + range}

    local resources = surface.find_entities_filtered{area={top_left, bottom_right}, type='resource'}
    categorized = {}
    for _, resource in pairs(resources) do
        if resource.prototype.resource_category == resource_category then
            table.insert(categorized, resource)
        end
    end
    return categorized
end

-- Find all entities of a certain type on the map. Called only once per map.
-- @param entity_type type of entity to find
-- @return array of matching entities
local function find_all_entities(entity_type)
    local surface = game.surfaces['nauvis']
    local entities = {}
    for chunk in surface.get_chunks() do
        local chunk_area = {lefttop = {x = chunk.x*32, y = chunk.y*32}, rightbottom = {x = chunk.x*32+32, y = chunk.y*32+32}}
        local chunk_entities = surface.find_entities_filtered({area = chunk_area, type = entity_type})
        for i = 1, #chunk_entities do
            entities[#entities + 1] = chunk_entities[i]
        end
    end
    return entities
end

-- Find an entity's target (output)
-- @param entity entity to find output for
-- @return LuaEntity target
local function find_target(entity)
    if entity.drop_target then
        return entity.drop_target
    else
        local entities = entity.surface.find_entities_filtered{position=entity.drop_position}
        if global.debug then msg_all({"autodeconstruct-debug", "found " .. entities[1].name .. " at " .. util.positiontostr(entities[1].position)}) end
        return entities[1]
    end
end

-- Find all mining drills with the same target
-- @param entity the target to search for
-- @return array of mining drills
local function find_targeting(entity)
    local range = global.max_radius
    local position = entity.position

    local top_left = {x = position.x - range, y = position.y - range}
    local bottom_right = {x = position.x + range, y = position.y + range}

    local surface = entity.surface
    local entities = {}
    local targeting = {}

    local entities = surface.find_entities_filtered{area={top_left, bottom_right}, type='mining-drill'}
    for i = 1, #entities do
        if find_target(entities[i]) == entity then 
            targeting[#targeting + 1] = entities[i]
        end
    end

    entities = surface.find_entities_filtered{area={top_left, bottom_right}, type='inserter'}
    for i = 1, #entities do
        if find_target(entities[i]) == entity then 
            targeting[#targeting + 1] = entities[i]
        end
    end
    if global.debug then msg_all({"autodeconstruct-debug", "found " .. #targeting .. " targeting"}) end
    return targeting
end

-- Find all mining drills that were mining a certain ore tile
-- @param entity ore entity
-- @return array of mining drills
local function find_drills(entity)
    local position = entity.position
    local surface = entity.surface
    
    local top_left = {x = position.x - global.max_radius, y = position.y - global.max_radius}
    local bottom_right = {x = position.x + global.max_radius, y = position.y + global.max_radius}

    local entities = {}
    local targeting = {}

    local entities = surface.find_entities_filtered{area={top_left, bottom_right}, type='mining-drill'}
    if global.debug then msg_all({"autodeconstruct-debug", "found " .. #entities  .. " drills"}) end
    for i = 1, #entities do
        if math.abs(entities[i].position.x - position.x) < entities[i].prototype.mining_drill_radius and math.abs(entities[i].position.y - position.y) < entities[i].prototype.mining_drill_radius then
            autodeconstruct.check_drill(entities[i])
        end
    end
end

-- Initialise globals
function autodeconstruct.init_globals()
    global.max_radius = 0.99
    drill_entities = find_all_entities('mining-drill')
    for _, drill_entity in pairs(drill_entities) do
        autodeconstruct.check_drill(drill_entity)
    end
end

-- Handle resource depletion
function autodeconstruct.on_resource_depleted(event)
    if event.entity.prototype.resource_category ~= 'basic-solid' or event.entity.prototype.infinite_resource ~= false then
        if global.debug then msg_all({"autodeconstruct-debug", "on_resource_depleted", game.tick .. " amount " .. event.entity.amount .. " resource_category " .. event.entity.prototype.resource_category .. " infinite_resource " .. (event.entity.prototype.infinite_resource == true and "true" or "false" )}) end
        return
    end
    drill = find_drills(event.entity)
end

-- Check a mining drill for depletion and order deconstruction if so
-- @param drill mining drill to check
function autodeconstruct.check_drill(drill)
    if drill.mining_target ~= nil and drill.mining_target.valid then
        if drill.mining_target.amount > 0 then return end -- this should also filter out pumpjacks and infinite resources
    end
    
    local mining_drill_radius = drill.prototype.mining_drill_radius
    if mining_drill_radius > global.max_radius then
        global.max_radius = mining_drill_radius
    end

    if mining_drill_radius == nil then return end 
    
    resources = find_resources(drill.surface, drill.position, mining_drill_radius)
    for i = 1, #resources do
        if resources[i].amount > 0 then return end
    end
    if global.debug then msg_all({"autodeconstruct-debug", util.positiontostr(drill.position) .. " found no resources, deconstructing"}) end
    autodeconstruct.order_deconstruction(drill)
end

-- Handle cancelled deconstruction
function autodeconstruct.on_canceled_deconstruction(event)
    if event.player_index ~= nil or event.entity.type ~= 'mining-drill' then return end
    if global.debug then msg_all({"autodeconstruct-debug", "on_canceled_deconstruction", util.positiontostr(event.entity.position) .. " deconstruction timed out, checking again"}) end
    autodeconstruct.check_drill(event.entity)
end

-- Handle placed entity
function autodeconstruct.on_built_entity(event)
    if event.created_entity.type ~= 'mining-drill' then return end
    if event.created_entity.prototype.mining_drill_radius > global.max_radius then
        global.max_radius = event.created_entity.prototype.mining_drill_radius
        if global.debug then msg_all({"autodeconstruct-debug", "on_built_entity", "global.max_radius updated to " .. global.max_radius}) end
    end
end

-- Order drill deconstruction
-- @param drill mining drill to deconstruct    
function autodeconstruct.order_deconstruction(drill)
    if drill.to_be_deconstructed(drill.force) then
        if global.debug then msg_all({"autodeconstruct-debug", util.positiontostr(drill.position)" already marked"}) end
        return
    end
    
    local deconstruct = false
--[[ #TODO
config.lua: autodeconstruct.wait_for_robots = false
    if autodeconstruct.wait_for_robots then
        logistic_network = drill.surface.find_logistic_network_by_position(drill.position, drill.force.name)
        if logistic_network ~= nil then
            if logistic_network.available_construction_robots > 0 then
                deconstruct = true
            end
        end
    else
        deconstruct = true
    end
--]]
    deconstruct = true
--[[ END TODO

--]]
    if deconstruct == true and drill.minable then
        if drill.order_deconstruction(drill.force) then
            if global.debug then msg_all({"autodeconstruct-debug", util.positiontostr(drill.position)  .. " " .. drill.name .. " success"}) end
        else
            msg_all({"autodeconstruct-err-specific", "drill.order_deconstruction", util.positiontostr(drill.position) .. "failed to order deconstruction on " .. drill.name })
        end
        if autodeconstruct.remove_target then
            target = find_target(drill)
            if target ~= nil and target.minable then
                if target.type == "logistic-container" or target.type == "container" then
                    targeting = find_targeting(target)
                    if targeting ~= nil then
                        for i = 1, #targeting do
                            if not targeting[i].to_be_deconstructed(targeting[i].force) then return end
                        end
                        -- we are the only one targeting
                        if target.to_be_deconstructed(target.force) then
                            target.cancel_deconstruction(target.force)
                        end
                        if target.order_deconstruction(target.force) then
                            if global.debug then msg_all({"autodeconstruct-debug", util.positiontostr(target.position) .. " " .. target.name .. " success"}) end
                        else
                            msg_all({"autodeconstruct-err-specific", "target.order_deconstruction", util.positiontostr(target.position) .. "failed to order deconstruction on " .. target.name})
                        end
                    end
                end
--[[ #TODO
                if target.type == "transport-belt" then
                    -- find entities with this belt as target
                end
--]]
            end
        end
    end
end

-- Message all players
-- @param message message to sen
function msg_all(message)
    if message[1] == "autodeconstruct-debug" then
        table.insert(message, 2, debug.getinfo(2).name)
    end
    for _,p in pairs(game.players) do
        p.print(message)
    end
end

global.debug = false
remote.add_interface("ad", {
    debug = function()
        global.debug = not global.debug
    end,
    init = function()
        autodeconstruct.init_globals()
    end
})

Event.register(-1, function()
    local _, err = pcall(autodeconstruct.init_globals)
    if err then msg_all({"autodeconstruct-err-generic", err}) end
end)

Event.register(-3, function()
    local _, err = pcall(autodeconstruct.init_globals)
    if err then msg_all({"autodeconstruct-err-generic", err}) end
end)

Event.register(defines.events.on_canceled_deconstruction, function(event)
    local _, err = pcall(autodeconstruct.on_canceled_deconstruction, event)
    if err then msg_all({"autodeconstruct-err-specific", "on_canceled_deconstruction", err}) end
end)

Event.register(defines.events.on_resource_depleted, function(event)
    local _, err = pcall(autodeconstruct.on_resource_depleted, event)
    if err then msg_all({"autodeconstruct-err-specific", "on_resource_depleted", err}) end
end)

Event.register(defines.events.on_robot_built_entity, function(event)
    local _, err = pcall(autodeconstruct.on_built_entity, event)
    if err then msg_all({"autodeconstruct-err-specific", "on_robot_built_entity", err}) end
end)

Event.register(defines.events.on_built_entity, function(event)
    local _, err = pcall(autodeconstruct.on_built_entity, event)
    if err then msg_all({"autodeconstruct-err-specific", "on_built_entity", err}) end
end)
ImageImage

Nexela
Smart Inserter
Smart Inserter
Posts: 1828
Joined: Wed May 25, 2016 11:09 am
Contact:

Re: scenarios making Help: script.on_init

Post by Nexela »

Those scenarios use a custom scripted event handler to handle events and registering/remove scripts using script. will break it.

replace your script.on_init() with

Code: Select all

Event.register(Event.core_events.init, function()
   tightspot_init(shops)
end

User avatar
Xagros
Inserter
Inserter
Posts: 40
Joined: Thu Jul 20, 2017 4:11 pm
Contact:

Re: scenarios making Help: script.on_init

Post by Xagros »

Nexela wrote:Those scenarios use a custom scripted event handler to handle events and registering/remove scripts using script. will break it.

replace your script.on_init() with

Code: Select all

Event.register(Event.core_events.init, function()
   tightspot_init(shops)
end)
Perfect working!

It worked perfectly. Thank you very much. And I will try harder and make a great scenario.
ImageImage

Post Reply

Return to “Modding help”