Update all code styles

This commit is contained in:
Cooldude2606
2024-09-28 01:56:54 +01:00
parent 5e2a62ab27
commit 292c1a1b68
194 changed files with 9817 additions and 9703 deletions

View File

@@ -13,42 +13,42 @@ Event.add(defines.events.on_player_created, function(event)
game.map_settings.enemy_expansion.enabled = config.enemy_expansion
local r = config.chart_radius
local p = player.position
player.force.chart(player.surface, {{p.x-r, p.y-r}, {p.x+r, p.y+r}})
player.force.chart(player.surface, { { p.x - r, p.y - r }, { p.x + r, p.y + r } })
end
-- spawn items
for item, callback in pairs(items) do
if type(callback) == 'function' then
if type(callback) == "function" then
local stats = player.force.get_item_production_statistics(player.surface)
local made = stats.get_input_count(item)
local success, count = pcall(callback, made, stats.get_input_count, player)
count = math.floor(count)
if success and count > 0 then
player.insert{name=item, count=count}
player.insert{ name = item, count = count }
end
end
end
if config.armor.enable then
player.insert{name=config.armor.main, count=1}
player.insert{ name = config.armor.main, count = 1 }
for _, item in pairs(config.armor.item) do
player.insert{name=item.equipment, count=item.count}
player.insert{ name = item.equipment, count = item.count }
end
end
end)
Event.on_init(function()
remote.call('freeplay', 'set_created_items', {})
remote.call('freeplay', 'set_chart_distance', 0)
remote.call('freeplay', 'set_skip_intro', config.skip_intro)
remote.call("freeplay", "set_created_items", {})
remote.call("freeplay", "set_chart_distance", 0)
remote.call("freeplay", "set_skip_intro", config.skip_intro)
if config.research_queue_from_start then
for _, force in pairs(game.forces) do
--force.research_queue_enabled = true
-- force.research_queue_enabled = true
end
end
if not config.disable_base_game_silo_script then
if config.skip_victory then
remote.call('silo_script', 'set_no_victory', true)
remote.call("silo_script", "set_no_victory", true)
end
end
end)
end)

View File

@@ -20,10 +20,10 @@ end)
--- Kicks an afk player, used to add a delay so the gui has time to appear
local kick_player_async =
Async.register(function(player)
if game.tick - primitives.last_active < config.kick_time then return end -- Safety Catch
game.kick_player(player, 'AFK while no active players on the server')
end)
Async.register(function(player)
if game.tick - primitives.last_active < config.kick_time then return end -- Safety Catch
game.kick_player(player, "AFK while no active players on the server")
end)
--- Check for an active player every update_time number of ticks
Event.on_nth_tick(config.update_time, function()
@@ -48,10 +48,10 @@ Event.on_nth_tick(config.update_time, function()
local res = player.display_resolution
local uis = player.display_scale
player.gui.screen.add{
type = 'frame',
name = 'afk-kick',
caption = {'afk-kick.message'},
}.location = { x=res.width*(0.5 - 0.11*uis), y=res.height*(0.5 - 0.14*uis) }
type = "frame",
name = "afk-kick",
caption = { "afk-kick.message" },
}.location = { x = res.width * (0.5 - 0.11 * uis), y = res.height * (0.5 - 0.14 * uis) }
-- Kick the player, some delay needed because network delay
kick_player_async:start_after(10, player)

View File

@@ -18,7 +18,7 @@ Event.add(defines.events.on_console_chat, function(event)
-- Sends the message as text above them
if config.show_player_messages then
send_text(player, {'chat-popup.message', player.name, event.message})
send_text(player, { "chat-popup.message", player.name, event.message })
end
if not config.show_player_mentions then return end
@@ -30,9 +30,8 @@ Event.add(defines.events.on_console_chat, function(event)
for _, mentioned_player in pairs(game.connected_players) do
if mentioned_player.index ~= player.index then
if search_string:find(mentioned_player.name:lower(), 1, true) then
send_text(mentioned_player, {'chat-popup.ping', player.name})
send_text(mentioned_player, { "chat-popup.ping", player.name })
end
end
end
end)
end)

View File

@@ -17,17 +17,17 @@ Event.add(defines.events.on_console_chat, function(event)
local prefix = config.command_prefix
for key_word, reply in pairs(config.messages) do
if message:find(key_word) then
local is_command = message:find(prefix..key_word)
if type(reply) == 'function' then
local is_command = message:find(prefix .. key_word)
if type(reply) == "function" then
reply = reply(player, is_command)
end
if is_command and allowed then
game.print{'chat-bot.reply', reply}
game.print{ "chat-bot.reply", reply }
elseif is_command then
player.print{'chat-bot.disallow'}
player.print{ "chat-bot.disallow" }
elseif not allowed then
player.print{'chat-bot.reply', reply}
player.print{ "chat-bot.reply", reply }
end
end
end
@@ -35,18 +35,16 @@ Event.add(defines.events.on_console_chat, function(event)
if not allowed then return end
for key_word, reply in pairs(config.commands) do
if message:find(prefix..key_word) then
if type(reply) == 'function' then
if message:find(prefix .. key_word) then
if type(reply) == "function" then
local msg = reply(player, true)
if reply then
game.print{'chat-bot.reply', msg}
game.print{ "chat-bot.reply", msg }
end
else
game.print{'chat-bot.reply', reply}
game.print{ "chat-bot.reply", reply }
end
end
end
end)
end)

View File

@@ -9,33 +9,33 @@ local messages = config.messages
local locations = config.locations
local Public = {
compilatrons={},
current_messages={}
compilatrons = {},
current_messages = {},
}
Storage.register({
compilatrons = Public.compilatrons,
current_messages = Public.current_messages
current_messages = Public.current_messages,
}, function(tbl)
Public.compilatrons = tbl.compilatrons
Public.current_messages = tbl.current_messages
end)
local speech_bubble_async =
Async.register(function(data)
local message =
data.ent.surface.create_entity{
name = 'compi-speech-bubble',
text = messages[data.name][data.msg_number],
source = data.ent,
position = {0, 0},
}
Async.register(function(data)
local message =
data.ent.surface.create_entity{
name = "compi-speech-bubble",
text = messages[data.name][data.msg_number],
source = data.ent,
position = { 0, 0 },
}
Public.current_messages[data.name] = {
message = message,
msg_number = data.msg_number
}
end)
Public.current_messages[data.name] = {
message = message,
msg_number = data.msg_number,
}
end)
--- This will move the messages onto the next message in the loop
local function circle_messages()
@@ -57,7 +57,7 @@ local function circle_messages()
msg_number = 1
end
-- this calls the callback above to re-spawn the message after some time
speech_bubble_async:start_after(300, {ent = ent, name = name, msg_number = msg_number})
speech_bubble_async:start_after(300, { ent = ent, name = name, msg_number = msg_number })
end
end
@@ -77,10 +77,10 @@ function Public.add_compilatron(entity, name)
Public.compilatrons[name] = entity
local message =
entity.surface.create_entity(
{name = 'compi-speech-bubble', text = messages[name][1], position = {0, 0}, source = entity}
)
Public.current_messages[name] = {message = message, msg_number = 1}
entity.surface.create_entity
{ name = "compi-speech-bubble", text = messages[name][1], position = { 0, 0 }, source = entity }
Public.current_messages[name] = { message = message, msg_number = 1 }
end
--- This spawns a new compilatron on a surface with the given location tag (not a position)
@@ -88,8 +88,8 @@ end
-- @tparam string location the location tag that is in the config file
function Public.spawn_compilatron(surface, location)
local position = locations[location]
local pos = surface.find_non_colliding_position('small-biter', position, 1.5, 0.5)
local compi = surface.create_entity {name='small-biter', position=pos, force=game.forces.neutral}
local pos = surface.find_non_colliding_position("small-biter", position, 1.5, 0.5)
local compi = surface.create_entity{ name = "small-biter", position = pos, force = game.forces.neutral }
Public.add_compilatron(compi, location)
end

View File

@@ -12,21 +12,21 @@ Event.add(defines.events.on_entity_damaged, function(event)
local damage = math.floor(event.original_damage_amount)
local health = math.floor(entity.health)
local health_percentage = entity.get_health_ratio()
local text_colour = {r=1-health_percentage, g=health_percentage, b=0}
local text_colour = { r = 1 - health_percentage, g = health_percentage, b = 0 }
-- Gets the location of the text
local size = entity.get_radius()
if size < 1 then size = 1 end
local r = (math.random()-0.5)*size*config.damage_location_variance
local r = (math.random() - 0.5) * size * config.damage_location_variance
local p = entity.position
local position = {x=p.x+r, y=p.y-size}
local position = { x = p.x + r, y = p.y - size }
-- Sets the message
local message
if entity.name == 'character' and config.show_player_health then
message = {'damage-popup.player-health', health}
elseif entity.name ~= 'character' and cause and cause.name == 'character' and config.show_player_damage then
message = {'damage-popup.player-damage', damage}
if entity.name == "character" and config.show_player_health then
message = { "damage-popup.player-health", health }
elseif entity.name ~= "character" and cause and cause.name == "character" and config.show_player_damage then
message = { "damage-popup.player-damage", damage }
end
-- Outputs the message as floating text
@@ -38,5 +38,4 @@ Event.add(defines.events.on_entity_damaged, function(event)
text_colour
)
end
end)
end)

View File

@@ -7,11 +7,11 @@ local config = require("modules.exp_legacy.config.death_logger") --- @dep config
local format_time, move_items = _C.format_time, _C.move_items_stack --- @dep expcore.common
-- Max amount of ticks a corpse can be alive
local corpse_lifetime = 60*60*15
local corpse_lifetime = 60 * 60 * 15
local deaths = {
archive={} -- deaths moved here after body is gone
--{player_name='Cooldude2606', time_of_death='15H 15M', position={x=0, y=0}, corpse=LuaEntity, tag=LuaCustomChartTag}
archive = {}, -- deaths moved here after body is gone
-- {player_name='Cooldude2606', time_of_death='15H 15M', position={x=0, y=0}, corpse=LuaEntity, tag=LuaCustomChartTag}
}
Storage.register(deaths, function(tbl)
deaths = tbl
@@ -20,15 +20,15 @@ end)
--- Creates a new death marker and saves it to the given death
local function create_map_tag(death)
local player = game.players[death.player_name]
local message = player.name..' died'
local message = player.name .. " died"
if config.include_time_of_death then
local time = format_time(death.time_of_death, {hours=true, minutes=true, string=true})
message = message..' at '..time
local time = format_time(death.time_of_death, { hours = true, minutes = true, string = true })
message = message .. " at " .. time
end
death.tag = player.force.add_chart_tag(player.surface, {
position=death.position,
icon=config.map_icon,
text=message
position = death.position,
icon = config.map_icon,
text = message,
})
end
@@ -62,7 +62,7 @@ end
-- when a player dies a new death is added to the records and a map marker is made
Event.add(defines.events.on_player_died, function(event)
local player = game.players[event.player_index]
local corpse = player.surface.find_entity('character-corpse', player.position)
local corpse = player.surface.find_entity("character-corpse", player.position)
if config.use_chests_as_bodies then
local items = corpse.get_inventory(defines.inventory.character_corpse)
local chest = move_items(items, corpse.surface, corpse.position)
@@ -74,7 +74,7 @@ Event.add(defines.events.on_player_died, function(event)
player_name = player.name,
time_of_death = event.tick,
position = player.position,
corpse = corpse
corpse = corpse,
}
if config.show_map_markers then
create_map_tag(death)
@@ -84,11 +84,11 @@ Event.add(defines.events.on_player_died, function(event)
-- Draw a light attached to the corpse with the player color
if config.show_light_at_corpse then
rendering.draw_light{
sprite = 'utility/light_medium',
sprite = "utility/light_medium",
color = player.color,
target = corpse,
force = player.force,
surface = player.surface
surface = player.surface,
}
end
end)
@@ -122,7 +122,7 @@ if config.show_line_to_corpse then
dash_length = 1,
gap_length = 1,
surface = player.surface,
draw_on_ground = true
draw_on_ground = true,
}
end
end
@@ -131,7 +131,7 @@ end
-- every 5 min all bodies are checked for valid map tags
if config.show_map_markers then
local check_period = 60*60*5 -- five minutes
local check_period = 60 * 60 * 5 -- five minutes
Event.on_nth_tick(check_period, function()
check_map_tags()
end)
@@ -141,9 +141,9 @@ if config.auto_collect_bodies then
Event.add(defines.events.on_character_corpse_expired, function(event)
local corpse = event.corpse
local items = corpse.get_inventory(defines.inventory.character_corpse)
move_items(items, corpse.surface, {x=0, y=0})
move_items(items, corpse.surface, { x = 0, y = 0 })
end)
end
-- this is so other modules can access the logs
return deaths
return deaths

View File

@@ -10,19 +10,19 @@ local config = require("modules.exp_legacy.config.deconlog") --- @dep config.dec
local filepath = "log/decon.log"
local function add_log(data)
game.write_file(filepath, data .. "\n", true, 0) -- write data
game.write_file(filepath, data .. "\n", true, 0) -- write data
end
local function get_secs()
return format_time(game.tick, { hours = true, minutes = true, seconds = true, string = true })
return format_time(game.tick, { hours = true, minutes = true, seconds = true, string = true })
end
local function pos_to_string(pos)
return tostring(pos.x) .. "," .. tostring(pos.y)
return tostring(pos.x) .. "," .. tostring(pos.y)
end
local function pos_to_gps_string(pos)
return '[gps=' .. string.format('%.1f', pos.x) .. ',' .. string.format('%.1f', pos.y) .. ']'
return "[gps=" .. string.format("%.1f", pos.x) .. "," .. string.format("%.1f", pos.y) .. "]"
end
--- Print a message to all players who match the value of admin
@@ -35,107 +35,107 @@ local function print_to_players(admin, message)
end
Event.on_init(function()
game.write_file(filepath, "\n", false, 0) -- write data
game.write_file(filepath, "\n", false, 0) -- write data
end)
if config.decon_area then
Event.add(defines.events.on_player_deconstructed_area, function(e)
if e.alt then
return
end
Event.add(defines.events.on_player_deconstructed_area, function(e)
if e.alt then
return
end
local player = game.get_player(e.player_index)
local player = game.get_player(e.player_index)
if Roles.player_has_flag(player, 'deconlog-bypass') then
return
end
if Roles.player_has_flag(player, "deconlog-bypass") then
return
end
local items = e.surface.find_entities_filtered{area=e.area, force=player.force}
local items = e.surface.find_entities_filtered{ area = e.area, force = player.force }
if #items > 250 then
print_to_players(true, {'deconlog.decon', player.name, e.surface.name, pos_to_gps_string(e.area.left_top), pos_to_gps_string(e.area.right_bottom), format_number(#items)})
end
if #items > 250 then
print_to_players(true, { "deconlog.decon", player.name, e.surface.name, pos_to_gps_string(e.area.left_top), pos_to_gps_string(e.area.right_bottom), format_number(#items) })
end
add_log(get_secs() .. ',' .. player.name .. ',decon_area,' .. e.surface.name .. ',' .. pos_to_string(e.area.left_top) .. ',' .. pos_to_string(e.area.right_bottom))
end)
add_log(get_secs() .. "," .. player.name .. ",decon_area," .. e.surface.name .. "," .. pos_to_string(e.area.left_top) .. "," .. pos_to_string(e.area.right_bottom))
end)
end
if config.built_entity then
Event.add(defines.events.on_built_entity, function (e)
if not e.player_index then return end
local player = game.get_player(e.player_index)
if Roles.player_has_flag(player, "deconlog-bypass") then
return
end
local ent = e.created_entity
add_log(get_secs() .. "," .. player.name .. ",built_entity," .. ent.name .. "," .. pos_to_string(ent.position) .. "," .. tostring(ent.direction) .. "," .. tostring(ent.orientation))
end)
Event.add(defines.events.on_built_entity, function(e)
if not e.player_index then return end
local player = game.get_player(e.player_index)
if Roles.player_has_flag(player, "deconlog-bypass") then
return
end
local ent = e.created_entity
add_log(get_secs() .. "," .. player.name .. ",built_entity," .. ent.name .. "," .. pos_to_string(ent.position) .. "," .. tostring(ent.direction) .. "," .. tostring(ent.orientation))
end)
end
if config.mined_entity then
Event.add(defines.events.on_player_mined_entity, function (e)
local player = game.get_player(e.player_index)
if Roles.player_has_flag(player, "deconlog-bypass") then
return
end
local ent = e.entity
add_log(get_secs() .. "," .. player.name .. ",mined_entity," .. ent.name .. "," .. pos_to_string(ent.position) .. "," .. tostring(ent.direction) .. "," .. tostring(ent.orientation))
end)
Event.add(defines.events.on_player_mined_entity, function(e)
local player = game.get_player(e.player_index)
if Roles.player_has_flag(player, "deconlog-bypass") then
return
end
local ent = e.entity
add_log(get_secs() .. "," .. player.name .. ",mined_entity," .. ent.name .. "," .. pos_to_string(ent.position) .. "," .. tostring(ent.direction) .. "," .. tostring(ent.orientation))
end)
end
if config.fired_rocket then
Event.add(defines.events.on_player_ammo_inventory_changed, function (e)
local player = game.get_player(e.player_index)
if Roles.player_has_flag(player, "deconlog-bypass") then
return
end
local ammo_inv = player.get_inventory(defines.inventory.character_ammo)
local item = ammo_inv[player.character.selected_gun_index]
if not item or not item.valid or not item.valid_for_read then
return
end
if item.name == "rocket" then
add_log(get_secs() .. "," .. player.name .. ",shot-rocket," .. pos_to_string(player.position) .. "," .. pos_to_string(player.shooting_state.position))
end
end)
Event.add(defines.events.on_player_ammo_inventory_changed, function(e)
local player = game.get_player(e.player_index)
if Roles.player_has_flag(player, "deconlog-bypass") then
return
end
local ammo_inv = player.get_inventory(defines.inventory.character_ammo)
local item = ammo_inv[player.character.selected_gun_index]
if not item or not item.valid or not item.valid_for_read then
return
end
if item.name == "rocket" then
add_log(get_secs() .. "," .. player.name .. ",shot-rocket," .. pos_to_string(player.position) .. "," .. pos_to_string(player.shooting_state.position))
end
end)
end
if config.fired_explosive_rocket then
Event.add(defines.events.on_player_ammo_inventory_changed, function (e)
local player = game.get_player(e.player_index)
Event.add(defines.events.on_player_ammo_inventory_changed, function(e)
local player = game.get_player(e.player_index)
if Roles.player_has_flag(player, "deconlog-bypass") then
return
end
local ammo_inv = player.get_inventory(defines.inventory.character_ammo)
local item = ammo_inv[player.character.selected_gun_index]
if Roles.player_has_flag(player, "deconlog-bypass") then
return
end
local ammo_inv = player.get_inventory(defines.inventory.character_ammo)
local item = ammo_inv[player.character.selected_gun_index]
if not item or not item.valid or not item.valid_for_read then
return
end
if item.name == "explosive-rocket" then
add_log(get_secs() .. "," .. player.name .. ",shot-explosive-rocket," .. pos_to_string(player.position) .. "," .. pos_to_string(player.shooting_state.position))
end
end)
if not item or not item.valid or not item.valid_for_read then
return
end
if item.name == "explosive-rocket" then
add_log(get_secs() .. "," .. player.name .. ",shot-explosive-rocket," .. pos_to_string(player.position) .. "," .. pos_to_string(player.shooting_state.position))
end
end)
end
if config.fired_nuke then
Event.add(defines.events.on_player_ammo_inventory_changed, function (e)
local player = game.get_player(e.player_index)
Event.add(defines.events.on_player_ammo_inventory_changed, function(e)
local player = game.get_player(e.player_index)
if Roles.player_has_flag(player, "deconlog-bypass") then
return
end
if Roles.player_has_flag(player, "deconlog-bypass") then
return
end
local ammo_inv = player.get_inventory(defines.inventory.character_ammo)
local item = ammo_inv[player.character.selected_gun_index]
local ammo_inv = player.get_inventory(defines.inventory.character_ammo)
local item = ammo_inv[player.character.selected_gun_index]
if not item or not item.valid or not item.valid_for_read then
return
end
if not item or not item.valid or not item.valid_for_read then
return
end
if item.name == "atomic-bomb" then
add_log(get_secs() .. "," .. player.name .. ",shot-nuke," .. pos_to_string(player.position) .. "," .. pos_to_string(player.shooting_state.position))
end
end)
if item.name == "atomic-bomb" then
add_log(get_secs() .. "," .. player.name .. ",shot-nuke," .. pos_to_string(player.position) .. "," .. pos_to_string(player.shooting_state.position))
end
end)
end

View File

@@ -6,7 +6,7 @@ local Colors = require("modules/exp_util/include/color")
local write_json, format_time = _C.write_json, _C.format_time --- @dep expcore.common
local config = require("modules.exp_legacy.config.discord_alerts") --- @dep config.discord_alerts
local playtime_format = {hours = true, minutes = true, short = true, string = true}
local playtime_format = { hours = true, minutes = true, short = true, string = true }
local function append_playtime(player_name)
if not config.show_playtime then
@@ -19,7 +19,7 @@ local function append_playtime(player_name)
return player_name
end
return player.name ..' (' .. format_time(player.online_time, playtime_format) .. ')'
return player.name .. " (" .. format_time(player.online_time, playtime_format) .. ")"
end
local function get_player_name(event)
@@ -28,27 +28,27 @@ local function get_player_name(event)
end
local function to_hex(color)
local hex_digits = '0123456789ABCDEF'
local hex_digits = "0123456789ABCDEF"
local function hex(bit)
local major, minor = math.modf(bit/16)
major, minor = major+1, minor*16+1
local major, minor = math.modf(bit / 16)
major, minor = major + 1, minor * 16 + 1
return hex_digits:sub(major, major) .. hex_digits:sub(minor, minor)
end
return '0x' .. hex(color.r) .. hex(color.g) .. hex(color.b)
return "0x" .. hex(color.r) .. hex(color.g) .. hex(color.b)
end
local function emit_event(args)
local title = args.title or ''
local color = args.color or '0x0'
local description = args.description or ''
local title = args.title or ""
local color = args.color or "0x0"
local description = args.description or ""
if type(color) == 'table' then
if type(color) == "table" then
color = to_hex(color)
end
local tick = args.tick or game.tick
local tick_formatted = format_time(tick, {days = false, hours = true, minutes = true, short = true, string = true})
local tick_formatted = format_time(tick, { days = false, hours = true, minutes = true, short = true, string = true })
local players_online = 0
local admins_online = 0
@@ -61,22 +61,22 @@ local function emit_event(args)
end
end
local done = {title=true, color=true, description=true}
local fields = {{
name='Server Details',
value=string.format('Server: ${serverName} Time: %s\nTotal: %d Online: %d Admins: %d', tick_formatted, #game.players, players_online, admins_online)
}}
local done = { title = true, color = true, description = true }
local fields = { {
name = "Server Details",
value = string.format("Server: ${serverName} Time: %s\nTotal: %d Online: %d Admins: %d", tick_formatted, #game.players, players_online, admins_online),
} }
for key, value in pairs(args) do
if not done[key] then
done[key] = true
local field = {
name=key,
value=value,
inline=false
name = key,
value = value,
inline = false,
}
local new_value, inline = value:gsub('<inline>', '', 1)
local new_value, inline = value:gsub("<inline>", "", 1)
if inline > 0 then
field.value = new_value
field.inline = true
@@ -86,11 +86,11 @@ local function emit_event(args)
end
end
write_json('ext/discord.out',{
title=title,
description=description,
color=color,
fields=fields
write_json("ext/discord.out", {
title = title,
description = description,
color = color,
fields = fields,
})
end
@@ -100,12 +100,12 @@ if config.entity_protection then
Event.add(EntityProtection.events.on_repeat_violation, function(event)
local player_name = get_player_name(event)
emit_event{
title='Entity Protection',
description='A player removed protected entities',
color=Colors.yellow,
['Player']='<inline>' .. append_playtime(player_name),
['Entity']='<inline>' .. event.entity.name,
['Location']='X ' .. event.entity.position.x .. ' Y ' .. event.entity.position.y
title = "Entity Protection",
description = "A player removed protected entities",
color = Colors.yellow,
["Player"] = "<inline>" .. append_playtime(player_name),
["Entity"] = "<inline>" .. event.entity.name,
["Location"] = "X " .. event.entity.position.x .. " Y " .. event.entity.position.y,
}
end)
end
@@ -116,25 +116,25 @@ if config.player_reports then
Event.add(Reports.events.on_player_reported, function(event)
local player_name, by_player_name = get_player_name(event)
emit_event{
title='Report',
description='A player was reported',
color=Colors.yellow,
['Player']='<inline>' .. append_playtime(player_name),
['By']='<inline>' .. append_playtime(by_player_name),
['Report Count']='<inline>' .. Reports.count_reports(player_name),
['Reason']=event.reason
title = "Report",
description = "A player was reported",
color = Colors.yellow,
["Player"] = "<inline>" .. append_playtime(player_name),
["By"] = "<inline>" .. append_playtime(by_player_name),
["Report Count"] = "<inline>" .. Reports.count_reports(player_name),
["Reason"] = event.reason,
}
end)
Event.add(Reports.events.on_report_removed, function(event)
if event.batch ~= 1 then return end
local player_name = get_player_name(event)
emit_event{
title='Reports Removed',
description='A player has a report removed',
color=Colors.green,
['Player']='<inline>' .. player_name,
['By']='<inline>' .. event.removed_by_name,
['Report Count']='<inline>' .. event.batch_count
title = "Reports Removed",
description = "A player has a report removed",
color = Colors.green,
["Player"] = "<inline>" .. player_name,
["By"] = "<inline>" .. event.removed_by_name,
["Report Count"] = "<inline>" .. event.batch_count,
}
end)
end
@@ -146,25 +146,25 @@ if config.player_warnings then
local player_name, by_player_name = get_player_name(event)
local player = game.get_player(player_name)
emit_event{
title='Warning',
description='A player has been given a warning',
color=Colors.yellow,
['Player']='<inline>' .. player_name,
['By']='<inline>' .. by_player_name,
['Warning Count']='<inline>' .. Warnings.count_warnings(player),
['Reason']=event.reason
title = "Warning",
description = "A player has been given a warning",
color = Colors.yellow,
["Player"] = "<inline>" .. player_name,
["By"] = "<inline>" .. by_player_name,
["Warning Count"] = "<inline>" .. Warnings.count_warnings(player),
["Reason"] = event.reason,
}
end)
Event.add(Warnings.events.on_warning_removed, function(event)
if event.batch ~= 1 then return end
local player_name = get_player_name(event)
emit_event{
title='Warnings Removed',
description='A player has a warning removed',
color=Colors.green,
['Player']='<inline>' .. player_name,
['By']='<inline>' .. event.removed_by_name,
['Warning Count']='<inline>' .. event.batch_count
title = "Warnings Removed",
description = "A player has a warning removed",
color = Colors.green,
["Player"] = "<inline>" .. player_name,
["By"] = "<inline>" .. event.removed_by_name,
["Warning Count"] = "<inline>" .. event.batch_count,
}
end)
end
@@ -175,22 +175,22 @@ if config.player_jail then
Event.add(Jail.events.on_player_jailed, function(event)
local player_name, by_player_name = get_player_name(event)
emit_event{
title='Jail',
description='A player has been jailed',
color=Colors.yellow,
['Player']='<inline>' .. player_name,
['By']='<inline>' .. by_player_name,
['Reason']=event.reason
title = "Jail",
description = "A player has been jailed",
color = Colors.yellow,
["Player"] = "<inline>" .. player_name,
["By"] = "<inline>" .. by_player_name,
["Reason"] = event.reason,
}
end)
Event.add(Jail.events.on_player_unjailed, function(event)
local player_name, by_player_name = get_player_name(event)
emit_event{
title='Unjail',
description='A player has been unjailed',
color=Colors.green,
['Player']='<inline>' .. player_name,
['By']='<inline>' .. by_player_name
title = "Unjail",
description = "A player has been unjailed",
color = Colors.green,
["Player"] = "<inline>" .. player_name,
["By"] = "<inline>" .. by_player_name,
}
end)
end
@@ -201,12 +201,12 @@ if config.player_bans then
if event.by_player then
local by_player = game.players[event.by_player]
emit_event{
title='Banned',
description='A player has been banned',
color=Colors.red,
['Player']='<inline>' .. event.player_name,
['By']='<inline>' .. by_player.name,
['Reason']=event.reason
title = "Banned",
description = "A player has been banned",
color = Colors.red,
["Player"] = "<inline>" .. event.player_name,
["By"] = "<inline>" .. by_player.name,
["Reason"] = event.reason,
}
end
end)
@@ -214,11 +214,11 @@ if config.player_bans then
if event.by_player then
local by_player = game.players[event.by_player]
emit_event{
title='Un-Banned',
description='A player has been un-banned',
color=Colors.green,
['Player']='<inline>' .. event.player_name,
['By']='<inline>' .. by_player.name
title = "Un-Banned",
description = "A player has been un-banned",
color = Colors.green,
["Player"] = "<inline>" .. event.player_name,
["By"] = "<inline>" .. by_player.name,
}
end
end)
@@ -229,19 +229,19 @@ if config.player_mutes then
Event.add(defines.events.on_player_muted, function(event)
local player_name = get_player_name(event)
emit_event{
title='Muted',
description='A player has been muted',
color=Colors.yellow,
['Player']='<inline>' .. player_name
title = "Muted",
description = "A player has been muted",
color = Colors.yellow,
["Player"] = "<inline>" .. player_name,
}
end)
Event.add(defines.events.on_player_unmuted, function(event)
local player_name = get_player_name(event)
emit_event{
title='Un-Muted',
description='A player has been un-muted',
color=Colors.green,
['Player']='<inline>' .. player_name
title = "Un-Muted",
description = "A player has been un-muted",
color = Colors.green,
["Player"] = "<inline>" .. player_name,
}
end)
end
@@ -253,12 +253,12 @@ if config.player_kicks then
local player_name = get_player_name(event)
local by_player = game.players[event.by_player]
emit_event{
title='Kick',
description='A player has been kicked',
color=Colors.orange,
['Player']='<inline>' .. player_name,
['By']='<inline>' .. by_player.name,
['Reason']=event.reason
title = "Kick",
description = "A player has been kicked",
color = Colors.orange,
["Player"] = "<inline>" .. player_name,
["By"] = "<inline>" .. by_player.name,
["Reason"] = event.reason,
}
end
end)
@@ -269,19 +269,19 @@ if config.player_promotes then
Event.add(defines.events.on_player_promoted, function(event)
local player_name = get_player_name(event)
emit_event{
title='Promote',
description='A player has been promoted',
color=Colors.green,
['Player']='<inline>' .. player_name
title = "Promote",
description = "A player has been promoted",
color = Colors.green,
["Player"] = "<inline>" .. player_name,
}
end)
Event.add(defines.events.on_player_demoted, function(event)
local player_name = get_player_name(event)
emit_event{
title='Demote',
description='A player has been demoted',
color=Colors.yellow,
['Player']='<inline>' .. player_name
title = "Demote",
description = "A player has been demoted",
color = Colors.yellow,
["Player"] = "<inline>" .. player_name,
}
end)
end
@@ -292,11 +292,11 @@ Event.add(defines.events.on_console_command, function(event)
local player_name = get_player_name(event)
if config[event.command] then
emit_event{
title=event.command:gsub('^%l', string.upper),
description='/' .. event.command .. ' was used',
color=Colors.grey,
['By']='<inline>' .. player_name,
['Details'] = event.parameters ~= '' and event.parameters or nil
title = event.command:gsub("^%l", string.upper),
description = "/" .. event.command .. " was used",
color = Colors.grey,
["By"] = "<inline>" .. player_name,
["Details"] = event.parameters ~= "" and event.parameters or nil,
}
end
end

View File

@@ -5,15 +5,15 @@ local Event = require("modules/exp_legacy/utils/event") --- @dep utils.event
-- Clear the file on startup to minimize its size
Event.on_init(function()
game.write_file("fagc-actions.txt", "", false, 0)
game.write_file("fagc-actions.txt", "", false, 0)
end)
Event.add(defines.events.on_player_banned, function(e)
local text = "ban;" .. e.player_name .. ";" .. (e.by_player or "") .. ";" .. (e.reason or "") .. "\n"
game.write_file("fagc-actions.txt", text, true, 0)
local text = "ban;" .. e.player_name .. ";" .. (e.by_player or "") .. ";" .. (e.reason or "") .. "\n"
game.write_file("fagc-actions.txt", text, true, 0)
end)
Event.add(defines.events.on_player_unbanned, function(e)
local text = "unban;" .. e.player_name .. ";" .. (e.by_player or "") .. ";" .. (e.reason or "") .. "\n"
game.write_file("fagc-actions.txt", text, true, 0)
local text = "unban;" .. e.player_name .. ";" .. (e.by_player or "") .. ";" .. (e.reason or "") .. "\n"
game.write_file("fagc-actions.txt", text, true, 0)
end)

View File

@@ -1,23 +1,23 @@
local Event = require("modules/exp_legacy/utils/event")
local controllers_with_inventory = {
[defines.controllers.character] = true,
[defines.controllers.god] = true,
[defines.controllers.editor] = true,
[defines.controllers.character] = true,
[defines.controllers.god] = true,
[defines.controllers.editor] = true,
}
Event.add(defines.events.on_player_mined_entity, function(event)
if (not event.entity.valid) or (event.entity.type ~= 'inserter') or event.entity.drop_target then
if (not event.entity.valid) or (event.entity.type ~= "inserter") or event.entity.drop_target then
return
end
local item_entity = event.entity.surface.find_entity('item-on-ground', event.entity.drop_position)
local item_entity = event.entity.surface.find_entity("item-on-ground", event.entity.drop_position)
if item_entity then
local player = game.get_player(event.player_index)
if item_entity then
local player = game.get_player(event.player_index)
if controllers_with_inventory[player.controller_type] then
player.mine_entity(item_entity)
end
end
if controllers_with_inventory[player.controller_type] then
player.mine_entity(item_entity)
end
end
end)

View File

@@ -8,52 +8,52 @@ local Event = require("modules/exp_legacy/utils/event") --- @dep utils.event
local config = require("modules.exp_legacy.config.lawnmower") --- @dep config.lawnmower
require("modules.exp_legacy.config.expcore.command_general_parse")
Commands.new_command('lawnmower', {'expcom-lawnmower.description'}, 'Clean up biter corpse, decoratives and nuclear hole')
:add_param('range', false, 'integer-range', 1, 200)
:register(function(player, range)
local tile_to_do = {}
Commands.new_command("lawnmower", "Clean up biter corpse, decoratives and nuclear hole")
:add_param("range", false, "integer-range", 1, 200)
:register(function(player, range)
local tile_to_do = {}
player.surface.destroy_decoratives({position=player.position, radius=range})
player.surface.destroy_decoratives{ position = player.position, radius = range }
local entities = player.surface.find_entities_filtered{position=player.position, radius=range, type='corpse'}
local entities = player.surface.find_entities_filtered{ position = player.position, radius = range, type = "corpse" }
for _, entity in pairs(entities) do
if (entity.name ~= 'transport-caution-corpse' and entity.name ~= 'invisible-transport-caution-corpse') then
entity.destroy()
end
end
for _, entity in pairs(entities) do
if (entity.name ~= "transport-caution-corpse" and entity.name ~= "invisible-transport-caution-corpse") then
entity.destroy()
end
end
local tiles = player.surface.find_tiles_filtered{position=player.position, radius=range, name={'nuclear-ground'}}
local tiles = player.surface.find_tiles_filtered{ position = player.position, radius = range, name = { "nuclear-ground" } }
for _, tile in pairs(tiles) do
table.insert(tile_to_do, {name='grass-1', position=tile.position})
end
for _, tile in pairs(tiles) do
table.insert(tile_to_do, { name = "grass-1", position = tile.position })
end
player.surface.set_tiles(tile_to_do)
player.surface.set_tiles(tile_to_do)
return Commands.success
end)
return Commands.success
end)
local function destroy_decoratives(entity)
if entity.type ~= 'entity-ghost' and entity.type ~= 'tile-ghost' and entity.prototype.selectable_in_game then
entity.surface.destroy_decoratives{area=entity.selection_box}
if entity.type ~= "entity-ghost" and entity.type ~= "tile-ghost" and entity.prototype.selectable_in_game then
entity.surface.destroy_decoratives{ area = entity.selection_box }
end
end
if config.destroy_decoratives then
Event.add(defines.events.on_built_entity, function(event)
destroy_decoratives(event.created_entity)
end)
Event.add(defines.events.on_built_entity, function(event)
destroy_decoratives(event.created_entity)
end)
Event.add(defines.events.on_robot_built_entity, function(event)
destroy_decoratives(event.created_entity)
end)
Event.add(defines.events.on_robot_built_entity, function(event)
destroy_decoratives(event.created_entity)
end)
Event.add(defines.events.script_raised_built, function(event)
destroy_decoratives(event.entity)
end)
Event.add(defines.events.script_raised_built, function(event)
destroy_decoratives(event.entity)
end)
Event.add(defines.events.script_raised_revive, function(event)
destroy_decoratives(event.entity)
end)
Event.add(defines.events.script_raised_revive, function(event)
destroy_decoratives(event.entity)
end)
end

View File

@@ -7,17 +7,14 @@ local config = require("modules.exp_legacy.config.logging") --- @dep config.logg
local config_res = require("modules.exp_legacy.config.research") --- @dep config.research
local function add_log(data)
game.write_file(config.file_name, data, true, 0)
game.write_file(config.file_name, '\n', true, 0)
game.write_file(config.file_name, data, true, 0)
game.write_file(config.file_name, "\n", true, 0)
end
Event.add(defines.events.on_rocket_launched, function(event)
if event and event.rocket and event.rocket.force and event.rocket.force.rockets_launched then
if event.rocket.force.rockets_launched >= config.rocket_launch_display_rate and event.rocket.force.rockets_launched % config.rocket_launch_display_rate == 0 then
add_log('[ROCKET] ' .. event.rocket.force.rockets_launched .. ' rockets launched')
elseif config.rocket_launch_display[event.rocket.force.rockets_launched] then
add_log('[ROCKET] ' .. event.rocket.force.rockets_launched .. ' rockets launched')
if config.rocket_launch_display[event.rocket.force.rockets_launched] then
add_log("[ROCKET] " .. event.rocket.force.rockets_launched .. " rockets launched")
end
end
end)
@@ -25,15 +22,13 @@ end)
Event.add(defines.events.on_pre_player_died, function(event)
if event and event.player_index then
if event.cause then
if event.cause.type and event.cause.type == 'character' and event.cause.player and event.cause.player.index then
add_log('[DEATH] ' .. game.players[event.player_index].name .. ' died because of ' .. (game.players[event.cause.player.index].name or 'unknown reason'))
if event.cause.type and event.cause.type == "character" and event.cause.player and event.cause.player.index then
add_log("[DEATH] " .. game.players[event.player_index].name .. " died because of " .. (game.players[event.cause.player.index].name or "unknown reason"))
else
add_log('[DEATH] ' .. game.players[event.player_index].name .. ' died because of ' .. (event.cause.name or 'unknown reason'))
add_log("[DEATH] " .. game.players[event.player_index].name .. " died because of " .. (event.cause.name or "unknown reason"))
end
else
add_log('[DEATH] ' .. game.players[event.player_index].name .. ' died because of unknown reason')
add_log("[DEATH] " .. game.players[event.player_index].name .. " died because of unknown reason")
end
end
end)
@@ -45,27 +40,25 @@ Event.add(defines.events.on_research_finished, function(event)
end
if (event.research.level and config_res.inf_res[event.research.name]) and (event.research.level >= config_res.inf_res[event.research.name]) then
add_log({'logging.add-l', event.research.prototype.localised_name, event.research.level - 1})
add_log{ "logging.add-l", event.research.prototype.localised_name, event.research.level - 1 }
else
add_log({'logging.add-n', event.research.prototype.localised_name})
add_log{ "logging.add-n", event.research.prototype.localised_name }
end
end
end)
Event.add(defines.events.on_player_joined_game, function(event)
if event and event.player_index then
add_log('[JOIN] ' .. game.players[event.player_index].name .. ' joined the game')
add_log("[JOIN] " .. game.players[event.player_index].name .. " joined the game")
end
end)
Event.add(defines.events.on_player_left_game, function(event)
if event and event.player_index then
if event.reason then
add_log('[LEAVE] ' .. game.players[event.player_index].name .. config.disconnect_reason[event.reason])
add_log("[LEAVE] " .. game.players[event.player_index].name .. config.disconnect_reason[event.reason])
else
add_log('[LEAVE] ' .. game.players[event.player_index].name .. config.disconnect_reason[defines.disconnect_reason.quit])
add_log("[LEAVE] " .. game.players[event.player_index].name .. config.disconnect_reason[defines.disconnect_reason.quit])
end
end
end)

View File

@@ -12,9 +12,8 @@ miner_data.queue = {}
local function drop_target(entity)
if entity.drop_target then
return entity.drop_target
else
local entities = entity.surface.find_entities_filtered{position=entity.drop_position}
local entities = entity.surface.find_entities_filtered{ position = entity.drop_position }
if #entities > 0 then
return entities[1]
@@ -43,7 +42,7 @@ local function check_entity(entity)
return true
end
if entity.has_flag('not-deconstructable') then
if entity.has_flag("not-deconstructable") then
-- if it can deconstruct
return true
end
@@ -58,13 +57,13 @@ local function chest_check(entity)
return
end
if target.type ~= 'logistic-container' and target.type ~= 'container' then
if target.type ~= "logistic-container" and target.type ~= "container" then
-- not a chest
return
end
local radius = 2
local entities = target.surface.find_entities_filtered{area={{target.position.x - radius, target.position.y - radius}, {target.position.x + radius, target.position.y + radius}}, type={'mining-drill', 'inserter'}}
local entities = target.surface.find_entities_filtered{ area = { { target.position.x - radius, target.position.y - radius }, { target.position.x + radius, target.position.y + radius } }, type = { "mining-drill", "inserter" } }
for _, e in pairs(entities) do
if drop_target(e) == target then
@@ -75,7 +74,7 @@ local function chest_check(entity)
end
if check_entity(target) then
table.insert(miner_data.queue, {t=game.tick + 10, e=target})
table.insert(miner_data.queue, { t = game.tick + 10, e = target })
end
end
@@ -85,7 +84,7 @@ local function miner_check(entity)
local ef = entity.force
local er = entity.prototype.mining_drill_radius
for _, r in pairs(entity.surface.find_entities_filtered{area={{x=ep.x - er, y=ep.y - er}, {x=ep.x + er, y=ep.y + er}}, type='resource'}) do
for _, r in pairs(entity.surface.find_entities_filtered{ area = { { x = ep.x - er, y = ep.y - er }, { x = ep.x + er, y = ep.y + er } }, type = "resource" }) do
if r.amount > 0 then
return
end
@@ -103,35 +102,32 @@ local function miner_check(entity)
if config.fluid and entity.fluidbox and #entity.fluidbox > 0 then
-- if require fluid to mine
table.insert(pipe_build, {x=0, y=0})
table.insert(pipe_build, { x = 0, y = 0 })
local half = math.floor(entity.get_radius())
local r = 1 + er
local entities = es.find_entities_filtered{area={{ep.x - r, ep.y - r}, {ep.x + r, ep.y + r}}, type={'mining-drill', 'pipe', 'pipe-to-ground'}}
local entities_t = es.find_entities_filtered{area={{ep.x - r, ep.y - r}, {ep.x + r, ep.y + r}}, ghost_type={'pipe', 'pipe-to-ground'}}
local entities = es.find_entities_filtered{ area = { { ep.x - r, ep.y - r }, { ep.x + r, ep.y + r } }, type = { "mining-drill", "pipe", "pipe-to-ground" } }
local entities_t = es.find_entities_filtered{ area = { { ep.x - r, ep.y - r }, { ep.x + r, ep.y + r } }, ghost_type = { "pipe", "pipe-to-ground" } }
table.array_insert(entities, entities_t)
for _, e in pairs(entities) do
if (e.position.x > ep.x) and (e.position.y == ep.y) then
for h=1, half do
table.insert(pipe_build, {x=h, y=0})
for h = 1, half do
table.insert(pipe_build, { x = h, y = 0 })
end
elseif (e.position.x < ep.x) and (e.position.y == ep.y) then
for h=1, half do
table.insert(pipe_build, {x=-h, y=0})
for h = 1, half do
table.insert(pipe_build, { x = -h, y = 0 })
end
elseif (e.position.x == ep.x) and (e.position.y > ep.y) then
for h=1, half do
table.insert(pipe_build, {x=0, y=h})
for h = 1, half do
table.insert(pipe_build, { x = 0, y = h })
end
elseif (e.position.x == ep.x) and (e.position.y < ep.y) then
for h=1, half do
table.insert(pipe_build, {x=0, y=-h})
for h = 1, half do
table.insert(pipe_build, { x = 0, y = -h })
end
end
end
@@ -141,10 +137,10 @@ local function miner_check(entity)
chest_check(entity)
end
table.insert(miner_data.queue, {t=game.tick + 5, e=entity})
table.insert(miner_data.queue, { t = game.tick + 5, e = entity })
for _, pos in ipairs(pipe_build) do
es.create_entity{name='entity-ghost', position={x=ep.x + pos.x, y=ep.y + pos.y}, force=ef, inner_name='pipe', raise_built=true}
es.create_entity{ name = "entity-ghost", position = { x = ep.x + pos.x, y = ep.y + pos.y }, force = ef, inner_name = "pipe", raise_built = true }
end
end
@@ -153,7 +149,7 @@ Event.add(defines.events.on_resource_depleted, function(event)
return
end
local entities = event.entity.surface.find_entities_filtered{area={{event.entity.position.x - 1, event.entity.position.y - 1}, {event.entity.position.x + 1, event.entity.position.y + 1}}, type='mining-drill'}
local entities = event.entity.surface.find_entities_filtered{ area = { { event.entity.position.x - 1, event.entity.position.y - 1 }, { event.entity.position.x + 1, event.entity.position.y + 1 } }, type = "mining-drill" }
if #entities == 0 then
return
@@ -171,7 +167,6 @@ Event.on_nth_tick(10, function(event)
if not q.e or not q.e.valid then
table.remove(miner_data.queue, k)
break
elseif event.tick >= q.t then
q.e.order_deconstruction(q.e.force)
table.remove(miner_data.queue, k)

View File

@@ -1,46 +1,44 @@
--- Disable new players from having certain items in their inventory, most commonly nukes
-- @addon Nukeprotect
local Event = require("modules/exp_legacy/utils/event") --- @dep utils.event
local Roles = require("modules.exp_legacy.expcore.roles") --- @dep expcore.roles
local config = require("modules.exp_legacy.config.nukeprotect") --- @dep config.nukeprotect
local Event = require("modules/exp_legacy/utils/event") --- @dep utils.event
local Roles = require("modules.exp_legacy.expcore.roles") --- @dep expcore.roles
local config = require("modules.exp_legacy.config.nukeprotect") --- @dep config.nukeprotect
local move_items_stack = _C.move_items_stack --- @dep expcore.common
local function check_items(player, type)
-- if the player has perms to be ignored, then they should be
if config.ignore_permisison and Roles.player_allowed(player, config.ignore_permisison) then return end
-- if the players
if config.ignore_admins and player.admin then return end
-- if the player has perms to be ignored, then they should be
if config.ignore_permisison and Roles.player_allowed(player, config.ignore_permisison) then return end
-- if the players
if config.ignore_admins and player.admin then return end
local inventory = player.get_inventory(type)
for i = 1, #inventory do
local item = inventory[i]
if item.valid and item.valid_for_read and config[tostring(type)][item.name] then
player.print({ "nukeprotect.found", { "item-name." .. item.name } })
-- insert the items into the table so all items are transferred at once
move_items_stack({ item })
end
end
local inventory = player.get_inventory(type)
for i = 1, #inventory do
local item = inventory[i]
if item.valid and item.valid_for_read and config[tostring(type)][item.name] then
player.print{ "nukeprotect.found", { "item-name." .. item.name } }
-- insert the items into the table so all items are transferred at once
move_items_stack{ item }
end
end
end
for _, inventory in ipairs(config.inventories) do
if #inventory.items > 0 then
Event.add(inventory.event, function(event)
local player = game.get_player(event.player_index)
if player and player.valid then
check_items(player, inventory.inventory)
end
end)
end
if #inventory.items > 0 then
Event.add(inventory.event, function(event)
local player = game.get_player(event.player_index)
if player and player.valid then
check_items(player, inventory.inventory)
end
end)
end
end
if config.disable_nuke_research then
Event.add(defines.events.on_research_started, function(event)
local name = event.research.name
if config.disable_nuke_research_names[name] then
event.research.force.cancel_current_research()
end
end)
Event.add(defines.events.on_research_started, function(event)
local name = event.research.name
if config.disable_nuke_research_names[name] then
event.research.force.cancel_current_research()
end
end)
end

View File

@@ -8,9 +8,9 @@ local delay = config.update_delay * 3600 -- convert from minutes to ticks
Event.on_nth_tick(delay, function()
local surface = game.surfaces[1]
local true_max = surface.get_pollution(config.reference_point)
local max = true_max*config.max_scalar
local min = max*config.min_scalar
local max = true_max * config.max_scalar
local min = max * config.min_scalar
local settings = game.map_settings.pollution
settings.expected_max_per_chunk = max
settings.min_to_show_per_chunk = min
end)
end)

View File

@@ -1,9 +1,9 @@
--- When a player triggers protection multiple times they are automatically jailed
-- @addon protection-jail
local Event = require("modules/exp_legacy/utils/event") ---@dep utils.event
local Storage = require("modules/exp_util/storage") ---@dep utils.global
local Jail = require("modules.exp_legacy.modules.control.jail") ---@dep modules.control.jail
local Event = require("modules/exp_legacy/utils/event") --- @dep utils.event
local Storage = require("modules/exp_util/storage") --- @dep utils.global
local Jail = require("modules.exp_legacy.modules.control.jail") --- @dep modules.control.jail
local Protection = require("modules.exp_legacy.modules.control.protection") --- @dep modules.control.protection
local format_chat_player_name = _C.format_chat_player_name --- @dep expcore.common
@@ -30,11 +30,11 @@ Event.add(Protection.events.on_repeat_violation, function(event)
end
local player_name_color = format_chat_player_name(player)
Jail.jail_player(player, '<protection>', 'Removed too many protected entities, please wait for a moderator.')
game.print{'protection-jail.jail', player_name_color}
Jail.jail_player(player, "<protection>", "Removed too many protected entities, please wait for a moderator.")
game.print{ "protection-jail.jail", player_name_color }
end)
--- Clear the counter when they leave the game (stops a build up of data)
Event.add(defines.events.on_player_left_game, function(event)
repeat_count[event.player_index] = nil
end)
end)

View File

@@ -1,8 +1,8 @@
--- When a player is reported, the player is automatically jailed if the combined playtime of the reporters exceeds the reported player
-- @addon report-jail
local Event = require("modules/exp_legacy/utils/event") ---@dep utils.event
local Jail = require("modules.exp_legacy.modules.control.jail") ---@dep modules.control.jail
local Event = require("modules/exp_legacy/utils/event") --- @dep utils.event
local Jail = require("modules.exp_legacy.modules.control.jail") --- @dep modules.control.jail
local Reports = require("modules.exp_legacy.modules.control.reports") --- @dep modules.control.reports
local format_chat_player_name = _C.format_chat_player_name --- @dep expcore.common
@@ -22,7 +22,7 @@ Event.add(Reports.events.on_player_reported, function(event)
-- player less than 30 min
if (Reports.count_reports(player) > 1) and (total_playtime > math.max(player.online_time * 2, 108000)) then
local player_name_color = format_chat_player_name(player)
Jail.jail_player(player, '<reports>', 'Reported by too many players, please wait for a moderator.')
game.print{'report-jail.jail', player_name_color}
Jail.jail_player(player, "<reports>", "Reported by too many players, please wait for a moderator.")
game.print{ "report-jail.jail", player_name_color }
end
end)

View File

@@ -26,7 +26,7 @@ local function degrade(surface, position)
local tile_name = tile.name
local degrade_tile_name = config.degrade_order[tile_name]
if not degrade_tile_name then return end
surface.set_tiles{{name=degrade_tile_name, position=position}}
surface.set_tiles{ { name = degrade_tile_name, position = position } }
end
-- Same as degrade but will degrade all tiles that are under an entity
@@ -39,25 +39,26 @@ local function degrade_entity(entity)
local lt = box.left_top
local rb = box.right_bottom
for x = lt.x, rb.x do -- x loop
local px = position.x+x
local px = position.x + x
for y = lt.y, rb.y do -- y loop
local p = {x=px, y=position.y+y}
local p = { x = px, y = position.y + y }
local tile = surface.get_tile(p)
local tile_name = tile.name
local degrade_tile_name = config.degrade_order[tile_name]
if not degrade_tile_name then return end
table.insert(tiles, {name=degrade_tile_name, position=p})
table.insert(tiles, { name = degrade_tile_name, position = p })
end
end
surface.set_tiles(tiles)
end
-- Turns the strength of a tile into a probability (0 = impossible, 1 = certain)
local function get_probability(strength)
local v1 = strength/max_strength
local v1 = strength / max_strength
local dif = 1 - v1
local v2 = dif/2
return (1-v1+v2)/config.weakness_value
local v2 = dif / 2
return (1 - v1 + v2) / config.weakness_value
end
-- Gets the mean of the strengths around a tile to give the strength at that position
@@ -69,24 +70,25 @@ local function get_tile_strength(surface, position)
for x = -1, 1 do -- x loop
local px = position.x + x
for y = -1, 1 do -- y loop
local check_tile = surface.get_tile{x=px, y=position.y+y}
local check_tile = surface.get_tile{ x = px, y = position.y + y }
local check_tile_name = check_tile.name
local check_strength = config.strengths[check_tile_name] or 0
strength = strength + check_strength
end
end
return strength/9
return strength / 9
end
-- Same as get_tile_strength but returns to a in game text rather than as a value
local function debug_get_tile_strength(surface, position)
for x = -3, 3 do -- x loop
local px = position.x+x
local px = position.x + x
for y = -3, 3 do -- y loop
local p = {x=px, y=position.y+y}
local p = { x = px, y = position.y + y }
local strength = get_tile_strength(surface, p) or 0
local tile = surface.get_tile(p)
print_grid_value(get_probability(strength)*config.weakness_value, surface, tile.position)
print_grid_value(get_probability(strength) * config.weakness_value, surface, tile.position)
end
end
end
@@ -113,7 +115,7 @@ Event.add(defines.events.on_built_entity, function(event)
local position = entity.position
local strength = get_tile_strength(surface, position)
if not strength then return end
if get_probability(strength)*config.weakness_value > math.random() then
if get_probability(strength) * config.weakness_value > math.random() then
degrade_entity(entity)
end
end)
@@ -125,7 +127,7 @@ Event.add(defines.events.on_robot_built_entity, function(event)
local position = entity.position
local strength = get_tile_strength(surface, position)
if not strength then return end
if get_probability(strength)*config.weakness_value > math.random() then
if get_probability(strength) * config.weakness_value > math.random() then
degrade_entity(entity)
end
end)
@@ -135,4 +137,4 @@ return function(player_name, state)
local player = game.players[player_name]
clear_flying_text(player.surface)
debug_players[player_name] = state
end
end

View File

@@ -12,7 +12,7 @@ end)
-- Apply an offset to a LuaPosition
local function apply_offset(position, offset)
return {x=position.x + (offset.x or offset[1]), y=position.y + (offset.y or offset[2])}
return { x = position.x + (offset.x or offset[1]), y = position.y + (offset.y or offset[2]) }
end
-- Apply the offset to the turrets default position
@@ -22,16 +22,16 @@ end
-- Get or create the force used for entities in spawn
local function get_spawn_force()
local force = game.forces['spawn']
local force = game.forces["spawn"]
if force and force.valid then
return force
end
force = game.create_force('spawn')
force.set_cease_fire('player', true)
force = game.create_force("spawn")
force.set_cease_fire("player", true)
-- force.set_friend('player', true)
game.forces['player'].set_cease_fire('spawn', true)
game.forces["player"].set_cease_fire("spawn", true)
-- game.forces['player'].set_friend('spawn', true)
return force
@@ -57,18 +57,18 @@ local function spawn_turrets()
for _, turret_pos in pairs(turrets) do
local surface = game.surfaces[turret_pos.surface]
local pos = turret_pos.position
local turret = surface.find_entity('gun-turret', pos)
local turret = surface.find_entity("gun-turret", pos)
-- Makes a new turret if it is not found
if not turret or not turret.valid then
turret = surface.create_entity{name='gun-turret', position=pos, force='spawn'}
turret = surface.create_entity{ name = "gun-turret", position = pos, force = "spawn" }
protect_entity(turret)
end
-- Adds ammo to the turret
local inv = turret.get_inventory(defines.inventory.turret_ammo)
if inv.can_insert{name=config.turrets.ammo_type, count=10} then
inv.insert{name=config.turrets.ammo_type, count=10}
if inv.can_insert{ name = config.turrets.ammo_type, count = 10 } then
inv.insert{ name = config.turrets.ammo_type, count = 10 }
end
end
end
@@ -77,13 +77,13 @@ end
local function spawn_belts(surface, position)
position = apply_offset(position, config.afk_belts.offset)
local belt_type = config.afk_belts.belt_type
local belt_details = {{-0.5, -0.5, 2}, {0.5, -0.5, 4}, {-0.5, 0.5, 0}, {0.5, 0.5, 6}} -- x, y,dir
local belt_details = { { -0.5, -0.5, 2 }, { 0.5, -0.5, 4 }, { -0.5, 0.5, 0 }, { 0.5, 0.5, 6 } } -- x, y,dir
for _, belt_set in pairs(config.afk_belts.locations) do
local set_position = apply_offset(position, belt_set)
for _, belt in pairs(belt_details) do
local pos = apply_offset(set_position, belt)
local belt_entity = surface.create_entity{name=belt_type, position=pos, force='neutral', direction=belt[3]}
local belt_entity = surface.create_entity{ name = belt_type, position = pos, force = "neutral", direction = belt[3] }
if config.afk_belts.protected then
protect_entity(belt_entity)
@@ -99,7 +99,7 @@ local function spawn_pattern(surface, position)
local pattern_tile = config.pattern.pattern_tile
for _, tile in pairs(config.pattern.locations) do
table.insert(tiles_to_make, {name=pattern_tile, position=apply_offset(position, tile)})
table.insert(tiles_to_make, { name = pattern_tile, position = apply_offset(position, tile) })
end
surface.set_tiles(tiles_to_make)
@@ -111,8 +111,9 @@ local function spawn_water(surface, position)
local tiles_to_make = {}
local water_tile = config.water.water_tile
for _, tile in pairs(config.water.locations) do
table.insert(tiles_to_make, {name=water_tile, position=apply_offset(position, tile)})
table.insert(tiles_to_make, { name = water_tile, position = apply_offset(position, tile) })
end
surface.set_tiles(tiles_to_make)
end
@@ -120,8 +121,8 @@ end
local function spawn_entities(surface, position)
position = apply_offset(position, config.entities.offset)
for _, entity in pairs(config.entities.locations) do
local pos = apply_offset(position, {x=entity[2], y=entity[3]})
entity = surface.create_entity{name=entity[1], position=pos, force='neutral'}
local pos = apply_offset(position, { x = entity[2], y = entity[3] })
entity = surface.create_entity{ name = entity[1], position = pos, force = "neutral" }
if config.entities.protected then
protect_entity(entity)
@@ -135,48 +136,49 @@ end
local function spawn_area(surface, position)
local dr = config.spawn_area.deconstruction_radius
local tr = config.spawn_area.tile_radius
local tr2 = tr^2
local tr2 = tr ^ 2
local decon_tile = config.spawn_area.deconstruction_tile
local fr = config.spawn_area.landfill_radius
local fr2 = fr^2
local fr2 = fr ^ 2
local fill_tile = surface.get_tile(position).name
-- Make sure a non water tile is used for each tile
if surface.get_tile(position).collides_with('player') then fill_tile = 'landfill' end
if surface.get_tile(position).collides_with("player") then fill_tile = "landfill" end
if decon_tile == nil then decon_tile = fill_tile end
local tiles_to_make = {}
for x = -fr, fr do -- loop over x
local x2 = (x+0.5)^2
local x2 = (x + 0.5) ^ 2
for y = -fr, fr do -- loop over y
local y2 = (y+0.5)^2
local dst = x2+y2
local pos = {x=position.x+x, y=position.y+y}
local y2 = (y + 0.5) ^ 2
local dst = x2 + y2
local pos = { x = position.x + x, y = position.y + y }
if dst < tr2 then
-- If it is inside the decon radius always set the tile
table.insert(tiles_to_make, {name=decon_tile, position=pos})
elseif dst < fr2 and surface.get_tile(pos).collides_with('player') then
table.insert(tiles_to_make, { name = decon_tile, position = pos })
elseif dst < fr2 and surface.get_tile(pos).collides_with("player") then
-- If it is inside the fill radius only set the tile if it is water
table.insert(tiles_to_make, {name=fill_tile, position=pos})
table.insert(tiles_to_make, { name = fill_tile, position = pos })
end
end
end
-- Remove entities then set the tiles
local entities_to_remove = surface.find_entities_filtered{position=position, radius=dr, name='character', invert=true}
local entities_to_remove = surface.find_entities_filtered{ position = position, radius = dr, name = "character", invert = true }
for _, entity in pairs(entities_to_remove) do
entity.destroy()
end
surface.set_tiles(tiles_to_make)
end
local function spawn_resource_tiles(surface)
for _, v in ipairs(config.resource_tiles.resources) do
if v.enabled then
for x=v.offset[1], v.offset[1] + v.size[1] do
for y=v.offset[2], v.offset[2] + v.size[2] do
surface.create_entity({name=v.name, amount=v.amount, position={x, y}})
for x = v.offset[1], v.offset[1] + v.size[1] do
for y = v.offset[2], v.offset[2] + v.size[2] do
surface.create_entity{ name = v.name, amount = v.amount, position = { x, y } }
end
end
end
@@ -186,8 +188,8 @@ end
local function spawn_resource_patches(surface)
for _, v in ipairs(config.resource_patches.resources) do
if v.enabled then
for i=1, v.num_patches do
surface.create_entity({name=v.name, amount=v.amount, position={v.offset[1] + v.offset_next[1] * (i - 1), v.offset[2] + v.offset_next[2] * (i - 1)}})
for i = 1, v.num_patches do
surface.create_entity{ name = v.name, amount = v.amount, position = { v.offset[1] + v.offset_next[1] * (i - 1), v.offset[2] + v.offset_next[2] * (i - 1) } }
end
end
end
@@ -208,7 +210,7 @@ if config.resource_refill_nearby.enabled then
return
end
for _, ore in pairs(game.players[1].surface.find_entities_filtered{position=game.players[1].force.get_spawn_position(game.players[1].surface), radius=config.resource_refill_nearby.range, name=config.resource_refill_nearby.resources_name}) do
for _, ore in pairs(game.players[1].surface.find_entities_filtered{ position = game.players[1].force.get_spawn_position(game.players[1].surface), radius = config.resource_refill_nearby.range, name = config.resource_refill_nearby.resources_name }) do
ore.amount = ore.amount + math.random(config.resource_refill_nearby.amount[1], config.resource_refill_nearby.amount[2])
end
end)
@@ -218,7 +220,7 @@ end
Event.add(defines.events.on_player_created, function(event)
if event.player_index ~= 1 then return end
local player = game.players[event.player_index]
local p = {x=0, y=0}
local p = { x = 0, y = 0 }
local s = player.surface
get_spawn_force()
spawn_area(s, p)

View File

@@ -1,86 +1,85 @@
---LuaPlayerBuiltEntityEventFilters
---Events.set_event_filter(defines.events.on_built_entity, {{filter = "name", name = "fast-inserter"}})
--- LuaPlayerBuiltEntityEventFilters
--- Events.set_event_filter(defines.events.on_built_entity, {{filter = "name", name = "fast-inserter"}})
local Event = require("modules/exp_legacy/utils/event") --- @dep utils.event
local config = require("modules.exp_legacy.config.station_auto_name") --- @dep config.chat_reply
--Credit to Cooldude2606 for using his lua magic to make this function.
-- Credit to Cooldude2606 for using his lua magic to make this function.
local directions = {
['W'] = -0.875,
['NW'] = -0.625,
['N'] = -0.375,
['NE'] = -0.125,
['E'] = 0.125,
['SE'] = 0.375,
['S'] = 0.625,
['SW'] = 0.875
["W"] = -0.875,
["NW"] = -0.625,
["N"] = -0.375,
["NE"] = -0.125,
["E"] = 0.125,
["SE"] = 0.375,
["S"] = 0.625,
["SW"] = 0.875,
}
local function Angle(entity)
local angle = math.atan2(entity.position.y, entity.position.x)/math.pi
local angle = math.atan2(entity.position.y, entity.position.x) / math.pi
for direction, requiredAngle in pairs(directions) do
if angle < requiredAngle then
return direction
end
end
return 'W'
return "W"
end
local custom_string = ' *'
local custom_string = " *"
local custom_string_len = #custom_string
local function station_name_changer(event)
local entity = event.created_entity
local name = entity.name
if name == "entity-ghost" then
if name == "entity-ghost" then
if entity.ghost_name ~= "train-stop" then return end
local backername = entity.backer_name
if backername ~= '' then
entity.backer_name = backername..custom_string
if backername ~= "" then
entity.backer_name = backername .. custom_string
end
elseif name == "train-stop" then --only do the event if its a train stop
elseif name == "train-stop" then -- only do the event if its a train stop
local backername = entity.backer_name
if backername:sub(-custom_string_len) == custom_string then
entity.backer_name = backername:sub(1, -custom_string_len-1)
entity.backer_name = backername:sub(1, -custom_string_len - 1)
return
end
local boundingBox = entity.bounding_box
-- expanded box for recourse search:
local bounding2 = {{boundingBox.left_top.x-100 ,boundingBox.left_top.y-100} , {boundingBox.right_bottom.x+100, boundingBox.right_bottom.y+100 }}
local bounding2 = { { boundingBox.left_top.x - 100, boundingBox.left_top.y - 100 }, { boundingBox.right_bottom.x + 100, boundingBox.right_bottom.y + 100 } }
-- gets all resources in bounding_box2:
local recourses = game.surfaces[1].find_entities_filtered{area = bounding2, type = "resource"}
local recourses = game.surfaces[1].find_entities_filtered{ area = bounding2, type = "resource" }
if #recourses > 0 then -- save cpu time if their are no recourses in bounding_box2
local closest_distance
local px, py = boundingBox.left_top.x, boundingBox.left_top.y
local recourse_closed
--Check which recourse is closest
-- Check which recourse is closest
for i, item in ipairs(recourses) do
local dx, dy = px - item.bounding_box.left_top.x, py - item.bounding_box.left_top.y
local distance = (dx*dx)+(dy*dy)
if not closest_distance or distance < closest_distance then
local distance = (dx * dx) + (dy * dy)
if not closest_distance or distance < closest_distance then
recourse_closed = item
closest_distance = distance
end
end
local item_name = recourse_closed.name
if item_name then -- prevent errors if something went wrong
local item_name2 = item_name:gsub("^%l", string.upper):gsub('-', ' ') -- removing the - and making first letter capital
local item_name2 = item_name:gsub("^%l", string.upper):gsub("-", " ") -- removing the - and making first letter capital
local item_type = 'item'
if item_name == 'crude-oil' then
item_type = 'fluid'
local item_type = "item"
if item_name == "crude-oil" then
item_type = "fluid"
end
entity.backer_name = config.station_name:gsub('__icon__', '[img=' .. item_type .. '.' .. item_name .. ']')
:gsub('__item_name__', item_name2)
:gsub('__backer_name__', entity.backer_name)
:gsub('__direction__', Angle(entity))
:gsub('__x__', math.floor(entity.position.x))
:gsub('__y__', math.floor(entity.position.y))
entity.backer_name = config.station_name:gsub("__icon__", "[img=" .. item_type .. "." .. item_name .. "]")
:gsub("__item_name__", item_name2)
:gsub("__backer_name__", entity.backer_name)
:gsub("__direction__", Angle(entity))
:gsub("__x__", math.floor(entity.position.x))
:gsub("__y__", math.floor(entity.position.y))
end
end
end

View File

@@ -9,8 +9,8 @@ local PlayerData = require("modules.exp_legacy.expcore.player_data") --- @dep ex
-- Storage queue used to store trees that need to be removed, also cache for player roles
local cache = {}
local tree_queue = { _head=0 }
Storage.register({tree_queue, cache}, function(tbl)
local tree_queue = { _head = 0 }
Storage.register({ tree_queue, cache }, function(tbl)
tree_queue = tbl[1]
cache = tbl[2]
end)
@@ -18,26 +18,29 @@ end)
local function get_permission(player_index)
if cache[player_index] == nil then
local player = game.players[player_index]
if Roles.player_allowed(player, 'fast-tree-decon') then cache[player_index] = 'fast'
elseif Roles.player_allowed(player, 'standard-decon') then cache[player_index] = 'standard'
else cache[player_index] = player.force end
if Roles.player_allowed(player, "fast-tree-decon") then
cache[player_index] = "fast"
elseif Roles.player_allowed(player, "standard-decon") then
cache[player_index] = "standard"
else
cache[player_index] = player.force
end
end
return cache[player_index]
end
-- Left menu button to toggle between fast decon and normal decon marking
local HasEnabledDecon = PlayerData.Settings:combine('HasEnabledDecon')
local HasEnabledDecon = PlayerData.Settings:combine("HasEnabledDecon")
HasEnabledDecon:set_default(false)
Gui.toolbar_toggle_button("entity/tree-01", {'tree-decon.main-tooltip'}, function (player)
return Roles.player_allowed(player, "fast-tree-decon")
Gui.toolbar_toggle_button("entity/tree-01", { "tree-decon.main-tooltip" }, function(player)
return Roles.player_allowed(player, "fast-tree-decon")
end)
:on_event(Gui.events.on_toolbar_button_toggled, function(player, _, event)
HasEnabledDecon:set(player, event.state)
player.print{'tree-decon.toggle-msg', event.state and {'tree-decon.enabled'} or {'tree-decon.disabled'}}
end)
:on_event(Gui.events.on_toolbar_button_toggled, function(player, _, event)
HasEnabledDecon:set(player, event.state)
player.print{ "tree-decon.toggle-msg", event.state and { "tree-decon.enabled" } or { "tree-decon.disabled" } }
end)
-- Add trees to queue when marked, only allows simple entities and for players with role permission
Event.add(defines.events.on_marked_for_deconstruction, function(event)
@@ -52,24 +55,23 @@ Event.add(defines.events.on_marked_for_deconstruction, function(event)
-- Not allowed to decon this entity
local last_user = entity.last_user
local allow = get_permission(index)
if last_user and allow ~= 'standard' and allow ~= 'fast' then
if last_user and allow ~= "standard" and allow ~= "fast" then
entity.cancel_deconstruction(allow)
return
end
-- Allowed to decon this entity, but not fast
if allow ~= 'fast' then return end
if allow ~= "fast" then return end
local player = game.get_player(index)
if not HasEnabledDecon:get(player) then return end
-- Allowed fast decon on this entity, just trees
local head = tree_queue._head + 1
if not last_user and entity.type ~= 'cliff' then
if not last_user and entity.type ~= "cliff" then
tree_queue[head] = entity
tree_queue._head = head
end
end)
-- Remove trees at random till the queue is empty
@@ -77,7 +79,7 @@ Event.add(defines.events.on_tick, function()
local head = tree_queue._head
if head == 0 then return end
local max_remove = math.floor(head/100)+1
local max_remove = math.floor(head / 100) + 1
local remove_count = math.random(0, max_remove)
while remove_count > 0 and head > 0 do
local remove_index = math.random(1, head)
@@ -89,6 +91,7 @@ Event.add(defines.events.on_tick, function()
entity.destroy()
end
end
tree_queue._head = head
end)
@@ -101,24 +104,24 @@ end)
-- Clear trees when hit with a car
Event.add(defines.events.on_entity_damaged, function(event)
if not (event.damage_type.name == 'impact' and event.force) then
return
end
if not (event.damage_type.name == "impact" and event.force) then
return
end
if not (event.entity.type == 'tree' or event.entity.type == 'simple-entity') then
return
end
if not (event.entity.type == "tree" or event.entity.type == "simple-entity") then
return
end
if (not event.cause) or (event.cause.type ~= 'car')then
return
end
if (not event.cause) or (event.cause.type ~= "car") then
return
end
local driver = event.cause.get_driver()
if not driver then return end
local allow = get_permission(driver.player.index)
if allow == "fast" and HasEnabledDecon:get(driver.player) then
event.entity.destroy()
event.entity.destroy()
else
event.entity.order_deconstruction(event.force, driver.player)
end

View File

@@ -10,17 +10,18 @@ require("modules.exp_legacy.config.expcore.command_general_parse")
--- Sends a message in chat that only admins can see
-- @command admin-chat
-- @tparam string message the message to send in the admin chat
Commands.new_command('admin-chat', {'expcom-admin-chat.description'}, 'Sends a message in chat that only admins can see.')
:add_param('message', false)
:enable_auto_concat()
:set_flag('admin_only')
:add_alias('ac')
:register(function(player, message)
local player_name_colour = format_chat_player_name(player)
for _, return_player in pairs(game.connected_players) do
if return_player.admin then
return_player.print{'expcom-admin-chat.format', player_name_colour, message}
Commands.new_command("admin-chat", { "expcom-admin-chat.description" }, "Sends a message in chat that only admins can see.")
:add_param("message", false)
:enable_auto_concat()
:set_flag("admin_only")
:add_alias("ac")
:register(function(player, message)
local player_name_colour = format_chat_player_name(player)
for _, return_player in pairs(game.connected_players) do
if return_player.admin then
return_player.print{ "expcom-admin-chat.format", player_name_colour, message }
end
end
end
return Commands.success -- prevents command complete message from showing
end)
return Commands.success -- prevents command complete message from showing
end)

View File

@@ -13,7 +13,7 @@ local markers = {} -- Stores all admin markers
--- Storage variables
Storage.register({
admins = admins,
markers = markers
markers = markers,
}, function(tbl)
admins = tbl.admins
markers = tbl.markers
@@ -21,20 +21,20 @@ end)
--- Toggle admin marker mode, can only be applied to yourself
-- @command admin-marker
Commands.new_command('admin-marker', {'expcom-admin-marker.description'}, 'Toggles admin marker mode, new markers can only be edited by admins')
:set_flag('admin_only')
:add_alias('am', 'admin-markers')
:register(function(player)
if admins[player.name] then
-- Exit admin mode
admins[player.name] = nil
return Commands.success{'expcom-admin-marker.exit'}
else
-- Enter admin mode
admins[player.name] = true
return Commands.success{'expcom-admin-marker.enter'}
end
end)
Commands.new_command("admin-marker", { "expcom-admin-marker.description" }, "Toggles admin marker mode, new markers can only be edited by admins")
:set_flag("admin_only")
:add_alias("am", "admin-markers")
:register(function(player)
if admins[player.name] then
-- Exit admin mode
admins[player.name] = nil
return Commands.success{ "expcom-admin-marker.exit" }
else
-- Enter admin mode
admins[player.name] = true
return Commands.success{ "expcom-admin-marker.enter" }
end
end)
--- Listen for new map markers being added, add admin marker if done by player in admin mode
Event.add(defines.events.on_chart_tag_added, function(event)
@@ -42,8 +42,8 @@ Event.add(defines.events.on_chart_tag_added, function(event)
local player = game.get_player(event.player_index)
if not admins[player.name] then return end
local tag = event.tag
markers[tag.force.name..tag.tag_number] = true
Commands.print({'expcom-admin-marker.place'}, nil, player)
markers[tag.force.name .. tag.tag_number] = true
Commands.print({ "expcom-admin-marker.place" }, nil, player)
end)
--- Listen for players leaving the game, leave admin mode to avoid unexpected admin markers
@@ -57,30 +57,30 @@ end)
local function maintain_tag(event)
local tag = event.tag
if not event.player_index then return end
if not markers[tag.force.name..tag.tag_number] then return end
if not markers[tag.force.name .. tag.tag_number] then return end
local player = game.get_player(event.player_index)
if player.admin then
-- Player is admin, tell them it was an admin marker
Commands.print({'expcom-admin-marker.edit'}, nil, player)
Commands.print({ "expcom-admin-marker.edit" }, nil, player)
elseif event.name == defines.events.on_chart_tag_modified then
-- Tag was modified, revert the changes
tag.text = event.old_text
tag.last_user = event.old_player
if event.old_icon then tag.icon = event.old_icon end
player.play_sound{path='utility/wire_pickup'}
Commands.print({'expcom-admin-marker.revert'}, nil, player)
player.play_sound{ path = "utility/wire_pickup" }
Commands.print({ "expcom-admin-marker.revert" }, nil, player)
else
-- Tag was removed, remake the tag
player.play_sound{path='utility/wire_pickup'}
Commands.print({'expcom-admin-marker.revert'}, 'orange_red', player)
player.play_sound{ path = "utility/wire_pickup" }
Commands.print({ "expcom-admin-marker.revert" }, "orange_red", player)
local new_tag = tag.force.add_chart_tag(tag.surface, {
last_user = tag.last_user,
position = tag.position,
icon = tag.icon,
text = tag.text,
})
markers[tag.force.name..tag.tag_number] = nil
markers[new_tag.force.name..new_tag.tag_number] = true
markers[tag.force.name .. tag.tag_number] = nil
markers[new_tag.force.name .. new_tag.tag_number] = true
end
end

View File

@@ -6,21 +6,17 @@
local Commands = require("modules.exp_legacy.expcore.commands") --- @dep expcore.commands
require("modules.exp_legacy.config.expcore.command_general_parse")
local Selection = require("modules.exp_legacy.modules.control.selection") --- @dep modules.control.selection
local SelectionArtyArea = 'ArtyArea'
local SelectionArtyArea = "ArtyArea"
local function location_break(player, pos)
if player.force.is_chunk_charted(player.surface, {x=math.floor(pos.left_top.x / 32), y=math.floor(pos.left_top.y / 32)}) then
if player.force.is_chunk_charted(player.surface, { x = math.floor(pos.left_top.x / 32), y = math.floor(pos.left_top.y / 32) }) then
return true
elseif player.force.is_chunk_charted(player.surface, {x=math.floor(pos.left_top.x / 32), y=math.floor(pos.right_bottom.y / 32)}) then
elseif player.force.is_chunk_charted(player.surface, { x = math.floor(pos.left_top.x / 32), y = math.floor(pos.right_bottom.y / 32) }) then
return true
elseif player.force.is_chunk_charted(player.surface, {x=math.floor(pos.right_bottom.x / 32), y=math.floor(pos.left_top.y / 32)}) then
elseif player.force.is_chunk_charted(player.surface, { x = math.floor(pos.right_bottom.x / 32), y = math.floor(pos.left_top.y / 32) }) then
return true
elseif player.force.is_chunk_charted(player.surface, {x=math.floor(pos.right_bottom.x / 32), y=math.floor(pos.right_bottom.y / 32)}) then
elseif player.force.is_chunk_charted(player.surface, { x = math.floor(pos.right_bottom.x / 32), y = math.floor(pos.right_bottom.y / 32) }) then
return true
else
return false
end
@@ -29,8 +25,8 @@ end
--- align an aabb to the grid by expanding it
local function aabb_align_expand(aabb)
return {
left_top = {x = math.floor(aabb.left_top.x), y = math.floor(aabb.left_top.y)},
right_bottom = {x = math.ceil(aabb.right_bottom.x), y = math.ceil(aabb.right_bottom.y)}
left_top = { x = math.floor(aabb.left_top.x), y = math.floor(aabb.left_top.y) },
right_bottom = { x = math.ceil(aabb.right_bottom.x), y = math.ceil(aabb.right_bottom.y) },
}
end
@@ -50,7 +46,7 @@ Selection.on_selection(SelectionArtyArea, function(event)
local count = 0
local hit = {}
for _, e in pairs(player.surface.find_entities_filtered({area=area, type={'unit-spawner', 'turret'}, force='enemy'})) do
for _, e in pairs(player.surface.find_entities_filtered{ area = area, type = { "unit-spawner", "turret" }, force = "enemy" }) do
local skip = false
for _, pos in ipairs(hit) do
@@ -61,7 +57,7 @@ Selection.on_selection(SelectionArtyArea, function(event)
end
if not skip then
player.surface.create_entity{name='artillery-flare', position=e.position, force=player.force, life_time=240, movement={0, 0}, height=0, vertical_speed=0, frame_speed=0}
player.surface.create_entity{ name = "artillery-flare", position = e.position, force = player.force, life_time = 240, movement = { 0, 0 }, height = 0, vertical_speed = 0, frame_speed = 0 }
table.insert(hit, e.position)
count = count + 1
@@ -72,13 +68,13 @@ Selection.on_selection(SelectionArtyArea, function(event)
end
end)
Commands.new_command('artillery-target-remote', {'expcom-artillery.description'}, 'Artillery Target Remote')
:register(function(player)
if Selection.is_selecting(player, SelectionArtyArea) then
Selection.stop(player)
else
Selection.start(player, SelectionArtyArea)
end
Commands.new_command("artillery-target-remote", { "expcom-artillery.description" }, "Artillery Target Remote")
:register(function(player)
if Selection.is_selecting(player, SelectionArtyArea) then
Selection.stop(player)
else
Selection.start(player, SelectionArtyArea)
end
return Commands.success
end)
return Commands.success
end)

View File

@@ -6,20 +6,20 @@
local Commands = require("modules.exp_legacy.expcore.commands") --- @dep expcore.commands
require("modules.exp_legacy.config.expcore.command_general_parse")
Commands.new_command('bot-queue-get', {'expcom-bot-queue.description-get'}, 'Get bot queue')
:set_flag('admin_only')
:register(function(player)
local s = player.force.max_successful_attempts_per_tick_per_construction_queue
local f = player.force.max_failed_attempts_per_tick_per_construction_queue
return Commands.success{'expcom-bot-queue.result', player.name, s, f}
end)
Commands.new_command("bot-queue-get", { "expcom-bot-queue.description-get" }, "Get bot queue")
:set_flag("admin_only")
:register(function(player)
local s = player.force.max_successful_attempts_per_tick_per_construction_queue
local f = player.force.max_failed_attempts_per_tick_per_construction_queue
return Commands.success{ "expcom-bot-queue.result", player.name, s, f }
end)
Commands.new_command('bot-queue-set', {'expcom-bot-queue.description-set'}, 'Set bot queue')
:add_param('amount', 'integer-range', 1, 20)
:set_flag('admin_only')
:register(function(player, amount)
player.force.max_successful_attempts_per_tick_per_construction_queue = 3 * amount
player.force.max_failed_attempts_per_tick_per_construction_queue = 1 * amount
game.print{'expcom-bot-queue.result', player.name, 3 * amount, 1 * amount}
return Commands.success
end)
Commands.new_command("bot-queue-set", { "expcom-bot-queue.description-set" }, "Set bot queue")
:add_param("amount", "integer-range", 1, 20)
:set_flag("admin_only")
:register(function(player, amount)
player.force.max_successful_attempts_per_tick_per_construction_queue = 3 * amount
player.force.max_failed_attempts_per_tick_per_construction_queue = 1 * amount
game.print{ "expcom-bot-queue.result", player.name, 3 * amount, 1 * amount }
return Commands.success
end)

View File

@@ -9,37 +9,37 @@ require("modules.exp_legacy.config.expcore.command_general_parse")
--- Toggles cheat mode for your player, or another player.
-- @command toggle-cheat-mode
-- @tparam[opt=self] LuaPlayer player player to toggle chest mode of, can be nil for self
Commands.new_command('toggle-cheat-mode', {'expcom-cheat.description-cheat'}, 'Toggles cheat mode for your player, or another player.')
:add_param('player', true, 'player')
:set_defaults{player=function(player)
return player -- default is the user using the command
end}
:set_flag('admin_only')
:register(function(_, player)
player.cheat_mode = not player.cheat_mode
return Commands.success
end)
Commands.new_command("toggle-cheat-mode", { "expcom-cheat.description-cheat" }, "Toggles cheat mode for your player, or another player.")
:add_param("player", true, "player")
:set_defaults{ player = function(player)
return player -- default is the user using the command
end }
:set_flag("admin_only")
:register(function(_, player)
player.cheat_mode = not player.cheat_mode
return Commands.success
end)
Commands.new_command('research-all', {'expcom-cheat.description-res'}, 'Set all research for your force.')
:set_flag('admin_only')
:add_param('force', true, 'force')
:set_defaults{force=function(player)
return player.force
end}
:register(function(player, force)
force.research_all_technologies()
game.print{'expcom-cheat.res', player.name}
return Commands.success
end)
Commands.new_command("research-all", { "expcom-cheat.description-res" }, "Set all research for your force.")
:set_flag("admin_only")
:add_param("force", true, "force")
:set_defaults{ force = function(player)
return player.force
end }
:register(function(player, force)
force.research_all_technologies()
game.print{ "expcom-cheat.res", player.name }
return Commands.success
end)
Commands.new_command('toggle-always-day', {'expcom-cheat.description-day'}, 'Toggles always day in surface.')
:set_flag('admin_only')
:add_param('surface', true, 'surface')
:set_defaults{surface=function(player)
return player.surface
end}
:register(function(player, surface)
surface.always_day = not surface.always_day
game.print{'expcom-cheat.day', player.name, surface.always_day}
return Commands.success
end)
Commands.new_command("toggle-always-day", { "expcom-cheat.description-day" }, "Toggles always day in surface.")
:set_flag("admin_only")
:add_param("surface", true, "surface")
:set_defaults{ surface = function(player)
return player.surface
end }
:register(function(player, surface)
surface.always_day = not surface.always_day
game.print{ "expcom-cheat.day", player.name, surface.always_day }
return Commands.success
end)

View File

@@ -10,14 +10,14 @@ require("modules.exp_legacy.config.expcore.command_role_parse")
--- Clears a players inventory
-- @command clear-inventory
-- @tparam LuaPlayer player the player to clear the inventory of
Commands.new_command('clear-inventory', {'expcom-clr-inv.description'}, 'Clears a players inventory')
:add_param('player', false, 'player-role')
:add_alias('clear-inv', 'move-inventory', 'move-inv')
:register(function(_, player)
local inv = player.get_main_inventory()
if not inv then
return Commands.error{'expcore-commands.reject-player-alive'}
end
move_items_stack(inv)
inv.clear()
end)
Commands.new_command("clear-inventory", { "expcom-clr-inv.description" }, "Clears a players inventory")
:add_param("player", false, "player-role")
:add_alias("clear-inv", "move-inventory", "move-inv")
:register(function(_, player)
local inv = player.get_main_inventory()
if not inv then
return Commands.error{ "expcore-commands.reject-player-alive" }
end
move_items_stack(inv)
inv.clear()
end)

View File

@@ -30,20 +30,20 @@ local function get_server_id(server)
end
if server_count > 1 then
return false, Commands.error{'expcom-connect.too-many-matching', concat(server_names, ', ')}
return false, Commands.error{ "expcom-connect.too-many-matching", concat(server_names, ", ") }
elseif server_count == 1 then
local server_id, server_details = next(servers)
local status = External.get_server_status(server_id)
if server_id == current_server.id then
return false, Commands.error{'expcom-connect.same-server', server_details.name}
elseif status == 'Offline' then
return false, Commands.error{'expcom-connect.offline', server_details.name}
return false, Commands.error{ "expcom-connect.same-server", server_details.name }
elseif status == "Offline" then
return false, Commands.error{ "expcom-connect.offline", server_details.name }
end
return true, server_id
elseif server_count_before > 0 then
return false, Commands.error{'expcom-connect.wrong-version', concat(server_names_before, ', ')}
return false, Commands.error{ "expcom-connect.wrong-version", concat(server_names_before, ", ") }
else
return false, Commands.error{'expcom-connect.none-matching'}
return false, Commands.error{ "expcom-connect.none-matching" }
end
end
@@ -51,57 +51,57 @@ end
-- @command connect
-- @tparam string server The address or name of the server to connect to
-- @tparam[opt=false] boolean is_address If an address was given for the server param
Commands.new_command('connect', {'expcom-connect.description'}, 'Connect to another server')
:add_param('server')
:add_param('is_address', true, 'boolean')
:add_alias('join', 'server')
:register(function(player, server, is_address)
local server_id = server
if not is_address and External.valid() then
local success, new_server_id = get_server_id(server)
if not success then return new_server_id end
server_id = new_server_id
end
Commands.new_command("connect", { "expcom-connect.description" }, "Connect to another server")
:add_param("server")
:add_param("is_address", true, "boolean")
:add_alias("join", "server")
:register(function(player, server, is_address)
local server_id = server
if not is_address and External.valid() then
local success, new_server_id = get_server_id(server)
if not success then return new_server_id end
server_id = new_server_id
end
Async(request_connection, player, server_id, true)
end)
Async(request_connection, player, server_id, true)
end)
--- Connect a player to a different server
-- @command connect-player
-- @tparam string address The address or name of the server to connect to
-- @tparam LuaPlayer player The player to connect to a different server
-- @tparam[opt=false] boolean is_address If an address was given for the server param
Commands.new_command('connect-player', {'expcom-connect.description-player'}, 'Send a player to a different server')
:add_param('player', 'player-role')
:add_param('server')
:add_param('is_address', true, 'boolean')
:register(function(_, player, server, is_address)
local server_id = server
if not is_address and External.valid() then
local success, new_server_id = get_server_id(server)
if not success then return new_server_id end
server_id = new_server_id
end
Commands.new_command("connect-player", { "expcom-connect.description-player" }, "Send a player to a different server")
:add_param("player", "player-role")
:add_param("server")
:add_param("is_address", true, "boolean")
:register(function(_, player, server, is_address)
local server_id = server
if not is_address and External.valid() then
local success, new_server_id = get_server_id(server)
if not success then return new_server_id end
server_id = new_server_id
end
External.request_connection(player, server_id)
end)
External.request_connection(player, server_id)
end)
--- Connect all players to a different server
-- @command connect-all
-- @tparam string address The address or name of the server to connect to
-- @tparam[opt=false] boolean is_address If an address was given for the server param
Commands.new_command('connect-all', {'expcom-connect.description-all'}, 'Connect all players to another server')
:add_param('server')
:add_param('is_address', true, 'boolean')
:register(function(_, server, is_address)
local server_id = server
if not is_address and External.valid() then
local success, new_server_id = get_server_id(server)
if not success then return new_server_id end
server_id = new_server_id
end
Commands.new_command("connect-all", { "expcom-connect.description-all" }, "Connect all players to another server")
:add_param("server")
:add_param("is_address", true, "boolean")
:register(function(_, server, is_address)
local server_id = server
if not is_address and External.valid() then
local success, new_server_id = get_server_id(server)
if not success then return new_server_id end
server_id = new_server_id
end
for _, player in pairs(game.connected_players) do
External.request_connection(player, server_id)
end
end)
for _, player in pairs(game.connected_players) do
External.request_connection(player, server_id)
end
end)

View File

@@ -8,7 +8,7 @@ local Commands = require("modules.exp_legacy.expcore.commands") --- @dep expcore
--- Opens the debug pannel for viewing tables.
-- @command debug
Commands.new_command('debug', {'expcom-debug.description'}, 'Opens the debug pannel for viewing tables.')
:register(function(player)
DebugView.open_dubug(player)
end)
Commands.new_command("debug", { "expcom-debug.description" }, "Opens the debug pannel for viewing tables.")
:register(function(player)
DebugView.open_dubug(player)
end)

View File

@@ -6,24 +6,24 @@
local Commands = require("modules.exp_legacy.expcore.commands") --- @dep expcore.commands
require("modules.exp_legacy.config.expcore.command_general_parse")
Commands.new_command('kill-biters', {'expcom-enemy.description-kill'}, 'Kill all biters only')
:set_flag('admin_only')
:register(function(_, _)
game.forces['enemy'].kill_all_units()
return Commands.success
end)
Commands.new_command("kill-biters", { "expcom-enemy.description-kill" }, "Kill all biters only")
:set_flag("admin_only")
:register(function(_, _)
game.forces["enemy"].kill_all_units()
return Commands.success
end)
Commands.new_command('remove-biters', {'expcom-enemy.description-remove'}, 'Remove biters and prevent generation')
:set_flag('admin_only')
:add_param('surface', true, 'surface')
:set_defaults{surface=function(player)
return player.surface
end}
:register(function(_, surface)
for _, entity in pairs(surface.find_entities_filtered({force='enemy'})) do
entity.destroy()
end
Commands.new_command("remove-biters", { "expcom-enemy.description-remove" }, "Remove biters and prevent generation")
:set_flag("admin_only")
:add_param("surface", true, "surface")
:set_defaults{ surface = function(player)
return player.surface
end }
:register(function(_, surface)
for _, entity in pairs(surface.find_entities_filtered{ force = "enemy" }) do
entity.destroy()
end
surface.map_gen_settings.autoplace_controls['enemy-base'].size = 'none'
return Commands.success
end)
surface.map_gen_settings.autoplace_controls["enemy-base"].size = "none"
return Commands.success
end)

View File

@@ -9,11 +9,11 @@ require("modules.exp_legacy.config.expcore.command_general_parse")
--- Find a player on your map.
-- @command find-on-map
-- @tparam LuaPlayer the player to find on the map
Commands.new_command('find-on-map', {'expcom-find.description'}, 'Find a player on your map.')
:add_param('player', false, 'player-online')
:add_alias('find', 'zoom-to')
:register(function(player, action_player)
local position = action_player.position
player.zoom_to_world(position, 1.75)
return Commands.success -- prevents command complete message from showing
end)
Commands.new_command("find-on-map", { "expcom-find.description" }, "Find a player on your map.")
:add_param("player", false, "player-online")
:add_alias("find", "zoom-to")
:register(function(player, action_player)
local position = action_player.position
player.zoom_to_world(position, 1.75)
return Commands.success -- prevents command complete message from showing
end)

View File

@@ -7,13 +7,13 @@ local Commands = require("modules.exp_legacy.expcore.commands") --- @dep expcore
require("modules.exp_legacy.config.expcore.command_general_parse")
-- For Modded Server Use
Commands.new_command('toggle-friendly-fire', {'expcom-ff.description'}, 'Toggle friendly fire')
:add_param('force', true, 'force')
:set_defaults{force=function(player)
return player.force
end}
:register(function(player, force)
force.friendly_fire = not force.friendly_fire
game.print{'expcom-ff.ff', player.name, force.friendly_fire}
return Commands.success
end)
Commands.new_command("toggle-friendly-fire", { "expcom-ff.description" }, "Toggle friendly fire")
:add_param("force", true, "force")
:set_defaults{ force = function(player)
return player.force
end }
:register(function(player, force)
force.friendly_fire = not force.friendly_fire
game.print{ "expcom-ff.ff", player.name, force.friendly_fire }
return Commands.success
end)

View File

@@ -18,78 +18,77 @@ end)
-- @command chelp
-- @tparam string keyword the keyword that will be looked for
-- @tparam number page the page of help to view, must be in range of pages
Commands.new_command('search-help', {'expcom-chelp.description'}, 'Searches for a keyword in all commands you are allowed to use.')
:add_alias('chelp', 'shelp', 'commands')
:add_param('keyword', true)
:add_param('page', true, 'integer')
:set_defaults{keyword='', page=1}
:register(function(player, keyword, page)
local player_index = player and player.index or 0
-- if keyword is a number then treat it as page number
if tonumber(keyword) then
page = math.floor(tonumber(keyword))
keyword = ''
end
Commands.new_command("search-help", { "expcom-chelp.description" }, "Searches for a keyword in all commands you are allowed to use.")
:add_alias("chelp", "shelp", "commands")
:add_param("keyword", true)
:add_param("page", true, "integer")
:set_defaults{ keyword = "", page = 1 }
:register(function(player, keyword, page)
local player_index = player and player.index or 0
-- if keyword is a number then treat it as page number
if tonumber(keyword) then
page = math.floor(tonumber(keyword))
keyword = ""
end
-- gets a value for pages, might have result in cache
local pages
local found = 0
-- gets a value for pages, might have result in cache
local pages
local found = 0
if search_cache[player_index] and search_cache[player_index].keyword == keyword:lower() then
pages = search_cache[player_index].pages
found = search_cache[player_index].found
else
pages = {{}}
local current_page = 1
local page_count = 0
local commands = Commands.search(keyword, player)
-- loops other all commands returned by search, includes game commands
for _, command_data in pairs(commands) do
-- if the number of results if greater than the number already added then it moves onto a new page
if page_count >= results_per_page then
page_count = 0
current_page = current_page + 1
table.insert(pages, {})
if search_cache[player_index] and search_cache[player_index].keyword == keyword:lower() then
pages = search_cache[player_index].pages
found = search_cache[player_index].found
else
pages = { {} }
local current_page = 1
local page_count = 0
local commands = Commands.search(keyword, player)
-- loops other all commands returned by search, includes game commands
for _, command_data in pairs(commands) do
-- if the number of results if greater than the number already added then it moves onto a new page
if page_count >= results_per_page then
page_count = 0
current_page = current_page + 1
table.insert(pages, {})
end
-- adds the new command to the page
page_count = page_count + 1
found = found + 1
local alias_format = #command_data.aliases > 0 and { "expcom-chelp.alias", table.concat(command_data.aliases, ", ") } or ""
table.insert(pages[current_page], {
"expcom-chelp.format",
command_data.name,
command_data.description,
command_data.help,
alias_format,
})
end
-- adds the new command to the page
page_count = page_count + 1
found = found + 1
local alias_format = #command_data.aliases > 0 and {'expcom-chelp.alias', table.concat(command_data.aliases, ', ')} or ''
table.insert(pages[current_page], {
'expcom-chelp.format',
command_data.name,
command_data.description,
command_data.help,
alias_format
})
end
-- adds the result to the cache
search_cache[player_index] = {
keyword=keyword:lower(),
pages=pages,
found=found
}
end
-- print the requested page
keyword = keyword == '' and '<all>' or keyword
Commands.print({'expcom-chelp.title', keyword}, 'cyan')
if pages[page] then
for _, command in pairs(pages[page]) do
Commands.print(command)
-- adds the result to the cache
search_cache[player_index] = {
keyword = keyword:lower(),
pages = pages,
found = found,
}
end
Commands.print({'expcom-chelp.footer', found, page, #pages}, 'cyan')
-- print the requested page
keyword = keyword == "" and "<all>" or keyword
Commands.print({ "expcom-chelp.title", keyword }, "cyan")
else
Commands.print({'expcom-chelp.footer', found, page, #pages}, 'cyan')
return Commands.error{'expcom-chelp.out-of-range', page}
end
-- blocks command complete message
return Commands.success
end)
if pages[page] then
for _, command in pairs(pages[page]) do
Commands.print(command)
end
Commands.print({ "expcom-chelp.footer", found, page, #pages }, "cyan")
else
Commands.print({ "expcom-chelp.footer", found, page, #pages }, "cyan")
return Commands.error{ "expcom-chelp.out-of-range", page }
end
-- blocks command complete message
return Commands.success
end)
-- way to access global
return search_cache

View File

@@ -14,7 +14,7 @@ end)
local function teleport(player, position)
local surface = player.surface
local pos = surface.find_non_colliding_position('character', position, 32, 1)
local pos = surface.find_non_colliding_position("character", position, 32, 1)
if not position then return false end
if player.driving then player.driving = false end -- kicks a player out a vehicle if in one
player.teleport(pos, surface)
@@ -23,61 +23,61 @@ end
local function floor_pos(position)
return {
x=math.floor(position.x),
y=math.floor(position.y)
x = math.floor(position.x),
y = math.floor(position.y),
}
end
--- Teleports you to your home location
-- @command home
Commands.new_command('home', {'expcom-home.description-home'}, 'Teleports you to your home location')
:register(function(player)
local home = homes[player.index]
if not home or not home[1] then
return Commands.error{'expcom-home.no-home'}
end
local rtn = floor_pos(player.position)
teleport(player, home[1])
home[2] = rtn
Commands.print{'expcom-home.return-set', rtn.x, rtn.y}
end)
Commands.new_command("home", { "expcom-home.description-home" }, "Teleports you to your home location")
:register(function(player)
local home = homes[player.index]
if not home or not home[1] then
return Commands.error{ "expcom-home.no-home" }
end
local rtn = floor_pos(player.position)
teleport(player, home[1])
home[2] = rtn
Commands.print{ "expcom-home.return-set", rtn.x, rtn.y }
end)
--- Sets your home location to your current position
-- @command home-set
Commands.new_command('home-set', {'expcom-home.description-home-set'}, 'Sets your home location to your current position')
:register(function(player)
local home = homes[player.index]
if not home then
home = {}
homes[player.index] = home
end
local pos = floor_pos(player.position)
home[1] = pos
Commands.print{'expcom-home.home-set', pos.x, pos.y}
end)
Commands.new_command("home-set", { "expcom-home.description-home-set" }, "Sets your home location to your current position")
:register(function(player)
local home = homes[player.index]
if not home then
home = {}
homes[player.index] = home
end
local pos = floor_pos(player.position)
home[1] = pos
Commands.print{ "expcom-home.home-set", pos.x, pos.y }
end)
--- Returns your current home location
-- @command home-get
Commands.new_command('home-get', {'expcom-home.description-home-get'}, 'Returns your current home location')
:register(function(player)
local home = homes[player.index]
if not home or not home[1] then
return Commands.error{'expcom-home.no-home'}
end
local pos = home[1]
Commands.print{'expcom-home.home-get', pos.x, pos.y}
end)
Commands.new_command("home-get", { "expcom-home.description-home-get" }, "Returns your current home location")
:register(function(player)
local home = homes[player.index]
if not home or not home[1] then
return Commands.error{ "expcom-home.no-home" }
end
local pos = home[1]
Commands.print{ "expcom-home.home-get", pos.x, pos.y }
end)
--- Teleports you to previous location
-- @command return
Commands.new_command('return', {'expcom-home.description-return'}, 'Teleports you to previous location')
:register(function(player)
local home = homes[player.index]
if not home or not home[2] then
return Commands.error{'expcom-home.no-return'}
end
local rtn = floor_pos(player.position)
teleport(player, home[2])
home[2] = rtn
Commands.print{'expcom-home.return-set', rtn.x, rtn.y}
end)
Commands.new_command("return", { "expcom-home.description-return" }, "Teleports you to previous location")
:register(function(player)
local home = homes[player.index]
if not home or not home[2] then
return Commands.error{ "expcom-home.no-return" }
end
local rtn = floor_pos(player.position)
teleport(player, home[2])
home[2] = rtn
Commands.print{ "expcom-home.return-set", rtn.x, rtn.y }
end)

View File

@@ -8,18 +8,18 @@ local Storage = require("modules/exp_util/storage")
-- modules that are loaded into the interface env to be accessed
local interface_modules = {
['Commands'] = Commands,
['output'] = _C.player_return,
['Group'] = 'expcore.permission_groups',
['Roles'] = 'expcore.roles',
['Gui'] = 'expcore.gui',
['Datastore'] = 'expcore.datastore',
['External'] = 'expcore.external'
["Commands"] = Commands,
["output"] = _C.player_return,
["Group"] = "expcore.permission_groups",
["Roles"] = "expcore.roles",
["Gui"] = "expcore.gui",
["Datastore"] = "expcore.datastore",
["External"] = "expcore.external",
}
-- loads all the modules given in the above table
for key, value in pairs(interface_modules) do
if type(value) == 'string' then
if type(value) == "string" then
interface_modules[key] = _C.opt_require(value)
end
end
@@ -42,7 +42,7 @@ end
-- @tparam string name The name that the value is assigned to
-- @tparam function callback The function that will be called to get the value
local function add_interface_callback(name, callback)
if type(callback) == 'function' then
if type(callback) == "function" then
interface_callbacks[name] = callback
end
end
@@ -61,55 +61,55 @@ end
--- Sends an invocation to be ran and returns the result.
-- @command interface
-- @tparam string invocation the command that will be run
Commands.new_command('interface', {'expcom-interface.description'}, 'Sends an invocation to be ran and returns the result.')
:add_param('invocation', false)
:enable_auto_concat()
:set_flag('admin_only')
:register(function(player, invocation)
-- If the invocation has no white space then prepend return to it
if not invocation:find('%s') and not invocation:find('return') then
invocation = 'return '..invocation
end
-- _env will be the new _ENV that the invocation will run inside of
local _env = setmetatable({}, {
__index = get_index,
__newindex = interface_env
})
-- If the command is ran by a player then load the dynamic values
if player then
for name, callback in pairs(interface_callbacks) do
local _, rtn = pcall(callback, player)
rawset(_env, name, rtn)
Commands.new_command("interface", { "expcom-interface.description" }, "Sends an invocation to be ran and returns the result.")
:add_param("invocation", false)
:enable_auto_concat()
:set_flag("admin_only")
:register(function(player, invocation)
-- If the invocation has no white space then prepend return to it
if not invocation:find("%s") and not invocation:find("return") then
invocation = "return " .. invocation
end
end
-- Compile the invocation with the custom _env value
local invocation_func, compile_error = load(invocation, 'interface', nil, _env)
if compile_error then return Commands.error(compile_error) end
-- _env will be the new _ENV that the invocation will run inside of
local _env = setmetatable({}, {
__index = get_index,
__newindex = interface_env,
})
-- Run the invocation
local success, rtn = pcall(invocation_func)
if not success then
local err = rtn:gsub('%.%.%..-/temp/currently%-playing', '')
return Commands.error(err)
end
return Commands.success(rtn)
end)
-- If the command is ran by a player then load the dynamic values
if player then
for name, callback in pairs(interface_callbacks) do
local _, rtn = pcall(callback, player)
rawset(_env, name, rtn)
end
end
-- Compile the invocation with the custom _env value
local invocation_func, compile_error = load(invocation, "interface", nil, _env)
if compile_error then return Commands.error(compile_error) end
-- Run the invocation
local success, rtn = pcall(invocation_func)
if not success then
local err = rtn:gsub("%.%.%..-/temp/currently%-playing", "")
return Commands.error(err)
end
return Commands.success(rtn)
end)
-- Adds some basic callbacks for the interface
add_interface_callback('player', function(player) return player end)
add_interface_callback('surface', function(player) return player.surface end)
add_interface_callback('force', function(player) return player.force end)
add_interface_callback('position', function(player) return player.position end)
add_interface_callback('entity', function(player) return player.selected end)
add_interface_callback('tile', function(player) return player.surface.get_tile(player.position) end)
add_interface_callback("player", function(player) return player end)
add_interface_callback("surface", function(player) return player.surface end)
add_interface_callback("force", function(player) return player.force end)
add_interface_callback("position", function(player) return player.position end)
add_interface_callback("entity", function(player) return player.selected end)
add_interface_callback("tile", function(player) return player.surface.get_tile(player.position) end)
-- Module Return
return {
add_interface_module = add_interface_module,
add_interface_callback = add_interface_callback,
interface_env = interface_env,
clean_stack_trace = function(str) return str:gsub('%.%.%..-/temp/currently%-playing', '') end
clean_stack_trace = function(str) return str:gsub("%.%.%..-/temp/currently%-playing", "") end,
}

View File

@@ -12,36 +12,36 @@ require("modules.exp_legacy.config.expcore.command_role_parse")
-- @command jail
-- @tparam LuaPlayer player the player that will be jailed
-- @tparam[opt] string reason the reason why the player is being jailed
Commands.new_command('jail', {'expcom-jail.description-jail'}, 'Puts a player into jail and removes all other roles.')
:add_param('player', false, 'player-role')
:add_param('reason', true)
:enable_auto_concat()
:register(function(player, action_player, reason)
reason = reason or 'Non Given.'
local action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(player)
local player_name = player and player.name or '<server>'
if Jail.jail_player(action_player, player_name, reason) then
game.print{'expcom-jail.give', action_player_name_color, by_player_name_color, reason}
else
return Commands.error{'expcom-jail.already-jailed', action_player_name_color}
end
end)
Commands.new_command("jail", { "expcom-jail.description-jail" }, "Puts a player into jail and removes all other roles.")
:add_param("player", false, "player-role")
:add_param("reason", true)
:enable_auto_concat()
:register(function(player, action_player, reason)
reason = reason or "Non Given."
local action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(player)
local player_name = player and player.name or "<server>"
if Jail.jail_player(action_player, player_name, reason) then
game.print{ "expcom-jail.give", action_player_name_color, by_player_name_color, reason }
else
return Commands.error{ "expcom-jail.already-jailed", action_player_name_color }
end
end)
--- Removes a player from jail.
-- @command unjail
-- @tparam LuaPlayer the player that will be unjailed
Commands.new_command('unjail', {'expcom-jail.description-unjail'}, 'Removes a player from jail.')
:add_param('player', false, 'player-role')
:add_alias('clear-jail', 'remove-jail')
:enable_auto_concat()
:register(function(player, action_player)
local action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(player)
local player_name = player and player.name or '<server>'
if Jail.unjail_player(action_player, player_name) then
game.print{'expcom-jail.remove', action_player_name_color, by_player_name_color}
else
return Commands.error{'expcom-jail.not-jailed', action_player_name_color}
end
end)
Commands.new_command("unjail", { "expcom-jail.description-unjail" }, "Removes a player from jail.")
:add_param("player", false, "player-role")
:add_alias("clear-jail", "remove-jail")
:enable_auto_concat()
:register(function(player, action_player)
local action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(player)
local player_name = player and player.name or "<server>"
if Jail.unjail_player(action_player, player_name) then
game.print{ "expcom-jail.remove", action_player_name_color, by_player_name_color }
else
return Commands.error{ "expcom-jail.not-jailed", action_player_name_color }
end
end)

View File

@@ -11,26 +11,24 @@ require("modules.exp_legacy.config.expcore.command_role_parse")
--- Kills yourself or another player.
-- @command kill
-- @tparam[opt=self] LuaPlayer player the player to kill, must be alive to be valid
Commands.new_command('kill', {'expcom-kill.description'}, 'Kills yourself or another player.')
:add_param('player', true, 'player-role-alive')
:set_defaults{player=function(player)
-- default is the player unless they are dead
if player.character and player.character.health > 0 then
return player
end
end}
:register(function(player, action_player)
if not action_player then
-- can only be nil if no player given and the user is dead
return Commands.error{'expcom-kill.already-dead'}
end
if player == action_player then
action_player.character.die()
elseif Roles.player_allowed(player, 'command/kill/always') then
action_player.character.die()
else
return Commands.error{'expcore-commands.unauthorized'}
end
end)
Commands.new_command("kill", { "expcom-kill.description" }, "Kills yourself or another player.")
:add_param("player", true, "player-role-alive")
:set_defaults{ player = function(player)
-- default is the player unless they are dead
if player.character and player.character.health > 0 then
return player
end
end }
:register(function(player, action_player)
if not action_player then
-- can only be nil if no player given and the user is dead
return Commands.error{ "expcom-kill.already-dead" }
end
if player == action_player then
action_player.character.die()
elseif Roles.player_allowed(player, "command/kill/always") then
action_player.character.die()
else
return Commands.error{ "expcore-commands.unauthorized" }
end
end)

View File

@@ -10,10 +10,10 @@ require("modules.exp_legacy.config.expcore.command_general_parse")
--- Get the last location of a player.
-- @command last-location
-- @tparam LuaPlayer player the player that you want a location of
Commands.new_command('last-location', {'expcom-lastlocation.description'}, 'Sends you the last location of a player')
:add_alias('location')
:add_param('player', false, 'player')
:register(function(_, action_player)
local action_player_name_color = format_chat_player_name(action_player)
return Commands.success{'expcom-lastlocation.response', action_player_name_color, string.format('%.1f', action_player.position.x), string.format('%.1f', action_player.position.y)}
end)
Commands.new_command("last-location", { "expcom-lastlocation.description" }, "Sends you the last location of a player")
:add_alias("location")
:add_param("player", false, "player")
:register(function(_, action_player)
local action_player_name_color = format_chat_player_name(action_player)
return Commands.success{ "expcom-lastlocation.response", action_player_name_color, string.format("%.1f", action_player.position.x), string.format("%.1f", action_player.position.y) }
end)

View File

@@ -8,10 +8,10 @@ local Commands = require("modules.exp_legacy.expcore.commands") --- @dep expcore
--- Sends an action message in the chat
-- @command me
-- @tparam string action the action that follows your name in chat
Commands.new_command('me', {'expcom-me.description'}, 'Sends an action message in the chat')
:add_param('action', false)
:enable_auto_concat()
:register(function(player, action)
local player_name = player and player.name or '<Server>'
game.print(string.format('* %s %s *', player_name, action), player.chat_color)
end)
Commands.new_command("me", { "expcom-me.description" }, "Sends an action message in the chat")
:add_param("action", false)
:enable_auto_concat()
:register(function(player, action)
local player_name = player and player.name or "<Server>"
game.print(string.format("* %s %s *", player_name, action), player.chat_color)
end)

View File

@@ -6,29 +6,29 @@
local Commands = require("modules.exp_legacy.expcore.commands") --- @dep expcore.commands
require("modules.exp_legacy.config.expcore.command_general_parse")
Commands.new_command('pollution-clear', {'expcom-pol.description-clr'}, 'Clear pollution')
:set_flag('admin_only')
:add_alias('pol-clr')
:add_param('surface', true, 'surface')
:set_defaults{surface=function(player)
return player.surface
end}
:register(function(player, surface)
surface.clear_pollution()
game.print{'expcom-pol.clr', player.name}
return Commands.success
end)
Commands.new_command("pollution-clear", { "expcom-pol.description-clr" }, "Clear pollution")
:set_flag("admin_only")
:add_alias("pol-clr")
:add_param("surface", true, "surface")
:set_defaults{ surface = function(player)
return player.surface
end }
:register(function(player, surface)
surface.clear_pollution()
game.print{ "expcom-pol.clr", player.name }
return Commands.success
end)
Commands.new_command('pollution-off', {'expcom-pol.description-off'}, 'Disable pollution')
:set_flag('admin_only')
:add_alias('pol-off')
:register(function(player)
game.map_settings.pollution.enabled = false
Commands.new_command("pollution-off", { "expcom-pol.description-off" }, "Disable pollution")
:set_flag("admin_only")
:add_alias("pol-off")
:register(function(player)
game.map_settings.pollution.enabled = false
for _, v in pairs(game.surfaces) do
v.clear_pollution()
end
for _, v in pairs(game.surfaces) do
v.clear_pollution()
end
game.print{'expcom-pol.off', player.name}
return Commands.success
end)
game.print{ "expcom-pol.off", player.name }
return Commands.success
end)

View File

@@ -11,12 +11,12 @@ local format_chat_player_name = _C.format_chat_player_name --- @dep expcore.comm
local EntityProtection = require("modules.exp_legacy.modules.control.protection") --- @dep modules.control.protection
local Selection = require("modules.exp_legacy.modules.control.selection") --- @dep modules.control.selection
local SelectionProtectEntity = 'ProtectEntity'
local SelectionProtectArea = 'ProtectArea'
local SelectionProtectEntity = "ProtectEntity"
local SelectionProtectArea = "ProtectArea"
local renders = {} -- Stores all renders for a player
Storage.register({
renders = renders
renders = renders,
}, function(tbl)
renders = tbl.renders
end)
@@ -36,19 +36,19 @@ end
--- Align an aabb to the grid by expanding it
local function aabb_align_expand(aabb)
return {
left_top = {x = math.floor(aabb.left_top.x), y = math.floor(aabb.left_top.y)},
right_bottom = {x = math.ceil(aabb.right_bottom.x), y = math.ceil(aabb.right_bottom.y)}
left_top = { x = math.floor(aabb.left_top.x), y = math.floor(aabb.left_top.y) },
right_bottom = { x = math.ceil(aabb.right_bottom.x), y = math.ceil(aabb.right_bottom.y) },
}
end
--- Get the key used in protected_entities
local function get_entity_key(entity)
return string.format('%i,%i', math.floor(entity.position.x), math.floor(entity.position.y))
return string.format("%i,%i", math.floor(entity.position.x), math.floor(entity.position.y))
end
--- Get the key used in protected_areas
local function get_area_key(area)
return string.format('%i,%i', math.floor(area.left_top.x), math.floor(area.left_top.y))
return string.format("%i,%i", math.floor(area.left_top.x), math.floor(area.left_top.y))
end
--- Show a protected entity to a player
@@ -57,16 +57,16 @@ local function show_protected_entity(player, entity)
if renders[player.index][key] then return end
local rb = entity.selection_box.right_bottom
local render_id = rendering.draw_sprite{
sprite = 'utility/notification',
sprite = "utility/notification",
target = entity,
target_offset = {
(rb.x-entity.position.x)*0.75,
(rb.y-entity.position.y)*0.75
(rb.x - entity.position.x) * 0.75,
(rb.y - entity.position.y) * 0.75,
},
x_scale = 2,
y_scale = 2,
surface = entity.surface,
players = { player }
players = { player },
}
renders[player.index][key] = render_id
end
@@ -76,13 +76,13 @@ local function show_protected_area(player, surface, area)
local key = get_area_key(area)
if renders[player.index][key] then return end
local render_id = rendering.draw_rectangle{
color = {1, 1, 0, 0.5},
color = { 1, 1, 0, 0.5 },
filled = false,
width = 3,
left_top = area.left_top,
right_bottom = area.right_bottom,
surface = surface,
players = { player }
players = { player },
}
renders[player.index][key] = render_id
end
@@ -96,29 +96,29 @@ end
--- Toggles entity protection selection
-- @command protect-entity
Commands.new_command('protect-entity', {'expcom-protection.description-pe'}, 'Toggles entity protection selection, hold shift to remove protection')
:add_alias('pe')
:register(function(player)
if Selection.is_selecting(player, SelectionProtectEntity) then
Selection.stop(player)
else
Selection.start(player, SelectionProtectEntity)
return Commands.success{'expcom-protection.entered-entity-selection'}
end
end)
Commands.new_command("protect-entity", { "expcom-protection.description-pe" }, "Toggles entity protection selection, hold shift to remove protection")
:add_alias("pe")
:register(function(player)
if Selection.is_selecting(player, SelectionProtectEntity) then
Selection.stop(player)
else
Selection.start(player, SelectionProtectEntity)
return Commands.success{ "expcom-protection.entered-entity-selection" }
end
end)
--- Toggles area protection selection
-- @command protect-area
Commands.new_command('protect-area', {'expcom-protection.description-pa'}, 'Toggles area protection selection, hold shift to remove protection')
:add_alias('pa')
:register(function(player)
if Selection.is_selecting(player, SelectionProtectArea) then
Selection.stop(player)
else
Selection.start(player, SelectionProtectArea)
return Commands.success{'expcom-protection.entered-area-selection'}
end
end)
Commands.new_command("protect-area", { "expcom-protection.description-pa" }, "Toggles area protection selection, hold shift to remove protection")
:add_alias("pa")
:register(function(player)
if Selection.is_selecting(player, SelectionProtectArea) then
Selection.stop(player)
else
Selection.start(player, SelectionProtectArea)
return Commands.success{ "expcom-protection.entered-area-selection" }
end
end)
--- When an area is selected to add protection to entities
Selection.on_selection(SelectionProtectEntity, function(event)
@@ -127,7 +127,8 @@ Selection.on_selection(SelectionProtectEntity, function(event)
EntityProtection.add_entity(entity)
show_protected_entity(player, entity)
end
player.print{'expcom-protection.protected-entities', #event.entities}
player.print{ "expcom-protection.protected-entities", #event.entities }
end)
--- When an area is selected to remove protection from entities
@@ -137,7 +138,8 @@ Selection.on_alt_selection(SelectionProtectEntity, function(event)
EntityProtection.remove_entity(entity)
remove_render(player, get_entity_key(entity))
end
player.print{'expcom-protection.unprotected-entities', #event.entities}
player.print{ "expcom-protection.unprotected-entities", #event.entities }
end)
--- When an area is selected to add protection to the area
@@ -147,12 +149,13 @@ Selection.on_selection(SelectionProtectArea, function(event)
local player = game.get_player(event.player_index)
for _, next_area in pairs(areas) do
if aabb_area_enclosed(area, next_area) then
return player.print{'expcom-protection.already-protected'}
return player.print{ "expcom-protection.already-protected" }
end
end
EntityProtection.add_area(event.surface, area)
show_protected_area(player, event.surface, area)
player.print{'expcom-protection.protected-area'}
player.print{ "expcom-protection.protected-area" }
end)
--- When an area is selected to remove protection from the area
@@ -163,7 +166,7 @@ Selection.on_alt_selection(SelectionProtectArea, function(event)
for _, next_area in pairs(areas) do
if aabb_area_enclosed(next_area, area) then
EntityProtection.remove_area(event.surface, next_area)
player.print{'expcom-protection.unprotected-area'}
player.print{ "expcom-protection.unprotected-area" }
remove_render(player, get_area_key(next_area))
end
end
@@ -180,6 +183,7 @@ Event.add(Selection.events.on_player_selection_start, function(event)
for _, entity in pairs(entities) do
show_protected_entity(player, entity)
end
-- Show always protected entities by name
if #EntityProtection.protected_entity_names > 0 then
for _, entity in pairs(surface.find_entities_filtered{ name = EntityProtection.protected_entity_names, force = player.force }) do
@@ -205,11 +209,12 @@ Event.add(Selection.events.on_player_selection_end, function(event)
for _, id in pairs(renders[event.player_index]) do
if rendering.is_valid(id) then rendering.destroy(id) end
end
renders[event.player_index] = nil
end)
--- When there is a repeat offence print it in chat
Event.add(EntityProtection.events.on_repeat_violation, function(event)
local player_name = format_chat_player_name(event.player_index)
Roles.print_to_roles_higher('Regular', {'expcom-protection.repeat-offence', player_name, event.entity.localised_name, event.entity.position.x, event.entity.position.y})
Roles.print_to_roles_higher("Regular", { "expcom-protection.repeat-offence", player_name, event.entity.localised_name, event.entity.position.x, event.entity.position.y })
end)

View File

@@ -8,9 +8,9 @@ local format_chat_colour = _C.format_chat_colour --- @dep expcore.common
local function step_component(c1, c2)
if c1 < 0 then
return 0, c2+c1
return 0, c2 + c1
elseif c1 > 1 then
return 1, c2-c1+1
return 1, c2 - c1 + 1
else
return c1, c2
end
@@ -25,17 +25,17 @@ local function step_color(color)
end
local function next_color(color, step)
step = step or 0.1
local new_color = {r=0, g=0, b=0}
step = step or 0.1
local new_color = { r = 0, g = 0, b = 0 }
if color.b == 0 and color.r ~= 0 then
new_color.r = color.r-step
new_color.g = color.g+step
new_color.r = color.r - step
new_color.g = color.g + step
elseif color.r == 0 and color.g ~= 0 then
new_color.g = color.g-step
new_color.b = color.b+step
new_color.g = color.g - step
new_color.b = color.b + step
elseif color.g == 0 and color.b ~= 0 then
new_color.b = color.b-step
new_color.r = color.r+step
new_color.b = color.b - step
new_color.r = color.r + step
end
return step_color(new_color)
end
@@ -43,20 +43,20 @@ end
--- Sends an rainbow message in the chat
-- @command rainbow
-- @tparam string message the message that will be printed in chat
Commands.new_command('rainbow', {'expcom-rainbow.description'}, 'Sends an rainbow message in the chat')
:add_param('message', false)
:enable_auto_concat()
:register(function(player, message)
local player_name = player and player.name or '<Server>'
local player_color = player and player.color or nil
local color_step = 3/message:len()
if color_step > 1 then color_step = 1 end
local current_color = {r=1, g=0, b=0}
local output = format_chat_colour(player_name..': ', player_color)
output = output..message:gsub('%S', function(letter)
local rtn = format_chat_colour(letter, current_color)
current_color = next_color(current_color, color_step)
return rtn
Commands.new_command("rainbow", { "expcom-rainbow.description" }, "Sends an rainbow message in the chat")
:add_param("message", false)
:enable_auto_concat()
:register(function(player, message)
local player_name = player and player.name or "<Server>"
local player_color = player and player.color or nil
local color_step = 3 / message:len()
if color_step > 1 then color_step = 1 end
local current_color = { r = 1, g = 0, b = 0 }
local output = format_chat_colour(player_name .. ": ", player_color)
output = output .. message:gsub("%S", function(letter)
local rtn = format_chat_colour(letter, current_color)
current_color = next_color(current_color, color_step)
return rtn
end)
game.print(output)
end)
game.print(output)
end)

View File

@@ -1,86 +1,83 @@
local Commands = require("modules.exp_legacy.expcore.commands")
local function Modules(moduleInventory) -- returns the multiplier of the modules
local effect1 = moduleInventory.get_item_count("productivity-module") -- type 1
local effect2 = moduleInventory.get_item_count("productivity-module-2")-- type 2
local effect2 = moduleInventory.get_item_count("productivity-module-2") -- type 2
local effect3 = moduleInventory.get_item_count("productivity-module-3") -- type 3
local multi = effect1*4+effect2*6+effect3*10
return multi/100+1
local multi = effect1 * 4 + effect2 * 6 + effect3 * 10
return multi / 100 + 1
end
local function AmountOfMachines(itemsPerSecond, output)
if(itemsPerSecond) then
return itemsPerSecond/output
if (itemsPerSecond) then
return itemsPerSecond / output
end
end
Commands.new_command('ratio', {'expcom-ratio.description'}, 'This command will give the input and output ratios of the selected machine. Use the parameter for calculating the machines needed for that amount of items per second.')
:add_param('itemsPerSecond', true, 'number')
:register(function(player, itemsPerSecond)
local machine = player.selected -- selected machine
Commands.new_command("ratio", { "expcom-ratio.description" },
"This command will give the input and output ratios of the selected machine. Use the parameter for calculating the machines needed for that amount of items per second.")
:add_param("itemsPerSecond", true, "number")
:register(function(player, itemsPerSecond)
local machine = player.selected -- selected machine
if not machine then --nil check
return Commands.error{'expcom-ratio.notSelecting'}
end
if machine.type ~= "assembling-machine" and machine.type ~= "furnace" then
return Commands.error{'expcom-ratio.notSelecting'}
end
local recipe = machine.get_recipe() -- recipe
if not recipe then --nil check
return Commands.error{'expcom-ratio.notSelecting'}
end
local items = recipe.ingredients -- items in that recipe
local products = recipe.products -- output items
local amountOfMachines
local moduleInventory = machine.get_module_inventory()--the module Inventory of the machine
local multi = Modules(moduleInventory) --function for the productively modals
if itemsPerSecond then
amountOfMachines = math.ceil( AmountOfMachines(itemsPerSecond, 1/recipe.energy*machine.crafting_speed*products[1].amount*multi)) -- amount of machines
end
if not amountOfMachines then
amountOfMachines = 1 --set to 1 to make it not nil
end
----------------------------items----------------------------
for i, item in ipairs(items) do
local sprite -- string to make the icon work either fluid ore item
if item.type == "item" then
sprite = 'expcom-ratio.item-in'
else
sprite = 'expcom-ratio.fluid-in'
if not machine then -- nil check
return Commands.error{ "expcom-ratio.notSelecting" }
end
local ips = item.amount/recipe.energy*machine.crafting_speed*amountOfMachines --math on the items/fluids per second
Commands.print{sprite, math.round(ips, 3), item.name} -- full string
end
----------------------------products----------------------------
for i, product in ipairs(products) do
local sprite -- string to make the icon work either fluid ore item
if product.type == "item" then
sprite = 'expcom-ratio.item-out'
else
sprite = 'expcom-ratio.fluid-out'
if machine.type ~= "assembling-machine" and machine.type ~= "furnace" then
return Commands.error{ "expcom-ratio.notSelecting" }
end
local output = 1/recipe.energy*machine.crafting_speed*product.amount*multi --math on the outputs per second
Commands.print {sprite, math.round(output*amountOfMachines, 3), product.name} -- full string
local recipe = machine.get_recipe() -- recipe
end
if not recipe then -- nil check
return Commands.error{ "expcom-ratio.notSelecting" }
end
if amountOfMachines ~= 1 then
Commands.print{'expcom-ratio.machines', amountOfMachines}
end
end)
local items = recipe.ingredients -- items in that recipe
local products = recipe.products -- output items
local amountOfMachines
local moduleInventory = machine.get_module_inventory() -- the module Inventory of the machine
local multi = Modules(moduleInventory) -- function for the productively modals
if itemsPerSecond then
amountOfMachines = math.ceil(AmountOfMachines(itemsPerSecond, 1 / recipe.energy * machine.crafting_speed * products[1].amount * multi)) -- amount of machines
end
if not amountOfMachines then
amountOfMachines = 1 -- set to 1 to make it not nil
end
----------------------------items----------------------------
for i, item in ipairs(items) do
local sprite -- string to make the icon work either fluid ore item
if item.type == "item" then
sprite = "expcom-ratio.item-in"
else
sprite = "expcom-ratio.fluid-in"
end
local ips = item.amount / recipe.energy * machine.crafting_speed * amountOfMachines -- math on the items/fluids per second
Commands.print{ sprite, math.round(ips, 3), item.name } -- full string
end
----------------------------products----------------------------
for i, product in ipairs(products) do
local sprite -- string to make the icon work either fluid ore item
if product.type == "item" then
sprite = "expcom-ratio.item-out"
else
sprite = "expcom-ratio.fluid-out"
end
local output = 1 / recipe.energy * machine.crafting_speed * product.amount * multi -- math on the outputs per second
Commands.print{ sprite, math.round(output * amountOfMachines, 3), product.name } -- full string
end
if amountOfMachines ~= 1 then
Commands.print{ "expcom-ratio.machines", amountOfMachines }
end
end)

View File

@@ -11,42 +11,42 @@ local max_time_to_live = 4294967295 -- unit32 max
--- Repairs entities on your force around you
-- @command repair
-- @tparam number range the range to repair stuff in, there is a max limit to this
Commands.new_command('repair', {'expcom-repair.description'}, 'Repairs entities on your force around you')
:add_param('range', false, 'integer-range', 1, config.max_range)
:register(function(player, range)
local revive_count = 0
local heal_count = 0
local range2 = range^2
local surface = player.surface
local center = player.position
local area = {{x=center.x-range, y=center.y-range}, {x=center.x+range, y=center.y+range}}
if config.allow_ghost_revive then
local ghosts = surface.find_entities_filtered({area=area, type='entity-ghost', force=player.force})
for _, ghost in pairs(ghosts) do
if ghost.valid then
local x = ghost.position.x-center.x
local y = ghost.position.y-center.y
if x^2+y^2 <= range2 then
if config.allow_blueprint_repair or ghost.time_to_live ~= max_time_to_live then
revive_count = revive_count+1
if not config.disallow[ghost.ghost_name] then ghost.revive() end
Commands.new_command("repair", { "expcom-repair.description" }, "Repairs entities on your force around you")
:add_param("range", false, "integer-range", 1, config.max_range)
:register(function(player, range)
local revive_count = 0
local heal_count = 0
local range2 = range ^ 2
local surface = player.surface
local center = player.position
local area = { { x = center.x - range, y = center.y - range }, { x = center.x + range, y = center.y + range } }
if config.allow_ghost_revive then
local ghosts = surface.find_entities_filtered{ area = area, type = "entity-ghost", force = player.force }
for _, ghost in pairs(ghosts) do
if ghost.valid then
local x = ghost.position.x - center.x
local y = ghost.position.y - center.y
if x ^ 2 + y ^ 2 <= range2 then
if config.allow_blueprint_repair or ghost.time_to_live ~= max_time_to_live then
revive_count = revive_count + 1
if not config.disallow[ghost.ghost_name] then ghost.revive() end
end
end
end
end
end
end
if config.allow_heal_entities then
local entities = surface.find_entities_filtered({area=area, force=player.force})
for _, entity in pairs(entities) do
if entity.valid then
local x = entity.position.x-center.x
local y = entity.position.y-center.y
if entity.health and entity.get_health_ratio() ~= 1 and x^2+y^2 <= range2 then
heal_count = heal_count+1
entity.health = max_time_to_live
if config.allow_heal_entities then
local entities = surface.find_entities_filtered{ area = area, force = player.force }
for _, entity in pairs(entities) do
if entity.valid then
local x = entity.position.x - center.x
local y = entity.position.y - center.y
if entity.health and entity.get_health_ratio() ~= 1 and x ^ 2 + y ^ 2 <= range2 then
heal_count = heal_count + 1
entity.health = max_time_to_live
end
end
end
end
end
return Commands.success{'expcom-repair.result', revive_count, heal_count}
end)
return Commands.success{ "expcom-repair.result", revive_count, heal_count }
end)

View File

@@ -6,7 +6,7 @@
local Roles = require("modules.exp_legacy.expcore.roles") --- @dep expcore.roles
local Commands = require("modules.exp_legacy.expcore.commands") --- @dep expcore.commands
local Reports = require("modules.exp_legacy.modules.control.reports") --- @dep modules.control.reports
local format_chat_player_name = _C.format_chat_player_name--- @dep expcore.common
local format_chat_player_name = _C.format_chat_player_name --- @dep expcore.common
require("modules.exp_legacy.config.expcore.command_general_parse")
--- Print a message to all players who match the value of admin
@@ -22,76 +22,77 @@ end
-- @command report
-- @tparam LuaPlayer player the player to report, some players are immune
-- @tparam string reason the reason the player is being reported
Commands.new_command('report', {'expcom-report.description-report'}, 'Reports a player and notifies moderators')
:add_param('player', false, function(input, player, reject)
input = Commands.parse('player', input, player, reject)
if not input then return end
if Roles.player_has_flag(input, 'report-immune') then
return reject{'expcom-report.player-immune'}
elseif player == input then
return reject{'expcom-report.self-report'}
else
return input
end
end)
:add_param('reason', false)
:add_alias('report-player')
:enable_auto_concat()
:register(function(player, action_player, reason)
local action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(player)
if Reports.report_player(action_player, player.name, reason) then
print_to_players(false, {'expcom-report.non-admin', action_player_name_color, reason})
print_to_players(true, {'expcom-report.admin', action_player_name_color, by_player_name_color, reason})
else
return Commands.error{'expcom-report.already-reported'}
end
end)
Commands.new_command("report", { "expcom-report.description-report" }, "Reports a player and notifies moderators")
:add_param("player", false, function(input, player, reject)
input = Commands.parse("player", input, player, reject)
if not input then return end
if Roles.player_has_flag(input, "report-immune") then
return reject{ "expcom-report.player-immune" }
elseif player == input then
return reject{ "expcom-report.self-report" }
else
return input
end
end)
:add_param("reason", false)
:add_alias("report-player")
:enable_auto_concat()
:register(function(player, action_player, reason)
local action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(player)
if Reports.report_player(action_player, player.name, reason) then
print_to_players(false, { "expcom-report.non-admin", action_player_name_color, reason })
print_to_players(true, { "expcom-report.admin", action_player_name_color, by_player_name_color, reason })
else
return Commands.error{ "expcom-report.already-reported" }
end
end)
--- Gets a list of all reports that a player has on them. If no player then lists all players and the number of reports on them.
-- @command get-reports
-- @tparam LuaPlayer player the player to get the report for
Commands.new_command('get-reports', {'expcom-report.description-get-reports'}, 'Gets a list of all reports that a player has on them. If no player then lists all players and the number of reports on them.')
:add_param('player', true, 'player')
:add_alias('reports', 'list-reports')
:register(function(_, player)
if player then
local reports = Reports.get_reports(player)
local player_name_color = format_chat_player_name(player)
Commands.print{'expcom-report.player-report-title', player_name_color}
for player_name, reason in pairs(reports) do
local by_player_name_color = format_chat_player_name(player_name)
Commands.print{'expcom-report.list', by_player_name_color, reason}
Commands.new_command("get-reports", { "expcom-report.description-get-reports" },
"Gets a list of all reports that a player has on them. If no player then lists all players and the number of reports on them.")
:add_param("player", true, "player")
:add_alias("reports", "list-reports")
:register(function(_, player)
if player then
local reports = Reports.get_reports(player)
local player_name_color = format_chat_player_name(player)
Commands.print{ "expcom-report.player-report-title", player_name_color }
for player_name, reason in pairs(reports) do
local by_player_name_color = format_chat_player_name(player_name)
Commands.print{ "expcom-report.list", by_player_name_color, reason }
end
else
local user_reports = Reports.user_reports
Commands.print{ "expcom-report.player-count-title" }
for player_name in pairs(user_reports) do
local player_name_color = format_chat_player_name(player_name)
local report_count = Reports.count_reports(player_name)
Commands.print{ "expcom-report.list", player_name_color, report_count }
end
end
else
local user_reports = Reports.user_reports
Commands.print{'expcom-report.player-count-title'}
for player_name in pairs(user_reports) do
local player_name_color = format_chat_player_name(player_name)
local report_count = Reports.count_reports(player_name)
Commands.print{'expcom-report.list', player_name_color, report_count}
end
end
end)
end)
--- Clears all reports from a player or just the report from one player.
-- @command clear-reports
-- @tparam LuaPlayer player the player to clear the report(s) from
-- @tparam[opt=all] LuaPlayer from-player remove only the report made by this player
Commands.new_command('clear-reports', {'expcom-report.description-clear-reports'}, 'Clears all reports from a player or just the report from one player.')
:add_param('player', false, 'player')
:add_param('from-player', true, 'player')
:register(function(player, action_player, from_player)
if from_player then
if not Reports.remove_report(action_player, from_player.name, player.name) then
return Commands.error{'expcom-report.not-reported'}
Commands.new_command("clear-reports", { "expcom-report.description-clear-reports" }, "Clears all reports from a player or just the report from one player.")
:add_param("player", false, "player")
:add_param("from-player", true, "player")
:register(function(player, action_player, from_player)
if from_player then
if not Reports.remove_report(action_player, from_player.name, player.name) then
return Commands.error{ "expcom-report.not-reported" }
end
else
if not Reports.remove_all(action_player, player.name) then
return Commands.error{ "expcom-report.not-reported" }
end
end
else
if not Reports.remove_all(action_player, player.name) then
return Commands.error{'expcom-report.not-reported'}
end
end
local action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(player)
game.print{'expcom-report.removed', action_player_name_color, by_player_name_color}
end)
local action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(player)
game.print{ "expcom-report.removed", action_player_name_color, by_player_name_color }
end)

View File

@@ -10,35 +10,35 @@ end)
local function res_queue(force, by_script)
local res_q = force.research_queue
local res = force.technologies['mining-productivity-4']
local res = force.technologies["mining-productivity-4"]
if #res_q < config.queue_amount then
for i=1, config.queue_amount - #res_q do
for i = 1, config.queue_amount - #res_q do
force.add_research(res)
if not (by_script) then
game.print{'expcom-res.inf-q', res.name, res.level + i}
game.print{ "expcom-res.inf-q", res.name, res.level + i }
end
end
end
end
Commands.new_command('auto-research', {'expcom-res.description-ares'}, 'Automatically queue up research')
:add_alias('ares')
:register(function(player)
research.res_queue_enable = not research.res_queue_enable
Commands.new_command("auto-research", { "expcom-res.description-ares" }, "Automatically queue up research")
:add_alias("ares")
:register(function(player)
research.res_queue_enable = not research.res_queue_enable
if research.res_queue_enable then
res_queue(player.force, true)
end
if research.res_queue_enable then
res_queue(player.force, true)
end
game.print{'expcom-res.res', player.name, research.res_queue_enable}
return Commands.success
end)
game.print{ "expcom-res.res", player.name, research.res_queue_enable }
return Commands.success
end)
Event.add(defines.events.on_research_finished, function(event)
if research.res_queue_enable then
if event.research.force.rockets_launched > 0 and event.research.force.technologies['mining-productivity-4'].level > 4 then
if event.research.force.rockets_launched > 0 and event.research.force.technologies["mining-productivity-4"].level > 4 then
res_queue(event.research.force, event.by_script)
end
end

View File

@@ -12,70 +12,68 @@ local format_chat_player_name, format_chat_colour_localized = _C.format_chat_pla
-- @command assign-role
-- @tparam LuaPlayer player the player to assign the role to
-- @tparam string role the name of the role to assign to the player, supports auto complete after enter
Commands.new_command('assign-role', {'expcom-roles.description-assign-role'}, 'Assigns a role to a player')
:add_param('player', false, 'player-role')
:add_param('role', false, 'role')
:set_flag('admin-only')
:add_alias('rpromote', 'assign', 'role', 'add-role')
:register(function(player, action_player, role)
local player_highest = Roles.get_player_highest_role(player)
Commands.new_command("assign-role", { "expcom-roles.description-assign-role" }, "Assigns a role to a player")
:add_param("player", false, "player-role")
:add_param("role", false, "role")
:set_flag("admin-only")
:add_alias("rpromote", "assign", "role", "add-role")
:register(function(player, action_player, role)
local player_highest = Roles.get_player_highest_role(player)
if player_highest.index < role.index then
Roles.assign_player(action_player, role, player.name)
else
return Commands.error{'expcom-roles.higher-role'}
end
end)
if player_highest.index < role.index then
Roles.assign_player(action_player, role, player.name)
else
return Commands.error{ "expcom-roles.higher-role" }
end
end)
--- Unassigns a role from a player
-- @command unassign-role
-- @tparam LuaPlayer player the player to unassign the role from
-- @tparam string role the name of the role to unassign from the player, supports auto complete after enter
Commands.new_command('unassign-role', {'expcom-roles.description-unassign-role'}, 'Unassigns a role from a player')
:add_param('player', false, 'player-role')
:add_param('role', false, 'role')
:set_flag('admin-only')
:add_alias('rdemote', 'unassign', 'rerole', 'remove-role')
:register(function(player, action_player, role)
local player_highest = Roles.get_player_highest_role(player)
Commands.new_command("unassign-role", { "expcom-roles.description-unassign-role" }, "Unassigns a role from a player")
:add_param("player", false, "player-role")
:add_param("role", false, "role")
:set_flag("admin-only")
:add_alias("rdemote", "unassign", "rerole", "remove-role")
:register(function(player, action_player, role)
local player_highest = Roles.get_player_highest_role(player)
if player_highest.index < role.index then
Roles.unassign_player(action_player, role, player.name)
else
return Commands.error{'expcom-roles.higher-role'}
end
end)
if player_highest.index < role.index then
Roles.unassign_player(action_player, role, player.name)
else
return Commands.error{ "expcom-roles.higher-role" }
end
end)
--- Lists all roles in they correct order
-- @command list-roles
-- @tparam[opt=all] LuaPlayer player list only the roles which this player has
Commands.new_command('list-roles', {'expcom-roles.description-list-roles'}, 'Lists all roles in they correct order')
:add_param('player', true, 'player')
:add_alias('lsroles', 'roles')
:register(function(_, player)
local roles = Roles.config.order
local message = {'expcom-roles.list'}
Commands.new_command("list-roles", { "expcom-roles.description-list-roles" }, "Lists all roles in they correct order")
:add_param("player", true, "player")
:add_alias("lsroles", "roles")
:register(function(_, player)
local roles = Roles.config.order
local message = { "expcom-roles.list" }
if player then
roles = Roles.get_player_roles(player)
end
for index, role in pairs(roles) do
role = Roles.get_role_from_any(role)
local colour = role.custom_color or Colours.white
local role_name = format_chat_colour_localized(role.name, colour)
if index == 1 then
message = {'expcom-roles.list', role_name}
if player then
local player_name_colour = format_chat_player_name(player)
message = {'expcom-roles.list-player', player_name_colour, role_name}
end
else
message = {'expcom-roles.list-element', message, role_name}
if player then
roles = Roles.get_player_roles(player)
end
end
return Commands.success(message)
end)
for index, role in pairs(roles) do
role = Roles.get_role_from_any(role)
local colour = role.custom_color or Colours.white
local role_name = format_chat_colour_localized(role.name, colour)
if index == 1 then
message = { "expcom-roles.list", role_name }
if player then
local player_name_colour = format_chat_player_name(player)
message = { "expcom-roles.list-player", player_name_colour, role_name }
end
else
message = { "expcom-roles.list-element", message, role_name }
end
end
return Commands.success(message)
end)

View File

@@ -12,19 +12,19 @@ require("modules.exp_legacy.config.expcore.command_general_parse")
--- Input parse for items by name
local function item_parse(input, _, reject)
if input == nil then return end
local lower_input = input:lower():gsub(' ', '-')
local lower_input = input:lower():gsub(" ", "-")
-- Simple Case - internal name is given
local item = prototypes.item[lower_input]
if item then return item end
-- Second Case - rich text is given
local item_name = input:match('%[item=([0-9a-z-]+)%]')
local item_name = input:match("%[item=([0-9a-z-]+)%]")
item = prototypes.item[item_name]
if item then return item end
-- No item found, we do not attempt to search all prototypes as this will be expensive
return reject{'expcom-inv-search.reject-item', lower_input}
return reject{ "expcom-inv-search.reject-item", lower_input }
end
--- Search all players for this item
@@ -37,7 +37,7 @@ local function search_players(players, item)
local item_count = player.get_item_count(item.name)
if item_count > 0 then
-- Add the player to the array as they have the item
found[head] = { player=player, count=item_count, online_time=player.online_time }
found[head] = { player = player, count = item_count, online_time = player.online_time }
head = head + 1
end
end
@@ -66,9 +66,10 @@ local function sort_players(players, func)
break
end
end
-- Insert the element, this can only be called when index <= 5
if not inserted then
sorted[#sorted+1] = player
sorted[#sorted + 1] = player
end
-- Update the threshold
if sorted[6] then
@@ -86,12 +87,12 @@ end
--- Display to the player the top players which were found
local function display_players(player, players, item)
player.print{'expcom-inv-search.results-heading', item.name}
player.print{ "expcom-inv-search.results-heading", item.name }
for index, data in ipairs(players) do
local player_name_color = format_chat_player_name(data.player)
local amount = format_number(data.count)
local time = format_time(data.online_time)
player.print{'expcom-inv-search.results-item', index, player_name_color, amount, time}
player.print{ "expcom-inv-search.results-item", index, player_name_color, amount, time }
end
end
@@ -103,16 +104,16 @@ end
--- Get a list of players sorted by the quantity of an item in their inventory
-- @command search-amount
-- @tparam LuaItemPrototype item The item to search for in players inventories
Commands.new_command('search-amount', {'expcom-inv-search.description-ia'}, 'Display players sorted by the quantity of an item held')
:add_alias('ia')
:add_param('item', false, item_parse)
:enable_auto_concat()
:register(function(player, item)
local players = search_players(game.players, item)
if #players == 0 then return {'expcom-inv-search.results-none', item.name} end
local top_players = sort_players(players, amount_sort)
display_players(player, top_players, item)
end)
Commands.new_command("search-amount", { "expcom-inv-search.description-ia" }, "Display players sorted by the quantity of an item held")
:add_alias("ia")
:add_param("item", false, item_parse)
:enable_auto_concat()
:register(function(player, item)
local players = search_players(game.players, item)
if #players == 0 then return { "expcom-inv-search.results-none", item.name } end
local top_players = sort_players(players, amount_sort)
display_players(player, top_players, item)
end)
--- Return the index of the player, higher means they joined more recently
local function recent_sort(data)
@@ -122,46 +123,46 @@ end
--- Get a list of players who have the given item, sorted by how recently they joined
-- @command search-recent
-- @tparam LuaItemPrototype item The item to search for in players inventories
Commands.new_command('search-recent', {'expcom-inv-search.description-ir'}, 'Display players who hold an item sorted by join time')
:add_alias('ir')
:add_param('item', false, item_parse)
:enable_auto_concat()
:register(function(player, item)
local players = search_players(game.players, item)
if #players == 0 then return {'expcom-inv-search.results-none', item.name} end
local top_players = sort_players(players, recent_sort)
display_players(player, top_players, item)
end)
Commands.new_command("search-recent", { "expcom-inv-search.description-ir" }, "Display players who hold an item sorted by join time")
:add_alias("ir")
:add_param("item", false, item_parse)
:enable_auto_concat()
:register(function(player, item)
local players = search_players(game.players, item)
if #players == 0 then return { "expcom-inv-search.results-none", item.name } end
local top_players = sort_players(players, recent_sort)
display_players(player, top_players, item)
end)
--- Return the the amount of an item a player has divided by their playtime
local function combined_sort(data)
return data.count/data.online_time
return data.count / data.online_time
end
--- Get a list of players sorted by quantity held and play time
-- @command search
-- @tparam LuaItemPrototype item The item to search for in players inventories
Commands.new_command('search', {'expcom-inv-search.description-i'}, 'Display players sorted by the quantity of an item held and playtime')
:add_alias('i')
:add_param('item', false, item_parse)
:enable_auto_concat()
:register(function(player, item)
local players = search_players(game.players, item)
if #players == 0 then return {'expcom-inv-search.results-none', item.name} end
local top_players = sort_players(players, combined_sort)
display_players(player, top_players, item)
end)
Commands.new_command("search", { "expcom-inv-search.description-i" }, "Display players sorted by the quantity of an item held and playtime")
:add_alias("i")
:add_param("item", false, item_parse)
:enable_auto_concat()
:register(function(player, item)
local players = search_players(game.players, item)
if #players == 0 then return { "expcom-inv-search.results-none", item.name } end
local top_players = sort_players(players, combined_sort)
display_players(player, top_players, item)
end)
--- Get a list of online players sorted by quantity held and play time
-- @command search-online
-- @tparam LuaItemPrototype item The item to search for in players inventories
Commands.new_command('search-online', {'expcom-inv-search.description-io'}, 'Display online players sorted by the quantity of an item held and playtime')
:add_alias('io')
:add_param('item', false, item_parse)
:enable_auto_concat()
:register(function(player, item)
local players = search_players(game.connected_players, item)
if #players == 0 then return {'expcom-inv-search.results-none', item.name} end
local top_players = sort_players(players, combined_sort)
display_players(player, top_players, item)
end)
Commands.new_command("search-online", { "expcom-inv-search.description-io" }, "Display online players sorted by the quantity of an item held and playtime")
:add_alias("io")
:add_param("item", false, item_parse)
:enable_auto_concat()
:register(function(player, item)
local players = search_players(game.connected_players, item)
if #players == 0 then return { "expcom-inv-search.results-none", item.name } end
local top_players = sort_players(players, combined_sort)
display_players(player, top_players, item)
end)

View File

@@ -9,7 +9,7 @@ local Roles = require("modules.exp_legacy.expcore.roles") --- @dep expcore.roles
local function teleport(player)
local surface = player.surface
local spawn = player.force.get_spawn_position(surface)
local position = surface.find_non_colliding_position('character', spawn, 32, 1)
local position = surface.find_non_colliding_position("character", spawn, 32, 1)
-- return false if no new position
if not position then
return false
@@ -39,29 +39,28 @@ end
--- Teleport to spawn
-- @command go-to-spawn
-- @tparam[opt=self] LuaPlayer player the player to teleport to their spawn point
Commands.new_command('go-to-spawn', {'expcom-spawn.description'}, 'Teleport to spawn')
:add_param('player', true, 'player-role-alive')
:set_defaults{
player=function(player)
if player.connected and player.character and player.character.health > 0 then
return player
Commands.new_command("go-to-spawn", { "expcom-spawn.description" }, "Teleport to spawn")
:add_param("player", true, "player-role-alive")
:set_defaults{
player = function(player)
if player.connected and player.character and player.character.health > 0 then
return player
end
end,
}
:add_alias("spawn", "tp-spawn")
:register(function(player, action_player)
if not action_player then
return Commands.error{ "expcom-spawn.unavailable" }
elseif action_player == player then
if not teleport(player) then
return Commands.error{ "expcom-spawn.unavailable" }
end
elseif Roles.player_allowed(player, "command/go-to-spawn/always") then
if not teleport(action_player) then
return Commands.error{ "expcom-spawn.unavailable" }
end
else
return Commands.error{ "expcore-commands.unauthorized" }
end
end
}
:add_alias('spawn', 'tp-spawn')
:register(function(player, action_player)
if not action_player then
return Commands.error{'expcom-spawn.unavailable'}
elseif action_player == player then
if not teleport(player) then
return Commands.error{'expcom-spawn.unavailable'}
end
elseif Roles.player_allowed(player, 'command/go-to-spawn/always') then
if not teleport(action_player) then
return Commands.error{'expcom-spawn.unavailable'}
end
else
return Commands.error{'expcore-commands.unauthorized'}
end
end)
end)

View File

@@ -9,26 +9,25 @@ require("modules.exp_legacy.config.expcore.command_general_parse")
--- Toggles spectator mode for the caller
-- @command spectate
Commands.new_command('spectate', {'expcom-spectate.description-spectate'}, 'Toggles spectator mode')
:register(function(player)
if Spectate.is_spectating(player) then
Spectate.stop_spectate(player)
else
Spectate.start_spectate(player)
end
end)
Commands.new_command("spectate", { "expcom-spectate.description-spectate" }, "Toggles spectator mode")
:register(function(player)
if Spectate.is_spectating(player) then
Spectate.stop_spectate(player)
else
Spectate.start_spectate(player)
end
end)
--- Enters follow mode for the caller, following the given player.
-- @command follow
-- @tparam LuaPlayer player The player that will be followed
Commands.new_command('follow', {'expcom-spectate.description-follow'}, 'Start following a player in spectator')
:add_alias('f')
:add_param('player', false, 'player-online')
:register(function(player, action_player)
if player == action_player then
return Commands.error{'expcom-spectate.follow-self'}
else
Spectate.start_follow(player, action_player)
end
end)
Commands.new_command("follow", { "expcom-spectate.description-follow" }, "Start following a player in spectator")
:add_alias("f")
:add_param("player", false, "player-online")
:register(function(player, action_player)
if player == action_player then
return Commands.error{ "expcom-spectate.follow-self" }
else
Spectate.start_follow(player, action_player)
end
end)

View File

@@ -6,11 +6,11 @@
local Commands = require("modules.exp_legacy.expcore.commands") --- @dep expcore.commands
require("modules.exp_legacy.config.expcore.command_general_parse")
Commands.new_command('game-speed', {'expcom-speed.description'}, 'Set game speed')
:add_param('amount', 'number-range', 0.2, 8)
:set_flag('admin_only')
:register(function(player, amount)
game.speed = math.round(amount, 3)
game.print{'expcom-speed.result', player.name, string.format('%.3f', amount)}
return Commands.success
end)
Commands.new_command("game-speed", { "expcom-speed.description" }, "Set game speed")
:add_param("amount", "number-range", 0.2, 8)
:set_flag("admin_only")
:register(function(player, amount)
game.speed = math.round(amount, 3)
game.print{ "expcom-speed.result", player.name, string.format("%.3f", amount) }
return Commands.success
end)

View File

@@ -7,27 +7,27 @@ local copy_items_stack = _C.copy_items_stack --- @dep expcore.common
local Commands = require("modules.exp_legacy.expcore.commands") --- @dep expcore.commands
require("modules.exp_legacy.config.expcore.command_general_parse")
Commands.new_command('clear-item-on-ground', {'expcom-surface-clearing.description-ci'}, 'Clear Item On Ground')
:add_param('range', false, 'integer-range', 1, 1000)
:register(function(player, range)
for _, e in pairs(player.surface.find_entities_filtered{position=player.position, radius=range, name='item-on-ground'}) do
if e.stack then
-- calling move_items_stack(e.stack) will crash to desktop
-- https://forums.factorio.com/viewtopic.php?f=7&t=110322
copy_items_stack{e.stack}
e.stack.clear()
Commands.new_command("clear-item-on-ground", { "expcom-surface-clearing.description-ci" }, "Clear Item On Ground")
:add_param("range", false, "integer-range", 1, 1000)
:register(function(player, range)
for _, e in pairs(player.surface.find_entities_filtered{ position = player.position, radius = range, name = "item-on-ground" }) do
if e.stack then
-- calling move_items_stack(e.stack) will crash to desktop
-- https://forums.factorio.com/viewtopic.php?f=7&t=110322
copy_items_stack{ e.stack }
e.stack.clear()
end
end
end
return Commands.success
end)
return Commands.success
end)
Commands.new_command('clear-blueprint', {'expcom-surface-clearing.description-cb'}, 'Clear Blueprint')
:add_param('range', false, 'integer-range', 1, 1000)
:register(function(player, range)
for _, e in pairs(player.surface.find_entities_filtered{position=player.position, radius=range, type='entity-ghost'}) do
e.destroy()
end
Commands.new_command("clear-blueprint", { "expcom-surface-clearing.description-cb" }, "Clear Blueprint")
:add_param("range", false, "integer-range", 1, 1000)
:register(function(player, range)
for _, e in pairs(player.surface.find_entities_filtered{ position = player.position, radius = range, type = "entity-ghost" }) do
e.destroy()
end
return Commands.success
end)
return Commands.success
end)

View File

@@ -8,7 +8,7 @@ require("modules.exp_legacy.config.expcore.command_general_parse")
local function teleport(from_player, to_player)
local surface = to_player.surface
local position = surface.find_non_colliding_position('character', to_player.position, 32, 1)
local position = surface.find_non_colliding_position("character", to_player.position, 32, 1)
-- return false if no new position
if not position then
@@ -41,53 +41,53 @@ end
-- @command teleport
-- @tparam LuaPlayer from_player the player that will be teleported, must be alive
-- @tparam LuaPlayer to_player the player to teleport to, must be online (if dead goes to where they died)
Commands.new_command('teleport', {'expcom-tp.description-tp'}, 'Teleports a player to another player.')
:add_param('from_player', false, 'player-alive')
:add_param('to_player', false, 'player-online')
:add_alias('tp')
:set_flag('admin_only')
:register(function(_, from_player, to_player)
if from_player.index == to_player.index then
-- return if attempting to teleport to self
return Commands.error{'expcom-tp.to-self'}
end
if not teleport(from_player, to_player) then
-- return if the teleport failed
return Commands.error{'expcom-tp.no-position-found'}
end
end)
Commands.new_command("teleport", { "expcom-tp.description-tp" }, "Teleports a player to another player.")
:add_param("from_player", false, "player-alive")
:add_param("to_player", false, "player-online")
:add_alias("tp")
:set_flag("admin_only")
:register(function(_, from_player, to_player)
if from_player.index == to_player.index then
-- return if attempting to teleport to self
return Commands.error{ "expcom-tp.to-self" }
end
if not teleport(from_player, to_player) then
-- return if the teleport failed
return Commands.error{ "expcom-tp.no-position-found" }
end
end)
--- Teleports a player to you.
-- @command bring
-- @tparam LuaPlayer player the player that will be teleported, must be alive
Commands.new_command('bring', {'expcom-tp.description-bring'}, 'Teleports a player to you.')
:add_param('player', false, 'player-alive')
:set_flag('admin_only')
:register(function(player, from_player)
if from_player.index == player.index then
-- return if attempting to teleport to self
return Commands.error{'expcom-tp.to-self'}
end
if not teleport(from_player, player) then
-- return if the teleport failed
return Commands.error{'expcom-tp.no-position-found'}
end
from_player.print('Come here my friend')
end)
Commands.new_command("bring", { "expcom-tp.description-bring" }, "Teleports a player to you.")
:add_param("player", false, "player-alive")
:set_flag("admin_only")
:register(function(player, from_player)
if from_player.index == player.index then
-- return if attempting to teleport to self
return Commands.error{ "expcom-tp.to-self" }
end
if not teleport(from_player, player) then
-- return if the teleport failed
return Commands.error{ "expcom-tp.no-position-found" }
end
from_player.print("Come here my friend")
end)
--- Teleports you to a player.
-- @command goto
-- @tparam LuaPlayer player the player to teleport to, must be online (if dead goes to where they died)
Commands.new_command('goto', {'expcom-tp.description-goto'}, 'Teleports you to a player.')
:add_param('player', false, 'player-online')
:add_alias('tp-me', 'tpme')
:register(function(player, to_player)
if to_player.index == player.index then
-- return if attempting to teleport to self
return Commands.error{'expcom-tp.to-self'}
end
if not teleport(player, to_player) then
-- return if the teleport failed
return Commands.error{'expcom-tp.no-position-found'}
end
end)
Commands.new_command("goto", { "expcom-tp.description-goto" }, "Teleports you to a player.")
:add_param("player", false, "player-online")
:add_alias("tp-me", "tpme")
:register(function(player, to_player)
if to_player.index == player.index then
-- return if attempting to teleport to self
return Commands.error{ "expcom-tp.to-self" }
end
if not teleport(player, to_player) then
-- return if the teleport failed
return Commands.error{ "expcom-tp.no-position-found" }
end
end)

View File

@@ -7,17 +7,17 @@ local Commands = require("modules.exp_legacy.expcore.commands") --- @dep expcore
require("modules.exp_legacy.config.expcore.command_general_parse")
local format_number = require("util").format_number
Commands.new_command('set-trains-to-automatic', {'expcom-train.description'}, 'Set All Trains to Automatic')
:register(function(player)
local count = 0
Commands.new_command("set-trains-to-automatic", { "expcom-train.description" }, "Set All Trains to Automatic")
:register(function(player)
local count = 0
for _, v in pairs(player.force.get_trains()) do
if v.manual_mode then
count = count + 1
v.manual_mode = false
for _, v in pairs(player.force.get_trains()) do
if v.manual_mode then
count = count + 1
v.manual_mode = false
end
end
end
game.print{'expcom-train.manual-result', player.name, format_number(count)}
return Commands.success
end)
game.print{ "expcom-train.manual-result", player.name, format_number(count) }
return Commands.success
end)

View File

@@ -5,11 +5,11 @@ local Commands = require("modules.exp_legacy.expcore.commands") --- @dep expcore
require("modules.exp_legacy.config.expcore.command_general_parse")
local vlayer = require("modules.exp_legacy.modules.control.vlayer")
Commands.new_command('vlayer-info', {'vlayer.description-vi'}, 'Vlayer Info')
:register(function(_)
local c = vlayer.get_circuits()
Commands.new_command("vlayer-info", { "vlayer.description-vi" }, "Vlayer Info")
:register(function(_)
local c = vlayer.get_circuits()
for k, v in pairs(c) do
Commands.print(v .. ' : ' .. k)
end
end)
for k, v in pairs(c) do
Commands.print(v .. " : " .. k)
end
end)

View File

@@ -13,62 +13,64 @@ require("modules.exp_legacy.config.expcore.command_role_parse")
-- @command give-warning
-- @tparam LuaPlayer player the player the will recive a warning
-- @tparam string reason the reason the player is being given a warning
Commands.new_command('give-warning', {'expcom-warnings.description-give'}, 'Gives a warning to a player; may lead to automatic script action.')
:add_param('player', false, 'player-role')
:add_param('reason', false)
:add_alias('warn')
:enable_auto_concat()
:register(function(player, action_player, reason)
Warnings.add_warning(action_player, player.name, reason)
local action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(player)
game.print{'expcom-warnings.received', action_player_name_color, by_player_name_color, reason}
end)
Commands.new_command("give-warning", { "expcom-warnings.description-give" }, "Gives a warning to a player; may lead to automatic script action.")
:add_param("player", false, "player-role")
:add_param("reason", false)
:add_alias("warn")
:enable_auto_concat()
:register(function(player, action_player, reason)
Warnings.add_warning(action_player, player.name, reason)
local action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(player)
game.print{ "expcom-warnings.received", action_player_name_color, by_player_name_color, reason }
end)
--- Gets the number of warnings a player has. If no player then lists all players and the number of warnings they have.
-- @command get-warnings
-- @tparam[opt=list] LuaPlayer player the player to get the warning for, if nil all players are listed
Commands.new_command('get-warnings', {'expcom-warnings.description-get'}, 'Gets the number of warnings a player has. If no player then lists all players and the number of warnings they have.')
:add_param('player', true, 'player')
:add_alias('warnings', 'list-warnings')
:register(function(_, player)
if player then
local warnings = Warnings.get_warnings(player)
local script_warnings = Warnings.get_script_warnings(player)
local player_name_color = format_chat_player_name(player)
Commands.print{'expcom-warnings.player', player_name_color, #warnings, #script_warnings, config.temp_warning_limit}
for _, warning in ipairs(warnings) do
Commands.print{'expcom-warnings.player-detail', format_chat_player_name(warning.by_player_name), warning.reason}
end
else
local rtn = {}
local user_script_warnings = Warnings.user_script_warnings
for player_name, warnings in pairs(Warnings.user_warnings:get_all()) do
rtn[player_name] = {#warnings, 0}
end
for player_name, warnings in pairs(user_script_warnings) do
if not rtn[player_name] then
rtn[player_name] = {0, 0}
Commands.new_command("get-warnings", { "expcom-warnings.description-get" }, "Gets the number of warnings a player has. If no player then lists all players and the number of warnings they have.")
:add_param("player", true, "player")
:add_alias("warnings", "list-warnings")
:register(function(_, player)
if player then
local warnings = Warnings.get_warnings(player)
local script_warnings = Warnings.get_script_warnings(player)
local player_name_color = format_chat_player_name(player)
Commands.print{ "expcom-warnings.player", player_name_color, #warnings, #script_warnings, config.temp_warning_limit }
for _, warning in ipairs(warnings) do
Commands.print{ "expcom-warnings.player-detail", format_chat_player_name(warning.by_player_name), warning.reason }
end
else
local rtn = {}
local user_script_warnings = Warnings.user_script_warnings
for player_name, warnings in pairs(Warnings.user_warnings:get_all()) do
rtn[player_name] = { #warnings, 0 }
end
for player_name, warnings in pairs(user_script_warnings) do
if not rtn[player_name] then
rtn[player_name] = { 0, 0 }
end
rtn[player_name][2] = #warnings
end
Commands.print{ "expcom-warnings.list-title" }
for player_name, warnings in pairs(rtn) do
local player_name_color = format_chat_player_name(player_name)
Commands.print{ "expcom-warnings.list", player_name_color, warnings[1], warnings[2], config.temp_warning_limit }
end
rtn[player_name][2] = #warnings
end
Commands.print{'expcom-warnings.list-title'}
for player_name, warnings in pairs(rtn) do
local player_name_color = format_chat_player_name(player_name)
Commands.print{'expcom-warnings.list', player_name_color, warnings[1], warnings[2], config.temp_warning_limit}
end
end
end)
end)
--- Clears all warnings (and script warnings) from a player
-- @command clear-warnings
-- @tparam LuaPlayer player the player to clear the warnings from
Commands.new_command('clear-warnings', {'expcom-warnings.description-clear'}, 'Clears all warnings (and script warnings) from a player')
:add_param('player', false, 'player')
:register(function(player, action_player)
Warnings.clear_warnings(action_player, player.name)
Warnings.clear_script_warnings(action_player)
local action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(player)
game.print{'expcom-warnings.cleared', action_player_name_color, by_player_name_color}
end)
Commands.new_command("clear-warnings", { "expcom-warnings.description-clear" }, "Clears all warnings (and script warnings) from a player")
:add_param("player", false, "player")
:register(function(player, action_player)
Warnings.clear_warnings(action_player, player.name)
Warnings.clear_script_warnings(action_player)
local action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(player)
game.print{ "expcom-warnings.cleared", action_player_name_color, by_player_name_color }
end)

View File

@@ -4,33 +4,33 @@
local Commands = require("modules.exp_legacy.expcore.commands") --- @dep expcore.commands
require("modules.exp_legacy.config.expcore.command_general_parse")
local Selection = require("modules.exp_legacy.modules.control.selection") --- @dep modules.control.selection
local SelectionConvertArea = 'ConvertArea'
local SelectionConvertArea = "ConvertArea"
--- Align an aabb to the grid by expanding it
local function aabb_align_expand(aabb)
return {
left_top = {x = math.floor(aabb.left_top.x), y = math.floor(aabb.left_top.y)},
right_bottom = {x = math.ceil(aabb.right_bottom.x), y = math.ceil(aabb.right_bottom.y)}
left_top = { x = math.floor(aabb.left_top.x), y = math.floor(aabb.left_top.y) },
right_bottom = { x = math.ceil(aabb.right_bottom.x), y = math.ceil(aabb.right_bottom.y) },
}
end
Commands.new_command('waterfill', {'expcom-waterfill.description'}, 'Change tile to water')
:register(function(player)
local inv = player.get_main_inventory()
Commands.new_command("waterfill", { "expcom-waterfill.description" }, "Change tile to water")
:register(function(player)
local inv = player.get_main_inventory()
if (inv.get_item_count('cliff-explosives')) == 0 then
return player.print{'expcom-waterfill.waterfill-cliff'}
end
if (inv.get_item_count("cliff-explosives")) == 0 then
return player.print{ "expcom-waterfill.waterfill-cliff" }
end
if Selection.is_selecting(player, SelectionConvertArea) then
Selection.stop(player)
else
Selection.start(player, SelectionConvertArea)
return Commands.success{'expcom-waterfill.entered-area-selection'}
end
if Selection.is_selecting(player, SelectionConvertArea) then
Selection.stop(player)
else
Selection.start(player, SelectionConvertArea)
return Commands.success{ "expcom-waterfill.entered-area-selection" }
end
return Commands.success
end)
return Commands.success
end)
--- When an area is selected to add protection to the area
Selection.on_selection(SelectionConvertArea, function(event)
@@ -41,10 +41,10 @@ Selection.on_selection(SelectionConvertArea, function(event)
return
end
local entities = player.surface.find_entities_filtered{area=area, name='steel-chest'}
local entities = player.surface.find_entities_filtered{ area = area, name = "steel-chest" }
if #entities == 0 then
player.print('No steel chest found')
player.print("No steel chest found")
return
end
@@ -55,21 +55,21 @@ Selection.on_selection(SelectionConvertArea, function(event)
return
end
local clf_exp = inv.get_item_count('cliff-explosives')
local clf_exp = inv.get_item_count("cliff-explosives")
for _, entity in pairs(entities) do
if clf_exp >= 1 then
if entity.get_inventory(defines.inventory.chest).is_empty() then
if (math.floor(player.position.x) ~= math.floor(entity.position.x)) or (math.floor(player.position.y) ~= math.floor(entity.position.y)) then
table.insert(tiles_to_make, {name='water-mud', position=entity.position})
table.insert(tiles_to_make, { name = "water-mud", position = entity.position })
entity.destroy()
else
player.print{'expcom-waterfill.waterfill-distance'}
player.print{ "expcom-waterfill.waterfill-distance" }
end
end
clf_exp = clf_exp - 1
inv.remove({name='cliff-explosives', count=1})
inv.remove{ name = "cliff-explosives", count = 1 }
else
break
end

View File

@@ -33,13 +33,13 @@ local Jail = {
-- @tparam number player_index the index of the player who was jailed
-- @tparam string by_player_name the name of the player who jailed the other player
-- @tparam string reason the reason that the player was jailed
on_player_jailed=script.generate_event_name(),
on_player_jailed = script.generate_event_name(),
--- When a player is unassigned from jail
-- @event on_player_unjailed
-- @tparam number player_index the index of the player who was unjailed
-- @tparam string by_player_name the name of the player who unjailed the other player
on_player_unjailed=script.generate_event_name(),
}
on_player_unjailed = script.generate_event_name(),
},
}
--- Used to emit the jail related events
@@ -49,11 +49,11 @@ local Jail = {
-- @tparam string reason the reason for the action (jail)
local function event_emit(event, player, by_player_name, reason)
script.raise_event(event, {
name=event,
tick=game.tick,
player_index=player.index,
by_player_name=by_player_name,
reason=reason
name = event,
tick = game.tick,
player_index = player.index,
by_player_name = by_player_name,
reason = reason,
})
end
@@ -65,7 +65,7 @@ end
-- @tparam LuaPlayer player the player to check if they are in jail
-- @treturn boolean whether the player is currently in jail
function Jail.is_jailed(player)
return has_role(player, 'Jail')
return has_role(player, "Jail")
end
--- Moves a player to jail and removes all other roles
@@ -78,9 +78,9 @@ function Jail.jail_player(player, by_player_name, reason)
if not player then return end
if not by_player_name then return end
reason = reason or 'Non given.'
reason = reason or "Non given."
if has_role(player, 'Jail') then return end
if has_role(player, "Jail") then return end
local roles = get_roles(player)
player.walking_state = { walking = false, direction = player.walking_state.direction }
@@ -91,7 +91,7 @@ function Jail.jail_player(player, by_player_name, reason)
player.repair_state = { repairing = false, position = player.repair_state.position }
unassign_roles(player, roles, by_player_name, nil, true)
assign_roles(player, 'Jail', by_player_name, nil, true)
assign_roles(player, "Jail", by_player_name, nil, true)
assign_roles(player, roles, by_player_name, nil, true)
event_emit(Jail.events.on_player_jailed, player, by_player_name, reason)
@@ -108,9 +108,9 @@ function Jail.unjail_player(player, by_player_name)
if not player then return end
if not by_player_name then return end
if not has_role(player, 'Jail') then return end
if not has_role(player, "Jail") then return end
unassign_roles(player, 'Jail', by_player_name, nil, true)
unassign_roles(player, "Jail", by_player_name, nil, true)
event_emit(Jail.events.on_player_unjailed, player, by_player_name)

View File

@@ -47,13 +47,20 @@ local Production = {}
-- @treturn[1] defines.flow_precision_index the next precision value
-- @treturn[1] number the multiplicive difference between the values
function Production.precision_up(precision)
if precision == precision_index.five_seconds then return precision_index.one_minute, 60
elseif precision == precision_index.one_minute then return precision_index.ten_minutes, 10
elseif precision == precision_index.ten_minutes then return precision_index.one_hour, 6
elseif precision == precision_index.one_hour then return precision_index.ten_hours, 10
elseif precision == precision_index.ten_hours then return precision_index.fifty_hours, 5
elseif precision == precision_index.fifty_hours then return precision_index.two_hundred_fifty_hours, 5
elseif precision == precision_index.two_hundred_fifty_hours then return precision_index.one_thousand_hours, 4
if precision == precision_index.five_seconds then
return precision_index.one_minute, 60
elseif precision == precision_index.one_minute then
return precision_index.ten_minutes, 10
elseif precision == precision_index.ten_minutes then
return precision_index.one_hour, 6
elseif precision == precision_index.one_hour then
return precision_index.ten_hours, 10
elseif precision == precision_index.ten_hours then
return precision_index.fifty_hours, 5
elseif precision == precision_index.fifty_hours then
return precision_index.two_hundred_fifty_hours, 5
elseif precision == precision_index.two_hundred_fifty_hours then
return precision_index.one_thousand_hours, 4
end
end
@@ -62,13 +69,20 @@ end
-- @treturn[1] defines.flow_precision_index the next precision value
-- @treturn[1] number the multiplicive difference between the values
function Production.precision_down(precision)
if precision == precision_index.one_minute then return precision_index.five_seconds, 60
elseif precision == precision_index.ten_minutes then return precision_index.one_minute, 10
elseif precision == precision_index.one_hour then return precision_index.ten_minutes, 6
elseif precision == precision_index.ten_hours then return precision_index.one_hour, 10
elseif precision == precision_index.fifty_hours then return precision_index.ten_hours, 5
elseif precision == precision_index.two_hundred_fifty_hours then return precision_index.fifty_hours, 5
elseif precision == precision_index.one_thousand_hours then return precision_index.two_hundred_fifty_hours, 4
if precision == precision_index.one_minute then
return precision_index.five_seconds, 60
elseif precision == precision_index.ten_minutes then
return precision_index.one_minute, 10
elseif precision == precision_index.one_hour then
return precision_index.ten_minutes, 6
elseif precision == precision_index.ten_hours then
return precision_index.one_hour, 10
elseif precision == precision_index.fifty_hours then
return precision_index.ten_hours, 5
elseif precision == precision_index.two_hundred_fifty_hours then
return precision_index.fifty_hours, 5
elseif precision == precision_index.one_thousand_hours then
return precision_index.two_hundred_fifty_hours, 4
end
end
@@ -76,14 +90,22 @@ end
-- @tparam defines.flow_precision_index precision
-- @treturn number the number of ticks in this time
function Production.precision_ticks(precision)
if precision == precision_index.five_seconds then return 300
elseif precision == precision_index.one_minute then return 3600
elseif precision == precision_index.ten_minutes then return 36000
elseif precision == precision_index.one_hour then return 216000
elseif precision == precision_index.ten_hours then return 2160000
elseif precision == precision_index.fifty_hours then return 10800000
elseif precision == precision_index.two_hundred_fifty_hours then return 54000000
elseif precision == precision_index.one_thousand_hours then return 216000000
if precision == precision_index.five_seconds then
return 300
elseif precision == precision_index.one_minute then
return 3600
elseif precision == precision_index.ten_minutes then
return 36000
elseif precision == precision_index.one_hour then
return 216000
elseif precision == precision_index.ten_hours then
return 2160000
elseif precision == precision_index.fifty_hours then
return 10800000
elseif precision == precision_index.two_hundred_fifty_hours then
return 54000000
elseif precision == precision_index.one_thousand_hours then
return 216000000
end
end
@@ -104,11 +126,10 @@ function Production.get_production_total(force, item_name)
end
return {
made=made,
used=used,
net=made-used
made = made,
used = used,
net = made - used,
}
end
--- Returns the production data for the given precision game time
@@ -120,16 +141,15 @@ function Production.get_production(force, item_name, precision)
local made, used = 0, 0
for _, surface in pairs(game.surfaces) do
local stats = force.get_item_production_statistics(surface).get_flow_count
made = made + stats{name=item_name, category="input", precision_index=precision}
used = used + stats{name=item_name, category="output", precision_index=precision}
made = made + stats{ name = item_name, category = "input", precision_index = precision }
used = used + stats{ name = item_name, category = "output", precision_index = precision }
end
return {
made=made,
used=used,
net=made-used
made = made,
used = used,
net = made - used,
}
end
--- Returns the current fluctuation from the average
@@ -143,11 +163,10 @@ function Production.get_fluctuations(force, item_name, precision)
local previous = Production.get_production(force, item_name, precision_up)
return {
made=(current.made/previous.made)-1,
used=(current.used/previous.used)-1,
net=(current.net/previous.net)-1,
made = (current.made / previous.made) - 1,
used = (current.used / previous.used) - 1,
net = (current.net / previous.net) - 1,
}
end
--- Returns the amount of ticks required to produce a certain amount
@@ -160,7 +179,7 @@ function Production.get_production_eta(force, item_name, precision, required)
required = required or 1000
local ticks = Production.precision_ticks(precision)
local production = Production.get_production(force, item_name, precision)
return production.made == 0 and -1 or ticks*required/production.made
return production.made == 0 and -1 or ticks * required / production.made
end
--- Returns the amount of ticks required to consume a certain amount
@@ -173,7 +192,7 @@ function Production.get_consumsion_eta(force, item_name, precision, required)
required = required or 1000
local ticks = Production.precision_ticks(precision)
local production = Production.get_production(force, item_name, precision)
return production.used == 0 and -1 or ticks*required/production.used
return production.used == 0 and -1 or ticks * required / production.used
end
--- Returns the amount of ticks required to produce but not consume a certain amount
@@ -186,7 +205,7 @@ function Production.get_net_eta(force, item_name, precision, required)
required = required or 1000
local ticks = Production.precision_ticks(precision)
local production = Production.get_production(force, item_name, precision)
return production.net == 0 and -1 or ticks*required/production.net
return production.net == 0 and -1 or ticks * required / production.net
end
--- Formating.
@@ -223,17 +242,16 @@ function Production.format_number(value)
local surfix = rtn:sub(-1)
if value > 0 then
rtn = '+'..rtn
elseif value == 0 and rtn:sub(1, 1) == '-' then
rtn = "+" .. rtn
elseif value == 0 and rtn:sub(1, 1) == "-" then
rtn = rtn:sub(2)
end
if not tonumber(surfix) then
return surfix, rtn:sub(1, -2)
else
return '', rtn
return "", rtn
end
end
return Production
return Production

View File

@@ -21,11 +21,11 @@ local EntityProtection = {
-- @tparam number player_index the player index of the player who got mined the entities
-- @tparam LuaEntity entity the last entity which was mined
on_repeat_violation = script.generate_event_name(),
}
},
}
-- Convert config tables into lookup tables
for _, config_key in ipairs{'always_protected_names', 'always_protected_types', 'always_trigger_repeat_names', 'always_trigger_repeat_types'} do
for _, config_key in ipairs{ "always_protected_names", "always_protected_types", "always_trigger_repeat_names", "always_trigger_repeat_types" } do
local tbl = config[config_key]
for key, value in ipairs(tbl) do
tbl[key] = nil
@@ -49,7 +49,7 @@ local repeats = {} -- Stores repeat removals by players
Storage.register({
protected_entities = protected_entities,
protected_areas = protected_areas,
repeats = repeats
repeats = repeats,
}, function(tbl)
protected_entities = tbl.protected_entities
protected_areas = tbl.protected_areas
@@ -61,12 +61,12 @@ end)
--- Get the key used in protected_entities
local function get_entity_key(entity)
return string.format('%i,%i', math.floor(entity.position.x), math.floor(entity.position.y))
return string.format("%i,%i", math.floor(entity.position.x), math.floor(entity.position.y))
end
--- Get the key used in protected_areas
local function get_area_key(area)
return string.format('%i,%i', math.floor(area.left_top.x), math.floor(area.left_top.y))
return string.format("%i,%i", math.floor(area.left_top.x), math.floor(area.left_top.y))
end
--- Check if an entity is always protected
@@ -145,6 +145,7 @@ function EntityProtection.is_position_protected(surface, position)
return true
end
end
return false
end
@@ -203,4 +204,4 @@ Event.add(defines.events.on_robot_pre_mined, event_remove_entity)
Event.add(defines.events.on_entity_died, event_remove_entity)
Event.add(defines.events.script_raised_destroy, event_remove_entity)
return EntityProtection
return EntityProtection

View File

@@ -30,7 +30,7 @@ local Storage = require("modules/exp_util/storage")
local valid_player = Game.get_player_from_any
local Reports = {
user_reports={}, -- stores all user reports, global table
user_reports = {}, -- stores all user reports, global table
events = {
--- When a player is reported
-- @event on_player_reported
@@ -45,8 +45,8 @@ local Reports = {
-- @tparam string removed_by_name the name of the player who removed the report
-- @tparam number batch_count the number of reports removed in this batch, always one when not a batch
-- @tparam number batch the index of this event in a batch, always one when not a batch
on_report_removed = script.generate_event_name()
}
on_report_removed = script.generate_event_name(),
},
}
local user_reports = Reports.user_reports
@@ -112,6 +112,7 @@ function Reports.count_reports(player, custom_count)
for by_player_name, reason in pairs(reports) do
ctn = ctn + custom_count(player, by_player_name, reason)
end
return ctn
else
return table_size(reports)
@@ -132,7 +133,7 @@ function Reports.report_player(player, by_player_name, reason)
if not player then return end
local player_name = player.name
if reason == nil or not reason:find("%S") then reason = 'No reason given' end
if reason == nil or not reason:find("%S") then reason = "No reason given" end
local reports = user_reports[player_name]
if not reports then
@@ -151,7 +152,7 @@ function Reports.report_player(player, by_player_name, reason)
tick = game.tick,
player_index = player.index,
by_player_name = by_player_name,
reason = reason
reason = reason,
})
return true
@@ -171,7 +172,7 @@ local function report_removed_event(player, reported_by_name, removed_by_name, b
reported_by_name = reported_by_name,
removed_by_name = removed_by_name,
batch_count = batch_count or 1,
batch = batch or 1
batch = batch or 1,
})
end

View File

@@ -39,7 +39,7 @@ end
local Rockets = {
times = {},
stats = {},
silos = {}
silos = {},
}
local rocket_times = Rockets.times
@@ -48,7 +48,7 @@ local rocket_silos = Rockets.silos
Storage.register({
rocket_times = rocket_times,
rocket_stats = rocket_stats,
rocket_silos = rocket_silos
rocket_silos = rocket_silos,
}, function(tbl)
Rockets.times = tbl.rocket_times
Rockets.stats = tbl.rocket_stats
@@ -63,7 +63,7 @@ end)
-- @treturn table the data table for this silo, contains rockets launch, silo status, and its force
function Rockets.get_silo_data(silo)
local position = silo.position
local silo_name = math.floor(position.x)..':'..math.floor(position.y)
local silo_name = math.floor(position.x) .. ":" .. math.floor(position.y)
return rocket_silos[silo_name]
end
@@ -99,6 +99,7 @@ function Rockets.get_silos(force_name)
table.insert(rtn, silo_data)
end
end
return rtn
end
@@ -125,6 +126,7 @@ function Rockets.get_game_rocket_count()
for _, force in pairs(game.forces) do
rtn = rtn + force.rockets_launched
end
return rtn
end
@@ -139,10 +141,10 @@ function Rockets.get_rolling_average(force_name, count)
local last_launch_time = rocket_times[force_name][rocket_count]
local start_rocket_time = 0
if count < rocket_count then
start_rocket_time = rocket_times[force_name][rocket_count-count+1]
start_rocket_time = rocket_times[force_name][rocket_count - count + 1]
rocket_count = count
end
return math.floor((last_launch_time-start_rocket_time)/rocket_count)
return math.floor((last_launch_time - start_rocket_time) / rocket_count)
end
--- Event used to update the stats and the hui when a rocket is launched
@@ -163,8 +165,8 @@ Event.add(defines.events.on_rocket_launched, function(event)
if rockets_launched == 1 then
stats.first_launch = event.tick
stats.fastest_launch = event.tick
elseif event.tick-stats.last_launch < stats.fastest_launch then
stats.fastest_launch = event.tick-stats.last_launch
elseif event.tick - stats.last_launch < stats.fastest_launch then
stats.fastest_launch = event.tick - stats.last_launch
end
stats.last_launch = event.tick
@@ -176,13 +178,13 @@ Event.add(defines.events.on_rocket_launched, function(event)
rocket_times[force_name][rockets_launched] = event.tick
local remove_rocket = rockets_launched-largest_rolling_avg
local remove_rocket = rockets_launched - largest_rolling_avg
if remove_rocket > 0 and not table.contains(config.milestones, remove_rocket) then
rocket_times[force_name][remove_rocket] = nil
end
--- Adds this 1 to the launch count for this silo
silo_data.launched = silo_data.launched+1
silo_data.launched = silo_data.launched + 1
end)
--- When a launch is reiggered it will await reset
@@ -195,19 +197,19 @@ end)
--- Adds a silo to the list when it is built
local function on_built(event)
local entity = event.created_entity
if entity.valid and entity.name == 'rocket-silo' then
if entity.valid and entity.name == "rocket-silo" then
local force = entity.force
local force_name = force.name
local position = entity.position
local silo_name = math.floor(position.x)..':'..math.floor(position.y)
local silo_name = math.floor(position.x) .. ":" .. math.floor(position.y)
rocket_silos[silo_name] = {
name=silo_name,
force=force_name,
entity=entity,
launched=0,
awaiting_reset=false,
built=game.tick
name = silo_name,
force = force_name,
entity = entity,
launched = 0,
awaiting_reset = false,
built = game.tick,
}
end
end
@@ -215,4 +217,4 @@ end
Event.add(defines.events.on_built_entity, on_built)
Event.add(defines.events.on_robot_built_entity, on_built)
return Rockets
return Rockets

View File

@@ -18,14 +18,14 @@ local Selection = {
-- @tparam number player_index the player index of the player who left selection mode
-- @tparam string selection the name of the selection which ended
on_player_selection_end = script.generate_event_name(),
}
},
}
local selection_tool = { name='selection-tool' }
local selection_tool = { name = "selection-tool" }
local selections = {}
Storage.register({
selections = selections
selections = selections,
}, function(tbl)
selections = tbl.selections
end)
@@ -42,7 +42,7 @@ function Selection.start(player, selection_name, single_use, ...)
name = Selection.events.on_player_selection_end,
tick = game.tick,
player_index = player.index,
selection = selections[player.index].name
selection = selections[player.index].name,
})
end
@@ -51,7 +51,7 @@ function Selection.start(player, selection_name, single_use, ...)
name = selection_name,
arguments = { ... },
single_use = single_use == true,
character = player.character
character = player.character,
}
-- Raise the event
@@ -59,7 +59,7 @@ function Selection.start(player, selection_name, single_use, ...)
name = Selection.events.on_player_selection_start,
tick = game.tick,
player_index = player.index,
selection = selection_name
selection = selection_name,
})
-- Give a selection tool if one is not in use
@@ -86,7 +86,7 @@ function Selection.stop(player)
name = Selection.events.on_player_selection_end,
tick = game.tick,
player_index = player.index,
selection = selection
selection = selection,
})
-- Remove the selection tool
@@ -146,7 +146,7 @@ end
--- Stop selection if the selection tool is removed from the cursor
Event.add(defines.events.on_player_cursor_stack_changed, function(event)
local player = game.get_player(event.player_index) ---@cast player -nil
local player = game.get_player(event.player_index) --- @cast player -nil
if player.cursor_stack.is_selection_tool then return end
Selection.stop(player)
end)
@@ -169,4 +169,4 @@ end
Event.add(defines.events.on_player_selected_area, stop_after_use)
Event.add(defines.events.on_player_alt_selected_area, stop_after_use)
return Selection
return Selection

View File

@@ -1,4 +1,3 @@
local Event = require("modules/exp_legacy/utils/event") --- @dep utils.event
local Storage = require("modules/exp_util/storage")
local Gui = require("modules.exp_legacy.expcore.gui") --- @dep expcore.gui
@@ -12,7 +11,7 @@ local Public = {}
----- Storage data -----
Storage.register({
following = following,
spectating = spectating
spectating = spectating,
}, function(tbl)
following = tbl.following
spectating = tbl.spectating
@@ -24,7 +23,7 @@ end)
-- @tparam LuaPlayer player The player to test the controller type of
-- @treturn boolean Returns true if the player is in spectator mode
function Public.is_spectating(player)
assert(player and player.valid, 'Invalid player given to follower')
assert(player and player.valid, "Invalid player given to follower")
return player.controller_type == defines.controllers.spectator
end
@@ -32,7 +31,7 @@ end
-- @tparam LuaPlayer player The player that will be placed into spectator mode
-- @treturn boolean Returns false if the player was already in spectator mode
function Public.start_spectate(player)
assert(player and player.valid, 'Invalid player given to follower')
assert(player and player.valid, "Invalid player given to follower")
if spectating[player.index] or not player.character then return false end
local character = player.character
local opened = player.opened
@@ -46,7 +45,7 @@ end
--- Return a player from spectator mode back to their character, if their character was killed then respawn them
-- @tparam LuaPlayer player The player that will leave spectator mode
function Public.stop_spectate(player)
assert(player and player.valid, 'Invalid player given to follower')
assert(player and player.valid, "Invalid player given to follower")
local character = spectating[player.index]
spectating[player.index] = nil
if character and character.valid then
@@ -63,7 +62,7 @@ end
-- @tparam LuaPlayer player The player to test the follow mode of
-- @treturn boolean Returns true if the player is in follow mode
function Public.is_following(player)
assert(player and player.valid, 'Invalid player given to follower')
assert(player and player.valid, "Invalid player given to follower")
return following[player.index] ~= nil
end
@@ -71,8 +70,8 @@ end
-- @tparam LuaPlayer player The player that will follow the entity
-- @tparam ?LuaPlayer|LuaEntity entity The player or entity that will be followed
function Public.start_follow(player, entity)
assert(player and player.valid, 'Invalid player given to follower')
assert(entity and entity.valid, 'Invalid entity given to follower')
assert(player and player.valid, "Invalid player given to follower")
assert(entity and entity.valid, "Invalid entity given to follower")
local spectate = Public.start_spectate(player)
player.close_map()
@@ -84,7 +83,7 @@ end
--- Returns camera control to the player, will return a player to their character if start_follow placed them into spectator mode
-- @tparam LuaPlayer player The player that will regain control of their camera
function Public.stop_follow(player)
assert(player and player.valid, 'Invalid player given to follower')
assert(player and player.valid, "Invalid player given to follower")
if following[player.index] and following[player.index][4] and Public.is_spectating(player) then
Public.stop_spectate(player)
end
@@ -105,32 +104,32 @@ end
--- Label used to show that the player is following, also used to allow esc to stop following
-- @element follow_label
follow_label =
Gui.element(function(definition, parent, target)
Gui.destroy_if_valid(parent[definition.name])
Gui.element(function(definition, parent, target)
Gui.destroy_if_valid(parent[definition.name])
local label = parent.add{
type = 'label',
style = 'frame_title',
caption = 'Following '..target.name..'.\nClick here or press esc to stop following.',
name = definition.name
}
local label = parent.add{
type = "label",
style = "frame_title",
caption = "Following " .. target.name .. ".\nClick here or press esc to stop following.",
name = definition.name,
}
local player = Gui.get_player_from_element(parent)
local res = player.display_resolution
label.location = {0, res.height-150}
label.style.width = res.width
label.style.horizontal_align = 'center'
player.opened = label
local player = Gui.get_player_from_element(parent)
local res = player.display_resolution
label.location = { 0, res.height - 150 }
label.style.width = res.width
label.style.horizontal_align = "center"
player.opened = label
return label
end)
:static_name(Gui.unique_static_name)
:on_click(Public.stop_follow)
:on_close(function(player)
-- Don't call set_controller during on_close as it invalidates the controller
-- Setting an invalid position (as to not equal their current) will call stop_follow on the next tick
following[player.index][3] = {}
end)
return label
end)
:static_name(Gui.unique_static_name)
:on_click(Public.stop_follow)
:on_close(function(player)
-- Don't call set_controller during on_close as it invalidates the controller
-- Setting an invalid position (as to not equal their current) will call stop_follow on the next tick
following[player.index][3] = {}
end)
----- Events -----
@@ -170,4 +169,4 @@ Event.add(defines.events.on_pre_player_left_game, function(event)
end)
----- Module Return -----
return Public
return Public

View File

@@ -14,13 +14,13 @@ local Datastore = require("modules.exp_legacy.expcore.datastore") --- @dep expco
local Storage = require("modules/exp_util/storage")
--- Stores all data for the warp gui
local TaskData = Datastore.connect('TaskData')
local TaskData = Datastore.connect("TaskData")
TaskData:set_serializer(function(raw_key) return raw_key.task_id end)
local Tasks = {}
-- Storage lookup table for force name to task ids
local force_tasks = {_uid=1}
local force_tasks = { _uid = 1 }
Storage.register(force_tasks, function(tbl)
force_tasks = tbl
end)
@@ -59,11 +59,11 @@ function Tasks.add_task(force_name, player_name, task_title, task_body)
TaskData:set(task_id, {
task_id = task_id,
force_name = force_name,
title = task_title or '',
body = task_body or '',
last_edit_name = player_name or '<server>',
title = task_title or "",
body = task_body or "",
last_edit_name = player_name or "<server>",
last_edit_time = game.tick,
currently_editing = {}
currently_editing = {},
})
return task_id

View File

@@ -17,22 +17,22 @@ local vlayer_data = {
energy = {},
circuit = {},
storage_input = {},
storage_output = {}
storage_output = {},
},
properties = {
total_surface_area = 0,
used_surface_area = 0,
production = 0,
discharge = 0,
capacity = 0
capacity = 0,
},
storage = {
items = {},
power_items = {},
energy = 0,
unallocated = {}
unallocated = {},
},
surface = table.deep_copy(config.surface)
surface = table.deep_copy(config.surface),
}
Storage.register(vlayer_data, function(tbl)
@@ -45,7 +45,7 @@ for name, properties in pairs(config.allowed_items) do
if properties.power then
vlayer_data.storage.power_items[name] = {
value = properties.fuel_value * 1000000,
count = 0
count = 0,
}
end
end
@@ -61,7 +61,7 @@ for item_name, properties in pairs(config.modded_items) do
surface_area = (base_properties.surface_area or 0) * m,
production = (base_properties.production or 0) * m,
capacity = (base_properties.capacity or 0) * m,
modded = true
modded = true,
}
end
@@ -133,7 +133,7 @@ end
--[[
25,000 / 416 s
昼 208秒 ソーラー効率100%
夕方 83秒 1秒ごとにソーラー発電量が約1.2%ずつ下がり、やがて0%になる
夕方 83秒 1秒ごとにソーラー発電量が約1.2%ずつ下がり、やがて0%になる
夜 41秒 ソーラー発電量が0%になる
朝方 83秒 1秒ごとにソーラー発電量が約1.2%ずつ上がり、やがて100%になる
@@ -160,7 +160,6 @@ local function get_production_multiplier()
if brightness >= surface.min_brightness then
return mul * (brightness - surface.min_brightness) / (1 - surface.min_brightness)
else
return 0
end
@@ -173,16 +172,12 @@ local function get_production_multiplier()
if daytime <= surface.dusk then -- Noon to Sunset
return mul
elseif daytime <= surface.evening then -- Sunset to Night
return mul * (1 - ((daytime - surface.dusk) / (surface.evening - surface.dusk)))
elseif daytime <= surface.morning then -- Night to Sunrise
return 0
elseif daytime <= surface.dawn then -- Sunrise to Morning
return mul * ((surface.daytime - surface.morning) / (surface.dawn - surface.morning))
else -- Morning to Noon
return mul
end
@@ -214,7 +209,7 @@ end
-- @tparam number count The count of the item to allocate
function vlayer.allocate_item(item_name, count)
local item_properties = config.allowed_items[item_name]
assert(item_properties, 'Item not allowed in vlayer: ' .. tostring(item_name))
assert(item_properties, "Item not allowed in vlayer: " .. tostring(item_name))
if item_properties.production then
vlayer_data.properties.production = vlayer_data.properties.production + item_properties.production * count
@@ -253,7 +248,7 @@ end
-- @tparam number count The count of the item to insert
function vlayer.insert_item(item_name, count)
local item_properties = config.allowed_items[item_name]
assert(item_properties, 'Item not allowed in vlayer: ' .. tostring(item_name))
assert(item_properties, "Item not allowed in vlayer: " .. tostring(item_name))
vlayer_data.storage.items[item_name] = vlayer_data.storage.items[item_name] + count
if not config.unlimited_surface_area and item_properties.required_area and item_properties.required_area > 0 then
@@ -266,7 +261,6 @@ function vlayer.insert_item(item_name, count)
end
vlayer_data.storage.unallocated[item_name] = vlayer_data.storage.unallocated[item_name] + count - allocate_count
else
vlayer.allocate_item(item_name, count)
end
@@ -279,7 +273,7 @@ end
-- @treturn number The count of the item actually removed
function vlayer.remove_item(item_name, count)
local item_properties = config.allowed_items[item_name]
assert(item_properties, 'Item not allowed in vlayer: ' .. tostring(item_name))
assert(item_properties, "Item not allowed in vlayer: " .. tostring(item_name))
local remove_unallocated = 0
if not config.unlimited_surface_area and item_properties.required_area and item_properties.required_area > 0 then
@@ -325,7 +319,7 @@ end
-- @tparam[opt] LuaPlayer player The player to show as the last user of the interface
-- @treturn LuaEntity The entity that was created for the interface
function vlayer.create_input_interface(surface, position, circuit, last_user)
local interface = surface.create_entity{name='logistic-chest-storage', position=position, force='neutral'}
local interface = surface.create_entity{ name = "logistic-chest-storage", position = position, force = "neutral" }
table.insert(vlayer_data.entity_interfaces.storage_input, interface)
if last_user then
@@ -335,7 +329,7 @@ function vlayer.create_input_interface(surface, position, circuit, last_user)
if circuit then
for k, _ in pairs(circuit) do
for _, v in pairs(circuit[k]) do
interface.connect_neighbour({wire=defines.wire_type[k], target_entity=v})
interface.connect_neighbour{ wire = defines.wire_type[k], target_entity = v }
end
end
end
@@ -352,7 +346,6 @@ local function handle_input_interfaces()
for index, interface in pairs(vlayer_data.entity_interfaces.storage_input) do
if not interface.valid then
vlayer_data.entity_interfaces.storage_input[index] = nil
else
local inventory = interface.get_inventory(defines.inventory.chest)
@@ -361,21 +354,18 @@ local function handle_input_interfaces()
if config.allowed_items[name].modded then
if config.modded_auto_downgrade then
vlayer.insert_item(config.modded_items[name].base_game_equivalent, count * config.modded_items[name].multiplier)
else
vlayer.insert_item(name, count)
end
else
if vlayer_data.storage.power_items[name] then
vlayer_data.storage.power_items[name].count = vlayer_data.storage.power_items[name].count + count
else
vlayer.insert_item(name, count)
end
end
inventory.remove({name=name, count=count})
inventory.remove{ name = name, count = count }
end
end
end
@@ -388,7 +378,7 @@ end
-- @tparam[opt] LuaPlayer player The player to show as the last user of the interface
-- @treturn LuaEntity The entity that was created for the interface
function vlayer.create_output_interface(surface, position, circuit, last_user)
local interface = surface.create_entity{name='logistic-chest-requester', position=position, force='neutral'}
local interface = surface.create_entity{ name = "logistic-chest-requester", position = position, force = "neutral" }
table.insert(vlayer_data.entity_interfaces.storage_output, interface)
if last_user then
@@ -398,7 +388,7 @@ function vlayer.create_output_interface(surface, position, circuit, last_user)
if circuit then
for k, _ in pairs(circuit) do
for _, v in pairs(circuit[k]) do
interface.connect_neighbour({wire=defines.wire_type[k], target_entity=v})
interface.connect_neighbour{ wire = defines.wire_type[k], target_entity = v }
end
end
end
@@ -415,7 +405,6 @@ local function handle_output_interfaces()
for index, interface in pairs(vlayer_data.entity_interfaces.storage_output) do
if not interface.valid then
vlayer_data.entity_interfaces.storage_output[index] = nil
else
local inventory = interface.get_inventory(defines.inventory.chest)
@@ -426,11 +415,11 @@ local function handle_output_interfaces()
local current_amount = inventory.get_item_count(request.name)
local request_amount = math.min(request.count - current_amount, vlayer_data.storage.items[request.name])
if request_amount > 0 and inventory.can_insert({name=request.name, count=request_amount}) then
if request_amount > 0 and inventory.can_insert{ name = request.name, count = request_amount } then
local removed_item_count = vlayer.remove_item(request.name, request_amount)
if removed_item_count > 0 then
inventory.insert({name=request.name, count=removed_item_count})
inventory.insert{ name = request.name, count = removed_item_count }
end
end
end
@@ -488,7 +477,7 @@ function vlayer.get_statistics()
energy_storage = vlayer_data.storage.energy,
day_time = math.floor(vlayer_data.surface.daytime * vlayer_data.surface.ticks_per_day),
day_length = vlayer_data.surface.ticks_per_day,
tick = game.tick
tick = game.tick,
}
end
@@ -500,17 +489,17 @@ end
--- Circuit signals used for the statistics
function vlayer.get_circuits()
return {
total_surface_area = 'signal-A',
used_surface_area = 'signal-U',
remaining_surface_area = 'signal-R',
production_multiplier = 'signal-M',
energy_production = 'signal-P',
energy_sustained = 'signal-S',
energy_capacity = 'signal-C',
energy_storage = 'signal-E',
day_time = 'signal-D',
day_length = 'signal-L',
tick = 'signal-T',
total_surface_area = "signal-A",
used_surface_area = "signal-U",
remaining_surface_area = "signal-R",
production_multiplier = "signal-M",
energy_production = "signal-P",
energy_sustained = "signal-S",
energy_capacity = "signal-C",
energy_storage = "signal-E",
day_time = "signal-D",
day_length = "signal-L",
tick = "signal-T",
}
end
@@ -520,7 +509,7 @@ end
-- @tparam[opt] LuaPlayer player The player to show as the last user of the interface
-- @treturn LuaEntity The entity that was created for the interface
function vlayer.create_circuit_interface(surface, position, circuit, last_user)
local interface = surface.create_entity{name='constant-combinator', position=position, force='neutral'}
local interface = surface.create_entity{ name = "constant-combinator", position = position, force = "neutral" }
table.insert(vlayer_data.entity_interfaces.circuit, interface)
if last_user then
@@ -530,7 +519,7 @@ function vlayer.create_circuit_interface(surface, position, circuit, last_user)
if circuit then
for k, _ in pairs(circuit) do
for _, v in pairs(circuit[k]) do
interface.connect_neighbour({wire=defines.wire_type[k], target_entity=v})
interface.connect_neighbour{ wire = defines.wire_type[k], target_entity = v }
end
end
end
@@ -549,7 +538,6 @@ local function handle_circuit_interfaces()
for index, interface in pairs(vlayer_data.entity_interfaces.circuit) do
if not interface.valid then
vlayer_data.entity_interfaces.circuit[index] = nil
else
local circuit_oc = interface.get_or_create_control_behavior()
local max_signals = circuit_oc.signals_count
@@ -558,14 +546,12 @@ local function handle_circuit_interfaces()
-- Set the virtual signals based on the vlayer stats
for stat_name, signal_name in pairs(circuit) do
if stat_name:find('energy') then
circuit_oc.set_signal(signal_index, {signal={type='virtual', name=signal_name}, count=math.floor(stats[stat_name] / mega)})
elseif stat_name == 'production_multiplier' then
circuit_oc.set_signal(signal_index, {signal={type='virtual', name=signal_name}, count=math.floor(stats[stat_name] * 10000)})
if stat_name:find("energy") then
circuit_oc.set_signal(signal_index, { signal = { type = "virtual", name = signal_name }, count = math.floor(stats[stat_name] / mega) })
elseif stat_name == "production_multiplier" then
circuit_oc.set_signal(signal_index, { signal = { type = "virtual", name = signal_name }, count = math.floor(stats[stat_name] * 10000) })
else
circuit_oc.set_signal(signal_index, {signal={type='virtual', name=signal_name}, count=math.floor(stats[stat_name])})
circuit_oc.set_signal(signal_index, { signal = { type = "virtual", name = signal_name }, count = math.floor(stats[stat_name]) })
end
signal_index = signal_index + 1
@@ -574,7 +560,7 @@ local function handle_circuit_interfaces()
-- Set the item signals based on stored items
for item_name, count in pairs(vlayer_data.storage.items) do
if prototypes.item[item_name] and count > 0 then
circuit_oc.set_signal(signal_index, {signal={type='item', name=item_name}, count=count})
circuit_oc.set_signal(signal_index, { signal = { type = "item", name = item_name }, count = count })
signal_index = signal_index + 1
if signal_index > max_signals then
return -- No more signals can be added
@@ -600,11 +586,11 @@ end
-- @tparam[opt] LuaPlayer player The player to show as the last user of the interface
-- @treturn LuaEntity The entity that was created for the interface, or nil if it could not be created
function vlayer.create_energy_interface(surface, position, last_user)
if not surface.can_place_entity{name='electric-energy-interface', position=position} then
if not surface.can_place_entity{ name = "electric-energy-interface", position = position } then
return nil
end
local interface = surface.create_entity{name='electric-energy-interface', position=position, force='neutral'}
local interface = surface.create_entity{ name = "electric-energy-interface", position = position, force = "neutral" }
table.insert(vlayer_data.entity_interfaces.energy, interface)
if last_user then
@@ -635,7 +621,6 @@ local function handle_energy_interfaces()
for index, interface in pairs(vlayer_data.entity_interfaces.energy) do
if not interface.valid then
vlayer_data.entity_interfaces.energy[index] = nil
else
available_energy = available_energy + interface.energy
end
@@ -657,7 +642,7 @@ local function handle_energy_interfaces()
if not config.unlimited_capacity and vlayer_data.storage.energy > vlayer_data.properties.capacity * mega then
vlayer_data.storage.energy = vlayer_data.properties.capacity * mega
-- burn the trash to produce power
-- burn the trash to produce power
elseif vlayer_data.storage.power_items then
for k, v in pairs(vlayer_data.storage.power_items) do
local max_burning = (vlayer_data.properties.capacity * mega / 2) - vlayer_data.storage.energy
@@ -679,11 +664,11 @@ end
-- @treturn MapPosition The position the interface was at, or nil if no interface was found
function vlayer.remove_interface(surface, position)
local entities = surface.find_entities_filtered{
name = {'logistic-chest-storage', 'logistic-chest-requester', 'constant-combinator', 'electric-energy-interface'},
force = 'neutral',
name = { "logistic-chest-storage", "logistic-chest-requester", "constant-combinator", "electric-energy-interface" },
force = "neutral",
position = position,
radius = 2,
limit = 1
limit = 1,
}
-- Get the details which will be returned
@@ -696,32 +681,29 @@ function vlayer.remove_interface(surface, position)
local pos = interface.position
-- Return the type of interface removed and do some clean up
if name == 'logistic-chest-storage' then
if name == "logistic-chest-storage" then
move_items_stack(interface.get_inventory(defines.inventory.chest).get_contents())
table.remove_element(vlayer_data.entity_interfaces.storage_input, interface)
interface.destroy()
return 'storage-input', pos
elseif name == 'logistic-chest-requester' then
return "storage-input", pos
elseif name == "logistic-chest-requester" then
move_items_stack(interface.get_inventory(defines.inventory.chest).get_contents())
table.remove_element(vlayer_data.entity_interfaces.storage_output, interface)
interface.destroy()
return 'storage-output', pos
elseif name == 'constant-combinator' then
return "storage-output", pos
elseif name == "constant-combinator" then
table.remove_element(vlayer_data.entity_interfaces.circuit, interface)
interface.destroy()
return 'circuit', pos
elseif name == 'electric-energy-interface' then
return "circuit", pos
elseif name == "electric-energy-interface" then
vlayer_data.storage.energy = vlayer_data.storage.energy + interface.energy
table.remove_element(vlayer_data.entity_interfaces.energy, interface)
interface.destroy()
return 'energy', pos
return "energy", pos
end
end

View File

@@ -30,19 +30,20 @@ local valid_player = Game.get_player_from_any
--- Stores the quickbar filters for a player
local PlayerData = require("modules.exp_legacy.expcore.player_data") --- @dep expcore.player_data
local PlayerWarnings = PlayerData.Required:combine('Warnings')
local PlayerWarnings = PlayerData.Required:combine("Warnings")
PlayerWarnings:set_metadata{
stringify = function(value)
if not value then return 'You have no warnings' end
if not value then return "You have no warnings" end
local count = 0
for _ in pairs(value) do count = count + 1 end
return 'You have '..count..' warnings'
end
return "You have " .. count .. " warnings"
end,
}
local Warnings = {
user_warnings=PlayerWarnings,
user_script_warnings={},
user_warnings = PlayerWarnings,
user_script_warnings = {},
events = {
--- When a warning is added to a player
-- @event on_warning_added
@@ -71,7 +72,7 @@ local Warnings = {
-- @tparam number player_index the index of the player who is having the warning removed
-- @tparam number warning_count the new number of warnings that the player has
on_script_warning_removed = script.generate_event_name(),
}
},
}
local user_script_warnings = Warnings.user_script_warnings
@@ -105,18 +106,18 @@ function Warnings.add_warning(player, by_player_name, reason)
if not player then return end
if not by_player_name then return end
reason = reason or 'None given.'
reason = reason or "None given."
local warning_count
PlayerWarnings:update(player.name, function(_, warnings)
local warning = {
by_player_name = by_player_name,
reason = reason
reason = reason,
}
if not warnings then
warning_count = 1
return {warning}
return { warning }
else
table.insert(warnings, warning)
warning_count = #warnings
@@ -129,20 +130,20 @@ function Warnings.add_warning(player, by_player_name, reason)
player_index = player.index,
warning_count = warning_count,
by_player_name = by_player_name,
reason = reason
reason = reason,
})
local action = config.actions[warning_count]
if action then
local _type = type(action)
if _type == 'function' then
if _type == "function" then
action(player, by_player_name, warning_count)
elseif _type == 'table' then
elseif _type == "table" then
local current = table.deepcopy(action)
table.insert(current, 2,by_player_name)
table.insert(current, 3,warning_count)
table.insert(current, 2, by_player_name)
table.insert(current, 3, warning_count)
player.print(current)
elseif type(action) == 'string' then
elseif type(action) == "string" then
player.print(action)
end
end
@@ -166,7 +167,7 @@ local function warning_removed_event(player, warning_by_name, removed_by_name, w
warning_by_name = warning_by_name,
removed_by_name = removed_by_name,
batch_count = batch_count or 1,
batch = batch or 1
batch = batch or 1,
})
end
@@ -206,7 +207,7 @@ function Warnings.clear_warnings(player, by_player_name)
local warning_count = #warnings
for n, warning in pairs(warnings) do
warning_removed_event(player, warning.by_player_name, by_player_name, warning_count-n, n, warning_count)
warning_removed_event(player, warning.by_player_name, by_player_name, warning_count - n, n, warning_count)
end
PlayerWarnings:remove(player)
@@ -236,7 +237,7 @@ function Warnings.add_script_warning(player, reason)
player = valid_player(player)
if not player then return end
reason = reason or 'Non given.'
reason = reason or "Non given."
local warnings = user_script_warnings[player.name]
if not warnings then
@@ -246,7 +247,7 @@ function Warnings.add_script_warning(player, reason)
table.insert(warnings, {
tick = game.tick,
reason = reason
reason = reason,
})
local warning_count = #warnings
@@ -256,11 +257,11 @@ function Warnings.add_script_warning(player, reason)
tick = game.tick,
player_index = player.index,
warning_count = warning_count,
reason = reason
reason = reason,
})
if warning_count > config.script_warning_limit then
Warnings.add_warning(player, '<server>', reason)
Warnings.add_warning(player, "<server>", reason)
end
return warning_count
@@ -274,7 +275,7 @@ local function script_warning_removed_event(player, warning_count)
name = Warnings.events.on_script_warning_removed,
tick = game.tick,
player_index = player.index,
warning_count = warning_count
warning_count = warning_count,
})
end
@@ -306,7 +307,7 @@ function Warnings.clear_script_warnings(player)
local warning_count = #warnings
for n, _ in pairs(warnings) do
script_warning_removed_event(player, warning_count-n)
script_warning_removed_event(player, warning_count - n)
end
user_script_warnings[player.name] = nil
@@ -314,8 +315,8 @@ function Warnings.clear_script_warnings(player)
end
-- script warnings are removed after a certain amount of time to make them even more lienient
local script_warning_cool_down = config.script_warning_cool_down*3600
Event.on_nth_tick(script_warning_cool_down/4, function()
local script_warning_cool_down = config.script_warning_cool_down * 3600
Event.on_nth_tick(script_warning_cool_down / 4, function()
local cutoff = game.tick - script_warning_cool_down
for player_name, script_warnings in pairs(user_script_warnings) do
if #script_warnings > 0 then
@@ -328,4 +329,4 @@ Event.on_nth_tick(script_warning_cool_down/4, function()
end
end)
return Warnings
return Warnings

View File

@@ -26,14 +26,14 @@ local Storage = require("modules/exp_util/storage")
local config = require("modules.exp_legacy.config.gui.warps") --- @dep config.warps
--- Stores all data for the warp system
local WrapData = Datastore.connect('WrapData')
local WrapData = Datastore.connect("WrapData")
WrapData:set_serializer(function(raw_key) return raw_key.warp_id end)
local Warps = {}
-- Storage lookup table for force name to task ids
local force_warps = {_uid=1}
---@cast force_warps table<string, { spawn: string, [number]: string }>
local force_warps = { _uid = 1 }
--- @cast force_warps table<string, { spawn: string, [number]: string }>
Storage.register(force_warps, function(tbl)
force_warps = tbl
end)
@@ -65,13 +65,13 @@ WrapData:on_update(function(warp_id, warp, old_warp)
for _, next_warp_id in pairs(warp_ids) do
local next_warp = WrapData:get(next_warp_id)
if next_warp_id ~= spawn_id then
warp_names[next_warp.name..next_warp_id] = next_warp_id
warp_names[next_warp.name .. next_warp_id] = next_warp_id
end
end
-- Sort the warp names in alphabetical order
local new_warp_ids = table.get_values(table.keysort(warp_names))
table.insert(new_warp_ids, 1,spawn_id)
table.insert(new_warp_ids, 1, spawn_id)
new_warp_ids.spawn = spawn_id
force_warps[force_name] = new_warp_ids
end
@@ -98,7 +98,7 @@ function Warps.make_warp_tag(warp_id)
local tag = warp.tag
if tag and tag.valid then
tag.text = 'Warp: ' .. name
tag.text = "Warp: " .. name
tag.icon = icon
return false
end
@@ -109,9 +109,9 @@ function Warps.make_warp_tag(warp_id)
local position = warp.position
tag = force.add_chart_tag(surface, {
position = {position.x+0.5, position.y+0.5},
text = 'Warp: ' .. name,
icon = icon
position = { position.x + 0.5, position.y + 0.5 },
text = "Warp: " .. name,
icon = icon,
})
-- Add the tag to this warp, store.update not needed as we dont want it to trigger
@@ -165,16 +165,17 @@ function Warps.make_warp_area(warp_id)
-- Add a tile pattern on top of the base
local tiles = {}
for _, tile in pairs(config.tiles) do
table.insert(tiles, {name=tile[1], position={tile[2]+posx, tile[3]+posy}})
table.insert(tiles, { name = tile[1], position = { tile[2] + posx, tile[3] + posy } })
end
surface.set_tiles(tiles)
-- Add entities to the warp structure
for _, entity in pairs(config.entities) do
entity = surface.create_entity{
name=entity[1],
position={entity[2]+posx, entity[3]+posy},
force='neutral'
name = entity[1],
position = { entity[2] + posx, entity[3] + posy },
force = "neutral",
}
entity.destructible = false
entity.health = 0
@@ -182,7 +183,7 @@ function Warps.make_warp_area(warp_id)
entity.rotatable = false
-- Save reference of the last power pole
if entity.type == 'electric-pole' then
if entity.type == "electric-pole" then
warp.electric_pole = entity
end
end
@@ -209,18 +210,18 @@ function Warps.remove_warp_area(warp_id)
local tiles = {}
for _, tile in pairs(config.tiles) do
table.insert(tiles, {name=old_tile, position={tile[2]+position.x, tile[3]+position.y}})
table.insert(tiles, { name = old_tile, position = { tile[2] + position.x, tile[3] + position.y } })
end
surface.set_tiles(tiles)
local area = {
{position.x-radius, position.y-radius},
{position.x+radius, position.y+radius}
{ position.x - radius, position.y - radius },
{ position.x + radius, position.y + radius },
}
-- Remove warp structure entities
local entities = surface.find_entities_filtered{ force='neutral', area=area, name = remove_warp_area_entity_names }
local entities = surface.find_entities_filtered{ force = "neutral", area = area, name = remove_warp_area_entity_names }
for _, entity in pairs(entities) do
-- Destroy them, this will leave corpses of the entities that it destroyed.
if entity and entity.valid and entity.destructible == false then
@@ -228,6 +229,7 @@ function Warps.remove_warp_area(warp_id)
entity.die(entity.force)
end
end
-- Rechart map area, useful if warp is not covered by a radar
game.forces[warp.force_name].chart(surface, area)
end
@@ -269,8 +271,8 @@ function Warps.teleport_player(warp_id, player)
local warp = WrapData:get(warp_id)
local surface = warp.surface
local position = {
x=warp.position.x+0.5,
y=warp.position.y+0.5
x = warp.position.x + 0.5,
y = warp.position.y + 0.5,
}
if player.vehicle then
@@ -285,13 +287,13 @@ function Warps.teleport_player(warp_id, player)
if not entity.teleport(goto_position) then
player.driving = false
-- Need to calculate new goto_position because entities have different collision boxes
goto_position = surface.find_non_colliding_position('character', position, 32, 1)
goto_position = surface.find_non_colliding_position("character", position, 32, 1)
player.teleport(goto_position, surface)
end
end
else
-- Teleport the player
local goto_position = surface.find_non_colliding_position('character', position, 32, 1)
local goto_position = surface.find_non_colliding_position("character", position, 32, 1)
if player.driving then player.driving = false end
player.teleport(goto_position, surface)
end
@@ -318,7 +320,7 @@ function Warps.add_warp(force_name, surface, position, player_name, warp_name)
-- Get new warp id
local warp_id = tostring(force_warps._uid)
force_warps._uid = force_warps._uid + 1
warp_name = warp_name or 'New warp'
warp_name = warp_name or "New warp"
-- Get the existing warps for this force
local warp_ids = force_warps[force_name]
@@ -345,9 +347,9 @@ function Warps.add_warp(force_name, surface, position, player_name, warp_name)
surface = surface,
position = {
x = math.floor(position.x),
y = math.floor(position.y)
y = math.floor(position.y),
},
last_edit_name = player_name or '<server>',
last_edit_name = player_name or "<server>",
last_edit_time = game.tick,
currently_editing = editing,
updates = 0,
@@ -389,7 +391,7 @@ function Warps.update_warp(warp_id, new_name, new_icon, player_name)
new_icon = warp.icon
end
warp.last_edit_name = player_name or '<server>'
warp.last_edit_name = player_name or "<server>"
warp.last_edit_time = game.tick
warp.name = new_name or warp.name
warp.icon = new_icon or warp.icon

View File

@@ -1,14 +1,14 @@
--- Stores if you use alt mode or not and auto applies it
-- @data Alt-View
local Event = require("modules/exp_legacy/utils/event") ---@dep utils.event
local Event = require("modules/exp_legacy/utils/event") --- @dep utils.event
--- Stores the visible state of alt mode
local PlayerData = require("modules.exp_legacy.expcore.player_data") --- @dep expcore.player_data
local UsesAlt = PlayerData.Settings:combine('UsesAlt')
local UsesAlt = PlayerData.Settings:combine("UsesAlt")
UsesAlt:set_default(false)
UsesAlt:set_metadata{
stringify = function(value) return value and 'Visible' or 'Hidden' end
stringify = function(value) return value and "Visible" or "Hidden" end,
}
--- When your data loads apply alt view if you have it enabled
@@ -21,4 +21,4 @@ end)
Event.add(defines.events.on_player_toggled_alt_mode, function(event)
local player = game.players[event.player_index]
UsesAlt:set(player, player.game_view_settings.show_entity_info)
end)
end)

View File

@@ -11,17 +11,17 @@ require("modules.exp_legacy.config.expcore.command_general_parse")
-- Stores the bonus for the player
local PlayerData = require("modules.exp_legacy.expcore.player_data") --- @dep expcore.player_data
local PlayerBonus = PlayerData.Settings:combine('Bonus')
local PlayerBonus = PlayerData.Settings:combine("Bonus")
PlayerBonus:set_default(0)
PlayerBonus:set_metadata{
permission = 'command/bonus',
permission = "command/bonus",
stringify = function(value)
if not value or value == 0 then
return 'None set'
return "None set"
end
return value
end
end,
}
--- Apply a bonus to a player
@@ -34,7 +34,7 @@ local function apply_bonus(player, stage)
player[k] = v.value * stage / 10
if v.combined_bonus then
for i=1, #v.combined_bonus, 1 do
for i = 1, #v.combined_bonus, 1 do
player[v.combined_bonus[i]] = v.value * stage / 10
end
end
@@ -49,18 +49,18 @@ end)
--- Changes the amount of bonus you receive
-- @command bonus
-- @tparam number amount range 0-10 the increase for your bonus
Commands.new_command('bonus', {'expcom-bonus.description'}, 'Changes the amount of bonus you receive')
:add_param('amount', 'integer-range', 0, 10)
:register(function(player, amount)
if not Roles.player_allowed(player, 'command/bonus') then
Commands.print{'expcom-bonus.perm', 1}
return
end
Commands.new_command("bonus", "Changes the amount of bonus you receive")
:add_param("amount", "integer-range", 0, 10)
:register(function(player, amount)
if not Roles.player_allowed(player, "command/bonus") then
Commands.print{ "expcom-bonus.perm", 1 }
return
end
PlayerBonus:set(player, amount)
PlayerBonus:set(player, amount)
Commands.print{'expcom-bonus.set', amount}
end)
Commands.print{ "expcom-bonus.set", amount }
end)
--- When a player respawns re-apply bonus
Event.add(defines.events.on_player_respawned, function(event)
@@ -71,7 +71,7 @@ end)
--- Remove bonus if a player no longer has access to the command
local function role_update(event)
local player = game.players[event.player_index]
if not Roles.player_allowed(player, 'command/bonus') then
if not Roles.player_allowed(player, "command/bonus") then
apply_bonus(player, 0)
end
end
@@ -80,7 +80,7 @@ end
Event.add(defines.events.on_player_died, function(event)
local player = game.players[event.player_index]
if Roles.player_has_flag(player, 'instant-respawn') then
if Roles.player_has_flag(player, "instant-respawn") then
player.ticks_to_respawn = 120
end
end)

View File

@@ -2,14 +2,14 @@
-- @data Greetings
local config = require("modules.exp_legacy.config.join_messages") --- @dep config.join_messages
local Commands = require("modules.exp_legacy.expcore.commands") ---@dep expcore.commands
local Commands = require("modules.exp_legacy.expcore.commands") --- @dep expcore.commands
require("modules.exp_legacy.config.expcore.command_general_parse")
--- Stores the join message that the player have
local PlayerData = require("modules.exp_legacy.expcore.player_data") --- @dep expcore.player_data
local CustomMessages = PlayerData.Settings:combine('JoinMessage')
local CustomMessages = PlayerData.Settings:combine("JoinMessage")
CustomMessages:set_metadata{
permission = 'command/join-message'
permission = "command/join-message",
}
--- When a players data loads show their message
@@ -19,25 +19,25 @@ CustomMessages:on_load(function(player_name, player_message)
if custom_message then
game.print(custom_message, player.color)
else
player.print{'join-message.greet', {'links.discord'}}
player.print{ "join-message.greet", { "links.discord" } }
end
end)
--- Set your custom join message
-- @command join-message
-- @tparam string message The custom join message that will be used
Commands.new_command('join-message', 'Sets your custom join message')
:add_param('message', false, 'string-max-length', 255)
:enable_auto_concat()
:register(function(player, message)
if not player then return end
CustomMessages:set(player, message)
return {'join-message.message-set'}
end)
Commands.new_command("join-message", "Sets your custom join message")
:add_param("message", false, "string-max-length", 255)
:enable_auto_concat()
:register(function(player, message)
if not player then return end
CustomMessages:set(player, message)
return { "join-message.message-set" }
end)
Commands.new_command('join-message-clear', 'Clear your join message')
:register(function(player)
if not player then return end
CustomMessages:remove(player)
return {'join-message.message-cleared'}
end)
Commands.new_command("join-message-clear", "Clear your join message")
:register(function(player)
if not player then return end
CustomMessages:remove(player)
return { "join-message.message-cleared" }
end)

View File

@@ -1,15 +1,15 @@
--- Stores the language used to join the server
-- @data Language
local Event = require("modules/exp_legacy/utils/event") ---@dep utils.event
local Event = require("modules/exp_legacy/utils/event") --- @dep utils.event
local PlayerData = require("modules.exp_legacy.expcore.player_data") --- @dep expcore.player_data
local LocalLanguage = PlayerData.Statistics:combine('LocalLanguage')
local LocalLanguage = PlayerData.Statistics:combine("LocalLanguage")
LocalLanguage:set_default("Unknown")
--- Creates translation request on_load of a player
LocalLanguage:on_load(function(player_name, _)
local player = game.players[player_name]
player.request_translation({"language.local-language"})
player.request_translation{ "language.local-language" }
end)
--- Resolves translation request for language setting
@@ -31,4 +31,4 @@ Event.add(defines.events.on_string_translated, function(event)
-- Change LocalLanguage value for the player to the recognized one
local language = event.result
LocalLanguage:set(player, language)
end)
end)

View File

@@ -1,26 +1,22 @@
local Commands = require("modules.exp_legacy.expcore.commands") --- @dep expcore.commands
local config = require("modules.exp_legacy.config.personal_logistic") --- @dep config.personal-logistic
local pl = {}
function pl.pl(type, target, amount)
local function pl(type, target, amount)
local c
local s
if type == 'p' then
if type == "p" then
c = target.clear_personal_logistic_slot
s = target.set_personal_logistic_slot
elseif type == 's' then
elseif type == "s" then
c = target.clear_vehicle_logistic_slot
s = target.set_vehicle_logistic_slot
else
return
end
for _, v in pairs(config.request) do
c(v.key)
c(config.start + v.key)
end
if (amount < 0) then
@@ -33,65 +29,58 @@ function pl.pl(type, target, amount)
local v_min = math.ceil(v.min * amount)
local v_max = math.ceil(v.max * amount)
if v.stack and v.stack ~= 1 and v.type ~= 'weapon' then
if v.stack ~= nil and v.stack ~= 1 and v.type ~= "weapon" then
v_min = math.floor(v_min / v.stack) * v.stack
v_max = math.ceil(v_max / v.stack) * v.stack
end
if v.upgrade_of == nil then
if v.type then
if v.type ~= nil then
if stats.get_input_count(k) < config.production_required[v.type] then
if v_min > 0 then
if v_min == v_max then
v_min = math.floor((v_max * 0.5) / v.stack) * v.stack
end
else
v_min = 0
end
end
end
s(v.key, {name=k, min=v_min, max=v_max})
s(config.start + v.key, { name = k, min = v_min, max = v_max })
else
if v.type then
if v.type ~= nil then
if stats.get_input_count(k) >= config.production_required[v.type] then
s(v.key, {name=k, min=v_min, max=v_max})
s(config.start + v.key, { name = k, min = v_min, max = v_max })
local vuo = v.upgrade_of
while vuo do
s(config.request[vuo].key, {name=vuo, min=0, max=0})
while (vuo ~= nil) do
s(config.start + config.request[vuo].key, { name = vuo, min = 0, max = 0 })
vuo = config.request[vuo].upgrade_of
end
else
s(v.key, {name=k, min=0, max=v_max})
s(config.start + v.key, { name = k, min = 0, max = v_max })
end
end
end
end
end
Commands.new_command('personal-logistic', {'expcom-personal-logistics'}, 'Set Personal Logistic (-1 to cancel all) (Select spidertron to edit spidertron)')
:add_param('amount', 'integer-range', -1, 10)
:add_alias('pl')
:register(function(player, amount)
if player.force.technologies['logistic-robotics'].researched then
if player.selected then
if player.selected.name == 'spidertron' then
pl.pl('s', player.selected, amount / 10)
Commands.new_command("personal-logistic", "Set Personal Logistic (-1 to cancel all) (Select spidertron to edit spidertron)")
:add_param("amount", "integer-range", -1, 10)
:add_alias("pl")
:register(function(player, amount)
if player.force.technologies["logistic-robotics"].researched then
if player.selected ~= nil then
if player.selected.name == "spidertron" then
pl("s", player.selected, amount / 10)
return Commands.success
end
else
pl("p", player, amount / 10)
return Commands.success
end
else
pl.pl('p', player, amount / 10)
return Commands.success
player.print("Personal Logistic not researched")
end
else
player.print('Personal Logistic not researched')
end
end)
return pl
end)

View File

@@ -7,13 +7,13 @@ local config = require("modules.exp_legacy.config.preset_player_colours") --- @d
--- Stores the colour that the player wants
local PlayerData = require("modules.exp_legacy.expcore.player_data") --- @dep expcore.player_data
local PlayerColours = PlayerData.Settings:combine('Colour')
local PlayerColours = PlayerData.Settings:combine("Colour")
PlayerColours:set_metadata{
stringify = function(value)
if not value then return 'None set' end
if not value then return "None set" end
local c = value[1]
return string.format('Red: %d Green: %d Blue: %d', c[1], c[2], c[3])
end
return string.format("Red: %d Green: %d Blue: %d", c[1], c[2], c[3])
end,
}
--- Used to compact player colours to take less space
@@ -22,13 +22,13 @@ local function compact(colour)
return {
floor(colour.r * 255),
floor(colour.g * 255),
floor(colour.b * 255)
floor(colour.b * 255),
}
end
--- Returns a colour that is a bit lighter than the one given
local function lighten(c)
return {r = 255 - (255 - c.r) * 0.5, g = 255 - (255 - c.g) * 0.5, b = 255 - (255 - c.b) * 0.5, a = 255}
return { r = 255 - (255 - c.r) * 0.5, g = 255 - (255 - c.g) * 0.5, b = 255 - (255 - c.b) * 0.5, a = 255 }
end
--- When your data loads apply the players colour, or a random on if none is saved
@@ -36,13 +36,14 @@ PlayerColours:on_load(function(player_name, player_colour)
if not player_colour then
local preset = config.players[player_name]
if preset then
player_colour = {preset, lighten(preset)}
player_colour = { preset, lighten(preset) }
else
local colour_name = 'white'
local colour_name = "white"
while config.disallow[colour_name] do
colour_name = table.get_random_dictionary_entry(Colours, true)
end
player_colour = {Colours[colour_name], lighten(Colours[colour_name])}
player_colour = { Colours[colour_name], lighten(Colours[colour_name]) }
end
end
@@ -53,10 +54,10 @@ end)
--- Save the players color when they use the color command
Event.add(defines.events.on_console_command, function(event)
if event.command ~= 'color' then return end
if event.parameters == '' then return end
if event.command ~= "color" then return end
if event.parameters == "" then return end
if not event.player_index then return end
local player = game.players[event.player_index]
if not player or not player.valid then return end
PlayerColours:set(player, {compact(player.color), compact(player.chat_color)})
end)
PlayerColours:set(player, { compact(player.color), compact(player.chat_color) })
end)

View File

@@ -8,15 +8,16 @@ local config = require("modules.exp_legacy.config.preset_player_quickbar") --- @
--- Stores the quickbar filters for a player
local PlayerData = require("modules.exp_legacy.expcore.player_data") --- @dep expcore.player_data
local PlayerFilters = PlayerData.Settings:combine('QuickbarFilters')
local PlayerFilters = PlayerData.Settings:combine("QuickbarFilters")
PlayerFilters:set_metadata{
permission = 'command/save-quickbar',
permission = "command/save-quickbar",
stringify = function(value)
if not value then return 'No filters set' end
if not value then return "No filters set" end
local count = 0
for _ in pairs(value) do count = count + 1 end
return count..' filters set'
end
return count .. " filters set"
end,
}
--- Loads your quickbar preset
@@ -25,7 +26,7 @@ PlayerFilters:on_load(function(player_name, filters)
if not filters then return end
local player = game.players[player_name]
for i, item_name in pairs(filters) do
if item_name ~= nil and item_name ~= '' then
if item_name ~= nil and item_name ~= "" then
player.set_quick_bar_slot(i, item_name)
end
end
@@ -36,32 +37,32 @@ local ignoredItems = {
["blueprint-book"] = true,
["deconstruction-planner"] = true,
["spidertron-remote"] = true,
["upgrade-planner"] = true
["upgrade-planner"] = true,
}
--- Saves your quickbar preset to the script-output folder
-- @command save-quickbar
Commands.new_command('save-quickbar', 'Saves your Quickbar preset items to file')
:add_alias('save-toolbar')
:register(function(player)
local filters = {}
Commands.new_command("save-quickbar", "Saves your Quickbar preset items to file")
:add_alias("save-toolbar")
:register(function(player)
local filters = {}
for i = 1, 100 do
local slot = player.get_quick_bar_slot(i)
-- Need to filter out blueprint and blueprint books because the slot is a LuaItemPrototype and does not contain a way to export blueprint data
if slot ~= nil then
local ignored = ignoredItems[slot.name]
if ignored ~= true then
filters[i] = slot.name
for i = 1, 100 do
local slot = player.get_quick_bar_slot(i)
-- Need to filter out blueprint and blueprint books because the slot is a LuaItemPrototype and does not contain a way to export blueprint data
if slot ~= nil then
local ignored = ignoredItems[slot.name]
if ignored ~= true then
filters[i] = slot.name
end
end
end
end
if next(filters) then
PlayerFilters:set(player, filters)
else
PlayerFilters:remove(player)
end
if next(filters) then
PlayerFilters:set(player, filters)
else
PlayerFilters:remove(player)
end
return {'quickbar.saved'}
end)
return { "quickbar.saved" }
end)

View File

@@ -1,10 +1,9 @@
local Event = require("modules/exp_legacy/utils/event") ---@dep utils.event
local Storage = require("modules/exp_util/storage") ---@dep utils.global
local config = require("modules.exp_legacy.config.statistics") ---@dep config.statistics
local Event = require("modules/exp_legacy/utils/event") --- @dep utils.event
local Storage = require("modules/exp_util/storage") --- @dep utils.global
local config = require("modules.exp_legacy.config.statistics") --- @dep config.statistics
local format_time = _C.format_time
local floor = math.floor
local afk_required = 5*3600 -- 5 minutes
local afk_required = 5 * 3600 -- 5 minutes
--- Stores players who have been created, required to avoid loss of data
local new_players = {}
@@ -17,7 +16,7 @@ local PlayerData = require("modules.exp_legacy.expcore.player_data") --- @dep ex
local AllPlayerData = PlayerData.All
local Statistics = PlayerData.Statistics
Statistics:set_metadata{
display_order = config.display_order
display_order = config.display_order,
}
--- Update your statistics with any which happened before the data was valid
@@ -49,27 +48,27 @@ end)
--- Used to format time in minute format
local function format_minutes(value)
return format_time(value*3600, {
return format_time(value * 3600, {
long = true,
hours = true,
minutes = true
minutes = true,
})
end
--- Used to format time into a clock
local function format_clock(value)
return format_time(value*3600, {
hours=true,
minutes=true,
seconds=false,
time=false,
string=true
return format_time(value * 3600, {
hours = true,
minutes = true,
seconds = false,
time = false,
string = true,
})
end
--- Add MapsPlayed if it is enabled
if config.MapsPlayed then
Statistics:combine('MapsPlayed')
Statistics:combine("MapsPlayed")
Event.add(defines.events.on_player_created, function(event)
local player = game.players[event.player_index]
new_players[player.name] = true
@@ -79,8 +78,14 @@ end
--- Add Playtime and AfkTime if it is enabled
if config.Playtime or config.AfkTime then
local playtime, afk_time
if config.Playtime then playtime = Statistics:combine('Playtime') playtime:set_metadata{stringify=format_minutes, stringify_short=format_clock} end
if config.AfkTime then afk_time = Statistics:combine('AfkTime') afk_time:set_metadata{stringify=format_minutes, stringify_short=format_clock} end
if config.Playtime then
playtime = Statistics:combine("Playtime")
playtime:set_metadata{ stringify = format_minutes, stringify_short = format_clock }
end
if config.AfkTime then
afk_time = Statistics:combine("AfkTime")
afk_time:set_metadata{ stringify = format_minutes, stringify_short = format_clock }
end
Event.on_nth_tick(3600, function()
if game.tick == 0 then return end
for _, player in pairs(game.connected_players) do
@@ -92,8 +97,8 @@ end
--- Add DistanceTravelled if it is enabled
if config.DistanceTravelled then
local stat = Statistics:combine('DistanceTravelled')
stat:set_metadata{unit=' tiles'}
local stat = Statistics:combine("DistanceTravelled")
stat:set_metadata{ unit = " tiles" }
Event.add(defines.events.on_player_changed_position, function(event)
local player = game.players[event.player_index]
if not player.valid or not player.connected or player.afk_time > afk_required then return end
@@ -104,18 +109,22 @@ end
--- Add MachinesRemoved and TreesDestroyed and config.OreMined if it is enabled
if config.MachinesRemoved or config.TreesDestroyed or config.OreMined then
local machines, trees, ore
if config.MachinesRemoved then machines = Statistics:combine('MachinesRemoved') end
if config.TreesDestroyed then trees = Statistics:combine('TreesDestroyed') end
if config.OreMined then ore = Statistics:combine('OreMined') end
if config.MachinesRemoved then machines = Statistics:combine("MachinesRemoved") end
if config.TreesDestroyed then trees = Statistics:combine("TreesDestroyed") end
if config.OreMined then ore = Statistics:combine("OreMined") end
local function on_event(event)
if not event.player_index then return end -- Check player is valid
if not event.player_index then return end -- Check player is valid
local player = game.players[event.player_index]
if not player.valid or not player.connected then return end
local entity = event.entity -- Check entity is valid
if not entity.valid then return end
if entity.type == 'resource' then ore:increment(player)
elseif entity.type == 'tree' then trees:increment(player)
elseif entity.force == player.force then machines:increment(player) end
if entity.type == "resource" then
ore:increment(player)
elseif entity.type == "tree" then
trees:increment(player)
elseif entity.force == player.force then
machines:increment(player)
end
end
Event.add(defines.events.on_marked_for_deconstruction, on_event)
Event.add(defines.events.on_player_mined_entity, on_event)
@@ -123,35 +132,35 @@ end
--- Add DamageDealt if it is enabled
if config.DamageDealt then
local stat = Statistics:combine('DamageDealt')
local stat = Statistics:combine("DamageDealt")
Event.add(defines.events.on_entity_damaged, function(event)
local character = event.cause -- Check character is valid
if not character or not character.valid or character.type ~= 'character' then return end
if not character or not character.valid or character.type ~= "character" then return end
local player = character.player -- Check player is valid
if not player.valid or not player.connected then return end
local entity = event.entity -- Check entity is valid
if not entity.valid or entity.force == player.force or entity.force.name == 'neutral' then return end
if not entity.valid or entity.force == player.force or entity.force.name == "neutral" then return end
stat:increment(player, floor(event.final_damage_amount))
end)
end
--- Add Kills if it is enabled
if config.Kills then
local stat = Statistics:combine('Kills')
local stat = Statistics:combine("Kills")
Event.add(defines.events.on_entity_died, function(event)
local character = event.cause -- Check character is valid
if not character or not character.valid or character.type ~= 'character' then return end
if not character or not character.valid or character.type ~= "character" then return end
local player = character.player -- Check player is valid
if not player or not player.valid or not player.connected then return end
local entity = event.entity -- Check entity is valid
if not entity.valid or entity.force == player.force or entity.force.name == 'neutral' then return end
if not entity.valid or entity.force == player.force or entity.force.name == "neutral" then return end
stat:increment(player)
end)
end
--- Add RocketsLaunched if it is enabled
if config.RocketsLaunched then
local stat = Statistics:combine('RocketsLaunched')
local stat = Statistics:combine("RocketsLaunched")
Event.add(defines.events.on_rocket_launched, function(event)
local silo = event.rocket_silo -- Check silo is valid
if not silo or not silo.valid then return end
@@ -165,9 +174,9 @@ end
--- Add RocketsLaunched if it is enabled
if config.ResearchCompleted then
local stat = Statistics:combine('ResearchCompleted')
local stat = Statistics:combine("ResearchCompleted")
Event.add(defines.events.on_research_finished, function(event)
local research = event.research -- Check research is valid
local research = event.research -- Check research is valid
if event.by_script or not research or not research.valid then return end
local force = research.force -- Check force is valid
if not force or not force.valid then return end

View File

@@ -11,22 +11,22 @@ require("modules.exp_legacy.config.expcore.command_color_parse")
--- Stores the tag for a player
local PlayerData = require("modules.exp_legacy.expcore.player_data") --- @dep expcore.player_data
local PlayerTags = PlayerData.Settings:combine('Tag')
local PlayerTagColors = PlayerData.Settings:combine('TagColor')
local PlayerTags = PlayerData.Settings:combine("Tag")
local PlayerTagColors = PlayerData.Settings:combine("TagColor")
PlayerTags:set_metadata{
permission = 'command/tag'
permission = "command/tag",
}
PlayerTagColors:set_metadata{
permission = 'command/tag-color'
permission = "command/tag-color",
}
local set_tag = function (player, tag, color)
if tag == nil or tag == '' then
player.tag = ''
local set_tag = function(player, tag, color)
if tag == nil or tag == "" then
player.tag = ""
elseif color then
player.tag = '- [color='.. color ..']'..tag..'[/color]'
player.tag = "- [color=" .. color .. "]" .. tag .. "[/color]"
else
player.tag = '- '..tag
player.tag = "- " .. tag
end
end
@@ -49,40 +49,40 @@ end)
--- Sets your player tag.
-- @command tag
-- @tparam string tag the tag that will be after the name, there is a max length
Commands.new_command('tag', 'Sets your player tag.')
:add_param('tag', false, 'string-max-length', 20)
:enable_auto_concat()
:register(function(player, tag)
PlayerTags:set(player, tag)
end)
Commands.new_command("tag", "Sets your player tag.")
:add_param("tag", false, "string-max-length", 20)
:enable_auto_concat()
:register(function(player, tag)
PlayerTags:set(player, tag)
end)
--- Sets your player tag color.
-- @command tag
-- @tparam string color name.
Commands.new_command('tag-color', 'Sets your player tag color.')
:add_param('color', false, 'color')
:enable_auto_concat()
:register(function(player, color)
PlayerTagColors:set(player, color)
end)
Commands.new_command("tag-color", "Sets your player tag color.")
:add_param("color", false, "color")
:enable_auto_concat()
:register(function(player, color)
PlayerTagColors:set(player, color)
end)
--- Clears your tag. Or another player if you are admin.
-- @command tag-clear
-- @tparam[opt=self] LuaPlayer player the player to remove the tag from, nil will apply to self
Commands.new_command('tag-clear', 'Clears your tag. Or another player if you are admin.')
:add_param('player', true, 'player-role')
:set_defaults{player=function(player)
return player -- default is the user using the command
end}
:register(function(player, action_player)
if action_player.index == player.index then
-- no player given so removes your tag
PlayerTags:remove(action_player)
elseif Roles.player_allowed(player, 'command/clear-tag/always') then
-- player given and user is admin so clears that player's tag
PlayerTags:remove(action_player)
else
-- user is not admin and tried to clear another users tag
return Commands.error{'expcore-commands.unauthorized'}
end
end)
Commands.new_command("tag-clear", "Clears your tag. Or another player if you are admin.")
:add_param("player", true, "player-role")
:set_defaults{ player = function(player)
return player -- default is the user using the command
end }
:register(function(player, action_player)
if action_player.index == player.index then
-- no player given so removes your tag
PlayerTags:remove(action_player)
elseif Roles.player_allowed(player, "command/clear-tag/always") then
-- player given and user is admin so clears that player's tag
PlayerTags:remove(action_player)
else
-- user is not admin and tried to clear another users tag
return Commands.error{ "expcore-commands.unauthorized" }
end
end)

View File

@@ -22,7 +22,7 @@ local created_items = function()
["pistol"] = 1,
["firearm-magazine"] = 10,
["burner-mining-drill"] = 1,
["stone-furnace"] = 1
["stone-furnace"] = 1,
}
end
@@ -30,13 +30,13 @@ local respawn_items = function()
return
{
["pistol"] = 1,
["firearm-magazine"] = 10
["firearm-magazine"] = 10,
}
end
if use_silo_script then
for k, v in pairs(silo_script.get_events()) do
Event.add(k, v)
Event.add(k, v)
end
end
@@ -45,13 +45,13 @@ Event.add(defines.events.on_player_created, function(event)
util.insert_safe(player, global.created_items)
local r = global.chart_distance or 200
player.force.chart(player.surface, {{player.position.x - r, player.position.y - r}, {player.position.x + r, player.position.y + r}})
player.force.chart(player.surface, { { player.position.x - r, player.position.y - r }, { player.position.x + r, player.position.y + r } })
if not global.skip_intro then
if game.is_multiplayer() then
player.print({"msg-intro"})
player.print{ "msg-intro" }
else
game.show_message_dialog{text = {"msg-intro"}}
game.show_message_dialog{ text = { "msg-intro" } }
end
end
@@ -88,37 +88,37 @@ if use_silo_script then
end
remote.add_interface("freeplay",
{
get_created_items = function()
return global.created_items
end,
set_created_items = function(map)
global.created_items = map
end,
get_respawn_items = function()
return global.respawn_items
end,
set_respawn_items = function(map)
global.respawn_items = map
end,
set_skip_intro = function(bool)
global.skip_intro = bool
end,
set_chart_distance = function(value)
global.chart_distance = tonumber(value)
end,
set_disable_crashsite = function()
end,
get_ship_items = function()
return {}
end,
set_ship_items = function()
return
end,
get_debris_items = function ()
return {}
end,
set_debris_items = function ()
return
end
})
{
get_created_items = function()
return global.created_items
end,
set_created_items = function(map)
global.created_items = map
end,
get_respawn_items = function()
return global.respawn_items
end,
set_respawn_items = function(map)
global.respawn_items = map
end,
set_skip_intro = function(bool)
global.skip_intro = bool
end,
set_chart_distance = function(value)
global.chart_distance = tonumber(value)
end,
set_disable_crashsite = function()
end,
get_ship_items = function()
return {}
end,
set_ship_items = function()
return
end,
get_debris_items = function()
return {}
end,
set_debris_items = function()
return
end,
})

View File

@@ -5,186 +5,192 @@ local config = require("modules.exp_legacy.config.graftorio")
local lib = {}
lib.collect_production = function()
for _, force in pairs(game.forces) do
general.data.output[force.name].production = {}
for _, surface in pairs(game.surfaces) do
---@class ItemStats
---@field count number
for _, force in pairs(game.forces) do
general.data.output[force.name].production = {}
for _, surface in pairs(game.surfaces) do
--- @class ItemStats
--- @field count number
---@class ProductionStatistics
---@field item_input table<string, ItemStats>
---@field item_output table<string, ItemStats>
---@field fluid_input table<string, ItemStats>
---@field fluid_output table<string, ItemStats>
---@field kill_input table<string, ItemStats>
---@field kill_output table<string, ItemStats>
---@field build_input table<string, ItemStats>
---@field build_output table<string, ItemStats>
local stats = {
item_input = {},
item_output = {},
fluid_input = {},
fluid_output = {},
kill_input = {},
kill_output = {},
build_input = {},
build_output = {},
}
--- @class ProductionStatistics
--- @field item_input table<string, ItemStats>
--- @field item_output table<string, ItemStats>
--- @field fluid_input table<string, ItemStats>
--- @field fluid_output table<string, ItemStats>
--- @field kill_input table<string, ItemStats>
--- @field kill_output table<string, ItemStats>
--- @field build_input table<string, ItemStats>
--- @field build_output table<string, ItemStats>
local stats = {
item_input = {},
item_output = {},
fluid_input = {},
fluid_output = {},
kill_input = {},
kill_output = {},
build_input = {},
build_output = {},
}
for name, count in pairs(force.get_item_production_statistics(surface).input_counts) do
local itemstats = stats.item_input[name] or {}
itemstats.count = count
stats.item_input[name] = itemstats
end
for name, count in pairs(force.get_item_production_statistics(surface).output_counts) do
local itemstats = stats.item_output[name] or {}
itemstats.count = count
stats.item_output[name] = itemstats
end
for name, count in pairs(force.get_item_production_statistics(surface).input_counts) do
local itemstats = stats.item_input[name] or {}
itemstats.count = count
stats.item_input[name] = itemstats
end
for name, count in pairs(force.get_fluid_production_statistics(surface).input_counts) do
local fluidstats = stats.fluid_input[name] or {}
fluidstats.count = count
stats.fluid_input[name] = fluidstats
end
for name, count in pairs(force.get_fluid_production_statistics(surface).output_counts) do
local fluidstats = stats.fluid_output[name] or {}
fluidstats.count = count
stats.fluid_output[name] = fluidstats
end
for name, count in pairs(force.get_item_production_statistics(surface).output_counts) do
local itemstats = stats.item_output[name] or {}
itemstats.count = count
stats.item_output[name] = itemstats
end
for name, count in pairs(force.get_kill_count_statistics(surface).input_counts) do
local killstats = stats.kill_input[name] or {}
killstats.count = count
stats.kill_input[name] = killstats
end
for name, count in pairs(force.get_kill_count_statistics(surface).output_counts) do
local killstats = stats.kill_output[name] or {}
killstats.count = count
stats.kill_output[name] = killstats
end
for name, count in pairs(force.get_fluid_production_statistics(surface).input_counts) do
local fluidstats = stats.fluid_input[name] or {}
fluidstats.count = count
stats.fluid_input[name] = fluidstats
end
for name, count in pairs(force.get_entity_build_count_statistics(surface).input_counts) do
local buildstats = stats.build_input[name] or {}
buildstats.count = count
stats.build_input[name] = buildstats
end
for name, count in pairs(force.get_entity_build_count_statistics(surface).output_counts) do
local buildstats = stats.build_output[name] or {}
buildstats.count = count
stats.build_output[name] = buildstats
end
for name, count in pairs(force.get_fluid_production_statistics(surface).output_counts) do
local fluidstats = stats.fluid_output[name] or {}
fluidstats.count = count
stats.fluid_output[name] = fluidstats
end
general.data.output[force.name].production[surface.name] = stats
end
end
for name, count in pairs(force.get_kill_count_statistics(surface).input_counts) do
local killstats = stats.kill_input[name] or {}
killstats.count = count
stats.kill_input[name] = killstats
end
for name, count in pairs(force.get_kill_count_statistics(surface).output_counts) do
local killstats = stats.kill_output[name] or {}
killstats.count = count
stats.kill_output[name] = killstats
end
for name, count in pairs(force.get_entity_build_count_statistics(surface).input_counts) do
local buildstats = stats.build_input[name] or {}
buildstats.count = count
stats.build_input[name] = buildstats
end
for name, count in pairs(force.get_entity_build_count_statistics(surface).output_counts) do
local buildstats = stats.build_output[name] or {}
buildstats.count = count
stats.build_output[name] = buildstats
end
general.data.output[force.name].production[surface.name] = stats
end
end
end
lib.collect_loginet = function()
for _, force in pairs(game.forces) do
---@class RobotStatistics
---@field all_construction_robots uint
---@field available_construction_robot uint
---@field all_logistic_robots uint
---@field available_logistic_robots uint
---@field charging_robot_count uint
---@field to_charge_robot_count uint
---@field items table<string, uint>
---@field pickups table<string, uint>
---@field deliveries table<string, uint>
local stats = {
all_construction_robots = 0,
available_construction_robots = 0,
for _, force in pairs(game.forces) do
--- @class RobotStatistics
--- @field all_construction_robots uint
--- @field available_construction_robot uint
--- @field all_logistic_robots uint
--- @field available_logistic_robots uint
--- @field charging_robot_count uint
--- @field to_charge_robot_count uint
--- @field items table<string, uint>
--- @field pickups table<string, uint>
--- @field deliveries table<string, uint>
local stats = {
all_construction_robots = 0,
available_construction_robots = 0,
all_logistic_robots = 0,
available_logistic_robots = 0,
all_logistic_robots = 0,
available_logistic_robots = 0,
charging_robot_count = 0,
to_charge_robot_count = 0,
charging_robot_count = 0,
to_charge_robot_count = 0,
items = {},
pickups = {},
deliveries = {},
}
for _, networks in pairs(force.logistic_networks) do
for _, network in pairs(networks) do
stats.available_construction_robots = network.available_construction_robots
stats.all_construction_robots = network.all_construction_robots
items = {},
pickups = {},
deliveries = {},
}
for _, networks in pairs(force.logistic_networks) do
for _, network in pairs(networks) do
stats.available_construction_robots = network.available_construction_robots
stats.all_construction_robots = network.all_construction_robots
stats.available_logistic_robots = network.available_logistic_robots
stats.all_logistic_robots = network.all_logistic_robots
stats.available_logistic_robots = network.available_logistic_robots
stats.all_logistic_robots = network.all_logistic_robots
stats.charging_robot_count = 0
stats.to_charge_robot_count = 0
for _, cell in pairs(network.cells) do
stats.charging_robot_count = (stats.charging_robot_count) + cell.charging_robot_count
stats.to_charge_robot_count = (stats.to_charge_robot_count) + cell.to_charge_robot_count
end
stats.charging_robot_count = 0
stats.to_charge_robot_count = 0
for _, cell in pairs(network.cells) do
stats.charging_robot_count = (stats.charging_robot_count) + cell.charging_robot_count
stats.to_charge_robot_count = (stats.to_charge_robot_count) + cell.to_charge_robot_count
end
if config.modules.logistorage then
for name, v in pairs(network.get_contents()) do
stats.items[name] = (stats.items[name] or 0) + v
end
if config.modules.logistorage then
for name, v in pairs(network.get_contents()) do
stats.items[name] = (stats.items[name] or 0) + v
end
-- pickups and deliveries of items
for _, point_list in pairs({ network.provider_points, network.requester_points, network.storage_points }) do
for _, point in pairs(point_list) do
for name, qty in pairs(point.targeted_items_pickup) do
stats.pickups[name] = (stats.pickups[name] or 0) + qty
end
for name, qty in pairs(point.targeted_items_deliver) do
stats.deliveries[name] = (stats.deliveries[name] or 0) + qty
end
end
end
end
end
end
general.data.output[force.name].robots = stats
end
-- pickups and deliveries of items
for _, point_list in pairs{ network.provider_points, network.requester_points, network.storage_points } do
for _, point in pairs(point_list) do
for name, qty in pairs(point.targeted_items_pickup) do
stats.pickups[name] = (stats.pickups[name] or 0) + qty
end
for name, qty in pairs(point.targeted_items_deliver) do
stats.deliveries[name] = (stats.deliveries[name] or 0) + qty
end
end
end
end
end
end
general.data.output[force.name].robots = stats
end
end
---@class Research
---@field name string
---@field level uint
---@field progress double
--- @class Research
--- @field name string
--- @field level uint
--- @field progress double
Event.add(defines.events.on_research_finished, function(evt)
local research = evt.research
if not general.data.output[research.force.name] then general.data.output[research.force.name] = {} end
if not general.data.output[research.force.name].research then general.data.output[research.force.name].research = {} end
local research = evt.research
if not general.data.output[research.force.name] then general.data.output[research.force.name] = {} end
if not general.data.output[research.force.name].research then general.data.output[research.force.name].research = {} end
local force_research = general.data.output[research.force.name].research or {}
table.remove(force_research, 1)
general.data.output[research.force.name].research = force_research
local force_research = general.data.output[research.force.name].research or {}
table.remove(force_research, 1)
general.data.output[research.force.name].research = force_research
end)
Event.add(defines.events.on_research_started, function(evt)
-- move queue up
local research = evt.research
if not general.data.output[research.force.name].research then general.data.output[research.force.name].research = {} end
-- move queue up
local research = evt.research
if not general.data.output[research.force.name].research then general.data.output[research.force.name].research = {} end
local force_research = general.data.output[research.force.name].research or {}
table.remove(force_research, 1)
general.data.output[research.force.name].research = force_research
local force_research = general.data.output[research.force.name].research or {}
table.remove(force_research, 1)
general.data.output[research.force.name].research = force_research
end)
Event.on_nth_tick(60, function()
for _, force in pairs(game.forces) do
if not general.data.output[force.name].research then general.data.output[force.name].research = {} end
for _, force in pairs(game.forces) do
if not general.data.output[force.name].research then general.data.output[force.name].research = {} end
local force_research = {}
-- this works even if the queue is disabled, but it will always be just 1 long in that case
for _, research in pairs(force.research_queue) do
table.insert(force_research, {
name = research.name,
level = research.level,
progress = force.get_saved_technology_progress(research) or 0,
})
end
local force_research = {}
-- this works even if the queue is disabled, but it will always be just 1 long in that case
for _, research in pairs(force.research_queue) do
table.insert(force_research, {
name = research.name,
level = research.level,
progress = force.get_saved_technology_progress(research) or 0,
})
end
general.data.output[force.name].research = force_research
end
general.data.output[force.name].research = force_research
end
end)
return lib

View File

@@ -4,60 +4,60 @@ local Storage = require("modules/exp_util/storage")
local lib = {}
lib.data = {
output = {}
output = {},
}
Storage.register(lib.data, function(tbl)
lib.data = tbl
lib.data = tbl
end)
---@class Statistics
---@field production ProductionStatistics?
---@field robots RobotStatistics?
---@field other OtherStatistics?
---@field research Research[]?
--- @class Statistics
--- @field production ProductionStatistics?
--- @field robots RobotStatistics?
--- @field other OtherStatistics?
--- @field research Research[]?
Event.on_init(function()
---@type table<string, Statistics>
lib.data.output = {}
for _, force in pairs(game.forces) do
lib.data.output[force.name] = {}
end
--- @type table<string, Statistics>
lib.data.output = {}
for _, force in pairs(game.forces) do
lib.data.output[force.name] = {}
end
end)
---@class OtherStatistics
---@field tick uint
---@field evolution EvolutionStatistics
--- @class OtherStatistics
--- @field tick uint
--- @field evolution EvolutionStatistics
---@class EvolutionStatistics
---@field evolution_factor double
---@field evolution_factor_by_pollution double
---@field evolution_factor_by_time double
---@field evolution_factor_by_killing_spawners double
--- @class EvolutionStatistics
--- @field evolution_factor double
--- @field evolution_factor_by_pollution double
--- @field evolution_factor_by_time double
--- @field evolution_factor_by_killing_spawners double
lib.collect_other = function()
for _, force in pairs(game.forces) do
---@type OtherStatistics
local other = lib.data.output[force.name].other or {}
for _, force in pairs(game.forces) do
--- @type OtherStatistics
local other = lib.data.output[force.name].other or {}
other.evolution = {
evolution_factor = force.evolution_factor,
evolution_factor_by_pollution = force.evolution_factor_by_pollution,
evolution_factor_by_time = force.evolution_factor_by_time,
evolution_factor_by_killing_spawners = force.evolution_factor_by_killing_spawners
}
for k, v in pairs(other) do
lib.data.output[force.name].other[k] = v
end
end
other.evolution = {
evolution_factor = force.evolution_factor,
evolution_factor_by_pollution = force.evolution_factor_by_pollution,
evolution_factor_by_time = force.evolution_factor_by_time,
evolution_factor_by_killing_spawners = force.evolution_factor_by_killing_spawners,
}
for k, v in pairs(other) do
lib.data.output[force.name].other[k] = v
end
end
end
Event.add(defines.events.on_force_created, function(evt)
lib.data.output[evt.force.name] = {}
lib.data.output[evt.force.name] = {}
end)
Event.add(defines.events.on_forces_merged, function(evt)
lib.data.output[evt.source_name] = nil
lib.data.output[evt.source_name] = nil
end)
return lib

View File

@@ -5,23 +5,23 @@ local general = require("modules.exp_legacy.modules.graftorio.general")
local forcestats = nil
if config.modules.forcestats then
forcestats = require("modules.exp_legacy.modules.graftorio.forcestats")
forcestats = require("modules.exp_legacy.modules.graftorio.forcestats")
end
Commands.new_command("collectdata", "Collect data for RCON usage")
:add_param("location", true)
:register(function()
-- this must be first as it overwrites the stats
-- also makes the .other table for all forces
statics.collect_statics()
if config.modules.other then
general.collect_other()
end
if config.modules.forcestats then
---@cast forcestats -nil
forcestats.collect_production()
forcestats.collect_loginet()
end
rcon.print(game.table_to_json(general.data.output))
return Commands.success()
end)
:add_param("location", true)
:register(function()
-- this must be first as it overwrites the stats
-- also makes the .other table for all forces
statics.collect_statics()
if config.modules.other then
general.collect_other()
end
if config.modules.forcestats then
--- @cast forcestats -nil
forcestats.collect_production()
forcestats.collect_loginet()
end
rcon.print(game.table_to_json(general.data.output))
return Commands.success()
end)

View File

@@ -2,34 +2,35 @@ local general = require("modules.exp_legacy.modules.graftorio.general")
local lib = {}
---@class StaticStatistics
---@field tick uint
---@field online_players string[]
---@field mods table<string, string>
---@field seed table<string, uint>
--- @class StaticStatistics
--- @field tick uint
--- @field online_players string[]
--- @field mods table<string, string>
--- @field seed table<string, uint>
lib.collect_statics = function()
local stats = {}
stats.tick = game.tick
local stats = {}
stats.tick = game.tick
stats.online_players = {}
for _, player in pairs(game.connected_players) do
table.insert(stats.online_players, player.name)
end
stats.online_players = {}
for _, player in pairs(game.connected_players) do
table.insert(stats.online_players, player.name)
end
stats.mods = {}
for name, version in pairs(game.active_mods) do
stats.mods[name] = version
end
stats.mods = {}
for name, version in pairs(game.active_mods) do
stats.mods[name] = version
end
-- reason behind this is that the map gen settings can be changed during runtime so just get them fresh
stats.seed = {}
for _, surface in pairs(game.surfaces) do
stats.seed[surface.name] = surface.map_gen_settings.seed
end
for _, force in pairs(game.forces) do
general.data.output[force.name].other = stats
end
-- reason behind this is that the map gen settings can be changed during runtime so just get them fresh
stats.seed = {}
for _, surface in pairs(game.surfaces) do
stats.seed[surface.name] = surface.map_gen_settings.seed
end
for _, force in pairs(game.forces) do
general.data.output[force.name].other = stats
end
end
return lib

View File

@@ -23,279 +23,277 @@ end)
local autofill_container
local function rich_img(type, value)
return '[img='..type..'/'..value..']'
return "[img=" .. type .. "/" .. value .. "]"
end
--- Toggle entity section visibility
-- @element toggle_item_button
local toggle_section =
Gui.element{
type = 'sprite-button',
sprite = 'utility/expand',
tooltip = {'autofill.toggle-section-tooltip'},
style = "frame_action_button",
name = Gui.unique_static_name
}
:style(Gui.sprite_style(20))
:on_click(function(_, element, _)
local header_flow = element.parent
local flow_name = header_flow.caption
local flow = header_flow.parent.parent[flow_name]
if Gui.toggle_visible_state(flow) then
element.sprite = 'utility/collapse'
element.tooltip = {'autofill.toggle-section-collapse-tooltip'}
else
element.sprite = 'utility/expand'
element.tooltip = {'autofill.toggle-section-tooltip'}
end
end)
Gui.element{
type = "sprite-button",
sprite = "utility/expand",
tooltip = { "autofill.toggle-section-tooltip" },
style = "frame_action_button",
name = Gui.unique_static_name,
}
:style(Gui.sprite_style(20))
:on_click(function(_, element, _)
local header_flow = element.parent
local flow_name = header_flow.caption
local flow = header_flow.parent.parent[flow_name]
if Gui.toggle_visible_state(flow) then
element.sprite = "utility/collapse"
element.tooltip = { "autofill.toggle-section-collapse-tooltip" }
else
element.sprite = "utility/expand"
element.tooltip = { "autofill.toggle-section-tooltip" }
end
end)
--- Toggle enitity button, used for toggling autofill for the specific entity
-- All entity autofill settings will be ignored if its disabled
-- @element entity_toggle
local entity_toggle =
Gui.element(function(_, parent, entity_name)
return parent.add{
type = 'sprite-button',
sprite = 'utility/confirm_slot',
tooltip = {'autofill.toggle-entity-tooltip', rich_img('item', entity_name)},
style = 'shortcut_bar_button_green'
}
end)
:style(Gui.sprite_style(22))
:on_click(function(player, element, _)
local entity_name = string.match(element.parent.parent.name,'(.*)%-header')
if not autofill_player_settings[player.name] then return end
local setting = autofill_player_settings[player.name][entity_name]
if not setting then return end
if setting.enabled then
setting.enabled = false
element.sprite = 'utility/close_black'
element.style = 'shortcut_bar_button_red'
else
setting.enabled = true
element.sprite = 'utility/confirm_slot'
element.style = 'shortcut_bar_button_green'
end
-- Correct the button size
local style = element.style
style.padding = -2
style.height = 22
style.width = 22
end)
Gui.element(function(_, parent, entity_name)
return parent.add{
type = "sprite-button",
sprite = "utility/confirm_slot",
tooltip = { "autofill.toggle-entity-tooltip", rich_img("item", entity_name) },
style = "shortcut_bar_button_green",
}
end)
:style(Gui.sprite_style(22))
:on_click(function(player, element, _)
local entity_name = string.match(element.parent.parent.name, "(.*)%-header")
if not autofill_player_settings[player.name] then return end
local setting = autofill_player_settings[player.name][entity_name]
if not setting then return end
if setting.enabled then
setting.enabled = false
element.sprite = "utility/close_black"
element.style = "shortcut_bar_button_red"
else
setting.enabled = true
element.sprite = "utility/confirm_slot"
element.style = "shortcut_bar_button_green"
end
-- Correct the button size
local style = element.style
style.padding = -2
style.height = 22
style.width = 22
end)
--- Draw a section header and main scroll
-- @element autofill_section_container
local section =
Gui.element(function(definition, parent, section_name, table_size)
-- Draw the header for the section
local header = Gui.header(
parent,
{'autofill.toggle-section-caption', rich_img('item', section_name), {'entity-name.'..section_name}},
{'autofill.toggle-section-tooltip'},
true,
section_name..'-header'
)
Gui.element(function(definition, parent, section_name, table_size)
-- Draw the header for the section
local header = Gui.header(
parent,
{ "autofill.toggle-section-caption", rich_img("item", section_name), { "entity-name." .. section_name } },
{ "autofill.toggle-section-tooltip" },
true,
section_name .. "-header"
)
definition:triggers_events(header.parent.header_label)
definition:triggers_events(header.parent.header_label)
-- Right aligned button to toggle the section
header.caption = section_name
entity_toggle(header, section_name)
toggle_section(header)
-- Right aligned button to toggle the section
header.caption = section_name
entity_toggle(header, section_name)
toggle_section(header)
local section_table = parent.add{
type = 'table',
name = section_name,
column_count = table_size
}
local section_table = parent.add{
type = "table",
name = section_name,
column_count = table_size,
}
section_table.visible = false
section_table.visible = false
return definition:no_events(section_table)
end)
:on_click(function(_, element, event)
event.element = element.parent.alignment[toggle_section.name]
toggle_section:raise_event(event)
end)
return definition:no_events(section_table)
end)
:on_click(function(_, element, event)
event.element = element.parent.alignment[toggle_section.name]
toggle_section:raise_event(event)
end)
--- Toggle item button, used for toggling autofill for the specific item
-- @element toggle_item_button
local toggle_item_button =
Gui.element(function(_, parent, item)
return parent.add{
type = 'sprite-button',
sprite = 'item/'..item.name,
tooltip = {'autofill.toggle-tooltip', rich_img('item', item.name), item.category},
style = 'shortcut_bar_button_red'
}
end)
:style(Gui.sprite_style(32, nil, { right_margin = -3 }))
:on_click(function(player, element)
local item_name = element.parent.tooltip
local entity_name = element.parent.parent.parent.name
if not autofill_player_settings[player.name] then return end
local setting = autofill_player_settings[player.name][entity_name]
if not setting then return end
local item = setting.items[item_name]
if not item then return end
if item.enabled then
item.enabled = false
element.style = 'shortcut_bar_button_red'
else
item.enabled = true
element.style = 'shortcut_bar_button_green'
end
-- Correct the button size
local style = element.style
style.right_margin = -3
style.padding = -2
style.height = 32
style.width = 32
end)
Gui.element(function(_, parent, item)
return parent.add{
type = "sprite-button",
sprite = "item/" .. item.name,
tooltip = { "autofill.toggle-tooltip", rich_img("item", item.name), item.category },
style = "shortcut_bar_button_red",
}
end)
:style(Gui.sprite_style(32, nil, { right_margin = -3 }))
:on_click(function(player, element)
local item_name = element.parent.tooltip
local entity_name = element.parent.parent.parent.name
if not autofill_player_settings[player.name] then return end
local setting = autofill_player_settings[player.name][entity_name]
if not setting then return end
local item = setting.items[item_name]
if not item then return end
if item.enabled then
item.enabled = false
element.style = "shortcut_bar_button_red"
else
item.enabled = true
element.style = "shortcut_bar_button_green"
end
-- Correct the button size
local style = element.style
style.right_margin = -3
style.padding = -2
style.height = 32
style.width = 32
end)
--- Amount text field for a autofill item
-- @element amount_textfield
local amount_textfield =
Gui.element(function(_, parent, item)
return parent.add{
type = 'textfield',
text = item.amount,
tooltip = {'autofill.amount-tooltip', item.category },
clear_and_focus_on_right_click = true,
numeric = true,
allow_decimal = false,
allow_negative = false
Gui.element(function(_, parent, item)
return parent.add{
type = "textfield",
text = item.amount,
tooltip = { "autofill.amount-tooltip", item.category },
clear_and_focus_on_right_click = true,
numeric = true,
allow_decimal = false,
allow_negative = false,
}
end)
:style{
maximal_width = 40,
height = 31,
padding = -2,
}
end)
:style{
maximal_width = 40,
height = 31,
padding = -2
}
:on_text_changed(function(player, element, _)
local value = tonumber(element.text)
if not value then value = 0 end
local clamped = math.clamp(value, 0, 1000)
local item_name = element.parent.tooltip
local entity_name = element.parent.parent.parent.name
if not autofill_player_settings[player.name] then return end
local setting = autofill_player_settings[player.name][entity_name]
if not setting then return end
local item = setting.items[item_name]
if not item then return end
item.amount = clamped
if clamped ~= value then
element.text = clamped
player.print{'autofill.invalid', item.amount, rich_img('item', item.name), rich_img('entity', entity_name) }
return
end
end)
:on_text_changed(function(player, element, _)
local value = tonumber(element.text)
if not value then value = 0 end
local clamped = math.clamp(value, 0, 1000)
local item_name = element.parent.tooltip
local entity_name = element.parent.parent.parent.name
if not autofill_player_settings[player.name] then return end
local setting = autofill_player_settings[player.name][entity_name]
if not setting then return end
local item = setting.items[item_name]
if not item then return end
item.amount = clamped
if clamped ~= value then
element.text = clamped
player.print{ "autofill.invalid", item.amount, rich_img("item", item.name), rich_img("entity", entity_name) }
return
end
end)
--- Autofill setting, contains a button and a textbox
-- @element add_autofill_setting
local add_autofill_setting =
Gui.element(function(_, parent, item)
local toggle_flow = parent.add{ type = 'flow', name = 'toggle-setting-'..item.name, tooltip = item.name }
local amount_flow = parent.add{ type = 'flow', name = 'amount-setting-'..item.name, tooltip = item.name }
toggle_flow.style.padding = 0
amount_flow.style.padding = 0
toggle_item_button(toggle_flow, item)
amount_textfield(amount_flow, item)
end)
Gui.element(function(_, parent, item)
local toggle_flow = parent.add{ type = "flow", name = "toggle-setting-" .. item.name, tooltip = item.name }
local amount_flow = parent.add{ type = "flow", name = "amount-setting-" .. item.name, tooltip = item.name }
toggle_flow.style.padding = 0
amount_flow.style.padding = 0
toggle_item_button(toggle_flow, item)
amount_textfield(amount_flow, item)
end)
--- Autofill setting empty, contains filler button and textfield gui elements
-- @element add_empty_autofill_setting
local add_empty_autofill_setting =
Gui.element(function(_, parent)
local toggle_element = parent.add{
type = 'sprite-button'
}
toggle_element.style.right_margin = -3
toggle_element.style.width = 32
toggle_element.style.height = 32
toggle_element.enabled = false
local amount_element = parent.add{
type = 'textfield'
}
amount_element.style.maximal_width = 40
amount_element.style.height = 31
amount_element.style.padding = -2
amount_element.enabled = false
end)
Gui.element(function(_, parent)
local toggle_element = parent.add{
type = "sprite-button",
}
toggle_element.style.right_margin = -3
toggle_element.style.width = 32
toggle_element.style.height = 32
toggle_element.enabled = false
local amount_element = parent.add{
type = "textfield",
}
amount_element.style.maximal_width = 40
amount_element.style.height = 31
amount_element.style.padding = -2
amount_element.enabled = false
end)
--- Main gui container for the left flow
-- @element autofill_container
autofill_container =
Gui.element(function(definition, parent)
-- Draw the internal container
local container = Gui.container(parent, definition.name)
-- Draw the scroll container
local scroll_table = Gui.scroll_table(container, 400, 1, 'autofill-scroll-table')
-- Set the scroll panel to always show the scrollbar (not doing this will result in a changing gui size)
scroll_table.parent.vertical_scroll_policy = 'always'
-- Scroll panel has by default padding
scroll_table.parent.style.padding = 0
-- Remove the default gap that is added in a table between elements
scroll_table.style.vertical_spacing = 0
-- Center the first collumn in the table
scroll_table.style.column_alignments[1] = 'center'
-- Loop over each default entity config
for _, setting in pairs(config.default_entities) do
local table_sizes = {}
local tables = {}
-- Draw a section for the element
local entity_table = section(scroll_table, setting.entity, 3)
-- Add some padding around the table
entity_table.style.padding = 3
-- Make sure each collumn is alignment top center
entity_table.style.column_alignments[1] = 'top-center'
entity_table.style.column_alignments[2] = 'top-center'
entity_table.style.column_alignments[3] = 'top-center'
-- Loop over each item category
for _, category in pairs(config.categories) do
if not table_sizes[category] then table_sizes[category] = 0 end
-- Draw table
local category_table = entity_table.add{
type = 'table',
name = category..'-category',
column_count = 2
}
-- Add padding between each item
category_table.style.vertical_spacing = 1
tables[category] = category_table
-- Add item autofill setting gui elements to the table
for _, item in pairs(setting.items) do
if item.category == category then
add_autofill_setting(category_table, item)
table_sizes[category] = table_sizes[category] + 1
Gui.element(function(definition, parent)
-- Draw the internal container
local container = Gui.container(parent, definition.name)
-- Draw the scroll container
local scroll_table = Gui.scroll_table(container, 400, 1, "autofill-scroll-table")
-- Set the scroll panel to always show the scrollbar (not doing this will result in a changing gui size)
scroll_table.parent.vertical_scroll_policy = "always"
-- Scroll panel has by default padding
scroll_table.parent.style.padding = 0
-- Remove the default gap that is added in a table between elements
scroll_table.style.vertical_spacing = 0
-- Center the first collumn in the table
scroll_table.style.column_alignments[1] = "center"
-- Loop over each default entity config
for _, setting in pairs(config.default_entities) do
local table_sizes = {}
local tables = {}
-- Draw a section for the element
local entity_table = section(scroll_table, setting.entity, 3)
-- Add some padding around the table
entity_table.style.padding = 3
-- Make sure each collumn is alignment top center
entity_table.style.column_alignments[1] = "top-center"
entity_table.style.column_alignments[2] = "top-center"
entity_table.style.column_alignments[3] = "top-center"
-- Loop over each item category
for _, category in pairs(config.categories) do
if not table_sizes[category] then table_sizes[category] = 0 end
-- Draw table
local category_table = entity_table.add{
type = "table",
name = category .. "-category",
column_count = 2,
}
-- Add padding between each item
category_table.style.vertical_spacing = 1
tables[category] = category_table
-- Add item autofill setting gui elements to the table
for _, item in pairs(setting.items) do
if item.category == category then
add_autofill_setting(category_table, item)
table_sizes[category] = table_sizes[category] + 1
end
end
end
-- Add empty gui elements for the categories with less items than the other categories
local t = table.get_values(table_sizes)
table.sort(t)
local biggest = t[#t]
for category, size in pairs(table_sizes) do
for i = biggest - size, 1, -1 do
add_empty_autofill_setting(tables[category])
end
end
end
-- Add empty gui elements for the categories with less items than the other categories
local t = table.get_values(table_sizes)
table.sort(t)
local biggest = t[#t]
for category, size in pairs(table_sizes) do
for i=biggest-size,1,-1 do
add_empty_autofill_setting(tables[category])
end
end
end
-- Return the external container
return container.parent
end)
:static_name(Gui.unique_static_name)
:add_to_left_flow()
-- Return the external container
return container.parent
end)
:static_name(Gui.unique_static_name)
:add_to_left_flow()
--- Button on the top flow used to toggle autofill container
-- @element autofill_toggle
Gui.left_toolbar_button(config.icon, {'autofill.main-tooltip'}, autofill_container, function(player)
return Roles.player_allowed(player, 'gui/autofill')
Gui.left_toolbar_button(config.icon, { "autofill.main-tooltip" }, autofill_container, function(player)
return Roles.player_allowed(player, "gui/autofill")
end)
--- When a player is created make sure they have the default autofill settings
@@ -341,19 +339,19 @@ local function entity_build(event)
if item_amount ~= 0 then
local inserted
text_position.y = text_position.y - 0.5
local color = { r = 0, g = 255, b = 0, a = 1}
local color = { r = 0, g = 255, b = 0, a = 1 }
if item_amount >= preferd_amount then
-- Can item be inserted? no, goto next item!
if not entity_inventory.can_insert{name=item.name, count=preferd_amount} then
if not entity_inventory.can_insert{ name = item.name, count = preferd_amount } then
goto end_item
end
inserted = entity_inventory.insert{name=item.name, count=preferd_amount}
inserted = entity_inventory.insert{ name = item.name, count = preferd_amount }
else
inserted = entity_inventory.insert{name=item.name, count=item_amount}
color = { r = 255, g = 165, b = 0, a = 1}
inserted = entity_inventory.insert{ name = item.name, count = item_amount }
color = { r = 255, g = 165, b = 0, a = 1 }
end
player_inventory.remove{name=item.name, count=inserted}
print_text(entity.surface, text_position, {'autofill.inserted', inserted, rich_img('item', item.name), rich_img('entity', entity.name) }, color)
player_inventory.remove{ name = item.name, count = inserted }
print_text(entity.surface, text_position, { "autofill.inserted", inserted, rich_img("item", item.name), rich_img("entity", entity.name) }, color)
end
::end_item::
end

View File

@@ -13,25 +13,26 @@ local bonus_container
local function bonus_gui_pts_needed(player)
local frame = Gui.get_left_element(player, bonus_container)
local disp = frame.container['bonus_st_2'].disp.table
local disp = frame.container["bonus_st_2"].disp.table
local total = 0
for k, v in pairs(config.conversion) do
total = total + (disp['bonus_display_' .. k .. '_slider'].slider_value / config.player_bonus[v].cost_scale * config.player_bonus[v].cost)
total = total + (disp["bonus_display_" .. k .. "_slider"].slider_value / config.player_bonus[v].cost_scale * config.player_bonus[v].cost)
end
total = total + (disp['bonus_display_personal_battery_recharge_slider'].slider_value / config.player_special_bonus['personal_battery_recharge'].cost_scale * config.player_special_bonus['personal_battery_recharge'].cost)
total = total +
(disp["bonus_display_personal_battery_recharge_slider"].slider_value / config.player_special_bonus["personal_battery_recharge"].cost_scale * config.player_special_bonus["personal_battery_recharge"].cost)
return total
end
local function apply_bonus(player)
if not Roles.player_allowed(player, 'gui/bonus') then
if not Roles.player_allowed(player, "gui/bonus") then
for k, v in pairs(config.player_bonus) do
player[k] = 0
if v.combined_bonus then
for i=1, #v.combined_bonus do
for i = 1, #v.combined_bonus do
player[v.combined_bonus[i]] = 0
end
end
@@ -45,21 +46,21 @@ local function apply_bonus(player)
end
local frame = Gui.get_left_element(player, bonus_container)
local disp = frame.container['bonus_st_2'].disp.table
local disp = frame.container["bonus_st_2"].disp.table
for k, v in pairs(config.conversion) do
player[v] = disp['bonus_display_' .. k .. '_slider'].slider_value
player[v] = disp["bonus_display_" .. k .. "_slider"].slider_value
if config.player_bonus[v].combined_bonus then
for i=1, #config.player_bonus[v].combined_bonus do
player[config.player_bonus[v].combined_bonus[i]] = disp['bonus_display_' .. k .. '_slider'].slider_value
for i = 1, #config.player_bonus[v].combined_bonus do
player[config.player_bonus[v].combined_bonus[i]] = disp["bonus_display_" .. k .. "_slider"].slider_value
end
end
end
end
local function apply_periodic_bonus(player)
if not Roles.player_allowed(player, 'gui/bonus') then
if not Roles.player_allowed(player, "gui/bonus") then
return
end
@@ -68,19 +69,19 @@ local function apply_periodic_bonus(player)
end
local frame = Gui.get_left_element(player, bonus_container)
local disp = frame.container['bonus_st_2'].disp.table
local disp = frame.container["bonus_st_2"].disp.table
if vlayer.get_statistics()['energy_sustained'] > 0 then
if vlayer.get_statistics()["energy_sustained"] > 0 then
local armor = player.get_inventory(defines.inventory.character_armor)[1].grid
if armor then
local slider = disp['bonus_display_personal_battery_recharge_slider'].slider_value * 100000 * config.player_special_bonus_rate / 6
local slider = disp["bonus_display_personal_battery_recharge_slider"].slider_value * 100000 * config.player_special_bonus_rate / 6
for i=1, #armor.equipment do
for i = 1, #armor.equipment do
if armor.equipment[i].energy < armor.equipment[i].max_energy then
local energy_required = math.min(math.floor(armor.equipment[i].max_energy - armor.equipment[i].energy), vlayer.get_statistics()['energy_storage'], slider)
local energy_required = math.min(math.floor(armor.equipment[i].max_energy - armor.equipment[i].energy), vlayer.get_statistics()["energy_storage"], slider)
armor.equipment[i].energy = armor.equipment[i].energy + energy_required
vlayer.energy_changed(- energy_required)
vlayer.energy_changed(-energy_required)
slider = slider - energy_required
end
@@ -92,250 +93,248 @@ end
--- Control label for the bonus points available
-- @element bonus_gui_control_pts_a
local bonus_gui_control_pts_a =
Gui.element{
type = 'label',
name = 'bonus_control_pts_a',
caption = {'bonus.control-pts-a'},
style = 'heading_2_label'
}:style{
width = config.gui_display_width['half']
}
Gui.element{
type = "label",
name = "bonus_control_pts_a",
caption = { "bonus.control-pts-a" },
style = "heading_2_label",
}:style{
width = config.gui_display_width["half"],
}
local bonus_gui_control_pts_a_count =
Gui.element{
type = 'label',
name = 'bonus_control_pts_a_count',
caption = config.pts.base,
style = 'heading_2_label'
}:style{
width = config.gui_display_width['half']
}
Gui.element{
type = "label",
name = "bonus_control_pts_a_count",
caption = config.pts.base,
style = "heading_2_label",
}:style{
width = config.gui_display_width["half"],
}
--- Control label for the bonus points needed
-- @element bonus_gui_control_pts_n
local bonus_gui_control_pts_n =
Gui.element{
type = 'label',
name = 'bonus_control_pts_n',
caption = {'bonus.control-pts-n'},
style = 'heading_2_label'
}:style{
width = config.gui_display_width['half']
}
Gui.element{
type = "label",
name = "bonus_control_pts_n",
caption = { "bonus.control-pts-n" },
style = "heading_2_label",
}:style{
width = config.gui_display_width["half"],
}
local bonus_gui_control_pts_n_count =
Gui.element{
type = 'label',
name = 'bonus_control_pts_n_count',
caption = '0',
style = 'heading_2_label'
}:style{
width =config.gui_display_width['half']
}
Gui.element{
type = "label",
name = "bonus_control_pts_n_count",
caption = "0",
style = "heading_2_label",
}:style{
width = config.gui_display_width["half"],
}
--- Control label for the bonus points remaining
-- @element bonus_gui_control_pts_r
local bonus_gui_control_pts_r =
Gui.element{
type = 'label',
name = 'bonus_control_pts_r',
caption = {'bonus.control-pts-r'},
style = 'heading_2_label'
}:style{
width = config.gui_display_width['half']
}
Gui.element{
type = "label",
name = "bonus_control_pts_r",
caption = { "bonus.control-pts-r" },
style = "heading_2_label",
}:style{
width = config.gui_display_width["half"],
}
local bonus_gui_control_pts_r_count =
Gui.element{
type = 'label',
name = 'bonus_control_pts_r_count',
caption = '0',
style = 'heading_2_label'
}:style{
width = config.gui_display_width['half']
}
Gui.element{
type = "label",
name = "bonus_control_pts_r_count",
caption = "0",
style = "heading_2_label",
}:style{
width = config.gui_display_width["half"],
}
--- A button used for pts calculations
-- @element bonus_gui_control_refresh
local bonus_gui_control_reset =
Gui.element{
type = 'button',
name = Gui.unique_static_name,
caption = {'bonus.control-reset'}
}:style{
width = config.gui_display_width['half']
}:on_click(function(player, element, _)
local frame = Gui.get_left_element(player, bonus_container)
local disp = frame.container['bonus_st_2'].disp.table
Gui.element{
type = "button",
name = Gui.unique_static_name,
caption = { "bonus.control-reset" },
}:style{
width = config.gui_display_width["half"],
}:on_click(function(player, element, _)
local frame = Gui.get_left_element(player, bonus_container)
local disp = frame.container["bonus_st_2"].disp.table
for k, v in pairs(config.conversion) do
local s = 'bonus_display_' .. k .. '_slider'
disp[s].slider_value = config.player_bonus[v].value
for k, v in pairs(config.conversion) do
local s = "bonus_display_" .. k .. "_slider"
disp[s].slider_value = config.player_bonus[v].value
if config.player_bonus[v].is_percentage then
disp[disp[s].tags.counter].caption = format_number(disp[s].slider_value * 100) .. ' %'
else
disp[disp[s].tags.counter].caption = format_number(disp[s].slider_value)
if config.player_bonus[v].is_percentage then
disp[disp[s].tags.counter].caption = format_number(disp[s].slider_value * 100) .. " %"
else
disp[disp[s].tags.counter].caption = format_number(disp[s].slider_value)
end
end
end
local slider = disp['bonus_display_personal_battery_recharge_slider']
slider.slider_value = config.player_special_bonus['personal_battery_recharge'].value
disp[slider.tags.counter].caption = format_number(slider.slider_value)
local slider = disp["bonus_display_personal_battery_recharge_slider"]
slider.slider_value = config.player_special_bonus["personal_battery_recharge"].value
disp[slider.tags.counter].caption = format_number(slider.slider_value)
local r = bonus_gui_pts_needed(player)
element.parent[bonus_gui_control_pts_n_count.name].caption = r
element.parent[bonus_gui_control_pts_r_count.name].caption = tonumber(element.parent[bonus_gui_control_pts_a_count.name].caption) - r
end)
local r = bonus_gui_pts_needed(player)
element.parent[bonus_gui_control_pts_n_count.name].caption = r
element.parent[bonus_gui_control_pts_r_count.name].caption = tonumber(element.parent[bonus_gui_control_pts_a_count.name].caption) - r
end)
--- A button used for pts apply
-- @element bonus_gui_control_apply
local bonus_gui_control_apply =
Gui.element{
type = 'button',
name = Gui.unique_static_name,
caption = {'bonus.control-apply'}
}:style{
width = config.gui_display_width['half']
}:on_click(function(player, element, _)
local n = bonus_gui_pts_needed(player)
element.parent[bonus_gui_control_pts_n_count.name].caption = n
local r = tonumber(element.parent[bonus_gui_control_pts_a_count.name].caption) - n
element.parent[bonus_gui_control_pts_r_count.name].caption = r
Gui.element{
type = "button",
name = Gui.unique_static_name,
caption = { "bonus.control-apply" },
}:style{
width = config.gui_display_width["half"],
}:on_click(function(player, element, _)
local n = bonus_gui_pts_needed(player)
element.parent[bonus_gui_control_pts_n_count.name].caption = n
local r = tonumber(element.parent[bonus_gui_control_pts_a_count.name].caption) - n
element.parent[bonus_gui_control_pts_r_count.name].caption = r
if r >= 0 then
apply_bonus(player)
end
end)
if r >= 0 then
apply_bonus(player)
end
end)
--- A vertical flow containing all the bonus control
-- @element bonus_control_set
local bonus_control_set =
Gui.element(function(_, parent, name)
local bonus_set = parent.add{type='flow', direction='vertical', name=name}
local disp = Gui.scroll_table(bonus_set, config.gui_display_width['half'] * 2, 2, 'disp')
Gui.element(function(_, parent, name)
local bonus_set = parent.add{ type = "flow", direction = "vertical", name = name }
local disp = Gui.scroll_table(bonus_set, config.gui_display_width["half"] * 2, 2, "disp")
bonus_gui_control_pts_a(disp)
bonus_gui_control_pts_a_count(disp)
bonus_gui_control_pts_a(disp)
bonus_gui_control_pts_a_count(disp)
bonus_gui_control_pts_n(disp)
bonus_gui_control_pts_n_count(disp)
bonus_gui_control_pts_n(disp)
bonus_gui_control_pts_n_count(disp)
bonus_gui_control_pts_r(disp)
bonus_gui_control_pts_r_count(disp)
bonus_gui_control_pts_r(disp)
bonus_gui_control_pts_r_count(disp)
bonus_gui_control_reset(disp)
bonus_gui_control_apply(disp)
bonus_gui_control_reset(disp)
bonus_gui_control_apply(disp)
return bonus_set
end)
return bonus_set
end)
--- Display group
-- @element bonus_gui_slider
local bonus_gui_slider =
Gui.element(function(_definition, parent, name, caption, tooltip, bonus)
local label = parent.add{
type = 'label',
caption = caption,
tooltip = tooltip,
style = 'heading_2_label'
}
label.style.width = config.gui_display_width['label']
local value = bonus.value
if bonus.is_percentage then
value = format_number(value * 100) .. ' %'
else
value = format_number(value)
end
local slider = parent.add{
type = 'slider',
name = name .. '_slider',
value = bonus.value,
maximum_value = bonus.max,
value_step = bonus.scale,
discrete_values = true,
style = 'notched_slider',
tags = {
counter = name .. '_count',
is_percentage = bonus.is_percentage
Gui.element(function(_definition, parent, name, caption, tooltip, bonus)
local label = parent.add{
type = "label",
caption = caption,
tooltip = tooltip,
style = "heading_2_label",
}
}
slider.style.width = config.gui_display_width['slider']
slider.style.horizontally_stretchable = true
label.style.width = config.gui_display_width["label"]
local count = parent.add{
type = 'label',
name = name .. '_count',
caption = value,
style = 'heading_2_label',
}
count.style.width = config.gui_display_width['count']
local value = bonus.value
return slider
end)
:on_value_changed(function(player, element, _event)
if element.tags.is_percentage then
element.parent[element.tags.counter].caption = format_number(element.slider_value * 100) .. ' %'
if bonus.is_percentage then
value = format_number(value * 100) .. " %"
else
value = format_number(value)
end
else
element.parent[element.tags.counter].caption = format_number(element.slider_value)
end
local slider = parent.add{
type = "slider",
name = name .. "_slider",
value = bonus.value,
maximum_value = bonus.max,
value_step = bonus.scale,
discrete_values = true,
style = "notched_slider",
tags = {
counter = name .. "_count",
is_percentage = bonus.is_percentage,
},
}
slider.style.width = config.gui_display_width["slider"]
slider.style.horizontally_stretchable = true
local r = bonus_gui_pts_needed(player)
local frame = Gui.get_left_element(player, bonus_container)
local disp = frame.container['bonus_st_1'].disp.table
disp[bonus_gui_control_pts_n_count.name].caption = r
disp[bonus_gui_control_pts_r_count.name].caption = tonumber(disp[bonus_gui_control_pts_a_count.name].caption) - r
end)
local count = parent.add{
type = "label",
name = name .. "_count",
caption = value,
style = "heading_2_label",
}
count.style.width = config.gui_display_width["count"]
return slider
end)
:on_value_changed(function(player, element, _event)
if element.tags.is_percentage then
element.parent[element.tags.counter].caption = format_number(element.slider_value * 100) .. " %"
else
element.parent[element.tags.counter].caption = format_number(element.slider_value)
end
local r = bonus_gui_pts_needed(player)
local frame = Gui.get_left_element(player, bonus_container)
local disp = frame.container["bonus_st_1"].disp.table
disp[bonus_gui_control_pts_n_count.name].caption = r
disp[bonus_gui_control_pts_r_count.name].caption = tonumber(disp[bonus_gui_control_pts_a_count.name].caption) - r
end)
--- A vertical flow containing all the bonus data
-- @element bonus_data_set
local bonus_data_set =
Gui.element(function(_, parent, name)
local bonus_set = parent.add{type='flow', direction='vertical', name=name}
local disp = Gui.scroll_table(bonus_set, config.gui_display_width['half'] * 2, 3, 'disp')
Gui.element(function(_, parent, name)
local bonus_set = parent.add{ type = "flow", direction = "vertical", name = name }
local disp = Gui.scroll_table(bonus_set, config.gui_display_width["half"] * 2, 3, "disp")
for k, v in pairs(config.conversion) do
bonus_gui_slider(disp, 'bonus_display_' .. k, {'bonus.display-' .. k}, {'bonus.display-' .. k .. '-tooltip'}, config.player_bonus[v])
end
for k, v in pairs(config.conversion) do
bonus_gui_slider(disp, "bonus_display_" .. k, { "bonus.display-" .. k }, { "bonus.display-" .. k .. "-tooltip" }, config.player_bonus[v])
end
bonus_gui_slider(disp, 'bonus_display_personal_battery_recharge', {'bonus.display-personal-battery-recharge'}, {'bonus.display-personal-battery-recharge-tooltip'}, config.player_special_bonus['personal_battery_recharge'])
bonus_gui_slider(disp, "bonus_display_personal_battery_recharge", { "bonus.display-personal-battery-recharge" }, { "bonus.display-personal-battery-recharge-tooltip" },
config.player_special_bonus["personal_battery_recharge"])
return bonus_set
end)
return bonus_set
end)
--- The main container for the bonus gui
-- @element bonus_container
bonus_container =
Gui.element(function(definition, parent)
local player = Gui.get_player_from_element(parent)
local container = Gui.container(parent, definition.name, config.gui_display_width['half'] * 2)
Gui.element(function(definition, parent)
local player = Gui.get_player_from_element(parent)
local container = Gui.container(parent, definition.name, config.gui_display_width["half"] * 2)
bonus_control_set(container, 'bonus_st_1')
bonus_data_set(container, 'bonus_st_2')
bonus_control_set(container, "bonus_st_1")
bonus_data_set(container, "bonus_st_2")
local frame = Gui.get_left_element(player, bonus_container)
local disp = frame.container['bonus_st_1'].disp.table
local n = bonus_gui_pts_needed(player)
disp[bonus_gui_control_pts_n_count.name].caption = n
local r = tonumber(disp[bonus_gui_control_pts_a_count.name].caption) - n
disp[bonus_gui_control_pts_r_count.name].caption = r
local frame = Gui.get_left_element(player, bonus_container)
local disp = frame.container["bonus_st_1"].disp.table
local n = bonus_gui_pts_needed(player)
disp[bonus_gui_control_pts_n_count.name].caption = n
local r = tonumber(disp[bonus_gui_control_pts_a_count.name].caption) - n
disp[bonus_gui_control_pts_r_count.name].caption = r
apply_bonus(player)
return container.parent
end)
:static_name(Gui.unique_static_name)
:add_to_left_flow()
apply_bonus(player)
return container.parent
end)
:static_name(Gui.unique_static_name)
:add_to_left_flow()
--- Button on the top flow used to toggle the bonus container
-- @element toggle_left_element
Gui.left_toolbar_button('item/exoskeleton-equipment', {'bonus.main-tooltip'}, bonus_container, function(player)
return Roles.player_allowed(player, 'gui/bonus')
Gui.left_toolbar_button("item/exoskeleton-equipment", { "bonus.main-tooltip" }, bonus_container, function(player)
return Roles.player_allowed(player, "gui/bonus")
end)
Event.add(defines.events.on_player_created, function(event)
@@ -364,7 +363,7 @@ end)
Event.add(defines.events.on_player_respawned, function(event)
local player = game.players[event.player_index]
local frame = Gui.get_left_element(player, bonus_container)
local disp = frame.container['bonus_st_1'].disp.table
local disp = frame.container["bonus_st_1"].disp.table
local n = bonus_gui_pts_needed(player)
disp[bonus_gui_control_pts_n_count.name].caption = n
local r = tonumber(disp[bonus_gui_control_pts_a_count.name].caption) - n
@@ -379,7 +378,7 @@ end)
Event.add(defines.events.on_player_died, function(event)
local player = game.players[event.player_index]
if Roles.player_has_flag(player, 'instant-respawn') then
if Roles.player_has_flag(player, "instant-respawn") then
player.ticks_to_respawn = 120
end
end)

View File

@@ -30,7 +30,7 @@ local ignore = {
type = true,
xpcall = true,
_VERSION = true,
['module'] = true,
["module"] = true,
require = true,
package = true,
unpack = true,
@@ -51,31 +51,31 @@ local ignore = {
util = true,
mod_gui = true,
game = true,
rendering = true
rendering = true,
}
local header_name = Gui.uid_name()
local left_panel_name = Gui.uid_name()
local right_panel_name = Gui.uid_name()
Public.name = '_G'
Public.name = "_G"
function Public.show(container)
local main_flow = container.add {type = 'flow', direction = 'horizontal'}
local main_flow = container.add{ type = "flow", direction = "horizontal" }
local left_panel = main_flow.add {type = 'scroll-pane', name = left_panel_name}
local left_panel = main_flow.add{ type = "scroll-pane", name = left_panel_name }
local left_panel_style = left_panel.style
left_panel_style.width = 300
for key, value in pairs(_G) do
if not ignore[key] then
local header =
left_panel.add({type = 'flow'}).add {type = 'label', name = header_name, caption = tostring(key)}
left_panel.add{ type = "flow" }.add{ type = "label", name = header_name, caption = tostring(key) }
Gui.set_data(header, value)
end
end
local right_panel = main_flow.add {type = 'text-box', name = right_panel_name}
local right_panel = main_flow.add{ type = "text-box", name = right_panel_name }
right_panel.read_only = true
right_panel.selectable = true
@@ -85,7 +85,7 @@ function Public.show(container)
right_panel_style.maximal_width = 1000
right_panel_style.maximal_height = 1000
Gui.set_data(left_panel, {right_panel = right_panel, selected_header = nil})
Gui.set_data(left_panel, { right_panel = right_panel, selected_header = nil })
end
Gui.on_click(

View File

@@ -13,7 +13,7 @@ local events_to_keep = 10
-- Local vars
local Public = {
name = 'Events'
name = "Events",
}
local name_lookup = {}
@@ -28,7 +28,7 @@ local last_events = {}
storage.debug_event_view = {
enabled = enabled,
last_events = last_events,
filter = ''
filter = "",
}
function Public.on_open_debug()
@@ -42,7 +42,7 @@ function Public.on_open_debug()
storage.debug_event_view = {
enabled = enabled,
last_events = last_events
last_events = last_events,
}
end
@@ -65,7 +65,7 @@ local function event_callback(event)
last_events[name][events_to_keep + 1] = nil
event.name = nil
local str = format('%s (id = %s): %s', name, id, Model.dump(event))
local str = format("%s (id = %s): %s", name, id, Model.dump(event))
game.print(str)
log(str)
end
@@ -95,13 +95,13 @@ table.sort(grid_builder)
local function redraw_event_table(gui_table, filter)
for _, event_name in pairs(grid_builder) do
if filter == '' or event_name:find(filter) then
if filter == "" or event_name:find(filter) then
local index = events[event_name]
gui_table.add({type = 'flow'}).add {
gui_table.add{ type = "flow" }.add{
name = checkbox_name,
type = 'checkbox',
type = "checkbox",
state = enabled[index] or false,
caption = event_name
caption = event_name,
}
end
end
@@ -110,18 +110,18 @@ end
function Public.show(container)
local filter = storage.debug_event_view.filter
local main_frame_flow = container.add({type = 'flow', direction = 'vertical'})
local main_frame_flow = container.add{ type = "flow", direction = "vertical" }
local filter_flow = main_frame_flow.add({type = 'flow', direction = 'horizontal'})
filter_flow.add({type = 'label', caption = 'filter'})
local filter_textfield = filter_flow.add({type = 'textfield', name = filter_name, text = filter})
local clear_button = filter_flow.add({type = 'button', name = clear_filter_name, caption = 'clear'})
local filter_flow = main_frame_flow.add{ type = "flow", direction = "horizontal" }
filter_flow.add{ type = "label", caption = "filter" }
local filter_textfield = filter_flow.add{ type = "textfield", name = filter_name, text = filter }
local clear_button = filter_flow.add{ type = "button", name = clear_filter_name, caption = "clear" }
local scroll_pane = main_frame_flow.add({type = 'scroll-pane'})
local gui_table = scroll_pane.add({type = 'table', column_count = 3, draw_horizontal_lines = true})
local scroll_pane = main_frame_flow.add{ type = "scroll-pane" }
local gui_table = scroll_pane.add{ type = "table", column_count = 3, draw_horizontal_lines = true }
Gui.set_data(filter_textfield, gui_table)
Gui.set_data(clear_button, {gui_table = gui_table, filter_textfield = filter_textfield})
Gui.set_data(clear_button, { gui_table = gui_table, filter_textfield = filter_textfield })
redraw_event_table(gui_table, filter)
end
@@ -134,7 +134,7 @@ Gui.on_text_changed(
local element = event.element
local gui_table = Gui.get_data(element)
local filter = element.text:gsub(' ', '_')
local filter = element.text:gsub(" ", "_")
storage.debug_event_view.filter = filter
element.text = filter
@@ -152,11 +152,11 @@ Gui.on_click(
local filter_textfield = data.filter_textfield
local gui_table = data.gui_table
filter_textfield.text = ''
storage.debug_event_view.filter = ''
filter_textfield.text = ""
storage.debug_event_view.filter = ""
gui_table.clear()
redraw_event_table(gui_table, '')
redraw_event_table(gui_table, "")
end
)

View File

@@ -14,37 +14,37 @@ local right_panel_name = Gui.uid_name()
local input_text_box_name = Gui.uid_name()
local refresh_name = Gui.uid_name()
Public.name = 'Datastore'
Public.name = "Datastore"
function Public.show(container)
local main_flow = container.add {type = 'flow', direction = 'horizontal'}
local main_flow = container.add{ type = "flow", direction = "horizontal" }
local left_panel = main_flow.add {type = 'scroll-pane', name = left_panel_name}
local left_panel = main_flow.add{ type = "scroll-pane", name = left_panel_name }
local left_panel_style = left_panel.style
left_panel_style.width = 300
for name in pairs(table.keysort(Datastore.debug())) do
local header = left_panel.add({type = 'flow'}).add {type = 'label', name = header_name, caption = name}
local header = left_panel.add{ type = "flow" }.add{ type = "label", name = header_name, caption = name }
Gui.set_data(header, name)
end
local right_flow = main_flow.add {type = 'flow', direction = 'vertical'}
local right_flow = main_flow.add{ type = "flow", direction = "vertical" }
local right_top_flow = right_flow.add {type = 'flow', direction = 'horizontal'}
local right_top_flow = right_flow.add{ type = "flow", direction = "horizontal" }
local input_text_box = right_top_flow.add {type = 'text-box', name = input_text_box_name}
local input_text_box = right_top_flow.add{ type = "text-box", name = input_text_box_name }
local input_text_box_style = input_text_box.style
input_text_box_style.horizontally_stretchable = true
input_text_box_style.height = 32
input_text_box_style.maximal_width = 1000
local refresh_button =
right_top_flow.add {type = 'sprite-button', name = refresh_name, sprite = 'utility/reset', tooltip = 'refresh'}
right_top_flow.add{ type = "sprite-button", name = refresh_name, sprite = "utility/reset", tooltip = "refresh" }
local refresh_button_style = refresh_button.style
refresh_button_style.width = 32
refresh_button_style.height = 32
local right_panel = right_flow.add {type = 'text-box', name = right_panel_name}
local right_panel = right_flow.add{ type = "text-box", name = right_panel_name }
right_panel.read_only = true
right_panel.selectable = true
@@ -57,7 +57,7 @@ function Public.show(container)
local data = {
right_panel = right_panel,
input_text_box = input_text_box,
selected_header = nil
selected_header = nil,
}
Gui.set_data(input_text_box, data)
@@ -90,9 +90,10 @@ Gui.on_click(
local content = Datastore.debug(tableName)
local content_string = {}
for key, value in pairs(content) do
content_string[#content_string+1] = key:gsub('^%l', string.upper)..' = '..dump(value)
content_string[#content_string + 1] = key:gsub("^%l", string.upper) .. " = " .. dump(value)
end
right_panel.text = concat(content_string, '\n')
right_panel.text = concat(content_string, "\n")
end
)
@@ -100,9 +101,10 @@ local function update_dump(text_input, data)
local content = Datastore.debug(text_input.text)
local content_string = {}
for key, value in pairs(content) do
content_string[#content_string+1] = key:gsub('^%l', string.upper)..' = '..dump(value)
content_string[#content_string + 1] = key:gsub("^%l", string.upper) .. " = " .. dump(value)
end
data.right_panel.text = concat(content_string, '\n')
data.right_panel.text = concat(content_string, "\n")
end
Gui.on_text_changed(

View File

@@ -15,37 +15,37 @@ local right_panel_name = Gui.uid_name()
local input_text_box_name = Gui.uid_name()
local refresh_name = Gui.uid_name()
Public.name = 'Elements'
Public.name = "Elements"
function Public.show(container)
local main_flow = container.add {type = 'flow', direction = 'horizontal'}
local main_flow = container.add{ type = "flow", direction = "horizontal" }
local left_panel = main_flow.add {type = 'scroll-pane', name = left_panel_name}
local left_panel = main_flow.add{ type = "scroll-pane", name = left_panel_name }
local left_panel_style = left_panel.style
left_panel_style.width = 300
for element_id, file_path in pairs(ExpGui.file_paths) do
local header = left_panel.add({type = 'flow'}).add {type = 'label', name = header_name, caption = element_id..' - '..file_path}
local header = left_panel.add{ type = "flow" }.add{ type = "label", name = header_name, caption = element_id .. " - " .. file_path }
Gui.set_data(header, element_id)
end
local right_flow = main_flow.add {type = 'flow', direction = 'vertical'}
local right_flow = main_flow.add{ type = "flow", direction = "vertical" }
local right_top_flow = right_flow.add {type = 'flow', direction = 'horizontal'}
local right_top_flow = right_flow.add{ type = "flow", direction = "horizontal" }
local input_text_box = right_top_flow.add {type = 'text-box', name = input_text_box_name}
local input_text_box = right_top_flow.add{ type = "text-box", name = input_text_box_name }
local input_text_box_style = input_text_box.style
input_text_box_style.horizontally_stretchable = true
input_text_box_style.height = 32
input_text_box_style.maximal_width = 1000
local refresh_button =
right_top_flow.add {type = 'sprite-button', name = refresh_name, sprite = 'utility/reset', tooltip = 'refresh'}
right_top_flow.add{ type = "sprite-button", name = refresh_name, sprite = "utility/reset", tooltip = "refresh" }
local refresh_button_style = refresh_button.style
refresh_button_style.width = 32
refresh_button_style.height = 32
local right_panel = right_flow.add {type = 'text-box', name = right_panel_name}
local right_panel = right_flow.add{ type = "text-box", name = right_panel_name }
right_panel.read_only = true
right_panel.selectable = true
@@ -58,7 +58,7 @@ function Public.show(container)
local data = {
right_panel = right_panel,
input_text_box = input_text_box,
selected_header = nil
selected_header = nil,
}
Gui.set_data(input_text_box, data)
@@ -85,10 +85,10 @@ Gui.on_click(
element.style.font_color = Color.orange
data.selected_header = element
input_text_box.text = concat {'Gui.defines[', element_id, ']'}
input_text_box.text = concat{ "Gui.defines[", element_id, "]" }
input_text_box.style.font_color = Color.black
local content = dump(ExpGui.debug_info[element_id]) or 'nil'
local content = dump(ExpGui.debug_info[element_id]) or "nil"
right_panel.text = content
end
)

View File

@@ -8,7 +8,7 @@ local concat = table.concat
local Public = {}
local ignore = {tokens = true, data_store = true, datastores = true}
local ignore = { tokens = true, data_store = true, datastores = true }
local header_name = Gui.uid_name()
local left_panel_name = Gui.uid_name()
@@ -16,40 +16,40 @@ local right_panel_name = Gui.uid_name()
local input_text_box_name = Gui.uid_name()
local refresh_name = Gui.uid_name()
Public.name = 'storage'
Public.name = "storage"
function Public.show(container)
local main_flow = container.add {type = 'flow', direction = 'horizontal'}
local main_flow = container.add{ type = "flow", direction = "horizontal" }
local left_panel = main_flow.add {type = 'scroll-pane', name = left_panel_name}
local left_panel = main_flow.add{ type = "scroll-pane", name = left_panel_name }
local left_panel_style = left_panel.style
left_panel_style.width = 300
for key, _ in pairs(storage) do
if not ignore[key] then
local header =
left_panel.add({type = 'flow'}).add {type = 'label', name = header_name, caption = tostring(key)}
left_panel.add{ type = "flow" }.add{ type = "label", name = header_name, caption = tostring(key) }
Gui.set_data(header, key)
end
end
local right_flow = main_flow.add {type = 'flow', direction = 'vertical'}
local right_flow = main_flow.add{ type = "flow", direction = "vertical" }
local right_top_flow = right_flow.add {type = 'flow', direction = 'horizontal'}
local right_top_flow = right_flow.add{ type = "flow", direction = "horizontal" }
local input_text_box = right_top_flow.add {type = 'text-box', name = input_text_box_name}
local input_text_box = right_top_flow.add{ type = "text-box", name = input_text_box_name }
local input_text_box_style = input_text_box.style
input_text_box_style.horizontally_stretchable = true
input_text_box_style.height = 32
input_text_box_style.maximal_width = 1000
local refresh_button =
right_top_flow.add {type = 'sprite-button', name = refresh_name, sprite = 'utility/reset', tooltip = 'refresh'}
right_top_flow.add{ type = "sprite-button", name = refresh_name, sprite = "utility/reset", tooltip = "refresh" }
local refresh_button_style = refresh_button.style
refresh_button_style.width = 32
refresh_button_style.height = 32
local right_panel = right_flow.add {type = 'text-box', name = right_panel_name}
local right_panel = right_flow.add{ type = "text-box", name = right_panel_name }
right_panel.read_only = true
right_panel.selectable = true
@@ -63,7 +63,7 @@ function Public.show(container)
right_panel = right_panel,
input_text_box = input_text_box,
selected_header = nil,
selected_token_id = nil
selected_token_id = nil,
}
Gui.set_data(input_text_box, data)
@@ -90,10 +90,10 @@ Gui.on_click(
element.style.font_color = Color.orange
data.selected_header = element
input_text_box.text = concat {"storage['", key, "']"}
input_text_box.text = concat{ "storage['", key, "']" }
input_text_box.style.font_color = Color.black
local content = dump(storage[key]) or 'nil'
local content = dump(storage[key]) or "nil"
right_panel.text = content
end
)

View File

@@ -10,7 +10,7 @@ local pages = {
require("modules.exp_legacy.modules.gui.debug.global_view"),
require("modules.exp_legacy.modules.gui.debug.package_view"),
require("modules.exp_legacy.modules.gui.debug._g_view"),
require("modules.exp_legacy.modules.gui.debug.event_view")
require("modules.exp_legacy.modules.gui.debug.event_view"),
}
local main_frame_name = Gui.uid_name()
@@ -40,23 +40,23 @@ function Public.open_dubug(player)
frame.auto_center = true
]]
frame = center.add {type = 'frame', name = main_frame_name, caption = 'Debuggertron 3002', direction = 'vertical'}
frame = center.add{ type = "frame", name = main_frame_name, caption = "Debuggertron 3002", direction = "vertical" }
local frame_style = frame.style
frame_style.height = 600
frame_style.width = 900
local tab_flow = frame.add {type = 'flow', direction = 'horizontal'}
local container = frame.add {type = 'flow'}
local tab_flow = frame.add{ type = "flow", direction = "horizontal" }
local container = frame.add{ type = "flow" }
container.style.vertically_stretchable = true
local data = {}
for i = 1, #pages do
local page = pages[i]
local tab_button = tab_flow.add({type = 'flow'}).add {type = 'button', name = tab_name, caption = page.name}
local tab_button = tab_flow.add{ type = "flow" }.add{ type = "button", name = tab_name, caption = page.name }
local tab_button_style = tab_button.style
Gui.set_data(tab_button, {index = i, frame_data = data})
Gui.set_data(tab_button, { index = i, frame_data = data })
if i == 1 then
tab_button_style.font_color = Color.orange
@@ -70,7 +70,7 @@ function Public.open_dubug(player)
end
end
frame.add {type = 'button', name = close_name, caption = 'Close'}
frame.add{ type = "button", name = close_name, caption = "Close" }
end
Gui.on_click(

View File

@@ -6,72 +6,72 @@ local type = type
local concat = table.concat
local inspect = table.inspect
local pcall = pcall
local loadstring = loadstring ---@diagnostic disable-line
local loadstring = loadstring --- @diagnostic disable-line
local rawset = rawset
local Public = {}
local luaObject = {'{', nil, ", name = '", nil, "'}"}
local luaPlayer = {"{LuaPlayer, name = '", nil, "', index = ", nil, '}'}
local luaEntity = {"{LuaEntity, name = '", nil, "', unit_number = ", nil, '}'}
local luaGuiElement = {"{LuaGuiElement, name = '", nil, "'}"}
local luaObject = { "{", nil, ", name = '", nil, "'}" }
local luaPlayer = { "{LuaPlayer, name = '", nil, "', index = ", nil, "}" }
local luaEntity = { "{LuaEntity, name = '", nil, "', unit_number = ", nil, "}" }
local luaGuiElement = { "{LuaGuiElement, name = '", nil, "'}" }
local function get(obj, prop)
return obj[prop]
end
local function get_name_safe(obj)
local s, r = pcall(get, obj, 'name')
local s, r = pcall(get, obj, "name")
if not s then
return 'nil'
return "nil"
else
return r or 'nil'
return r or "nil"
end
end
local function get_lua_object_type_safe(obj)
local s, r = pcall(get, obj, 'help')
local s, r = pcall(get, obj, "help")
if not s then
return
end
return r():match('Lua%a+')
return r():match("Lua%a+")
end
local function inspect_process(item)
if type(item) ~= 'table' or type(item.__self) ~= 'userdata' then
if type(item) ~= "table" or type(item.__self) ~= "userdata" then
return item
end
local suc, valid = pcall(get, item, 'valid')
local suc, valid = pcall(get, item, "valid")
if not suc then
-- no 'valid' property
return get_lua_object_type_safe(item) or '{NoHelp LuaObject}'
return get_lua_object_type_safe(item) or "{NoHelp LuaObject}"
end
if not valid then
return '{Invalid LuaObject}'
return "{Invalid LuaObject}"
end
local obj_type = get_lua_object_type_safe(item)
if not obj_type then
return '{NoHelp LuaObject}'
return "{NoHelp LuaObject}"
end
if obj_type == 'LuaPlayer' then
luaPlayer[2] = item.name or 'nil'
luaPlayer[4] = item.index or 'nil'
if obj_type == "LuaPlayer" then
luaPlayer[2] = item.name or "nil"
luaPlayer[4] = item.index or "nil"
return concat(luaPlayer)
elseif obj_type == 'LuaEntity' then
luaEntity[2] = item.name or 'nil'
luaEntity[4] = item.unit_number or 'nil'
elseif obj_type == "LuaEntity" then
luaEntity[2] = item.name or "nil"
luaEntity[4] = item.unit_number or "nil"
return concat(luaEntity)
elseif obj_type == 'LuaGuiElement' then
elseif obj_type == "LuaGuiElement" then
local name = item.name
luaGuiElement[2] = gui_names and gui_names[name] or name or 'nil'
luaGuiElement[2] = gui_names and gui_names[name] or name or "nil"
return concat(luaGuiElement)
else
@@ -82,10 +82,11 @@ local function inspect_process(item)
end
end
local inspect_options = {process = inspect_process}
local inspect_options = { process = inspect_process }
function Public.dump(data)
return inspect(data, inspect_options)
end
local dump = Public.dump
function Public.dump_ignore_builder(ignore)
@@ -97,14 +98,14 @@ function Public.dump_ignore_builder(ignore)
return inspect_process(item)
end
local options = {process = process}
local options = { process = process }
return function(data)
return inspect(data, options)
end
end
function Public.dump_function(func)
local res = {'upvalues:\n'}
local res = { "upvalues:\n" }
local i = 1
while true do
@@ -112,11 +113,11 @@ function Public.dump_function(func)
if n == nil then
break
elseif n ~= '_ENV' then
elseif n ~= "_ENV" then
res[#res + 1] = n
res[#res + 1] = ' = '
res[#res + 1] = " = "
res[#res + 1] = dump(v)
res[#res + 1] = '\n'
res[#res + 1] = "\n"
end
i = i + 1
@@ -126,16 +127,16 @@ function Public.dump_function(func)
end
function Public.dump_text(text, player)
local func = loadstring('return ' .. text)
local func = loadstring("return " .. text)
if not func then
return false
end
rawset(game, 'player', player)
rawset(game, "player", player)
local suc, var = pcall(func)
rawset(game, 'player', nil)
rawset(game, "player", nil)
if not suc then
return false

View File

@@ -17,9 +17,9 @@ local ignore = {
math = true,
debug = true,
serpent = true,
['overrides.math'] = true,
["overrides.math"] = true,
util = true,
['mod-gui'] = true
["mod-gui"] = true,
}
local file_label_name = Gui.uid_name()
@@ -29,34 +29,34 @@ local top_panel_name = Gui.uid_name()
local variable_label_name = Gui.uid_name()
local text_box_name = Gui.uid_name()
Public.name = 'package'
Public.name = "package"
function Public.show(container)
local main_flow = container.add {type = 'flow', direction = 'horizontal'}
local main_flow = container.add{ type = "flow", direction = "horizontal" }
local left_panel = main_flow.add {type = 'scroll-pane', name = left_panel_name}
local left_panel = main_flow.add{ type = "scroll-pane", name = left_panel_name }
local left_panel_style = left_panel.style
left_panel_style.width = 300
for name, file in pairs(loaded) do
if not ignore[name] then
local file_label =
left_panel.add({type = 'flow'}).add {type = 'label', name = file_label_name, caption = name}
left_panel.add{ type = "flow" }.add{ type = "label", name = file_label_name, caption = name }
Gui.set_data(file_label, file)
end
end
local right_flow = main_flow.add {type = 'flow', direction = 'vertical'}
local right_flow = main_flow.add{ type = "flow", direction = "vertical" }
local breadcrumbs = right_flow.add {type = 'label', name = breadcrumbs_name}
local breadcrumbs = right_flow.add{ type = "label", name = breadcrumbs_name }
local top_panel = right_flow.add {type = 'scroll-pane', name = top_panel_name}
local top_panel = right_flow.add{ type = "scroll-pane", name = top_panel_name }
local top_panel_style = top_panel.style
top_panel_style.height = 200
top_panel_style.maximal_width = 1000
top_panel_style.horizontally_stretchable = true
local text_box = right_flow.add {type = 'text-box', name = text_box_name}
local text_box = right_flow.add{ type = "text-box", name = text_box_name }
text_box.read_only = true
text_box.selectable = true
@@ -72,7 +72,7 @@ function Public.show(container)
top_panel = top_panel,
text_box = text_box,
selected_file_label = nil,
selected_variable_label = nil
selected_variable_label = nil,
}
Gui.set_data(left_panel, data)
@@ -104,13 +104,13 @@ Gui.on_click(
local file_type = type(file)
if file_type == 'table' then
if file_type == "table" then
for k, v in pairs(file) do
local label =
top_panel.add({type = 'flow'}).add {type = 'label', name = variable_label_name, caption = k}
top_panel.add{ type = "flow" }.add{ type = "label", name = variable_label_name, caption = k }
Gui.set_data(label, v)
end
elseif file_type == 'function' then
elseif file_type == "function" then
text_box.text = dump_function(file)
else
text_box.text = tostring(file)
@@ -130,13 +130,14 @@ Gui.on_click(
local variable_type = type(variable)
if variable_type == 'table' then
if variable_type == "table" then
Gui.clear(top_panel)
for k, v in pairs(variable) do
local label =
top_panel.add({type = 'flow'}).add {type = 'label', name = variable_label_name, caption = k}
top_panel.add{ type = "flow" }.add{ type = "label", name = variable_label_name, caption = k }
Gui.set_data(label, v)
end
return
end
@@ -149,7 +150,7 @@ Gui.on_click(
element.style.font_color = Color.orange
data.selected_variable_label = element
if variable_type == 'function' then
if variable_type == "function" then
text_box.text = dump_function(variable)
else
text_box.text = tostring(variable)

View File

@@ -15,37 +15,37 @@ local right_panel_name = Gui.uid_name()
local input_text_box_name = Gui.uid_name()
local refresh_name = Gui.uid_name()
Public.name = 'Storage'
Public.name = "Storage"
function Public.show(container)
local main_flow = container.add {type = 'flow', direction = 'horizontal'}
local main_flow = container.add{ type = "flow", direction = "horizontal" }
local left_panel = main_flow.add {type = 'scroll-pane', name = left_panel_name}
local left_panel = main_flow.add{ type = "scroll-pane", name = left_panel_name }
local left_panel_style = left_panel.style
left_panel_style.width = 300
for token_id in pairs(Storage.registered) do
local header = left_panel.add({type = 'flow'}).add {type = 'label', name = header_name, caption = token_id}
local header = left_panel.add{ type = "flow" }.add{ type = "label", name = header_name, caption = token_id }
Gui.set_data(header, token_id)
end
local right_flow = main_flow.add {type = 'flow', direction = 'vertical'}
local right_flow = main_flow.add{ type = "flow", direction = "vertical" }
local right_top_flow = right_flow.add {type = 'flow', direction = 'horizontal'}
local right_top_flow = right_flow.add{ type = "flow", direction = "horizontal" }
local input_text_box = right_top_flow.add {type = 'text-box', name = input_text_box_name}
local input_text_box = right_top_flow.add{ type = "text-box", name = input_text_box_name }
local input_text_box_style = input_text_box.style
input_text_box_style.horizontally_stretchable = true
input_text_box_style.height = 32
input_text_box_style.maximal_width = 1000
local refresh_button =
right_top_flow.add {type = 'sprite-button', name = refresh_name, sprite = 'utility/reset', tooltip = 'refresh'}
right_top_flow.add{ type = "sprite-button", name = refresh_name, sprite = "utility/reset", tooltip = "refresh" }
local refresh_button_style = refresh_button.style
refresh_button_style.width = 32
refresh_button_style.height = 32
local right_panel = right_flow.add {type = 'text-box', name = right_panel_name}
local right_panel = right_flow.add{ type = "text-box", name = right_panel_name }
right_panel.read_only = true
right_panel.selectable = true
@@ -58,7 +58,7 @@ function Public.show(container)
local data = {
right_panel = right_panel,
input_text_box = input_text_box,
selected_header = nil
selected_header = nil,
}
Gui.set_data(input_text_box, data)
@@ -85,10 +85,10 @@ Gui.on_click(
element.style.font_color = Color.orange
data.selected_header = element
input_text_box.text = concat {'storage.exp_storage[', token_id, ']'}
input_text_box.text = concat{ "storage.exp_storage[", token_id, "]" }
input_text_box.style.font_color = Color.black
local content = dump(storage.exp_storage[token_id]) or 'nil'
local content = dump(storage.exp_storage[token_id]) or "nil"
right_panel.text = content
end
)

View File

@@ -11,7 +11,7 @@ local Roles = require("modules.exp_legacy.expcore.roles") --- @dep expcore.roles
local rolling_stocks = {}
local function landfill_init()
for name, _ in pairs(prototypes.get_entity_filtered{{filter = 'rolling-stock'}}) do
for name, _ in pairs(prototypes.get_entity_filtered{ { filter = "rolling-stock" } }) do
rolling_stocks[name] = true
end
end
@@ -20,50 +20,50 @@ local function rotate_bounding_box(box)
return {
left_top = {
x = -box.right_bottom.y,
y = box.left_top.x
y = box.left_top.x,
},
right_bottom = {
x = -box.left_top.y,
y = box.right_bottom.x
}
y = box.right_bottom.x,
},
}
end
local function curve_flip_lr(oc)
local nc = table.deepcopy(oc)
local nc = table.deepcopy(oc)
for r=1, 8 do
for c=1, 8 do
nc[r][c] = oc[r][9 - c]
end
end
for r = 1, 8 do
for c = 1, 8 do
nc[r][c] = oc[r][9 - c]
end
end
return nc
return nc
end
local function curve_flip_d(oc)
local nc = table.deepcopy(oc)
local nc = table.deepcopy(oc)
for r=1, 8 do
for c=1, 8 do
nc[r][c] = oc[c][r]
end
end
for r = 1, 8 do
for c = 1, 8 do
nc[r][c] = oc[c][r]
end
end
return nc
return nc
end
local curves = {}
curves[1] = {
{0, 0, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 1, 1, 1, 0},
{0, 0, 0, 1, 1, 1, 1, 0},
{0, 0, 0, 1, 1, 1, 0, 0},
{0, 0, 1, 1, 1, 0, 0, 0},
{0, 0, 1, 1, 1, 0, 0, 0},
{0, 0, 1, 1, 0, 0, 0, 0},
{0, 0, 1, 1, 0, 0, 0, 0}
{ 0, 0, 0, 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 1, 1, 1, 0 },
{ 0, 0, 0, 1, 1, 1, 1, 0 },
{ 0, 0, 0, 1, 1, 1, 0, 0 },
{ 0, 0, 1, 1, 1, 0, 0, 0 },
{ 0, 0, 1, 1, 1, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0, 0, 0 },
}
curves[6] = curve_flip_d(curves[1])
curves[3] = curve_flip_lr(curves[6])
@@ -79,12 +79,12 @@ for i, map in ipairs(curves) do
curve_n[i] = {}
local index = 1
for r=1, 8 do
for c=1, 8 do
for r = 1, 8 do
for c = 1, 8 do
if map[r][c] == 1 then
curve_n[i][index] = {
['x'] = c - 5,
['y'] = r - 5
["x"] = c - 5,
["y"] = r - 5,
}
index = index + 1
@@ -100,13 +100,13 @@ local function landfill_gui_add_landfill(blueprint)
for _, ent in pairs(entities) do
-- vehicle
if not (rolling_stocks[ent.name] or ent.name == 'offshore-pump') then
if not (rolling_stocks[ent.name] or ent.name == "offshore-pump") then
-- curved rail, special
if ent.name ~= 'curved-rail' then
if ent.name ~= "curved-rail" then
local proto = prototypes.entity[ent.name]
local box = proto.collision_box or proto.selection_box
if proto.collision_mask['ground-tile'] == nil then
if proto.collision_mask["ground-tile"] == nil then
if ent.direction then
if ent.direction ~= defines.direction.north then
box = rotate_bounding_box(box)
@@ -125,21 +125,21 @@ local function landfill_gui_add_landfill(blueprint)
for x = math.floor(ent.position.x + box.left_top.x), math.floor(ent.position.x + box.right_bottom.x), 1 do
tile_index = tile_index + 1
new_tiles[tile_index] = {
name = 'landfill',
position = {x, y}
name = "landfill",
position = { x, y },
}
end
end
end
-- curved rail
-- curved rail
else
local curve_mask = curve_n[ent.direction or 8]
for m=1, #curve_mask do
for m = 1, #curve_mask do
new_tiles[tile_index + 1] = {
name = 'landfill',
position = {curve_mask[m].x + ent.position.x, curve_mask[m].y + ent.position.y}
name = "landfill",
position = { curve_mask[m].x + ent.position.x, curve_mask[m].y + ent.position.y },
}
tile_index = tile_index + 1
@@ -153,34 +153,33 @@ local function landfill_gui_add_landfill(blueprint)
if old_tiles then
for _, old_tile in pairs(old_tiles) do
new_tiles[tile_index + 1] = {
name = 'landfill',
position = {old_tile.position.x, old_tile.position.y}
name = "landfill",
position = { old_tile.position.x, old_tile.position.y },
}
tile_index = tile_index + 1
end
end
return {tiles = new_tiles}
return { tiles = new_tiles }
end
-- @element toolbar_button
Gui.toolbar_button('item/landfill', {'landfill.main-tooltip'}, function(player)
return Roles.player_allowed(player, 'gui/landfill')
Gui.toolbar_button("item/landfill", { "landfill.main-tooltip" }, function(player)
return Roles.player_allowed(player, "gui/landfill")
end)
:on_click(function(player, _, _)
if player.cursor_stack and player.cursor_stack.valid_for_read then
if player.cursor_stack.type == 'blueprint' and player.cursor_stack.is_blueprint_setup() then
local modified = landfill_gui_add_landfill(player.cursor_stack)
:on_click(function(player, _, _)
if player.cursor_stack and player.cursor_stack.valid_for_read then
if player.cursor_stack.type == "blueprint" and player.cursor_stack.is_blueprint_setup() then
local modified = landfill_gui_add_landfill(player.cursor_stack)
if modified and next(modified.tiles) then
player.cursor_stack.set_blueprint_tiles(modified.tiles)
if modified and next(modified.tiles) then
player.cursor_stack.set_blueprint_tiles(modified.tiles)
end
end
else
player.print{ "landfill.cursor-none" }
end
else
player.print{'landfill.cursor-none'}
end
end)
end)
Event.add(defines.events.on_player_joined_game, landfill_init)

View File

@@ -6,19 +6,19 @@ local Event = require("modules/exp_legacy/utils/event") --- @dep utils.event
local Roles = require("modules.exp_legacy.expcore.roles") --- @dep expcore.roles
local config = require("modules.exp_legacy.config.module") --- @dep config.module
local Selection = require("modules.exp_legacy.modules.control.selection") --- @dep modules.control.selection
local SelectionModuleArea = 'ModuleArea'
local SelectionModuleArea = "ModuleArea"
--- align an aabb to the grid by expanding it
local function aabb_align_expand(aabb)
return {
left_top = {
x = math.floor(aabb.left_top.x),
y = math.floor(aabb.left_top.y)
y = math.floor(aabb.left_top.y),
},
right_bottom = {
x = math.ceil(aabb.right_bottom.x),
y = math.ceil(aabb.right_bottom.y)
}
y = math.ceil(aabb.right_bottom.y),
},
}
end
@@ -40,30 +40,30 @@ local function get_module_name()
end
local elem_filter = {
name = {{
filter = 'name',
name = machine_name
}},
normal = {{
filter = 'type',
type = 'module'
name = { {
filter = "name",
name = machine_name,
} },
normal = { {
filter = "type",
type = "module",
}, {
filter = 'name',
filter = "name",
name = prod_module_names,
mode = 'and',
invert = true
}},
prod = {{
filter = 'type',
type = 'module'
}}
mode = "and",
invert = true,
} },
prod = { {
filter = "type",
type = "module",
} },
}
local function clear_module(player, area, machine)
for _, entity in pairs(player.surface.find_entities_filtered{area=area, name=machine, force=player.force}) do
for _, r in pairs(player.surface.find_entities_filtered{position=entity.position, name='item-request-proxy', force=player.force}) do
for _, entity in pairs(player.surface.find_entities_filtered{ area = area, name = machine, force = player.force }) do
for _, r in pairs(player.surface.find_entities_filtered{ position = entity.position, name = "item-request-proxy", force = player.force }) do
if r then
r.destroy{raise_destroy=true}
r.destroy{ raise_destroy = true }
end
end
@@ -74,7 +74,7 @@ local function clear_module(player, area, machine)
if m_current_module_content then
for k, m in pairs(m_current_module_content) do
player.surface.spill_item_stack(entity.bounding_box.left_top, {name=k, count=m}, true, player.force, false)
player.surface.spill_item_stack(entity.bounding_box.left_top, { name = k, count = m }, true, player.force, false)
end
end
@@ -84,25 +84,23 @@ local function clear_module(player, area, machine)
end
local function apply_module(player, area, machine, modules)
for _, entity in pairs(player.surface.find_entities_filtered{area=area, name=machine, force=player.force}) do
for _, entity in pairs(player.surface.find_entities_filtered{ area = area, name = machine, force = player.force }) do
local m_current_recipe
if entity.prototype.crafting_speed then
m_current_recipe= entity.get_recipe()
m_current_recipe = entity.get_recipe()
end
if m_current_recipe then
if config.module_allowed[m_current_recipe.name] then
entity.surface.create_entity{name='item-request-proxy', target=entity, position=entity.position, force=entity.force, modules=modules['n']}
entity.surface.create_entity{ name = "item-request-proxy", target = entity, position = entity.position, force = entity.force, modules = modules["n"] }
entity.last_user = player
else
entity.surface.create_entity{name='item-request-proxy', target=entity, position=entity.position, force=entity.force, modules=modules['p']}
entity.surface.create_entity{ name = "item-request-proxy", target = entity, position = entity.position, force = entity.force, modules = modules["p"] }
entity.last_user = player
end
else
entity.surface.create_entity{name='item-request-proxy', target=entity, position=entity.position, force=entity.force, modules=modules['n']}
entity.surface.create_entity{ name = "item-request-proxy", target = entity, position = entity.position, force = entity.force, modules = modules["n"] }
entity.last_user = player
end
end
@@ -115,35 +113,34 @@ Selection.on_selection(SelectionModuleArea, function(event)
local frame = Gui.get_left_element(player, module_container)
local scroll_table = frame.container.scroll.table
for i=1, config.default_module_row_count do
local mma = scroll_table['module_mm_' .. i .. '_0'].elem_value
for i = 1, config.default_module_row_count do
local mma = scroll_table["module_mm_" .. i .. "_0"].elem_value
if mma then
local mm = {
['n'] = {},
['p'] = {}
["n"] = {},
["p"] = {},
}
for j=1, prototypes.entity[mma].module_inventory_size, 1 do
local mmo = scroll_table['module_mm_' .. i .. '_' .. j].elem_value
for j = 1, prototypes.entity[mma].module_inventory_size, 1 do
local mmo = scroll_table["module_mm_" .. i .. "_" .. j].elem_value
if mmo then
if mm['n'][mmo] then
mm['n'][mmo] = mm['n'][mmo] + 1
mm['p'][mmo] = mm['p'][mmo] + 1
if mm["n"][mmo] then
mm["n"][mmo] = mm["n"][mmo] + 1
mm["p"][mmo] = mm["p"][mmo] + 1
else
mm['n'][mmo] = 1
mm['p'][mmo] = 1
mm["n"][mmo] = 1
mm["p"][mmo] = 1
end
end
end
for k, v in pairs(mm['p']) do
if k:find('productivity') then
local module_name = k:gsub('productivity', 'effectivity')
mm['p'][module_name] = (mm['p'][module_name] or 0) + v
mm['p'][k] = nil
for k, v in pairs(mm["p"]) do
if k:find("productivity") then
local module_name = k:gsub("productivity", "effectivity")
mm["p"][module_name] = (mm["p"][module_name] or 0) + v
mm["p"][k] = nil
end
end
@@ -159,29 +156,26 @@ local function row_set(player, element)
local frame = Gui.get_left_element(player, module_container)
local scroll_table = frame.container.scroll.table
if scroll_table[element .. '0'].elem_value then
for i=1, config.module_slot_max do
if i <= prototypes.entity[scroll_table[element .. '0'].elem_value].module_inventory_size then
if config.machine[scroll_table[element .. '0'].elem_value].prod then
if scroll_table[element .. "0"].elem_value then
for i = 1, config.module_slot_max do
if i <= prototypes.entity[scroll_table[element .. "0"].elem_value].module_inventory_size then
if config.machine[scroll_table[element .. "0"].elem_value].prod then
scroll_table[element .. i].elem_filters = elem_filter.prod
else
scroll_table[element .. i].elem_filters = elem_filter.normal
end
scroll_table[element .. i].enabled = true
scroll_table[element .. i].elem_value = config.machine[scroll_table[element .. '0'].elem_value].module
scroll_table[element .. i].elem_value = config.machine[scroll_table[element .. "0"].elem_value].module
else
scroll_table[element .. i].enabled = false
scroll_table[element .. i].elem_value = nil
end
end
else
local mf = elem_filter.normal
for i=1, config.module_slot_max do
for i = 1, config.module_slot_max do
scroll_table[element .. i].enabled = false
scroll_table[element .. i].elem_filters = mf
scroll_table[element .. i].elem_value = nil
@@ -190,61 +184,61 @@ local function row_set(player, element)
end
local button_apply =
Gui.element{
type = 'button',
caption = 'Apply',
style = 'button'
}:on_click(function(player)
if Selection.is_selecting(player, SelectionModuleArea) then
Selection.stop(player)
else
Selection.start(player, SelectionModuleArea)
end
end)
Gui.element{
type = "button",
caption = "Apply",
style = "button",
}:on_click(function(player)
if Selection.is_selecting(player, SelectionModuleArea) then
Selection.stop(player)
else
Selection.start(player, SelectionModuleArea)
end
end)
module_container =
Gui.element(function(definition, parent)
local container = Gui.container(parent, definition.name, (config.module_slot_max + 2) * 36)
Gui.header(container, 'Module Inserter', '', true)
Gui.element(function(definition, parent)
local container = Gui.container(parent, definition.name, (config.module_slot_max + 2) * 36)
Gui.header(container, "Module Inserter", "", true)
local scroll_table = Gui.scroll_table(container, (config.module_slot_max + 2) * 36, config.module_slot_max + 1)
local scroll_table = Gui.scroll_table(container, (config.module_slot_max + 2) * 36, config.module_slot_max + 1)
for i=1, config.default_module_row_count do
scroll_table.add{
name = 'module_mm_' .. i .. '_0',
type = 'choose-elem-button',
elem_type = 'entity',
elem_filters = elem_filter.name,
style = 'slot_button'
}
for j=1, config.module_slot_max do
for i = 1, config.default_module_row_count do
scroll_table.add{
name = 'module_mm_' .. i .. '_' .. j,
type = 'choose-elem-button',
elem_type = 'item',
elem_filters = elem_filter.normal,
style = 'slot_button',
enabled = false
name = "module_mm_" .. i .. "_0",
type = "choose-elem-button",
elem_type = "entity",
elem_filters = elem_filter.name,
style = "slot_button",
}
for j = 1, config.module_slot_max do
scroll_table.add{
name = "module_mm_" .. i .. "_" .. j,
type = "choose-elem-button",
elem_type = "item",
elem_filters = elem_filter.normal,
style = "slot_button",
enabled = false,
}
end
end
end
button_apply(container)
button_apply(container)
return container.parent
end)
:static_name(Gui.unique_static_name)
:add_to_left_flow()
return container.parent
end)
:static_name(Gui.unique_static_name)
:add_to_left_flow()
Gui.left_toolbar_button('item/productivity-module-3', {'module.main-tooltip'}, module_container, function(player)
return Roles.player_allowed(player, 'gui/module')
Gui.left_toolbar_button("item/productivity-module-3", { "module.main-tooltip" }, module_container, function(player)
return Roles.player_allowed(player, "gui/module")
end)
Event.add(defines.events.on_gui_elem_changed, function(event)
if event.element.name:sub(1, 10) == 'module_mm_' then
if event.element.name:sub(-1) == '0' then
row_set(game.players[event.player_index], 'module_mm_' .. event.element.name:sub(-3):sub(1, 1) .. '_')
if event.element.name:sub(1, 10) == "module_mm_" then
if event.element.name:sub(-1) == "0" then
row_set(game.players[event.player_index], "module_mm_" .. event.element.name:sub(-3):sub(1, 1) .. "_")
end
end
end)
@@ -271,7 +265,7 @@ Event.add(defines.events.on_entity_settings_pasted, function(event)
-- rotate machine also
if config.copy_paste_rotation then
if (source.name == destination.name or source.prototype.fast_replaceable_group == destination.prototype.fast_replaceable_group) then
if source.supports_direction and destination.supports_direction and source.type ~= 'transport-belt' then
if source.supports_direction and destination.supports_direction and source.type ~= "transport-belt" then
local destination_box = destination.bounding_box
local ltx = destination_box.left_top.x
@@ -309,7 +303,7 @@ Event.add(defines.events.on_entity_settings_pasted, function(event)
clear_module(player, destination.bounding_box, destination.name)
if next(source_inventory_content) ~= nil then
apply_module(player, destination.bounding_box, destination.name, {['n']=source_inventory_content, ['p']=source_inventory_content})
apply_module(player, destination.bounding_box, destination.name, { ["n"] = source_inventory_content, ["p"] = source_inventory_content })
end
end
end)

View File

@@ -14,10 +14,10 @@ local Colors = require("modules/exp_util/include/color")
local format_time = _C.format_time --- @dep expcore.common
--- Stores all data for the warp gui
local PlayerListData = Datastore.connect('PlayerListData')
local PlayerListData = Datastore.connect("PlayerListData")
PlayerListData:set_serializer(Datastore.name_serializer)
local SelectedPlayer = PlayerListData:combine('SelectedPlayer')
local SelectedAction = PlayerListData:combine('SelectedAction')
local SelectedPlayer = PlayerListData:combine("SelectedPlayer")
local SelectedAction = PlayerListData:combine("SelectedAction")
-- Set the config to use these stores
config.set_datastores(SelectedPlayer, SelectedAction)
@@ -25,118 +25,118 @@ config.set_datastores(SelectedPlayer, SelectedAction)
--- Button used to open the action bar
-- @element open_action_bar
local open_action_bar =
Gui.element{
type = 'sprite-button',
sprite = 'utility/expand_dots',
tooltip = {'player-list.open-action-bar'},
style = 'frame_button',
name = Gui.unique_static_name
}
:style{
padding = -2,
width = 8,
height = 14
}
:on_click(function(player, element, _)
local selected_player_name = element.parent.name
local old_selected_player_name = SelectedPlayer:get(player)
if selected_player_name == old_selected_player_name then
SelectedPlayer:remove(player)
else
SelectedPlayer:set(player, selected_player_name)
end
end)
Gui.element{
type = "sprite-button",
sprite = "utility/expand_dots",
tooltip = { "player-list.open-action-bar" },
style = "frame_button",
name = Gui.unique_static_name,
}
:style{
padding = -2,
width = 8,
height = 14,
}
:on_click(function(player, element, _)
local selected_player_name = element.parent.name
local old_selected_player_name = SelectedPlayer:get(player)
if selected_player_name == old_selected_player_name then
SelectedPlayer:remove(player)
else
SelectedPlayer:set(player, selected_player_name)
end
end)
--- Button used to close the action bar
-- @element close_action_bar
local close_action_bar =
Gui.element{
type = 'sprite-button',
sprite = 'utility/close_black',
tooltip = {'player-list.close-action-bar'},
style = 'slot_sized_button_red'
}
:style(Gui.sprite_style(30, -1, { top_margin = -1, right_margin = -1 }))
:on_click(function(player, _)
SelectedPlayer:remove(player)
SelectedAction:remove(player)
end)
Gui.element{
type = "sprite-button",
sprite = "utility/close_black",
tooltip = { "player-list.close-action-bar" },
style = "slot_sized_button_red",
}
:style(Gui.sprite_style(30, -1, { top_margin = -1, right_margin = -1 }))
:on_click(function(player, _)
SelectedPlayer:remove(player)
SelectedAction:remove(player)
end)
--- Button used to confirm a reason
-- @element reason_confirm
local reason_confirm =
Gui.element{
type = 'sprite-button',
sprite = 'utility/confirm_slot',
tooltip = {'player-list.reason-confirm'},
style = 'slot_sized_button_green'
}
:style(Gui.sprite_style(30, -1, { left_margin = -2, right_margin = -1 }))
:on_click(function(player, element)
local reason = element.parent.entry.text
local action_name = SelectedAction:get(player)
local reason_callback = config.buttons[action_name].reason_callback
if reason == nil or not reason:find("%S") then reason = 'no reason given' end
reason_callback(player, reason)
SelectedPlayer:remove(player)
SelectedAction:remove(player)
element.parent.entry.text = ''
end)
Gui.element{
type = "sprite-button",
sprite = "utility/confirm_slot",
tooltip = { "player-list.reason-confirm" },
style = "slot_sized_button_green",
}
:style(Gui.sprite_style(30, -1, { left_margin = -2, right_margin = -1 }))
:on_click(function(player, element)
local reason = element.parent.entry.text
local action_name = SelectedAction:get(player)
local reason_callback = config.buttons[action_name].reason_callback
if reason == nil or not reason:find("%S") then reason = "no reason given" end
reason_callback(player, reason)
SelectedPlayer:remove(player)
SelectedAction:remove(player)
element.parent.entry.text = ""
end)
--- Set of elements that are used to make up a row of the player table
-- @element add_player_base
local add_player_base =
Gui.element(function(_, parent, player_data)
-- Add the button to open the action bar
local toggle_action_bar_flow = parent.add{ type = 'flow', name = player_data.name }
open_action_bar(toggle_action_bar_flow)
Gui.element(function(_, parent, player_data)
-- Add the button to open the action bar
local toggle_action_bar_flow = parent.add{ type = "flow", name = player_data.name }
open_action_bar(toggle_action_bar_flow)
-- Add the player name
local player_name = parent.add{
type = 'label',
name = 'player-name-'..player_data.index,
caption = player_data.name,
tooltip = {'player-list.open-map', player_data.name, player_data.tag, player_data.role_name}
}
player_name.style.padding = {0, 2,0, 0}
player_name.style.font_color = player_data.chat_color
-- Add the player name
local player_name = parent.add{
type = "label",
name = "player-name-" .. player_data.index,
caption = player_data.name,
tooltip = { "player-list.open-map", player_data.name, player_data.tag, player_data.role_name },
}
player_name.style.padding = { 0, 2, 0, 0 }
player_name.style.font_color = player_data.chat_color
-- Add the time played label
local alignment = Gui.alignment(parent, 'player-time-'..player_data.index)
local time_label = alignment.add{
name = 'label',
type = 'label',
caption = player_data.caption,
tooltip = player_data.tooltip
}
time_label.style.padding = 0
-- Add the time played label
local alignment = Gui.alignment(parent, "player-time-" .. player_data.index)
local time_label = alignment.add{
name = "label",
type = "label",
caption = player_data.caption,
tooltip = player_data.tooltip,
}
time_label.style.padding = 0
return player_name
end)
:on_click(function(player, element, event)
local selected_player_name = element.caption
local selected_player = game.players[selected_player_name]
if event.button == defines.mouse_button_type.left then
-- LMB will open the map to the selected player
local position = selected_player.position
event.player.zoom_to_world(position, 1.75)
else
-- RMB will toggle the settings
local old_selected_player_name = SelectedPlayer:get(player)
if selected_player_name == old_selected_player_name then
SelectedPlayer:remove(player)
SelectedAction:remove(player)
return player_name
end)
:on_click(function(player, element, event)
local selected_player_name = element.caption
local selected_player = game.players[selected_player_name]
if event.button == defines.mouse_button_type.left then
-- LMB will open the map to the selected player
local position = selected_player.position
event.player.zoom_to_world(position, 1.75)
else
SelectedPlayer:set(player, selected_player_name)
-- RMB will toggle the settings
local old_selected_player_name = SelectedPlayer:get(player)
if selected_player_name == old_selected_player_name then
SelectedPlayer:remove(player)
SelectedAction:remove(player)
else
SelectedPlayer:set(player, selected_player_name)
end
end
end
end)
end)
-- Removes the three elements that are added as part of the base
local function remove_player_base(parent, player)
Gui.destroy_if_valid(parent[player.name])
Gui.destroy_if_valid(parent['player-name-'..player.index])
Gui.destroy_if_valid(parent['player-time-'..player.index])
Gui.destroy_if_valid(parent["player-name-" .. player.index])
Gui.destroy_if_valid(parent["player-time-" .. player.index])
end
-- Update the time label for a player using there player time data
@@ -151,21 +151,21 @@ end
--- Adds all the buttons and flows that make up the action bar
-- @element add_action_bar
local add_action_bar_buttons =
Gui.element(function(_, parent)
close_action_bar(parent)
-- Loop over all the buttons in the config
for action_name, button_data in pairs(config.buttons) do
-- Added the permission flow
local permission_flow = parent.add{ type = 'flow', name = action_name }
permission_flow.visible = false
-- Add the buttons under that permission
for _, button in ipairs(button_data) do
button(permission_flow)
Gui.element(function(_, parent)
close_action_bar(parent)
-- Loop over all the buttons in the config
for action_name, button_data in pairs(config.buttons) do
-- Added the permission flow
local permission_flow = parent.add{ type = "flow", name = action_name }
permission_flow.visible = false
-- Add the buttons under that permission
for _, button in ipairs(button_data) do
button(permission_flow)
end
end
end
return parent
end)
return parent
end)
--- Updates the visible state of the action bar buttons
local function update_action_bar(element)
@@ -175,7 +175,6 @@ local function update_action_bar(element)
if not selected_player_name then
-- Hide the action bar when no player is selected
element.visible = false
else
local selected_player = game.players[selected_player_name]
if not selected_player.connected then
@@ -183,7 +182,6 @@ local function update_action_bar(element)
element.visible = false
SelectedPlayer:remove(player)
SelectedAction:remove(player)
else
-- Otherwise check what actions the player is allowed to use
element.visible = true
@@ -194,7 +192,6 @@ local function update_action_bar(element)
element[action_name].visible = true
end
end
end
end
end
@@ -202,74 +199,74 @@ end
--- Main player list container for the left flow
-- @element player_list_container
local player_list_container =
Gui.element(function(definition, parent)
-- Draw the internal container
local container = Gui.container(parent, definition.name, 200)
Gui.element(function(definition, parent)
-- Draw the internal container
local container = Gui.container(parent, definition.name, 200)
-- Draw the scroll table for the players
local scroll_table = Gui.scroll_table(container, 184, 3)
-- Draw the scroll table for the players
local scroll_table = Gui.scroll_table(container, 184, 3)
-- Change the style of the scroll table
local scroll_table_style = scroll_table.style
scroll_table_style.padding = {1, 0,1, 2}
-- Change the style of the scroll table
local scroll_table_style = scroll_table.style
scroll_table_style.padding = { 1, 0, 1, 2 }
-- Add the action bar
local action_bar = Gui.footer(container, nil, nil, false, 'action_bar')
-- Add the action bar
local action_bar = Gui.footer(container, nil, nil, false, "action_bar")
-- Change the style of the action bar
local action_bar_style = action_bar.style
action_bar_style.height = 35
action_bar_style.padding = {1, 3}
action_bar.visible = false
-- Change the style of the action bar
local action_bar_style = action_bar.style
action_bar_style.height = 35
action_bar_style.padding = { 1, 3 }
action_bar.visible = false
-- Add the buttons to the action bar
add_action_bar_buttons(action_bar)
-- Add the buttons to the action bar
add_action_bar_buttons(action_bar)
-- Add the reason bar
local reason_bar = Gui.footer(container, nil, nil, false, 'reason_bar')
-- Add the reason bar
local reason_bar = Gui.footer(container, nil, nil, false, "reason_bar")
-- Change the style of the reason bar
local reason_bar_style = reason_bar.style
reason_bar_style.height = 35
reason_bar_style.padding = {-1, 3}
reason_bar.visible = false
-- Change the style of the reason bar
local reason_bar_style = reason_bar.style
reason_bar_style.height = 35
reason_bar_style.padding = { -1, 3 }
reason_bar.visible = false
-- Add the text entry for the reason bar
local reason_field =
reason_bar.add{
name = 'entry',
type = 'textfield',
style = 'stretchable_textfield',
tooltip = {'player-list.reason-entry'}
}
-- Add the text entry for the reason bar
local reason_field =
reason_bar.add{
name = "entry",
type = "textfield",
style = "stretchable_textfield",
tooltip = { "player-list.reason-entry" },
}
-- Change the style of the text entry
local reason_entry_style = reason_field.style
reason_entry_style.padding = 0
reason_entry_style.height = 28
reason_entry_style.minimal_width = 160
-- Change the style of the text entry
local reason_entry_style = reason_field.style
reason_entry_style.padding = 0
reason_entry_style.height = 28
reason_entry_style.minimal_width = 160
-- Add the confirm reason button
reason_confirm(reason_bar)
-- Add the confirm reason button
reason_confirm(reason_bar)
-- Return the exteral container
return container.parent
end)
:static_name(Gui.unique_static_name)
:add_to_left_flow(true)
-- Return the exteral container
return container.parent
end)
:static_name(Gui.unique_static_name)
:add_to_left_flow(true)
--- Button on the top flow used to toggle the player list container
-- @element toggle_player_list
Gui.left_toolbar_button('entity/character', {'player-list.main-tooltip'}, player_list_container, function(player)
return Roles.player_allowed(player, 'gui/player-list')
Gui.left_toolbar_button("entity/character", { "player-list.main-tooltip" }, player_list_container, function(player)
return Roles.player_allowed(player, "gui/player-list")
end)
-- Get caption and tooltip format for a player
local function get_time_formats(online_time, afk_time)
local tick = game.tick > 0 and game.tick or 1
local percent = math.round(online_time/tick, 3)*100
local percent = math.round(online_time / tick, 3) * 100
local caption = format_time(online_time)
local tooltip = {'player-list.afk-time', percent, format_time(afk_time, {minutes=true, long=true})}
local tooltip = { "player-list.afk-time", percent, format_time(afk_time, { minutes = true, long = true }) }
return caption, tooltip
end
@@ -282,9 +279,9 @@ local function get_player_times()
-- Add the player time details to the array
local caption, tooltip = get_time_formats(player.online_time, player.afk_time)
player_times[ctn] = {
element_name = 'player-time-'..player.index,
element_name = "player-time-" .. player.index,
caption = caption,
tooltip = tooltip
tooltip = tooltip,
}
end
@@ -319,7 +316,7 @@ local function get_player_list_order()
role_name = role_name,
chat_color = player.chat_color,
caption = caption,
tooltip = tooltip
tooltip = tooltip,
}
end
end
@@ -398,9 +395,9 @@ SelectedPlayer:on_update(function(player_name, selected_player)
update_action_bar(frame.container.action_bar)
for _, next_player in pairs(game.connected_players) do
local element = scroll_table[next_player.name][open_action_bar.name]
local style = 'frame_button'
local style = "frame_button"
if next_player.name == selected_player then
style = 'tool_button'
style = "tool_button"
end
element.style = style
local element_style = element.style
@@ -426,9 +423,7 @@ SelectedAction:on_update(function(player_name, selected_action)
SelectedPlayer:remove(player)
SelectedAction:remove(player)
end
else
element.visible = false
end
end)
end)

View File

@@ -11,21 +11,21 @@ local format_number = require("util").format_number --- @dep util
local pd_container
local label_width = {
['name'] = 135,
['count'] = 105,
['total'] = 480
["name"] = 135,
["count"] = 105,
["total"] = 480,
}
local function format_time_short(value)
return format_time(value*3600, {
hours=true,
minutes=true,
seconds=false
return format_time(value * 3600, {
hours = true,
minutes = true,
seconds = false,
})
end
local function format_number_n(n)
return format_number(math.floor(n)) .. string.format('%.2f', n % 1):sub(2)
return format_number(math.floor(n)) .. string.format("%.2f", n % 1):sub(2)
end
local playerStats = PlayerData.Statistics
@@ -33,87 +33,87 @@ local computed_stats = {
DamageDeathRatio = {
default = format_number_n(0),
calculate = function(player_name)
return format_number_n(playerStats['DamageDealt']:get(player_name, 0) / playerStats['Deaths']:get(player_name, 1))
end
return format_number_n(playerStats["DamageDealt"]:get(player_name, 0) / playerStats["Deaths"]:get(player_name, 1))
end,
},
KillDeathRatio = {
default = format_number_n(0),
calculate = function(player_name)
return format_number_n(playerStats['Kills']:get(player_name, 0) / playerStats['Deaths']:get(player_name, 1))
end
return format_number_n(playerStats["Kills"]:get(player_name, 0) / playerStats["Deaths"]:get(player_name, 1))
end,
},
SessionTime = {
default = format_time_short(0),
calculate = function(player_name)
return format_time_short((playerStats['Playtime']:get(player_name, 0) - playerStats['AfkTime']:get(player_name, 0)) / playerStats['JoinCount']:get(player_name, 1))
end
return format_time_short((playerStats["Playtime"]:get(player_name, 0) - playerStats["AfkTime"]:get(player_name, 0)) / playerStats["JoinCount"]:get(player_name, 1))
end,
},
BuildRatio = {
default = format_number_n(0),
calculate = function(player_name)
return format_number_n(playerStats['MachinesBuilt']:get(player_name, 0) / playerStats['MachinesRemoved']:get(player_name, 1))
end
return format_number_n(playerStats["MachinesBuilt"]:get(player_name, 0) / playerStats["MachinesRemoved"]:get(player_name, 1))
end,
},
RocketPerHour = {
default = format_number_n(0),
calculate = function(player_name)
return format_number_n(playerStats['RocketsLaunched']:get(player_name, 0) * 60 / playerStats['Playtime']:get(player_name, 1))
end
return format_number_n(playerStats["RocketsLaunched"]:get(player_name, 0) * 60 / playerStats["Playtime"]:get(player_name, 1))
end,
},
TreeKillPerMinute = {
default = format_number_n(0),
calculate = function(player_name)
return format_number_n(playerStats['TreesDestroyed']:get(player_name, 0) / playerStats['Playtime']:get(player_name, 1))
end
return format_number_n(playerStats["TreesDestroyed"]:get(player_name, 0) / playerStats["Playtime"]:get(player_name, 1))
end,
},
NetPlayTime = {
default = format_time_short(0),
calculate = function(player_name)
return format_time_short((playerStats['Playtime']:get(player_name, 0) - playerStats['AfkTime']:get(player_name, 0)))
end
return format_time_short((playerStats["Playtime"]:get(player_name, 0) - playerStats["AfkTime"]:get(player_name, 0)))
end,
},
AFKTimeRatio = {
default = format_number_n(0),
calculate = function(player_name)
return format_number_n(playerStats['AfkTime']:get(player_name, 0) * 100 / playerStats['Playtime']:get(player_name, 1))
end
return format_number_n(playerStats["AfkTime"]:get(player_name, 0) * 100 / playerStats["Playtime"]:get(player_name, 1))
end,
},
}
local label =
Gui.element(function(_, parent, width, caption, tooltip, name)
local new_label = parent.add{
type = 'label',
caption = caption,
tooltip = tooltip,
name = name,
style = 'heading_2_label'
}
Gui.element(function(_, parent, width, caption, tooltip, name)
local new_label = parent.add{
type = "label",
caption = caption,
tooltip = tooltip,
name = name,
style = "heading_2_label",
}
new_label.style.width = width
return new_label
end)
new_label.style.width = width
return new_label
end)
local pd_data_set =
Gui.element(function(_, parent, name)
local pd_data_set = parent.add{type='flow', direction='vertical', name=name}
local disp = Gui.scroll_table(pd_data_set, label_width['total'], 4, 'disp')
Gui.element(function(_, parent, name)
local pd_data_set = parent.add{ type = "flow", direction = "vertical", name = name }
local disp = Gui.scroll_table(pd_data_set, label_width["total"], 4, "disp")
for _, stat_name in pairs(PlayerData.Statistics.metadata.display_order) do
local child = PlayerData.Statistics[stat_name]
local metadata = child.metadata
local value = metadata.stringify_short and metadata.stringify_short(0) or metadata.stringify and metadata.stringify(0) or format_number(0)
label(disp, label_width['name'], metadata.name or {'exp-statistics.'..stat_name}, metadata.tooltip or {'exp-statistics.'..stat_name..'-tooltip'})
label(disp, label_width['count'], {'readme.data-format', value, metadata.unit or ''}, metadata.value_tooltip or {'exp-statistics.'..stat_name..'-tooltip'}, stat_name)
end
for _, stat_name in pairs(PlayerData.Statistics.metadata.display_order) do
local child = PlayerData.Statistics[stat_name]
local metadata = child.metadata
local value = metadata.stringify_short and metadata.stringify_short(0) or metadata.stringify and metadata.stringify(0) or format_number(0)
label(disp, label_width["name"], metadata.name or { "exp-statistics." .. stat_name }, metadata.tooltip or { "exp-statistics." .. stat_name .. "-tooltip" })
label(disp, label_width["count"], { "readme.data-format", value, metadata.unit or "" }, metadata.value_tooltip or { "exp-statistics." .. stat_name .. "-tooltip" }, stat_name)
end
for stat_name, data in pairs(computed_stats) do
label(disp, label_width['name'], {'exp-statistics.'..stat_name}, {'exp-statistics.'..stat_name..'-tooltip'})
label(disp, label_width['count'], {'readme.data-format', data.default, ''}, {'exp-statistics.'..stat_name..'-tooltip'}, stat_name)
end
for stat_name, data in pairs(computed_stats) do
label(disp, label_width["name"], { "exp-statistics." .. stat_name }, { "exp-statistics." .. stat_name .. "-tooltip" })
label(disp, label_width["count"], { "readme.data-format", data.default, "" }, { "exp-statistics." .. stat_name .. "-tooltip" }, stat_name)
end
return pd_data_set
end)
return pd_data_set
end)
local function pd_update(table, player_name)
for _, stat_name in pairs(PlayerData.Statistics.metadata.display_order) do
@@ -127,79 +127,79 @@ local function pd_update(table, player_name)
else
value = format_number(value or 0)
end
table[stat_name].caption = {'readme.data-format', value, metadata.unit or ''}
table[stat_name].caption = { "readme.data-format", value, metadata.unit or "" }
end
for stat_name, data in pairs(computed_stats) do
table[stat_name].caption = {'readme.data-format', data.calculate(player_name), ''}
table[stat_name].caption = { "readme.data-format", data.calculate(player_name), "" }
end
end
local pd_username_player =
Gui.element(function(definition, parent, player_list)
return parent.add{
name = definition.name,
type = 'drop-down',
items = player_list,
selected_index = #player_list > 0 and 1
}
end)
:style{
horizontally_stretchable = true
}:on_selection_changed(function(_, element, _)
local player_name = game.connected_players[element.selected_index]
local table = element.parent.parent.parent.parent['pd_st_2'].disp.table
pd_update(table, player_name)
end)
:static_name(Gui.unique_static_name)
Gui.element(function(definition, parent, player_list)
return parent.add{
name = definition.name,
type = "drop-down",
items = player_list,
selected_index = #player_list > 0 and 1,
}
end)
:style{
horizontally_stretchable = true,
}:on_selection_changed(function(_, element, _)
local player_name = game.connected_players[element.selected_index]
local table = element.parent.parent.parent.parent["pd_st_2"].disp.table
pd_update(table, player_name)
end)
:static_name(Gui.unique_static_name)
local pd_username_update =
Gui.element{
type = 'button',
name = Gui.unique_static_name,
caption = 'update'
}:style{
width = 128
}:on_click(function(_, element, _)
local player_index = element.parent[pd_username_player.name].selected_index
Gui.element{
type = "button",
name = Gui.unique_static_name,
caption = "update",
}:style{
width = 128,
}:on_click(function(_, element, _)
local player_index = element.parent[pd_username_player.name].selected_index
if player_index > 0 then
local player_name = game.connected_players[player_index]
local table = element.parent.parent.parent.parent['pd_st_2'].disp.table
pd_update(table, player_name)
end
end)
if player_index > 0 then
local player_name = game.connected_players[player_index]
local table = element.parent.parent.parent.parent["pd_st_2"].disp.table
pd_update(table, player_name)
end
end)
local pd_username_set =
Gui.element(function(_, parent, name, player_list)
local pd_username_set = parent.add{type='flow', direction='vertical', name=name}
local disp = Gui.scroll_table(pd_username_set, label_width['total'], 2, 'disp')
Gui.element(function(_, parent, name, player_list)
local pd_username_set = parent.add{ type = "flow", direction = "vertical", name = name }
local disp = Gui.scroll_table(pd_username_set, label_width["total"], 2, "disp")
pd_username_player(disp, player_list)
pd_username_update(disp)
pd_username_player(disp, player_list)
pd_username_update(disp)
return pd_username_set
end)
return pd_username_set
end)
pd_container =
Gui.element(function(definition, parent)
local container = Gui.container(parent, definition.name, label_width['total'])
local player_list = {}
Gui.element(function(definition, parent)
local container = Gui.container(parent, definition.name, label_width["total"])
local player_list = {}
for _, player in pairs(game.connected_players) do
table.insert(player_list, player.name)
end
for _, player in pairs(game.connected_players) do
table.insert(player_list, player.name)
end
pd_username_set(container, 'pd_st_1', player_list)
pd_data_set(container, 'pd_st_2')
pd_username_set(container, "pd_st_1", player_list)
pd_data_set(container, "pd_st_2")
return container.parent
end)
:static_name(Gui.unique_static_name)
:add_to_left_flow()
return container.parent
end)
:static_name(Gui.unique_static_name)
:add_to_left_flow()
Gui.left_toolbar_button('item/power-armor-mk2', 'Player Data GUI', pd_container, function(player)
return Roles.player_allowed(player, 'gui/playerdata')
Gui.left_toolbar_button("item/power-armor-mk2", "Player Data GUI", pd_container, function(player)
return Roles.player_allowed(player, "gui/playerdata")
end)
local function gui_player_list_update()
@@ -211,7 +211,7 @@ local function gui_player_list_update()
for _, player in pairs(game.connected_players) do
local frame = Gui.get_left_element(player, pd_container)
frame.container['pd_st_1'].disp.table[pd_username_player.name].items = player_list
frame.container["pd_st_1"].disp.table[pd_username_player.name].items = player_list
end
end

View File

@@ -12,153 +12,150 @@ local precision = {
[2] = defines.flow_precision_index.one_minute,
[3] = defines.flow_precision_index.ten_minutes,
[4] = defines.flow_precision_index.one_hour,
[5] = defines.flow_precision_index.ten_hours
[5] = defines.flow_precision_index.ten_hours,
}
local font_color = {
-- positive
[1] = {r = 0.3, g = 1, b = 0.3},
[1] = { r = 0.3, g = 1, b = 0.3 },
-- negative
[2] = {r = 1, g = 0.3, b = 0.3}
[2] = { r = 1, g = 0.3, b = 0.3 },
}
local function format_n(n)
local _i, _j, m, i, f = string.format('%.1f', n):find('([-]?)(%d+)([.]?%d*)')
i = i:reverse():gsub('(%d%d%d)', '%1,')
local _i, _j, m, i, f = tostring(n):find("([-]?)(%d+)([.]?%d*)")
i = i:reverse():gsub("(%d%d%d)", "%1,")
if f ~= '' then
return m .. i:reverse():gsub('^,', '') .. f
if f ~= "" then
return m .. i:reverse():gsub("^,", "") .. f
else
return m .. i:reverse():gsub('^,', '') .. '.0'
return m .. i:reverse():gsub("^,", "") .. ".0"
end
end
--- Display group
-- @element production_data_group
local production_data_group =
Gui.element(function(_definition, parent, i)
local item
Gui.element(function(_definition, parent, i)
local item
if i == 0 then
item = parent.add{
type = 'drop-down',
name = 'production_0_e',
items = {'5s', '1m', '10m', '1h', '10h'},
selected_index = 3
if i == 0 then
item = parent.add{
type = "drop-down",
name = "production_0_e",
items = { "5s", "1m", "10m", "1h", "10h" },
selected_index = 3,
}
item.style.width = 80
else
item = parent.add{
type = "choose-elem-button",
name = "production_" .. i .. "_e",
elem_type = "item",
style = "slot_button",
}
item.style.height = 32
item.style.width = 32
end
local data_1 = parent.add{
type = "label",
name = "production_" .. i .. "_1",
caption = "0.0",
style = "heading_2_label",
}
item.style.width = 80
data_1.style.width = 90
data_1.style.horizontal_align = "right"
data_1.style.font_color = font_color[1]
else
item = parent.add{
type = 'choose-elem-button',
name = 'production_' .. i .. '_e',
elem_type = 'item',
style = 'slot_button'
local data_2 = parent.add{
type = "label",
name = "production_" .. i .. "_2",
caption = "0.0",
style = "heading_2_label",
}
item.style.height = 32
item.style.width = 32
end
data_2.style.width = 90
data_2.style.horizontal_align = "right"
data_2.style.font_color = font_color[2]
local data_1 = parent.add{
type = 'label',
name = 'production_' .. i .. '_1',
caption = '0.0',
style = 'heading_2_label'
}
data_1.style.width = 90
data_1.style.horizontal_align = 'right'
data_1.style.font_color = font_color[1]
local data_3 = parent.add{
type = "label",
name = "production_" .. i .. "_3",
caption = "0.0",
style = "heading_2_label",
}
data_3.style.width = 90
data_3.style.horizontal_align = "right"
data_3.style.font_color = font_color[1]
local data_2 = parent.add{
type = 'label',
name = 'production_' .. i .. '_2',
caption = '0.0',
style = 'heading_2_label'
}
data_2.style.width = 90
data_2.style.horizontal_align = 'right'
data_2.style.font_color = font_color[2]
local data_3 = parent.add{
type = 'label',
name = 'production_' .. i .. '_3',
caption = '0.0',
style = 'heading_2_label'
}
data_3.style.width = 90
data_3.style.horizontal_align = 'right'
data_3.style.font_color = font_color[1]
return item
end)
return item
end)
--- A vertical flow containing all the production data
-- @element production_data_set
local production_data_set =
Gui.element(function(_, parent, name)
local production_set = parent.add{type='flow', direction='vertical', name=name}
local disp = Gui.scroll_table(production_set, 350, 4, 'disp')
Gui.element(function(_, parent, name)
local production_set = parent.add{ type = "flow", direction = "vertical", name = name }
local disp = Gui.scroll_table(production_set, 350, 4, "disp")
production_data_group(disp, 0)
production_data_group(disp, 0)
disp['production_0_1'].caption = {'production.label-prod'}
disp['production_0_2'].caption = {'production.label-con'}
disp['production_0_3'].caption = {'production.label-bal'}
disp["production_0_1"].caption = { "production.label-prod" }
disp["production_0_2"].caption = { "production.label-con" }
disp["production_0_3"].caption = { "production.label-bal" }
for i=1, 8 do
production_data_group(disp, i)
end
for i = 1, 8 do
production_data_group(disp, i)
end
return production_set
end)
return production_set
end)
production_container =
Gui.element(function(definition, parent)
local container = Gui.container(parent, definition.name, 350)
Gui.element(function(definition, parent)
local container = Gui.container(parent, definition.name, 350)
production_data_set(container, 'production_st')
production_data_set(container, "production_st")
return container.parent
end)
:static_name(Gui.unique_static_name)
:add_to_left_flow()
return container.parent
end)
:static_name(Gui.unique_static_name)
:add_to_left_flow()
Gui.left_toolbar_button('entity/assembling-machine-3', {'production.main-tooltip'}, production_container, function(player)
return Roles.player_allowed(player, 'gui/production')
Gui.left_toolbar_button("entity/assembling-machine-3", { "production.main-tooltip" }, production_container, function(player)
return Roles.player_allowed(player, "gui/production")
end)
Event.on_nth_tick(60, function()
for _, player in pairs(game.connected_players) do
local frame = Gui.get_left_element(player, production_container)
local stat = player.force.get_item_production_statistics(player.surface)
local precision_value = precision[frame.container['production_st'].disp.table['production_0_e'].selected_index]
local table = frame.container['production_st'].disp.table
local precision_value = precision[frame.container["production_st"].disp.table["production_0_e"].selected_index]
local table = frame.container["production_st"].disp.table
for i=1, 8 do
local production_prefix = 'production_' .. i
local item = table[production_prefix .. '_e'].elem_value
for i = 1, 8 do
local production_prefix = "production_" .. i
local item = table[production_prefix .. "_e"].elem_value
if item then
local add = math.floor(stat.get_flow_count{name=item, category="input", precision_index=precision_value, count=false} / 6) / 10
local minus = math.floor(stat.get_flow_count{name=item, category="output", precision_index=precision_value, count=false} / 6) / 10
local add = math.floor(stat.get_flow_count{ name = item, category = "input", precision_index = precision_value, count = false } / 6) / 10
local minus = math.floor(stat.get_flow_count{ name = item, category = "output", precision_index = precision_value, count = false } / 6) / 10
local sum = add - minus
table[production_prefix .. '_1'].caption = format_n(add)
table[production_prefix .. '_2'].caption = format_n(minus)
table[production_prefix .. '_3'].caption = format_n(sum)
table[production_prefix .. "_1"].caption = format_n(add)
table[production_prefix .. "_2"].caption = format_n(minus)
table[production_prefix .. "_3"].caption = format_n(sum)
if sum < 0 then
table[production_prefix .. '_3'].style.font_color = font_color[2]
table[production_prefix .. "_3"].style.font_color = font_color[2]
else
table[production_prefix .. '_3'].style.font_color = font_color[1]
table[production_prefix .. "_3"].style.font_color = font_color[1]
end
else
table[production_prefix .. '_1'].caption = '0.0'
table[production_prefix .. '_2'].caption = '0.0'
table[production_prefix .. '_3'].caption = '0.0'
table[production_prefix .. '_3'].style.font_color = font_color[1]
table[production_prefix .. "_1"].caption = "0.0"
table[production_prefix .. "_2"].caption = "0.0"
table[production_prefix .. "_3"].caption = "0.0"
table[production_prefix .. "_3"].style.font_color = font_color[1]
end
end
end

View File

@@ -15,7 +15,7 @@ local format_number = require("util").format_number --- @dep util
local tabs = {}
local function Tab(caption, tooltip, element_define)
tabs[#tabs+1] = {caption, tooltip, element_define}
tabs[#tabs + 1] = { caption, tooltip, element_define }
end
local frame_width = 595 -- controls width of top descriptions
@@ -25,441 +25,445 @@ local scroll_height = 275 -- controls the height of the scrolls
--- Sub content area used within the content areas
-- @element sub_content
local sub_content =
Gui.element{
type = 'frame',
direction = 'vertical',
style = 'inside_deep_frame'
}
:style{
horizontally_stretchable = true,
horizontal_align = 'center',
padding = {2, 2},
top_margin = 2
}
Gui.element{
type = "frame",
direction = "vertical",
style = "inside_deep_frame",
}
:style{
horizontally_stretchable = true,
horizontal_align = "center",
padding = { 2, 2 },
top_margin = 2,
}
--- Table which has a title above it above it
-- @element title_table
local title_table =
Gui.element(function(_, parent, bar_size, caption, column_count)
Gui.title_label(parent, bar_size, caption)
Gui.element(function(_, parent, bar_size, caption, column_count)
Gui.title_label(parent, bar_size, caption)
return parent.add{
type = 'table',
column_count = column_count,
style = 'bordered_table'
return parent.add{
type = "table",
column_count = column_count,
style = "bordered_table",
}
end)
:style{
padding = 0,
cell_padding = 0,
vertical_align = "center",
horizontally_stretchable = true,
}
end)
:style{
padding = 0,
cell_padding = 0,
vertical_align = 'center',
horizontally_stretchable = true
}
--- Scroll to be used with Gui.title_label tables
-- @element title_table_scroll
local title_table_scroll =
Gui.element{
type = 'scroll-pane',
direction = 'vertical',
horizontal_scroll_policy = 'never',
vertical_scroll_policy = 'auto',
style = 'scroll_pane_under_subheader'
}
:style{
padding = {1, 3},
maximal_height = scroll_height,
horizontally_stretchable = true,
}
Gui.element{
type = "scroll-pane",
direction = "vertical",
horizontal_scroll_policy = "never",
vertical_scroll_policy = "auto",
style = "scroll_pane_under_subheader",
}
:style{
padding = { 1, 3 },
maximal_height = scroll_height,
horizontally_stretchable = true,
}
--- Used to connect to servers in server list
-- @element join_server
local join_server =
Gui.element(function(_, parent, server_id, wrong_version)
local status = External.get_server_status(server_id) or 'Offline'
if wrong_version then status = 'Version' end
local flow = parent.add{ name = server_id, type = 'flow' }
local button = flow.add{
type = 'sprite-button',
sprite = 'utility/circuit_network_panel',
hovered_sprite = 'utility/circuit_network_panel',
tooltip = {'readme.servers-connect-'..status, wrong_version},
style = "frame_action_button"
}
Gui.element(function(_, parent, server_id, wrong_version)
local status = External.get_server_status(server_id) or "Offline"
if wrong_version then status = "Version" end
local flow = parent.add{ name = server_id, type = "flow" }
local button = flow.add{
type = "sprite-button",
sprite = "utility/circuit_network_panel",
hovered_sprite = "utility/circuit_network_panel",
tooltip = { "readme.servers-connect-" .. status, wrong_version },
style = "frame_action_button",
}
if status == 'Offline' or status == 'Current' then
button.enabled = false
button.sprite = 'utility/circuit_network_panel'
elseif status == 'Version' then
button.enabled = false
button.sprite = 'utility/shuffle'
elseif status == 'Password' then
button.sprite = 'utility/warning_white'
button.hovered_sprite = 'utility/warning'
elseif status == 'Modded' then
button.sprite = 'utility/downloading_white'
button.hovered_sprite = 'utility/downloading'
end
if status == "Offline" or status == "Current" then
button.enabled = false
button.sprite = "utility/circuit_network_panel"
elseif status == "Version" then
button.enabled = false
button.sprite = "utility/shuffle"
elseif status == "Password" then
button.sprite = "utility/warning_white"
button.hovered_sprite = "utility/warning"
elseif status == "Modded" then
button.sprite = "utility/downloading_white"
button.hovered_sprite = "utility/downloading"
end
return button
end)
:style(Gui.sprite_style(20, -1))
:on_click(function(player, element, _)
local server_id = element.parent.name
External.request_connection(player, server_id, true)
end)
return button
end)
:style(Gui.sprite_style(20, -1))
:on_click(function(player, element, _)
local server_id = element.parent.name
External.request_connection(player, server_id, true)
end)
--- Content area for the welcome tab
-- @element welcome_content
Tab({'readme.welcome-tab'}, {'readme.welcome-tooltip'},
Gui.element(function(_, parent)
local server_details = { name='ExpGaming S0 - Local', welcome='Failed to load description: disconnected from external api.', reset_time='Non Set', branch='Unknown'}
if External.valid() then server_details = External.get_current_server() end
local container = parent.add{ type='flow', direction='vertical' }
local player = Gui.get_player_from_element(parent)
Tab({ "readme.welcome-tab" }, { "readme.welcome-tooltip" },
Gui.element(function(_, parent)
local server_details = { name = "ExpGaming S0 - Local", welcome = "Failed to load description: disconnected from external api.", reset_time = "Non Set", branch = "Unknown" }
if External.valid() then server_details = External.get_current_server() end
local container = parent.add{ type = "flow", direction = "vertical" }
local player = Gui.get_player_from_element(parent)
-- Set up the top flow with logos
local top_flow = container.add{ type='flow' }
top_flow.add{ type='sprite', sprite='file/modules/exp_legacy/modules/gui/logo.png' }
local top_vertical_flow = top_flow.add{ type='flow', direction='vertical' }
top_flow.add{ type='sprite', sprite='file/modules/exp_legacy/modules/gui/logo.png' }
top_vertical_flow.style.horizontal_align = 'center'
-- Set up the top flow with logos
local top_flow = container.add{ type = "flow" }
top_flow.add{ type = "sprite", sprite = "file/modules/exp_legacy/modules/gui/logo.png" }
local top_vertical_flow = top_flow.add{ type = "flow", direction = "vertical" }
top_flow.add{ type = "sprite", sprite = "file/modules/exp_legacy/modules/gui/logo.png" }
top_vertical_flow.style.horizontal_align = "center"
-- Add the title and description to the top flow
Gui.title_label(top_vertical_flow, 62, 'Welcome to '..server_details.name)
Gui.centered_label(top_vertical_flow, 380, server_details.welcome)
Gui.bar(container)
-- Add the title and description to the top flow
Gui.title_label(top_vertical_flow, 62, "Welcome to " .. server_details.name)
Gui.centered_label(top_vertical_flow, 380, server_details.welcome)
Gui.bar(container)
-- Get the names of the roles the player has
local player_roles = Roles.get_player_roles(player)
local role_names = {}
for i, role in ipairs(player_roles) do
role_names[i] = role.name
end
-- Get the names of the roles the player has
local player_roles = Roles.get_player_roles(player)
local role_names = {}
for i, role in ipairs(player_roles) do
role_names[i] = role.name
end
-- Add the other information to the gui
container.add{ type='flow' }.style.height = 4
local online_time = format_time(game.tick, {days=true, hours=true, minutes=true, long=true})
Gui.centered_label(sub_content(container), frame_width, {'readme.welcome-general', server_details.reset_time, online_time})
Gui.centered_label(sub_content(container), frame_width, {'readme.welcome-roles', table.concat(role_names, ', ')})
Gui.centered_label(sub_content(container), frame_width, {'readme.welcome-chat'})
-- Add the other information to the gui
container.add{ type = "flow" }.style.height = 4
local online_time = format_time(game.tick, { days = true, hours = true, minutes = true, long = true })
Gui.centered_label(sub_content(container), frame_width, { "readme.welcome-general", server_details.reset_time, online_time })
Gui.centered_label(sub_content(container), frame_width, { "readme.welcome-roles", table.concat(role_names, ", ") })
Gui.centered_label(sub_content(container), frame_width, { "readme.welcome-chat" })
return container
end))
return container
end))
--- Content area for the rules tab
-- @element rules_content
Tab({'readme.rules-tab'}, {'readme.rules-tooltip'},
Gui.element(function(_, parent)
local container = parent.add{ type='flow', direction='vertical' }
Tab({ "readme.rules-tab" }, { "readme.rules-tooltip" },
Gui.element(function(_, parent)
local container = parent.add{ type = "flow", direction = "vertical" }
-- Add the title and description to the content
Gui.title_label(container, title_width-3, {'readme.rules-tab'})
Gui.centered_label(container, frame_width, {'readme.rules-general'})
Gui.bar(container)
container.add{ type='flow' }
-- Add the title and description to the content
Gui.title_label(container, title_width - 3, { "readme.rules-tab" })
Gui.centered_label(container, frame_width, { "readme.rules-general" })
Gui.bar(container)
container.add{ type = "flow" }
-- Add a table for the rules
local rules = Gui.scroll_table(container, scroll_height, 1)
rules.style = 'bordered_table'
rules.style.cell_padding = 4
-- Add a table for the rules
local rules = Gui.scroll_table(container, scroll_height, 1)
rules.style = "bordered_table"
rules.style.cell_padding = 4
-- Add the rules to the table
for i = 1, 15 do
Gui.centered_label(rules, 565, {'readme.rules-'..i})
end
-- Add the rules to the table
for i = 1, 15 do
Gui.centered_label(rules, 565, { "readme.rules-" .. i })
end
return container
end))
return container
end))
--- Content area for the commands tab
-- @element commands_content
Tab({'readme.commands-tab'}, {'readme.commands-tooltip'},
Gui.element(function(_, parent)
local container = parent.add{ type='flow', direction='vertical' }
local player = Gui.get_player_from_element(parent)
Tab({ "readme.commands-tab" }, { "readme.commands-tooltip" },
Gui.element(function(_, parent)
local container = parent.add{ type = "flow", direction = "vertical" }
local player = Gui.get_player_from_element(parent)
-- Add the title and description to the content
Gui.title_label(container, title_width-20, {'readme.commands-tab'})
Gui.centered_label(container, frame_width, {'readme.commands-general'})
Gui.bar(container)
container.add{ type='flow' }
-- Add the title and description to the content
Gui.title_label(container, title_width - 20, { "readme.commands-tab" })
Gui.centered_label(container, frame_width, { "readme.commands-general" })
Gui.bar(container)
container.add{ type = "flow" }
-- Add a table for the commands
local commands = Gui.scroll_table(container, scroll_height, 2)
commands.style = 'bordered_table'
commands.style.cell_padding = 0
-- Add a table for the commands
local commands = Gui.scroll_table(container, scroll_height, 2)
commands.style = "bordered_table"
commands.style.cell_padding = 0
-- Add the rules to the table
for name, command in pairs(Commands.get(player)) do
Gui.centered_label(commands, 120, name)
Gui.centered_label(commands, 450, command.help)
end
-- Add the rules to the table
for name, command in pairs(Commands.get(player)) do
Gui.centered_label(commands, 120, name)
Gui.centered_label(commands, 450, command.help)
end
return container
end))
return container
end))
--- Content area for the servers tab
-- @element servers_content
Tab({'readme.servers-tab'}, {'readme.servers-tooltip'},
Gui.element(function(_, parent)
local container = parent.add{ type='flow', direction='vertical' }
Tab({ "readme.servers-tab" }, { "readme.servers-tooltip" },
Gui.element(function(_, parent)
local container = parent.add{ type = "flow", direction = "vertical" }
-- Add the title and description to the content
Gui.title_label(container, title_width-10, {'readme.servers-tab'})
Gui.centered_label(container, frame_width, {'readme.servers-general'})
Gui.bar(container)
container.add{ type='flow' }
-- Add the title and description to the content
Gui.title_label(container, title_width - 10, { "readme.servers-tab" })
Gui.centered_label(container, frame_width, { "readme.servers-general" })
Gui.bar(container)
container.add{ type = "flow" }
-- Draw the scroll
local scroll_pane = title_table_scroll(container)
scroll_pane.style.maximal_height = scroll_height + 20 -- the text is a bit shorter
-- Draw the scroll
local scroll_pane = title_table_scroll(container)
scroll_pane.style.maximal_height = scroll_height + 20 -- the text is a bit shorter
-- Add the factorio servers
if External.valid() then
local factorio_servers = title_table(scroll_pane, 225, {'readme.servers-factorio'}, 3)
local current_version = External.get_current_server().version
for server_id, server in pairs(External.get_servers()) do
Gui.centered_label(factorio_servers, 110, server.short_name)
Gui.centered_label(factorio_servers, 436, server.description)
join_server(factorio_servers, server_id, current_version ~= server.version and server.version)
-- Add the factorio servers
if External.valid() then
local factorio_servers = title_table(scroll_pane, 225, { "readme.servers-factorio" }, 3)
local current_version = External.get_current_server().version
for server_id, server in pairs(External.get_servers()) do
Gui.centered_label(factorio_servers, 110, server.short_name)
Gui.centered_label(factorio_servers, 436, server.description)
join_server(factorio_servers, server_id, current_version ~= server.version and server.version)
end
else
local factorio_servers = title_table(scroll_pane, 225, { "readme.servers-factorio" }, 2)
for i = 1, 8 do
Gui.centered_label(factorio_servers, 110, { "readme.servers-" .. i })
Gui.centered_label(factorio_servers, 460, { "readme.servers-d" .. i })
end
end
else
local factorio_servers = title_table(scroll_pane, 225, {'readme.servers-factorio'}, 2)
for i = 1, 8 do
Gui.centered_label(factorio_servers, 110, {'readme.servers-'..i})
Gui.centered_label(factorio_servers, 460, {'readme.servers-d'..i})
-- Add the external links
local external_links = title_table(scroll_pane, 235, { "readme.servers-external" }, 2)
for _, key in ipairs{ "discord", "website", "patreon", "status", "github" } do
local upper_key = key:gsub("^%l", string.upper)
Gui.centered_label(external_links, 110, upper_key)
Gui.centered_label(external_links, 460, { "links." .. key }, { "readme.servers-open-in-browser" })
end
end
-- Add the external links
local external_links = title_table(scroll_pane, 235, {'readme.servers-external'}, 2)
for _, key in ipairs{'discord', 'website', 'patreon', 'status', 'github'} do
local upper_key = key:gsub("^%l", string.upper)
Gui.centered_label(external_links, 110, upper_key)
Gui.centered_label(external_links, 460, {'links.'..key}, {'readme.servers-open-in-browser'})
end
return container
end))
return container
end))
--- Content area for the servers tab
-- @element backers_content
Tab({'readme.backers-tab'}, {'readme.backers-tooltip'},
Gui.element(function(_, parent)
local container = parent.add{ type='flow', direction='vertical' }
Tab({ "readme.backers-tab" }, { "readme.backers-tooltip" },
Gui.element(function(_, parent)
local container = parent.add{ type = "flow", direction = "vertical" }
-- Add the title and description to the content
Gui.title_label(container, title_width-10, {'readme.backers-tab'})
Gui.centered_label(container, frame_width, {'readme.backers-general'})
Gui.bar(container)
container.add{ type='flow' }
-- Add the title and description to the content
Gui.title_label(container, title_width - 10, { "readme.backers-tab" })
Gui.centered_label(container, frame_width, { "readme.backers-general" })
Gui.bar(container)
container.add{ type = "flow" }
-- Find which players will go where
local done = {}
local groups = {
{ _roles={'Senior Administrator', 'Administrator'}, _title={'readme.backers-management'}, _width=230 },
{ _roles={'Board Member', 'Senior Backer'}, _title={'readme.backers-board'}, _width=145 }, -- change role to board
{ _roles={'Sponsor', 'Supporter'}, _title={'readme.backers-backers'}, _width=196 }, -- change to backer
{ _roles={'Moderator', 'Trainee'}, _title={'readme.backers-staff'}, _width=235 },
{ _roles={}, _time=3*3600*60, _title={'readme.backers-active'}, _width=235 },
}
-- Find which players will go where
local done = {}
local groups = {
{ _roles = { "Senior Administrator", "Administrator" }, _title = { "readme.backers-management" }, _width = 230 },
{ _roles = { "Board Member", "Senior Backer" }, _title = { "readme.backers-board" }, _width = 145 }, -- change role to board
{ _roles = { "Sponsor", "Supporter" }, _title = { "readme.backers-backers" }, _width = 196 }, -- change to backer
{ _roles = { "Moderator", "Trainee" }, _title = { "readme.backers-staff" }, _width = 235 },
{ _roles = {}, _time = 3 * 3600 * 60, _title = { "readme.backers-active" }, _width = 235 },
}
-- Fill by player roles
for player_name, player_roles in pairs(Roles.config.players) do
for _, players in ipairs(groups) do
for _, role_name in pairs(players._roles) do
if table.contains(player_roles, role_name) then
done[player_name] = true
table.insert(players, player_name)
break
end
end
end
end
-- Fill by active times
for _, player in pairs(game.players) do
if not done[player.name] then
-- Fill by player roles
for player_name, player_roles in pairs(Roles.config.players) do
for _, players in ipairs(groups) do
if players._time and player.online_time > players._time then
table.insert(players, player.name)
for _, role_name in pairs(players._roles) do
if table.contains(player_roles, role_name) then
done[player_name] = true
table.insert(players, player_name)
break
end
end
end
end
end
-- Add the different tables
local scroll_pane = title_table_scroll(container)
for _, players in ipairs(groups) do
local table = title_table(scroll_pane, players._width, players._title, 4)
for _, player_name in ipairs(players) do
Gui.centered_label(table, 140, player_name)
end
if #players < 4 then
for i = 1, 4-#players do
Gui.centered_label(table, 140)
-- Fill by active times
for _, player in pairs(game.players) do
if not done[player.name] then
for _, players in ipairs(groups) do
if players._time and player.online_time > players._time then
table.insert(players, player.name)
end
end
end
end
end
return container
end))
-- Add the different tables
local scroll_pane = title_table_scroll(container)
for _, players in ipairs(groups) do
local table = title_table(scroll_pane, players._width, players._title, 4)
for _, player_name in ipairs(players) do
Gui.centered_label(table, 140, player_name)
end
if #players < 4 then
for i = 1, 4 - #players do
Gui.centered_label(table, 140)
end
end
end
return container
end))
--- Content area for the player data tab
-- @element commands_content
Tab({'readme.data-tab'}, {'readme.data-tooltip'},
Gui.element(function(_, parent)
local container = parent.add{ type='flow', direction='vertical' }
local player = Gui.get_player_from_element(parent)
local player_name = player.name
Tab({ "readme.data-tab" }, { "readme.data-tooltip" },
Gui.element(function(_, parent)
local container = parent.add{ type = "flow", direction = "vertical" }
local player = Gui.get_player_from_element(parent)
local player_name = player.name
local enum = PlayerData.PreferenceEnum
local preference = PlayerData.DataSavingPreference:get(player_name)
local preference_meta = PlayerData.DataSavingPreference.metadata
preference = enum[preference]
local enum = PlayerData.PreferenceEnum
local preference = PlayerData.DataSavingPreference:get(player_name)
local preference_meta = PlayerData.DataSavingPreference.metadata
preference = enum[preference]
-- Add the title and description to the content
Gui.title_label(container, title_width, {'readme.data-tab'})
Gui.centered_label(container, frame_width, {'readme.data-general'})
Gui.bar(container)
container.add{ type='flow' }
local scroll_pane = title_table_scroll(container)
-- Add the title and description to the content
Gui.title_label(container, title_width, { "readme.data-tab" })
Gui.centered_label(container, frame_width, { "readme.data-general" })
Gui.bar(container)
container.add{ type = "flow" }
local scroll_pane = title_table_scroll(container)
-- Add the required area
local required = title_table(scroll_pane, 250, {'readme.data-required'}, 2)
Gui.centered_label(required, 150, preference_meta.name, preference_meta.tooltip)
Gui.centered_label(required, 420, {'expcore-data.preference-'..enum[preference]}, preference_meta.value_tooltip)
-- Add the required area
local required = title_table(scroll_pane, 250, { "readme.data-required" }, 2)
Gui.centered_label(required, 150, preference_meta.name, preference_meta.tooltip)
Gui.centered_label(required, 420, { "expcore-data.preference-" .. enum[preference] }, preference_meta.value_tooltip)
for name, child in pairs(PlayerData.Required.children) do
local metadata = child.metadata
local value = child:get(player_name)
if value ~= nil or metadata.show_always then
if metadata.stringify then value = metadata.stringify(value) end
Gui.centered_label(required, 150, metadata.name or {'exp-required.'..name}, metadata.tooltip or {'exp-required.'..name..'-tooltip'})
Gui.centered_label(required, 420, tostring(value), metadata.value_tooltip or {'exp-required.'..name..'-value-tooltip'})
end
end
-- Add the settings area
if preference <= enum.Settings then
local settings = title_table(scroll_pane, 255, {'readme.data-settings'}, 2)
for name, child in pairs(PlayerData.Settings.children) do
local metadata = child.metadata
local value = child:get(player_name)
if not metadata.permission or Roles.player_allowed(player, metadata.permission) then
if metadata.stringify then value = metadata.stringify(value) end
if value == nil then value = 'None set' end
Gui.centered_label(settings, 150, metadata.name or {'exp-settings.'..name}, metadata.tooltip or {'exp-settings.'..name..'-tooltip'})
Gui.centered_label(settings, 420, tostring(value), metadata.value_tooltip or {'exp-settings.'..name..'-value-tooltip'})
end
end
end
-- Add the statistics area
if preference <= enum.Statistics then
local count = 4
local statistics = title_table(scroll_pane, 250, {'readme.data-statistics'}, 4)
for _, name in pairs(PlayerData.Statistics.metadata.display_order) do
local child = PlayerData.Statistics[name]
for name, child in pairs(PlayerData.Required.children) do
local metadata = child.metadata
local value = child:get(player_name)
if value ~= nil or metadata.show_always then
count = count - 2
if metadata.stringify then value = metadata.stringify(value)
else value = format_number(value or 0) end
Gui.centered_label(statistics, 150, metadata.name or {'exp-statistics.'..name}, metadata.tooltip or {'exp-statistics.'..name..'-tooltip'})
Gui.centered_label(statistics, 130, {'readme.data-format', value, metadata.unit or ''}, metadata.value_tooltip or {'exp-statistics.'..name..'-tooltip'})
if metadata.stringify then value = metadata.stringify(value) end
Gui.centered_label(required, 150, metadata.name or { "exp-required." .. name }, metadata.tooltip or { "exp-required." .. name .. "-tooltip" })
Gui.centered_label(required, 420, tostring(value), metadata.value_tooltip or { "exp-required." .. name .. "-value-tooltip" })
end
end
if count > 0 then for i = 1, count do Gui.centered_label(statistics, 140) end end
end
-- Add the misc area
local skip = {DataSavingPreference=true, Settings=true, Statistics=true, Required=true}
local count = 0; for _ in pairs(PlayerData.All.children) do count = count + 1 end
if preference <= enum.All and count > 4 then
local misc = title_table(scroll_pane, 232, {'readme.data-misc'}, 2)
for name, child in pairs(PlayerData.All.children) do
if not skip[name] then
-- Add the settings area
if preference <= enum.Settings then
local settings = title_table(scroll_pane, 255, { "readme.data-settings" }, 2)
for name, child in pairs(PlayerData.Settings.children) do
local metadata = child.metadata
local value = child:get(player_name)
if value ~= nil or metadata.show_always then
if not metadata.permission or Roles.player_allowed(player, metadata.permission) then
if metadata.stringify then value = metadata.stringify(value) end
Gui.centered_label(misc, 150, metadata.name or name, metadata.tooltip)
Gui.centered_label(misc, 420, tostring(value), metadata.value_tooltip)
if value == nil then value = "None set" end
Gui.centered_label(settings, 150, metadata.name or { "exp-settings." .. name }, metadata.tooltip or { "exp-settings." .. name .. "-tooltip" })
Gui.centered_label(settings, 420, tostring(value), metadata.value_tooltip or { "exp-settings." .. name .. "-value-tooltip" })
end
end
end
end
return container
end))
-- Add the statistics area
if preference <= enum.Statistics then
local count = 4
local statistics = title_table(scroll_pane, 250, { "readme.data-statistics" }, 4)
for _, name in pairs(PlayerData.Statistics.metadata.display_order) do
local child = PlayerData.Statistics[name]
local metadata = child.metadata
local value = child:get(player_name)
if value ~= nil or metadata.show_always then
count = count - 2
if metadata.stringify then
value = metadata.stringify(value)
else
value = format_number(value or 0)
end
Gui.centered_label(statistics, 150, metadata.name or { "exp-statistics." .. name }, metadata.tooltip or { "exp-statistics." .. name .. "-tooltip" })
Gui.centered_label(statistics, 130, { "readme.data-format", value, metadata.unit or "" }, metadata.value_tooltip or { "exp-statistics." .. name .. "-tooltip" })
end
end
if count > 0 then for i = 1, count do Gui.centered_label(statistics, 140) end end
end
-- Add the misc area
local skip = { DataSavingPreference = true, Settings = true, Statistics = true, Required = true }
local count = 0; for _ in pairs(PlayerData.All.children) do count = count + 1 end
if preference <= enum.All and count > 4 then
local misc = title_table(scroll_pane, 232, { "readme.data-misc" }, 2)
for name, child in pairs(PlayerData.All.children) do
if not skip[name] then
local metadata = child.metadata
local value = child:get(player_name)
if value ~= nil or metadata.show_always then
if metadata.stringify then value = metadata.stringify(value) end
Gui.centered_label(misc, 150, metadata.name or name, metadata.tooltip)
Gui.centered_label(misc, 420, tostring(value), metadata.value_tooltip)
end
end
end
end
return container
end))
--- Main readme container for the center flow
-- @element readme
local readme_toggle
local readme =
Gui.element(function(definition, parent)
local container = parent.add{
name = definition.name,
type = 'frame',
style = 'invisible_frame'
}
Gui.element(function(definition, parent)
local container = parent.add{
name = definition.name,
type = "frame",
style = "invisible_frame",
}
-- Add the left hand side of the frame back, removed because of frame_tabbed_pane style
local left_alignment = Gui.alignment(container, nil, nil, 'bottom')
left_alignment.style.padding = {32, 0,0, 0}
-- Add the left hand side of the frame back, removed because of frame_tabbed_pane style
local left_alignment = Gui.alignment(container, nil, nil, "bottom")
left_alignment.style.padding = { 32, 0, 0, 0 }
local left_side =
left_alignment.add{
type = 'frame',
style = 'character_gui_left_side'
}
left_side.style.vertically_stretchable = true
left_side.style.padding = 0
left_side.style.width = 5
local left_side =
left_alignment.add{
type = "frame",
style = "character_gui_left_side",
}
left_side.style.vertically_stretchable = true
left_side.style.padding = 0
left_side.style.width = 5
-- Add the tab pane
local tab_pane = container.add{
name = 'pane',
type = 'tabbed-pane',
style = 'frame_tabbed_pane'
}
-- Add the tab pane
local tab_pane = container.add{
name = "pane",
type = "tabbed-pane",
style = "frame_tabbed_pane",
}
-- Add the different content areas
for _, tab_details in ipairs(tabs) do
local tab = tab_pane.add{ type = 'tab', style = 'frame_tab', caption = tab_details[1], tooltip = tab_details[2] }
tab_pane.add_tab(tab, tab_details[3](tab_pane))
end
-- Add the different content areas
for _, tab_details in ipairs(tabs) do
local tab = tab_pane.add{ type = "tab", style = "frame_tab", caption = tab_details[1], tooltip = tab_details[2] }
tab_pane.add_tab(tab, tab_details[3](tab_pane))
end
return container
end)
:static_name(Gui.unique_static_name)
:on_open(function(player)
Gui.toggle_toolbar_button(player, readme_toggle, true)
end)
:on_close(function(player, element)
Gui.toggle_toolbar_button(player, readme_toggle, false)
Gui.destroy_if_valid(element)
end)
return container
end)
:static_name(Gui.unique_static_name)
:on_open(function(player)
Gui.toggle_toolbar_button(player, readme_toggle, true)
end)
:on_close(function(player, element)
Gui.toggle_toolbar_button(player, readme_toggle, false)
Gui.destroy_if_valid(element)
end)
--- Toggle button for the readme gui
-- @element readme_toggle
readme_toggle =
Gui.toolbar_button('virtual-signal/signal-info', {'readme.main-tooltip'}, function(player)
return Roles.player_allowed(player, 'gui/readme')
end)
:on_click(function(player, _)
local center = player.gui.center
if center[readme.name] then
player.opened = nil
else
player.opened = readme(center)
end
end)
Gui.toolbar_button("virtual-signal/signal-info", { "readme.main-tooltip" }, function(player)
return Roles.player_allowed(player, "gui/readme")
end)
:on_click(function(player, _)
local center = player.gui.center
if center[readme.name] then
player.opened = nil
else
player.opened = readme(center)
end
end)
--- When a player joins the game for the first time show this gui
Event.add(defines.events.on_player_created, function(event)
@@ -483,4 +487,4 @@ Event.add(defines.events.on_player_respawned, function(event)
if not player.opened then
player.gui.center.clear()
end
end)
end)

Some files were not shown because too many files have changed in this diff Show More