content stringlengths 5 1.05M |
|---|
function love.keypressed(key)
if key == "escape" or key == "q" then
love.event.quit()
elseif key == "p" or key == "space" then
if not pause then
pause = true
else
pause = false
end
elseif key == "f" then
local fullscreen = love.window.getFullscreen()
if not fullscreen then
love.window.setFullscreen(true)
else
love.window.setFullscreen(false)
end
elseif key == "z" then
scale = 1
bubbleScale = scale
elseif key == "x" then
scale = 0.1
bubbleScale = scale
elseif key == "c" then
scale = 0.02
bubbleScale = scale
elseif key == "v" then
scale = 0.01
bubbleScale = 0.01
elseif key == "b" then
timeScale = 2
elseif key == "n" then
timeScale = 10
elseif key == "m" then
timeScale = 20
elseif key == "e" then
if autoExplore then
autoExplore = false
else
autoExplore = true
end
elseif key == "r" then
pos = {x = 0, y = 0}
end
end
function continuous_controls(dt)
if love.keyboard.isDown("left", "a") then
pos.x = pos.x - speed * dt / scale
end
if love.keyboard.isDown("right","d") then
pos.x = pos.x + speed * dt / scale
end
if love.keyboard.isDown("up","w") then
pos.y = pos.y + speed * dt / scale
end
if love.keyboard.isDown("down","s") then
pos.y = pos.y - speed * dt / scale
end
end
|
Ext.Require("BootstrapShared.lua")
Ext.Require("Server/_InitServer.lua")
|
object_tangible_tcg_series6_shared_painting_nightsister = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/tcg/series6/shared_painting_nightsister.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_tcg_series6_shared_painting_nightsister, "object/tangible/tcg/series6/shared_painting_nightsister.iff")
object_tangible_tcg_series6_shared_painting_winged_quenker = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/tcg/series6/shared_painting_winged_quenker.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_tcg_series6_shared_painting_winged_quenker, "object/tangible/tcg/series6/shared_painting_winged_quenker.iff")
object_tangible_tcg_series6_shared_painting_travel_ad_coruscant = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/tcg/series6/shared_painting_travel_ad_coruscant.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_tcg_series6_shared_painting_travel_ad_coruscant, "object/tangible/tcg/series6/shared_painting_travel_ad_coruscant.iff")
object_tangible_tcg_series6_shared_painting_spined_rancor = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/tcg/series6/shared_painting_spined_rancor.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_tcg_series6_shared_painting_spined_rancor, "object/tangible/tcg/series6/shared_painting_spined_rancor.iff")
object_tangible_tcg_series6_shared_painting_travel_ad_ord_mantell = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/tcg/series6/shared_painting_travel_ad_ord_mantell.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_tcg_series6_shared_painting_travel_ad_ord_mantell, "object/tangible/tcg/series6/shared_painting_travel_ad_ord_mantell.iff")
|
local TXT = Localize{
[0] = " ",
[1] = "Door",
[2] = "Leave the Cave",
[3] = "Chest",
[4] = "Button",
[5] = "Lever",
[6] = "Vault",
[7] = "Cabinet",
[8] = "Switch",
[9] = "",
[10] = "Bookcase",
[11] = "",
[12] = "Strange Torch",
[13] = "The exit is sealed!",
[14] = "You Successfully disarm the trap",
[15] = "The chest is locked",
[16] = "Take a Drink",
[17] = "Not Very Refreshing",
[18] = "Refreshing",
}
table.copy(TXT, evt.str, true)
Game.MapEvtLines:RemoveEvent(1)
evt.map[1] = function() -- function events.LoadMap()
if not evt.Cmp{"QBits", Value = 815} then -- Reward
if not evt.Cmp{"QBits", Value = 814} then -- Small House only Once
if evt.Cmp{"QBits", Value = 611} then -- Chose the path of Light
evt.Set{"QBits", Value = 814} -- Small House only Once
evt.SummonMonsters{TypeIndexInMapStats = 3, Level = 3, Count = 10, X = 3, Y = 3042, Z = 0, -- ERROR: Not found
NPCGroup = 1587, unk = 0}
evt.SummonMonsters{TypeIndexInMapStats = 3, Level = 2, Count = 10, X = 718, Y = 2956, Z = 0, -- ERROR: Not found
NPCGroup = 1587, unk = 0}
evt.SummonMonsters{TypeIndexInMapStats = 3, Level = 2, Count = 10, X = -646, Y = 2889, Z = 0, -- ERROR: Not found
NPCGroup = 1587, unk = 0}
evt.SummonMonsters{TypeIndexInMapStats = 3, Level = 1, Count = 10, X = 0, Y = 3500, Z = 0, -- ERROR: Not found
NPCGroup = 1587, unk = 0}
evt.SummonMonsters{TypeIndexInMapStats = 3, Level = 3, Count = 10, X = -31, Y = 1900, Z = 0, -- ERROR: Not found
NPCGroup = 1587, unk = 0}
evt.SummonMonsters{TypeIndexInMapStats = 3, Level = 2, Count = 10, X = 597, Y = 1900, Z = 0, -- ERROR: Not found
NPCGroup = 1587, unk = 0}
evt.SummonMonsters{TypeIndexInMapStats = 3, Level = 1, Count = 10, X = -624, Y = 1900, Z = 0, -- ERROR: Not found
NPCGroup = 1587, unk = 0}
evt.SpeakNPC{NPC = 762} -- "Maximus"
else
if evt.Cmp{"QBits", Value = 612} then -- Chose the path of Dark
evt.Set{"QBits", Value = 814} -- Small House only Once
evt.SummonMonsters{TypeIndexInMapStats = 2, Level = 3, Count = 10, X = 3, Y = 3042, Z = 0, -- ERROR: Not found
NPCGroup = 1587, unk = 0}
evt.SummonMonsters{TypeIndexInMapStats = 2, Level = 2, Count = 10, X = 718, Y = 2956, Z = 0, -- ERROR: Not found
NPCGroup = 1587, unk = 0}
evt.SummonMonsters{TypeIndexInMapStats = 2, Level = 2, Count = 10, X = -646, Y = 2889, Z = 0, -- ERROR: Not found
NPCGroup = 1587, unk = 0}
evt.SummonMonsters{TypeIndexInMapStats = 2, Level = 1, Count = 10, X = 0, Y = 3500, Z = 0, -- ERROR: Not found
NPCGroup = 1587, unk = 0}
evt.SummonMonsters{TypeIndexInMapStats = 2, Level = 3, Count = 10, X = -31, Y = 1900, Z = 0, -- ERROR: Not found
NPCGroup = 1587, unk = 0}
evt.SummonMonsters{TypeIndexInMapStats = 2, Level = 2, Count = 10, X = 597, Y = 1900, Z = 0, -- ERROR: Not found
NPCGroup = 1587, unk = 0}
evt.SummonMonsters{TypeIndexInMapStats = 2, Level = 1, Count = 10, X = -624, Y = 1900, Z = 0, -- ERROR: Not found
NPCGroup = 1587, unk = 0}
evt.SpeakNPC{NPC = 724} -- "Sir Carneghem"
end
end
end
end
end
events.LoadMap = evt.map[1].last
Game.MapEvtLines:RemoveEvent(2)
evt.map[2] = function()
if evt.CheckMonstersKilled{CheckType = 3, Id = 0, Count = 0} then
evt.Set{"QBits", Value = 630} -- Killed Good MM3 Person
else
if evt.CheckMonstersKilled{CheckType = 3, Id = 1, Count = 0} then
evt.Set{"QBits", Value = 631} -- Killed Evil MM3 Person
end
end
evt.Add{"QBits", Value = 746} -- Control Cube - I lost it
end
evt.hint[5] = evt.str[12] -- "Strange Torch"
Game.MapEvtLines:RemoveEvent(5)
evt.map[5] = function()
evt.MoveToMap{X = 0, Y = 0, Z = 0, Direction = 512, LookAngle = 0, SpeedZ = 0, HouseId = 0, Icon = 0, Name = "7nwc.blv"}
end
evt.hint[176] = evt.str[3] -- "Chest"
Game.MapEvtLines:RemoveEvent(176)
evt.map[176] = function()
if evt.Cmp{"QBits", Value = 815} then -- Reward
evt.OpenChest{Id = 1}
else
evt.StatusText{Str = 15} -- "The chest is locked"
end
end
evt.hint[177] = evt.str[1] -- "Door"
Game.MapEvtLines:RemoveEvent(177)
evt.map[177] = function()
evt.OpenChest{Id = 2}
end
evt.hint[178] = evt.str[1] -- "Door"
Game.MapEvtLines:RemoveEvent(178)
evt.map[178] = function()
evt.OpenChest{Id = 3}
end
evt.hint[179] = evt.str[1] -- "Door"
Game.MapEvtLines:RemoveEvent(179)
evt.map[179] = function()
evt.OpenChest{Id = 4}
end
evt.hint[180] = evt.str[1] -- "Door"
Game.MapEvtLines:RemoveEvent(180)
evt.map[180] = function()
evt.OpenChest{Id = 5}
end
evt.hint[181] = evt.str[1] -- "Door"
Game.MapEvtLines:RemoveEvent(181)
evt.map[181] = function()
evt.OpenChest{Id = 6}
end
evt.hint[182] = evt.str[1] -- "Door"
Game.MapEvtLines:RemoveEvent(182)
evt.map[182] = function()
evt.OpenChest{Id = 7}
end
evt.hint[183] = evt.str[1] -- "Door"
Game.MapEvtLines:RemoveEvent(183)
evt.map[183] = function()
evt.OpenChest{Id = 8}
end
evt.hint[184] = evt.str[1] -- "Door"
Game.MapEvtLines:RemoveEvent(184)
evt.map[184] = function()
evt.OpenChest{Id = 9}
end
evt.hint[185] = evt.str[1] -- "Door"
Game.MapEvtLines:RemoveEvent(185)
evt.map[185] = function()
evt.OpenChest{Id = 10}
end
evt.hint[186] = evt.str[1] -- "Door"
Game.MapEvtLines:RemoveEvent(186)
evt.map[186] = function()
evt.OpenChest{Id = 11}
end
evt.hint[187] = evt.str[1] -- "Door"
Game.MapEvtLines:RemoveEvent(187)
evt.map[187] = function()
evt.OpenChest{Id = 12}
end
evt.hint[188] = evt.str[1] -- "Door"
Game.MapEvtLines:RemoveEvent(188)
evt.map[188] = function()
evt.OpenChest{Id = 13}
end
evt.hint[189] = evt.str[1] -- "Door"
Game.MapEvtLines:RemoveEvent(189)
evt.map[189] = function()
evt.OpenChest{Id = 14}
end
evt.hint[190] = evt.str[1] -- "Door"
Game.MapEvtLines:RemoveEvent(190)
evt.map[190] = function()
evt.OpenChest{Id = 15}
end
evt.hint[191] = evt.str[1] -- "Door"
Game.MapEvtLines:RemoveEvent(191)
evt.map[191] = function()
evt.OpenChest{Id = 16}
end
evt.hint[192] = evt.str[1] -- "Door"
Game.MapEvtLines:RemoveEvent(192)
evt.map[192] = function()
evt.OpenChest{Id = 17}
end
evt.hint[193] = evt.str[1] -- "Door"
Game.MapEvtLines:RemoveEvent(193)
evt.map[193] = function()
evt.OpenChest{Id = 18}
end
evt.hint[194] = evt.str[1] -- "Door"
Game.MapEvtLines:RemoveEvent(194)
evt.map[194] = function()
evt.OpenChest{Id = 19}
end
evt.hint[195] = evt.str[1] -- "Door"
Game.MapEvtLines:RemoveEvent(195)
evt.map[195] = function()
if evt.Cmp{"QBits", Value = 815} then -- Reward
evt.OpenChest{Id = 0}
else
evt.StatusText{Str = 15} -- "The chest is locked"
end
end
Game.MapEvtLines:RemoveEvent(501)
evt.map[501] = function()
evt.StatusText{Str = 13} -- "The exit is sealed!"
end
Game.MapEvtLines:RemoveEvent(502)
evt.map[502] = function()
if not evt.Cmp{"QBits", Value = 879} then -- 0
evt.MoveNPC{NPC = 424, HouseId = 1071} -- "Maximus" -> "Hostel"
evt.SetNPCTopic{NPC = 424, Index = 0, Event = 0} -- "Maximus"
evt.SetNPCTopic{NPC = 424, Index = 1, Event = 878} -- "Maximus" : "Congratulations!"
evt.Set{"QBits", Value = 879} -- 0
end
evt.MoveToMap{X = -7745, Y = -6673, Z = 65, Direction = 2047, LookAngle = 0, SpeedZ = 0, HouseId = 0, Icon = 8, Name = "7D26.blv"}
end
|
require('mobdebug').start()
waxClass{"TestDebugVC"}
function viewDidLoad(self)
self:ORIGviewDidLoad();
print(self:memberString())
print(self:memberDict())
self:setMemberString("123")
self:setMemberDict({key1="value1", key2="value2"})
end
function aButtonPress(self, sender)
print("lua aButtonPress")
print(sender)
self:aAction(self:memberString())
end
function aAction(self, a)
print("lua aAction")
print(a)
self:bAction(self:memberDict())
end
function bAction(self, b)
print("lua aAction")
print(b)
for k, v in pairs(b) do
print("k=", k, " v=", v)
end
self:cAction("test")
end
function cAction(self, c)
print("lua cAction")
end |
local github = require("cmp_git.github")
local gitlab = require("cmp_git.gitlab")
local utils = require("cmp_git.utils")
local Source = {
cache_issues = {},
cache_mentions = {},
cache_merge_requests = {},
config = {},
filetypes = {},
}
Source.new = function(overrides)
local self = setmetatable({}, {
__index = Source,
})
self.config = vim.tbl_extend("force", require("cmp_git.config"), overrides or {})
for _, item in ipairs(self.config.filetypes) do
self.filetypes[item] = true
end
self.trigger_characters = { "#", "@", "!" }
self.trigger_characters_str = table.concat(self.trigger_characters, "")
self.keyword_pattern = string.format("[%s]\\S*", self.trigger_characters_str)
return self
end
function Source:complete(params, callback)
local bufnr = vim.api.nvim_get_current_buf()
local trigger_character = nil
if params.completion_context.triggerKind == 1 then
trigger_character = string.match(
params.context.cursor_before_line,
"%s*([" .. self.trigger_characters_str .. "])%S*$"
)
elseif params.completion_context.triggerKind == 2 then
trigger_character = params.completion_context.triggerCharacter
end
if trigger_character == "#" then
if not self.cache_issues[bufnr] then
local git_info = utils.get_git_info()
if
self.config.github
and self.config.github.issues
and git_info.host == "github.com"
and git_info.owner ~= nil
and git_info.repo ~= nil
then
github.get_issues(self, callback, bufnr, git_info)
elseif
self.config.gitlab
and self.config.gitlab.issues
and git_info.host ~= nil
and git_info.owner ~= nil
and git_info.repo ~= nil
then
gitlab.get_issues(self, callback, bufnr, git_info)
else
callback({ items = {}, isIncomplete = false })
self.cache_issues[bufnr] = {}
end
else
callback({ items = self.cache_issues[bufnr], isIncomplete = false })
end
elseif trigger_character == "@" then
if not self.cache_mentions[bufnr] then
local git_info = utils.get_git_info()
if
self.config.github
and self.config.github.mentions
and git_info.host == "github.com"
and git_info.owner ~= nil
and git_info.repo ~= nil
then
github.get_mentions(self, callback, bufnr, git_info)
elseif
self.config.gitlab
and self.config.gitlab.mentions
and git_info.host ~= nil
and git_info.owner ~= nil
and git_info.repo ~= nil
then
gitlab.get_mentions(self, callback, bufnr, git_info)
else
callback({ items = {}, isIncomplete = false })
self.cache_mentions[bufnr] = {}
end
else
callback({ items = self.cache_mentions[bufnr], isIncomplete = false })
end
elseif trigger_character == "!" then
if not self.cache_merge_requests[bufnr] then
local git_info = utils.get_git_info()
if
self.config.gitlab
and self.config.gitlab.mentions
and git_info.host ~= "github.com"
and git_info.owner ~= nil
and git_info.repo ~= nil
then
gitlab.get_merge_requests(self, callback, bufnr, git_info)
end
else
callback({ items = self.cache_merge_requests[bufnr], isIncomplete = false })
end
end
end
function Source:get_keyword_pattern()
return self.keyword_pattern
end
function Source:get_trigger_characters()
return self.trigger_characters
end
function Source:get_debug_name()
return "cmp_git"
end
function Source:is_available()
return self.filetypes["*"] ~= nil or self.filetypes[vim.bo.filetype] ~= nil
end
return Source
|
#!/usr/bin/env lua
local ts = tostring
io.write ([[
function allocate_integer
(parent : widget_access_t;
bar_type : type_t;
flags : flags_t;
min : agar.core.types.integer_access_t;
max : agar.core.types.integer_access_t;
visible : agar.core.types.integer_access_t) return scrollbar_access_t;
pragma import (c, allocate_integer, "AG_ScrollbarNewInt");
function allocate_unsigned
(parent : widget_access_t;
bar_type : type_t;
flags : flags_t;
min : agar.core.types.unsigned_access_t;
max : agar.core.types.unsigned_access_t;
visible : agar.core.types.unsigned_access_t) return scrollbar_access_t;
pragma import (c, allocate_unsigned, "AG_ScrollbarNewUint");
function allocate_float
(parent : widget_access_t;
bar_type : type_t;
flags : flags_t;
min : agar.core.types.float_access_t;
max : agar.core.types.float_access_t;
visible : agar.core.types.float_access_t) return scrollbar_access_t;
pragma import (c, allocate_float, "AG_ScrollbarNewFloat");
function allocate_double
(parent : widget_access_t;
bar_type : type_t;
flags : flags_t;
min : agar.core.types.double_access_t;
max : agar.core.types.double_access_t;
visible : agar.core.types.double_access_t) return scrollbar_access_t;
pragma import (c, allocate_double, "AG_ScrollbarNewDouble");
]])
for _, value in pairs ({8, 16, 32, 64}) do
io.write ([[
function allocate_uint]] .. ts (value) .. [[
(parent : widget_access_t;
bar_type : type_t;
flags : flags_t;
value : agar.core.types.uint]] .. ts (value) ..[[_access_t;
min : agar.core.types.uint]] .. ts (value) ..[[_access_t;
max : agar.core.types.uint]] .. ts (value) ..[[_access_t;
visible : agar.core.types.uint]] .. ts (value) ..[[_access_t) return scrollbar_access_t;
pragma import (c, allocate_uint]] .. ts (value) .. [[, "AG_ScrollbarNewUint]] .. ts (value) .. [[");
function allocate_int]] .. ts (value) .. [[
(parent : widget_access_t;
bar_type : type_t;
flags : flags_t;
value : agar.core.types.int]] .. ts (value) ..[[_access_t;
min : agar.core.types.int]] .. ts (value) ..[[_access_t;
max : agar.core.types.int]] .. ts (value) ..[[_access_t;
visible : agar.core.types.int]] .. ts (value) ..[[_access_t) return scrollbar_access_t;
pragma import (c, allocate_int]] .. ts (value) .. [[, "AG_ScrollbarNewSint]] .. ts (value) .. [[");
]])
end
|
local lsp_selection_range = require('lsp-selection-range')
local client_module = require('lsp-selection-range.client')
local Range = require('lsp-selection-range.range')
local selection = require('lsp-selection-range.selection')
local utils = require('lsp-selection-range.tests.helpers.utils')
local simple_php = require('lsp-selection-range.tests.helpers.simple-php')
local stub = require('luassert.stub')
local buf_get_clients
local function use_client(client)
buf_get_clients.returns({ client })
end
describe('update_capabilities()', function()
it('creates new capabilities including "textDocument/selectionRange" and returns them', function()
local expectedCapabilities = vim.lsp.protocol.make_client_capabilities()
expectedCapabilities.textDocument.selectionRange = { dynamicRegistration = false }
local capabilities = lsp_selection_range.update_capabilities(nil)
assert.same(expectedCapabilities, capabilities)
end)
it('updates the provided capabilities to handle "textDocument/selectionRange" and returns them', function()
local capabilities = {
textDocument = {
hover = {
dynamicRegistration = false,
},
},
workspace = {
applyEdit = true,
},
}
local expectedCapabilities = vim.deepcopy(capabilities)
expectedCapabilities.textDocument.selectionRange = { dynamicRegistration = false }
capabilities = lsp_selection_range.update_capabilities(capabilities)
assert.same(expectedCapabilities, capabilities)
end)
end)
describe('trigger()', function()
before_each(function()
buf_get_clients = stub(vim.lsp, 'buf_get_clients')
vim.cmd('edit ' .. simple_php.file_path)
use_client(nil)
end)
after_each(function()
buf_get_clients:revert()
vim.cmd('bdelete!')
end)
it('preserves current visual selection when no client provide selection ranges', function()
local visual_range = Range.from_table(simple_php.selection_ranges.from_last_return.variable.range)
selection.select(visual_range)
lsp_selection_range.trigger()
assert.same(visual_range, selection.current())
end)
it('selects the first range returned by the client', function()
local expected_visual_range = Range.from_table(simple_php.selection_ranges.from_last_return.variable.range)
use_client(simple_php.get_client())
utils.move_cursor_to(simple_php.positions.on_last_return_var)
lsp_selection_range.trigger()
assert.same(expected_visual_range, selection.current())
end)
end)
describe('expand()', function()
before_each(function()
buf_get_clients = stub(vim.lsp, 'buf_get_clients')
vim.cmd('edit ' .. simple_php.file_path)
use_client(simple_php.get_client())
end)
after_each(function()
buf_get_clients:revert()
vim.cmd('bdelete!')
end)
it('does nothing when not in visual mode', function()
utils.move_cursor_to(simple_php.positions.on_last_return_var)
lsp_selection_range.expand()
assert.same(nil, selection.current())
end)
it('selects the parent of the current selection range when it matches the visual selection', function()
local expected_selection_range = simple_php.selection_ranges.from_last_return.return_stmt
utils.move_cursor_to(simple_php.positions.on_last_return_var)
lsp_selection_range.trigger()
lsp_selection_range.expand()
assert.same(Range.from_table(expected_selection_range.range), selection.current())
end)
it('can be chained', function()
local expected_selection_range = simple_php.selection_ranges.from_last_return.return_stmt
utils.move_cursor_to(simple_php.positions.on_last_return_var)
lsp_selection_range.trigger()
lsp_selection_range.expand()
lsp_selection_range.expand()
assert.same(Range.from_table(expected_selection_range.parent.range), selection.current())
end)
it(
'selects the first range containing the visual selection when it does not match the current selection range',
function()
local visual_range = Range.from_table(simple_php.ranges.from_if_to_last_return)
local expected_visual_range = Range.from_table(
simple_php.selection_ranges.from_last_return.function_body_without_braces.range
)
selection.select(visual_range)
lsp_selection_range.expand()
assert.same(expected_visual_range, selection.current())
end
)
end)
describe('setup', function()
after_each(function()
lsp_selection_range.setup()
end)
describe('get_client', function()
it('use defaults when not provided', function()
lsp_selection_range.setup()
assert.same(client_module.select, lsp_selection_range.get_client, 'get_client function not correctly defined')
end)
it('sets the function used to choose which client to use', function()
local custom_function = function() end
lsp_selection_range.setup({ get_client = custom_function })
assert.same(custom_function, lsp_selection_range.get_client, 'get_client function not correctly defined')
end)
end)
end)
|
local I = require("inspect")
local T = require("tools")
local lines, count = T.input(5)
local LOWER = 0
local UPPER = 1
local BYTE_F = string.byte("F", 1)
local BYTE_B = string.byte("B", 1)
local BYTE_L = string.byte("L", 1)
local BYTE_R = string.byte("R", 1)
local function convert_line(line)
local rows = {}
local cols = {}
for i = 1, 7 do
local ch = string.byte(line, i)
if ch == BYTE_F then
table.insert(rows, LOWER)
elseif ch == BYTE_B then
table.insert(rows, UPPER)
end
end
for i = 8, 10 do
local ch = string.byte(line, i)
if ch == BYTE_L then
table.insert(cols, LOWER)
elseif ch == BYTE_R then
table.insert(cols, UPPER)
end
end
return rows, cols
end
local function binary_search(items, startn, endn)
local startx, endx = startn, endn
for _, binary in ipairs(items) do
--print("Search", startx, endx)
if (endx - startx) == 1 then
if binary == LOWER then
return startx
elseif binary == UPPER then
return endx
end
end
local half = (endx - startx + 1) / 2
if binary == LOWER then
endx = startx + half - 1
elseif binary == UPPER then
startx = startx + half
end
end
return nil
end
local function exe_line(line)
local rows, cols = convert_line(line)
local row = binary_search(rows, 0, 127)
local col = binary_search(cols, 0, 7)
--print(line, row, col, I.inspect(rows), I.inspect(cols))
return (8 * row) + col
end
--print("UT", exe_line("BFFFBBFRRR"))
-- Part 1
local seat_indexes = T.map_lines(lines, exe_line)
table.sort(seat_indexes, function (a, b) return a > b end)
print("Max seat index", seat_indexes[1])
--print("All seats ids", I.inspect(seat_indexes))
-- Part 2
local last_idx = seat_indexes[1]
for _, id in ipairs(seat_indexes) do
if (id - last_idx) == -2 then
print("My seat", last_idx - 1, "between", last_idx, id)
end
last_idx = id
end
|
function onCreate()
makeLuaSprite('shade', 'shadepink', 0, 0);
setLuaSpriteScrollFactor('shade', 0, 0);
defaultCamZoom = getProperty('defaultCamZoom') - 0.01;
setProperty('shade.scale.x', 1 / defaultCamZoom);
setProperty('shade.scale.y', 1 / defaultCamZoom);
setProperty('shade.alpha', 0.0001);
addLuaSprite('shade', true);
end
-- Event notes hooks
function onEvent(name, value1, value2)
if name == "Shade" then
choose = tonumber(value2);
if (choose == 0) then
setProperty('shade.alpha', 1);
end
if (choose == 1) then
setProperty('shade.alpha', 0.0001);
end
end
end |
-- © 2016 Peter Brantsch <peter@bingo-ev.de>, see license.txt
local config = {
url = "http://www.invg.de/rt/getRealtimeData.action?stopPoint=2&station=IN-Klini&sid=273";
interval = 30;
display = {
interval = 5;
lines = 4;
columns = 20;
};
hostname = "busschild-01";
telnetport = 23;
}
return config
|
-- CSS Lang
require'lspconfig'.cssls.setup{
on_attach = require('lsp').custom_attach
}
|
--IupDialog Example in IupLua
--Creates a simple dialog.
require( "iuplua" )
vbox = iup.vbox { iup.label {title="Label"}, iup.button { title="Test" } }
dlg = iup.dialog{vbox; title="Dialog"}
dlg:show()
if (iup.MainLoopLevel()==0) then
iup.MainLoop()
end
|
-- Complete list of commands (and command aliases for Bumpercarz)
-- Type "/help <command name>" and it will show information about that command.
rconadd(aliases: "addrcon")
adminadd(aliases: "a", "addadmin")
admindel(aliases: "deladmin", "revoke", "a del", "adminrevoke", "revokeadmin")
setafk(aliases: "afk")
adminlist(aliases: "admins", "listadmins", "alist")
alias(aliases: "alias")
remotecontrol(aliases:none)
anticaps(aliases: "disablecaps", "nocaps")
chatcommands(aliases:none)
chatids(aliases: "chatid", "showplayernumbers")
crouchcamo(aliases: "tigermode", "ninja", "ninjamode")
uniquesenabled(aliases: "uniqueplayercounting")
deathless(aliases: "deathlessplayer", "deathlessmode", "cheatdeathlessplayer")
falldamage(aliases:none)
firstjoinmessage(aliases:none)
centralbanlist(aliases: "centralbansystem", "remotebansystem", "remotebanlist", "globalbansystem", "globalbanlist", "masterbansystem", "masterbanlist")
hashduplicates(aliases:none)
infiniteammo(aliases: "infammo")
killspree(aliases: "killingspree")
multiteamvehicles(aliases:none)
noweapons(aliases:none)
pmenabled(aliases: "pvtmessage", "privatemessage")
rtvenabled(aliases:none)
serveradminmessage(aliases: "samessage")
scrimmode(aliases:none)
tbagdet(aliases: "tbagdetection")
votekickenabled(aliases:none)
defaultspawnweapons(aliases: "spawnweapons", "weaponsonspawn", "chooseweapons", "selectweapons", "poontang")
welcomebackmessage(aliases: "wbmessage")
adminblocker(aliases:none)
antispam(aliases:none)
balance(aliases:none)
banpenalty(aliases:none)
ban(aliases: "hashban", "b", "playerban", "banplayer")
bos(aliases:none)
kickbansfile(aliases:none)
commandsfile(aliases:none)
adminfile(aliases:none)
sharedhashfile(aliases:none)
banlistfile(aliases:none)
hashbanlist(aliases:none)
ipbanlist(aliases:none)
namebanlist(aliases:none)
textbanlist(aliases:none)
banlist(aliases: "listbans", "bans", "showbans", "viewbans")
unban(aliases: "ipunban", "hashunban", "textunban", "nameunban")
boslist(aliases:none)
bosplayers(aliases: "bosableplayers")
changelevel(aliases: "adminlevel", "levelchange", "level", "modifylevel", "changeadminlevel", "modifyadminlevel")
changeteam(aliases: "ts", "teamchange", "swapteam", "teamswap")
disconnect(aliases: "losenetworkconnection", "loseconnection", "dc")
count(aliases: "uniques", "uniqueplayers")
commands(aliases: "cmds", "commandlist", "list", "listcommands", "showcommands", "allcommands", "getcommands", "viewcommands")
crash(aliases:none)
damage(aliases: "dmg", "setdmg", "setdmgmulti", "setdamage")
delrcon(aliases: "rcondel")
eject(aliases: "playereject", "ejectplayer")
gethash(aliases: "hash", "gethash")
getip(aliases:none)
getloc(aliases: "getplayerlocation", "getplayerloc", "getplayercoords", "getcoords", "coords", "playerloc", "playercoords")
setgod(aliases: "god", "godmode", "godset", "cheatgod", "cheatsetgod", "cheatgodmode", "cheatinvincible", "invincible")
cheathax(aliases: "hax", "haxolu", "haxor", "1337")
heal(aliases: "healplayer", "playerheal", "cheatheal", "restorehealth", "cheatrestorehealth", "cheatheal")
hide(aliases: "hideplayer", "playerhide", "cheathide")
info(aliases: "i", "playerinfo", "infoplayer", "getplayerinfo", "getinfo")
ipban(aliases: "banip", "ipbanplayer")
invis(aliases: "camo", "camouflage", "setcamo", "cheatsetcamo", "cheatcamo", "cheatgivecamo", "givecamo")
kick(aliases: "k", "kickplayer", "playerkick")
kill(aliases: "killplayer", "playerkill", "cheatkill", "cheatkillplayer")
launch(aliases:none)
lo3(aliases: "scrim", "startscrim")
login(aliases: "l", "log")
mnext(aliases: "mapnext")
reset(aliases: "mapreset", "resetmap")
move(aliases: "j", "mv")
nameban(aliases: "banname")
overshield(aliases: "os", "giveos", "osgive", "giveovershield", "overshieldgive", "cheatgiveos", "cheatosgive", "cheatovershield", "cheatplayerovershield", "cheatgiveovershield", "cheatovershieldgive")
players(aliases: "pl", "playerlist")
playersmore(aliases: "plmore", "moreplayers")
privatesay(aliases: "pvtsay", "psay", "sayprivately")
rconlist(aliases: "listrcons", "rcons")
read(aliases:none)
write(aliases:none)
resetplayer(aliases: "playerreset", "playereset")
resetweapons(aliases:none)
resp(aliases: "respplayer", "playerresp")
rtvrequired(aliases: "rtvneeded", "totalrtv", "rtvtotal", "rtvpercent", "rtvpercentage", "rockthevoteneeded", "rockthevotepercent", "rockthevotetotal", "totalrockthevote", "midgamevoteneeded")
rtvtimeout(aliases: "rockthevotetimeout")
setammo(aliases: "ammo", "setammo", "ammoset")
setcolor(aliases: "color", "colorset", "playercolor", "cheatsetcolor", "cheatplayercolor")
setassists(aliases: "assists", "assistset", "setassists", "setassist")
setdeaths(aliases: "deaths", "deathset", "setdeaths", "setdeath")
setkills(aliases: "kills", "killset")
setscore(aliases: "scores", "score", "scoreset")
setupright(aliases:none)
setfrags(aliases: "setfrags", "frags", "fragset", "setfragnades")
setplasmas(aliases: "setplasmas", "stickies", "plasmas", "plasmaset", "setplasmanades")
setprefix(aliases: "serverprefix")
setmode(aliases: "modeset")
pass(aliases: "setpass", "password", "setpassword")
reloadadmins(aliases: "reloadadminlist", "adminlistreload", "adminsreload")
loadbanlist(aliases: "banlistload", "loadbans", "bansload", "mergebans", "bansmerge", "mergebanlist", "banlistmerge")
reloadbanlist(aliases: "banlistreload", "reloadbans", "bansreload", "refreshipbans")
respawntime(aliases: "setresp", "setrespawntime")
setspeed(aliases: "spd", "s", "speed", "speedset")
setteleport(aliases: "teleportadd", "addteleport", "tadd", "st", "tpadd", "addtp", "addlocation", "locationadd")
teleportlist(aliases: "tlist", "listteleports", "locations", "teleports", "locs")
spawn(aliases: "spawnobj", "create", "createobject", "spawnobject", "objspawn")
enter(aliases: "entervehicle", "vehicleeneter", "vehienter", "entervehi")
give(aliases: "giveweapon", "weapongive", "cheatgiveweapon")
spammax(aliases: "smax", "maxspam")
spamtimeout(aliases: "timeoutspam")
specs(aliases: "serverspecs", "machineinfo")
mc(aliases: "mcbegin", "startcycle", "cyclestart", "mapcyclebegin")
statusmore(aliases: "serverinfo", "sinfo", "sinfo")
superban(aliases: "ultraban", "megaban")
suspend(aliases: "suspendplayer", "playersuspend", "suspendpl", "sleep", "cheatsuspendplayer")
unsuspend(aliases: "unsuspendplayer", "unsuspendpl", "playerunsuspend")
takeweapons(aliases: "removeweapons", "takeweaponspl", "takeweps")
teleportdel(aliases: "tdel", "delteleport", "dellocation", "locationdel", "tpdel", "rmtel", "teldel", "deltel")
teleport(aliases: "tp", "t", "teletolocation", "tele")
textban(aliases: "mute", "muteplayer", "textbanplayer", "tban", "chatban", "playermute")
timecur(aliases: "curtime")
unbos(aliases: "removebos", "bosremove", "unbanbos", "bosunban")
ungod(aliases: "unsetgod", "removegod", "godunset", "godremove", "cheatunsetgod", "cheatremovegod", "cheatremovegodmode")
cheatunhax(aliases: "unhax")
unhide(aliases: "removehide", "cheatunhide", "cheatunhideplayer")
uninvis(aliases: "uncamo", "removeinvis", "removecamo", "cheatuncamoplayer", "cheatuninvis", "cheatremovecamo", "cheatuncamo", "cheatuncamoplayer")
unmute(aliases: "removemute")
viewadmins(aliases: "curadmins", "adminscur")
votekick_action(aliases: "votekickaction")
votekicktimeout(aliases:none)
votekickrequired(aliases: "votekickneeded")
|
--[[
-- $Id$
-- Simple animation class
-- See Copyright Notice in COPYRIGHT
--]]
require "class"
Animation = class(function(self)
self.running = true
self.frames = {}
self.activeFrame = 1
self.time = 0
self.duration = 0
end)
function Animation:addFrame(image, x, y, width, height, delay)
if type(image) == "string" then
image = scrupp.addImage(image)
end
self.frames[#self.frames+1] = {
image = image,
rect = { x, y, width, height },
delay = delay
}
self.duration = self.duration + delay
return self
end
function Animation:addFrames(image, sizex, sizey, width, height, sep, delay)
if type(image) == "string" then
image = scrupp.addImage(image)
end
for i=1, sizey do
for j=1, sizex do
self.frames[#self.frames+1] = {
image = image,
rect = {
(j-1)*(width+sep), -- x
(i-1)*(height+sep), -- y
width,
height
},
delay = delay
}
end
end
self.duration = sizex * sizey * delay
return self
end
function Animation:getWidth()
return self.frames[self.activeFrame].rect[3] or 0
end
function Animation:getHeight()
return self.frames[self.activeFrame].rect[4] or 0
end
function Animation:getSize()
return self.frames[self.activeFrame].rect[3] or 0,
self.frames[self.activeFrame].rect[4] or 0
end
function Animation:isTransparent(x, y)
local frame = self.frames[self.activeFrame]
x = x + frame.rect[1]
y = y + frame.rect[2]
return frame.image:isTransparent(x, y)
end
function Animation:start()
self.running = true
end
function Animation:stop()
self.running = false
self.activeFrame = 1
end
function Animation:copy()
local t = {}
t.running = self.running
t.frames = self.frames
t.activeFrame = self.activeFrame
t.time = self.time
t.duration = self.duration
setmetatable(t, getmetatable(self))
return t
end
function Animation:render(x, y, delta)
if self.running then
self.time = math.fmod(self.time + delta, self.duration)
end
local moment = 0
for i,frame in ipairs(self.frames) do
moment = moment + frame.delay
if moment >= self.time then
self.activeFrame = i
frame.x = x
frame.y = y
frame.image:render(frame)
break
end
end
end
|
------- Metadata --------------------------------------------------------------
-- Cpuing
-- Author: Lucky Penny
-- Description: Generates the meters for the cpu widget.
-- License: Creative Commons BY-NC-SA 3.0
-- Version: 0.0.3
--
-- Initialize(): As described.
-------------------------------------------------------------------------------
-- Load all schemes from file
function Initialize()
dofile(SKIN:ReplaceVariables("#@#").."FileHelper.lua")
GenerateFile("CpusTotal","TemplateCpuMeters","Cpu")
end
|
Consumeables = {
["sandwich"] = math.random(35, 54),
["water_bottle"] = math.random(35, 54),
["tosti"] = math.random(40, 50),
["kurkakola"] = math.random(35, 54),
["twerks_candy"] = math.random(35, 54),
["snikkel_candy"] = math.random(40, 50),
["coffee"] = math.random(40, 50),
["whiskey"] = math.random(20, 30),
["beer"] = math.random(30, 40),
["vodka"] = math.random(20, 40),
}
Config = {}
Config.EnableProne = true
Config.RemoveWeaponDrops = true
Config.RemoveWeaponDropsTimer = 25
Config.JointEffectTime = 60
Config.BlacklistedScenarios = {
['TYPES'] = {
"WORLD_VEHICLE_MILITARY_PLANES_SMALL",
"WORLD_VEHICLE_MILITARY_PLANES_BIG",
},
['GROUPS'] = {
2017590552,
2141866469,
1409640232,
`ng_planes`,
}
}
Config.BlacklistedVehs = {
[`SHAMAL`] = true,
[`LUXOR`] = true,
[`LUXOR2`] = true,
[`JET`] = true,
[`LAZER`] = true,
[`BUZZARD`] = true,
[`BUZZARD2`] = true,
[`ANNIHILATOR`] = true,
[`SAVAGE`] = true,
[`TITAN`] = true,
[`RHINO`] = true,
[`FIRETRUK`] = true,
[`MULE`] = true,
[`MAVERICK`] = true,
[`BLIMP`] = true,
[`AIRTUG`] = true,
[`CAMPER`] = true,
}
Config.BlacklistedPeds = {
[`s_m_y_ranger_01`] = true,
[`s_m_y_sheriff_01`] = true,
[`s_m_y_cop_01`] = true,
[`s_f_y_sheriff_01`] = true,
[`s_f_y_cop_01`] = true,
[`s_m_y_hwaycop_01`] = true,
}
Config.Teleports = {
--Elevator @ labs
[1] = {
[1] = {
coords = vector4(3540.74, 3675.59, 20.99, 167.5),
["AllowVehicle"] = false,
drawText = '[E] Take Elevator Up'
},
[2] = {
coords = vector4(3540.74, 3675.59, 28.11, 172.5),
["AllowVehicle"] = false,
drawText = '[E] Take Elevator Down'
},
},
--Coke Processing Enter/Exit
[2] = {
[1] = {
coords = vector4(909.49, -1589.22, 30.51, 92.24),
["AllowVehicle"] = false,
drawText = '[E] Enter Coke Processing'
},
[2] = {
coords = vector4(1088.81, -3187.57, -38.99, 181.7),
["AllowVehicle"] = false,
drawText = '[E] Leave'
},
},
}
|
--[[
A tiny library for working with paths. Tiny, because it is simple.
Only Unix-style paths are supported. Windows-style `\` are not handled.
My hypothesis is that it's less error-prone for a path library to support a
consistant API surface. If you need Windows paths, you can write conversion
functions that will let you switch from Win to Unix and back.
]]--
local path = {}
function path.remove_trailing_slash(s)
-- Remove trailing slash from string. Will not remove slash if it is the
-- only character in the string.
return s:gsub('(.)%/$', '%1')
end
local function resolve_double_slashes(s)
-- Resolution is a simple case of replacing double slashes with single.
return s:gsub('%/%/', '/')
end
local function make_same_dir_explicit(s)
if s == "" then return "." else return s end
end
local function resolve_dir_traversals(s)
-- Resolves ../ and ./ directory traversals.
-- Takes a path as string and returns resolved path string.
-- First, resolve `../`. It needs to be handled first because `./` also
-- matches `../`
-- Watch for illegal traversals above root.
-- For these cases, simply return root.
-- /../ -> /
if (s:find("^%/%.%.") ~= nil) then return "/" end
-- Leading double dots should not be messed with.
-- Replace leading dots with token so we don't accidentally replace it.
s = s:gsub('^%.%.', "<LEADING_DOUBLE_DOT>")
-- Elsewhere, remove double dots as well as directory above.
s = s:gsub('[^/]+%/%.%.%/?', '')
-- Next, resolve `./`.
-- Remove single ./ from beginning of string
s = s:gsub("^%.%/", "")
-- Remove single ./ elsewhere in string
-- Note: if we didn't do ../ subsitution earlier, this naive pattern would
-- cause problems. Future me: don't introduce a bug by running this before
-- ../ subsitution.
s = s:gsub("%.%/", "")
-- Remove single /. at end of string
s = s:gsub("%/%.$", "")
-- Bring back any leading double dots.
s = s:gsub('<LEADING_DOUBLE_DOT>', "..")
-- The patterns above can leave behind trailing slashes. Trim them.
s = path.remove_trailing_slash(s)
-- If string ended up empty, return "."
s = make_same_dir_explicit(s)
return s
end
function path.normalize(s)
--[[
/foo/bar -> /foo/bar
/foo/bar/ -> /foo/bar
/foo/../ -> /
/foo/bar/baz/./ -> /foo/bar/baz
/foo/bar/baz/../ -> /foo/bar
.. -> ..
/.. -> /
/../../ -> /
]]--
s = resolve_double_slashes(s)
s = resolve_dir_traversals(s)
return s
end
function path.join(a, b)
return path.normalize(path.normalize(a) .. '/' .. path.normalize(b))
end
function path.shift(s)
-- Return the highest-level portion of a path (it's a split on `/`), along
-- with the rest of the path string.
-- If your path contains traversals, you probably want to use `path.normalize`
-- before passing to shift, since traversals will be considered parts of the
-- path as well.
-- Special case: if path starts with slash, it is a root path and slash has
-- value. Return slash, along with rest of string.
if s:find("^/") then return "/", s:sub(2) end
local i, j = s:find('/')
if i == nil then return s
else return s:sub(1, i - 1), s:sub(j + 1) end
end
function path.parts(s)
-- Get all parts of path as list table.
local head, rest = "", s
local t = {}
repeat
head, rest = path.shift(rest)
table.insert(t, head)
until rest == nil
return t
end
-- Return the portion at the end of a path.
function path.basename(path_string)
-- Get all parts of path as list table.
local head, rest = "", path_string
repeat
head, rest = path.shift(rest)
until rest == nil
-- @fixme I think the way I calculate the rest of the path may be too naive.
-- Update: it is. It doesn't take into account cases where you don't have a
-- basename.
return head, path_string:sub(0, #path_string - #head - 1)
end
function path.extension(path_string)
local dot_i = path_string:find("%.%w+$")
if not dot_i then return "" end
return path_string:sub(dot_i)
end
function path.replace_extension(path_string, new_extension)
return path_string:gsub("(%.%w+)$", new_extension)
end
function path.has_any_extension(path_string, extensions)
for _, extension in ipairs(extensions) do
if path.extension(path_string) == extension then return true end
end
return false
end
-- Remove the explicit index at the end of a url.
-- Returns URL with any index removed.
function path.drop_explicit_index(url_string)
return url_string:gsub("/index%.[^.]+$", "/")
end
-- Given a path and a base URL, will return a pretty URL.
-- `base_url_string` can be absolute or relative.
function path.to_url(base_url_string, relative_path_string)
local normalized_path = path.normalize(relative_path_string)
local pretty_path = path.drop_explicit_index(normalized_path)
-- Rebase path and return.
return base_url_string .. "/" .. pretty_path
end
return path |
--[[
AI Unit tests
Mainly just to see if all AI functionality is available.
Code: Perry
Date: October, 2015
]]
AIUnitTests = class({})
function AIUnitTests:Run( global, unit, ability, aiPlayerRes )
local success = 0
local fail = 0
local globalF = {
'AI_FindUnitsInRadius',
'AI_MinimapEvent',
'AI_EntIndexToHScript',
'AI_Say',
'AI_GetGameTime',
'AI_Log',
'GetItemCost',
'LoadKeyValues',
'RandomFloat',
'RandomInt',
'RandomVector',
'RotateOrientation',
'RotatePosition',
'RotateQuaternionByAxisAngle',
'RotationDelta'
}
--Validate global
for _,func in ipairs( globalF ) do
if global[func] == nil then
fail = fail + 1
Warning('Global function '..func..' not set in AI!')
else
success = success + 1
end
end
local unitF = {
'GetAbsOrigin',
'GetHealth',
'GetMaxHealth',
'GetModelName',
'GetOrigin',
'GetOwner',
'GetOwnerEntity',
'GetTeam',
'GetTeamNumber',
'IsAlive',
'IsInVision',
'HasBuyback',
'GetAbilityByIndex',
'FindAbilityByName',
'GetClassname',
'GetEntityHandle',
'GetEntityIndex',
'GetName',
'GetPlayerOwnerID',
'GetItemInSlot'
}
--Validate unit
for _,func in ipairs( unitF ) do
if unit[func] == nil then
fail = fail + 1
Warning('Unit function '..func..' not set in AI!')
else
success = success + 1
end
end
local abilityF = {
'GetAbilityDamage',
'GetAbilityDamageType',
'GetAbilityTargetFlags',
'GetAbilityTargetTeam',
'GetAbilityTargetType',
'GetAutoCastState',
'GetBackswingTime',
'GetCastPoint',
'GetCooldownTime',
'GetCooldownTimeRemaining',
'GetAbilityType',
'GetAbilityIndex',
'GetChannelledManaCostPerSecond',
'GetCooldown',
'GetClassname',
'GetEntityHandle',
'GetEntityIndex',
'GetName',
'GetAbilityName'
}
--Validate unit
for _,func in ipairs( abilityF ) do
if ability[func] == nil then
fail = fail + 1
Warning('Ability function '..func..' not set in AI!')
else
success = success + 1
end
end
local playerResF = {
'GetAssists',
'GetConnectionState',
'GetDeaths',
'GetGold',
'GetKills',
'GetLastHits',
'GetDenies',
'GetLevel',
'GetNthCourierForTeam',
'GetNumCouriersForTeam',
'GetNthPlayerIDOnTeam',
'GetPlayerCount',
'GetPlayerCountForTeam',
'GetPlayerLoadedCompletely',
'GetPlayerName',
'GetReliableGold',
'GetSteamAccountID',
'GetTeam',
'GetTeamKills',
'GetTeamPlayerCount',
'GetUnreliableGold'
}
--Validate AIPlayerResource
for _,func in ipairs( playerResF ) do
if aiPlayerRes[func] == nil then
fail = fail + 1
Warning('AIPlayerResource function '..func..' not set in AI!')
else
success = success + 1
end
end
if fail == 0 then
print( string.format('AI Unit test: (%i/%i) Success!', success, success ) )
else
Warning( string.format('AI Unit test: (%i/%i) Succeeded.\n', success, success + fail ) )
end
AIEvents:UnitTest()
end |
MQ_Consumer = {
input_type = "mq.consume",
icon = "terminal.png",
output_type = "request"
}
|
-- steel_bars/init.lua
-- Load support for Minebase translation.
local S = minetest.get_translator("steel_bars")
minetest.register_craftitem("steel_bars:bar", {
description = S("Steel Bar"),
inventory_image = "steel_bars_bar.png",
})
minetest.register_craft({
output = "steel_bars:bar",
type = "shaped",
recipe = {
{"base_ores:steel_ingot","",""},
{"base_ores:steel_ingot","",""},
{"base_ores:steel_ingot","",""}
}
})
minetest.register_craft({
output = "base_ores:steel_ingot 3",
type = "cooking",
recipe = "steel_bars:bar",
cooktime = 4
})
minetest.register_node("steel_bars:block", {
description = S("Steel Bar Block"),
drawtype = "glasslike_framed_optional",
tiles = {"steel_bars_bars.png"},
paramtype = "light",
sunlight_propagates = true,
use_texture_alpha = "clip",
is_ground_content = false,
groups = {cracky = 1},
sounds = sounds.get_defaults("ore_sounds:metal"),
})
minetest.register_craft({
output = "steel_bars:block",
type = "shaped",
recipe = {
{"steel_bars:bar", "steel_bars:bar", "steel_bars:bar"},
{"steel_bars:bar", "steel_bars:bar", "steel_bars:bar"},
{"steel_bars:bar", "steel_bars:bar", "steel_bars:bar"}
}
})
if minetest.get_modpath("base_tools") then
minetest.register_craft({
output = "base_tools:steel_pick",
recipe = {
{"", "steel_bars:bar", ""},
{"", "group:stick", ""},
{"", "group:stick", ""}
}
})
end
if minetest.get_modpath("base_ladders") then
minetest.register_craft({
output = "base_ladders:steel_ladder 15",
type = "shaped",
recipe = {
{"","",""},
{"steel_bars:bar","base_ores:steel_ingot","steel_bars:bar"},
{"","",""}
}
})
end
if minetest.get_modpath("base_rails") then
minetest.register_craft({
output = "base_rails:rail 18",
type = "shaped",
recipe = {
{"","group:wood",""},
{"steel_bars:bar","","steel_bars:bar"},
{"","group:wood",""}
}
})
minetest.register_craft({
output = "base_rails:powerrail 18",
type = "shaped",
recipe = {
{"","group:wood",""},
{"steel_bars:bar","base_ores:mese_crystal","steel_bars:bar"},
{"","group:wood",""}
}
})
minetest.register_craft({
output = "base_rails:brakerail 18",
type = "shaped",
recipe = {
{"","group:wood",""},
{"steel_bars:bar","base_ores:coal_lump","steel_bars:bar"},
{"","group:wood",""}
}
})
end
|
local Slot = require("motras_slot")
local t = require("motras_types")
local TrackUpgdateUtils = {}
function TrackUpgdateUtils.upgradeFromParams(params)
if not (params.modules and params.slotId) then
return {}
end
if not (params.modules[params.slotId] and params.modules[params.slotId].metadata) then
return {}
end
local affectedModules = TrackUpgdateUtils.filterAffectedModules(params.modules, params.slotId)
if params.catenaryToggle == 1 and type(params.modules[params.slotId].metadata.motras_electrified) == 'boolean' then
return TrackUpgdateUtils.toggleElectrification(affectedModules, not params.modules[params.slotId].metadata.motras_electrified)
end
if params.trackTypeToggle == 1 and type(params.modules[params.slotId].metadata.motras_highspeed) == 'boolean' then
return TrackUpgdateUtils.toggleHighspeed(affectedModules, not params.modules[params.slotId].metadata.motras_highspeed)
end
return {}
end
function TrackUpgdateUtils.filterAffectedModules(modules, slotId)
local trackInterruptionLeft = nil
local trackInterruptionRight = nil
local matchingModules = {}
local slot = Slot:new{id = slotId}
for moduleSlotId, module in pairs(modules) do
local moduleSlot = Slot:new{id = moduleSlotId}
if moduleSlot.gridY == slot.gridY then
if moduleSlot.gridType == t.GRID_TRACK then
matchingModules[moduleSlotId] = module
else
if moduleSlot.gridX < slot.gridX and ((not trackInterruptionLeft) or moduleSlot.gridX > trackInterruptionLeft) then
trackInterruptionLeft = moduleSlot.gridX
end
if moduleSlot.gridX > slot.gridX and ((not trackInterruptionRight) or moduleSlot.gridX < trackInterruptionRight) then
trackInterruptionRight = moduleSlot.gridX
end
end
end
end
local finalMatchingModules = {}
for moduleSlotId, module in pairs(matchingModules) do
local moduleSlot = Slot:new{id = moduleSlotId}
if ((not trackInterruptionLeft) or moduleSlot.gridX > trackInterruptionLeft) and ((not trackInterruptionRight) or moduleSlot.gridX < trackInterruptionRight) then
finalMatchingModules[moduleSlotId] = module
end
end
return finalMatchingModules
end
function TrackUpgdateUtils.toggleElectrification(modules, shouldElectrify)
local moduleChanges = {}
for slotId, trackModule in pairs(modules) do
if trackModule.metadata
and trackModule.metadata.motras_toggleElectrificationTo
and trackModule.metadata.motras_electrified == not shouldElectrify
then
table.insert(moduleChanges, {slotId, trackModule.metadata.motras_toggleElectrificationTo})
end
end
return moduleChanges
end
function TrackUpgdateUtils.toggleHighspeed(modules, shouldLevelUp)
local moduleChanges = {}
for slotId, trackModule in pairs(modules) do
if trackModule.metadata
and trackModule.metadata.motras_toggleHighspeedTo
and trackModule.metadata.motras_highspeed == not shouldLevelUp
then
table.insert(moduleChanges, {slotId, trackModule.metadata.motras_toggleHighspeedTo})
end
end
return moduleChanges
end
return TrackUpgdateUtils |
local nextTick = require'nodish.process'.nextTick
local S = require'syscall'
local h = require "syscall.helpers"
local events = require'nodish.events'
local ev = require'ev'
local nsocket = require'nodish.net.socket'
local util = require'nodish._util'
local dns = require'nodish.dns'
local ffi = require'ffi'
local loop = ev.Loop.default
local INADDR_ANY = 0x0
local inaddr = function(port,addr)
local inaddr = S.t.sockaddr_in()
inaddr.family = S.c.AF.INET
inaddr.port = port
if addr then
inaddr.addr = addr
else
inaddr.sin_addr.s_addr = INADDR_ANY--h.htonl(INADDR_ANY)
end
return inaddr
end
--- creates and binds a listening socket for
-- ipv4 and (if available) ipv6.
local sbind = function(host,port,backlog)
local server = S.socket('inet','stream')
server:nonblock(true)
server:setsockopt('socket','reuseaddr',true)
-- TODO respect host
local hostAddr
if host then
hostAddr = dns.getaddrinfo(host)[1].addr --maybe nil
end
server:bind(inaddr(port,hostAddr))
server:listen(backlog or 511)
return server
end
local new = function(options)
local allowHalfOpen = options and options.allowHalfOpen
local self = events.EventEmitter()
local conCount = 0
local lsock
local listenIo
local closing
self:once('error',function(err)
if lsock then
lsock:close()
end
self:emit('close',err)
end)
self.listen = function(_,port,host,backlog,callback)
assert(_ == self)
lsock = sbind(host,port,backlog)
nextTick(function()
self:emit('listening',self)
end)
if callback then
self:once('listening',callback)
end
listenIo = ev.IO.new(
function()
local sock,err = lsock:accept()
if sock then
local s = nsocket.new({
fd = sock,
allowHalfOpen = allowHalfOpen
})
conCount = conCount + 1
assert(conCount > 0)
s:once('close',function()
assert(conCount > 0)
conCount = conCount - 1
if closing and conCount == 0 then
self:emit('close')
end
end)
self:emit('connection',s)
else
assert(err)
self:emit('error',err)
end
end,
lsock:getfd(),
ev.READ)
listenIo:start(loop)
end
self.unref = function()
util.unref(listenIo)
end
self.ref = function()
util.ref(listenIo)
end
self.address = function()
if lsock then
local addr = lsock:getsockname()
local resObj = {
address = tostring(addr.addr),
port = addr.port,
family = family[addr.family],
}
return resObj
end
end
self.close = function(_,cb)
listenIo:stop(loop)
lsock:close()
closing = true
if cb then
self:once('close',cb)
end
if conCount == 0 then
self:emit('close')
end
end
return self
end
local createServer = function(...)
local args = {...}
local options
local connectionListener
if type(args[1]) == 'table' then
options = args[1]
elseif type(args[1]) == 'function' then
connectionListener = args[1]
end
if #args > 1 then
connectionListener = args[2]
end
local server = new(options)
server:on('connection',connectionListener)
return server
end
return {
createServer = createServer
}
|
local Rand = require("api.Rand")
local Chara = require("api.Chara")
local I18N = require("api.I18N")
local Effect = require("mod.elona.api.Effect")
local Skill = require("mod.elona_sys.api.Skill")
local Charagen = require("mod.elona.api.Charagen")
local Dialog = require("mod.elona_sys.dialog.api.Dialog")
local DeferredEvent = require("mod.elona_sys.api.DeferredEvent")
local Event = require("api.Event")
local ElonaQuest = require("mod.elona.api.ElonaQuest")
data:add {
_type = "elona.encounter",
_id = "merchant",
encounter_level = function()
-- >>>>>>>> shade2/action.hsp:685 encounterLv=10+rnd(100) ...
return 10 + Rand.rnd(100)
-- <<<<<<<< shade2/action.hsp:685 encounterLv=10+rnd(100) ..
end,
on_map_entered = function(map, level, outer_map, outer_x, outer_y)
local player = Chara.player()
-- >>>>>>>> shade2/map.hsp:1623 flt ...
local merchant = Chara.create("elona.shopkeeper", 10, 11, nil, map)
merchant:add_role("elona.shopkeeper", { inventory_id = "elona.wandering_merchant" })
merchant.shop_rank = level
merchant.name = I18N.get("chara.job.wandering_vendor", merchant.name)
Effect.generate_money(merchant)
for _ = 1, level / 2 + 1 do
Skill.gain_level(merchant)
end
for _ = 1, 6 + Rand.rnd(6) do
local filter = {
initial_level = level + Rand.rnd(6),
tag_filters = { "shopguard" }
}
local guard = Charagen.create(14, 11, filter, map)
if guard then
guard:add_role("elona.shop_guard") -- Prevents incognito from having an effect
guard.name = ("%s Lv%d"):format(guard.name, guard.level)
end
end
local event = function()
-- >>>>>>>> shade2/main.hsp:1680 tc=findChara(idShopKeeper) : gosub *chat ...
local map_ = player:current_map()
if map_.uid == map.uid then
local merchant_ = Chara.find("elona.shopkeeper", "all", map_)
Dialog.start(merchant_)
end
-- <<<<<<<< shade2/main.hsp:1680 tc=findChara(idShopKeeper) : gosub *chat ..
end
DeferredEvent.add(event)
-- <<<<<<<< shade2/map.hsp:1636 ..
end
}
local function is_wandering_merchant(chara)
return chara:iter_roles("elona.shopkeeper"):any(function(role) return role.inventory_id == "elona.wandering_merchant" end)
end
local function exit_merchant_encounter(_, params, result)
if params.talk.dialog._id == "elona.default" and is_wandering_merchant(params.talk.speaker) then
if result.node_id == "__END__" then
ElonaQuest.travel_to_previous_map()
end
end
return result
end
Event.register("elona_sys.on_step_dialog", "Exit merchant encounter on dialog end", exit_merchant_encounter)
local function add_attack_dialog_option(speaker, _, choices)
-- >>>>>>>> shade2/chat.hsp:2217 if cRole(tc)=cRoleShopWander:chatList 31,lang("襲 ...
if is_wandering_merchant(speaker) then
Dialog.add_choice("elona.wandering_merchant:attack_confirm", "talk.npc.shop.choices.attack", choices)
end
-- <<<<<<<< shade2/chat.hsp:2217 if cRole(tc)=cRoleShopWander:chatList 31,lang("襲 ..
return choices
end
Event.register("elona.calc_dialog_choices", "Add attack option for wandering merchant",
add_attack_dialog_option, {priority = 210000})
data:add {
_type = "elona_sys.dialog",
_id = "wandering_merchant",
nodes = {
-- >>>>>>>> shade2/chat.hsp:2583 listMax=0 ...
attack_confirm = {
text = "talk.npc.shop.attack.dialog",
choices = {
{"attack", "talk.npc.shop.attack.choices.attack"},
{"elona.default:you_kidding", "talk.npc.shop.attack.choices.go_back"}
}
},
-- <<<<<<<< shade2/chat.hsp:2588 if chatVal!1:buff=strKidding:goto *chat_default ..
attack = function(t)
-- >>>>>>>> shade2/chat.hsp:2590 goHostile ...
Effect.turn_guards_hostile(Chara.player())
return "__END__"
-- <<<<<<<< shade2/chat.hsp:2591 goto *chat_end ..
end
}
}
|
local frames = {
["ContainerFrame1"] = {
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame1.ClickableTitleFrame"] = {
DriftDelegate = "ContainerFrame1",
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame2"] = {
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame2.ClickableTitleFrame"] = {
DriftDelegate = "ContainerFrame2",
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame3"] = {
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame3.ClickableTitleFrame"] = {
DriftDelegate = "ContainerFrame3",
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame4"] = {
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame4.ClickableTitleFrame"] = {
DriftDelegate = "ContainerFrame4",
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame5"] = {
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame5.ClickableTitleFrame"] = {
DriftDelegate = "ContainerFrame5",
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame6"] = {
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame6.ClickableTitleFrame"] = {
DriftDelegate = "ContainerFrame6",
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame7"] = {
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame7.ClickableTitleFrame"] = {
DriftDelegate = "ContainerFrame7",
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame8"] = {
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame8.ClickableTitleFrame"] = {
DriftDelegate = "ContainerFrame8",
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame9"] = {
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame9.ClickableTitleFrame"] = {
DriftDelegate = "ContainerFrame9",
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame10"] = {
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame10.ClickableTitleFrame"] = {
DriftDelegate = "ContainerFrame10",
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame11"] = {
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame11.ClickableTitleFrame"] = {
DriftDelegate = "ContainerFrame11",
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame12"] = {
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame12.ClickableTitleFrame"] = {
DriftDelegate = "ContainerFrame12",
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame13"] = {
DriftDisabledBy = "bagsDisabled"
},
["ContainerFrame13.ClickableTitleFrame"] = {
DriftDelegate = "ContainerFrame13",
DriftDisabledBy = "bagsDisabled"
},
["CharacterFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["HonorFrame"] = {
DriftDisabledBy = "windowsDisabled",
DriftDelegate = "CharacterFrame"
},
["TradeSkillFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["CraftFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["QuestLogFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["QuestFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["QuestWatchFrame"] = {
DriftDisabledBy = "objectivesDisabled"
},
["GossipFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["SpellBookFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["PlayerTalentFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["WorldMapFrame"] = {
DriftDisabledBy = "windowsDisabled",
-- TODO: Add scaling support for WorldMapFrame
DriftUnscalable = true
},
["FriendsFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["BNToastFrame"] = {
DriftDisabledBy = "miscellaneousDisabled",
},
["ReputationDetailFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["GuildInfoFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["CommunitiesFrame"] = {
DriftDisabledBy = "windowsDisabled",
DriftTabs = {
"CommunitiesFrame.ChatTab",
"CommunitiesFrame.RosterTab",
"CommunitiesFrame.MaximizeMinimizeFrame.MinimizeButton",
"CommunitiesFrame.MaximizeMinimizeFrame.MaximizeButton",
"CommunitiesFrameCommunitiesListListScrollFrameButton1",
"CommunitiesFrameCommunitiesListListScrollFrameButton2",
"CommunitiesFrameCommunitiesListListScrollFrameButton3",
"CommunitiesFrameCommunitiesListListScrollFrameButton4",
"CommunitiesFrameCommunitiesListListScrollFrameButton5",
"CommunitiesFrameCommunitiesListListScrollFrameButton6",
"CommunitiesFrameCommunitiesListListScrollFrameButton7",
"CommunitiesFrameCommunitiesListListScrollFrameButton8",
"CommunitiesFrameCommunitiesListListScrollFrameButton9",
"CommunitiesFrameCommunitiesListListScrollFrameButton10",
"CommunitiesFrameCommunitiesListListScrollFrameButton11",
"CommunitiesFrameCommunitiesListListScrollFrameButton12",
"CommunitiesFrameCommunitiesListListScrollFrameButton13",
"CommunitiesFrameCommunitiesListListScrollFrameButton14",
"CommunitiesFrameCommunitiesListListScrollFrameButton15",
"CommunitiesFrameCommunitiesListListScrollFrameButton16",
"CommunitiesFrameCommunitiesListListScrollFrameButton17",
"CommunitiesFrameCommunitiesListListScrollFrameButton18",
"CommunitiesFrameCommunitiesListListScrollFrameButton19",
"CommunitiesFrameCommunitiesListListScrollFrameButton20"
}
},
["ChannelFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["RaidInfoFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["DressUpFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["SideDressUpFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["AddonList"] = {
DriftDisabledBy = "windowsDisabled",
},
["MerchantFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["MailFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["SendMailFrame"] = {
DriftDisabledBy = "windowsDisabled",
DriftDelegate = "MailFrame"
},
["OpenMailFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["BankFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["LootFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["GroupLootFrame1"] = {
DriftDisabledBy = "miscellaneousDisabled",
},
["GroupLootFrame2"] = {
DriftDisabledBy = "miscellaneousDisabled",
},
["GroupLootFrame3"] = {
DriftDisabledBy = "miscellaneousDisabled",
},
["GroupLootFrame4"] = {
DriftDisabledBy = "miscellaneousDisabled",
},
["GameMenuFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["VideoOptionsFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["AudioOptionsFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["InterfaceOptionsFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["KeyBindingFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["HelpFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["HelpOpenWebTicketButton"] = {
DriftDisabledBy = "buttonsDisabled",
},
["RaidParentFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["RaidBrowserFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["TradeFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["SUFWrapperFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["TimeManagerFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["TabardFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["GuildRegistrarFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["GuildControlUI"] = {
DriftDisabledBy = "windowsDisabled",
},
["PetitionFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["ColorPickerFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["InspectFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["ItemSocketingFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["MacroFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["MacroPopupFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["WardrobeFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["ClassTrainerFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["AuctionFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["ItemTextFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["PetStableFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["TaxiFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["FlightMapFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["WorldStateScoreFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["BattlefieldFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["ChatConfigFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
["UIWidgetTopCenterContainerFrame"] = {
DriftDisabledBy = "miscellaneousDisabled",
DriftChildMovers = true
},
["MinimapCluster"] = {
DriftDisabledBy = "minimapDisabled",
},
["MinimapZoneTextButton"] = {
DriftDisabledBy = "minimapDisabled",
DriftDelegate = "MinimapCluster"
},
["LFGParentFrame"] = {
DriftDisabledBy = "windowsDisabled",
},
}
-- Frame for handling events
local Drift = CreateFrame("Frame")
local function eventHandler(self, event, ...)
if event == "ADDON_LOADED" then
local addonName = select(1, ...)
-- Blizzard Groups buttons are delayed for some reason
if addonName == "Blizzard_Communities" then
DriftHelpers:Wait(0.25, DriftHelpers.ModifyFrames, DriftHelpers, frames)
else
DriftHelpers:ModifyFrames(frames)
end
elseif event == "PLAYER_REGEN_ENABLED" then
DriftHelpers:ModifyFrames(frames)
elseif event == "VARIABLES_LOADED" then
-- Config
DriftHelpers:SetupConfig()
-- Disable frames depending on DriftOptions
for frameName, properties in pairs(frames) do
local disabledBy = properties.DriftDisabledBy
if disabledBy ~= nil and DriftOptions[disabledBy] then
frames[frameName] = nil
end
end
-- Modify pre-loaded frames
DriftHelpers:ModifyFrames(frames)
-- Quest Watch
Drift:RegisterEvent("QUEST_WATCH_LIST_CHANGED")
-- Groups
Drift:RegisterEvent("CLUB_TICKET_RECEIVED")
-- Modify frames after an addon loads
DriftHelpers:Wait(1, Drift.RegisterEvent, Drift, "ADDON_LOADED")
-- Modify frames after combat ends
Drift:RegisterEvent("PLAYER_REGEN_ENABLED")
else
DriftHelpers:BroadcastReset(frames)
end
end
-- Respond to events to fix frames
Drift:SetScript("OnEvent", eventHandler)
Drift:RegisterEvent("VARIABLES_LOADED")
|
local EVENT = {}
EVENT.Title = "Petrify!"
EVENT.Description = "Turns players into a stone like figure, playing a quite annoying sound when they move."
EVENT.id = "petrify"
function EVENT:GetConVars()
local sliders = {}
for _, v in pairs({}) do
local name = "randomat_" .. self.id .. "_" .. v
if ConVarExists(name) then
local convar = GetConVar(name)
table.insert(sliders, {
cmd = v, -- The command extension (e.g. everything after "randomat_example_")
dsc = convar:GetHelpText(), -- The description of the ConVar
min = convar:GetMin(), -- The minimum value for this slider-based ConVar
max = convar:GetMax(), -- The maximum value for this slider-based ConVar
dcm = 0 -- The number of decimal points to support in this slider-based ConVar
})
end
end
local checks = {}
for _, v in pairs({}) do
local name = "randomat_" .. self.id .. "_" .. v
if ConVarExists(name) then
local convar = GetConVar(name)
table.insert(checks, {
cmd = v, -- The command extension (e.g. everything after "randomat_example_")
dsc = convar:GetHelpText() -- The description of the ConVar
})
end
end
local textboxes = {}
for _, v in pairs({}) do
local name = "randomat_" .. self.id .. "_" .. v
if ConVarExists(name) then
local convar = GetConVar(name)
table.insert(textboxes, {
cmd = v, -- The command extension (e.g. everything after "randomat_example_")
dsc = convar:GetHelpText() -- The description of the ConVar
})
end
end
return sliders, checks, textboxes
end
-- Turn player to stone
local function petrify(ply)
if ply then
if ply:IsValid() and ply:Alive() then
FindMetaTable("Entity").SetModel(ply, "models/player.mdl")
end
end
end
function EVENT:Begin()
hook.Add("PlayerSpawn", "randomatDefaultPlayer", function(ply)
-- Petrify on spawn
if ply then
timer.Simple(0.5, petrify, ply)
end
end)
-- Petrify all players
for i, ply in pairs(player.GetAll()) do
petrify(ply)
ply.soundPlaying = false
end
-- Player sound when moving
hook.Add( "Move", "randomatDefaultPlayerMove", function( ply, mv )
if ply and ply:Alive() then
if mv:GetVelocity():Length() > 10 and not ply.soundPlaying and ply:IsOnGround() then
ply:EmitSound( "physics\\concrete\\concrete_scrape_smooth_loop1.wav", 30)
ply.soundPlaying = true
elseif (mv:GetVelocity():Length() < 10 or not ply:IsOnGround()) and ply.soundPlaying then
ply:StopSound("physics\\concrete\\concrete_scrape_smooth_loop1.wav")
ply.soundPlaying = false
end
end
end)
-- Stop sound on death
hook.Add( "DoPlayerDeath", "randomatDefaultPlayerDeath", function( ply)
if ply.soundPlaying then
ply:StopSound("physics\\concrete\\concrete_scrape_smooth_loop1.wav")
end
end)
end
function EVENT:End()
-- Clean up hooks
hook.Remove("PlayerSpawn", "randomatDefaultPlayer")
hook.Remove("Move", "randomatDefaultPlayerMove")
hook.Remove("DoPlayerDeath", "randomatDefaultPlayerDeath")
-- Stop Sound
for i, ply in ipairs ( player.GetAll() ) do
ply:StopSound("physics\\concrete\\concrete_scrape_smooth_loop1.wav")
end
end
Randomat:register(EVENT) |
minetest.register_node("terranova:craft_bench", {
description = "Workshop",
tiles = {"t.workbench.png"},
drawtype = "nodebox",
on_construct = function()
})
utils.register_craft({
output = "iron_ingot",
input = {"magnetite_lump"},
type = {"craftbench", "smelter"},
milestone = 0,
alternate = false,
time = 1,
name = "Iron Ingot"
})
utils.register_craft({
output = "iron_rod 2",
input = {"iron_ingot"},
type = {"craftbench", "constructor"},
milestone = 0,
alternate = false,
time = 1,
name = "Iron Rod"
})
utils.register_craft({
output = "iron_plate 3",
input = {"iron_ingot 2"},
type = {"craftbench", "constructor"},
milestone = 0,
alternate = false,
time = 1,
name = "Iron Plate"
}) |
local lwGetMode = _G.love.window.getMode
local lgPush = _G.love.graphics.push
local lgPop = _G.love.graphics.pop
local lgTranslate = _G.love.graphics.translate
local lgScale = _G.love.graphics.scale
local lgRectangle = _G.love.graphics.rectangle
local lgSetColor = _G.love.graphics.setColor
local lmGetPosition = _G.love.mouse.getPosition
local min = math.min
local TLfres = {}
local lastMouseX, lastMouseY = 0, 0
local currentlyRendering
-- Internal helper function
local function _getRawMousePosition(width, height)
local x, y = lmGetPosition()
local w, h = lwGetMode()
local scale = min(w/width, h/height)
return (x - (w - width * scale) * 0.5)/scale, (y - (h - height * scale) * 0.5)/scale
end
-- Use this any time you would normally call love.mouse.getPosition.
-- The returned position is scaled to the given dimensions.
-- width and height is expected canvas width and height
function TLfres.getMousePosition(width, height)
local x, y = _getRawMousePosition(width, height)
if x >= 0 and x <= width and y >= 0 and y <= height then
lastMouseX, lastMouseY = _getRawMousePosition(width, height)
end
return lastMouseX, lastMouseY
end
-- Calculate the current scale based on the desired dimensions and current ones
-- If called within a rendering block, width and height are optional.
function TLfres.getScale(width, height)
if currentlyRendering then
width = width or currentlyRendering[1]
height = height or currentlyRendering[2]
end
local w, h = lwGetMode()
return min(w/width, h/height)
end
-- Zooms and centers to fit width×height into the current window.
-- 0,0 is at the top-left of the canvas, or the middle if centered is true.
-- Use love.graphics.push before this and love.graphics.pop after done rendering
function TLfres.beginRendering(width, height, centered)
if currentlyRendering then
error("Must call tlfres.endRendering before calling beginRendering.")
return
end
currentlyRendering = {width, height}
lgPush()
local w, h = lwGetMode()
local scale = min(w/width, h/height)
lgTranslate((w - width * scale) * 0.5, (h - height * scale) * 0.5)
lgScale(scale)
if centered then
lgTranslate(0.5 * width, 0.5 * height)
end
return scale
end
local _black = {0, 0, 0, 255}
-- Pops out of the transform; if letterboxColor is true, draws black letterbox
-- bars. letterboxColor can also be any {r, g, b, a} table.
function TLfres.endRendering(letterboxColor)
if not currentlyRendering then
error("Must call tlfres.beginRendering before calling endRendering.")
return
end
local width, height = currentlyRendering[1], currentlyRendering[2]
currentlyRendering = nil
lgPop()
local w, h = lwGetMode()
local scale = min(w/width, h/height)
width, height = width * scale, height * scale
lgSetColor(letterboxColor or _black)
lgRectangle("fill", 0, 0, w, 0.5 * (h - height)) -- top
lgRectangle("fill", 0, h, w, -0.5 * (h - height)) -- bottom
lgRectangle("fill", 0, 0, 0.5 * (w - width), h) -- left
lgRectangle("fill", w, 0, -0.5 * (w - width), h) -- right
end
return TLfres |
local f = string.format
My.Translator:register("en", {
side_mission_destroy_graveyard_too_close = "You are too close to the area of operations and can not accept the mission.",
side_mission_destroy_graveyard = function(sectorName)
return f("Destroy space junk in sector %s", sectorName)
end,
side_mission_destroy_graveyard_description = function(sectorName, number, payment)
return Util.random({
"You might have noticed that we have a problem with space scrap here.",
"We have to admit this mission is not the most prestigious. But someone has to do it.",
}) .. " " .. Util.random({
f("Some wrecks on the ship graveyard in sector %s went off route and threaten to drift into a nearby trade route. You have to vaporize the wrecks of %d ships.", sectorName, number),
f("%d ship wrecks in the nearby ship graveyard will leave their stable orbit soon. We do not want them to be a danger to near travel routes, so we are looking for someone to vaporize them.", number),
}) .. "\n\n" .. Util.random({
f("We pay %0.2fRP on completion.", payment),
f("If you would help us, we are paying %0.2fRP.", payment),
})
end,
side_mission_destroy_graveyard_hint = function(numberOfTargets)
if numberOfTargets > 1 then
return f("Destroy %d more marked ships on the ship graveyard.", numberOfTargets)
else
return "Destroy one more marked ship on the ship graveyard."
end
end,
side_mission_destroy_graveyard_success_comms = function(payment)
return Util.random({
"Excellent. You proofed you can shoot on immobile targets.",
}) .. " " .. Util.random({
"Should ever again be in need of someone to destroy immovable targets with an oversized beam weapon, we might come back to you.",
"Don't worry about it: Every good fighter pilot started small.",
"If you continue to put your shoulder to the wheel, maybe we'll have you shooting at moving targets soon - like the big boys.",
"Don't listen to people who say that the mission could have been done by a group of Girl Scouts. They're just jealous.",
}) .. "\n\n" .. Util.random({
f("Here are your %0.2fRP.", payment),
f("As agreed you get %0.2fRP from us.", payment),
}) .. " " .. Util.random({
"You can buy yourself a medal of cleanness in the next toy shop.",
"Get yourself an ice cream.",
"If you invest the money well, you might buy a dollhouse in a few years.",
})
end,
side_mission_destroy_graveyard_raid_comms = function(captainPerson)
return Util.random({
f("Get off this container. It is official property of me, Captain %s now.", captainPerson:getFormalName()),
"Get away from the ship container or will have to deal with me.",
})
end
}) |
--[=[
@Author: Gavin "Mullets" Rosenthal
@Desc: Public Modular Component System. The only respectible way to handle Roblox UI
]=]
--[=[
Modular Component System is a light weight component system designed
for handling interface at a surface level. Components work with attributes
so you won't have to do anything when Roblox enables them. ValueBase objects
work perfectly fine as well.
[DOCUMENTATION]:
This is an overview of how MCS works.
This is the recommended way to initialize a component on a given tag:
MCS('tag',function(component)
-- code
end)
This is the recommended way to get the *first* component on a tag in PlayerGui:
MCS('tag')
Note the function, by excluding it you can shortcut this function to return a get instead of a create
Standard API:
MCS:Get(GuiObject)
- Returns the component on a UI object
MCS:GetAll('string')
- Returns all components, in a table, on a given tag
MCS:GetComponent('string')
- Returns the first component on a tag in the PlayerGui
MCS:Fire('string', ...)
- Fire a binded function on a given name
MCS:Create('string', function)
- Create the component & pass it in the function
MCS('string', function)
- See MCS:Create
MCS('string')
- See MCS:GetComponent
[LICENSE]:
MIT License
Copyright (c) 2020 Mullet Mafia Dev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]=]
local MCS = {}
MCS.__index = MCS
MCS._ComponentCode = {}
MCS._ComponentCache = {}
setmetatable(MCS,MCS)
local Components = require(script:WaitForChild('Components'))
local Players = game:GetService('Players')
local CollectionService = game:GetService('CollectionService')
--[=[
Bind & create a component with an element
@param tag string -- the tag used
@param element GuiObject -- the object used for the component
@return nil
@private
]=]
local function BindComponent(tag: string, element: GuiObject): nil
if MCS._ComponentCache[tag][element] then return end
local Player = Players.LocalPlayer
local PlayerGui = Player.PlayerGui
coroutine.wrap(function()
while not element:IsDescendantOf(PlayerGui) do
element.AncestryChanged:Wait()
end
local code = MCS._ComponentCode[tag]
local create = Components.new(element)
MCS._ComponentCache[tag][element] = create
code(create)
end)()
end
--[=[
Return a component on an element
@param element GuiObject -- the element to get a component from
]=]
function MCS:Get(element: GuiObject): typeof(MCS:Create())?
for tag,data in pairs(MCS._ComponentCache) do
for index,obj in pairs(data) do
if index ~= element then continue end
return obj
end
end
end
--[=[
Returns all the components on a tag in PlayerGui
@param tag string -- the tag to get from
]=]
function MCS:GetAll(tag: string): table
return MCS._ComponentCache[tag]
end
--[=[
Get the first component on a tag in the PlayerGui
@param tag string
@return Component?
]=]
function MCS:GetComponent(tag: string): typeof(MCS:Create())?
local tags = MCS:GetAll(tag)
for index,component in pairs(tags) do
return component
end
end
--[=[
Fires a function with the tag
@param name string -- the name of the binding
@param ...? any -- optional parameters to pass
@return nil
]=]
function MCS:Fire(name: string, ...): nil
assert(Components._Bindings[name],"Attempted to fire non-existant binding on '"..name.."'")
local code = Components._Bindings[name]
code(...)
end
--[=[
Create a component out of a collection service tag!
@param tag string -- the CollectionService tag to track
@param code function -- the function to run when you get a component
@return nil
]=]
function MCS:Create(tag: string, code: (any) -> nil): nil
assert(MCS._ComponentCache[tag] == nil,"tag is claimed")
MCS._ComponentCache[tag] = {}
MCS._ComponentCode[tag] = code
CollectionService:GetInstanceAddedSignal(tag):Connect(function(component)
BindComponent(tag,component)
end)
local tagged = CollectionService:GetTagged(tag)
for index,component in pairs(tagged) do
BindComponent(tag,component)
end
end
--[=[
Redirects to either Interface:Create() or Interface:GetComponent(), streamlines shortcutting to Interface()
@param tag string -- the CollectionService tag to track
@param code? function -- the function to run when you get a component
@return typeof(MCS:Create())?
]=]
function MCS:__call(tag: string, code: ((any) -> nil)?): typeof(MCS:Create())?
if not code and MCS._ComponentCache[tag] then
return MCS:GetComponent(tag)
end
MCS:Create(tag,code)
end
return MCS |
-- reserve the namespace
save_restore = {}
-- TODO: if this gets more versatile, add sanity checks for filename
-- TODO: save and restore ought to be library functions and not implemented in each individual mod!
save_restore.save_data = function( filename, data )
local path = minetest.get_worldpath()..'/'..filename;
local file = io.open( path, 'w' );
if( file ) then
file:write( minetest.serialize( data ));
file:close();
else
print("[save_restore] Error: Savefile '"..tostring( path ).."' could not be written.");
end
end
save_restore.restore_data = function( filename )
local path = minetest.get_worldpath()..'/'..filename;
local file = io.open( path, 'r' );
if( file ) then
local data = file:read("*all");
file:close();
return minetest.deserialize( data );
else
print("[save_restore] Error: Savefile '"..tostring( path ).."' not found.");
return {}; -- return empty table
end
end
|
--[[Created by Luada
--]]
require "base.class"
require "base.scriptObject"
require "common.ticker"
require "common.timeEvent"
require "common.eventCenter"
require "common.eventCallback"
require "game"
|
local displayTime = true
local useMilitaryTime = false
local displayDayOfWeek = true
local displayDate = true
local timeAndDateString = nil
local hour
local minute
local dayOfWeek
local month
local dayOfMonth
local year
-- Display Time and Date at top right of screen -- format: | 12:13 | Wednesday | January 17, 2017 |
Citizen.CreateThread(function()
while true do
Wait(1)
timeAndDateString = "|"
if displayTime == true then
CalculateTimeToDisplay()
timeAndDateString = timeAndDateString .. " " .. hour .. ":" .. minute .. " |"
end
if displayDayOfWeek == true then
CalculateDayOfWeekToDisplay()
timeAndDateString = timeAndDateString .. " " .. dayOfWeek .. " |"
end
if displayDate == true then
CalculateDateToDisplay()
timeAndDateString = timeAndDateString .. " " .. month .. " " .. dayOfMonth .. ", " .. year .. " |"
end
SetTextFont(0)
SetTextProportional(1)
SetTextScale(0.30, 0.30)
SetTextColour(255, 255, 255, 255)
SetTextDropshadow(0, 0, 0, 0, 255)
SetTextEdge(1, 0, 0, 0, 255)
SetTextDropShadow()
SetTextOutline()
SetTextRightJustify(true)
SetTextWrap(0,0.95)
SetTextEntry("STRING")
AddTextComponentString(timeAndDateString)
DrawText(0.5, 0.01)
end
end)
function CalculateTimeToDisplay()
hour = GetClockHours()
minute = GetClockMinutes()
if useMilitaryTime == false then
if hour == 0 or hour == 24 then
hour = 12
elseif hour >= 13 then
hour = hour - 12
end
end
if hour <= 9 then
hour = "0" .. hour
end
if minute <= 9 then
minute = "0" .. minute
end
end
function CalculateDayOfWeekToDisplay()
dayOfWeek = GetClockDayOfWeek()
if dayOfWeek == 0 then
dayOfWeek = "Domingo"
elseif dayOfWeek == 1 then
dayOfWeek = "Segunda"
elseif dayOfWeek == 2 then
dayOfWeek = "Terça"
elseif dayOfWeek == 3 then
dayOfWeek = "Quarta"
elseif dayOfWeek == 4 then
dayOfWeek = "Quinta"
elseif dayOfWeek == 5 then
dayOfWeek = "Sexta"
elseif dayOfWeek == 6 then
dayOfWeek = "Sábado"
end
end
function CalculateDateToDisplay()
month = GetClockMonth()
dayOfMonth = GetClockDayOfMonth()
year = GetClockYear()
if month == 0 then
month = "Janeiro"
elseif month == 1 then
month = "Fevereiro"
elseif month == 2 then
month = "Março"
elseif month == 3 then
month = "Abril"
elseif month == 4 then
month = "Maio"
elseif month == 5 then
month = "Junho"
elseif month == 6 then
month = "Julho"
elseif month == 7 then
month = "Agosto"
elseif month == 8 then
month = "Setembro"
elseif month == 9 then
month = "Outubro"
elseif month == 10 then
month = "Novembro"
elseif month == 11 then
month = "Dezembro"
end
end
|
-- Copyright (C) by Zexuan Luo (spacewander), under MIT License
-- Ported from https://github.com/ryanuber/go-glob
local _M = {}
local _E = {}
local mt = {__index = _E}
local GLOB = '*'
local GLOB_BYTE = string.byte(GLOB, 1)
-- http://lua-users.org/wiki/SplitJoin
local function split(s, sep)
local res = {}
if #s > 0 then
local n, start = 1, 1
local first, last = s:find(sep, start, true)
while first do
res[n] = s:sub(start, first - 1)
n = n + 1
start = last + 1
first, last = s:find(sep, start, true)
end
res[n] = s:sub(start)
end
return res
end
function _M.compile(pat)
local exp = {}
exp.pattern = pat
exp.parts = split(pat, GLOB)
exp.n_part = #exp.parts
exp.leading_glob = pat:byte(1) == GLOB_BYTE
exp.trailing_glob = pat:byte(#pat) == GLOB_BYTE
return setmetatable(exp, mt)
end
local function has_suffix(s, offset, suffix)
if #suffix + offset > #s then
return false
end
local start = #s - #suffix
for i = 1, #suffix do
if suffix:byte(i) ~= s:byte(i + start) then
return false
end
end
return true
end
function _E.match(self, subj)
if self.pattern == GLOB then
return true
end
if self.pattern == "" or self.n_part == 1 then
return subj == self.pattern
end
local start = 1
for i = 1, self.n_part - 1 do
local part = self.parts[i]
local from, to = subj:find(part, start, true)
if i == 1 then
if not self.leading_glob and from ~= 1 then
return false
end
to = 0
else
if not from then
return false
end
end
start = to + 1
end
return self.trailing_glob or
has_suffix(subj, start, self.parts[self.n_part])
end
return _M
|
local _M = {}
local ffi = require "ffi"
local C = ffi.C
local ffi_str = ffi.string
local base = require "resty.core.base"
local FFI_OK = base.FFI_OK
local FFI_ERROR = base.FFI_ERROR
local FFI_AGAIN = base.FFI_AGAIN
local get_request = base.get_request
local co_yield = coroutine._yield
local ERR_BUF_SIZE = 128
local errmsg = base.get_errmsg_ptr()
local errbuf = base.get_string_buf(ERR_BUF_SIZE)
local errlen = base.get_size_ptr()
ffi.cdef[[
void *ngx_http_lua_purge_ffi_get_cache_zone(const unsigned char *name_data,
int name_len, char **err);
int ngx_http_lua_purge_ffi_purge_data(ngx_http_request_t *r, void *cache_zone,
const unsigned char *key_data, int key_len, unsigned char *err, size_t *errlen);
]]
function _M.get_zone(name)
if name == nil then
return nil, "nil name"
end
if type(name) ~= "string" then
name = tostring(name)
end
local cache_zone = C.ngx_http_lua_purge_ffi_get_cache_zone(name, #name, errmsg)
if cache_zone == nil then
return nil, ffi_str(errmsg[0])
end
return cache_zone
end
function _M.purge(cache_zone, key)
local r = get_request()
if not r then
error("no request found")
end
if type(cache_zone) ~= "cdata" then
error("bad \"cache_zone\" argument")
end
if key == nil then
return nil, "nil key"
end
if type(key) ~= "string" then
key = tostring(key)
end
errlen[0] = ERR_BUF_SIZE
local rc = C.ngx_http_lua_purge_ffi_purge_data(r, cache_zone, key, #key, errbuf, errlen)
if rc == FFI_ERROR then
return nil, ffi_str(errbuf, errlen[0])
end
if rc == FFI_AGAIN then
return co_yield()
end
return true -- FFI_OK
end
return _M
|
-- Copyright (c) 2021 Kirazy
-- Part of Artisanal Reskins: Bob's Mods
--
-- See LICENSE in the project directory for license information.
-- Check to see if reskinning needs to be done.
if mods["ScienceCostTweakerM"] then return end
if not (reskins.bobs and reskins.bobs.triggers.technology.items) then return end
local inputs = {
mod = "bobs",
group = "technology",
type = "tool",
icon_name = "science-pack",
tier_labels = false,
}
local items = {
["advanced-logistic-science-pack"] = {flat_icon = true, subgroup = "science-pack"}
}
-- Color overhaul for science packs
if reskins.lib.setting("bobmods-tech-colorupdate") == true and reskins.lib.setting("reskins-lib-customize-tier-colors") == true then
items["automation-science-pack"] = {tier = 1}
items["logistic-science-pack"] = {tier = 2}
items["chemical-science-pack"] = {tier = 3}
items["production-science-pack"] = {tier = 4}
items["utility-science-pack"] = {tier = 5}
end
-- Burner phase is enabled
if reskins.lib.setting("bobmods-burnerphase") == true then
items["steam-science-pack"] = {subgroup = "science-pack", flat_icon = true}
end
-- Alien science packs
if reskins.lib.setting("bobmods-enemies-enablenewartifacts") == true then
items["alien-science-pack"] = {subgroup = "alien-science-pack", flat_icon = true}
items["alien-science-pack-blue"] = {subgroup = "alien-science-pack", flat_icon = true}
items["alien-science-pack-orange"] = {subgroup = "alien-science-pack", flat_icon = true}
items["alien-science-pack-purple"] = {subgroup = "alien-science-pack", flat_icon = true}
items["alien-science-pack-yellow"] = {subgroup = "alien-science-pack", flat_icon = true}
items["alien-science-pack-green"] = {subgroup = "alien-science-pack", flat_icon = true}
items["alien-science-pack-red"] = {subgroup = "alien-science-pack", flat_icon = true}
items["science-pack-gold"] = {subgroup = "alien-science-pack", flat_icon = true}
end
reskins.lib.create_icons_from_list(items, inputs) |
--[[----------------------------------------------------------------------------
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
------------------------------------------------------------------------------]]
-- fine-tuning of pretrained inception-v3 trained by google and converted to
-- torch using https://github.com/Moodstocks/inception-v3.torch
require 'cudnn'
require 'cunn'
require 'inn'
require 'fbcoco'
inn.utils = require 'inn.utils'
local utils = paths.dofile'model_utils.lua'
local net = torch.load'./data/models/inceptionv3.t7'
local input = torch.randn(1,3,299,299):cuda()
local output1 = net:forward(input):clone()
utils.BNtoFixed(net, true)
local output2 = net:forward(input):clone()
assert((output1 - output2):abs():max() < 1e-5)
local features = nn.Sequential()
local classifier = nn.Sequential()
for i=1,25 do features:add(net:get(i)) end
for i=26,30 do classifier:add(net:get(i)) end
utils.testSurgery(input, utils.disableFeatureBackprop, features, 16)
utils.testSurgery(input, inn.utils.foldBatchNorm, features:findModules'nn.NoBackprop'[1])
local model = nn.Sequential()
:add(nn.ParallelTable()
:add(utils.makeDataParallel(features))
:add(nn.Identity())
)
:add(inn.ROIPooling(17,17):setSpatialScale(17/299))
:add(utils.makeDataParallel(classifier))
:add(utils.classAndBBoxLinear(2048))
model:cuda()
model.input_size = 299 -- for utils.testModel
utils.testModel(model)
return {model, fbcoco.ImageTransformer({1,1,1},nil,2)}
|
local LibNumbers = Wheel("LibNumbers")
assert(LibNumbers, "GenericXP requires LibNumbers to be loaded.")
-- Lua API
local _G = _G
local math_floor = math.floor
local math_min = math.min
local tonumber = tonumber
local tostring = tostring
-- WoW API
local GetRestState = GetRestState
local GetTimeToWellRested = GetTimeToWellRested
local GetXPExhaustion = GetXPExhaustion
local IsResting = IsResting
local UnitXP = UnitXP
local UnitXPMax = UnitXPMax
-- Number Abbreviation
local short = LibNumbers:GetNumberAbbreviationShort()
local large = LibNumbers:GetNumberAbbreviationLong()
local UpdateValue = function(element, min, max, restedLeft, restedTimeLeft)
local value = element.Value or element:IsObjectType("FontString") and element
if value.showPercent then
if (max > 0) then
local perc = math_floor(min/max*100)
if (perc == 100) and (min < max) then
perc = 99
end
if (perc >= 1) then
value:SetFormattedText("%.0f%%", perc)
else
value:SetText(_G.XP)
end
else
value:SetText("")
end
elseif value.showDeficit then
value:SetFormattedText(short(max - min))
else
value:SetFormattedText(short(min))
end
local percent = value.Percent
if percent then
if (max > 0) then
local perc = math_floor(min/max*100)
if (perc == 100) and (min < max) then
perc = 99
end
if (perc >= 1) then
percent:SetFormattedText("%.0f%%", perc)
else
percent:SetText(_G.XP)
end
else
percent:SetText("")
end
end
if element.colorValue then
local color
if restedLeft then
local colors = element._owner.colors
color = colors.restedValue or colors.rested or colors.xpValue or colors.xp
else
local colors = element._owner.colors
color = colors.xpValue or colors.xp
end
value:SetTextColor(color[1], color[2], color[3])
if percent then
percent:SetTextColor(color[1], color[2], color[3])
end
end
end
local Update = function(self, event, ...)
local element = self.XP
if element.PreUpdate then
element:PreUpdate()
end
local resting = IsResting()
local restState, restedName, mult = GetRestState()
local restedLeft, restedTimeLeft = GetXPExhaustion(), GetTimeToWellRested()
local min = UnitXP("player") or 0
local max = UnitXPMax("player") or 0
if element:IsObjectType("StatusBar") then
element:SetMinMaxValues(0, max)
element:SetValue(min)
if element.colorXP then
local color = self.colors[restedLeft and "rested" or "xp"]
element:SetStatusBarColor(color[1], color[2], color[3])
end
end
if element.Value then
(element.OverrideValue or element.UpdateValue) (element, min, max, restedLeft, restedTimeLeft)
end
if element.Rested then
if element.Rested:IsObjectType("StatusBar") then
element.Rested:SetMinMaxValues(0, max)
element.Rested:SetValue(math_min(max, min + (restedLeft or 0)))
if element.colorRested then
local color = self.colors.restedBonus
element.Rested:SetStatusBarColor(color[1], color[2], color[3])
end
end
if (not element.Rested:IsShown()) then
element.Rested:Show()
end
end
if (not element:IsShown()) then
element:Show()
end
if element.PostUpdate then
element:PostUpdate(min, max, restedLeft, restedTimeLeft)
end
end
local Proxy = function(self, ...)
return (self.XP.Override or Update)(self, ...)
end
local ForceUpdate = function(element, ...)
return Proxy(element._owner, "Forced", ...)
end
local Enable = function(self)
local element = self.XP
if element then
element._owner = self
element.ForceUpdate = ForceUpdate
element.UpdateValue = UpdateValue
self:RegisterEvent("PLAYER_ENTERING_WORLD", Proxy, true)
self:RegisterEvent("PLAYER_LOGIN", Proxy, true)
self:RegisterEvent("PLAYER_ALIVE", Proxy, true)
self:RegisterEvent("PLAYER_LEVEL_UP", Proxy, true)
self:RegisterEvent("PLAYER_XP_UPDATE", Proxy, true)
self:RegisterEvent("PLAYER_FLAGS_CHANGED", Proxy, true)
self:RegisterEvent("DISABLE_XP_GAIN", Proxy, true)
self:RegisterEvent("ENABLE_XP_GAIN", Proxy, true)
self:RegisterEvent("PLAYER_UPDATE_RESTING", Proxy, true)
return true
end
end
local Disable = function(self)
local element = self.XP
if element then
if element.Rested then
element.Rested:Hide()
end
self:UnregisterEvent("PLAYER_ENTERING_WORLD", Proxy)
self:UnregisterEvent("PLAYER_LOGIN", Proxy)
self:UnregisterEvent("PLAYER_ALIVE", Proxy)
self:UnregisterEvent("PLAYER_LEVEL_UP", Proxy)
self:UnregisterEvent("PLAYER_XP_UPDATE", Proxy)
self:UnregisterEvent("PLAYER_FLAGS_CHANGED", Proxy)
self:UnregisterEvent("DISABLE_XP_GAIN", Proxy)
self:UnregisterEvent("ENABLE_XP_GAIN", Proxy)
self:UnregisterEvent("PLAYER_UPDATE_RESTING", Proxy)
end
end
-- Register it with compatible libraries
for _,Lib in ipairs({ (Wheel("LibUnitFrame", true)), (Wheel("LibNamePlate", true)), (Wheel("LibMinimap", true)) }) do
Lib:RegisterElement("XP", Enable, Disable, Proxy, 13)
end
|
if not PriceTracker then
return
end
local PriceTracker = PriceTracker
local PriceTrackerEnchantingTable = {}
PriceTracker.enchantingTable = PriceTrackerEnchantingTable
PriceTrackerEnchantingTable.enchanting = ENCHANTING
PriceTrackerEnchantingTable.enchantingRunes = {
potency = {
bagId = nil,
itemIndex = nil
},
essence = {
bagId = nil,
itemIndex = nil
},
aspect = {
bagId = nil,
itemIndex = nil
}
}
function PriceTrackerEnchantingTable:OnLoad(eventCode, addOnName)
if(addOnName ~= "PriceTracker") then return end
ZO_PreHookHandler(self.enchanting.runeSlots[1].control, "OnUpdate", function() self:OnUpdateEnchantingRune(self.enchanting.runeSlots[1], "aspect") end)
ZO_PreHookHandler(self.enchanting.runeSlots[2].control, "OnUpdate", function() self:OnUpdateEnchantingRune(self.enchanting.runeSlots[2], "essence") end)
ZO_PreHookHandler(self.enchanting.runeSlots[3].control, "OnUpdate", function() self:OnUpdateEnchantingRune(self.enchanting.runeSlots[3], "potency") end)
ZO_PreHookHandler(self.enchanting.resultTooltip, "OnHide", function() PriceTracker:OnHideTooltip(self.enchanting.resultTooltip) end)
end
function PriceTrackerEnchantingTable:OnUpdateEnchantingRune(rune, runeType)
if rune.bagId == self.enchantingRunes[runeType].bagId and rune.slotIndex == self.enchantingRunes[runeType].itemIndex then return end
self.enchantingRunes[runeType].bagId = rune.bagId
self.enchantingRunes[runeType].itemIndex = rune.slotIndex
self:UpdateEnchantingTooltip()
end
function PriceTrackerEnchantingTable:UpdateEnchantingTooltip()
if not self.enchantingRunes.potency.bagId or not self.enchantingRunes.potency.itemIndex or
not self.enchantingRunes.essence.bagId or not self.enchantingRunes.essence.itemIndex or
not self.enchantingRunes.aspect.bagId or not self.enchantingRunes.aspect.itemIndex then return end
local name, icon, stack, sellPrice, meetsUsageRequirement, quality =
GetEnchantingResultingItemInfo(self.enchantingRunes.potency.bagId, self.enchantingRunes.potency.itemIndex,
self.enchantingRunes.essence.bagId, self.enchantingRunes.essence.itemIndex,
self.enchantingRunes.aspect.bagId, self.enchantingRunes.aspect.itemIndex)
local _, _, _, itemId, level =
ZO_LinkHandler_ParseLink(GetEnchantingResultingItemLink(self.enchantingRunes.potency.bagId, self.enchantingRunes.potency.itemIndex,
self.enchantingRunes.essence.bagId, self.enchantingRunes.essence.itemIndex,
self.enchantingRunes.aspect.bagId, self.enchantingRunes.aspect.itemIndex))
local item = {
dataEntry = {
data = {
name = name,
stackCount = 1,
purchasePrice = sellPrice,
itemId = itemId,
level = level,
quality = quality,
}
}
}
if(meetsUsageRequirement) then
PriceTracker:OnUpdateTooltip(item, self.enchanting.resultTooltip)
end
end
|
return {'timbaal','timbre','time','timemanagement','timen','timer','timesharing','timide','timiditeit','timing','timmeraar','timmerage','timmerbedrijf','timmerdoos','timmeren','timmerfabriek','timmergereedschap','timmerhout','timmering','timmerloods','timmerman','timmermansbaas','timmermansjongen','timmermansoog','timmermanspotlood','timmermanswerkplaats','timmermanszoon','timmerwerf','timmerwerk','timmerwerkplaats','timmerwinkel','timocratie','timotheegras','timp','timpaan','timpen','timmerindustrie','timorees','tim','timanrug','timboektoe','timmermans','timo','timothy','timmers','timber','timme','timmie','timmy','timon','timoteus','timur','timman','timp','timan','timisela','timbres','timers','timider','timmer','timmeraars','timmerde','timmerden','timmerdozen','timmergereedschappen','timmeringen','timmerlieden','timmerlui','timmermanswerkplaatsen','timmert','timmerwerken','timmerwerven','timmerwinkels','timpaantje','timpaantjes','timpanen','timede','timet','timmerende','timmermannen','timmermanspotloden','timbalen','timmermansogen','tims','timbers','timmes','timmies','timmys','timos','timons','timoteus','timothys','timurs','timmerfabrieken','timmerwerkplaatsen','timorezen'} |
local Hamming = {}
function Hamming.compute(a,b)
if #a ~= #b then return -1 end
local distance = 0
for i = 1, a:len() do
if (a:sub(i, i) ~= b:sub(i, i)) then
distance = distance + 1
end
end
return distance
end
return Hamming
|
--
-- Author: SunLightJuly
-- Date: 2014-07-29 16:56:47
--
local ArmatureTestLayer = require("layers.ArmatureTestLayer")
local TestArmatureNesting = class("TestArmatureNesting", ArmatureTestLayer)
function TestArmatureNesting:ctor(index)
TestArmatureNesting.super.ctor(self)
self:creatTitleAndSubTitle(index)
end
function TestArmatureNesting:onEnter()
self.weaponIndex = 0
self.armature = ccs.Armature:create("cyborg")
self.armature:getAnimation():playWithIndex(1)
self.armature:setPosition(display.cx, display.cy)
self.armature:setScale(1.2)
self.armature:getAnimation():setSpeedScale(0.4)
self:addChild(self.armature)
local function onTouchEnded(touches, event)
self.weaponIndex = (self.weaponIndex + 1) % 4
self.armature:getBone("armInside"):getChildArmature():getAnimation():playWithIndex(self.weaponIndex)
self.armature:getBone("armOutside"):getChildArmature():getAnimation():playWithIndex(self.weaponIndex)
end
self:addNodeEventListener(cc.NODE_TOUCH_EVENT, function(event)
if event.name=='began' then
return true
elseif event.name=='ended' then
onTouchEnded()
end
end)
end
return TestArmatureNesting |
HOME = os.getenv("HOME")
CONFIG_DIR = (os.getenv("XDG_CONFIG_HOME") or HOME .. "/.config") .. "/awesome"
user = {
terminal = os.getenv("TERMINAL") or "xterm",
editor = os.getenv("EDITOR") or "vim",
}
-- If LuaRocks is installed, make sure that packages installed through it are
-- found (e.g. lgi). If LuaRocks is not installed, do nothing.
pcall(require, "luarocks.loader")
-- Load libraries
local gears = require("gears")
local awful = require("awful")
require("awful.autofocus")
local wibox = require("wibox")
local beautiful = require("beautiful")
local naughty = require("naughty")
local menubar = require("menubar")
local hotkeys_popup = require("awful.hotkeys_popup")
-- Load theme
beautiful.init(CONFIG_DIR .. "/theme.lua")
-- Handle runtime errors after startup
do
local in_error = false
awesome.connect_signal("debug::error", function(err)
-- Make sure we don't go into an endless error loop
if in_error then return end
in_error = true
naughty.notify {
preset = naughty.config.presets.critical,
title = "An error happened!",
text = tostring(err)
}
in_error = false
end)
end
local kb = require("kb")
-- Table of layouts to cover with awful.layout.inc, order matters.
awful.layout.layouts = {
awful.layout.suit.tile,
awful.layout.suit.max,
}
-- Menubar configuration
menubar.utils.terminal = terminal -- Set the terminal for applications that require it
-- Wibar {{{
-- Create a textclock widget
local text_clock = wibox.widget.textclock()
text_clock.format = " %a, %Y-%m-%d %H:%M "
-- Create a wibox for each screen and add it
local taglist_buttons = gears.table.join(
awful.button({}, 1, function(t) t:view_only() end),
awful.button({modkey}, 1, function(t)
if client.focus then
client.focus:move_to_tag(t)
end
end),
awful.button({}, 3, awful.tag.viewtoggle),
awful.button({modkey}, 3, function(t)
if client.focus then
client.focus:toggle_tag(t)
end
end),
awful.button({}, 4, function(t) awful.tag.viewprev(t.screen) end),
awful.button({}, 5, function(t) awful.tag.viewnext(t.screen) end)
)
local tasklist_buttons = gears.table.join(
awful.button({}, 1, function(c)
if c == client.focus then
c.minimized = true
else
c:emit_signal(
"request::activate",
"tasklist",
{raise = true}
)
end
end),
awful.button({}, 3, function()
awful.menu.client_list({ theme = { width = 250 } })
end),
awful.button({}, 4, function() awful.client.focus.byidx(-1) end),
awful.button({}, 5, function() awful.client.focus.byidx(1) end)
)
-- Re-set wallpaper when a screen's geometry changes (e.g. different resolution)
-- screen.connect_signal("property::geometry", set_wallpaper)
awful.screen.connect_for_each_screen(function(s)
awful.tag({"1", "2", "3", "4", "5", "6", "7", "8", "9"}, s, awful.layout.layouts[1])
-- Create a promptbox for each screen
s.mypromptbox = awful.widget.prompt()
-- Create an imagebox widget which will contain an icon indicating which layout we're using.
-- We need one layoutbox per screen.
s.mylayoutbox = awful.widget.layoutbox(s)
s.mylayoutbox:buttons(gears.table.join(
awful.button({}, 1, function() awful.layout.inc( 1) end),
awful.button({}, 3, function() awful.layout.inc(-1) end),
awful.button({}, 4, function() awful.layout.inc( 1) end),
awful.button({}, 5, function() awful.layout.inc(-1) end))
)
s.mytaglist = awful.widget.taglist {
screen = s,
filter = awful.widget.taglist.filter.all,
buttons = taglist_buttons,
layout = { layout = wibox.layout.fixed.horizontal },
}
s.mytasklist = awful.widget.tasklist {
screen = s,
filter = awful.widget.tasklist.filter.currenttags,
buttons = tasklist_buttons,
style = {
shape = gears.shape.rounded_bar,
},
layout = {
spacing = 10,
spacing_widget = {
{
forced_width = 5,
shape = gears.shape.circle,
widget = wibox.widget.separator
},
valign = 'center',
halign = 'center',
widget = wibox.container.place,
},
layout = wibox.layout.flex.horizontal
},
widget_template = {
{
{
{
id = 'text_role',
widget = wibox.widget.textbox,
},
layout = wibox.layout.fixed.horizontal,
},
left = 10,
right = 10,
widget = wibox.container.margin
},
id = 'background_role',
widget = wibox.container.background,
},
}
-- Create the wibox
s.mywibox = awful.wibar {
position = "top",
screen = s,
height = 19,
}
-- Add widgets to the wibox
s.mywibox:setup {
layout = wibox.layout.align.horizontal,
{ -- Left widgets
layout = wibox.layout.fixed.horizontal,
-- launcher,
s.mytaglist,
s.mypromptbox,
},
s.mytasklist, -- Middle widget
{ -- Right widgets
layout = wibox.layout.fixed.horizontal,
-- awful.widget.keyboardlayout(),
wibox.widget.systray(),
text_clock,
s.mylayoutbox,
},
}
end)
-- }}}
-- Rules {{{
-- Rules to apply to new clients (through the "manage" signal).
awful.rules.rules = {
-- All clients will match this rule.
{
rule = {},
properties = { border_width = beautiful.border_width,
border_color = beautiful.border_normal,
focus = awful.client.focus.filter,
raise = true,
keys = kb.client_keys,
buttons = kb.client_btn,
screen = awful.screen.preferred,
placement = awful.placement.no_overlap+awful.placement.no_offscreen
},
},
-- Floating clients.
{
rule_any = {
instance = {
"DTA", -- Firefox addon DownThemAll.
"copyq", -- Includes session name in class.
"pinentry",
},
class = {
"Arandr",
"Blueman-manager",
"Gpick",
"Kruler",
"MessageWin", -- kalarm.
"Sxiv",
"Tor Browser", -- Needs a fixed window size to avoid fingerprinting by screen size.
"Wpa_gui",
"veromix",
"xtightvncviewer"
},
-- Note that the name property shown in xprop might be set slightly after creation of the client
-- and the name shown there might not match defined rules here.
name = {
"Event Tester", -- xev.
},
role = {
"AlarmWindow", -- Thunderbird's calendar.
"ConfigManager", -- Thunderbird's about:config.
"pop-up", -- e.g. Google Chrome's (detached) Developer Tools.
},
},
properties = {floating = true},
},
-- Add titlebars to normal clients and dialogs
{
rule_any = {
type = {"normal", "dialog"}
},
properties = {titlebars_enabled = false},
},
-- Set Firefox to always map on the tag named "2" on screen 1.
-- { rule = { class = "Firefox" },
-- properties = { screen = 1, tag = "2" } },
}
-- }}}
-- Signals {{{
-- Signal function to execute when a new client appears.
client.connect_signal("manage", function(c)
-- Set the windows at the slave,
-- i.e. put it at the end of others instead of setting it master.
-- if not awesome.startup then awful.client.setslave(c) end
if awesome.startup
and not c.size_hints.user_position
and not c.size_hints.program_position then
-- Prevent clients from being unreachable after screen count changes.
awful.placement.no_offscreen(c)
end
end)
-- Add a titlebar if titlebars_enabled is set to true in the rules.
client.connect_signal("request::titlebars", function(c)
-- buttons for the titlebar
local buttons = gears.table.join(
awful.button({}, 1, function()
c:emit_signal("request::activate", "titlebar", {raise = true})
awful.mouse.client.move(c)
end),
awful.button({}, 3, function()
c:emit_signal("request::activate", "titlebar", {raise = true})
awful.mouse.client.resize(c)
end)
)
awful.titlebar(c):setup {
{ -- Left
awful.titlebar.widget.iconwidget(c),
buttons = buttons,
layout = wibox.layout.fixed.horizontal
},
{ -- Middle
{ -- Title
align = "center",
widget = awful.titlebar.widget.titlewidget(c)
},
buttons = buttons,
layout = wibox.layout.flex.horizontal
},
{ -- Right
-- awful.titlebar.widget.floatingbutton(c),
-- awful.titlebar.widget.maximizedbutton(c),
-- awful.titlebar.widget.stickybutton(c),
-- awful.titlebar.widget.ontopbutton(c),
awful.titlebar.widget.closebutton(c),
layout = wibox.layout.fixed.horizontal(),
},
layout = wibox.layout.align.horizontal
}
end)
-- Enable sloppy focus, so that focus follows mouse.
client.connect_signal("mouse::enter", function(c)
c:emit_signal("request::activate", "mouse_enter", {raise = false})
end)
client.connect_signal("focus", function(c) c.border_color = beautiful.border_focus end)
client.connect_signal("unfocus", function(c) c.border_color = beautiful.border_normal end)
-- }}}
|
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf/protobuf"
module('TeamCountClient_pb')
TEAMCOUNTCLIENT = protobuf.Descriptor();
local TEAMCOUNTCLIENT_TEAMTYPE_FIELD = protobuf.FieldDescriptor();
local TEAMCOUNTCLIENT_LEFTCOUNT_FIELD = protobuf.FieldDescriptor();
local TEAMCOUNTCLIENT_BUYCOUNT_FIELD = protobuf.FieldDescriptor();
local TEAMCOUNTCLIENT_MAXCOUNT_FIELD = protobuf.FieldDescriptor();
TEAMCOUNTCLIENT_TEAMTYPE_FIELD.name = "teamtype"
TEAMCOUNTCLIENT_TEAMTYPE_FIELD.full_name = ".KKSG.TeamCountClient.teamtype"
TEAMCOUNTCLIENT_TEAMTYPE_FIELD.number = 1
TEAMCOUNTCLIENT_TEAMTYPE_FIELD.index = 0
TEAMCOUNTCLIENT_TEAMTYPE_FIELD.label = 1
TEAMCOUNTCLIENT_TEAMTYPE_FIELD.has_default_value = false
TEAMCOUNTCLIENT_TEAMTYPE_FIELD.default_value = 0
TEAMCOUNTCLIENT_TEAMTYPE_FIELD.type = 5
TEAMCOUNTCLIENT_TEAMTYPE_FIELD.cpp_type = 1
TEAMCOUNTCLIENT_LEFTCOUNT_FIELD.name = "leftcount"
TEAMCOUNTCLIENT_LEFTCOUNT_FIELD.full_name = ".KKSG.TeamCountClient.leftcount"
TEAMCOUNTCLIENT_LEFTCOUNT_FIELD.number = 2
TEAMCOUNTCLIENT_LEFTCOUNT_FIELD.index = 1
TEAMCOUNTCLIENT_LEFTCOUNT_FIELD.label = 1
TEAMCOUNTCLIENT_LEFTCOUNT_FIELD.has_default_value = false
TEAMCOUNTCLIENT_LEFTCOUNT_FIELD.default_value = 0
TEAMCOUNTCLIENT_LEFTCOUNT_FIELD.type = 5
TEAMCOUNTCLIENT_LEFTCOUNT_FIELD.cpp_type = 1
TEAMCOUNTCLIENT_BUYCOUNT_FIELD.name = "buycount"
TEAMCOUNTCLIENT_BUYCOUNT_FIELD.full_name = ".KKSG.TeamCountClient.buycount"
TEAMCOUNTCLIENT_BUYCOUNT_FIELD.number = 3
TEAMCOUNTCLIENT_BUYCOUNT_FIELD.index = 2
TEAMCOUNTCLIENT_BUYCOUNT_FIELD.label = 1
TEAMCOUNTCLIENT_BUYCOUNT_FIELD.has_default_value = false
TEAMCOUNTCLIENT_BUYCOUNT_FIELD.default_value = 0
TEAMCOUNTCLIENT_BUYCOUNT_FIELD.type = 5
TEAMCOUNTCLIENT_BUYCOUNT_FIELD.cpp_type = 1
TEAMCOUNTCLIENT_MAXCOUNT_FIELD.name = "maxcount"
TEAMCOUNTCLIENT_MAXCOUNT_FIELD.full_name = ".KKSG.TeamCountClient.maxcount"
TEAMCOUNTCLIENT_MAXCOUNT_FIELD.number = 4
TEAMCOUNTCLIENT_MAXCOUNT_FIELD.index = 3
TEAMCOUNTCLIENT_MAXCOUNT_FIELD.label = 1
TEAMCOUNTCLIENT_MAXCOUNT_FIELD.has_default_value = false
TEAMCOUNTCLIENT_MAXCOUNT_FIELD.default_value = 0
TEAMCOUNTCLIENT_MAXCOUNT_FIELD.type = 5
TEAMCOUNTCLIENT_MAXCOUNT_FIELD.cpp_type = 1
TEAMCOUNTCLIENT.name = "TeamCountClient"
TEAMCOUNTCLIENT.full_name = ".KKSG.TeamCountClient"
TEAMCOUNTCLIENT.nested_types = {}
TEAMCOUNTCLIENT.enum_types = {}
TEAMCOUNTCLIENT.fields = {TEAMCOUNTCLIENT_TEAMTYPE_FIELD, TEAMCOUNTCLIENT_LEFTCOUNT_FIELD, TEAMCOUNTCLIENT_BUYCOUNT_FIELD, TEAMCOUNTCLIENT_MAXCOUNT_FIELD}
TEAMCOUNTCLIENT.is_extendable = false
TEAMCOUNTCLIENT.extensions = {}
TeamCountClient = protobuf.Message(TEAMCOUNTCLIENT)
|
local Players = game:GetService("Players")
local LocalPlayer = Players.LocalPlayer
local PlayerGui = LocalPlayer:WaitForChild("PlayerGui")
script.Parent.ShowAndLeave.Enabled = true
local showButton = script.Parent.ShowAndLeave.EditAvatarButton
local leaveButton = script.Parent.ShowAndLeave.LeaveButton
local AvatarEditorInterface = require(script.Parent.AvatarEditorInterface)
local touchGuiWasEnabled = false
local function showAvatarEditor()
showButton.Visible = false
local touchGui = PlayerGui:FindFirstChild("TouchGui")
if touchGui then
touchGuiWasEnabled = touchGui.Enabled
touchGui.Enabled = false
end
AvatarEditorInterface:showAvatarEditor()
leaveButton.Visible = true
end
local leaving = false
local function hideAvatarEditor()
if leaving then
return
end
leaving = true
AvatarEditorInterface:hideAvatarEditor(--[[saveOnClose =]] true)
local touchGui = PlayerGui:FindFirstChild("TouchGui")
if touchGui then
touchGui.Enabled = touchGuiWasEnabled
end
game.Workspace.CurrentCamera.CameraType = Enum.CameraType.Custom
if LocalPlayer.Character then
local humanoid = LocalPlayer.Character:FindFirstChildWhichIsA("Humanoid")
if humanoid then
game.Workspace.CurrentCamera.CameraSubject = humanoid
end
end
leaveButton.Visible = false
showButton.Visible = true
leaving = false
end
showButton.Activated:connect(function()
showAvatarEditor()
end)
leaveButton.Activated:connect(function()
hideAvatarEditor()
end)
|
return {
summary = 'Get the size of the Blob\'s data.',
description = [[
Returns the size of the Blob's contents, in bytes.
]],
arguments = {},
returns = {
{
name = 'bytes',
type = 'number',
description = 'The size of the Blob, in bytes.'
}
}
}
|
-- Based on http://lua-users.org/wiki/SimpleLuaClasses
-- Simplified to remove inheritance
--
-- Example:
--
-- Person = class()
--
-- function Person:__init(name, age)
-- self.name = name
-- self.age = age
-- end
--
-- function Person:sayHi()
-- print("Hi, my name is " .. self.name)
-- end
--
-- Bob = Person("Bob", 41)
-- Bob:sayHi()
function class()
local c = {} -- a new class instance
-- the class will be the metatable for all its objects,
-- and they will look up their methods in it.
c.__index = c
-- expose a constructor which can be called by <classname>(<args>)
local mt = {}
mt.__call = function(class_tbl, ...)
local obj = {}
setmetatable(obj, c)
-- call the class:__init method if it's been defined
if class_tbl.__init then
class_tbl.__init(obj, ...)
end
return obj
end
setmetatable(c, mt)
return c
end
|
-- Vaygr
supplyLimit("Fighter", 135);
supplyLimit("Scout", 30);
supplyLimit("Interceptor", 135);
supplyLimit("Bomber", 135);
supplyLimit("LanceFighter", 135);
supplyLimit("Capital", 26);
supplyLimit("Carrier", 5);
|
local Vector2 = require('geometry.vector2')
local DiskObstacle = require('geometry.disk')
local SegSeqObstacle = require('geometry.segseq')
local Obstacle = require('core.obstacle')
local Vehicle = require('core.vehicle')
local FollowPath = require('steering.follow_path')
local Space = require('core.space')
local World = require('core.world')
local ScenarioHelpers = require('scenarios.helpers')
local Panicker = require('scenarios.panic.panicker')
-- Construct the environment.
local width = 800
local height = 600
local space = Space.Regular(width, height)
local world = World(width, height)
-- Construct the room to be escaped.
local offset = 125
local seq = { Vector2(-offset, -15),
Vector2(-offset, -offset),
Vector2( offset, -offset),
Vector2( offset, offset),
Vector2(-offset, offset),
Vector2(-offset, 15) }
world:add_obstacle(Obstacle(space, 'segseq', Vector2(), SegSeqObstacle(seq)))
-- Create panicked characters.
local disk = DiskObstacle(5)
local steering = FollowPath(Vector2(), Vector2(-10000, 0), 10)
local create_character = function (position)
local vehicle = Vehicle(space, 'character1', position, disk, 50, 50)
local panicker = Panicker(vehicle, 5)
panicker.steering = steering
return panicker
end
-- Populate room with characters.
for _, position in pairs(ScenarioHelpers.radial_points(Vector2(), 90, 25)) do
world:add_character(create_character(position))
end
for _, position in pairs(ScenarioHelpers.radial_points(Vector2(), 60, 15)) do
world:add_character(create_character(position))
end
for _, position in pairs(ScenarioHelpers.radial_points(Vector2(), 30, 10)) do
world:add_character(create_character(position))
end
return world
|
-- Plane of Earth
function events.AfterLoadMap()
Party.QBits[930] = true -- DDMapBuff, changed for rev4 for merge
end
|
local M = {}
local char_to_hex = function(c)
return ("%%%02X"):format(c:byte())
end
local encode = function(url)
url = url:gsub("\n", "\r\n")
url = url:gsub("([^%w _%%%-%.~/:%?@=&#])", char_to_hex)
url = url:gsub(" ", "+")
return url
end
function M.collect(self)
local file_path = self.pathlib.user_data_path("url_bookmark.txt")
if self.filelib.create_if_need(file_path) then
local f = io.open(file_path, "w")
f:write("sample\thttps://github.com/notomo/dotfiles")
f:close()
end
local items = {}
local f = io.open(file_path, "r")
local i = 1
for line in f:lines() do
local url = encode(vim.fn.reverse(vim.split(line, "\t", true))[1])
table.insert(items, {value = line, path = file_path, row = i, url = url})
i = i + 1
end
f:close()
return items
end
M.kind_name = "file"
return M
|
local utils = require("jupyter-nvim.utils")
local config = require("jupyter-nvim.config")
local M = {}
M.setup = config.setup
M.utils = utils
return M
|
--- Simple, non-blocking, TCP socket server that listens for
-- clients on a specific port and for each connection
-- polls for data.
--
-- @usage
--
-- local function on_data(data, ip)
-- print("Received", data, "from", ip)
-- return "My response"
-- end
--
-- local function on_client_connected(ip)
-- print("Client", ip, "connected")
-- end
--
-- local function on_client_disconnected(ip)
-- print("Client", ip, "disconnected")
-- end
--
-- function init(self)
-- self.server = tcp_server.create(8190, on_data, on_client_connected, on_client_disconnected)
-- self.server.start()
-- end
--
-- function final(self)
-- self.server.stop()
-- end
--
-- function update(self, dt)
-- self.server.update()
-- end
--
local socket = require "socket.socket"
local tcp_send_queue = require "defnet.tcp_send_queue"
local M = {}
M.TCP_SEND_CHUNK_SIZE = 8192
--- Creates a new TCP socket server
-- @param port
-- @param on_data Function to call when data is received. The
-- function will be called with the following args: data, ip
-- Any value returned from this function will be sent as response.
-- @param on_client_connected Function to call when a client has
-- connected. The function will be called with the following args: ip
-- @param on_client_disconnected Function to call when a client has
-- disconnected. The function will be called with the following args: ip
-- @return Server instance
function M.create(port, on_data, on_client_connected, on_client_disconnected)
assert(port, "You must provide a port")
assert(on_data, "You must provide an on_data function")
print("Creating TCP server")
local server = {}
local co = nil
local server_socket = nil
local clients = {}
local queues = {}
local function remove_client(connection_to_remove)
for i,connection in pairs(clients) do
if connection == connection_to_remove then
table.remove(clients, i)
queues[connection_to_remove] = nil
if on_client_disconnected then
local client_ip, client_port = connection:getsockname()
on_client_disconnected(client_ip, client_port)
end
break
end
end
end
--- Start the TCP socket server and listen for clients
-- Each connection is run in it's own coroutine
-- @return success
-- @return error_message
function server.start()
print("Starting TCP server on port " .. port)
local ok, err = pcall(function()
local skt, err = socket.bind("*", port)
assert(skt, err)
server_socket = skt
server_socket:settimeout(0)
end)
if not server_socket or err then
print("Unable to start TCP server", err)
return false, err
end
return true
end
--- Stop the TCP socket server. The socket and all
-- clients will be closed
function server.stop()
if server_socket then
server_socket:close()
end
while #clients > 0 do
local client = table.remove(clients)
queues[client] = nil
client:close()
end
end
function server.receive(client)
return client:receive("*l")
end
function server.send(data)
for client,queue in pairs(queues) do
queue.add(data)
end
end
--- Update the TCP socket server. This will resume all
-- the spawned coroutines in order to check for new
-- clients and data on existing clients
function server.update()
if not server_socket then
return
end
-- new connection?
local client, err = server_socket:accept()
if client then
client:settimeout(0)
table.insert(clients, client)
queues[client] = tcp_send_queue.create(client, M.TCP_SEND_CHUNK_SIZE)
if on_client_connected then
local client_ip, client_port = client:getsockname()
on_client_connected(client_ip, client_port)
end
end
-- read from client sockets that has data
local read, write, err = socket.select(clients, nil, 0)
for _,client in ipairs(read) do
coroutine.wrap(function()
local data, err = server.receive(client)
if data and on_data then
local client_ip, client_port = client:getsockname()
local response = on_data(data, client_ip, client_port, function(response)
if not queues[client] then
return false
end
queues[client].add(response)
return true
end)
if response then
queues[client].add(response)
end
end
if err and err == "closed" then
print("Client connection closed")
remove_client(client)
end
end)()
end
-- send to client sockets that are writable
local read, write, err = socket.select(nil, clients, 0)
for _,client in ipairs(write) do
coroutine.wrap(function()
queues[client].send()
end)()
end
end
return server
end
return M
|
local HttpRequestAdapter = require("AlgoLua.Api.HttpRequestAdapter")
local json = require("AlgoLua.Libs.json")
local HttpClient = {}
local function _catch_response(on_success, on_error)
return function(_, _, http_response)
if (http_response and http_response.status == 200) then
local _, response = pcall(json.decode, http_response.response or "null")
if (on_success) then
on_success(response or nil)
end
elseif (on_error) then
on_error({
code = http_response.status,
status = http_response.status,
error_code = 1123,
error = "service_unavailable",
error_message = "Could not deserialize response from server: " .. tostring(http_response.response)
})
end
end
end
function HttpClient.request(method, full_url, body, headers, on_success, on_error)
if headers['Content-Type'] then
request_json = body
elseif method ~= "GET" and body then
local ok, request_json = pcall(json.encode, body)
if not ok then
on_error(request_json or "Request could not be converted to json")
end
end
local request_headers = {
["Content-Type"] = "application/json"
}
for k, v in pairs(headers) do request_headers[k] = v end
HttpRequestAdapter(
full_url,
method,
_catch_response(on_success, on_error),
request_headers,
request_json,
{} -- options
)
end
function HttpClient.get(full_url, headers, on_success, on_error)
HttpClient.request("GET", full_url, nil, headers, on_success, on_error)
end
function HttpClient.post(full_url, body, headers, on_success, on_error)
HttpClient.request("POST", full_url, body, headers, on_success, on_error)
end
function HttpClient.delete(full_url, headers, on_success, on_error)
HttpClient.request("DELETE", full_url, nil, headers, on_success, on_error)
end
return HttpClient
|
RPGM.RegisterScaledConstant("HUD.Minimap.Size", 240)
local rotation = Angle(0, 0, 0)
local lerpAngle = LerpAngle
local ft = FrameTime
local hasFocus = system.HasFocus
local function updateStats(ply)
if not hasFocus() then return ply:EyeAngles() end
local rot = ply:EyeAngles()
if ply:InVehicle() then
rot:Add(Angle(0, ply:GetVehicle():GetAngles().y, 0))
end
rotation = lerpAngle(ft() * 20, rotation, rot)
rotation[1] = 0
rotation[3] = 0
return rot
end
local newMatrix = Matrix
local newVector = Vector
local setScissorRect = render.SetScissorRect
local pushModelMatrix, popModelMatrix = cam.PushModelMatrix, cam.PopModelMatrix
local disableClipping = DisableClipping
local backgroundCol = RPGM.Colors.Background
local getScaledConstant = RPGM.GetScaledConstant
hook.Add("RPGM.DrawHUD", "RPGM.DrawMinimap", function(scrW, scrH, localPly)
local realRotation = updateStats(localPly)
local padding = getScaledConstant("HUD.Padding")
local mapSize = getScaledConstant("HUD.Minimap.Size")
local halfMapSize = mapSize * .5
local mapX, mapY = padding, padding
local mapCenterX, mapCenterY = mapX + halfMapSize, mapY + halfMapSize
surface.SetDrawColor(backgroundCol)
surface.DrawRect(mapX, mapY, mapSize, mapSize)
local layer = RPGM.MapData[1]
local scale = .3
local size = layer.size * scale
local halfSize = size * .5
local mapOffsetX, mapOffsetY
do
local pos = localPly:GetPos()
mapOffsetX, mapOffsetY = layer:worldToMap(pos[1], pos[2])
mapOffsetX, mapOffsetY = mapOffsetX * scale - size / 2, mapOffsetY * scale + size / 2
local mat = newMatrix()
mat:Translate(newVector(mapCenterX, mapCenterY))
mat:Rotate(rotation)
mat:Translate(newVector(-mapOffsetX, mapOffsetY))
setScissorRect(mapX, mapY, mapX + mapSize, mapY + mapSize, true)
pushModelMatrix(mat)
disableClipping(true)
local offset = -halfSize
RPGM.DrawSubpixelClippedMaterial(RPGM.MapMaterial, offset, offset, size, size)
disableClipping(false)
popModelMatrix()
setScissorRect(0, 0, 0, 0, false)
end
local plySize = RPGM.Scale(16)
RPGM.DrawImgurRotated(mapCenterX, mapCenterY, plySize, plySize, (realRotation - rotation)[2], "h4qOjrP", Color(200, 200, 200))
end) |
BuildEnv(...)
Area = Addon:NewClass('Area', Object)
function Area:Constructor(id, level)
self.id = id
self.level = level
end
function Area:GetID()
return self.id
end
function Area:GetLevel()
return self.level
end
function Area:GetMapID()
return MAP_FILE_TO_ID[self.id]
end
function Area:IsGarrsion()
return IsMapGarrisonMap(self:GetMapID())
end
function Area:GetToken(id, level)
return self.token or format('%d:%d', id or self.id, level or self.level)
end
function Area.Once:GetNpcList()
local list = {}
local token = self:GetToken()
for id, v in pairs(NPC_DATA) do
if v.Coords and v.Coords[token] then
tinsert(list, Npc:Get(id))
end
end
return list
end
function Area.Once:GetGameObjectList()
local list = {}
local token = self:GetToken()
for id, v in pairs(OBJECT_DATA) do
if v.Coords and v.Coords[token] then
tinsert(list, GameObject:Get(id))
end
end
return list
end
function Area:GetName()
SetMapByID(self:GetMapID())
SetDungeonMapLevel(self.level + (DungeonUsesTerrainMap() and 1 or 0))
local name = GetMapNameByID(self:GetMapID())
local levelName = _G['DUNGEON_FLOOR_' .. strupper(GetMapInfo() or '') .. self.level]
return levelName and levelName ~= name and name .. '-' .. levelName or name
end
function Area:GetNotCollectedCount()
local exists = {}
local counts = {}
for _, object in ipairs(self:GetGameObjectList()) do
for _, item in ipairs(object:GetDropList()) do
if not exists[item] and not item:IsCollected() and not item:IsHideOnChar() then
local klass = item:GetType()
exists[item] = true
counts[klass] = (counts[klass] or 0) + 1
end
end
end
for _, object in ipairs(self:GetNpcList()) do
for _, item in ipairs(object:GetDropList()) do
if not exists[item] and not item:IsCollected() and not item:IsHideOnChar() then
local klass = item:GetType()
exists[item] = true
counts[klass] = (counts[klass] or 0) + 1
end
end
for _, item in ipairs(object:GetSoldList()) do
if not exists[item] and not item:IsCollected() and not item:IsHideOnChar() then
local klass = item:GetType()
exists[item] = true
counts[klass] = (counts[klass] or 0) + 1
end
end
end
return counts[Mount] or 0, counts[Pet] or 0
end |
minetest.register_node("sponge:sponge", {
description = "Sponge Dry",
drawtype = "normal",
tiles = {"sponge_sponge.png"},
paramtype = 'light',
walkable = true,
pointable = true,
diggable = true,
buildable_to = false,
stack_max = 99,
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=3,flammable=3},
after_place_node = function(pos, placer, itemstack, pointed_thing)
local pn = placer:get_player_name()
if pointed_thing.type ~= "node" then
return
end
if minetest.is_protected(pointed_thing.above, pn) then
return
end
local change = false
local on_water = false
local p, n
-- verifier si il est dans l'eau ou a cotée
if string.find(minetest.get_node(pointed_thing.above).name, "water_source")
or string.find(minetest.get_node(pointed_thing.above).name, "water_flowing") then
on_water = true
end
for i=-1,1 do
p = {x=pos.x+i, y=pos.y, z=pos.z}
n = minetest.get_node(p)
-- On verifie si il y a de l'eau
if (n.name=="default:water_flowing") or (n.name == "default:water_source")
or (n.name == "default:river_water_flowing") or (n.name == "default:river_water_source") then
on_water = true
end
end
for i=-1,1 do
p = {x=pos.x, y=pos.y+i, z=pos.z}
n = minetest.get_node(p)
-- On verifie si il y a de l'eau
if (n.name=="default:water_flowing") or (n.name == "default:water_source")
or (n.name == "default:river_water_flowing") or (n.name == "default:river_water_source") then
on_water = true
end
end
for i=-1,1 do
p = {x=pos.x, y=pos.y, z=pos.z+i}
n = minetest.get_node(p)
-- On verifie si il y a de l'eau
if (n.name=="default:water_flowing") or (n.name == "default:water_source")
or (n.name == "default:river_water_flowing") or (n.name == "default:river_water_source") then
on_water = true
end
end
if on_water == true then
for i=-3,3 do
for j=-3,3 do
for k=-3,3 do
p = {x=pos.x+i, y=pos.y+j, z=pos.z+k}
n = minetest.get_node(p)
-- On Supprime l'eau
if (n.name=="default:water_flowing") or (n.name == "default:water_source")
or (n.name == "default:river_water_flowing") or (n.name == "default:river_water_source") then
minetest.add_node(p, {name="air"})
change = true
end
end
end
end
end
if change then
minetest.add_node(pos, {name = "sponge:sponge_wet"})
end
end
})
minetest.register_node("sponge:sponge_wet", {
description = "Wet Sponge",
drawtype = "normal",
tiles = {"sponge_sponge_wet.png"},
paramtype = 'light',
walkable = true,
pointable = true,
diggable = true,
buildable_to = false,
stack_max = 99,
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=3},
})
-- Sponge wet back to Sponge Dry if coocked in a furnace
minetest.register_craft({
type = "cooking", output = "sponge:sponge", recipe = "sponge:sponge_wet",
})
minetest.register_craft({
output = "sponge:sponge",
recipe = {
{"", "dye:black", ""},
{"dye:yellow", "wool:white", "dye:yellow"},
{"", "farming:wheat", ""},
},
})
|
------------------------------------------------------------------------
--- @file percc.lua
--- @brief (percc) utility.
--- Utility functions for the percc_header structs
--- Includes:
--- - percc constants
--- - percc header utility
--- - Definition of percc packets
------------------------------------------------------------------------
--[[
-- Use this file as template when implementing a new protocol (to implement all mandatory stuff)
-- Replace all occurrences of proto with your protocol (e.g. sctp)
-- Remove unnecessary comments in this file (comments inbetween [[...]]
-- Necessary changes to other files:
-- - packet.lua: if the header has a length member, adapt packetSetLength;
-- if the packet has a checksum, adapt createStack (loop at end of function) and packetCalculateChecksums
-- - proto/proto.lua: add percc.lua to the list so it gets loaded
--]]
require "utils"
local ffi = require "ffi"
require "proto.template"
local initHeader = initHeader
---------------------------------------------------------------------------
---- percc constants
---------------------------------------------------------------------------
--- percc protocol constants
local percc = {}
percc.LABEL_INACTIVE = 0x0
percc.LABEL_SAT = 0x1
percc.LABEL_UNSAT = 0x2
percc.LABEL_NEW_FLOW = 0x3
---------------------------------------------------------------------------
---- percc header
---------------------------------------------------------------------------
percc.headerFormat = [[
uint32_t flowID;
uint8_t leave;
uint8_t isForward;
uint8_t hopCnt;
uint8_t bottleneck_id;
uint32_t demand;
uint8_t insert_debug;
uint64_t timestamp;
uint8_t label_0;
uint8_t label_1;
uint8_t label_2;
uint32_t alloc_0;
uint32_t alloc_1;
uint32_t alloc_2;
uint32_t linkCap;
uint32_t sumSatAdj;
uint32_t numFlowsAdj;
uint32_t numSatAdj;
uint32_t newMaxSat;
uint32_t R;
uint64_t resetTimer;
uint8_t nf_index;
]]
--- Variable sized member
percc.headerVariableMember = nil
--- Module for percc_address struct
local perccHeader = initHeader()
perccHeader.__index = perccHeader
-- Maps headers to respective protocol value.
-- This list should be extended whenever a new protocol is added to 'IPv4 constants'.
local mapNameProto = {
}
--[[ for all members of the header with non-standard data type: set, get, getString
-- for set also specify a suitable default value
--]]
--- Set the flowID.
--- @param int flowID of the perc header as 32 bit integer.
function perccHeader:setflowID(int)
int = int or 0
self.flowID = bswap(int)
end
--- Retrieve the flowID.
--- @return flowID as 32 bit integer.
function perccHeader:getflowID()
return bswap(self.flowID)
end
--- Retrieve the flowID as string.
--- @return flowID as string.
function perccHeader:getflowIDString()
return self.flowID
end
--- Set the leave.
--- @param int leave of the percc header as 8 bit integer.
function perccHeader:setleave(int)
int = int or 0
self.leave = int
end
--- Retrieve the leave.
--- @return leave as 8 bit integer.
function perccHeader:getleave()
return self.leave
end
--- Retrieve the leave as string.
--- @return leave as string.
function perccHeader:getleaveString()
return self.leave
end
--- Set the isForward.
--- @param int isForward of the percc header as 8 bit integer.
function perccHeader:setisForward(int)
int = int or 0x1
self.isForward = int
end
--- Retrieve the isForward.
--- @return isForward as 8 bit integer.
function perccHeader:getisForward()
return self.isForward
end
--- Retrieve the isForward as string.
--- @return isForward as string.
function perccHeader:getisForwardString()
return self.isForward
end
--- Set the hopCnt.
--- @param int hopCnt of the percc header as 8 bit integer.
function perccHeader:sethopCnt(int)
int = int or 0
self.hopCnt = int
end
--- Retrieve the hopCnt.
--- @return hopCnt as 8 bit integer.
function perccHeader:gethopCnt()
return self.hopCnt
end
--- Retrieve the hopCnt as string.
--- @return hopCnt as string.
function perccHeader:gethopCntString()
return self.hopCnt
end
--- Set the bottleneck_id.
--- @param int bottleneck_id of the percc header as 8 bit integer.
function perccHeader:setbottleneck_id(int)
int = int or 0xFF
self.bottleneck_id = int
end
--- Retrieve the bottleneck_id.
--- @return bottleneck_id as 8 bit integer.
function perccHeader:getbottleneck_id()
return self.bottleneck_id
end
--- Retrieve the bottleneck_id as string.
--- @return bottleneck_id as string.
function perccHeader:getbottleneck_idString()
return self.bottleneck_id
end
--- Set the demand.
--- @param int demand of the percc header as 32 bit integer.
function perccHeader:setdemand(int)
int = int or 0xFFFFFFFF
self.demand = bswap(int)
end
--- Retrieve the demand.
--- @return demand as 32 bit integer.
function perccHeader:getdemand()
return tonumber(bit.band(bswap(self.demand), 0xFFFFFFFFULL))
end
--- Retrieve the demand as string.
--- @return demand as string.
function perccHeader:getdemandString()
return bswap(self.demand)
end
--- Set the insert_debug.
--- @param int insert_debug of the percc header as 8 bit integer.
function perccHeader:setinsert_debug(int)
int = int or 0
self.insert_debug = int
end
--- Retrieve the insert_debug.
--- @return insert_debug as 8 bit integer.
function perccHeader:getinsert_debug()
return self.insert_debug
end
--- Retrieve the insert_debug as string.
--- @return insert_debug as string.
function perccHeader:getinsert_debugString()
return self.insert_debug
end
--- Set the timestamp.
--- @param int timestamp of the percc header as 64 bit integer.
function perccHeader:settimestamp(int)
int = int or 0
self.timestamp = bswap(int)
end
--- Retrieve the timestamp.
--- @return timestamp as 64 bit integer.
function perccHeader:gettimestamp()
return bswap(self.timestamp)
end
--- Retrieve the timestamp as string.
--- @return timestamp as string.
function perccHeader:gettimestampString()
return bswap(self.timestamp)
end
--- Set the label_0.
--- @param int label_0 of the percc header as 8 bit integer.
function perccHeader:setlabel_0(int)
int = int or percc.LABEL_NEW_FLOW
self.label_0 = int
end
--- Retrieve the label_0.
--- @return label_0 as 8 bit integer.
function perccHeader:getlabel_0()
return self.label_0
end
--- Retrieve the label_0 as string.
--- @return label_0 as string.
function perccHeader:getlabel_0String()
local label = self:getlabel_0()
local cleartext = ""
if label == percc.LABEL_INACTIVE then
cleartext = "(LABEL INACTIVE)"
elseif label == percc.LABEL_SAT then
cleartext = "(LABEL SAT)"
elseif label == percc.LABEL_UNSAT then
cleartext = "(LABEL UNSAT)"
elseif label == percc.LABEL_NEW_FLOW then
cleartext = "(LABEL NEW_FLOW)"
else
cleartext = "(unknown)"
end
return format("0x%02x %s", label, cleartext)
end
--- Set the label_1.
--- @param int label_1 of the percc header as 8 bit integer.
function perccHeader:setlabel_1(int)
int = int or percc.LABEL_NEW_FLOW
self.label_1 = int
end
--- Retrieve the label_1.
--- @return label_1 as 8 bit integer.
function perccHeader:getlabel_1()
return self.label_1
end
--- Retrieve the label_1 as string.
--- @return label_1 as string.
function perccHeader:getlabel_1String()
local label = self:getlabel_1()
local cleartext = ""
if label == percc.LABEL_INACTIVE then
cleartext = "(LABEL INACTIVE)"
elseif label == percc.LABEL_SAT then
cleartext = "(LABEL SAT)"
elseif label == percc.LABEL_UNSAT then
cleartext = "(LABEL UNSAT)"
elseif label == percc.LABEL_NEW_FLOW then
cleartext = "(LABEL NEW_FLOW)"
else
cleartext = "(unknown)"
end
return format("0x%02x %s", label, cleartext)
end
--- Set the label_2.
--- @param int label_2 of the percc header as 8 bit integer.
function perccHeader:setlabel_2(int)
int = int or percc.LABEL_NEW_FLOW
self.label_2 = int
end
--- Retrieve the label_2.
--- @return label_2 as 8 bit integer.
function perccHeader:getlabel_2()
return self.label_2
end
--- Retrieve the label_2 as string.
--- @return label_2 as string.
function perccHeader:getlabel_2String()
local label = self:getlabel_2()
local cleartext = ""
if label == percc.LABEL_INACTIVE then
cleartext = "(LABEL INACTIVE)"
elseif label == percc.LABEL_SAT then
cleartext = "(LABEL SAT)"
elseif label == percc.LABEL_UNSAT then
cleartext = "(LABEL UNSAT)"
elseif label == percc.LABEL_NEW_FLOW then
cleartext = "(LABEL NEW_FLOW)"
else
cleartext = "(unknown)"
end
return format("0x%02x %s", label, cleartext)
end
-- Usually host should not be modifying any of the following fields
-- So we don't bother to convert between host and network byte order (bswap)
--- Set the alloc_0.
--- @param int alloc_0 of the percc header as 32 bit integer.
function perccHeader:setalloc_0(int)
int = int or 0xFFFFFFFF
self.alloc_0 = int
end
--- Retrieve the alloc_0.
--- @return alloc_0 as 32 bit integer.
function perccHeader:getalloc_0()
return self.alloc_0
end
--- Retrieve the alloc_0 as string.
--- @return alloc_0 as string.
function perccHeader:getalloc_0String()
return self.alloc_0
end
--- Set the alloc_1.
--- @param int alloc_1 of the percc header as 32 bit integer.
function perccHeader:setalloc_1(int)
int = int or 0xFFFFFFFF
self.alloc_1 = int
end
--- Retrieve the alloc_1.
--- @return alloc_1 as 32 bit integer.
function perccHeader:getalloc_1()
return self.alloc_1
end
--- Retrieve the alloc_1 as string.
--- @return alloc_1 as string.
function perccHeader:getalloc_1String()
return self.alloc_1
end
--- Set the alloc_2.
--- @param int alloc_2 of the percc header as 32 bit integer.
function perccHeader:setalloc_2(int)
int = int or 0xFFFFFFFF
self.alloc_2 = int
end
--- Retrieve the alloc_2.
--- @return alloc_2 as 32 bit integer.
function perccHeader:getalloc_2()
return self.alloc_2
end
--- Retrieve the alloc_2 as string.
--- @return alloc_2 as string.
function perccHeader:getalloc_2String()
return self.alloc_2
end
--- Set the linkCap.
--- @param int linkCap of the percc header as 32 bit integer.
function perccHeader:setlinkCap(int)
int = int or 0
self.linkCap = int
end
--- Retrieve the linkCap.
--- @return linkCap as 32 bit integer.
function perccHeader:getlinkCap()
return self.linkCap
end
--- Retrieve the linkCap as string.
--- @return linkCap as string.
function perccHeader:getlinkCapString()
return self.linkCap
end
--- Set the sumSatAdj.
--- @param int sumSatAdj of the percc header as 32 bit integer.
function perccHeader:setsumSatAdj(int)
int = int or 0
self.sumSatAdj = int
end
--- Retrieve the sumSatAdj.
--- @return sumSatAdj as 32 bit integer.
function perccHeader:getsumSatAdj()
return self.sumSatAdj
end
--- Retrieve the sumSatAdj as string.
--- @return sumSatAdj as string.
function perccHeader:getsumSatAdjString()
return self.sumSatAdj
end
--- Set the numFlowsAdj.
--- @param int numFlowsAdj of the percc header as 32 bit integer.
function perccHeader:setnumFlowsAdj(int)
int = int or 0
self.numFlowsAdj = int
end
--- Retrieve the numFlowsAdj.
--- @return numFlowsAdj as 32 bit integer.
function perccHeader:getnumFlowsAdj()
return self.numFlowsAdj
end
--- Retrieve the numFlowsAdj as string.
--- @return numFlowsAdj as string.
function perccHeader:getnumFlowsAdjString()
return self.numFlowsAdj
end
--- Set the numSatAdj.
--- @param int numSatAdj of the percc header as 32 bit integer.
function perccHeader:setnumSatAdj(int)
int = int or 0
self.numSatAdj = int
end
--- Retrieve the numSatAdj.
--- @return numSatAdj as 32 bit integer.
function perccHeader:getnumSatAdj()
return self.numSatAdj
end
--- Retrieve the numSatAdj as string.
--- @return numSatAdj as string.
function perccHeader:getnumSatAdjString()
return self.numSatAdj
end
--- Set the newMaxSat.
--- @param int newMaxSat of the percc header as 32 bit integer.
function perccHeader:setnewMaxSat(int)
int = int or 0
self.newMaxSat = int
end
--- Retrieve the newMaxSat.
--- @return newMaxSat as 32 bit integer.
function perccHeader:getnewMaxSat()
return self.newMaxSat
end
--- Retrieve the newMaxSat as string.
--- @return newMaxSat as string.
function perccHeader:getnewMaxSatString()
return self.newMaxSat
end
--- Set the R.
--- @param int R of the percc header as 32 bit integer.
function perccHeader:setR(int)
int = int or 0
self.R = int
end
--- Retrieve the R.
--- @return R as 32 bit integer.
function perccHeader:getR()
return self.R
end
--- Retrieve the R as string.
--- @return R as string.
function perccHeader:getRString()
return self.R
end
--- Set the resetTimer.
--- @param int timestamp of the resetTimer of the percc header as 64 bit integer.
function perccHeader:setresetTimer(int)
int = int or 0
self.resetTimer = bswap(int)
end
--- Retrieve the resetTimer timestamp.
--- @return resetTimer timestamp as 64 bit integer.
function perccHeader:getresetTimer()
return bswap(self.resetTimer)
end
--- Retrieve the resetTimer timestamp as string.
--- @return resetTimer timestamp as string.
function perccHeader:getresetTimerString()
return bswap(self.resetTimer)
end
--- Set the nf_index.
--- @param int nf_index of the percc header as 64 bit integer.
function perccHeader:setnf_index(int)
int = int or 0
self.nf_index = bswap(int)
end
--- Retrieve the nf_index.
--- @return nf_index as 32 bit integer.
function perccHeader:getnf_index()
return bswap(self.nf_index)
end
--- Retrieve the nf_index as string.
--- @return nf_index as string.
function perccHeader:getnf_indexString()
return bswap(self.nf_index)
end
--- Set all members of the percc header.
--- Per default, all members are set to default values specified in the respective set function.
--- Optional named arguments can be used to set a member to a user-provided value.
--- @param args Table of named arguments. Available arguments: perccXYZ
--- @param pre prefix for namedArgs. Default 'percc'.
--- @code
--- fill() -- only default values
--- fill{ perccXYZ=1 } -- all members are set to default values with the exception of perccXYZ, ...
--- @endcode
function perccHeader:fill(args, pre)
args = args or {}
pre = pre or "percc"
self:setflowID(args[pre .. "flowID"])
self:setleave(args[pre .. "leave"])
self:setisForward(args[pre .. "isForward"])
self:sethopCnt(args[pre .. "hopCnt"])
self:setbottleneck_id(args[pre .. "bottleneck_id"])
self:setdemand(args[pre .. "demand"])
self:setinsert_debug(args[pre .. "insert_debug"])
self:settimestamp(args[pre .. "timestamp"])
self:setlabel_0(args[pre .. "label_0"])
self:setlabel_1(args[pre .. "label_1"])
self:setlabel_2(args[pre .. "label_2"])
self:setalloc_0(args[pre .. "alloc_0"])
self:setalloc_1(args[pre .. "alloc_1"])
self:setalloc_2(args[pre .. "alloc_2"])
self:setlinkCap(args[pre .. "linkCap"])
self:setsumSatAdj(args[pre .. "sumSatAdj"])
self:setnumFlowsAdj(args[pre .. "numFlowsAdj"])
self:setnumSatAdj(args[pre .. "numSatAdj"])
self:setnewMaxSat(args[pre .. "newMaxSat"])
self:setR(args[pre .. "R"])
self:setresetTimer(args[pre .. "resetTimer"])
self:setnf_index(args[pre .. "nf_index"])
end
--- Retrieve the values of all members.
--- @param pre prefix for namedArgs. Default 'percc'.
--- @return Table of named arguments. For a list of arguments see "See also".
--- @see perccHeader:fill
function perccHeader:get(pre)
pre = pre or "percc"
local args = {}
args[pre .. "flowID"] = self:getflowID()
args[pre .. "leave"] = self:getleave()
args[pre .. "isForward"] = self:getisForward()
args[pre .. "hopCnt"] = self:gethopCnt()
args[pre .. "bottleneck_id"] = self:getbottleneck_id()
args[pre .. "demand"] = self:getdemand()
args[pre .. "insert_debug"] = self:getinsert_debug()
args[pre .. "timestamp"] = self:gettimestamp()
args[pre .. "label_0"] = self:getlabel_0()
args[pre .. "label_1"] = self:getlabel_1()
args[pre .. "label_2"] = self:getlabel_2()
args[pre .. "alloc_0"] = self:getalloc_0()
args[pre .. "alloc_1"] = self:getalloc_1()
args[pre .. "alloc_2"] = self:getalloc_2()
args[pre .. "linkCap"] = self:getlinkCap()
args[pre .. "sumSatAdj"] = self:getsumSatAdj()
args[pre .. "numFlowsAdj"] = self:getnumFlowsAdj()
args[pre .. "numSatAdj"] = self:getnumSatAdj()
args[pre .. "newMaxSat"] = self:getnewMaxSat()
args[pre .. "R"] = self:getR()
args[pre .. "resetTimer"] = self:getresetTimer()
args[pre .. "nf_index"] = self:getnf_index()
return args
end
--- Retrieve the values of all members.
--- @return Values in string format.
function perccHeader:getString()
return "Perc_control "
.. " flowID " .. self:getflowID()
.. " nf_index " .. self:getnf_index()
.. " leave " .. self:getleaveString()
.. " isForward " .. self:getisForward()
.. " hopCnt " .. self:gethopCnt()
.. " bottleneck_id " .. self:getbottleneck_id()
.. " demand " .. self:getdemand()
.. " insert_debug " .. self:getinsert_debug()
.. " timestamp " .. self:gettimestamp()
.. " label_0 " .. self:getlabel_0()
.. " label_1 " .. self:getlabel_1()
.. " label_2 " .. self:getlabel_2()
.. " alloc_0 " .. self:getalloc_0()
.. " alloc_1 " .. self:getalloc_1()
.. " alloc_2 " .. self:getalloc_2()
end
--- Resolve which header comes after this one (in a packet)
--- For instance: in tcp/udp based on the ports
--- This function must exist and is only used when get/dump is executed on
--- an unknown (mbuf not yet casted to e.g. tcpv6 packet) packet (mbuf)
--- @return String next header (e.g. 'eth', 'ip4', nil)
function perccHeader:resolveNextHeader()
return nil
end
--- Change the default values for namedArguments (for fill/get)
--- This can be used to for instance calculate a length value based on the total packet length
--- See proto/ip4.setDefaultNamedArgs as an example
--- This function must exist and is only used by packet.fill
--- @param pre The prefix used for the namedArgs, e.g. 'percc'
--- @param namedArgs Table of named arguments (see See more)
--- @param nextHeader The header following after this header in a packet
--- @param accumulatedLength The so far accumulated length for previous headers in a packet
--- @return Table of namedArgs
--- @see perccHeader:fill
function perccHeader:setDefaultNamedArgs(pre, namedArgs, nextHeader, accumulatedLength)
return namedArgs
end
------------------------------------------------------------------------
---- Metatypes
------------------------------------------------------------------------
percc.metatype = perccHeader
return percc
|
local core = require "core"
local command = require "core.command"
local config = require "core.config"
local keymap = require "core.keymap"
local function dv()
return core.active_view
end
local function doc()
return core.active_view.doc
end
command.add("core.docview", {
["doc:copy-path"] = function()
local doc = core.active_view.doc
if not doc.filename then
core.error "Cannot copy location of unsaved doc"
return
end
local filename = system.absolute_path(doc.filename)
core.log("Copying to clipboard \"%s\"", filename)
system.set_clipboard(filename)
end,
["doc:close"] = function()
command.perform("root:close")
end,
["doc:reveal-in-file-system"] = function()
local doc = core.active_view.doc
if not doc.filename then
core.error "Cannot open location of unsaved doc"
return
end
if PLATFORM == "Mac OS X" then
local filename = system.absolute_path(doc.filename or ".")
core.log("Opening \"%s\"", filename)
system.exec(string.format("osascript -e \"tell application \\\"Finder\\\"\" -e activate -e \"reveal POSIX file \\\"%s\\\"\" -e end tell", filename))
return
end
local folder = doc.filename:match("^(.*)[/\\].*$") or "."
core.log("Opening \"%s\"", folder)
if PLATFORM == "Windows" then
system.exec(string.format("%s %s", "explorer", folder))
else
system.exec(string.format("%s %q", "xdg-open", folder))
end
end
})
keymap.add { ["ctl+w"] = "doc:close" }
keymap.add { ["cmd+w"] = "doc:close" }
|
lightbridge = class:new()
function lightbridge:init(x, y, dir, r)
self.cox = x
self.coy = y
self.dir = dir
self.r = r
self.childtable = {}
self.enabled = true
self:updaterange()
end
function lightbridge:link()
self.outtable = {}
if #self.r > 2 then
for j, w in pairs(outputs) do
for i, v in pairs(objects[w]) do
if tonumber(self.r[4]) == v.cox and tonumber(self.r[5]) == v.coy then
v:addoutput(self)
self.enabled = false
end
end
end
end
end
function lightbridge:input(t)
if t == "on" then
self.enabled = true
self:updaterange()
elseif t == "off" then
self.enabled = false
self:updaterange()
else
self.enabled = not self.enabled
self:updaterange()
end
end
function lightbridge:update(dt)
end
function lightbridge:draw()
local rot = 0
if self.dir == "up" then
rot = math.pi*1.5
elseif self.dir == "down" then
rot = math.pi*0.5
elseif self.dir == "left" then
rot = math.pi
end
love.graphics.draw(lightbridgesideimg, math.floor((self.cox-xscroll-.5)*16*scale), (self.coy-1)*16*scale, rot, scale, scale, 8, 8)
end
function lightbridge:updaterange()
for i, v in pairs(self.childtable) do
v.destroy = true
end
self.childtable = {}
if self.enabled == false then
return
end
local dir = self.dir
local startx, starty = self.cox, self.coy
local x, y = self.cox, self.coy
local firstcheck = true
local quit = false
while x >= 1 and x <= mapwidth and y >= 1 and y <= 15 and tilequads[map[x][y][1]].collision == false and (x ~= startx or y ~= starty or dir ~= self.dir or firstcheck == true) and quit == false do
firstcheck = false
if dir == "right" then
x = x + 1
table.insert(objects["lightbridgebody"], lightbridgebody:new(self, x-1, y, "hor"))
elseif dir == "left" then
x = x - 1
table.insert(objects["lightbridgebody"], lightbridgebody:new(self, x+1, y, "hor"))
elseif dir == "up" then
y = y - 1
table.insert(objects["lightbridgebody"], lightbridgebody:new(self, x, y+1, "ver"))
elseif dir == "down" then
y = y + 1
table.insert(objects["lightbridgebody"], lightbridgebody:new(self, x, y-1, "ver"))
end
--check if current block is a portal
local portalx, portaly, portalfacing, infacing = getPortal(x, y)
if portalx ~= false and ((dir == "left" and infacing == "right") or (dir == "right" and infacing == "left") or (dir == "up" and infacing == "down") or (dir == "down" and infacing == "up")) then
x, y = portalx, portaly
dir = portalfacing
if dir == "right" then
x = x + 1
elseif dir == "left" then
x = x - 1
elseif dir == "up" then
y = y - 1
elseif dir == "down" then
y = y + 1
end
end
--doors
for i, v in pairs(objects["door"]) do
if v.active then
if v.dir == "ver" then
if x == v.cox and (y == v.coy or y == v.coy-1) then
quit = true
end
elseif v.dir == "hor" then
if y == v.coy and (x == v.cox or x == v.cox+1) then
quit = true
end
end
end
end
end
end
function lightbridge:addChild(t)
table.insert(self.childtable, t)
end
------------------------------------
lightbridgebody = class:new()
function lightbridgebody:init(parent, x, y, dir)
parent:addChild(self)
self.cox = x
self.coy = y
self.dir = dir
--PHYSICS STUFF
if dir == "hor" then
self.x = x-1
self.y = y-9/16
self.width = 1
self.height = 1/8
else
self.x = x-9/16
self.y = y-1
self.width= 1/8
self.height = 1
end
self.static = true
self.active = true
self.category = 28
self.mask = {true}
self:pushstuff()
end
function lightbridgebody:pushstuff()
local col = checkrect(self.x, self.y, self.width, self.height, {"box", "player"})
for i = 1, #col, 2 do
local v = objects[col[i]][col[i+1]]
if self.dir == "ver" then
if v.speedx >= 0 then
if #checkrect(self.x + self.width, v.y, v.width, v.height, {"exclude", v}, true) > 0 then
v.x = self.x - v.width
else
v.x = self.x + self.width
end
else
if #checkrect(self.x - v.width, v.y, v.width, v.height, {"exclude", v}, true) > 0 then
v.x = self.x + self.width
else
v.x = self.x - v.width
end
end
elseif self.dir == "hor" then
if v.speedy <= 0 then
if #checkrect(v.x, self.y - v.height, v.width, v.height, {"exclude", v}, true) > 0 then
v.y = self.y + self.height
else
v.y = self.y - v.height
end
else
if #checkrect(v.x, self.y + self.height, v.width, v.height, {"exclude", v}, true) > 0 then
v.y = self.y - v.height
else
v.y = self.y + self.height
end
end
end
end
end
function lightbridgebody:update(dt)
if self.destroy then
return true
else
return false
end
end
function lightbridgebody:draw()
love.graphics.setColor(1, 1, 1)
if self.dir == "hor" then
love.graphics.draw(lightbridgeimg, math.floor((self.cox-xscroll-1)*16*scale), (self.coy-20/16)*16*scale, 0, scale, scale)
else
love.graphics.draw(lightbridgeimg, math.floor((self.cox-xscroll-5/16)*16*scale), (self.coy-1)*16*scale, math.pi/2, scale, scale, 8, 1)
end
end |
--[[
Copyright (c) 2017 George Prosser
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]--
local class = require 'code/lib/middleclass'
Zombie = class('Zombie')
function Zombie:initialize(x, y, v)
self.x = x
self.y = y
self.radius = 22
self.angle = 0
self.speed = v
self.hp = 3
end
function Zombie:update(dt)
-- update angle to player
local player_dx = game.player.x - self.x
local player_dy = game.player.y - self.y
self.angle = math.atan2(player_dy, player_dx)
-- movement
local vx = self.speed * math.cos(self.angle)
local vy = self.speed * math.sin(self.angle)
local d = math.sqrt(player_dx^2 + player_dy^2)
if d > 10 then
self.x = self.x + vx * dt
self.y = self.y + vy * dt
end
-- bullets
for i=1, #game.bullets.contents do
local bullet = game.bullets.contents[i]
local bullet_dx = bullet.x - self.x
local bullet_dy = bullet.y - self.y
local d = math.sqrt(bullet_dx^2 + bullet_dy^2)
if d < self.radius + bullet.radius then
self.hp = self.hp - 1
bullet.to_delete = true
-- sfx
sounds.punch:setPitch(1.17^(2*math.random() - 1))
sounds.punch:stop()
sounds.punch:play()
end
end
-- health
if self.hp <= 0 then
-- score
game.score = game.score + 1
-- sfx
sounds.kill:setPitch(1.17^(1*math.random() - 0.5))
sounds.kill:stop()
sounds.kill:play()
-- blood
table.insert(game.blood, {x=self.x, y=self.y, angle=math.random() * 2 * math.pi})
self.to_delete = true
end
end
function Zombie:draw()
love.graphics.setColor(255, 255, 255)
love.graphics.draw(images.zombie, self.x, self.y, self.angle, 1, 1, 16, 22)
end
|
require("firecast.lua");
local __o_rrpgObjs = require("rrpgObjs.lua");
require("rrpgGUI.lua");
require("rrpgDialogs.lua");
require("rrpgLFM.lua");
require("ndb.lua");
require("locale.lua");
local __o_Utils = require("utils.lua");
local function constructNew_frmFichaRPGmeister4h_svg()
local obj = GUI.fromHandle(_obj_newObject("form"));
local self = obj;
local sheet = nil;
rawset(obj, "_oldSetNodeObjectFunction", rawget(obj, "setNodeObject"));
function obj:setNodeObject(nodeObject)
sheet = nodeObject;
self.sheet = nodeObject;
self:_oldSetNodeObjectFunction(nodeObject);
end;
function obj:setNodeDatabase(nodeObject)
self:setNodeObject(nodeObject);
end;
_gui_assignInitialParentForForm(obj.handle);
obj:beginUpdate();
obj:setName("frmFichaRPGmeister4h_svg");
obj:setHeight(25);
obj:setWidth(350);
obj:setMargins({top=2});
local function askForDelete()
Dialogs.confirmYesNo("Deseja realmente apagar essa habilidade?",
function (confirmado)
if confirmado then
NDB.deleteNode(sheet);
end;
end);
end;
local function showHabilidadePopup()
local pop = self:findControlByName("popHabilidade");
if pop ~= nil then
pop:setNodeObject(self.sheet);
pop:showPopupEx("right", self);
else
showMessage("Ops, bug.. nao encontrei o popup de habilidades para exibir");
end;
end;
local function use()
local mesa = Firecast.getMesaDe(sheet);
local texto = (sheet.nomeHabilidade or "Habilidade") .. " foi usado.";
if sheet.cd~=nil then
texto = texto .. " CD: " .. sheet.cd .. ".";
end;
if sheet.dados~=nil then
local rolagem = Firecast.interpretarRolagem(sheet.dados);
mesa.activeChat:rolarDados(rolagem, texto);
end;
if sheet.BarrinhaValor~=nil then
sheet.BarrinhaValor = tonumber(sheet.BarrinhaValor) - 1;
if sheet.dados==nil then
mesa.activeChat:enviarMensagem(texto);
end;
end;
end;
obj.edit1 = GUI.fromHandle(_obj_newObject("edit"));
obj.edit1:setParent(obj);
obj.edit1:setAlign("left");
obj.edit1:setWidth(30);
obj.edit1:setField("nivelHabilidade");
obj.edit1:setType("number");
obj.edit1:setVertTextAlign("center");
obj.edit1:setName("edit1");
obj.layout1 = GUI.fromHandle(_obj_newObject("layout"));
obj.layout1:setParent(obj);
obj.layout1:setAlign("right");
obj.layout1:setWidth(75);
obj.layout1:setName("layout1");
obj.layout2 = GUI.fromHandle(_obj_newObject("layout"));
obj.layout2:setParent(obj.layout1);
obj.layout2:setTop(5);
obj.layout2:setHeight(15);
obj.layout2:setWidth(45);
obj.layout2:setName("layout2");
obj.imageCheckBox1 = GUI.fromHandle(_obj_newObject("imageCheckBox"));
obj.imageCheckBox1:setParent(obj.layout2);
obj.imageCheckBox1:setAlign("client");
obj.imageCheckBox1:setName("imageCheckBox1");
obj.Barrinha = GUI.fromHandle(_obj_newObject("progressBar"));
obj.Barrinha:setParent(obj.imageCheckBox1);
obj.Barrinha:setColorMode("hl");
obj.Barrinha:setWidth(45);
obj.Barrinha:setHeight(15);
obj.Barrinha:setMargins({top=5,bottom=5});
obj.Barrinha:setHitTest(true);
obj.Barrinha:setMouseGlow(true);
obj.Barrinha:setColor("Green");
obj.Barrinha:setName("Barrinha");
obj.Barrinha:setField("BarrinhaValor");
obj.Barrinha:setFieldMax("BarrinhaValorMax");
obj.ValoresBarrinha = GUI.fromHandle(_obj_newObject("layout"));
obj.ValoresBarrinha:setParent(obj.layout1);
obj.ValoresBarrinha:setLeft(45);
obj.ValoresBarrinha:setTop(5);
obj.ValoresBarrinha:setHeight(15);
obj.ValoresBarrinha:setWidth(30);
obj.ValoresBarrinha:setMargins({top=5,bottom=5});
obj.ValoresBarrinha:setVisible(false);
obj.ValoresBarrinha:setName("ValoresBarrinha");
obj.CorBarrinha = GUI.fromHandle(_obj_newObject("rectangle"));
obj.CorBarrinha:setParent(obj.ValoresBarrinha);
obj.CorBarrinha:setAlign("client");
obj.CorBarrinha:setXradius(2);
obj.CorBarrinha:setYradius(2);
obj.CorBarrinha:setName("CorBarrinha");
obj.CorBarrinha:setColor("Green");
obj.InfoBarrinha = GUI.fromHandle(_obj_newObject("label"));
obj.InfoBarrinha:setParent(obj.CorBarrinha);
obj.InfoBarrinha:setAlign("left");
obj.InfoBarrinha:setFontColor("white");
obj.InfoBarrinha:setFontSize(10);
obj.InfoBarrinha:setAutoSize(true);
obj.InfoBarrinha:setTextTrimming("none");
obj.InfoBarrinha:setWordWrap(false);
obj.InfoBarrinha:setName("InfoBarrinha");
obj.InfoBarrinha:setField("InfoBarrinha");
obj.InfoBarrinha:setHorzTextAlign("center");
obj.InfoBarrinha:setText("0/0");
obj.dataLink1 = GUI.fromHandle(_obj_newObject("dataLink"));
obj.dataLink1:setParent(obj.layout1);
obj.dataLink1:setField("CorBarrinha");
obj.dataLink1:setDefaultValue("Green");
obj.dataLink1:setName("dataLink1");
obj.button1 = GUI.fromHandle(_obj_newObject("button"));
obj.button1:setParent(obj);
obj.button1:setAlign("right");
obj.button1:setWidth(25);
obj.button1:setText("i");
obj.button1:setName("button1");
obj.button2 = GUI.fromHandle(_obj_newObject("button"));
obj.button2:setParent(obj);
obj.button2:setAlign("right");
obj.button2:setWidth(25);
obj.button2:setText("U");
obj.button2:setName("button2");
obj.button3 = GUI.fromHandle(_obj_newObject("button"));
obj.button3:setParent(obj);
obj.button3:setAlign("right");
obj.button3:setWidth(25);
obj.button3:setText("X");
obj.button3:setName("button3");
obj.edit2 = GUI.fromHandle(_obj_newObject("edit"));
obj.edit2:setParent(obj);
obj.edit2:setAlign("client");
obj.edit2:setVertTextAlign("center");
obj.edit2:setField("nomeHabilidade");
obj.edit2:setName("edit2");
obj._e_event0 = obj.Barrinha:addEventListener("onMouseEnter",
function (_)
self.CorBarrinha.color = "Green";
self.ValoresBarrinha.visible = true;
sheet.InfoBarrinha = (sheet.BarrinhaValor or 0) .. "/" .. (sheet.BarrinhaValorMax or 0);
end, obj);
obj._e_event1 = obj.Barrinha:addEventListener("onMouseLeave",
function (_)
self.ValoresBarrinha.visible = false;
end, obj);
obj._e_event2 = obj.Barrinha:addEventListener("onDblClick",
function (_)
sheet.BarrinhaID = sheet.index;
sheet.AtributoBarrinha = sheet.nomeHabilidade;
sheet.ModificadorBarrinha = "igual";
sheet.ModificadorBarrinhaMax = "igual";
sheet.ValorTempAtualBarrinha = sheet.BarrinhaValor;
sheet.ValorTempMaxBarrinha = sheet.BarrinhaValorMax;
sheet.ValorMudadoAtualBarrinha = sheet.BarrinhaValor;
sheet.ValorMudadoMaxBarrinha = sheet.BarrinhaValorMax;
local rec = self:findControlByName("PopupBarColor");
if rec~=nil then rec.color = "Green" end;
local pop = self:findControlByName("BarPopup");
if pop~= nil then
pop.scopeNode = sheet;
pop:show("top", self.Barrinha);
pop.top = (pop.top + 29 + 10);
end;
end, obj);
obj._e_event3 = obj.InfoBarrinha:addEventListener("onResize",
function (_)
self.InfoBarrinha.width = (self.ValoresBarrinha.width - 4);
end, obj);
obj._e_event4 = obj.dataLink1:addEventListener("onChange",
function (_, field, oldValue, newValue)
self.Barrinha.color = "Green";
end, obj);
obj._e_event5 = obj.button1:addEventListener("onClick",
function (_)
showHabilidadePopup();
end, obj);
obj._e_event6 = obj.button2:addEventListener("onClick",
function (_)
use();
end, obj);
obj._e_event7 = obj.button3:addEventListener("onClick",
function (_)
askForDelete();
end, obj);
function obj:_releaseEvents()
__o_rrpgObjs.removeEventListenerById(self._e_event7);
__o_rrpgObjs.removeEventListenerById(self._e_event6);
__o_rrpgObjs.removeEventListenerById(self._e_event5);
__o_rrpgObjs.removeEventListenerById(self._e_event4);
__o_rrpgObjs.removeEventListenerById(self._e_event3);
__o_rrpgObjs.removeEventListenerById(self._e_event2);
__o_rrpgObjs.removeEventListenerById(self._e_event1);
__o_rrpgObjs.removeEventListenerById(self._e_event0);
end;
obj._oldLFMDestroy = obj.destroy;
function obj:destroy()
self:_releaseEvents();
if (self.handle ~= 0) and (self.setNodeDatabase ~= nil) then
self:setNodeDatabase(nil);
end;
if self.Barrinha ~= nil then self.Barrinha:destroy(); self.Barrinha = nil; end;
if self.button1 ~= nil then self.button1:destroy(); self.button1 = nil; end;
if self.CorBarrinha ~= nil then self.CorBarrinha:destroy(); self.CorBarrinha = nil; end;
if self.InfoBarrinha ~= nil then self.InfoBarrinha:destroy(); self.InfoBarrinha = nil; end;
if self.button3 ~= nil then self.button3:destroy(); self.button3 = nil; end;
if self.ValoresBarrinha ~= nil then self.ValoresBarrinha:destroy(); self.ValoresBarrinha = nil; end;
if self.button2 ~= nil then self.button2:destroy(); self.button2 = nil; end;
if self.imageCheckBox1 ~= nil then self.imageCheckBox1:destroy(); self.imageCheckBox1 = nil; end;
if self.edit2 ~= nil then self.edit2:destroy(); self.edit2 = nil; end;
if self.layout1 ~= nil then self.layout1:destroy(); self.layout1 = nil; end;
if self.edit1 ~= nil then self.edit1:destroy(); self.edit1 = nil; end;
if self.layout2 ~= nil then self.layout2:destroy(); self.layout2 = nil; end;
if self.dataLink1 ~= nil then self.dataLink1:destroy(); self.dataLink1 = nil; end;
self:_oldLFMDestroy();
end;
obj:endUpdate();
return obj;
end;
function newfrmFichaRPGmeister4h_svg()
local retObj = nil;
__o_rrpgObjs.beginObjectsLoading();
__o_Utils.tryFinally(
function()
retObj = constructNew_frmFichaRPGmeister4h_svg();
end,
function()
__o_rrpgObjs.endObjectsLoading();
end);
assert(retObj ~= nil);
return retObj;
end;
local _frmFichaRPGmeister4h_svg = {
newEditor = newfrmFichaRPGmeister4h_svg,
new = newfrmFichaRPGmeister4h_svg,
name = "frmFichaRPGmeister4h_svg",
dataType = "",
formType = "undefined",
formComponentName = "form",
title = "",
description=""};
frmFichaRPGmeister4h_svg = _frmFichaRPGmeister4h_svg;
Firecast.registrarForm(_frmFichaRPGmeister4h_svg);
return _frmFichaRPGmeister4h_svg;
|
ESX = nil
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
ESX.RegisterUsableItem('moottorikitti', function(source)
local _source = source
TriggerClientEvent('esx_korjauskitti:moottori', _source)
end)
RegisterServerEvent('esx_korjauskitti:poistakitti')
AddEventHandler('esx_korjauskitti:poistakitti', function()
local xPlayer = ESX.GetPlayerFromId(source)
xPlayer.removeInventoryItem('moottorikitti', 1)
end)
|
Citizen.CreateThread(function()
SwitchTrainTrack(0, true)
SwitchTrainTrack(3, true)
N_0x21973bbf8d17edfa(0, 120000)
SetRandomTrains(true)
end) |
-- Nexss PROGRAMMER 2.0.0 - Lua
-- Default template for JSON Data
json = require "json"
-- STDIN
local NexssStdin = io.read()
local parsedJson = json.decode(NexssStdin)
-- Modify Data
parsedJson['test'] = "test"
local NexssStdout = json.encode(parsedJson)
-- STDOUT
io.write(NexssStdout) |
return {'enig','enige','enigen','enigerlei','enigermate','enigerwijs','enigerwijze','eniggeboren','enigheid','enigma','enigmatisch','enigst','enigszins','eniac','enigmas','enigmata','enigmatische','enigmatischer','enigste'} |
-- Packet Handlers
Helpers.PacketHandler('lawman:GoOnDuty', function(playerId, data)
Lawman.GoOnDuty(playerId, data.LocationId)
end)
Helpers.PacketHandler('lawman:GoOffDuty', function(playerId, data)
Lawman.GoOffDuty(playerId)
end)
Helpers.PacketHandler('lawman:GetArmoryItem', function(playerId, data)
Lawman.GetArmoryItem(playerId, data.ItemId)
end)
Helpers.PacketHandler('lawman:Cuff', function(playerId, data)
Lawman.Cuff(playerId, data.TargetId)
end)
Helpers.PacketHandler('lawman:Escort', function(playerId, data)
Lawman.Escort(playerId, data.TargetId)
end)
Helpers.PacketHandler('lawman:SearchPersons', function(playerId, data)
Lawman.SearchPersons(playerId, data.FirstName, data.LastName)
end)
Helpers.PacketHandler('lawman:SearchArrests', function(playerId, data)
Lawman.SearchArrests(playerId, data.CaseNumber, data.FirstName, data.LastName)
end)
Helpers.PacketHandler('lawman:SearchWarrants', function(playerId, data)
Lawman.SearchWarrants(playerId, data.CaseNumber, data.FirstName, data.LastName)
end)
Helpers.PacketHandler('lawman:AddNote', function(playerId, data)
Lawman.AddNote(playerId, data.LocationId, data.TargetId, data.Message)
end)
-- Class Functions
function Lawman.GoOnDuty(playerId, locationId)
-- validate/get this location
local location = Lawman.Locations[locationId]
if (location == nil) then
return
end
if (location.SheriffId ~= nil) then
Helpers.Respond(playerId, '^1We already have a sheriff.')
return
end
-- get character
Helpers.GetCharacter(playerId, function(character)
-- validate that this person can do this
if (character.getPermissions() < 5) then
Helpers.Respond(playerId, '^1You can\'t do that.')
return
end
-- set sheriff id for this location
location.SheriffId = playerId
-- notify the player that she went on duty
Helpers.Respond(playerId, '^2You went on duty, Sheriff.')
Helpers.Packet(playerId, 'lawman:SetDuty', { Value = true })
end)
end
function Lawman.GoOffDuty(playerId)
-- set this person as off duty if on duty
for k, v in pairs(Lawman.Locations) do
if (v.SheriffId == playerId) then
v.SheriffId = nil
break
end
end
-- do stuffs
Helpers.Respond(playerId, '^2You went off duty, Sheriff.')
Helpers.Packet(playerId, 'lawman:SetDuty', { Value = false })
end
function Lawman.OnPlayerDropped(playerId)
-- clear this person if they are a sheriff
for k, v in pairs(Lawman.Locations) do
if (v.SheriffId == playerId) then
v.SheriffId = nil
break
end
end
end
function Lawman.GetArmoryItem(playerId, locationId, itemId)
-- get location of this armory
local location = Lawman.Locations[locationId]
if (location == nil) then
return
end
-- make sure this is the sheriff
if (location.SheriffId ~= playerId) then
Helpers.Respond(playerId, '^1You are not a lawman.')
return
end
-- validate item data
local itemData = location.Armory[itemId]
if (itemData == nil) then
return
end
-- get inventory data and add item
Helpers.GetInventory(function(inventory)
inventory.addItem(playerId, itemData.Name, itemData.Ammo, itemData.WeaponHash)
end)
end
function Lawman.Cuff(playerId, targetId)
print('try to cuff ' .. playerId .. ' ' .. tostring(targetId))
Helpers.GetCharacter(playerId, function(lawman)
-- validate lawman
if (lawman == nil) then
return
end
Helpers.GetCharacter(targetId, function(suspect)
-- validate suspect
if (suspect == nil) then
print('no suspect in cuff')
return
end
-- assign session var
local isCuffed = suspect.getSessionVar('IsCuffed') or false
suspect.setSessionVar('IsCuffed', not isCuffed)
-- notify target that cuffs need to be put on
Helpers.Packet(targetId, 'player:Restrain', { LawmanId = playerId, RestraintType = 0 })
end)
end)
end
function Lawman.Escort(playerId, targetId)
Helpers.GetCharacter(playerId, function(lawman)
-- validate lawman
if (lawman == nil) then
return
end
Helpers.GetCharacter(targetId, function(suspect)
-- validate suspect
if (suspect == nil) then
return
end
-- assign session var
local isEscorted = suspect.getSessionVar('IsEscorted') or false
suspect.setSessionVar('IsEscorted', not isEscorted)
-- notify target that cuffs need to be put on
Helpers.Packet(targetId, 'player:Escort', { LawmanId = playerId })
end)
end)
end
function Lawman.SearchPersons(playerId, firstName, lastName)
-- note:
-- i am forced to use the LOWER function here because case sensitivty matters on the `characters` table apparently.
-- this table is created with the redemrp_identity script so i don't want to change it as this will affect everyone
-- that uses that resource.
local query = 'select * from `characters` where '
local queryAdds = ''
if (firstName ~= nil and #firstName > 0) then
queryAdds = queryAdds .. 'lower(FirstName) like @FirstName'
end
if (lastName ~= nil and #lastName > 0) then
if (#queryAdds > 0) then
queryAdds = queryAdds .. ' or '
end
queryAdds = queryAdds .. 'lower(LastName) like @LastName'
end
query = query .. queryAdds
print(query)
local params = {
['@FirstName'] = string.lower('%' .. firstName .. '%'),
['@LastName'] = string.lower('%' .. lastName .. '%')
}
-- perform query
MySQL.Async.fetchAll(query, params, function(results)
if (results == nil or results[1] == nil) then
print('no results')
end
Helpers.Packet(playerId, 'lawman:OnSearchPersons', { Results = results })
end)
end
function Lawman.SearchArrests(playerId, caseNumber, firstName, lastName)
local query = 'select * from `arrests` as a inner join `characters` as c on a.CharacterId = c.Id where a.CaseNumber like @CaseNumber or c.FirstName like @FirstName or c.LastName like @LastName'
local params = {
['@CaseNumber'] = '%' .. caseNumber .. '%',
['@FirstName'] = '%' .. firstName .. '%',
['@LastName'] = '%' .. lastName .. '%',
}
-- perform query
MySQL.Async.fetchAll(query, params, function(results)
Helpers.Packet(playerId, 'lawman:OnSearchArrests', { Results = results })
end)
end
function Lawman.SearchWarrants(playerId, caseNumber, firstName, lastName)
local query = 'select * from `warrants` as a inner join `characters` as c on a.CharacterId = c.Id where a.CaseNumber like @CaseNumber or c.FirstName like @FirstName or c.LastName like @LastName'
local params = {
['@CaseNumber'] = '%' .. caseNumber .. '%',
['@FirstName'] = '%' .. firstName .. '%',
['@LastName'] = '%' .. lastName .. '%',
}
-- perform query
MySQL.Async.fetchAll(query, params, function(results)
Helpers.Packet(playerId, 'lawman:OnSearchWarrants', { Results = results })
end)
end
function Lawman.AddNote(playerId, locationId, targetId, message)
if (#message > 255) then
message = string.sub(message, 0, 254)
end
Helpers.GetCharacter(playerId, function(sheriff)
Helpers.GetCharacter(targetId, function(target)
local query = 'insert into `characternotes` set (CharacterId, SheriffId, LocationId, Message) values (@CharacterId, @SheriffId, @LocationId, @Message); select LAST_INSERT_ID();'
local params = {
['@CharacterId'] = target.Id,
['@SheriffId'] = sheriff.Id,
['@LocationId'] = locationId,
['@Message'] = message
}
-- perform query
MySQL.Async.fetchScalar(query, params, function(returnId)
--
end)
end)
end)
end
-- Payment Timer
function Lawman.PayTimer()
SetTimeout(60000*5, function()
for k, v in pairs(Lawman.Locations) do
if (v.SheriffId ~= nil) then
Helpers.GetCharacter(v.SheriffId, function(character)
character.addXP(5)
character.addMoney(4)
Helpers.Respond(v.SheriffId, '^2You have been paid $4.00 and received 5 xp for your work, Sheriff.')
end)
end
end
Lawman.PayTimer()
end)
end
Lawman.PayTimer() |
---
-- Plot a real-valued signal in a gnuplot time plot. This sink requires the
-- gnuplot program. This sink should be used with relatively low sample rates,
-- as it does not skip any samples, or it may otherwise throttle a flow graph.
--
-- @category Sinks
-- @block GnuplotPlotSink
-- @tparam int num_samples Number of samples to plot
-- @tparam[opt=""] string title Title of plot
-- @tparam[opt={}] table options Additional options, specifying:
-- * `xlabel` (string, default "Sample Number")
-- * `ylabel` (string, default "Value")
-- * `yrange` (array of two numbers, default `nil`
-- for autoscale)
-- * `extra_settings` (array of strings containing
-- gnuplot commands)
--
-- @signature in:Float32 >
--
-- @usage
-- -- Plot a 1 kHz cosine sampled at 250 kHz
-- local src = radio.SignalSource('cosine', 1e3, 250e3)
-- local throttle = radio.ThrottleBlock()
-- local snk = radio.GnuplotPlotSink(1000, 'Cosine')
-- top:connect(src, throttle, snk)
local ffi = require('ffi')
local block = require('radio.core.block')
local types = require('radio.types')
local GnuplotPlotSink = block.factory("GnuplotPlotSink")
function GnuplotPlotSink:instantiate(num_samples, title, options)
self.num_samples = assert(num_samples, "Missing argument #1 (num_samples)")
self.title = title or ""
self.options = options or {}
self.sample_count = 0
self:add_type_signature({block.Input("in", types.Float32)}, {})
end
function GnuplotPlotSink:initialize()
-- Check gnuplot exists
local ret = os.execute("gnuplot --version >/dev/null 2>&1")
assert(ret == 0 or ret == true, "gnuplot not found. Is gnuplot installed?")
end
function GnuplotPlotSink:write_gnuplot(s)
local len = 0
while len < #s do
local bytes_written = tonumber(ffi.C.fwrite(ffi.cast("char *", s) + len, 1, #s - len, self.gnuplot_f))
if bytes_written <= 0 then
error("gnuplot write(): " .. ffi.string(ffi.C.strerror(ffi.errno())))
end
len = len + bytes_written
end
end
function GnuplotPlotSink:initialize_gnuplot()
-- Initialize gnuplot
self.gnuplot_f = io.popen("gnuplot >/dev/null 2>&1", "w")
self:write_gnuplot("set xtics\n")
self:write_gnuplot("set ytics\n")
self:write_gnuplot("set grid\n")
self:write_gnuplot("set style data linespoints\n")
self:write_gnuplot("unset key\n")
self:write_gnuplot(string.format("set xlabel '%s'\n", self.options.xlabel or "Sample Number"))
self:write_gnuplot(string.format("set ylabel '%s'\n", self.options.ylabel or "Value"))
self:write_gnuplot(string.format("set title '%s'\n", self.title))
-- Set xrange to number of samples
self:write_gnuplot(string.format("set xrange [%d:%d]\n", 0, self.num_samples))
-- Use yrange if it was specified, otherwise default to autoscale
if self.options.yrange then
self:write_gnuplot(string.format("set yrange [%f:%f]\n", self.options.yrange[1], self.options.yrange[2]))
else
self:write_gnuplot("set autoscale y\n")
end
-- Apply any extra settings
if self.options.extra_settings then
for i = 1, #self.options.extra_settings do
self:write_gnuplot(self.options.extra_settings[i] .. "\n")
end
end
-- Build plot string
self.plot_str = string.format("plot '-' binary format='%%float32' array=%d using 1 linestyle 1\n", self.num_samples)
self:write_gnuplot(self.plot_str)
end
function GnuplotPlotSink:process(x)
if not self.gnuplot_f then
self:initialize_gnuplot()
end
for i = 0, x.length-1 do
-- Write each raw sample
self:write_gnuplot(ffi.string(x.data[i], ffi.sizeof(x.data[0])))
self.sample_count = self.sample_count + 1
-- Restart plot when we reach num_samples
if self.sample_count == self.num_samples then
self.sample_count = 0
self:write_gnuplot(self.plot_str)
end
end
end
function GnuplotPlotSink:cleanup()
if not self.gnuplot_f then
return
end
self.gnuplot_f:write("quit\n")
self.gnuplot_f:close()
end
return GnuplotPlotSink
|
require( "debugLog" )
function make_logistics_wagon_items( wName, wFilePath )
local item =
{
type = "item",
name = wName,
icon = "__LogisticsWagons__/resources/icons/" .. wFilePath .. ".png",
icon_size = 32,
subgroup = "transport",
order = "a[train-system]-z[" .. wName .. "]",
place_result = wName,
stack_size = 5
}
data:extend( { item } )
end
make_logistics_wagon_items( "lw-cargo-wagon-passive" , "wagon-passive-provider" )
make_logistics_wagon_items( "lw-cargo-wagon-active" , "wagon-active-provider" )
make_logistics_wagon_items( "lw-cargo-wagon-requester", "wagon-requester" )
make_logistics_wagon_items( "lw-cargo-wagon-storage" , "wagon-storage" )
make_logistics_wagon_items( "lw-cargo-wagon-buffer" , "wagon-buffer" )
|
--Copyright © 2017, Krizz
--All rights reserved.
--Redistribution and use in source and binary forms, with or without
--modification, are permitted provided that the following conditions are met:
-- * Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of thtracker nor the
-- names of its contributors may be used to endorse or promote products
-- derived from this software without specific prior written permission.
--THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
--ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
--WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
--DISCLAIMED. IN NO EVENT SHALL KRIZZ BE LIABLE FOR ANY
--DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
--(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
--LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
--ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
--(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
--SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
_addon.name = 'THTracker'
_addon.author = 'Krizz'
_addon.version = 1.2
_addon.commands = {'thtracker', 'th'}
config = require ('config')
texts = require ('texts')
packets = require('packets')
require('logger')
defaults = {}
defaults.pos = {}
defaults.pos.x = 1000
defaults.pos.y = 200
defaults.color = {}
defaults.color.alpha = 200
defaults.color.red = 200
defaults.color.green = 200
defaults.color.blue = 200
defaults.bg = {}
defaults.bg.alpha = 200
defaults.bg.red = 30
defaults.bg.green = 30
defaults.bg.blue = 30
settings = config.load(defaults)
th = texts.new('${th_string}', settings)
local th_table = {}
windower.register_event('addon command', function(command, ...)
command = command and command:lower()
local args = {...}
if command == 'pos' then
local posx, posy = tonumber(params[2]), tonumber(params[3])
if posx and posy then
th:pos(posx, posy)
end
elseif command == "hide" then
th:hide()
elseif command == 'show' then
th:show()
else
print('th help : Shows help message')
print('th pos <x> <y> : Positions the list')
print('th hide : Hides the box')
print('th show : Shows the box')
end
end)
windower.register_event('incoming chunk', function(id, data)
if id == 0x028 then
local packet = packets.parse('incoming', data)
if packet.Category == 1 and packet['Target 1 Action 1 Has Added Effect'] and packet['Target 1 Action 1 Added Effect Message'] == 603 then
th_table[packet['Target 1 ID']] = 'TH: '..packet['Target 1 Action 1 Added Effect Param']
update_text()
elseif packet.Category == 3 and packet['Target 1 Action 1 Message'] == 608 then
th_table[packet['Target 1 ID']] = 'TH: '..packet['Target 1 Action 1 Param']
update_text()
end
elseif id == 0x038 then
local packet = packets.parse('incoming', data)
if th_table[packet['Mob']] and packet['Type'] == 'kesu' then
th_table[packet['Mob']] = nil
update_text()
end
elseif id == 0x00E then
local packet = packets.parse('incoming', data)
if th_table[packet['NPC']] and packet['Status'] == 0 and packet['HP %'] == 100 then
th_table[packet['NPC']] = nil
update_text()
end
end
end)
windower.register_event('zone change', function()
th_table = {}
update_text()
end)
windower.register_event('target change', function()
update_text()
end)
function update_text()
local current_string
local target = windower.ffxi.get_mob_by_target('st') or windower.ffxi.get_mob_by_target('t')
if target and th_table[target.id] then
current_string = target.name..'\n '..th_table[target.id]
th:show()
else
current_string = ''
th:hide()
end
th.th_string = current_string
end
|
--[[
Sample plugin file for highlight 3.9
]]
Description="Capitalize keywords if the syntax is not case sensitive."
-- optional parameter: syntax description
function syntaxUpdate(desc)
if IgnoreCase ~=true then
return
end
function Decorate(token, state)
if (state == HL_KEYWORD and not token:match("%W")) then
cap=token:gsub("^%l", string.upper) --why do I need cap variable here???
return cap
end
end
end
Plugins={
{ Type="lang", Chunk=syntaxUpdate },
}
|
function GetTimeString(amt)
local minutes = math.floor(amt / 60)
local seconds = math.floor(amt % 60)
local timestring = ""
if minutes > 0 and seconds > 0 then
timestring = minutes .. " minutes and " .. seconds .. " seconds."
elseif seconds > 0 then
timestring = seconds .. " seconds."
elseif minutes > 0 then
timestring = minutes .. " minutes."
end
return timestring
end
function DoTimeString(ply, Job)
if Job == CLASS_POLICE && ply.OCRPData["JobCoolDown"].Police then
local amt = ply.OCRPData["JobCoolDown"].Police - CurTime()
ply:Hint("You cannot be a cop for another " .. GetTimeString(amt))
return
elseif Job == CLASS_MEDIC && ply.OCRPData["JobCoolDown"].Medic then
local amt = ply.OCRPData["JobCoolDown"].Medic - CurTime()
ply:Hint("You cannot be a medic for another " .. GetTimeString(amt))
return
elseif Job == CLASS_FIREMAN && ply.OCRPData["JobCoolDown"].Fireman then
local amt = ply.OCRPData["JobCoolDown"].Fireman - CurTime()
ply:Hint("You cannot be a fireman for another " .. GetTimeString(amt))
return
elseif Job == CLASS_Tow and ply.OCRPData["JobCoolDown"].Tow then
local amt = ply.OCRPData["JobCoolDown"].Tow - CurTime()
ply:Hint("You cannot be a tow truck driver for another " .. GetTimeString(amt))
return
elseif Job == CLASS_TAXI and ply.OCRPData["JobCoolDown"].Taxi then
local amt = ply.OCRPData["JobCoolDown"].Tow - CurTime()
ply:Hint("You cannot be a taxi driver for another " .. GetTimeString(amt))
return
end
end
util.AddNetworkString("OCRP_JobTimeString")
net.Receive("OCRP_JobTimeString", function(len, ply)
DoTimeString(ply, net.ReadInt(32))
end)
function OCRP_Job_Join( ply ,Job)
if ply:Team() != CLASS_CITIZEN then
return
end
if Job == CLASS_Mayor and !ply.Mayor then
return false
end
if Job == CLASS_POLICE and !ply:NearNPC( "Cop" ) then
return false
end
if Job == CLASS_MEDIC and !ply:NearNPC( "Medic" ) then
return false
end
if Job == CLASS_FIREMAN and !ply:NearNPC( "Fireman" ) then
return false
end
if Job == CLASS_CHIEF and !ply.DueToBeChief then
return false
end
if Job == CLASS_SWAT and !ply.DueToBeSWAT then
return false
end
if Job == CLASS_Tow and !ply:NearNPC("Tow") then
return false
end
if Job == CLASS_TAXI and !ply:NearNPC("Taxi") then
return false
end
if ply:IsBlacklisted(Job) then
ply:Hint( "You have been blacklisted from this job. Go to the forums to appeal." )
return
end
if ply:GetWarranted() >= 1 then
ply:Hint("You can't join this job with a warrant on you.")
return
end
if OCRPCfg[Job].Condition != nil then
OCRPCfg[Job].Condition(ply)
end
if !ply:HasItem("item_policeradio") then
if Job != CLASS_TAXI and Job != CLASS_Tow then
ply:GiveItem("item_policeradio")
end
end
if Job == CLASS_SWAT then
ply:BodyArmor(5)
end
for _,weapon in pairs(OCRPCfg[Job].Weapons) do
ply:Give(weapon)
end
ply:SetTeam( Job )
-- for k, v in pairs( ply.OCRPData["Wardrobe"] ) do
-- if tostring(v.Choice) == tostring(true) then
-- thekey = v.Key
-- break
-- end
-- end
for _,item in pairs(GAMEMODE.OCRP_Items) do
if item.Weapondata != nil && ply:HasItem(_) && item.Weapondata.Weapon != "weapon_physgun" && ply:HasWeapon(item.Weapondata.Weapon) then
for _,wep in pairs(ply:GetWeapons()) do
if wep:GetClass() == item.Weapondata.Weapon then
if wep:Clip1() > 0 then
wep:EmptyClip()
end
end
end
ply:StripWeapon(item.Weapondata.Weapon)
end
end
ply.OCRPData["MyModel"] = ply:GetModel()
for _,car in pairs(ents.FindByClass("prop_vehicle_jeep")) do
if car:IsValid() and car:GetNWInt("Owner") > 0 then
if car:GetNWInt("Owner") == ply:EntIndex() then
car:Remove()
end
end
end
if Job == CLASS_POLICE then
SV_PrintToAdmin( ply, "JOB-JOIN-POLICE", ply:Nick() .." just became a Police Officer" )
ply:StripAmmo()
ply:GiveItem("item_ammo_cop",32)
ply:UpdateAmmoCount()
elseif Job == CLASS_SWAT then
SV_PrintToAdmin( ply, "JOB-JOIN-SWAT", ply:Nick() .." just became a SWAT member" )
ply:StripAmmo()
ply:GiveItem("item_ammo_cop",32)
ply:UpdateAmmoCount()
elseif Job == CLASS_CHIEF then
SV_PrintToAdmin( ply, "JOB-JOIN-CHIEF", ply:Nick() .." just became a chief of the police force" )
ply:StripAmmo()
ply:GiveItem("item_ammo_cop",32)
ply:UpdateAmmoCount()
elseif Job == CLASS_MEDIC then
SV_PrintToAdmin( ply, "JOB-JOIN-MEDIC", ply:Nick() .." just became a medic" )
elseif Job == CLASS_FIREMAN then
local rad2 = math.random( 1, 3 )
NUMBER_FIREMEN = NUMBER_FIREMEN + 1
SV_PrintToAdmin( ply, "JOB-JOIN-FIREMAN", ply:Nick() .." just became a fireman" )
elseif Job == CLASS_Mayor then
SV_PrintToAdmin( ply, "JOB-JOIN-MAYOR", ply:Nick() .." just became the mayor" )
elseif Job == CLASS_Tow then
SV_PrintToAdmin(ply, "JOB-JOIN-TOW", ply:Nick() .. " just became a tow truck driver!")
elseif Job == CLASS_TAXI then
SV_PrintToAdmin(ply, "JOB-JOIN-TAXI", ply:Nick() .. " just became a taxi driver!")
end
ply:SetJobModel()
ply:StripAmmo()
ply:UpdateAmmoCount()
local org = OCRP_Orgs[ply:GetOrg()]
if org and not org.Perks[3] then
if GAMEMODE.OCRPPerks[3].Check(ply:GetOrg()) then
org.Perks[3] = true
for _,member in pairs(org.Members) do
local p = player.GetBySteamID(member.SteamID)
if p and p:IsValid() then
p:Hint("Congratulations, your org has unlocked the " .. GAMEMODE.OCRPPerks[3].Name .. " perk!")
GAMEMODE.OCRPPerks[3].Function(p)
end
end
end
end
end
net.Receive("OCRP_Job_Join", function(len, ply)
OCRP_Job_Join( ply ,net.ReadInt(32))
end)
function PMETA:DoJobCoolDown()
if self:Team() == CLASS_CITIZEN then return end
if self:Team() == CLASS_POLICE then
self.OCRPData["JobCoolDown"].Police = CurTime() + 300
timer.Simple(300,function() if self:IsValid() then self.OCRPData["JobCoolDown"].Police = false self:SetNWBool("JobCD_" .. tostring(CLASS_POLICE), false) end end)
self:Hint("You may not be a cop for 5 minutes.")
elseif self:Team() == CLASS_MEDIC then
self.OCRPData["JobCoolDown"].Medic = CurTime() + 300
timer.Simple(300,function() if self:IsValid() then self.OCRPData["JobCoolDown"].Medic = false self:SetNWBool("JobCD_" .. tostring(CLASS_MEDIC), false) end end)
self:Hint("You may not be a medic for 5 minutes.")
elseif self:Team() == CLASS_Mayor then
self.OCRPData["JobCoolDown"].Mayor = CurTime() + 300
self:Hint("You may not run for mayor in the next election.")
elseif self:Team() == CLASS_FIREMAN then
self.OCRPData["JobCoolDown"].Fireman = CurTime() + 300
self:Hint("You may not be a fireman for 5 minutes.")
timer.Simple(300, function() if self:IsValid() then self.OCRPData["JobCoolDown"].Fireman = false self:SetNWBool("JobCD_" .. tostring(CLASS_FIREMAN), false) end end)
elseif self:Team() == CLASS_Tow then
self.OCRPData["JobCoolDown"].Tow = CurTime() + 300
self:Hint("You may not be a tow truck driver for 5 minutes.")
timer.Simple(300, function() if self:IsValid() then self.OCRPData["JobCoolDown"].Tow = false self:SetNWBool("JobCD_" .. tostring(CLASS_Tow), false) end end)
elseif self:Team() == CLASS_TAXI then
self.OCRPData["JobCoolDown"].Taxi = CurTime() + 300
self:Hint("You may not be a taxi driver for 5 minutes.")
timer.Simple(300, function() if self:IsValid() then self.OCRPData["JobCoolDown"].Taxi = false self:SetNWBool("JobCD_" .. tostring(CLASS_TAXI), false) end end)
end
self:SetNWBool("JobCD_" .. tostring(self:Team()), true)
end
function PMETA:Resupply()
if self:Team() != CLASS_CITIZEN then
if !self:HasItem("item_policeradio") then
self:GiveItem("item_policeradio")
self:Hint("You have been commissioned a new radio, try not to lose it this time!")
end
else
self:Hint("Only government officials can resupply here.")
end
end
function OCRP_Job_Quit( ply )
if ply:Team() == CLASS_CITIZEN then
return
end
SV_PrintToAdmin( ply, "JOB-QUIT", ply:Nick() .." just quit his job" )
ply:DoJobCoolDown()
for _,weapon in pairs( OCRPCfg[ply:Team()].Weapons) do
if ply:HasWeapon(weapon) then
ply:StripWeapon(weapon)
end
end
if ply:HasWeapon("swat_shotgun_ocrp") then
ply:StripWeapon("swat_shotgun_ocrp")
elseif ply:HasWeapon("swat_ump45_ocrp") then
ply:StripWeapon("swat_ump45_ocrp")
end
if ply:HasItem("item_policeradio") then
ply:RemoveItem("item_policeradio")
end
for _,item in pairs(GAMEMODE.OCRP_Items) do
if item.Weapondata != nil && ply:HasItem(_) && item.Weapondata.Weapon != "weapon_physgun" then
ply:Give(item.Weapondata.Weapon)
end
end
if ply:Team() == CLASS_POLICE || ply:Team() == CLASS_CHIEF || ply:Team() == CLASS_SWAT then
for _,ent in pairs(ents.FindByClass("gov_resupply")) do
if ent:IsValid() then
if ply:HasItem("item_ammo_cop") then
ent.items["item_ammo_cop"] = (ent.items["item_ammo_cop"] or 0) + ply.OCRPData["Inventory"]["item_ammo_cop"]
ply:RemoveItem("item_ammo_cop",ply.OCRPData["Inventory"]["item_ammo_cop"])
end
if ply:HasItem("item_ammo_riot") then
ent.items["item_ammo_riot"] = (ent.items["item_ammo_riot"] or 0) + ply.OCRPData["Inventory"]["item_ammo_riot"]
ply:RemoveItem("item_ammo_riot",ply.OCRPData["Inventory"]["item_ammo_riot"])
end
if ply:HasItem("item_ammo_ump") then
ent.items["item_ammo_ump"] = (ent.items["item_ammo_ump"] or 0) + ply.OCRPData["Inventory"]["item_ammo_ump"]
ply:RemoveItem("item_ammo_ump",ply.OCRPData["Inventory"]["item_ammo_ump"])
end
if ply:HasItem("item_shotgun_cop") then
ent.items["item_shotgun_cop"] = (ent.items["item_shotgun_cop"] or 0) + ply.OCRPData["Inventory"]["item_shotgun_cop"]
ply:RemoveItem("item_shotgun_cop",ply.OCRPData["Inventory"]["item_shotgun_cop"])
end
break
end
end
end
if ply:Team() == CLASS_FIREMAN then
NUMBER_FIREMEN = NUMBER_FIREMEN - 1
end
if ply.OCRPData.CurCar then
if ply.OCRPData.CurCar:IsValid() then
ply.OCRPData.CurCar:Remove()
ply.OCRPData.CurCar = nil
end
end
for k,v in pairs(ents.FindByClass("prop_vehicle_jeep")) do
if v:GetNWInt("Owner") > 0 and ply:EntIndex() == v:GetNWInt("Owner") then
v:Remove()
end
end
ply:SetTeam( CLASS_CITIZEN )
ply:SetModel(ply.OCRPData["MyModel"])
ply:StripAmmo()
ply:UpdateAmmoCount()
end
net.Receive("OCRP_Job_Quit", function(len, ply)
OCRP_Job_Quit( ply )
end)
function OCRP_Job_Demote( ply, FromTeam, demoter )
if demoter:Team() != CLASS_Mayor then
if demoter:GetLevel() > 2 then
return
end
end
local TheTeam
if FromTeam == CLASS_CITIZEN then return end
OCRP_Job_Quit(ply)
if FromTeam == CLASS_POLICE then
TheTeam = "a police officer"
elseif FromTeam == CLASS_CHIEF then
TheTeam = "the Police Chief"
elseif FromTeam == CLASS_SWAT then
TheTeam = "a SWAT agent"
elseif FromTeam == CLASS_FIREMAN then
TheTeam = "a fireman"
elseif FromTeam == CLASS_MEDIC then
TheTeam = "a paramedic"
elseif FromTeam == CLASS_Tow then
TheTeam = "a tow truck driver"
elseif FromTeam == CLASS_TAXI then
TheTeam = "a taxi driver"
end
ply:Hint("You have been demoted from your job as ".. TheTeam .." by the mayor.")
ply:Hint("If you are unsure why, ask the mayor.")
end
net.Receive("OCRP_DemotePlayer", function(len, ply)
for _,v in pairs(player.GetAll()) do
if v:Nick() == net.ReadString() then
OCRP_Job_Demote(v,v:Team(),ply) ply:Hint("Demoted "..v:Nick())
end
end
end)
function OCRP_DEMOTE( ply, ply2 )
if !ply:IsAdmin() then return false end
ply:Hint("You have demoted ".. ply2:Nick() ..".")
ply2:Hint("You have been demoted from your job by an Admin.")
ply2:Hint("If you are unsure why, ask an Admin.")
OCRP_Job_Quit(ply2)
end
function PMETA:GetWarranted( ) -- placeholder
if self:GetNWInt("Warrant") > 0 then
return self:GetNWInt("Warrant")
end
return 0
end
function PMETA:SetWarranted( Warrant ) -- placeholder
self:SetNWInt("Warrant",Warrant)
self:Hint("You have been Warranted")
end
net.Receive("OCRP_WarrantPlayer", function(len, ply)
local nick = net.ReadString()
local w = net.ReadInt(32)
if ply:Team() == CLASS_Mayor || ply:Team() == CLASS_CHIEF then
for _,v in pairs(player.GetAll()) do
if v:Nick() == nick then
v:SetWarranted(w)
if w > 0 then
ply:Hint("Warranted "..v:Nick())
else
ply:Hint("Unwarranted "..v:Nick())
end
end
end
end
end)
function getJobString(job)
if job == 1 then
return "Citizen"
elseif job == 2 then
return"Medic"
elseif job == 3 then
return"Police Officer"
elseif job == 4 then
return"SWAT Member"
elseif job == 5 then
return"Police Chief"
elseif job == 6 then
return"Mayor"
elseif job == 7 then
return "Fireman"
elseif job == 8 then
return"Towtruck Driver"
elseif job == 9 then
return"Taxi Driver"
end
return
end
--[[concommand.Add("OCRP_Blacklist", function(ply, cmd, args)
if not ply:IsAdmin() then return end
if not args[2] or not getJobString(tonumber(args[2])) then
ply:PrintMessage(HUD_PRINTCONSOLE, "Usage: OCRP_Blacklist \"<STEAM_ID>\" <JOB ENUM>")
ply:PrintMessage(HUD_PRINTCONSOLE, "You MUST have quotes around the STEAM ID!")
ply:PrintMessage(HUD_PRINTCONSOLE, "The following are the job enums:")
for i=2,9 do
ply:PrintMessage(HUD_PRINTCONSOLE, "" .. getJobString(i) .. ": " .. i)
end
return
end
if not string.find(args[1], "STEAM_") then
ply:PrintMessage(HUD_PRINTCONSOLE, "Invalid STEAM ID")
return
end
if tonumber(args[2]) == 1 then
ply:PrintMessage(HUD_PRINTCONSOLE, "You can't blacklist a player from Citizen... Who made you an admin anyways?")
return
end
if player.GetBySteamID(args[1]) then
ply:Blacklist(player.GetBySteamID(args[1]), tonumber(args[2]))
else
runOCRPQuery("SELECT * FROM `ocrp_users` WHERE `STEAM_ID` = '" .. ocrpdb:escape(args[1]) .. "'", function(data)
if not data[1] then
if ply:IsValid() then
ply:PrintMessage(HUD_PRINTCONSOLE, "No user found with that STEAM ID")
end
return
end
data[1]["blacklist"] = data[1]["blacklist"] or ""
local ExplodedStr = string.Explode(";", data[1]["blacklist"])
local BLTable = {}
for k,v in pairs(ExplodedStr) do
if tonumber(v) then
BLTable[v] = true
end
end
BLTable[args[2] ] = true
local BLStr = ""
for k,v in pairs(BLTable) do
BLStr = BLStr .. k .. ";"
end
runOCRPQuery("UPDATE `ocrp_users` SET `blacklist` = '" .. ocrpdb:escape(BLStr) .. "' WHERE `STEAM_ID` = '".. ocrpdb:escape(args[1]) .."'", function()
if ply:IsValid() then
ply:PrintMessage(HUD_PRINTCONSOLE, data[1]["nick"] .. " blacklisted from " .. getJobString(tonumber(args[2])))
SV_PrintToAdmin(ply, "BLACKLIST", "blacklisted " .. data[1]["nick"] .. "(" .. data[1]["STEAM_ID"] .. ") from " .. getJobString(tonumber(args[2])))
end
end)
end, function()
ply:Hint("Error updating blacklist in database. Retry and report if error continues.")
end
)
end
end)]]
function PMETA:Blacklist( ply, FromTeam ) -- This is retarded. Why do you call admin:Blacklist(player) instead of player:Blacklist(admin) ??
if !self:IsAdmin() then return false end
if FromTeam == 1 then
self:Hint("You can't blacklist a player from Citizen... Who made you an admin anyways?")
return
end
local TehTxt = getJobString(FromTeam)
ply.OCRPData["Blacklists"] = ply.OCRPData["Blacklists"] or {}
ply.OCRPData["Blacklists"][FromTeam] = true
self:Hint( "You have blacklisted ".. ply:Nick() .." from being a ".. TehTxt .."." )
ply:Hint( "You have been blacklisted from being a ".. TehTxt .."." )
SV_PrintToAdmin(self, "BLACKLIST", "blacklisted " .. ply:Nick() .. " from " .. tehTxt)
if ply:Team() == FromTeam then
OCRP_Job_Quit( ply )
end
end
function PMETA:IsBlacklisted( job )
if job == 1 then return false end
if self.OCRPData["Blacklists"] then
return self.OCRPData["Blacklists"][job]
end
return false
end
function PMETA:UnBlacklist( ply, Team )
if !self:IsAdmin() then return false end
if FromTeam == 1 then
self:Hint("You can't blacklist a player from Citizen... Who made you an admin anyways?")
return
end
local TehTxt = getJobString(Team)
ply.OCRPData["Blacklists"] = ply.OCRPData["Blacklists"] or {}
ply.OCRPData["Blacklists"][Team] = false
self:Hint( "You have unblacklisted ".. ply:Nick() .." from " .. TehTxt .. ".")
self:PrintMessage(HUD_PRINTCONSOLE, "You have unblacklisted " .. ply:Nick() .. " from " .. TehTxt .. ".")
ply:Hint( "You have been unblacklisted from ".. TheTxt .."." )
end
util.AddNetworkString("OCRP_Arrest")
concommand.Add("OCRP_Unblacklist", function(ply, cmd, args)
if #args < 2 then
ply:PrintMessage(HUD_PRINTCONSOLE, "Usage: OCRP_Unblacklist \"<STEAMID>\" <JOB ENUM>")
ply:PrintMessage(HUD_PRINTCONSOLE, "You MUST have quotes around the STEAM ID!")
ply:PrintMessage(HUD_PRINTCONSOLE, "The following are the job enums:")
for i=2,9 do
ply:PrintMessage(HUD_PRINTCONSOLE, "" .. getJobString(i) .. ": " .. i)
end
return
end
local target = player.GetBySteamID(args[1])
if not target or not target:IsValid() then
ply:PrintMessage(HUD_PRINTCONSOLE, "Invalid player. Make sure you typed the STEAM ID properly and surrounded by quotes.")
return
end
if args[2] == "1" then
ply:PrintMessage(HUD_PRINTCONSOLE, "You can't change blacklist settings for the Citizen team... Who made you admin anyways?")
return
end
if not getJobString(args[2]) then
ply:PrintMessage(HUD_PRINTCONSOLE, "Invalid job enum. Type \"OCRP_Unblacklist\" to see a list of the available values.")
return
end
ply:UnBlacklist(target, tonumber(args[2]))
end)
function PMETA:JailPlayer( Time, Bail, Arrester )
if Arrester:Team() != CLASS_POLICE && Arrester:Team() != CLASS_CHIEF then return false end
if Arrester:GetPos():Distance(self:GetPos()) > 100 then return false end
self.Arrested = true
self.Bail = Bail
if self:GetWarranted() == 2 then Time = Time * 1.5 end
net.Start("OCRP_Arrest")
net.WriteInt(CurTime() + Time, 32)
net.WriteInt(Bail, 32)
net.Send(self)
if GAMEMODE.Maps[string.lower(game.GetMap())].Jails != nil then
local free = true
local data = table.Random(GAMEMODE.Maps[string.lower(game.GetMap())].Jails)
for _,objs in pairs(ents.FindInSphere(data.Position,32)) do
if objs:IsPlayer() then
local free = false
break
end
end
if free then
self:SetPos(data.Position + Vector(0,0,10))
self:SetAngles(data.Ang)
else
for _,data in pairs(GAMEMODE.Maps[string.lower(game.GetMap())].Jails) do
free = true
for _,objs in pairs(ents.FindInSphere(data.Position,32)) do
if objs:IsPlayer() then
local free = false
break
end
end
if free then
self:SetPos(data.Position + Vector(0,0,10))
self:SetAngles(data.Ang)
break
end
end
end
end
SV_PrintToAdmin( self, "ARREST", self:Nick() .." was arrested by ".. Arrester:Nick() )
self:StripWeapons()
local hasMayor = false
for bleh,blah in pairs(player.GetAll()) do
if blah:Team() == CLASS_Mayor then
hasMayor = true
end
end
if hasMayor then
for illitem,bool in pairs(GAMEMODE.IllegalItems) do
if self:HasItem(illitem) then
Arrester:AddMoney("Wallet", 100)
Arrester:Hint("You have gained $100 for arresting someone carrying Illegal weapons")
self:RemoveItem(illitem)
SV_PrintToAdmin(self, "ARREST-WEAPON-LOSS", "lost a " .. illitem .. " when arrested.")
break
end
end
end
if !self:GetNWBool("Handcuffed") then
self:SetNWBool("Handcuffed",true)
end
if self:GetWarranted() >= 2 then
Arrester:AddMoney("Wallet", 1000)
Arrester:Hint("You have gained $1000 for arresting a Warranted criminal")
SV_PrintToAdmin(self, "ARREST-REWARD", "gained $1000 for arresting a warranted criminal.")
end
--timer.Simple(Time, function() if self.Arrested then self:UnJail() end end)
timer.Simple(Time, function ( )
if self.Arrested then
self:UnJail()
end
end);
self:SetNWInt("Warrant",0)
end
net.Receive("OCRP_Arrest_Player", function(len, ply1)
local ply = player.GetByID(net.ReadInt(32))
ply:JailPlayer(net.ReadInt(32), net.ReadInt(32), ply1)
end)
net.Receive("OCRP_Handcuffplayer", function(len, ply)
if ply:Team() == CLASS_POLICE || ply:Team() == CLASS_CHIEF then
local player = player.GetByID(net.ReadInt(32))
ply:Hint("You handcuffed "..player:Nick() .. ".")
player:SelectWeapon("weapon_idle_hands_ocrp")
player:SetNWBool("Handcuffed", true )
SV_PrintToAdmin( ply, "HANDCUFF", ply:Nick() .." handcuffed ".. player:Nick() )
end
end)
function PMETA:UnJail()
self:Hint("You have been released from jail.")
self.Arrested = false
self:Spawn()
self:SetNWBool("Handcuffed",false)
end
local EMETA = FindMetaTable("Entity")
function EMETA:BootCar(booter)
if not self:IsValid() then return end
if not self:GetClass() == "prop_vehicle_jeep" then return end
--[[if self:IsGovCar() then
booter:Hint("You cannot boot a government vehicle!")
return
end]]
if self.Boot == true then
self.Boot = false
self.Booter = nil
booter:Hint("You have unbooted this car.")
return
end
local pos = self:GetPos()
if pos.x > 440 and pos.x < 1177 then
if pos.y > 3602 and pos.y < 4601 then
self.Boot = true
self.Booter = booter
if self.rope and self.rope:IsValid() then
self.rope:Remove()
end
return true
else
booter:Hint("You can't boot and ticket a car unless you've towed it to the dealership!")
end
else
booter:Hint("You can't boot and ticket a car unless you've towed it to the dealership!")
end
end
--setpos 6019.138672 -3176.522705 57.048531;
--setpos 3751.103760 -5057.364746 62.556919;
-- This is now part of the ticketing process through F1
--[[function BootCarPress(ply)
if not ply:IsValid() then return end
if ply:Team() ~= CLASS_Tow then return end
if ply.CantUse == true then return end
ply.CantUse = true
timer.Simple(1, function()
if ply:IsValid() then
ply.CantUse = false
end
end)
local tr = util.TraceLine({
start = ply:EyePos(),
endpos = ply:EyePos() + ply:EyeAngles():Forward() * 100,
filter = function(ent)
if ent:GetClass() == "prop_vehicle_jeep" then
target = ent
end
end,
})
if not target or not target:IsValid() then return end
if target:GetPos():Distance(ply:GetPos()) > 100 then return end
target:BootCar(ply)
end
hook.Add("ShowSpare2", "OCRP_BootCar", BootCarPress)]]
net.Receive("OCRP_Pay_Bail", function(len, ply)
ply:TakeMoney(WALLET,ply.Bail)
Mayor_SpawnMoney(ply.Bail)
ply:UnJail()
ply.Bail = 0
umsg.Start("OCRP_Arrest", self) -- Send the arrest to the player
umsg.Long( 0 )
umsg.Long( 0 )
umsg.End()
end)
net.Receive("OCRP_IllegalizeItem", function(len, ply)
local item1 = net.ReadString()
if ply:Team() == CLASS_Mayor then
GAMEMODE.IllegalItems[item1] = tobool(net.ReadInt(2))
end
end) |
Gamestate = require('./libraries/gamestate')
suit = require('./libraries/SUIT/')
local card = require('./src/card')
local cards = card.getCards()
local counter = 0
local cardTimer = 0
local gameTimer = 30
local prevCard = {}
local prevIndex = 0
local score = 0
local gameOver = false
local fadeOut = 255
local winCondition = 0
game = {}
function game:enter(previous)
matchSound = love.audio.newSource('assets/match.mp3')
font = love.graphics.newFont('assets/CaviarDreams.ttf', 60)
smallFont = love.graphics.newFont('assets/CaviarDreams.ttf', 15)
card.loadAssets()
fontColor = {normal = {bg = {255,255,255}, fg = {255,255,255}}}
end
function game:update(dt)
if gameOver == false then
suit.Label(score, {font = font, color = fontColor}, 1, 1, 200, 100)
suit.Label(gameTimer, {font = font, color = fontColor}, 750, 1, 200, 100)
else
game:gameover(dt)
end
gameTimer = string.format("%.02f", gameTimer - dt)
if gameTimer < '0' then
gameOver = true
elseif winCondition == 6 then
gameOver = true
game:gameover(dt)
end
if counter == 2 then
cardTimer = cardTimer + dt
prevCard = {}
end
if cardTimer > 0.9 then
for i, card in ipairs(cards) do
if card.match == false then
card.cardBack = love.graphics.newImage('assets/card-back-1-1.png')
end
end
cardTimer = 0
counter = 0
end
end
function game:draw()
suit.draw()
card.drawCards()
end
-- When the left mouse button is pressed, we flip the card to its face position and check for a match
function game:mousepressed(x, y, button, istouch)
for i, card in ipairs(cards) do
if button == 1 and card.match ~= true and gameOver ~= true then
if x >= card.x and x < card.x + card.width
and y >= card.y and y < card.y + card.height
and counter ~= 2 then
card.cardBack = love.graphics.newImage(card.cardFace)
if prevCard.cardFace == card.cardFace and prevCard ~= card then
matchSound:play()
winCondition = winCondition + 1
score = score + 100
card.match = true
cards[prevIndex].match = true
counter = counter + 1
end
if prevCard ~= card and card.match ~= true then
counter = counter + 1
end
prevCard = card
prevIndex = i
end
end
end
end
function game:gameover(dt)
fadeOut = fadeOut - dt * 50
if winCondition == 6 then
str = "You Won!"
else
str = "Game Over"
end
love.graphics.setColor(255, 255, 255, fadeOut)
if fadeOut < 10 then
suit.Label(str, {font = font, color = fontColor}, 410, 240, 200, 200)
end
if fadeOut < -20 then
suit.Label("Score: "..score, {font = font, color = fontColor}, 370, 400, 320, 320)
suit.Label("Press escape to restart the game...", {font = smallFont, color = fontColor}, 410, 700)
end
if love.keyboard.isDown("escape") then
love.event.quit('restart')
end
end
return game |
function setvalue(address,flags,value) local tt={} tt[1]={} tt[1].address=address tt[1].flags=flags tt[1].value=value gg.setValues(tt) end
gg.alert("HYDRA SCRİPT V3\n Yapan=Hydra🇹🇷","DEWAMKE➡️")
gg.toast("■□□□□□□□□□10% ")
gg.sleep(300)
gg.toast("■■□□□□□□□□20% ")
gg.sleep(300)
gg.toast("■■■□□□□□□□30% ")
gg.sleep(300)
gg.toast("■■■■□□□□□□40% ")
gg.sleep(300)
gg.toast("■■■■■□□□□□50% ")
gg.sleep(300)
gg.toast("■■■■■■□□□□60% ")
gg.sleep(300)
gg.toast("■■■■■■■□□□70% ")
gg.sleep(300)
gg.toast("■■■■■■■■□□80% ")
gg.sleep(300)
gg.toast("■■■■■■■■■□90%. ")
gg.sleep(300)
gg.toast("■■■■■■■■■■100%")
gg.sleep(300)
function HOME()
PM = gg.multiChoice({
"𝙰ntiban",
"𝙽𝙾 𝚁𝙴𝙲𝙾𝙸𝙻",
"YÜKSEK HASAR",
"Vip Anten",
"𝙸𝙿𝙰𝙳 𝚅𝙸𝙴𝚆",
"ARABA UÇUR",
"UZAYAN KOL",
"𝙼𝙰𝙶𝙸𝙲 𝙱𝚄𝙻𝙻𝙴𝚃",
"KAFADAN VURMA",
"🛡️REPORT SİLİCİ🛡️",
"PLAYER ESP",
"NO LAG FLASH",
"UZUN ZIPLAMA",
"❌UZUN ZIPLAMA KAPALI❌ ",
" X EFEKT",
" SMALL CROSHAIR",
" SKİN HACK MENÜ",
"𝙴𝚇𝙸𝚃 ",
}, nil, "HYDRA HACK 𝐕3 SCRİPT ")
if PM == nil then else
if PM[1] == true then v1() end
if PM[2] == true then v2() end
if PM[3] == true then v3() end
if PM[4] == true then v4() end
if PM[5] == true then v5() end
if PM[6] == true then v6() end
if PM[7] == true then v7() end
if PM[8] == true then v8() end
if PM[9] == true then v9() end
if PM[10] == true then v10() end
if PM[11] == true then v11() end
if PM[12] == true then v12() end
if PM[13] == true then v13() end
if PM[14] == true then v14() end
if PM[15] == true then v15() end
if PM[16] == true then v16() end
if PM[17] == true then v17() end
if PM[18] == true then CLOSE() end
end
PmhackXx = -1
end
function v1()
gg.toast("■□□□□□□10%")
gg.sleep(300)
gg.toast("■■□□□□□20%")
gg.sleep(300)
gg.toast("■■■□□□□40%")
gg.sleep(300)
gg.toast("■■■■□□□60%")
gg.sleep(300)
gg.toast("■■■■■□□80%")
gg.sleep(300)
gg.toast("■■■■■■□90%")
gg.sleep(300)
gg.toast("■■■■■■■100%")
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("1.88696049e-40", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResultsCount()
gg.getResults(100000)
gg.editAll("1.5047707e-36", gg.TYPE_FLOAT, false, 536870912, 0, -1)
gg.clearResults()
gg.searchNumber("1.86902387e-40", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResultsCount()
gg.getResults(100000)
gg.editAll("1.5047707e-36", gg.TYPE_FLOAT, false, 536870912, 0, -1)
gg.clearResults()
gg.searchNumber("1.89054781e-40", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResultsCount()
gg.getResults(100000)
gg.editAll("1.5047707e-36", gg.TYPE_FLOAT, false, 536870912, 0, -1)
gg.clearResults()
gg.searchNumber("1.87261119e-40", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResultsCount()
gg.getResults(100000)
gg.editAll("1.5047707e-36", gg.TYPE_FLOAT, false, 536870912, 0, -1)
gg.clearResults()
gg.setRanges(gg.REGION_C_HEAP | gg.REGION_C_DATA | gg.REGION_JAVA_HEAP | gg.REGION_C_BSS | gg.REGION_C_ALLOC)
gg.searchNumber("1.5047707e-36", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1, 0)
gg.searchNumber("1.5047707e-36", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1, 0)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("70368744177664;288233678981562368", gg.TYPE_QWORD)
gg.refineNumber("70368744177664", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("288233678981562368", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("578351706144768;564058054983680", gg.TYPE_QWORD)
gg.refineNumber("578351706144768", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("361418272522109953", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("582749752655872;620137442967552", gg.TYPE_QWORD)
gg.refineNumber("582749752655872", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("288233678981562368", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("565157566611456;566257078239232", gg.TYPE_QWORD)
gg.refineNumber("565157566611456", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("288233678981562368", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("577,252,194,516,992;565157566611456", gg.TYPE_QWORD)
gg.refineNumber("577,252,194,516,992", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("288233678981562368", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("578351706144768;578351706144768", gg.TYPE_QWORD)
gg.refineNumber("578351706144768", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("288233678981562368", gg.TYPE_QWORD)
gg.clearResults()
gg.searchNumber("565157566611456;566257078239232", gg.TYPE_QWORD)
gg.refineNumber("565157566611456", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("288233678981562368", gg.TYPE_QWORD)
gg.clearResults()
gg.searchNumber("565157566611456;566257078239232", gg.TYPE_QWORD)
gg.refineNumber("565157566611456", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("288233678981562368", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("582749752655872;620137442967552", gg.TYPE_QWORD)
gg.refineNumber("582749752655872", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("361418272522109953", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("565157566611456;566257078239232", gg.TYPE_QWORD)
gg.refineNumber("565157566611456", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("288233678981562368", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("582749752655872;620137442967552", gg.TYPE_QWORD)
gg.refineNumber("582749752655872", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("361418272522109953", gg.TYPE_QWORD)
gg.clearResults()
gg.searchNumber("565157566611456;566257078239232", gg.TYPE_QWORD)
gg.refineNumber("565157566611456", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("288233678981562368", gg.TYPE_QWORD)
gg.clearResults()
gg.setVisible(false)
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("565157566611456;566257078239232", gg.TYPE_QWORD)
gg.refineNumber("565157566611456", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("361418272522109953", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("133634;134658", gg.TYPE_DWORD)
gg.refineNumber("133634", gg.TYPE_DWORD)
gg.getResults(200000)
gg.editAll("131842", gg.TYPE_DWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("70,368,744,177,664;288,232,579,469,934,592", gg.TYPE_QWORD)
gg.refineNumber("70,368,744,177,664", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("361418272522109953", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("578,351,706,144,768;564,058,054,983,680", gg.TYPE_QWORD)
gg.refineNumber("578,351,706,144,768", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("288233678981562368", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("582749752655872;620137442967552", gg.TYPE_QWORD)
gg.refineNumber("582749752655872", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("361418272522109953", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("565157566611456;566257078239232", gg.TYPE_QWORD)
gg.refineNumber("565157566611456", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("288233678981562368", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("17,592,186,044,416;582749752655872", gg.TYPE_QWORD)
gg.refineNumber("17,592,186,044,416", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("288233678981562368", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("577252194516992;288233678981562368", gg.TYPE_QWORD)
gg.refineNumber("577252194516992", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("361418272522109953", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("132098;131842", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("132098", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1, 0)
gg.getResults(200000)
gg.editAll("131586", gg.TYPE_DWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("578351706144768;578351706144768", gg.TYPE_QWORD)
gg.refineNumber("578351706144768", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("361418272522109953", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("582749752655872;620137442967552", gg.TYPE_QWORD)
gg.refineNumber("582749752655872", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("288233678981562368", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("565157566611456;566257078239232", gg.TYPE_QWORD)
gg.refineNumber("565157566611456", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("288233678981562368", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("577252194516992;361418272522109953", gg.TYPE_QWORD)
gg.refineNumber("577252194516992", gg.TYPE_QWORD)
gg.getResults(200000)
gg.editAll("288233678981562368", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("133378", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1, 0)
gg.getResults(11082001)
gg.editAll("131842", gg.TYPE_DWORD)
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("131586", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1, 0)
gg.getResults(11082001)
gg.editAll("131842", gg.TYPE_DWORD)
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("134402", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1, 0)
gg.getResults(11082001)
gg.editAll("131842", gg.TYPE_DWORD)
gg.setRanges(gg.REGION_C_ALLOC)
gg.searchNumber("135682", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1, 0)
gg.getResults(11082001)
gg.editAll("131842", gg.TYPE_DWORD)
gg.clearResults()
gg.alert("ʜʏᴅʀᴀ BYPASS ACTIVATED ")
end
function v2()
so=gg.getRangesList('libUE4.so')[1].start
py=21136552
setvalue(so+py,16,0)
py=60403368
setvalue(so+py,16,0)
gg.toast("𝙽𝙾 𝚁𝙴𝙲𝙾𝙸𝙻")
end
function v3()
gg.clearResults()
gg.setRanges(gg.REGION_C_DATA | gg.REGION_CODE_APP)
gg.searchNumber("0.10000000149;64.50088500977", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("0.10000000149", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(50)
gg.editAll("8", gg.TYPE_FLOAT)
gg.clearResults()
gg.setRanges(gg.REGION_BAD)
gg.searchNumber("-88.66608428955;26:512", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("26", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(2)
gg.editAll("-460", gg.TYPE_FLOAT)
gg.clearResults()
gg.searchNumber("-88.73961639404;28:512", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("28", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(2)
gg.editAll("-560", gg.TYPE_FLOAT)
gg.clearResults()
gg.setRanges(gg.REGION_ANONYMOUS)
gg.searchNumber("9.201618;30.5;25", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("25;30.5", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(10)
gg.editAll("250", gg.TYPE_FLOAT)
gg.clearResults()
gg.setRanges(gg.REGION_C_DATA | gg.REGION_CODE_APP)
gg.searchNumber("-298284466;-1.304566e23F", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("-298284466", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(99)
gg.editAll("0", gg.TYPE_DWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_DATA | gg.REGION_CODE_APP)
gg.searchNumber("-1,883,348,481,058,764,210", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(99)
gg.editAll("-1,883,348,485,055,444,540", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_DATA | gg.REGION_CODE_APP)
gg.searchNumber("0.9986295104", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("0.9986295104", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(99)
gg.editAll("1224995", gg.TYPE_FLOAT)
gg.clearResults()
gg.setRanges(gg.REGION_CODE_APP)
gg.searchNumber("-298284466;-1.304566e23F", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("-298284466", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(999)
gg.editAll("0", gg.TYPE_DWORD)
gg.clearResults()
gg.toast("Yᴜ̈ᴋsᴇᴋ Hᴀsᴀʀ Aᴋᴛɪғ")
end
function v4()
gg.clearResults()
gg.setVisible(false)
gg.setRanges(gg.REGION_ANONYMOUS)
gg.searchNumber("0.98900693655~0.98900723457;0.14786802232~0.14786840975;1.1920926e-7::9", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("0.98900693655~0.98900723457", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(100)
gg.editAll("160000", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1, 0)
gg.clearResults()
gg.setVisible(false)
gg.setRanges(32)
gg.searchNumber("88.50576019287F;87.27782440186F;-100.91194152832F;1F::13", 16, false, 536870912, 0, -1)
gg.searchNumber("88.50576019287F;87.27782440186F;1F", 16, false, 536870912, 0, -1)
gg.getResults(90)
gg.editAll("160009", 16)
gg.clearResults()
gg.setVisible(false)
gg.toast("\n ⊱📡⊰Vip ᴀɴᴛᴇɴ Açık✅⊱📡⊰ ")
end
function v5()
so=gg.getRangesList('libUE4.so')[1].start
py=0x3A05C20
setvalue(so+py,16,205)
gg.toast("𝙸𝙿𝙰𝙳 𝚅𝙸𝙴𝚆 ")
end
function v6()
gg.clearResults()
gg.setRanges(gg.REGION_ANONYMOUS)
gg.searchNumber("-980", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(30)
gg.editAll("25000", gg.TYPE_FLOAT)
gg.sleep(800)
gg.editAll("-980", gg.TYPE_FLOAT)
gg.clearResults()
gg.toast("Uçuyoruz✈️️")
end
function v7()
gg.clearResults()
gg.setRanges(gg.REGION_ANONYMOUS)
gg.searchNumber("4138667321167981973", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("4138667321167981973", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(1401)
gg.editAll("4848124999984742400", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_ANONYMOUS)
gg.searchNumber("-4767057191653227520", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("-4767057191653227520", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(1401)
gg.editAll("-4767057191527907328", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_ANONYMOUS)
gg.clearResults()
gg.searchNumber("18.38787841797;0.53867292404;-3.42232513428;1.77635705e-15:13", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("18.38787841797", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(2805)
gg.editAll("130.5419921875", gg.TYPE_FLOAT)
gg.clearResults()
gg.toast("uzayan kol aktif✓ ")
end
function v8()
so=gg.getRangesList('libUE4.so')[1].start
py=0x3E3A718
setvalue(so+py,16,50)
end
function v9()
gg.clearResults()
gg.setRanges(gg.REGION_BAD)
gg.searchNumber("-88.66608428955;26:512", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("26", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(2)
gg.editAll("-460", gg.TYPE_FLOAT)
gg.clearResults()
gg.searchNumber("-88.73961639404;28:512", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("28", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(2)
gg.editAll("-560", gg.TYPE_FLOAT)
gg.clearResults()
gg.setRanges(gg.REGION_ANONYMOUS)
gg.searchNumber("9.201618;30.5;25", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("25;30.5", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(10)
gg.editAll("250", gg.TYPE_FLOAT)
gg.clearResults()
gg.toast("Kafadan vurma Etkin🥶")
end
function v10()
os["remove"]("/storage/emulated/0/tencent")
os["remove"]("/storage/emulated/0/MidasOverse")
os["remove"]("/storage/emulated/0/Android/data/com.tencent.ig/files/tbslog")
os["remove"]("/storage/emulated/0/Android/data/com.tencent.ig/files/login-identifier.txt")
os["remove"]("/storage/emulated/0/Android/data/com.tencent.ig/files/cacheFile.txt")
os["remove"]("/storage/emulated/0/Android/data/com.tencent.ig/files/vmpcloudconfig.json")
os["remove"]("/storage/emulated/0/Android/data/com.tencent.ig/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/Logs")
os["remove"]("/storage/emulated/0/Android/data/com.tencent.ig/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/GameErrorNoRecords")
os["remove"]("/storage/emulated/0/Android/data/com.tencent.ig/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/Config/Android/AntiCheat.ini")
os["remove"]("/storage/emulated/0/Android/data/com.tencent.ig/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/Config/Android/IGH5CachePluginConfig.ini")
os["remove"]("/storage/emulated/0/Android/data/com.tencent.ig/cache")
os["remove"]("/storage/emulated/0/tencent")
os["remove"]("/storage/emulated/0/MidasOverse")
os["remove"]("/storage/emulated/0/Android/data/com.pubg.krmobile/files/tbslog")
os["remove"]("/storage/emulated/0/Android/data/com.pubg.krmobile/files/login-identifier.txt")
os["remove"]("/storage/emulated/0/Android/data/com.pubg.krmobile/files/cacheFile.txt")
os["remove"]("/storage/emulated/0/Android/data/com.pubg.krmobile/files/vmpcloudconfig.json")
os["remove"]("/storage/emulated/0/Android/data/com.pubg.krmobile/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/Logs")
os["remove"]("/storage/emulated/0/Android/data/com.pubg.krmobile/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/GameErrorNoRecords")
os["remove"]("/storage/emulated/0/Android/data/com.pubg.krmobile/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/Config/Android/AntiCheat.ini")
os["remove"]("/storage/emulated/0/Android/data/com.pubg.krmobile/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/Config/Android/IGH5CachePluginConfig.ini")
os["remove"]("/storage/emulated/0/Android/data/com.pubg.krmobile/cache")
os["remove"]("/storage/emulated/0/tencent")
os["remove"]("/storage/emulated/0/MidasOverse")
os["remove"]("/storage/emulated/0/Android/data/com.vng.pubgmobile/files/tbslog")
os["remove"]("/storage/emulated/0/Android/data/com.vng.pubgmobile/files/login-identifier.txt")
os["remove"]("/storage/emulated/0/Android/data/com.vng.pubgmobile/files/cacheFile.txt")
os["remove"]("/storage/emulated/0/Android/data/com.vng.pubgmobile/files/vmpcloudconfig.json")
os["remove"]("/storage/emulated/0/Android/data/com.vng.pubgmobile/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/Logs")
os["remove"]("/storage/emulated/0/Android/data/com.vng.pubgmobile/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/GameErrorNoRecords")
os["remove"]("/storage/emulated/0/Android/data/com.vng.pubgmobile/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/Config/Android/AntiCheat.ini")
os["remove"]("/storage/emulated/0/Android/data/com.vng.pubgmobile/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/Config/Android/IGH5CachePluginConfig.ini")
os["remove"]("/storage/emulated/0/Android/data/com.vng.pubgmobile/cache")
gg["toast"](" \nBᴇᴋʟᴇ...10%\n🧽▒▒▒▒▒▒▒▒▒")
gg["sleep"](260)
gg["toast"](" \nBᴇᴋʟᴇ...20%\n🧽🧽▒▒▒▒▒▒▒▒")
gg["sleep"](260)
gg["toast"](" \nBᴇᴋʟᴇ...30%\n🧽🧽🧽▒▒▒▒▒▒▒")
gg["sleep"](260)
gg["toast"](" \nBᴇᴋʟᴇ...40%\n🧽🧽🧽🧽▒▒▒▒▒▒")
gg["sleep"](260)
gg["toast"](" \nBᴇᴋʟᴇ...50%\n🧽🧽🧽🧽🧽▒▒▒▒▒")
gg["sleep"](260)
gg["toast"](" \nBᴇᴋʟᴇ...60%\n🧽🧽🧽🧽🧽🧽▒▒▒▒")
gg["sleep"](260)
gg["toast"](" \nBᴇᴋʟᴇ...70%\n🧽🧽🧽🧽🧽🧽🧽▒▒▒")
gg["sleep"](260)
gg["toast"](" \nBᴇᴋʟᴇ...80%\n🧽🧽🧽🧽🧽🧽🧽🧽▒▒")
gg["sleep"](260)
gg["toast"](" \nBᴇᴋʟᴇ...90%\n🧽🧽🧽🧽🧽🧽🧽🧽🧽▒")
gg["sleep"](260)
gg["toast"](" \nBᴀşᴀʀıʟı…100%\n🧽🧽🧽🧽🧽🧽🧽🧽🧽🧽")
gg.toast("🧽Reportlar Temizlendi🧽")
end
function v11()
gg.clearResults()
gg.setRanges(gg.REGION_CODE_APP)
gg.searchNumber("-299890176D;2046820354D;-494071768D", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("2046820354", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(10)
gg.editAll("2046820353", gg.TYPE_DWORD)
gg.clearResults()
gg.setRanges(gg.REGION_CODE_APP)
gg.searchNumber("-1,901,891,198,734,303,227", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(1)
gg.editAll("-1,901,891,198,902,075,392", gg.TYPE_QWORD)
gg.clearResults()
gg.toast("\n ⊱☠️⊰ ᴘʟᴀʏᴇʀ ᴇsᴘ ⊱☠️⊰")
end
function v12()
gg.clearResults()
gg.setRanges(gg.REGION_C_DATA | gg.REGION_CODE_APP)
gg.searchNumber("-1585267064848315881", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(667478)
gg.editAll("-1585267068834414550", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_DATA | gg.REGION_CODE_APP)
gg.searchNumber("1,873,498,234,778,812,417", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("1,873,498,234,778,812,417", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("1,873,498,234,778,812,417", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(667478)
gg.editAll("1,873,498,234,778,812,416", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_DATA | gg.REGION_CODE_APP)
gg.searchNumber("403,635,275,035,574,273", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("403,635,275,035,574,273", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("403,635,275,035,574,273", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(667478)
gg.editAll("403,635,275,035,574,272", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_DATA | gg.REGION_CODE_APP)
gg.searchNumber("-2,044,616,634,647,180,784", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("-2,044,616,634,647,180,784", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("-2,044,616,634,647,180,784", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(667478)
gg.editAll("-2,044,616,634,647,180,800", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_DATA | gg.REGION_CODE_APP)
gg.searchNumber("-1296744149883614555", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("-1296744149883614555", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("-1296744149883614555", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(667478)
gg.editAll("-1296744153870237696", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_C_DATA | gg.REGION_CODE_APP)
gg.searchNumber("-6.03221444e26;-1.3078764e28;-3.74440972e28;-1.86389771e-20;-1.11445016e28;-9.39921508e20;-1.8331477e27:33", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("-1.86389771e-20", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(667478)
gg.editAll("0", gg.TYPE_FLOAT)
gg.clearResults()
gg.setRanges(gg.REGION_C_DATA | gg.REGION_CODE_APP)
gg.searchNumber("-1505254313802431360", gg.TYPE_QWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(667478)
gg.editAll("-1505254313804899999", gg.TYPE_QWORD)
gg.clearResults()
gg.setRanges(gg.REGION_ANONYMOUS)
gg.searchNumber("30D;10D;0F~1F;257D;3D::40", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("0.08600000292", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(667478)
gg.editAll("0.4", gg.TYPE_FLOAT)
gg.clearResults()
gg.setRanges(gg.REGION_ANONYMOUS)
gg.searchNumber("30D;10D;0.0~1.0F;257D;3D::40", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("0.10000000149", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(100)
gg.editAll("0.4", gg.TYPE_FLOAT)
gg.getResults(667478)
gg.setRanges(gg.REGION_C_DATA | gg.REGION_CODE_APP)
gg.searchNumber('-3.693674e20;-1.2382424e28;-8.5076384e22::', gg.TYPE_FLOAT, false, gg.SIGN_EQUAL)
gg.searchNumber('-1.2382424e28', gg.TYPE_FLOAT, false, gg.SIGN_EQUAL)
gg.getResults(2)
gg.editAll('0', gg.TYPE_FLOAT)
gg.getResults(667478)
gg.toast("No lagFlash ✅")
end
function v13()
gg.clearResults()
gg.setRanges(gg.REGION_ANONYMOUS)
gg.searchNumber("7.0064923e-45F;0.6~1;1065353216D;100F;1065353216D;2500000000F;0.10000000149F;88F::", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("7.0064923e-45F;0.6~1;1065353216D;100F;1065353216D;2500000000F;0.10000000149F;88F::", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("0.6~1", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("0.6~1", gg.TYPE_FLOA, false, gg.SIGN_EQUAL, 0, -1)
sjumpff1 = gg.getResults(2500)
gg.editAll("3.5241295", gg.TYPE_FLOAT)
gg.editAll("3.5241295", gg.TYPE_FLOAT)
gg.clearResults()
gg.searchNumber("300;0;0.05000000075;2;25::17", gg.TYPE_FLOAT, false)
gg.searchNumber("300;0;0.05000000075;2;25::17", gg.TYPE_FLOAT, false)
gg.refineNumber("0.05000000075", gg.TYPE_FLOAT, false)
gg.refineNumber("0.05000000075", gg.TYPE_FLOAT, false)
sjumpff2 = gg.getResults(2400)
gg.editAll("2.1241295", gg.TYPE_FLOAT)
gg.editAll("2.1241295", gg.TYPE_FLOAT)
gg.clearResults()
gg.clearResults()
gg.setRanges(gg.REGION_CODE_APP)
gg.searchNumber("-6.1526231e27;-1.0070975e28::", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("-6.1526231e27", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
sjumpff3 = gg.getResults(1)
gg.editAll("0", gg.TYPE_FLOAT)
gg.clearResults()
gg.toast("🐇 UZUN ZIPLAMA AKTİF🐇")
end
function v14()
gg.clearResults()
gg.clearResults()
gg.toast("❌UZUN ZIPLAMA KAPALI❌ ")
end
function v15()
gg.clearResults()
gg.setRanges(gg.REGION_ANONYMOUS)
gg.searchNumber("10;45", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("10", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(100)
gg.editAll("9999", gg.TYPE_FLOAT)
gg.clearResults()
gg.toast("x ᴇғᴇᴄᴛ ᴀᴋᴛɪғ ")
end
function v16()
gg.clearResults()
gg.setRanges(gg.REGION_CODE_APP)
gg.clearResults()
gg.searchNumber("-1.2382424e28;-1.4239333e28;-1.1144502e28;-1.8331474e27;-7.1608877e24::", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.searchNumber("-1.1144502e28", gg.TYPE_FLOAT, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(100)
gg.editAll("90", gg.TYPE_FLOAT)
gg.clearResults()
gg.toast(" ➕ Namlu Ucu Sabitlendi ➕")
end
function v17()
gg.toast("SKİN HACK")
MB = gg.multiChoice({
"3.SEZON EMOJİSİ",
"6.SEZON EMOJİSİ",
"BUZ DİYARİ M416",
"MASKARA M416",
"KERTENKELE M416",
"⬅️ᴇxɪᴛ"
}, nil, "ʜʏᴅʀᴀ antiban menu")
if MB == nil then
else
if MB[1] == true then
MB1()
end
if MB[2] == true then
MB2()
end
if MB[3] == true then
MB3()
end
if MB[4] == true then
MB4()
end
if MB[5] == true then
MB5()
end
if MB[6] == true then
HOME()
end
end
PUBGMH = -1
end
function MB1()
gg.setRanges(gg.REGION_JAVA_HEAP | gg.REGION_C_HEAP | gg.REGION_C_ALLOC | gg.REGION_C_DATA | gg.REGION_C_BSS | gg.REGION_PPSSPP | gg.REGION_ANONYMOUS)
gg.processResume()
gg.setRanges(gg.REGION_ANONYMOUS)
gg.searchNumber("2,200,101", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("2,200,101", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
revert = gg.getResults(100, nil, nil, nil, nil, nil, nil, nil, nil)
gg.editAll("2,202,101", gg.TYPE_DWORD)
gg.toast("3.SEZON EMOJİSİ AKTİF")
end
function MB2()
gg.setRanges(gg.REGION_JAVA_HEAP | gg.REGION_C_HEAP | gg.REGION_C_ALLOC | gg.REGION_C_DATA | gg.REGION_C_BSS | gg.REGION_PPSSPP | gg.REGION_ANONYMOUS)
gg.processResume()
gg.setRanges(gg.REGION_ANONYMOUS)
gg.searchNumber("2,200,101", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.refineNumber("2,200,101", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
revert = gg.getResults(100, nil, nil, nil, nil, nil, nil, nil, nil)
gg.editAll("2,202,101", gg.TYPE_DWORD)
gg.toast("6.SEZON EMOJİSİ AKTİF")
end
function MB3()
gg.clearResults()
gg.setRanges(gg.REGION_ANONYMOUS)
gg.searchNumber("10100400 ", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(10)
gg.editAll("1101004046", gg.TYPE_DWORD)
gg.clearResults()
gg.toast("BUZ DYARI M416 AKTF")
end
function MB4()
gg.clearResults()
gg.setRanges(gg.REGION_ANONYMOUS)
gg.searchNumber("10100400 ", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(10)
gg.editAll("1101004062", gg.TYPE_DWORD)
gg.clearResults()
gg.toast("MASKARA M416 AKTF")
end
function MB5()
gg.clearResults()
gg.setRanges(gg.REGION_ANONYMOUS)
gg.searchNumber("10100400 ", gg.TYPE_DWORD, false, gg.SIGN_EQUAL, 0, -1)
gg.getResults(10)
gg.editAll("1101004086", gg.TYPE_DWORD)
gg.clearResults()
gg.toast("KERTENKELE M416 AKTF")
end
function CLOSE()
gg.alert("🇹🇷BİZİM SCRİPTİMİZİ KULLANDIGINİZ İÇİN TEŞŞEKUR EDERİZ🇹🇷")
print("HYDRA HACK YİNE BEKLERİZ")
gg.skipRestoreState()
gg.setVisible(true)
os.exit()
end
while true do
if gg.isVisible(true) then
PmhackXx = 1
gg.setVisible(false)
end
if PmhackXx == 1 then
HOME()
end
end
|
require "ISBaseObject"
require "ISUI/ISBackButtonWheel"
require "ISUI/ISInventoryPage"
require "ISUI/ISLayoutManager"
require "ISUI/ISSafetyUI"
---@class ISPlayerDataObject : ISBaseObject
ISPlayerDataObject = ISBaseObject:derive("ISPlayerDataObject");
function ISPlayerDataObject:createInventoryInterface()
local zoom = 2.0;
local playerObj = getSpecificPlayer(self.id);
local bind = playerObj:getJoypadBind();
--[[
if self.id > 0 and bind == -1 then
return;
end
--]]
local isMouse = self.id == 0 and bind == -1;
local register = self.id == 0;
if isMouse then
print("player ".. self.id .. " is mouse");
zoom = 1.34;
else
register = false;
end
zoom = 1.34
local numPlayers = getNumActivePlayers();
self:placeInventoryScreens(self.id, numPlayers, isMouse);
local panel2 = ISInventoryPage:new(self.x1, self.y1, self.w1, self.h1, playerObj:getInventory(), true, zoom);
panel2.player = self.id;
panel2:initialise();
panel2:setUIName("inventory"..self.id)
panel2:addToUIManager();
panel2:setController(bind)
panel2:setInfo(getText("UI_InventoryInfo"));
-- print("createInventoryInterface player="..self.id);
panel2.player = self.id;
panel2.transferAll:setVisible(true);
self.playerInventory = panel2;
self.playerInventory.player = self.id;
if not isMouse then
panel2:setVisible(false);
end
--ISInventoryPage.playerInventory = panel2;
-- if ISContainerPanelInstance == nil then
local panel3 = ISInventoryPage:new(self.x2, self.y2, self.w2, self.h2, nil, false, zoom);
self.lootInventory = panel3;
self.lootInventory.player = self.id;
panel3:setUIName("loot"..self.id)
-- print("loot inv created");
--ISContainerPanelInstance = panel3;
-- panel2:setNewContainer(self.container);
panel3.player = self.id;
panel3:initialise();
panel3:addToUIManager();
panel3:setController(bind)
panel3:setInfo(getText("UI_LootInfo"));
if not isMouse then
panel3:setVisible(false);
end
panel3.lootAll:setVisible(true);
UIManager.setPlayerInventory(self.id, self.playerInventory.javaObject, self.lootInventory.javaObject)
if isMouse then
panel2.pin = false;
panel2.collapseButton:setVisible(false);
panel2.pinButton:setVisible(true);
panel2.pinButton:bringToTop();
panel2.isCollapsed = true;
panel2:setMaxDrawHeight(15);
panel3.pin = false;
panel3.collapseButton:setVisible(false);
panel3.pinButton:setVisible(true);
panel3.pinButton:bringToTop();
panel3.isCollapsed = true;
panel3:setMaxDrawHeight(15);
else
panel2:setPinned()
panel3:setPinned()
end
self.buttonPrompt = ISButtonPrompt:new(self.id);
self.buttonPrompt:initialise();
self.buttonPrompt:addToUIManager();
-- print("loot all visible");
self.contextMenu = ISContextMenu:new(0, 0, 1, 1);
-- print("context menu created");
self.contextMenu:initialise();
-- print("context menu initialised");
self.contextMenu:addToUIManager();
-- print("context menu added");
self.contextMenu:setVisible(false);
self.contextMenu.player = self.id;
local xoff = 300
local yoff = 100
if self.id > 0 then xoff = 70; yoff = 20 end
self.characterInfo = ISCharacterInfoWindow:new(self.x1left + xoff,self.y1top + yoff,400,400,self.id);
self.characterInfo:initialise();
self.characterInfo:addToUIManager();
self.characterInfo:setVisible(isMouse and (self.characterInfo.visibleOnStartup == true));
self.equipped = launchEquippedItem(playerObj);
self.equipped:setX(self.x1left + 10);
self.equipped:setY(self.y1top + 10);
-- end
--panel2 = ISInventoryPage:new(300, 300, 400+32, 400, getPlayer():getInventory());
--panel2:initialise();
--panel2:addToUIManager();
local x = getPlayerScreenLeft(self.id)
local y = getPlayerScreenTop(self.id)
local w = getPlayerScreenWidth(self.id)
local h = getPlayerScreenHeight(self.id)
self.backButtonWheel = ISBackButtonWheel:new(self.id, (x + w) / 2 - 150, (y + h) / 2 - 150, 300, 300)
self.backButtonWheel:setVisible(false)
self.backButtonWheel:setAlwaysOnTop(true)
self.backButtonWheel:addToUIManager()
if isClient() then
self.safetyUI = ISSafetyUI:new(x + w - 150, y + h - 100, self.id)
self.safetyUI:initialise()
self.safetyUI:addToUIManager()
self.safetyUI:setVisible(true)
end
if getCore():getGameMode() ~= "Tutorial" then
self.playerHotbar = ISHotbar:new(playerObj)
self.playerHotbar:initialise();
self.playerHotbar:addToUIManager();
self.playerHotbar:setVisible(isMouse);
end
self.craftingUI = ISCraftingUI:new(0, 0, 800, 600, playerObj)
self.craftingUI:initialise();
self.craftingUI:addToUIManager();
self.craftingUI:setVisible(false);
self.craftingUI:setEnabled(false)
self.mechanicsUI = ISVehicleMechanics:new(0,0,playerObj,nil);
self.mechanicsUI:initialise();
-- self.mechanicsUI:addToUIManager();
self.mechanicsUI:setVisible(false);
self.mechanicsUI:setEnabled(false);
self.vehicleDashboard = ISVehicleDashboard:new(self.id, playerObj)
self.vehicleDashboard:initialise()
self.vehicleDashboard:instantiate()
-- Redisplay the dashboard after a splitscreen player is added.
if playerObj:getVehicle() and playerObj:getVehicle():isDriver(playerObj) then
self.vehicleDashboard:setVehicle(playerObj:getVehicle())
end
self.radialMenu = ISRadialMenu:new(0, 0, 100, 200, self.id)
self.radialMenu:initialise()
if register then
ISLayoutManager.RegisterWindow('inventory'..self.id, ISInventoryPage, self.playerInventory)
ISLayoutManager.RegisterWindow('loot'..self.id, ISInventoryPage, self.lootInventory)
ISLayoutManager.RegisterWindow('crafting'..self.id, ISCraftingUI, self.craftingUI)
ISLayoutManager.RegisterWindow('mechanics'..self.id, ISVehicleMechanics, self.mechanicsUI)
if getCore():getGameMode() == "Tutorial" then
self.characterInfo:setVisible(false);
self.characterInfo:setX(25)
self.characterInfo:setY(300)
self.lootInventory:setVisible(false);
self.playerInventory:setVisible(false);
end
end
end
function ISPlayerDataObject:placeInventoryScreens(playerID, totalPlayers, mouse)
local x = getPlayerScreenLeft(playerID)
local y = getPlayerScreenTop(playerID)
local w = getPlayerScreenWidth(playerID)
local h = getPlayerScreenHeight(playerID)
if mouse then
local divhei = h / 3;
if w < h then
divhei = h / 4;
end
local divwid = round(w / 3)
if divwid < 256 + 32 then
-- min width of ISInventoryPage
divwid = 256 + 32
end
self.x1 = x + w / 2 - divwid;
self.x1left = x;
self.y1top = y;
self.y1 = self.y1top;
self.w1 = divwid;
self.h1 = divhei;
self.x2 = self.x1 + divwid;
self.y2 = self.y1top;
self.w2 = divwid;
self.h2 = divhei;
else
local ww = w
local hh = h
self.x1left = x;
self.x1 = x;
self.y1top = y;
self.y1 = self.y1top + (hh/2);
self.w1 = (ww / 2);
self.h1 = (hh / 2);
self.x2 = self.x1 + self.w1;
self.y2 = self.y1;
self.w2 = (ww / 2);
self.h2 = (hh / 2);
end
print("PLAYER DATA OFFSET " .. playerID);
if playerID > 0 then
getSpecificPlayer(playerID):setOffSetXUI(self.x1);
getSpecificPlayer(playerID):setOffSetYUI(self.y1);
end
print(self.x1);
print(self.y1);
print(self.w1);
print(self.h1);
end
function ISPlayerDataObject:onResolutionChange(oldw, oldh, neww, newh)
if JoypadState.players[self.id+1] then
self:placeInventoryScreens(self.id, getNumActivePlayers(), false)
self.playerInventory:setWidth(self.w1)
self.playerInventory:setHeight(self.h1)
self.playerInventory:setX(self.x1)
self.playerInventory:setY(self.y1)
self.lootInventory:setWidth(self.w2)
self.lootInventory:setHeight(self.h2)
self.lootInventory:setX(self.x2)
self.lootInventory:setY(self.y2)
self.equipped:setX(self.x1left + 10)
self.equipped:setY(self.y1top + 10)
end
local x = getPlayerScreenLeft(self.id)
local y = getPlayerScreenTop(self.id)
local w = getPlayerScreenWidth(self.id)
local h = getPlayerScreenHeight(self.id)
if self.safetyUI then
self.safetyUI:setX(x + w - 100)
self.safetyUI:setY(y + h - 100)
end
if self.vehicleDashboard then
self.vehicleDashboard:onResolutionChange()
end
if JoypadState.players[self.id+1] then
self.characterInfo:setX(x + 70)
self.characterInfo:setY(y + 20)
end
end
function ISPlayerDataObject:new (id)
local o = {}
--o.data = {}
setmetatable(o, self)
self.__index = self
o.id = id;
return o
end
ISPlayerDataObject.onKeyPressed = function(key)
if key == getCore():getKey("Zoom in") then
screenZoomIn();
end
if key == getCore():getKey("Zoom out") then
screenZoomOut();
end
end
-- Events.OnKeyPressed.Add(ISPlayerDataObject.onKeyPressed);
|
local fs = require 'fs'
local path = require 'path'
local timer = require 'timer'
local spawn = require 'coro-spawn'
local function escape(s)
local needs_escape = {
['-'] = true
}
return (s:gsub('.', function(c)
if needs_escape[c] then
return '%' .. c
end
end))
end
local function multipart(req, res, go)
if (req.headers['Content-Type'] or ''):match('^' .. escape('multipart/form-data')) then
req.multipart ={}
local boundary = req.headers['Content-Type']:match('boundary=(.*)$')
boundary = escape(boundary)
local body = req.body:match(boundary .. '(.*)')
for part in body:gmatch('(..-)' .. boundary) do
local name = part:match('name="([^";]*)";')
local filename = part:match('filename="([^\r\n]*)"')
local contents = part:match('Content%-Type[^\r\n]*\r\n\r\n' .. '(.*)' .. '\r\n%-%-$')
if name and filename and contents then
req.multipart[name] = req.multipart[name] or {}
table.insert(req.multipart[name], { filename = filename, contents = contents })
end
end
end
return go()
end
local function write_to_file(filename, contents)
fs.mkdirpSync(path.dirname(filename))
local f = io.open(filename, 'w')
assert(f, 'Cannot open ' .. filename .. ' for writing')
f:write(contents)
f:close()
end
return function(args)
local weblit = require 'weblit'
local app = weblit.app
app.bind({ host = '127.0.0.1', port = 1337 })
app.use(weblit.logger)
app.use(weblit.autoHeaders)
app.use(weblit.static('static'))
app.use(weblit.static('tmp'))
app.use(multipart)
app.route({ method = 'POST', path = '/upload' }, function(req, res)
p(req.multipart)
local rand = math.random(1234567890)
local dir = path.resolve('tmp/' .. rand)
local data
for _, o in pairs(req.multipart.project) do
if o.filename:match(req.multipart.data[1].filename) then
data = o.filename
end
write_to_file(dir .. '/' .. o.filename, o.contents)
end
coroutine.wrap(function()
timer.sleep(10000)
spawn('rm', { args = { '-rf', dir } })
end)()
res.code = 301
res.headers.Location = rand .. '/' .. data
end)
app.route({ path = '/:name' }, function(req, res)
res.body = req.method .. ' - ' .. req.params.name .. '\n'
res.code = 200
res.headers['Content-Type'] = 'text/plain'
end)
app.start()
end
|
local addon = KuiNameplates
local ele = addon:NewElement('AbsorbBar')
-- prototype additions #########################################################
function addon.Nameplate.UpdateAbsorb(f)
f = f.parent
f.state.absorbs = UnitGetTotalAbsorbs(f.unit) or 0
if f.elements.AbsorbBar then
if f.state.health_max and f.state.absorbs > 0 then
f.AbsorbBar:SetMinMaxValues(0,f.state.health_max)
f.AbsorbBar:SetValue(f.state.absorbs)
f.AbsorbBar:Show()
if f.AbsorbBar.spark then
-- show spark for over-absorbs
if f.state.absorbs > f.state.health_max then
f.AbsorbBar.spark:Show()
else
f.AbsorbBar.spark:Hide()
end
end
else
f.AbsorbBar:SetValue(0)
f.AbsorbBar:Hide()
if f.AbsorbBar.spark then
f.AbsorbBar.spark:Hide()
end
end
end
end
-- messages ####################################################################
function ele:Show(f)
f.handler:UpdateAbsorb()
end
-- events ######################################################################
function ele:AbsorbEvent(_,f)
f.handler:UpdateAbsorb()
end
-- enable/disable per frame ####################################################
function ele:EnableOnFrame(f)
if f:IsShown() then
self:Show(f)
end
end
function ele:DisableOnFrame(f)
f.AbsorbBar:Hide()
if f.AbsorbBar.spark then
f.AbsorbBar.spark:Hide()
end
end
-- register ####################################################################
function ele:OnDisable()
for _,f in addon:Frames() do
self:DisableOnFrame(f)
end
end
function ele:OnEnable()
self:RegisterMessage('Show')
self:RegisterUnitEvent('UNIT_MAXHEALTH','AbsorbEvent')
self:RegisterUnitEvent('UNIT_ABSORB_AMOUNT_CHANGED','AbsorbEvent')
end
|
local AddonName, AddonTable = ...
-- Blackrock Caverns
AddonTable.blackrock = {
-- Rom'ogg Bonecrusher
55278,
55279,
55776,
55777,
55778,
56310,
56311,
56312,
56313,
56314,
157608,
-- Corla, Herald of Twilight
55263,
55264,
55265,
55266,
55267,
56295,
56296,
56297,
56298,
56299,
-- Karsh Steelbender
55268,
55271,
55272,
55270,
55269,
56303,
56302,
56301,
56304,
157610,
56300,
-- Beauty
55273,
55274,
55275,
55276,
55277,
56305,
56306,
56307,
56308,
56309,
157607,
-- Ascendant Lord Obsidius
55779,
55780,
55781,
55782,
55784,
55785,
55786,
55787,
55788,
56315,
56317,
56318,
56319,
56320,
56321,
56322,
56323,
56324,
}
|
function iscallable(x)
if type(x) == 'function' then
return true
elseif type(x) == 'table' then
-- It would be elegant and quick to say
-- `return iscallable(debug.getmetatable(x).__call)`
-- but that is actually not quite correct
-- (at least in my experiments), since it appears
-- that the `__call` metamethod must be a *function value*
-- (and not some table that has been made callable)
local mt = debug.getmetatable(x)
return type(mt) == "table" and type(mt.__call) == "function"
else
return false
end
end
return iscallable
|
ix.lang = ix.lang or {}
ix.lang.stored = ix.lang.stored or {}
ix.lang.names = ix.lang.names or {}
function ix.lang.LoadFromDir(directory)
for _, v in ipairs(file.Find(directory.."/sh_*.lua", "LUA")) do
local niceName = v:sub(4, -5):lower()
ix.util.Include(directory.."/"..v, "shared")
if (LANGUAGE) then
if (NAME) then
ix.lang.names[niceName] = NAME
NAME = nil
end
ix.lang.stored[niceName] = table.Merge(ix.lang.stored[niceName] or {}, LANGUAGE)
LANGUAGE = nil
end
end
end
local FormatString = string.format
if (SERVER) then
-- luacheck: globals L
function L(key, client, ...)
local languages = ix.lang.stored
local langKey = ix.option.Get(client, "language", "english")
local info = languages[langKey] or languages.english
return FormatString(info and info[key] or key, ...)
end
-- luacheck: globals L2
function L2(key, client, ...)
local languages = ix.lang.stored
local langKey = ix.option.Get(client, "language", "english")
local info = languages[langKey] or languages.english
if (info and info[key]) then
return FormatString(info[key], ...)
end
end
else
function L(key, ...)
local languages = ix.lang.stored
local langKey = ix.option.Get("language", "english")
local info = languages[langKey] or languages.english
return FormatString(info and info[key] or key, ...)
end
function L2(key, ...)
local langKey = ix.option.Get("language", "english")
local info = ix.lang.stored[langKey]
if (info and info[key]) then
return FormatString(info[key], ...)
end
end
end
|
return {
CACHE_AGE = 3600, -- seconds
ID_DELAY = 5000, -- milliseconds
GATEWAY_DELAY = 500, -- milliseconds,
DISCORD_EPOCH = 1420070400000, -- milliseconds
GATEWAY_VERSION = 6,
DEFAULT_AVATARS = 5,
ZWSP = '\226\128\139',
NS_PER_US = 1000,
US_PER_MS = 1000,
MS_PER_S = 1000,
S_PER_MIN = 60,
MIN_PER_HOUR = 60,
HOUR_PER_DAY = 24,
DAY_PER_WEEK = 7,
}
|
require('components/mutation/mutation_list')
require('components/mutation/mutation_settings')
local validItems = {} -- Empty table to fill with full list of valid airdrop items
local tier1 = {} -- 1000 to 2000 gold cost up to 5 minutes
local tier2 = {} -- 2000 to 3500 gold cost up to 10 minutes
local tier3 = {} -- 3500 to 5000 gold cost up to 15 minutes
local tier4 = {} -- 5000 to 99998 gold cost beyond 15 minutes
local counter = 1 -- Slowly increments as time goes on to expand list of cost-valid items
local varFlag = 0 -- Flag to stop the repeat until loop for tier iterations
function Mutation:Init()
-- Selecting Mutations (Take out if statement for IsInToolsMode if you want to test randomized)
IMBA_MUTATION["imba"] = "frantic"
if IsInToolsMode() then
IMBA_MUTATION["positive"] = "teammate_resurrection"
IMBA_MUTATION["negative"] = "periodic_spellcast"
IMBA_MUTATION["terrain"] = "tug_of_war"
else
Mutation:ChooseMutation("positive", POSITIVE_MUTATION_LIST)
Mutation:ChooseMutation("negative", NEGATIVE_MUTATION_LIST)
Mutation:ChooseMutation("terrain", TERRAIN_MUTATION_LIST)
end
CustomNetTables:SetTableValue("mutations", "mutation", {IMBA_MUTATION})
-- if IMBA_MUTATION["positive"] == "greed_is_good" then
-- LinkLuaModifier("modifier_mutation_greed_is_good", "components/modifiers/mutation/modifier_mutation_greed_is_good.lua", LUA_MODIFIER_MOTION_NONE )
-- end
if IMBA_MUTATION["positive"] == "killstreak_power" then
LinkLuaModifier("modifier_mutation_kill_streak_power", "components/modifiers/mutation/modifier_mutation_kill_streak_power.lua", LUA_MODIFIER_MOTION_NONE )
elseif IMBA_MUTATION["positive"] == "slark_mode" then
LinkLuaModifier("modifier_mutation_shadow_dance", "components/modifiers/mutation/modifier_mutation_shadow_dance.lua", LUA_MODIFIER_MOTION_NONE )
elseif IMBA_MUTATION["positive"] == "super_fervor" then
LinkLuaModifier("modifier_mutation_super_fervor", "components/modifiers/mutation/modifier_mutation_super_fervor.lua", LUA_MODIFIER_MOTION_NONE )
end
-- if IMBA_MUTATION["negative"] == "alien_incubation" then
-- LinkLuaModifier("modifier_mutation_alien_incubation", "components/modifiers/mutation/modifier_mutation_alien_incubation.lua", LUA_MODIFIER_MOTION_NONE )
if IMBA_MUTATION["negative"] == "all_random_deathmatch" then
require('components/mutation/mutators/negative/ardm')
elseif IMBA_MUTATION["negative"] == "death_explosion" then
LinkLuaModifier("modifier_mutation_death_explosion", "components/modifiers/mutation/modifier_mutation_death_explosion.lua", LUA_MODIFIER_MOTION_NONE )
elseif IMBA_MUTATION["negative"] == "defense_of_the_ants" then
LinkLuaModifier("modifier_mutation_ants", "components/modifiers/mutation/modifier_mutation_ants.lua", LUA_MODIFIER_MOTION_NONE )
elseif IMBA_MUTATION["negative"] == "monkey_business" then
LinkLuaModifier("modifier_mutation_monkey_business", "components/modifiers/mutation/modifier_mutation_monkey_business.lua", LUA_MODIFIER_MOTION_NONE )
elseif IMBA_MUTATION["negative"] == "no_health_bar" then
LinkLuaModifier("modifier_no_health_bar", "components/modifiers/mutation/modifier_no_health_bar.lua", LUA_MODIFIER_MOTION_NONE )
elseif IMBA_MUTATION["negative"] == "periodic_spellcast" then
LinkLuaModifier("modifier_mutation_thundergods_wrath", "components/modifiers/mutation/periodic_spellcast/modifier_mutation_thundergods_wrath.lua", LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier("modifier_mutation_track", "components/modifiers/mutation/periodic_spellcast/modifier_mutation_track.lua", LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier("modifier_mutation_rupture", "components/modifiers/mutation/periodic_spellcast/modifier_mutation_rupture.lua", LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier("modifier_mutation_torrent", "components/modifiers/mutation/periodic_spellcast/modifier_mutation_torrent.lua", LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier("modifier_mutation_cold_feet", "components/modifiers/mutation/periodic_spellcast/modifier_mutation_cold_feet.lua", LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier("modifier_mutation_stampede", "components/modifiers/mutation/periodic_spellcast/modifier_mutation_stampede.lua", LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier("modifier_mutation_bloodlust", "components/modifiers/mutation/periodic_spellcast/modifier_mutation_bloodlust.lua", LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier("modifier_mutation_aphotic_shield", "components/modifiers/mutation/periodic_spellcast/modifier_mutation_aphotic_shield.lua", LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier("modifier_mutation_sun_strike", "components/modifiers/mutation/periodic_spellcast/modifier_mutation_sun_strike.lua", LUA_MODIFIER_MOTION_NONE )
-- elseif IMBA_MUTATION["negative"] == "stay_frosty" then
-- LinkLuaModifier("modifier_disable_healing", "components/modifiers/mutation/modifier_disable_healing.lua", LUA_MODIFIER_MOTION_NONE )
-- LinkLuaModifier("modifier_mutation_stay_frosty", "components/modifiers/mutation/modifier_mutation_stay_frosty.lua", LUA_MODIFIER_MOTION_NONE )
end
if IMBA_MUTATION["terrain"] == "danger_zone" then
LinkLuaModifier("modifier_mutation_danger_zone", "components/modifiers/mutation/modifier_mutation_danger_zone.lua", LUA_MODIFIER_MOTION_NONE )
elseif IMBA_MUTATION["terrain"] == "river_flows" then
LinkLuaModifier("modifier_mutation_river_flows", "components/modifiers/mutation/modifier_mutation_river_flows.lua", LUA_MODIFIER_MOTION_NONE )
elseif IMBA_MUTATION["terrain"] == "speed_freaks" then
LinkLuaModifier("modifier_mutation_speed_freaks", "components/modifiers/mutation/modifier_mutation_speed_freaks.lua", LUA_MODIFIER_MOTION_NONE )
elseif IMBA_MUTATION["terrain"] == "sticky_river" then
LinkLuaModifier("modifier_sticky_river", "components/modifiers/mutation/modifier_sticky_river.lua", LUA_MODIFIER_MOTION_NONE )
elseif IMBA_MUTATION["terrain"] == "tug_of_war" then
LinkLuaModifier("modifier_mutation_tug_of_war_golem", "components/modifiers/mutation/modifier_mutation_tug_of_war_golem.lua", LUA_MODIFIER_MOTION_NONE )
elseif IMBA_MUTATION["terrain"] == "wormhole" then
LinkLuaModifier("modifier_mutation_wormhole_cooldown", "components/modifiers/mutation/modifier_mutation_wormhole_cooldown.lua", LUA_MODIFIER_MOTION_NONE )
end
end
function Mutation:Precache(context)
-- if IMBA_MUTATION["positive"] == "killstreak_power" then
PrecacheResource("particle", "particles/hw_fx/candy_carrying_stack.vpcf", context)
-- elseif IMBA_MUTATION["positive"] == "super_fervor" then
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_troll_warlord.vsndevts", context)
-- end
-- if IMBA_MUTATION["negative"] == "death_explosion" then
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_pugna.vsndevts", context)
-- elseif IMBA_MUTATION["negative"] == "death_gold_drop" then
-- PrecacheItemByNameSync("item_bag_of_gold", context)
-- elseif IMBA_MUTATION["negative"] == "monkey_business" then
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_monkey_king.vsndevts", context)
-- elseif IMBA_MUTATION["negative"] == "periodic_spellcast" then
PrecacheResource("particle", "particles/econ/items/zeus/arcana_chariot/zeus_arcana_thundergods_wrath_start_bolt_parent.vpcf", context) -- Thundergod's Wrath
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_abaddon.vsndevts", context) -- Shield
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_ancient_apparition.vsndevts", context) -- Cold Feet
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_bloodseeker.vsndevts", context) -- Rupture
-- PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_bounty_hunter.vsndevts", context) -- Track
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_centaur.vsndevts", context) -- Stampede
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_kunkka.vsndevts", context) -- Torrent
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_ogre_magi.vsndevts", context) -- Bloodlust
-- PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_warlock.vsndevts", context)
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_zuus.vsndevts", context) -- Thundergod's Wrath
-- end
-- if IMBA_MUTATION["terrain"] == "danger_zone" then
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_gyrocopter.vsndevts", context)
-- elseif IMBA_MUTATION["terrain"] == "tug_of_war" then
PrecacheResource("particle", "particles/ambient/tug_of_war_team_dire.vpcf", context)
PrecacheResource("particle", "particles/ambient/tug_of_war_team_radiant.vpcf", context)
PrecacheResource("soundfile", "soundevents/game_sounds_heroes/game_sounds_warlock.vsndevts", context) -- BOB Golem
-- elseif IMBA_MUTATION["terrain"] == "wormhole" then
PrecacheResource("particle", "particles/ambient/wormhole_circle.vpcf", context)
-- end
end
function Mutation:ChooseMutation(mType, mList)
-- Pick a random number within bounds of given mutation list
local random_int = RandomInt(1, #mList)
-- Select a mutation from within that list and place it in the relevant IMBA_MUTATION field
IMBA_MUTATION[mType] = mList[random_int]
--print("IMBA_MUTATION["..mType.."] mutation picked: ", mList[random_int])
end
-- Mutation: Events
function Mutation:OnGameRulesStateChange(keys)
if GameRules:State_Get() == DOTA_GAMERULES_STATE_CUSTOM_GAME_SETUP then
Mutation:Init()
elseif GameRules:State_Get() == DOTA_GAMERULES_STATE_PRE_GAME then
if IMBA_MUTATION["negative"] == "all_random_deathmatch" then
Mutation:ARDM()
end
if IMBA_MUTATION["terrain"] == "no_trees" then
GameRules:SetTreeRegrowTime(99999)
GridNav:DestroyTreesAroundPoint(Vector(0, 0, 0), 50000, false)
Mutation:RevealAllMap(1.0)
elseif IMBA_MUTATION["terrain"] == "omni_vision" then
Mutation:RevealAllMap()
elseif IMBA_MUTATION["terrain"] == "fast_runes" then
RUNE_SPAWN_TIME = 30.0
BOUNTY_RUNE_SPAWN_TIME = 60.0
end
Mutation:UpdatePanorama()
elseif GameRules:State_Get() == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then
if IMBA_MUTATION["negative"] == "periodic_spellcast" then
local buildings = FindUnitsInRadius(DOTA_TEAM_GOODGUYS, Vector(0,0,0), nil, 20000, DOTA_UNIT_TARGET_TEAM_BOTH, DOTA_UNIT_TARGET_BUILDING, DOTA_UNIT_TARGET_FLAG_INVULNERABLE, FIND_ANY_ORDER, false)
local good_fountain = nil
local bad_fountain = nil
for _, building in pairs(buildings) do
local building_name = building:GetName()
if string.find(building_name, "ent_dota_fountain_bad") then
bad_fountain = building
elseif string.find(building_name, "ent_dota_fountain_good") then
good_fountain = building
end
end
local random_int
local counter = 0 -- Used to alternate between negative and positive spellcasts, and increments after each timer call
local varSwap -- Switches between 1 and 2 based on counter for negative and positive spellcasts
local caster
-- initialize to negative
CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["negative"], {0})
Timers:CreateTimer(55.0, function()
varSwap = (counter % 2) + 1
random_int = RandomInt(1, #IMBA_MUTATION_PERIODIC_SPELLS[varSwap])
Notifications:TopToAll({text = IMBA_MUTATION_PERIODIC_SPELLS[varSwap][random_int][2].." Mutation in 5 seconds...", duration = 5.0, style = {color = IMBA_MUTATION_PERIODIC_SPELLS[varSwap][random_int][3]}})
return 60.0
end)
Timers:CreateTimer(60.0, function()
CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["negative"], {varSwap})
if bad_fountain == nil or good_fountain == nil then
log.error("nao cucekd up!!! ")
return 60.0
end
for _, hero in pairs(HeroList:GetAllHeroes()) do
if (hero:GetTeamNumber() == 3 and IMBA_MUTATION_PERIODIC_SPELLS[varSwap][random_int][3] == "Red") or (hero:GetTeamNumber() == 2 and IMBA_MUTATION_PERIODIC_SPELLS[varSwap][random_int][3] == "Green") then
caster = good_fountain
else
caster = bad_fountain
end
hero:AddNewModifier(caster, caster, "modifier_mutation_"..IMBA_MUTATION_PERIODIC_SPELLS[varSwap][random_int][1], {duration=IMBA_MUTATION_PERIODIC_SPELLS[varSwap][random_int][4]})
end
counter = counter + 1
return 60.0
end)
end
if IMBA_MUTATION["terrain"] == "airdrop" then
for k, v in pairs(KeyValues.ItemKV) do -- Go through all the items in KeyValues.ItemKV and store valid items in validItems table
varFlag = 0 -- Let's borrow this memory to suss out the forbidden items first...
if v["ItemCost"] and v["ItemCost"] >= IMBA_MUTATION_AIRDROP_ITEM_MINIMUM_GOLD_COST and v["ItemCost"] ~= 99999 and not string.find(k, "recipe") and not string.find(k, "cheese") then
for _, item in pairs(IMBA_MUTATION_RESTRICTED_ITEMS) do -- Make sure item isn't a restricted item
if k == item then
varFlag = 1
end
end
if varFlag == 0 then -- If not a restricted item (while still meeting all the other criteria...)
validItems[#validItems + 1] = {k = k, v = v["ItemCost"]}
end
end
end
table.sort(validItems, function(a, b) return a.v < b.v end) -- Sort by ascending item cost for easier retrieval later on
--[[
print("Table length: ", #validItems) -- # of valid items
for a, b in pairs(validItems) do
print(a)
for key, value in pairs(b) do
print('\t', key, value)
end
end
]]--
varFlag = 0
-- Create Tier 1 Table
repeat
if validItems[counter].v <= IMBA_MUTATION_AIRDROP_ITEM_TIER_1_GOLD_COST then
tier1[#tier1 + 1] = {k = validItems[counter].k, v = validItems[counter].v}
counter = counter + 1
else
varFlag = 1
end
until varFlag == 1
varFlag = 0
-- Create Tier 2 Table
repeat
if validItems[counter].v <= IMBA_MUTATION_AIRDROP_ITEM_TIER_2_GOLD_COST then
tier2[#tier2 + 1] = {k = validItems[counter].k, v = validItems[counter].v}
counter = counter + 1
else
varFlag = 1
end
until varFlag == 1
varFlag = 0
-- Create Tier 3 Table
repeat
if validItems[counter].v <= IMBA_MUTATION_AIRDROP_ITEM_TIER_3_GOLD_COST then
tier3[#tier3 + 1] = {k = validItems[counter].k, v = validItems[counter].v}
counter = counter + 1
else
varFlag = 1
end
until varFlag == 1
varFlag = 0
-- Create Tier 4 Table
for num = counter, #validItems do
tier4[#tier4 + 1] = {k = validItems[num].k, v = validItems[num].v}
end
varFlag = 0
--[[
print("TIER 1 LIST")
for a, b in pairs(tier1) do
print(a)
for key, value in pairs(b) do
print('\t', key, value)
end
end
print("TIER 2 LIST")
for a, b in pairs(tier2) do
print(a)
for key, value in pairs(b) do
print('\t', key, value)
end
end
print("TIER 3 LIST")
for a, b in pairs(tier3) do
print(a)
for key, value in pairs(b) do
print('\t', key, value)
end
end
print("TIER 4 LIST")
for a, b in pairs(tier4) do
print(a)
for key, value in pairs(b) do
print('\t', key, value)
end
end
]]--
Timers:CreateTimer(110.0, function()
Mutation:SpawnRandomItem()
return 120.0
end)
end
if IMBA_MUTATION["terrain"] == "danger_zone" then
local dummy_unit = CreateUnitByName("npc_dummy_unit_perma", Vector(0, 0, 0), true, nil, nil, DOTA_TEAM_NEUTRALS)
dummy_unit:AddNewModifier(dummy_unit, nil, "modifier_mutation_danger_zone", {})
end
if IMBA_MUTATION["terrain"] == "wormhole" then
-- Assign initial wormhole positions
local current_wormholes = {}
for i = 1, 12 do
local random_int = RandomInt(1, #IMBA_MUTATION_WORMHOLE_POSITIONS)
current_wormholes[i] = IMBA_MUTATION_WORMHOLE_POSITIONS[random_int]
table.remove(IMBA_MUTATION_WORMHOLE_POSITIONS, random_int)
end
-- Create wormhole particles (destroy and redraw every minute to accommodate for reconnecting players)
local wormhole_particles = {}
Timers:CreateTimer(0, function()
for i = 1, 12 do
if wormhole_particles[i] then
ParticleManager:DestroyParticle(wormhole_particles[i], true)
ParticleManager:ReleaseParticleIndex(wormhole_particles[i])
end
wormhole_particles[i] = ParticleManager:CreateParticle("particles/ambient/wormhole_circle.vpcf", PATTACH_CUSTOMORIGIN, nil)
ParticleManager:SetParticleControl(wormhole_particles[i], 0, GetGroundPosition(current_wormholes[i], nil) + Vector(0, 0, 20))
ParticleManager:SetParticleControl(wormhole_particles[i], 2, IMBA_MUTATION_WORMHOLE_COLORS[i])
end
return 60
end)
-- Teleport loop
Timers:CreateTimer(function()
-- Find units to teleport
for i = 1, 12 do
local units = FindUnitsInRadius(DOTA_TEAM_GOODGUYS, current_wormholes[i], nil, 150, DOTA_UNIT_TARGET_TEAM_BOTH, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES + DOTA_UNIT_TARGET_FLAG_INVULNERABLE + DOTA_UNIT_TARGET_FLAG_PLAYER_CONTROLLED, FIND_ANY_ORDER, false)
for _, unit in pairs(units) do
if not unit:HasModifier("modifier_mutation_wormhole_cooldown") then
if unit:IsHero() then
unit:EmitSound("Wormhole.Disappear")
Timers:CreateTimer(0.03, function()
unit:EmitSound("Wormhole.Appear")
end)
else
unit:EmitSound("Wormhole.CreepDisappear")
Timers:CreateTimer(0.03, function()
unit:EmitSound("Wormhole.CreepAppear")
end)
end
unit:AddNewModifier(unit, nil, "modifier_mutation_wormhole_cooldown", {duration = IMBA_MUTATION_WORMHOLE_PREVENT_DURATION})
FindClearSpaceForUnit(unit, current_wormholes[13-i], true)
if unit.GetPlayerID and unit:GetPlayerID() then
PlayerResource:SetCameraTarget(unit:GetPlayerID(), unit)
Timers:CreateTimer(0.1, function()
PlayerResource:SetCameraTarget(unit:GetPlayerID(), nil)
end)
end
end
end
end
return 0.5
end)
end
if IMBA_MUTATION["terrain"] == "tug_of_war" then
local golem
-- Random a team for the initial golem spawn
if RandomInt(1, 2) == 1 then
golem = CreateUnitByName("npc_dota_mutation_golem", IMBA_MUTATION_TUG_OF_WAR_START[DOTA_TEAM_GOODGUYS], false, nil, nil, DOTA_TEAM_GOODGUYS)
golem.ambient_pfx = ParticleManager:CreateParticle("particles/ambient/tug_of_war_team_radiant.vpcf", PATTACH_ABSORIGIN_FOLLOW, golem)
ParticleManager:SetParticleControl(golem.ambient_pfx, 0, golem:GetAbsOrigin())
Timers:CreateTimer(0.1, function()
golem:MoveToPositionAggressive(IMBA_MUTATION_TUG_OF_WAR_TARGET[DOTA_TEAM_GOODGUYS])
end)
else
golem = CreateUnitByName("npc_dota_mutation_golem", IMBA_MUTATION_TUG_OF_WAR_START[DOTA_TEAM_BADGUYS], false, nil, nil, DOTA_TEAM_BADGUYS)
golem.ambient_pfx = ParticleManager:CreateParticle("particles/ambient/tug_of_war_team_dire.vpcf", PATTACH_ABSORIGIN_FOLLOW, golem)
ParticleManager:SetParticleControl(golem.ambient_pfx, 0, golem:GetAbsOrigin())
Timers:CreateTimer(0.1, function()
golem:MoveToPositionAggressive(IMBA_MUTATION_TUG_OF_WAR_TARGET[DOTA_TEAM_BADGUYS])
end)
end
-- Initial logic
golem:AddNewModifier(golem, nil, "modifier_mutation_tug_of_war_golem", {}):SetStackCount(1)
FindClearSpaceForUnit(golem, golem:GetAbsOrigin(), true)
golem:SetDeathXP(50)
golem:SetMinimumGoldBounty(50)
golem:SetMaximumGoldBounty(50)
end
--[[
if IMBA_MUTATION["terrain"] == "minefield" then
local mines = {
"npc_imba_techies_proximity_mine",
"npc_imba_techies_proximity_mine_big_boom",
"npc_imba_techies_stasis_trap",
}
Timers:CreateTimer(function()
local units = FindUnitsInRadius(DOTA_TEAM_NEUTRALS, Vector(0,0,0), nil, FIND_UNITS_EVERYWHERE, DOTA_UNIT_TARGET_TEAM_FRIENDLY, DOTA_UNIT_TARGET_ALL, DOTA_UNIT_TARGET_FLAG_INVULNERABLE + DOTA_UNIT_TARGET_FLAG_OUT_OF_WORLD, FIND_ANY_ORDER, false)
local mine_count = 0
local max_mine_count = 75
for _, unit in pairs(units) do
if unit:GetUnitName() == "npc_imba_techies_proximity_mine" or unit:GetUnitName() == "npc_imba_techies_proximity_mine_big_boom" or unit:GetUnitName() == "npc_imba_techies_stasis_trap" then
if unit:GetUnitName() == "npc_imba_techies_proximity_mine" then
unit:FindAbilityByName("imba_techies_proximity_mine_trigger"):SetLevel(RandomInt(1, 4))
elseif unit:GetUnitName() == "npc_imba_techies_proximity_mine_big_boom" then
unit:FindAbilityByName("imba_techies_proximity_mine_trigger"):SetLevel(RandomInt(1, 4))
elseif unit:GetUnitName() == "npc_imba_techies_stasis_trap" then
unit:FindAbilityByName("imba_techies_stasis_trap_trigger"):SetLevel(RandomInt(1, 4))
end
mine_count = mine_count + 1
end
end
if mine_count < max_mine_count then
for i = 1, 10 do
local mine = CreateUnitByName(mines[RandomInt(1, #mines)], RandomVector(IMBA_MUTATION_MINEFIELD_MAP_SIZE), true, nil, nil, DOTA_TEAM_NEUTRALS)
mine:AddNewModifier(mine, nil, "modifier_invulnerable", {})
end
end
-- print("Mine count:", mine_count)
return 10.0
end)
end
]]
end
end
function Mutation:OnReconnect(id)
CustomGameEventManager:Send_ServerToPlayer(PlayerResource:GetPlayer(id), "send_mutations", IMBA_MUTATION)
CustomGameEventManager:Send_ServerToPlayer(PlayerResource:GetPlayer(id), "update_mutations", {})
end
function Mutation:OnHeroFirstSpawn(hero)
print("Mutation: On Hero First Spawn")
-- Check if we can add modifiers to hero
if not Mutation:IsEligibleHero(hero) then return end
if IMBA_MUTATION["positive"] == "killstreak_power" then
hero:AddNewModifier(hero, nil, "modifier_mutation_kill_streak_power", {})
elseif IMBA_MUTATION["positive"] == "super_blink" then
if not hero:IsIllusion() and not hero:IsClone() then
hero:AddItemByName("item_imba_blink"):SetSellable(false)
end
elseif IMBA_MUTATION["positive"] == "pocket_roshan" then
if not hero:IsIllusion() and not hero:IsClone() then
hero:AddItemByName("item_pocket_roshan")
end
elseif IMBA_MUTATION["positive"] == "pocket_tower" then
if not hero:IsIllusion() and not hero:IsClone() then
hero:AddItemByName("item_pocket_tower")
end
elseif IMBA_MUTATION["positive"] == "greed_is_good" then
hero:AddNewModifier(hero, nil, "modifier_mutation_greed_is_good", {})
elseif IMBA_MUTATION["positive"] == "teammate_resurrection" then
hero.reincarnation = false
elseif IMBA_MUTATION["positive"] == "super_fervor" then
hero:AddNewModifier(hero, nil, "modifier_mutation_super_fervor", {})
elseif IMBA_MUTATION["positive"] == "slark_mode" then
hero:AddNewModifier(hero, nil, "modifier_mutation_shadow_dance", {})
-- elseif IMBA_MUTATION["positive"] == "damage_reduction" then
-- hero:AddNewModifier(hero, nil, "modifier_mutation_damage_reduction", {})
end
if IMBA_MUTATION["negative"] == "death_explosion" then
hero:AddNewModifier(hero, nil, "modifier_mutation_death_explosion", {})
elseif IMBA_MUTATION["negative"] == "no_health_bar" then
hero:AddNewModifier(hero, nil, "modifier_no_health_bar", {})
elseif IMBA_MUTATION["negative"] == "defense_of_the_ants" then
hero:AddNewModifier(hero, nil, "modifier_mutation_ants", {})
elseif IMBA_MUTATION["negative"] == "stay_frosty" then
hero:AddNewModifier(hero, nil, "modifier_mutation_stay_frosty", {})
elseif IMBA_MUTATION["negative"] == "monkey_business" then
hero:AddNewModifier(hero, nil, "modifier_mutation_monkey_business", {})
elseif IMBA_MUTATION["negative"] == "alien_incubation" then
hero:AddNewModifier(hero, nil, "modifier_mutation_alien_incubation", {})
end
if IMBA_MUTATION["terrain"] == "speed_freaks" then
hero:AddNewModifier(hero, nil, "modifier_mutation_speed_freaks", {projectile_speed = IMBA_MUTATION_SPEED_FREAKS_PROJECTILE_SPEED, movespeed_pct = _G.IMBA_MUTATION_SPEED_FREAKS_MOVESPEED_PCT, max_movespeed = IMBA_MUTATION_SPEED_FREAKS_MAX_MOVESPEED})
elseif IMBA_MUTATION["terrain"] == "river_flows" then
hero:AddNewModifier(hero, nil, "modifier_mutation_river_flows", {})
end
end
function Mutation:OnHeroSpawn(hero)
print("Mutation: On Hero Respawned")
-- Check if we can add modifiers to hero
if not Mutation:IsEligibleHero(hero) then return end
if IMBA_MUTATION["negative"] == "all_random_deathmatch" then
if not hero:IsImbaReincarnating() then
Mutation:ARDMReplacehero(hero)
return
else
print("hero is reincarnating, don't change hero!")
return
end
end
if IMBA_MUTATION["positive"] == "teammate_resurrection" then
if hero.tombstone_fx then
ParticleManager:DestroyParticle(hero.tombstone_fx, false)
ParticleManager:ReleaseParticleIndex(hero.tombstone_fx)
hero.tombstone_fx = nil
end
Timers:CreateTimer(FrameTime(), function()
if IsNearFountain(hero:GetAbsOrigin(), 1200) == false and hero.reincarnation == false then
hero:SetHealth(hero:GetHealth() * 50 / 100)
hero:SetMana(hero:GetMana() * 50 / 100)
end
PlayerResource:SetCameraTarget(hero:GetPlayerID(), hero)
Timers:CreateTimer(0.1, function()
PlayerResource:SetCameraTarget(hero:GetPlayerID(), nil)
end)
hero.reincarnation = false
end)
end
end
function Mutation:OnHeroDeath(hero)
-- print("Mutation: On Hero Dead")
if IMBA_MUTATION["positive"] == "teammate_resurrection" then
local newItem = CreateItem("item_tombstone", hero, hero)
newItem:SetPurchaseTime(0)
newItem:SetPurchaser(hero)
local tombstone = SpawnEntityFromTableSynchronous("dota_item_tombstone_drop", {})
tombstone:SetContainedItem(newItem)
tombstone:SetAngles(0, RandomFloat(0, 360), 0)
FindClearSpaceForUnit(tombstone, hero:GetAbsOrigin(), true)
hero.tombstone_fx = ParticleManager:CreateParticle("particles/units/heroes/hero_abaddon/holdout_borrowed_time_"..hero:GetTeamNumber()..".vpcf", PATTACH_ABSORIGIN_FOLLOW, tombstone)
if hero:IsImbaReincarnating() then
print("Hero is reincarnating!")
hero.reincarnation = true
end
end
if IMBA_MUTATION["negative"] == "all_random_deathmatch" then
if hero:IsImbaReincarnating() then print("hero is reincarnating, don't count down respawn count!") return end
IMBA_MUTATION_ARDM_RESPAWN_SCORE[hero:GetTeamNumber()] = IMBA_MUTATION_ARDM_RESPAWN_SCORE[hero:GetTeamNumber()] - 1
if IMBA_MUTATION_ARDM_RESPAWN_SCORE[hero:GetTeamNumber()] < 0 then
IMBA_MUTATION_ARDM_RESPAWN_SCORE[hero:GetTeamNumber()] = 0
end
if IMBA_MUTATION_ARDM_RESPAWN_SCORE[hero:GetTeamNumber()] == 0 then
print("hero respawn disabled!")
hero:SetRespawnsDisabled(true)
hero:SetTimeUntilRespawn(-1)
local end_game = true
Timers:CreateTimer(1.0, function()
for _, alive_hero in pairs(HeroList:GetAllHeroes()) do
if hero:GetTeamNumber() == alive_hero:GetTeamNumber() then
if alive_hero:IsAlive() then
print("A hero is still alive!")
end_game = false
break
end
end
end
-- if everyone is dead, end the game
if end_game == true then
if hero:GetTeamNumber() == 2 then
GAME_WINNER_TEAM = 3
GameRules:SetGameWinner(3)
elseif hero:GetTeamNumber() == 3 then
GAME_WINNER_TEAM = 2
GameRules:SetGameWinner(2)
end
end
end)
end
CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["negative"], {IMBA_MUTATION_ARDM_RESPAWN_SCORE[2], IMBA_MUTATION_ARDM_RESPAWN_SCORE[3]})
CustomGameEventManager:Send_ServerToAllClients("update_mutations", {})
end
-- if IMBA_MUTATION["negative"] == "death_gold_drop" then
-- local game_time = math.min(GameRules:GetDOTATime(false, false) / 60, 30)
-- local random_int = RandomInt(30, 60)
-- local newItem = CreateItem("item_bag_of_gold", nil, nil)
-- newItem:SetPurchaseTime(0)
-- newItem:SetCurrentCharges(random_int * game_time)
-- local drop = CreateItemOnPositionSync(hero:GetAbsOrigin(), newItem)
-- local dropTarget = hero:GetAbsOrigin() + RandomVector(RandomFloat( 50, 150 ))
-- newItem:LaunchLoot(true, 300, 0.75, dropTarget)
-- EmitSoundOn("Dungeon.TreasureItemDrop", hero)
-- end
end
function Mutation:OnUnitFirstSpawn(unit)
if IMBA_MUTATION["terrain"] == "speed_freaks" then
unit:AddNewModifier(unit, nil, "modifier_mutation_speed_freaks", {projectile_speed = IMBA_MUTATION_SPEED_FREAKS_PROJECTILE_SPEED, movespeed_pct = _G.IMBA_MUTATION_SPEED_FREAKS_MOVESPEED_PCT, max_movespeed = IMBA_MUTATION_SPEED_FREAKS_MAX_MOVESPEED})
end
end
function Mutation:OnUnitSpawn(hero)
-- print("Mutation: On Unit Respawned")
end
function Mutation:OnUnitDeath(unit)
if IMBA_MUTATION["terrain"] == "tug_of_war" then
if unit:GetUnitName() == "npc_dota_mutation_golem" then
IMBA_MUTATION_TUG_OF_WAR_DEATH_COUNT = IMBA_MUTATION_TUG_OF_WAR_DEATH_COUNT + 1
CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["terrain"], {IMBA_MUTATION_TUG_OF_WAR_DEATH_COUNT})
CustomGameEventManager:Send_ServerToAllClients("update_mutations", {})
end
end
end
function Mutation:OnThink()
-- print("Mutation: On Think")
if GameRules:State_Get() == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then
if IMBA_MUTATION["terrain"] == "airdrop" or IMBA_MUTATION["terrain"] == "danger_zone" then
Mutation:MutationTimer()
end
end
end
function Mutation:OnSlowThink() -- 60 seconds
if GameRules:State_Get() == DOTA_GAMERULES_STATE_GAME_IN_PROGRESS then
if IMBA_MUTATION["negative"] == "death_explosion" then
Mutation:DeathExplosionDamage()
end
end
end
-- Mutation: Utilities
function Mutation:RevealAllMap(duration)
GameRules:GetGameModeEntity():SetFogOfWarDisabled(true)
if duration then
Timers:CreateTimer(duration, function()
GameRules:GetGameModeEntity():SetFogOfWarDisabled(false)
end)
end
end
function Mutation:SpawnRandomItem()
local selectedItem
if GameRules:GetDOTATime(false, false) > IMBA_MUTATION_AIRDROP_ITEM_TIER_3_MINUTES * 60 then
selectedItem = tier4[RandomInt(1, #tier4)].k
elseif GameRules:GetDOTATime(false, false) > IMBA_MUTATION_AIRDROP_ITEM_TIER_2_MINUTES * 60 then
selectedItem = tier3[RandomInt(1, #tier3)].k
elseif GameRules:GetDOTATime(false, false) > IMBA_MUTATION_AIRDROP_ITEM_TIER_1_MINUTES * 60 then
selectedItem = tier2[RandomInt(1, #tier2)].k
else
selectedItem = tier1[RandomInt(1, #tier1)].k
end
local pos = RandomVector(IMBA_MUTATION_AIRDROP_MAP_SIZE)
AddFOWViewer(2, pos, IMBA_MUTATION_AIRDROP_ITEM_SPAWN_RADIUS, IMBA_MUTATION_AIRDROP_ITEM_SPAWN_DELAY + IMBA_MUTATION_AIRDROP_ITEM_VISION_LINGER, false)
AddFOWViewer(3, pos, IMBA_MUTATION_AIRDROP_ITEM_SPAWN_RADIUS, IMBA_MUTATION_AIRDROP_ITEM_SPAWN_DELAY + IMBA_MUTATION_AIRDROP_ITEM_VISION_LINGER, false)
GridNav:DestroyTreesAroundPoint(pos, IMBA_MUTATION_AIRDROP_ITEM_SPAWN_RADIUS, false)
local particle_dummy = CreateUnitByName("npc_dummy_unit", pos, true, nil, nil, 6)
local particle_arena_fx = ParticleManager:CreateParticle("particles/hero/centaur/centaur_hoof_stomp_arena.vpcf", PATTACH_ABSORIGIN_FOLLOW, particle_dummy)
ParticleManager:SetParticleControl(particle_arena_fx, 0, pos)
ParticleManager:SetParticleControl(particle_arena_fx, 1, Vector(IMBA_MUTATION_AIRDROP_ITEM_SPAWN_RADIUS + 45, 1, 1))
local particle = ParticleManager:CreateParticle("particles/items_fx/aegis_respawn_timer.vpcf", PATTACH_ABSORIGIN_FOLLOW, particle_dummy)
ParticleManager:SetParticleControl(particle, 1, Vector(IMBA_MUTATION_AIRDROP_ITEM_SPAWN_DELAY, 0, 0))
ParticleManager:SetParticleControl(particle, 3, pos)
ParticleManager:ReleaseParticleIndex(particle)
Timers:CreateTimer(IMBA_MUTATION_AIRDROP_ITEM_SPAWN_DELAY, function()
local item = CreateItem(selectedItem, nil, nil)
item.airdrop = true
-- print("Item Name:", selectedItem, pos)
local drop = CreateItemOnPositionSync(pos, item)
CustomGameEventManager:Send_ServerToAllClients("item_has_spawned", {spawn_location = pos})
EmitGlobalSound( "powerup_05" )
ParticleManager:DestroyParticle(particle_arena_fx, false)
ParticleManager:ReleaseParticleIndex(particle_arena_fx)
particle_dummy:ForceKill(false)
end)
CustomGameEventManager:Send_ServerToAllClients("item_will_spawn", {spawn_location = pos})
EmitGlobalSound("powerup_03")
end
-- Currently only checks stuff for monkey king
function Mutation:IsEligibleHero(hero)
if hero:HasModifier("modifier_monkey_king_fur_army_soldier") or hero:HasModifier("modifier_monkey_king_fur_army_soldier_hidden") then
-- print("fake hero entered the game, ignoring mutation!", hero:GetEntityIndex(), hero:GetName())
return false
end
return true
end
function Mutation:UpdatePanorama()
local var_swap = 1
-- unique update
-- if IMBA_MUTATION["imba"] == "frantic" then
CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["imba"], {_G.IMBA_FRANTIC_VALUE, "%"})
-- end
if IMBA_MUTATION["positive"] == "killstreak_power" then
CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["positive"], {_G.IMBA_MUTATION_KILLSTREAK_POWER, "%"})
elseif IMBA_MUTATION["positive"] == "slark_mode" then
CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["positive"], {_G.IMBA_MUTATION_SLARK_MODE_HEALTH_REGEN, _G.IMBA_MUTATION_SLARK_MODE_MANA_REGEN})
elseif IMBA_MUTATION["positive"] == "ultimate_level" then
CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["positive"], {IMBA_MUTATION_ULTIMATE_LEVEL})
end
if IMBA_MUTATION["negative"] == "death_explosion" then
CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["negative"], {_G.IMBA_MUTATION_DEATH_EXPLOSION_DAMAGE})
elseif IMBA_MUTATION["negative"] == "defense_of_the_ants" then
CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["negative"], {_G.IMBA_MUTATION_DEFENSE_OF_THE_ANTS_SCALE, "%"})
elseif IMBA_MUTATION["negative"] == "monkey_business" then
CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["negative"], {_G.IMBA_MUTATION_MONKEY_BUSINESS_DELAY, "s"})
elseif IMBA_MUTATION["negative"] == "all_random_deathmatch" then
CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["negative"], {IMBA_MUTATION_ARDM_RESPAWN_SCORE[2], IMBA_MUTATION_ARDM_RESPAWN_SCORE[3]})
end
-- shows undefined on panorama for reasons
-- if IMBA_MUTATION["terrain"] == "airdrop" then
-- CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["terrain"], {IMBA_MUTATION_AIRDROP_TIMER})
-- elseif IMBA_MUTATION["terrain"] == "danger_zone" then
-- CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["terrain"], {IMBA_MUTATION_DANGER_ZONE_TIMER})
-- elseif IMBA_MUTATION["terrain"] == "fast_runes" then
if IMBA_MUTATION["terrain"] == "fast_runes" then
CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["terrain"], {RUNE_SPAWN_TIME, BOUNTY_RUNE_SPAWN_TIME})
elseif IMBA_MUTATION["terrain"] == "river_flows" then
CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["terrain"], {_G.IMBA_MUTATION_RIVER_FLOWS_MOVESPEED})
elseif IMBA_MUTATION["terrain"] == "speed_freaks" then
CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["terrain"], {_G.IMBA_MUTATION_SPEED_FREAKS_MOVESPEED_PCT, "%"})
elseif IMBA_MUTATION["terrain"] == "tug_of_war" then
CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["terrain"], {IMBA_MUTATION_TUG_OF_WAR_DEATH_COUNT})
end
CustomGameEventManager:Send_ServerToAllClients("update_mutations", {})
end
function Mutation:DeathExplosionDamage()
local damage = _G.IMBA_MUTATION_DEATH_EXPLOSION_DAMAGE
local game_time = math.min(GameRules:GetDOTATime(false, false) / 60, _G.IMBA_MUTATION_DEATH_EXPLOSION_MAX_MINUTES)
game_time = game_time * _G.IMBA_MUTATION_DEATH_EXPLOSION_DAMAGE_INCREASE_PER_MIN
CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["negative"], {damage + game_time})
CustomGameEventManager:Send_ServerToAllClients("update_mutations", {})
end
function Mutation:MutationTimer()
if IMBA_MUTATION_TIMER == nil then
if IMBA_MUTATION["terrain"] == "danger_zone" then
IMBA_MUTATION_TIMER = IMBA_MUTATION_DANGER_ZONE_TIMER
elseif IMBA_MUTATION["terrain"] == "airdrop" then
IMBA_MUTATION_TIMER = IMBA_MUTATION_AIRDROP_TIMER
end
end
IMBA_MUTATION_TIMER = IMBA_MUTATION_TIMER - 1
if IMBA_MUTATION_TIMER == 10 then
if IMBA_MUTATION["terrain"] == "airdrop" then
CustomGameEventManager:Send_ServerToAllClients("timer_alert", {true})
end
elseif IMBA_MUTATION_TIMER == 0 then
if IMBA_MUTATION["terrain"] == "danger_zone" then
IMBA_MUTATION_TIMER = IMBA_MUTATION_DANGER_ZONE_TIMER - 1
elseif IMBA_MUTATION["terrain"] == "airdrop" then
IMBA_MUTATION_TIMER = IMBA_MUTATION_AIRDROP_TIMER - 1
CustomGameEventManager:Send_ServerToAllClients("timer_alert", {false})
end
end
local t = IMBA_MUTATION_TIMER
local minutes = math.floor(t / 60)
local seconds = t - (minutes * 60)
local m10 = math.floor(minutes / 10)
local m01 = minutes - (m10 * 10)
local s10 = math.floor(seconds / 10)
local s01 = seconds - (s10 * 10)
local broadcast_gametimer =
{
timer_minute_10 = m10,
timer_minute_01 = m01,
timer_second_10 = s10,
timer_second_01 = s01,
}
CustomNetTables:SetTableValue("mutation_info", IMBA_MUTATION["terrain"], broadcast_gametimer)
CustomGameEventManager:Send_ServerToAllClients("update_mutations", {})
end
|
-- luacheck: max line length 152
-- local nvim = require'nvim'
-- local tools = require'tools'
-- local executable = require'tools'.files.executable
local load_module = require'tools'.helpers.load_module
local get_icon = require'tools'.helpers.get_icon
-- local set_mapping = nvim.mappings.set_mapping
local saga = load_module'lspsaga'
if not saga then
return false
end
saga.init_lsp_saga{
error_sign = get_icon('error'),
warn_sign = get_icon('warn'),
hint_sign = get_icon('hint'),
infor_sign = get_icon('info'),
-- dianostic_header_icon = ' ',
-- code_action_icon = ' ',
-- finder_definition_icon = ' ',
-- finder_reference_icon = ' ',
-- definition_preview_icon = ' ',
rename_prompt_prefix = get_icon('virtual_text'),
rename_action_keys = {
quit = '<ESC>',
exec = '<CR>',
},
code_action_keys = {
quit = '<ESC>',
exec = '<CR>',
},
finder_action_keys = {
open = '<CR>',
vsplit = 'V',
split = 'X',
quit = '<ESC>',
scroll_down = '<C-u>',
scroll_up = '<C-d>',
},
}
return true
|
--[[
AarOS Interpreter 1.2
AarOS Version Interpreted: 1.2
Created by Aarex
Read the readme.md for all of the commands.
]]--
-- Main variables
code,xPosition,yPosition,direction,memory,memoryPosition,output=io.read("*a"),1,1,0,{0},1,''
-- Functions
function getCharacterFromLocation(text,position)
return string.sub(text,position,position)
end
function move()
if direction == 0 then -- right
xPosition = xPosition+1
elseif direction == 1 then -- down
yPosition = yPosition+1
elseif direction == 2 then -- left
xPosition = xPosition-1
elseif direction == 3 then -- up
yPosition = yPosition-1
end
end
function nextCommand(xPosition,yPosition,direction)
if direction == 0 then -- right
xPosition = xPosition+1
elseif direction == 1 then -- down
yPosition = yPosition+1
elseif direction == 2 then -- left
xPosition = xPosition-1
elseif direction == 3 then -- up
yPosition = yPosition-1
end
local nextCommand = getCharacterFromLocation(lines[yPosition],xPosition)
if nextCommand == nil then
return ''
else
return nextCommand
end
end
-- Variables from arugments
debug = false
verbose = false
version = 4
-- Arugments
for number,flag in ipairs(arg) do
if number > 1 then
if string.sub(flag,1,2) == '-h' then
print('Help:')
print('-d: Debug mode')
print('-v: Verbose mode')
print('-r: Run in different versions')
os.exit()
end
if string.sub(flag,1,2) == '-d' then
debug = true
end
if string.sub(flag,1,2) == '-v' then
verbose = true
end
if string.sub(flag,1,2) == '-r' then
if string.sub(flag,3,3) ~= ' ' then -- No given version
print('Help:')
print('-r 1.0: Run in version 1.1')
print('-r 1.1: Run in version 1.1')
print('-r 1.1.1: Run in version 1.1.1')
print('-r 1.2: Run in version 1.2')
os.exit()
elseif string.sub(flag,4) == '1.0' then -- Pre-development version
version = 1
elseif string.sub(flag,4) == '1.1' then -- First release version
version = 2
elseif string.sub(flag,4) == '1.1.1' then
version = 3
elseif string.sub(flag,4) == '1.2' then
version = 4
else
print('Wrong version!')
os.exit()
end
end
end
end
-- Splitting lines to store the lines
codeLineFind = code
lineCharacterNum = string.find(codeLineFind,"\n")
lines = {}
while not (lineCharacterNum==nil) do
table.insert(lines,string.sub(codeLineFind,1,lineCharacterNum-1))
codeLineFind = string.sub(codeLineFind,lineCharacterNum+1)
lineCharacterNum = string.find(codeLineFind,"\n")
end
table.insert(lines,codeLineFind)
-- Get sizes
xSize = 0
ySize = 0
while true do
ySize = ySize+1
if lines[ySize] == nil then
ySize = ySize-1
break
end
lineLength = string.len(lines[ySize])
if xSize < lineLength then
xSize = lineLength
end
end
-- Preparation
stringMode = 0
if version > 3 then
popMode = 1
else
popMode = 2
end
input = arg[1]
-- Popping
function pop2Cells(memoryPosition)
local a,b
if popMode == 1 then
a,b=memory[memoryPosition],memory[memoryPosition+1]
else
a,b=memory[memoryPosition+1],memory[memoryPosition]
end
memory[memoryPosition] = 0
memory[memoryPosition+1] = 0
return a,b
end
-- Run
while true do
if not (0 < xPosition and xSize+1 > xPosition and 0 < yPosition and ySize+1 > yPosition) then
break
end
if memory[memoryPosition-1] == nil then
memory[memoryPosition-1] = 0
end
if memory[memoryPosition] == nil then
memory[memoryPosition] = 0
end
if memory[memoryPosition+1] == nil then
memory[memoryPosition+1] = 0
end
local command = getCharacterFromLocation(lines[yPosition],xPosition)
if verbose then print('Command: '..command..', X: '..xPosition..', Y: '..yPosition..', Direction: '..direction) end
if not (command==nil) then
if stringMode == 0 then -- Main commands
if command=='+' then -- Increase cell
memory[memoryPosition] = memory[memoryPosition]+1
elseif command=='-' then -- Decrease cell
memory[memoryPosition] = memory[memoryPosition]-1
elseif command=='>' then -- Turn the pointer to right
direction = 0
elseif command=='<' then -- Turn the pointer to left
direction = 2
elseif command=='^' then -- Turn the pointer to up
direction = 3
elseif command=='v' then -- Turn the pointer to down
direction = 1
elseif command=='L' then -- Move to previous cell.
if memoryPosition > 1 then
memoryPosition = memoryPosition - 1
end
elseif command=='R' then -- Move to next cell.
memoryPosition = memoryPosition + 1
elseif command=='A' then -- Addition
local cell1,cell2 = pop2Cells(memoryPosition)
memory[memoryPosition] = cell1+cell2
memory[memoryPosition+1] = 0
elseif command=='M' then
local nCommand = nextCommand(xPosition,yPosition,direction)
if version > 3 and nCommand == '/' then -- Mirrors
move()
if direction == 0 then
direction = 3
elseif direction == 1 then
direction = 2
elseif direction == 2 then
direction = 1
elseif direction == 3 then
direction = 0
end
elseif version > 3 and nCommand == '\\' then -- Mirrors
move()
if direction == 0 then
direction = 1
elseif direction == 1 then
direction = 0
elseif direction == 2 then
direction = 3
elseif direction == 3 then
direction = 2
end
elseif version < 3 then -- Subtraction
local cell1,cell2 = pop2Cells(memoryPosition)
memory[memoryPosition] = cell1-cell2
else
memory[memoryPosition] = memory[memoryPosition]-memory[memoryPosition+1]
end
memory[memoryPosition+1] = 0
elseif command=='P' then -- Multiplication
local cell1,cell2 = pop2Cells(memoryPosition)
memory[memoryPosition] = cell1*cell2
memory[memoryPosition+1] = 0
elseif command=='D' then -- Division
if not (memory[memoryPosition+1]==0) then
local cell1,cell2 = pop2Cells(memoryPosition)
memory[memoryPosition] = cell1/cell2
memory[memoryPosition+1] = 0
end
elseif command=='S' then -- Skip
move()
elseif command=='I' then -- If the current cell is not 0, then skip a next command.
if not (memory[memoryPosition] == 0) then
move()
end
elseif command=='.' then -- Push the input to current cell.
if not (input == nil) then
memory[memoryPosition] = string.byte(string.sub(input,1,1))
input = string.sub(input,2)
else
memory[memoryPosition] = 0
end
elseif command==',' then -- Pop a current cell, then output it as a character.
output = output..string.char(memory[memoryPosition])
if version > 2 then
memory[memoryPosition] = 0
end
elseif command=='@' then -- End program
break
elseif version > 1 and (version < 3 and command=='\'') or (version > 2 and command=='\"') then -- Start the simple string literal.
stringMode = 1
elseif version > 1 and command=='\\' then
local nCommand = nextCommand(xPosition,yPosition,direction)
if nCommand=='*' then -- Start the complex string literal.
move()
stringMode = 2
else
if popMode == 1 then
popMode = 2
else
popMode = 1
end
end
elseif version > 1 and command=='&' then -- Remove the current cell.
table.remove(memory,memoryPosition)
elseif version > 1 and command=='%' then -- Pop a current cell, then output it as a number.
output = output..memory[memoryPosition]
if version > 2 then
memory[memoryPosition] = 0
end
elseif version > 1 and command=='/' then -- Pop the next cell and 'mod' the current cell by it.
if not (memory[memoryPosition+1]==0) then
memory[memoryPosition] = memory[memoryPosition] % memory[memoryPosition+1]
memory[memoryPosition+1] = 0
end
elseif version > 3 and command=='\'' then -- Start a number literal
stringMode = 3
elseif version > 3 and command=='E' then -- Exponentiation
local cell1,cell2 = pop2Cells(memoryPosition)
memory[memoryPosition] = cell1^cell2
memory[memoryPosition+1] = 0
elseif version > 3 and command=='$' then -- Pop
memory[memoryPosition] = 0
elseif version > 3 and command=='#' then -- Swap cells
local swapMemory = memory[memoryPosition]
memory[memoryPosition] = memory[memoryPosition+1]
memory[memoryPosition+1] = swapMemory
elseif version > 3 and command=='`' then -- Copy cell
memory[memoryPosition+1] = memory[memoryPosition]
end
elseif stringMode == 1 then -- Simple string literal
if (version < 3 and command=='\'') or (version > 2 and command=='\"') then -- End string literal
stringMode = 0
else -- Push character
memory[memoryPosition] = string.byte(command)
memoryPosition = memoryPosition+1
end
elseif stringMode == 2 then -- Complex string literal
if command=='*' then
local nCommand = nextCommand(xPosition,yPosition,direction)
if nCommand=='\\' then -- End string literal.
move()
stringMode = 0
else -- Push character
memory[memoryPosition] = string.byte(command)
end
else -- Push character
memory[memoryPosition] = string.byte(command)
memoryPosition = memoryPosition+1
end
elseif stringMode == 3 then -- Number literal
if command == '\'' then -- End string literal
stringMode = 0
elseif string.byte(command) > 47 and string.byte(command) < 58 then -- Push number
memory[memoryPosition] = command
memoryPosition = memoryPosition+1
end
end
end
move()
if verbose then print('String Mode: '..stringMode..', Pop Mode: '..popMode..', Memory: '..memory[memoryPosition]..', Position: '..memoryPosition) end
end
if debug then
if verbose then print() end
local verNames = {"1.0","1.1","1.1.1","1.2"}
print('String Mode: '..stringMode)
print('Pop Mode: '..popMode)
print('Version: '..verNames[version])
print('X Size: '..xSize..', Y Size: '..ySize)
print('Final position: ('..xPosition..','..yPosition..')')
local dirNames = {"Right","Down","Left","Up"}
print('Final direction: '..dirNames[direction+1])
print('Memory: ')
mem = ''
for _,num in ipairs(memory) do
mem = mem..num..','
end
mem = string.sub(mem,1,string.len(mem)-1)
print(mem)
print('Output: ')
elseif verbose then
print()
end
io.write(output) |
local classes = classes;
local super = classes.Object;
local class = inherit({
name = "Stream",
super = super,
func = inherit({}, super.func),
get = inherit({}, super.get),
set = inherit({}, super.set),
concrete = true,
}, super);
classes[class.name] = class;
class.CHAR_MASK = 2^7;
class.SHORT_MASK = 2^15;
class.INT_MASK = 2^31;
function class.new(bytes)
local bytes_t = type(bytes);
if (bytes_t ~= "string") then
error("bad argument #1 to '" ..__func__.. "' (string expected, got " ..bytes_t.. ")", 2);
end
local success, obj = pcall(super.new, class);
if (not success) then error(obj, 2) end
if (fileExists(bytes)) then
-- outputDebugString("creating stream from file found at " ..bytes);
local f = fileOpen(bytes);
obj.bytes = fileRead(f, fileGetSize(f));
fileClose(f);
else
-- outputDebugString("file not found at " ..bytes.. "; creating stream from string instead");
obj.bytes = bytes;
end
obj.size = #obj.bytes;
obj.pos = 0;
return obj;
end
class.meta = extend({
__metatable = super.name.. ":" ..class.name,
__tostring = function(obj)
return tostring(obj.isOpen).. ", " ..obj.pos.. "/" ..obj.size;
end,
}, super.meta);
function class.func.read(obj, count)
if (count ~= nil) then
local count_t = type(count);
if (count_t ~= "number") then
error("bad argument #1 to '" ..__func__.. "' (number expected, got " ..count_t.. ")", 2);
elseif (count < 0) then
error("bad argument #1 to '" ..__func__.. "' (value out of bounds)", 2);
end
count = math.floor(count);
else
count = 1;
end
local newPos = obj.pos+count;
if (newPos > obj.size) then
newPos = obj.size;
end
local ret = obj.bytes:sub(obj.pos+1, newPos);
obj.pos = newPos;
return ret;
end
function class.func.read_uchar(obj)
return obj:read():byte();
end
function class.func.read_ushort(obj, bigEndian)
if (bigEndian ~= nil) then
local bigEndian_t = type(bigEndian);
if (bigEndian_t ~= "boolean") then
error("bad argument #1 to '" ..__func__.. "' (boolean expected, got " ..bigEndian_t.. ")", 2);
end
else
bigEndian = false;
end
local uchar1 = obj:read_uchar();
local uchar2 = obj:read_uchar();
return (bigEndian) and 0x100 * uchar1
+ uchar2
or uchar1
+ 0x100 * uchar2;
end
function class.func.read_uint(obj, bigEndian)
if (bigEndian ~= nil) then
local bigEndian_t = type(bigEndian);
if (bigEndian_t ~= "boolean") then
error("bad argument #1 to '" ..__func__.. "' (boolean expected, got " ..bigEndian_t.. ")", 2);
end
else
bigEndian = false;
end
local ushort1 = obj:read_ushort(bigEndian);
local ushort2 = obj:read_ushort(bigEndian);
return (bigEndian) and 0x10000 * ushort1
+ ushort2
or ushort1
+ 0x10000 * ushort2;
end
-- convert unsigned to signed
-- using masks to determine if MSB is 1 or 0
function class.func.read_char(obj)
local uchar = obj:read_uchar();
return uchar-2*bitAnd(uchar, class.CHAR_MASK);
end
function class.func.read_short(obj, bigEndian)
local ushort = obj:read_ushort(bigEndian);
return ushort-2*bitAnd(ushort, class.SHORT_MASK);
end
function class.func.read_int(obj, bigEndian)
local uint = obj:read_uint(bigEndian);
return uint-2*bitAnd(uint, class.INT_MASK);
end
function class.get.BOF(obj)
return (obj.pos == 0);
end
function class.get.EOF(obj)
return (obj.pos >= obj.size);
end
function class.set.pos(obj, pos)
local pos_t = type(pos);
if (pos_t ~= "number") then
error("bad argument #1 to 'pos' (number expected, got " ..pos_t.. ")", 2);
end
pos = math.floor(pos);
if (pos < 0) or (pos > obj.size) then
error("bad argument #1 to 'pos' (value out of bounds)", 2);
end
obj.pos = pos;
end
|
function f(a, b)
return a or b
end
print(f(3))
print(f(3, 4))
print(f(3, 4, 5))
|
if (SERVER) then return end
function PIS:GetServerID()
return game.GetIPAddress() or "192.168.0.0:27015"
end
function PIS:CreateSQLTables()
sql.Query([[
CREATE TABLE IF NOT EXISTS nexus_psi_settings (
id TEXT(50),
settings TEXT(4000),
PRIMARY KEY (id)
)
]])
end
function PIS:LoadSettings(ply)
local id = sql.SQLStr(PIS:GetServerID())
local result = sql.Query([[
SELECT * FROM nexus_psi_settings
WHERE id = ]] .. id
)
if (istable(result) and #result > 0) then
PIS:SetSettings(ply, util.JSONToTable(result[1].settings))
end
end
function PIS:SaveSettings(ply)
local settings = sql.SQLStr(util.TableToJSON(self:GetSettings(ply)))
local id = sql.SQLStr(PIS:GetServerID())
local result = sql.Query([[
SELECT * FROM nexus_psi_settings
WHERE id = ]] .. id
)
if (istable(result) and #result > 0) then
sql.Query([[
UPDATE nexus_psi_settings
SET settings = ]] .. settings .. [[
WHERE id = ]] .. id
)
else
sql.Query([[
INSERT INTO nexus_psi_settings (id, settings)
VALUES (]] .. id .. [[, ]] .. settings .. [[)
]])
end
end
hook.Add("Initialize", "PIS.SQLCreation", function()
PIS:CreateSQLTables()
end)
hook.Add("HUDPaint", "PIS.LoadSettings", function()
hook.Remove("HUDPaint", "PIS.LoadSettings")
timer.Simple(3, function()
PIS:LoadSettings(LocalPlayer())
end)
end) |
Script.Load("lua/Globals.lua")
Script.Load("lua/GUIUtility.lua")
Script.Load("lua/GUIAnimatedScript.lua")
class 'MarineStatusHUD' (GUIAnimatedScript)
MarineStatusHUD.kTexture = PrecacheAsset("ui/marine_HUD_presbg.dds")
MarineStatusHUD.kXpBarTexture = PrecacheAsset("ui/combatui_xp_bar.dds")
MarineStatusHUD.kXPFontName = Fonts.kArial_13
MarineStatusHUD.kXPTextPosition = Vector(0, -61, 0)
MarineStatusHUD.kRankFontName = Fonts.kAgencyFB_Small
MarineStatusHUD.kRankTextPosition = Vector(0, -82, 0)
MarineStatusHUD.kXPBarSize = Vector(589, 10, 0)
MarineStatusHUD.kXPBarSizeScaled = Vector(589, 10, 0)
MarineStatusHUD.kXPBarPos = Vector(5, 13, 0)
MarineStatusHUD.kXPBarColor = Color(0.26, 0.8, 0.87, 0.75)
MarineStatusHUD.kXPBarGlowSize = Vector(8, 22, 0)
MarineStatusHUD.kXPBarGlowPos = Vector(-MarineStatusHUD.kXPBarGlowSize.x, 0, 0)
MarineStatusHUD.kAbilityIconBkgTexture = PrecacheAsset("ui/combatui_ability_buttonbg.dds")
MarineStatusHUD.kAbilityIconSize = Vector(68, 68, 0)
MarineStatusHUD.kAbilityIconTexture = PrecacheAsset("ui/combatui_marine_ability_icons.dds")
MarineStatusHUD.kAbilityBkgColorEnabled = Color(0.23, 0.33, 0.74, 1)
MarineStatusHUD.kAbilityCooldownColor = Color(0.24, 0.64, 1, 0.6)
MarineStatusHUD.kAnimSpeedDown = 0.2
MarineStatusHUD.kAnimSpeedUp = 0.5
local gAbilityIconIndex
local function GetAbilityIconPixelCoordinates(itemTechId)
if not gAbilityIconIndex then
gAbilityIconIndex = {}
gAbilityIconIndex[kTechId.MedPack] = 0
gAbilityIconIndex[kTechId.AmmoPack] = 1
gAbilityIconIndex[kTechId.CatPack] = 2
gAbilityIconIndex[kTechId.Scan] = 3
end
local x1 = 0
local x2 = 64
local index = gAbilityIconIndex[itemTechId]
if not index then
index = 0
end
local y1 = index * 64
local y2 = (index + 1) * 64
return x1, y1, x2, y2
end
local function UpdateItemsGUIScale(self)
end
function MarineStatusHUD:Initialize()
GUIAnimatedScript.Initialize(self)
self.scale = 1
self.lastXP = 0
self.lastRank = 1
self.background = self:CreateAnimatedGraphicItem()
self.background:SetPosition( Vector(0, 0, 0) )
self.background:SetIsScaling(false)
self.background:SetSize(Vector(Client.GetScreenWidth(), Client.GetScreenHeight(),0))
self.background:SetIsVisible(true)
self.background:SetLayer(kGUILayerPlayerHUDForeground1)
self.background:SetColor( Color(1, 1, 1, 0) )
self.newXpBarBkg = self:CreateAnimatedGraphicItem()
self.newXpBarBkg:SetAnchor(GUIItem.Middle, GUIItem.Bottom)
self.newXpBarBkg:SetTexture(MarineStatusHUD.kXpBarTexture)
self.newXpBarBkg:SetIsVisible(true)
self.background:AddChild(self.newXpBarBkg)
self.newXpBar = self:CreateAnimatedGraphicItem()
self.newXpBar:SetAnchor(GUIItem.Left, GUIItem.Top)
self.newXpBar:SetIsVisible(true)
self.newXpBar:SetColor( MarineStatusHUD.kXPBarColor )
self.newXpBarBkg:AddChild(self.newXpBar)
self.currentXPText = GetGUIManager():CreateTextItem()
self.currentXPText:SetFontName(MarineStatusHUD.kXPFontName)
self.currentXPText:SetAnchor(GUIItem.Middle, GUIItem.Bottom)
self.currentXPText:SetTextAlignmentX(GUIItem.Align_Center)
self.currentXPText:SetTextAlignmentY(GUIItem.Align_Center)
self.currentXPText:SetText("0 XP of 1000 (Rank 1)")
self.currentXPText:SetIsVisible(true)
self.currentXPText:SetColor( Color(1, 1, 1, 1) )
self.background:AddChild(self.currentXPText)
self.currentRankText = GetGUIManager():CreateTextItem()
self.currentRankText:SetFontName(MarineStatusHUD.kRankFontName)
self.currentRankText:SetAnchor(GUIItem.Middle, GUIItem.Bottom)
self.currentRankText:SetTextAlignmentX(GUIItem.Align_Center)
self.currentRankText:SetTextAlignmentY(GUIItem.Align_Center)
self.currentRankText:SetText("Rank 1 : Private")
self.currentRankText:SetIsVisible(true)
self.currentRankText:SetColor( Color(0.62, 0.92, 1, 0.8) )
self.background:AddChild(self.currentRankText)
self.medPackIconBackground = self:CreateAnimatedGraphicItem()
self.medPackIconBackground:SetAnchor(GUIItem.Right, GUIItem.Bottom)
self.medPackIconBackground:SetTexture(MarineStatusHUD.kAbilityIconBkgTexture)
self.medPackIconBackground:SetTexturePixelCoordinates(0, 0, MarineStatusHUD.kAbilityIconSize.x, MarineStatusHUD.kAbilityIconSize.y)
self.background:AddChild(self.medPackIconBackground)
self.medPackIcon = self:CreateAnimatedGraphicItem()
self.medPackIcon:SetAnchor(GUIItem.Left, GUIItem.Top)
self.medPackIcon:SetTexture(MarineStatusHUD.kAbilityIconTexture)
self.medPackIcon:SetTexturePixelCoordinates(GetAbilityIconPixelCoordinates(kTechId.MedPack))
self.medPackIcon:SetColor( Color(0.44, 0.58, 0.74, 1) )
self.medPackIconBackground:AddChild(self.medPackIcon)
self.medPackCooldownOverlay = self:CreateAnimatedGraphicItem()
self.medPackCooldownOverlay:SetAnchor(GUIItem.Left, GUIItem.Top)
self.medPackCooldownOverlay:SetColor( MarineStatusHUD.kAbilityCooldownColor )
self.medPackIconBackground:AddChild(self.medPackCooldownOverlay)
self.ammoPackIconBackground = self:CreateAnimatedGraphicItem()
self.ammoPackIconBackground:SetAnchor(GUIItem.Right, GUIItem.Bottom)
self.ammoPackIconBackground:SetTexture(MarineStatusHUD.kAbilityIconBkgTexture)
self.ammoPackIconBackground:SetTexturePixelCoordinates(0, 0, MarineStatusHUD.kAbilityIconSize.x, MarineStatusHUD.kAbilityIconSize.y)
self.background:AddChild(self.ammoPackIconBackground)
self.ammoPackIcon = self:CreateAnimatedGraphicItem()
self.ammoPackIcon:SetAnchor(GUIItem.Left, GUIItem.Top)
self.ammoPackIcon:SetTexture(MarineStatusHUD.kAbilityIconTexture)
self.ammoPackIcon:SetTexturePixelCoordinates(GetAbilityIconPixelCoordinates(kTechId.AmmoPack))
self.ammoPackIcon:SetColor( Color(0.44, 0.58, 0.74, 1) )
self.ammoPackIconBackground:AddChild(self.ammoPackIcon)
self.ammoPackCooldownOverlay = self:CreateAnimatedGraphicItem()
self.ammoPackCooldownOverlay:SetAnchor(GUIItem.Left, GUIItem.Top)
self.ammoPackCooldownOverlay:SetColor( MarineStatusHUD.kAbilityCooldownColor )
self.ammoPackIconBackground:AddChild(self.ammoPackCooldownOverlay)
self.catPackIconBackground = self:CreateAnimatedGraphicItem()
self.catPackIconBackground:SetAnchor(GUIItem.Right, GUIItem.Bottom)
self.catPackIconBackground:SetTexture(MarineStatusHUD.kAbilityIconBkgTexture)
self.catPackIconBackground:SetTexturePixelCoordinates(0, 0, MarineStatusHUD.kAbilityIconSize.x, MarineStatusHUD.kAbilityIconSize.y)
self.background:AddChild(self.catPackIconBackground)
self.catPackIcon = self:CreateAnimatedGraphicItem()
self.catPackIcon:SetAnchor(GUIItem.Left, GUIItem.Top)
self.catPackIcon:SetTexture(MarineStatusHUD.kAbilityIconTexture)
self.catPackIcon:SetTexturePixelCoordinates(GetAbilityIconPixelCoordinates(kTechId.CatPack))
self.catPackIcon:SetColor( Color(0.44, 0.58, 0.74, 1) )
self.catPackIconBackground:AddChild(self.catPackIcon)
self.catPackCooldownOverlay = self:CreateAnimatedGraphicItem()
self.catPackCooldownOverlay:SetAnchor(GUIItem.Left, GUIItem.Top)
self.catPackCooldownOverlay:SetColor( MarineStatusHUD.kAbilityCooldownColor )
self.catPackIconBackground:AddChild(self.catPackCooldownOverlay)
self.scanIconBackground = self:CreateAnimatedGraphicItem()
self.scanIconBackground:SetAnchor(GUIItem.Right, GUIItem.Bottom)
self.scanIconBackground:SetTexture(MarineStatusHUD.kAbilityIconBkgTexture)
self.scanIconBackground:SetTexturePixelCoordinates(0, 0, MarineStatusHUD.kAbilityIconSize.x, MarineStatusHUD.kAbilityIconSize.y)
self.background:AddChild(self.scanIconBackground)
self.scanIcon = self:CreateAnimatedGraphicItem()
self.scanIcon:SetAnchor(GUIItem.Left, GUIItem.Top)
self.scanIcon:SetTexture(MarineStatusHUD.kAbilityIconTexture)
self.scanIcon:SetTexturePixelCoordinates(GetAbilityIconPixelCoordinates(kTechId.Scan))
self.scanIcon:SetColor( Color(0.44, 0.58, 0.74, 1) )
self.scanIconBackground:AddChild(self.scanIcon)
self.scanCooldownOverlay = self:CreateAnimatedGraphicItem()
self.scanCooldownOverlay:SetAnchor(GUIItem.Left, GUIItem.Top)
self.scanCooldownOverlay:SetColor( MarineStatusHUD.kAbilityCooldownColor )
self.scanIconBackground:AddChild(self.scanCooldownOverlay)
self.visible = true
self:UpdateVisibility()
self:Reset(1)
end
function MarineStatusHUD:Reset(scale)
self.scale = scale
GUIAnimatedScript.Reset(self)
self.background:SetSize(Vector(Client.GetScreenWidth(), Client.GetScreenHeight(),0))
local xpBarWidthBkg = GUIScaleWidth(600)
self.newXpBarBkg:SetUniformScale(self.scale)
self.newXpBarBkg:SetSize( Vector(xpBarWidthBkg, 32, 0) )
self.newXpBarBkg:SetPosition( Vector(-1 * xpBarWidthBkg / 2, -80, 0) )
MarineStatusHUD.kXPBarSizeScaled = Vector(GUIScaleWidth(MarineStatusHUD.kXPBarSizeScaled.x), MarineStatusHUD.kXPBarSizeScaled.y, 0)
self.newXpBar:SetUniformScale(self.scale)
self.newXpBar:SetSize( Vector(0, MarineStatusHUD.kXPBarSizeScaled.y, 0) )
self.newXpBar:SetPosition(MarineStatusHUD.kXPBarPos)
self.currentXPText:SetScale(GetScaledVector())
self.currentXPText:SetPosition(MarineStatusHUD.kXPTextPosition)
self.currentXPText:SetFontName(MarineStatusHUD.kXPFontName)
GUIMakeFontScale(self.currentXPText)
self.currentRankText:SetScale(GetScaledVector())
self.currentRankText:SetPosition(MarineStatusHUD.kRankTextPosition)
self.currentRankText:SetFontName(MarineStatusHUD.kRankFontName)
GUIMakeFontScale(self.currentRankText)
self.medPackIconBackground:SetUniformScale(self.scale)
self.medPackIconBackground:SetPosition( Vector(-142, -180, 0) )
self.medPackIconBackground:SetSize(MarineStatusHUD.kAbilityIconSize)
self.medPackIcon:SetUniformScale(self.scale)
self.medPackIcon:SetPosition( Vector(2, 2, 0) )
self.medPackIcon:SetSize( Vector(64, 64, 0) )
self.medPackCooldownOverlay:SetUniformScale(self.scale)
self.medPackCooldownOverlay:SetPosition( Vector(3, 3, 0) )
self.medPackCooldownOverlay:SetSize( Vector(60, 60, 0) )
self.ammoPackIconBackground:SetUniformScale(self.scale)
self.ammoPackIconBackground:SetPosition( Vector(-142, -110, 0) )
self.ammoPackIconBackground:SetSize(MarineStatusHUD.kAbilityIconSize)
self.ammoPackIcon:SetUniformScale(self.scale)
self.ammoPackIcon:SetPosition( Vector(2, 2, 0) )
self.ammoPackIcon:SetSize( Vector(64, 64, 0) )
self.ammoPackCooldownOverlay:SetUniformScale(self.scale)
self.ammoPackCooldownOverlay:SetPosition( Vector(3, 3, 0) )
self.ammoPackCooldownOverlay:SetSize( Vector(60, 60, 0) )
self.catPackIconBackground:SetUniformScale(self.scale)
self.catPackIconBackground:SetPosition( Vector(-72, -180, 0) )
self.catPackIconBackground:SetSize(MarineStatusHUD.kAbilityIconSize)
self.catPackIcon:SetUniformScale(self.scale)
self.catPackIcon:SetPosition( Vector(2, 2, 0) )
self.catPackIcon:SetSize( Vector(64, 64, 0) )
self.catPackCooldownOverlay:SetUniformScale(self.scale)
self.catPackCooldownOverlay:SetPosition( Vector(3, 3, 0) )
self.catPackCooldownOverlay:SetSize( Vector(60, 60, 0) )
self.scanIconBackground:SetUniformScale(self.scale)
self.scanIconBackground:SetPosition( Vector(-72, -110, 0) )
self.scanIconBackground:SetSize(MarineStatusHUD.kAbilityIconSize)
self.scanIcon:SetUniformScale(self.scale)
self.scanIcon:SetPosition( Vector(2, 2, 0) )
self.scanIcon:SetSize( Vector(64, 64, 0) )
self.scanCooldownOverlay:SetUniformScale(self.scale)
self.scanCooldownOverlay:SetPosition( Vector(3, 3, 0) )
self.scanCooldownOverlay:SetSize( Vector(60, 60, 0) )
--self.xpBar:SetSize(Vector(0, MarineStatusHUD.kXPBarSize.y, 0))
--self.xpBar:SetTexturePixelCoordinates(MarineStatusHUD.kXPBarPixelCoords[1], MarineStatusHUD.kXPBarPixelCoords[2], MarineStatusHUD.kXPBarPixelCoords[1], MarineStatusHUD.kXPBarPixelCoords[4])
end
function MarineStatusHUD:Uninitialize()
GUIAnimatedScript.Uninitialize(self)
GUI.DestroyItem(self.currentXPText)
self.currentXPText = nil
GUI.DestroyItem(self.currentRankText)
self.currentRankText = nil
end
function MarineStatusHUD:UpdateCooldowns(player)
if HasMixin(player, "MedPackAbility") then
local visible = player:GetIsMedPackAbilityEnabled()
local bkgColor = ConditionalValue(visible, MarineStatusHUD.kAbilityBkgColorEnabled, Color(1,1,1,1))
self.medPackIconBackground:SetColor(bkgColor)
self.medPackIcon:SetIsVisible(visible)
local medPackCooldownFraction = player:GetMedPackCooldownFraction()
self.medPackCooldownOverlay:SetSize( Vector(60, 60 * medPackCooldownFraction, 0) )
self.medPackCooldownOverlay:SetPosition( Vector(3, 60 - (60 * medPackCooldownFraction) + 3, 0) )
self.medPackCooldownOverlay:SetIsVisible(visible)
end
if HasMixin(player, "AmmoPackAbility") then
local visible = player:GetIsAmmoPackAbilityEnabled()
local bkgColor = ConditionalValue(visible, MarineStatusHUD.kAbilityBkgColorEnabled, Color(1,1,1,1))
self.ammoPackIconBackground:SetColor(bkgColor)
self.ammoPackIcon:SetIsVisible(visible)
local ammoPackCooldownFraction = player:GetAmmoPackCooldownFraction()
self.ammoPackCooldownOverlay:SetSize( Vector(60, 60 * ammoPackCooldownFraction, 0) )
self.ammoPackCooldownOverlay:SetPosition( Vector(3, 60 - (60 * ammoPackCooldownFraction) + 3, 0) )
self.ammoPackCooldownOverlay:SetIsVisible(visible)
end
if HasMixin(player, "CatPackAbility") then
local visible = player:GetIsCatPackAbilityEnabled()
local bkgColor = ConditionalValue(visible, MarineStatusHUD.kAbilityBkgColorEnabled, Color(1,1,1,1))
self.catPackIconBackground:SetColor(bkgColor)
self.catPackIcon:SetIsVisible(visible)
local catPackCooldownFraction = player:GetCatPackCooldownFraction()
self.catPackCooldownOverlay:SetSize( Vector(60, 60 * catPackCooldownFraction, 0) )
self.catPackCooldownOverlay:SetPosition( Vector(3, 60 - (60 * catPackCooldownFraction) + 3, 0) )
self.catPackCooldownOverlay:SetIsVisible(visible)
end
if HasMixin(player, "ScanAbility") then
local visible = player:GetIsScanAbilityEnabled()
local bkgColor = ConditionalValue(visible, MarineStatusHUD.kAbilityBkgColorEnabled, Color(1,1,1,1))
self.scanIconBackground:SetColor(bkgColor)
self.scanIcon:SetIsVisible(visible)
local scanCooldownFraction = player:GetScanCooldownFraction()
self.scanCooldownOverlay:SetSize( Vector(60, 60 * scanCooldownFraction, 0) )
self.scanCooldownOverlay:SetPosition( Vector(3, 60 - (60 * scanCooldownFraction) + 3, 0) )
self.scanCooldownOverlay:SetIsVisible(visible)
end
end
function MarineStatusHUD:UpdateVisibility()
self.currentXPText:SetIsVisible(self.visible)
self.currentRankText:SetIsVisible(self.visible)
self.newXpBarBkg:SetIsVisible(self.visible)
self.medPackIconBackground:SetIsVisible(self.visible)
self.ammoPackIconBackground:SetIsVisible(self.visible)
self.catPackIconBackground:SetIsVisible(self.visible)
self.scanIconBackground:SetIsVisible(self.visible)
end
function MarineStatusHUD:SetIsVisible(isVisible)
self.visible = isVisible
self:UpdateVisibility()
end
function MarineStatusHUD:GetIsVisible()
return self.visible
end
function MarineStatusHUD:OnResolutionChanged(oldX, oldY, newX, newY)
self:Reset(newY / kBaseScreenHeight)
self:Uninitialize()
self:Initialize()
end
function MarineStatusHUD:Update(deltaTime)
GUIAnimatedScript.Update(self, deltaTime)
local player = Client.GetLocalPlayer()
self:UpdateCooldowns(player)
if player and HasMixin(player, "CombatScore") then
local currentXP = player.combatXP
local currentRank = player.combatRank
local title = CombatPlusPlus_GetMarineTitleByRank(currentRank)
local oldXPThreshold = CombatPlusPlus_GetXPThresholdByRank(currentRank)
local newXPThreshold = 0
if currentRank < kMaxCombatRank then
newXPThreshold = CombatPlusPlus_GetXPThresholdByRank(currentRank + 1)
end
-- update rank text
self.currentRankText:SetText(string.format("Rank %s : %s", currentRank, title))
-- update xp text
if newXPThreshold == 0 then
self.currentXPText:SetText(string.format("%s XP", currentXP))
else
self.currentXPText:SetText(string.format("%s XP : %s XP to Next Rank", currentXP, newXPThreshold - currentXP))
end
-- normalize the current xp scale
local currentXPNorm = currentXP - oldXPThreshold
local newXPThresholdNorm = newXPThreshold - oldXPThreshold
if currentRank ~= self.lastRank then
if currentRank > self.lastRank then
self.newXpBar:DestroyAnimations()
self.newXpBar:SetSize(Vector(0, 10, 0))
end
self.lastRank = currentRank
end
if currentXP ~= self.lastXP then
local animSpeed = ConditionalValue(currentXP < self.lastXP, MarineStatusHUD.kAnimSpeedDown, MarineStatusHUD.kAnimSpeedUp)
local xpFraction = currentXPNorm / newXPThresholdNorm
local xpBarSize = Vector(MarineStatusHUD.kXPBarSizeScaled.x * xpFraction, MarineStatusHUD.kXPBarSizeScaled.y, 0)
self.newXpBar:DestroyAnimations()
self.newXpBar:SetSize(xpBarSize, animSpeed)
self.newXpBar:SetColor( Color(1, 1, 1, 1) )
self.newXpBar:SetColor( MarineStatusHUD.kXPBarColor, 1 )
self.lastXP = currentXP
end
end
end
|
--爱情加工厂
menuBtn.onClick=function()
退出页面()
end
require "import"
import "android.app.*"
import "android.os.*"
import "android.widget.*"
import "com.lua.views.MarTextView"
ghost={
LinearLayout,
layout_height="match_parent",
layout_width="match_parent",
orientation="vertical",
background="#FFFFFFFF";
{
ScrollView,
layout_width="match_parent";
layout_height="match_parent";
VerticalScrollBarEnabled=false;
{
LinearLayout,
layout_height="match_parent",
layout_width="match_parent",
orientation="vertical",
{
LinearLayout,
layout_height="200dp",
layout_width="match_parent",
orientation="vertical",
layout_margin="10dp",
{
CardView;
layout_margin="0.5dp",
elevation="1.5dp";
id="k1";
layout_width="match_parent";
CardBackgroundColor="#EEFFFFFF";
layout_height="match_parent";
radius="15dp";
{
PageView,
id="pg1";
layout_width="fill",
layout_height="fill",
pages={
{
LinearLayout;
id="f1";
layout_height="match_parent",
layout_width="match_parent",
orientation="vertical";
{
CardView;
elevation="1.5dp";
id="k1";
layout_width="match_parent";
CardBackgroundColor="#00FFFFFF";
layout_height="match_parent";
radius="15dp";
{
ImageView;
layout_width="match_parent",
layout_height="match_parent",
background="drawable/1.jpg";
},
{
TextView,
layout_height="30dp",
layout_width="match_parent",
layout_gravity="bottom",
gravity="center",
background="#44000000";
text="",
textSize="15sp",
},
},
},
{
LinearLayout;
id="f2";
layout_height="match_parent",
layout_width="match_parent",
orientation="vertical";
{
CardView;
elevation="1.5dp";
id="k1";
layout_width="match_parent";
CardBackgroundColor="#00FFFFFF";
layout_height="match_parent";
radius="15dp";
{
ImageView;
layout_width="match_parent",
layout_height="match_parent",
background="drawable/2.jpg";
},
{
TextView,
layout_height="30dp",
layout_width="match_parent",
layout_gravity="bottom",
gravity="center",
background="#44000000";
text="",
textSize="15sp",
},
},
},
{
LinearLayout;
id="f3";
layout_height="match_parent",
layout_width="match_parent",
orientation="vertical";
{
CardView;
elevation="1.5dp";
id="k1";
layout_width="match_parent";
CardBackgroundColor="#00FFFFFF";
layout_height="match_parent";
radius="15dp";
{
ImageView;
layout_width="match_parent",
layout_height="match_parent",
background="drawable/3.jpg";
},
{
TextView,
layout_height="30dp",
layout_width="match_parent",
layout_gravity="bottom",
gravity="center",
background="#44000000";
text="",
textSize="15sp",
},
},
},
},
},
},
},
{
LinearLayout,
layout_height="wrap_content",
layout_width="match_parent",
orientation="vertical",
layout_margin="10dp",
{
CardView;
layout_margin="0.5dp",
elevation="1.5dp";
id="k1";
layout_width="match_parent";
CardBackgroundColor="#00FFFFFF";
layout_height="match_parent";
radius="5dp";
{
LinearLayout,
layout_height="match_parent",
layout_width="match_parent",
orientation="horizontal",
{
LinearLayout,
layout_height="wrap_content",
layout_width="match_parent",
orientation="vertical",
layout_margin="10dp",
{
LinearLayout,
layout_height="wrap_content",
layout_width="match_parent",
orientation="horizontal",
layout_weight="1.0",
{
LinearLayout,
layout_height="match_parent",
layout_width="wrap_content",
orientation="vertical",
layout_weight="1.0",
gravity="center",
{
LinearLayout,
layout_height="wrap_content",
layout_width="wrap_content",
layout_weight="1.0",
{
CircleImageView;
src="1.png";
layout_height="56dp";
layout_width="56dp";
onTouchListener=点击监听,
onClick=function()
进入子页面("情感语录")
end
};
},
{
TextView,
layout_height="wrap_content",
layout_width="wrap_content",
text="情感语录",
},
},
{
LinearLayout,
layout_height="match_parent",
layout_width="wrap_content",
orientation="vertical",
layout_weight="1.0",
gravity="center",
{
LinearLayout,
layout_height="wrap_content",
layout_width="wrap_content",
layout_weight="1.0",
{
CircleImageView;
src="2.png";
layout_height="56dp";
layout_width="56dp";
onTouchListener=点击监听,
onClick=function()
进入子页面("撩妹惯例")
end
};
},
{
TextView,
layout_height="wrap_content",
layout_width="wrap_content",
text="撩妹惯例",
},
},
{
LinearLayout,
layout_height="match_parent",
layout_width="wrap_content",
orientation="vertical",
layout_weight="1.0",
gravity="center",
{
LinearLayout,
layout_height="wrap_content",
layout_width="wrap_content",
layout_weight="1.0",
{
CircleImageView;
src="3.png";
layout_height="56dp";
layout_width="56dp";
onTouchListener=点击监听,
onClick=function()
进入子页面("一个图文")
end
};
},
{
TextView,
layout_height="wrap_content",
layout_width="wrap_content",
text="一个图文",
},
},
{
LinearLayout,
layout_height="match_parent",
layout_width="wrap_content",
orientation="vertical",
layout_weight="1.0",
gravity="center",
{
LinearLayout,
layout_height="wrap_content",
layout_width="wrap_content",
layout_weight="1.0",
{
CircleImageView;
src="4.png";
layout_height="56dp";
layout_width="56dp";
onTouchListener=点击监听,
onClick=function()
进入子页面("一个阅读")
end
};
},
{
TextView,
layout_height="wrap_content",
layout_width="wrap_content",
text="一个阅读",
},
},
},
{
LinearLayout,
layout_marginTop="2%h";
layout_height="wrap_content",
layout_width="match_parent",
orientation="horizontal",
layout_weight="1.0",
{
LinearLayout,
layout_height="match_parent",
layout_width="wrap_content",
orientation="vertical",
layout_weight="1.0",
gravity="center",
{
LinearLayout,
layout_height="wrap_content",
layout_width="wrap_content",
layout_weight="1.0",
{
CircleImageView;
src="5.png";
layout_height="56dp";
layout_width="56dp";
onTouchListener=点击监听,
onClick=function()
进入子页面("图片精选")
end
};
},
{
TextView,
layout_height="wrap_content",
layout_width="wrap_content",
text="图片精选",
},
},
{
LinearLayout,
layout_height="match_parent",
layout_width="wrap_content",
orientation="vertical",
layout_weight="1.0",
gravity="center",
{
LinearLayout,
layout_height="wrap_content",
layout_width="wrap_content",
layout_weight="1.0",
{
CircleImageView;
src="6.png";
layout_height="56dp";
layout_width="56dp";
onTouchListener=点击监听,
onClick=function()
进入子页面("专属情头")
end
};
},
{
TextView,
layout_height="wrap_content",
layout_width="wrap_content",
text="专属情头",
},
},
{
LinearLayout,
layout_height="match_parent",
layout_width="wrap_content",
orientation="vertical",
layout_weight="1.0",
gravity="center",
{
LinearLayout,
layout_height="wrap_content",
layout_width="wrap_content",
layout_weight="1.0",
{
CircleImageView;
src="7.png";
layout_height="56dp";
layout_width="56dp";
onTouchListener=点击监听,
onClick=function()
进入子页面("颜值评分")
end
};
},
{
TextView,
layout_height="wrap_content",
layout_width="wrap_content",
text="颜值评分",
},
},
{
LinearLayout,
layout_height="match_parent",
layout_width="wrap_content",
orientation="vertical",
layout_weight="1.0",
gravity="center",
{
LinearLayout,
layout_height="wrap_content",
layout_width="wrap_content",
layout_weight="1.0",
{
CircleImageView;
src="8.png";
layout_height="56dp";
layout_width="56dp";
onTouchListener=点击监听,
onClick=function()
进入子页面("生逢何时")
end
};
},
{
TextView,
layout_height="wrap_content",
layout_width="wrap_content",
text="生逢何时",
},
},
};
};
};
};
};
{
LinearLayout,
layout_height="wrap_content",
layout_width="match_parent",
orientation="horizontal",
layout_marginLeft="10dp",
layout_marginRight="10dp",
layout_marginBottom="10dp",
{
CardView;
layout_margin="0.5dp",
elevation="1.5dp";
id="k1";
layout_width="match_parent";
CardBackgroundColor="#00FFFFFF";
layout_height="match_parent";
radius="5dp";
{
LinearLayout,
layout_height="match_parent",
layout_width="match_parent",
orientation="vertical",
{
LinearLayout,
layout_height="70dp",
layout_width="match_parent",
orientation="horizontal",
{
LinearLayout,
layout_height="8%h",
layout_width="50%w",
layout_weight="1.0",
layout_margin="10dp",
{
CardView;
layout_margin="0.5dp",
elevation="1.5dp";
layout_width="match_parent";
CardBackgroundColor="#00FFFFFF";
layout_height="match_parent";
radius="5dp";
{
ImageView;
layout_width="fill",
layout_height="fill",
scaleType="fitXY";
id="n1";
onTouchListener=点击监听,
onClick=function()
进入子页面("表白网页制作")
end
},
{
TextView,
layout_height="wrap_content",
layout_width="wrap_content",
text="表白网页制作",
--textSize="10sp",
layout_gravity="center",
},
},
},
{
LinearLayout,
layout_height="8%h",
layout_width="50%w",
layout_weight="1.0",
layout_margin="10dp",
{
CardView;
layout_margin="0.5dp",
elevation="1.5dp";
id="k1";
layout_width="match_parent";
CardBackgroundColor="#00FFFFFF";
layout_height="match_parent";
radius="5dp";
{
ImageView;
layout_width="fill",
layout_height="fill",
id="n2";
onTouchListener=点击监听,
onClick=function()
进入子页面("表白图片制作")
end
},
{
TextView,
layout_height="wrap_content",
layout_width="wrap_content",
text="表白图片制作",
--textSize="10sp",
layout_gravity="center",
},
},
},
},
{
LinearLayout,
layout_height="50dp",--
layout_width="match_parent",
orientation="horizontal",
{
LinearLayout,
layout_height="8%h",
layout_width="50%w",
layout_weight="1.0",
layout_marginLeft="10dp",
layout_marginRight="10dp",
{
CardView;
layout_margin="0.5dp",
elevation="1.5dp";
id="k1";
layout_width="match_parent";
CardBackgroundColor="#00FFFFFF";
layout_height="match_parent";
radius="5dp";
{
ImageView;
layout_width="fill",
layout_height="fill",
id="n3";
onTouchListener=点击监听,
onClick=function()
弹出消息("待开发")
end
},
{
TextView,
layout_height="wrap_content",
layout_width="wrap_content",
text="待开发",
--textSize="10sp",
layout_gravity="center",
},
},
},
{
LinearLayout,
layout_height="8%h",
layout_width="50%w",
layout_weight="1.0",
layout_marginLeft="10dp",
layout_marginRight="10dp",
{
CardView;
layout_margin="0.5dp",
elevation="1.5dp";
id="k1";
layout_width="match_parent";
CardBackgroundColor="#00FFFFFF";
layout_height="match_parent";
radius="5dp";
{
ImageView;
layout_width="fill",
layout_height="fill",
id="n4";
onTouchListener=点击监听,
onClick=function()
弹出消息("待开发")
end
},
{
TextView,
layout_height="wrap_content",
layout_width="wrap_content",
text="待开发",
--textSize="10sp",
layout_gravity="center",
},
},
},
},
{
LinearLayout,
layout_height="70dp",
layout_width="match_parent",
orientation="horizontal",
{
LinearLayout,
layout_height="8%h",
layout_width="wrap_content",
layout_weight="1.0",
layout_margin="10dp",
{
CardView;
layout_margin="0.5dp",
elevation="1.5dp";
id="k1";
layout_width="match_parent";
CardBackgroundColor="#00FFFFFF";
layout_height="match_parent";
radius="5dp";
{
ImageView;
layout_width="fill",
layout_height="fill",
id="n5";
onTouchListener=点击监听,
onClick=function()
弹出消息("待开发")
end
},
{
TextView,
layout_height="wrap_content",
layout_width="wrap_content",
text="待开发",
--textSize="10sp",
layout_gravity="center",
},
},
},
{
LinearLayout,
layout_height="8%h",
layout_width="wrap_content",
layout_weight="1.0",
layout_margin="10dp",
{
CardView;
layout_margin="0.5dp",
elevation="1.5dp";
id="k1";
layout_width="match_parent";
CardBackgroundColor="#00FFFFFF";
layout_height="match_parent";
radius="5dp";
{
ImageView;
layout_width="fill",
layout_height="fill",
id="n6";
onTouchListener=点击监听,
onClick=function()
弹出消息("待开发")
end
},
{
TextView,
layout_height="wrap_content",
layout_width="wrap_content",
text="待开发",
--textSize="10sp",
layout_gravity="center",
};
};
};
};
};
};
};
};
};
};
webView.addView(loadlayout(ghost))
import "android.graphics.drawable.GradientDrawable"
function 渐变(left_jb,right_jb,id)
drawable = GradientDrawable(GradientDrawable.Orientation.TR_BL,{
right_jb,
left_jb,
});
id.setBackgroundDrawable(drawable)
end
渐变(0xff1799f9,0xff16c9ff,n1)
渐变(0xfffdad30,0xfff2e513,n2)
渐变(0xff6154f2,0xff6780e7,n3)
渐变(0xff9ecece,0xff5d8cba,n4)
渐变(0xfffc9273,0xfff7c0a1,n5)
渐变(0xfffa8052,0xfffc9273,n6)
f1.onClick=function()
pg1.showPage(0)
end
f2.onClick=function()
pg1.showPage(1)
end
f3.onClick=function()
pg1.showPage(2)
end
local n=0
function images()
task(4000,function()
n=n+1 pg1.showPage(n%3)
images()
end)
end
images();
aer=true
bt=0
pg1.addOnPageChangeListener{
onPageSelected=function(page)
bt=page
end,
onPageScrollStateChanged=function(state)
end,
}; |
--
-- from src/acker.c
--
-- int A(int, int) to ack
--
local function ack(x, y)
if x == 0 then return y+1 end
if y == 0 then return ack(x-1,1) end
return ack(x-1, ack(x,y-1))
end
return {
ack = ack
}
|
Wait(500)
character_1:WithWaitTime(100):UseSkill(1)
SkipAttack() |
local adsKit = require "plugin.huaweiAdsKit"
local widget = require( "widget" )
local json = require("json")
local TAG = "adsKit"
local header = display.newText( "Huawei Ads Kit", display.contentCenterX, 60, native.systemFont, 10 )
header:setFillColor( 255, 255, 255 )
local function listener( event )
print(TAG, json.prettify(event))
end
adsKit.init( listener, {setTagForChildProtection= -1, setTagForUnderAgeOfPromise=1, setAdContentClassification="W", setNonPersonalizedAd=0} )
-- Interstitial Ad
local header = display.newText( "Interstitial Ad", display.contentCenterX, 100, native.systemFont, 10 )
header:setFillColor( 255, 255, 255 )
local InterstitialCreate = widget.newButton(
{
left = 65,
top = 110,
id = "create",
label = "create",
onPress = function()
adsKit.create("Interstitial", {AdId="testb4znbuh3n2"})
end,
width = 90,
height = 30
}
)
local InterstitialLoad = widget.newButton(
{
left = 155,
top = 110,
id = "load",
label = "load",
onPress = function()
adsKit.load("Interstitial")
end,
width = 90,
height = 30
}
)
local InterstitialShow = widget.newButton(
{
left = 65,
top = 140,
id = "show",
label = "show",
onPress = function()
adsKit.show("Interstitial")
end,
width = 90,
height = 30
}
)
--Banner Ad
local header = display.newText( "Banner Ad", display.contentCenterX, 200, native.systemFont, 10 )
header:setFillColor( 255, 255, 255 )
local BannerCreate = widget.newButton(
{
left = 65,
top = 210,
id = "create",
label = "create",
onPress = function()
adsKit.create("Banner", {AdId="testw6vs28auh3", BannerSize="360x144", BannerRefresh=60})
end,
width = 90,
height = 30
}
)
local BannerLoad = widget.newButton(
{
left = 155,
top = 210,
id = "load",
label = "load",
onPress = function()
adsKit.load("Banner")
end,
width = 90,
height = 30
}
)
local BannerHide = widget.newButton(
{
left = 65,
top = 240,
id = "hide",
label = "hide",
onPress = function()
adsKit.hide("Banner")
end,
width = 90,
height = 30
}
)
local BannerShow = widget.newButton(
{
left = 155,
top = 240,
id = "show",
label = "show",
onPress = function()
adsKit.show("Banner")
end,
width = 90,
height = 30
}
)
--Rewarded Ad
local header = display.newText( "Rewarded Ad", display.contentCenterX, 300, native.systemFont, 10 )
header:setFillColor( 255, 255, 255 )
local RewardedCreate = widget.newButton(
{
left = 65,
top = 310,
id = "create",
label = "create",
onPress = function()
adsKit.create("Rewarded", {AdId="testw6vs28auh3"})
end,
width = 90,
height = 30
}
)
local RewardedLoad = widget.newButton(
{
left = 155,
top = 310,
id = "load",
label = "load",
onPress = function()
adsKit.load("Rewarded")
end,
width = 90,
height = 30
}
)
local show = widget.newButton(
{
left = 65,
top = 340,
id = "show",
label = "show",
onPress = function()
adsKit.show("Rewarded")
end,
width = 90,
height = 30
}
)
|
--[[
Performs a left-fold of the list with the given initial value and callback.
]]
local function foldLeft(list, initial, callback)
local accum = initial
for i = 1, #list do
accum = callback(accum, list[i], i)
end
return accum
end
return foldLeft
|
return {
unpack = table.unpack or unpack,
}
|
require('pathfinding/point');
local Point = Pathfinding.Point;
--[[
Checks if a specific point is along a segment. Returns true if it is, otherwise false.
All three arguments should be a Point object
]]
function Pathfinding.pointOnSegment(point, segmentStart, segmentEnd)
local dx,dy = segmentEnd.x - segmentStart.x, segmentEnd.y - segmentStart.x;
return (((point.x - segmentStart.x) * dy) == ((point.y - segmentStart.y) * dx));
end
--[[
Finds the point along two segments (points point1,point2 and point3,point4) that intersect.
If constrain is true, then the two segments must overlap. Otherwise, the intersection point may be outside of the segments.
Returns a Point at the point of intersection if one is available, otherwise returns nil
]]
function Pathfinding.lineIntersection(vertex1, vertex2, vertex3, vertex4, constrain)
assert(vertex1 and vertex2 and vertex3 and vertex3);
assert(vertex1.x and vertex1.y);
assert(vertex2.x and vertex2.y);
assert(vertex3.x and vertex3.y);
assert(vertex4.x and vertex4.y);
local line1 = {x1 = vertex1.x, y1 = vertex1.y, x2 = vertex2.x, y2 = vertex2.y};
local line2 = {x1 = vertex3.x, y1 = vertex3.y, x2 = vertex4.x, y2 = vertex4.y};
local denominator = (line1.x2 - line1.x1)*(line2.y2 - line2.y1) - (line2.x2 - line2.x1)*(line1.y2 - line1.y1);
-- If denominator is 0, lines are parallel
if( denominator == 0 ) then
return nil;
end
local nA = (line2.x2 - line2.x1)*(line1.y1 - line2.y1) - (line2.y2 - line2.y1)*(line1.x1 - line2.x1);
local nB = (line1.x2 - line1.x1)*(line1.y1 - line2.y1) - (line1.y2 - line1.y1)*(line1.x1 - line2.x1);
-- Calculate intermediate fractional point
local uA = nA / denominator;
local uB = nB / denominator;
if( constrain ) then
-- We could check if fractional point (both uA and uB) is between (or includes) 0 and 1
-- to check if the segments overlap
-- If uA and uB are outside of the range of 0..1, then the segments do not overlap
if( uA < 0 or uA > 1 or uB < 0 or uB > 1 ) then
return nil;
end
-- If we're touching end pieces, don't count is as an intersection
if( (uA == 0 or uA == 1) and (uB == 0 or uB == 1) ) then
return nil;
end
end
local nX = line1.x1 + (uA * (line1.x2 - line1.x1));
local nY = line1.y1 + (uA * (line1.y2 - line1.y1));
return Point(nX, nY);
end
-- Checks if there's visibility between two nodes.
-- Returns a boolean - true if there's visibility, otherwise returns false
function Pathfinding.checkVisibility(polygons, point1, point2)
-- Iterate over every segment in all polygons, check for line collisions
for i,polygon in pairs(polygons) do
-- If this line spans across the interior of the polygon we don't have visibility
local midpoint = Point((point1.x + point2.x) / 2, (point1.y + point2.y) / 2);
local inPoly, onPoly = clipper.pointInPoly(midpoint, polygon:getPoints());
if( inPoly ) then
return false;
end
for j,point in pairs(polygon:getPoints()) do
local v1 = polygon:getPoint(j);
local v2 = polygon:getPoint(polygon:nextIndex(j));
local intersection = Pathfinding.lineIntersection(point1, point2, v1, v2, true);
if( intersection ~= nil ) then
return false;
end
end
end
return true;
end |
-----------------------------------
-- Area: Batallia Downs
-- NPC: Luck Rune
-- Involved in Quest: Mhaura Fortune
-- !pos -362.167 -12.199 157.158 105
-----------------------------------
local ID = require("scripts/zones/Batallia_Downs/IDs")
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY)
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end; |
-- ***************************************************************
--
-- Copyright 2016 by Sean Conner. All Rights Reserved.
--
-- This library is free software; you can redistribute it and/or modify it
-- under the terms of the GNU Lesser General Public License as published by
-- the Free Software Foundation; either version 3 of the License, or (at your
-- option) any later version.
--
-- This library is distributed in the hope that it will be useful, but
-- WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
-- License for more details.
--
-- You should have received a copy of the GNU Lesser General Public License
-- along with this library; if not, see <http://www.gnu.org/licenses/>.
--
-- Comments, questions and criticisms can be sent to: sean@conman.org
--
-- ====================================================================
--
-- Module: cbor
--
-- Desc: Decodes CBOR data.
--
-- Types:
-- cbor (enum)
-- *** base types
-- * UINT unsigned integer (Lua number)
-- * NINT negative integer (Lua number)
-- * BIN binary string (Lua string)
-- * TEXT UTF-8 string (Lua string)
-- * ARRAY value is item count (Lua number)
-- * MAP value is item count (Lua number)
-- *** simple types
-- * SIMPLE SEE NOTES (Lua number)
-- * false false value (Lua false)
-- * true true value (Lua true)
-- * null NULL value (Lua nil)
-- * undefined undefined value (Lua nil)
-- * half half precicion IEEE 754 float
-- * single single precision IEEE 754 float
-- * double double precision IEEE 754 float
-- * __break SEE NOTES
-- *** tagged types
-- * TAG_* unsupported tag type (Lua number)
-- * _datetime datetime (TEXT)
-- * _epoch see cbor.isnumber()
-- * _pbignum positive bignum (BIN)
-- * _nbignum negative bignum (BIN)
-- * _decimalfraction ARRAY(integer exp, integer mantissa)
-- * _bigfloat ARRAY(float exp,integer mantissa)
-- * _tobase64url should be base64url encoded (BIN)
-- * _tobase64 should be base64 encoded (BIN)
-- * _tobase16 should be base16 encoded (BIN)
-- * _cbor CBOR encoded data (BIN)
-- * _url URL (TEXT)
-- * _base64url base64url encoded data (TEXT)
-- * _base64 base64 encoded data (TEXT)
-- * _regex regex (TEXT)
-- * _mime MIME encoded messsage (TEXT)
-- * _magic_cbor itself (no data, used to self-describe CBOR data)
-- ** more tagged types, extensions
-- * _nthstring shared string
-- * _perlobj Perl serialized object
-- * _serialobj Generic serialized object
-- * _shareable sharable resource (ARRAY or MAP)
-- * _sharedref reference (UINT)
-- * _rational Rational number
-- * _uuid UUID value (BIN)
-- * _language Language-tagged string
-- * _id Identifier
-- * _stringref string reference
-- * _bmime Binary MIME message
-- * _decimalfractionexp like _decimalfraction, non-int exponent
-- * _bigfloatexp like _bigfloat, non-int exponent
-- * _indirection Indirection
-- * _rains RAINS message
-- * _ipaddress IP address (or MAC address)
-- *** Lua CBOR library types
-- * __error error parsing (TEXT)
-- data (any) decoded CBOR data
-- pos (integer) position parsing stopped
--
-- NOTES: The simple type is returned for non-defined simple types.
--
-- The __break type is used to indicate the end of an
-- indefinite array or map.
--
-- luacheck: globals isnumber isinteger isfloat decode encode pdecode pencode
-- luacheck: globals TYPE TAG SIMPLE _VERSION __ENCODE_MAP _ENV
-- luacheck: ignore 611
-- ********************************************************************
local math = require "math"
local string = require "string"
local table = require "table"
local lpeg = require "lpeg"
local cbor_c = require "org.conman.cbor_c"
local LUA_VERSION = _VERSION
local error = error
local pcall = pcall
local assert = assert
local getmetatable = getmetatable
local setmetatable = setmetatable
local pairs = pairs
local ipairs = ipairs
local type = type
local tonumber = tonumber
if LUA_VERSION < "Lua 5.3" then
function math.type(n)
return n >= -9007199254740992
and n <= 9007199254740992
and n % 1 == 0
and 'integer'
or 'float'
end
end
if LUA_VERSION == "Lua 5.1" then
module "org.conman.cbor" -- luacheck: ignore
else
_ENV = {} -- luacheck: ignore
end
_VERSION = cbor_c._VERSION
-- ***********************************************************************
-- UTF-8 defintion from RFC-3629. There's a deviation from the RFC
-- specification in that I only allow certain codes from the US-ASCII C0
-- range (control codes) that are in common use.
-- ***********************************************************************
local UTF8 = (
lpeg.R("\7\13"," ~")
+ lpeg.R("\194\223") * lpeg.R("\128\191")
+ lpeg.P("\224") * lpeg.R("\160\191") * lpeg.R("\128\191")
+ lpeg.R("\225\236") * lpeg.R("\128\191") * lpeg.R("\128\191")
+ lpeg.P("\237") * lpeg.R("\128\159") * lpeg.R("\128\191")
+ lpeg.R("\238\239") * lpeg.R("\128\191") * lpeg.R("\128\191")
+ lpeg.P("\240") * lpeg.R("\144\191") * lpeg.R("\128\191") * lpeg.R("\128\191")
+ lpeg.R("\241\243") * lpeg.R("\128\191") * lpeg.R("\128\191") * lpeg.R("\128\191")
+ lpeg.P("\224") * lpeg.R("\128\142") * lpeg.R("\128\191") * lpeg.R("\128\191")
)^0
-- ***********************************************************************
local function throw(pos,...)
error( { pos = pos , msg = string.format(...) } , 2)
end
-- ***********************************************************************
-- Usage: bool = cbor.isnumber(ctype)
-- Desc: returns true of the given CBOR type is a number
-- Input: type (enum/cbor) CBOR type
-- Return: bool (boolean) true if number, false otherwise
-- ***********************************************************************
function isnumber(ctype)
return ctype == 'UINT'
or ctype == 'NINT'
or ctype == 'half'
or ctype == 'single'
or ctype == 'double'
end
-- ***********************************************************************
-- Usage: bool = cbor.isinteger(ctype)
-- Desc: returns true if the given CBOR type is an integer
-- Input: ctype (enum/cbor) CBOR type
-- Return: bool (boolean) true if number, false othersise
-- ***********************************************************************
function isinteger(ctype)
return ctype == 'UINT'
or ctype == 'NINT'
end
-- ***********************************************************************
-- Usage: bool = cbor.isfloat(ctype)
-- Desc: returns true if the given CBOR type is a float
-- Input: ctype (enum/cbor) CBOR type
-- Return: bool (boolean) true if number, false otherwise
-- ***********************************************************************
function isfloat(ctype)
return ctype == 'half'
or ctype == 'single'
or ctype == 'double'
end
-- ***********************************************************************
-- usage: len = mstrlen(ref)
-- desc: This function returns the minimum length a string should
-- have to find its reference (see notes)
-- input: ref (table) reference table
-- return: len (integer) minimum string length for reference
--
-- note: via http://cbor.schmorp.de/stringref
-- ***********************************************************************
local function mstrlen(ref)
if #ref < 24 then
return 3
elseif #ref < 256 then
return 4
elseif #ref < 65536 then
return 5
elseif #ref < 4294967296 then
return 7
else
return 11
end
end
-- ***********************************************************************
-- usage: value2,pos2,ctype2 = decbintext(packet,pos,info,value,conv,ref,ctype)
-- desc: Decode a CBOR BIN or CBOR TEXT into a Lua string
-- input: packet (binary) binary blob
-- pos (integer) byte position in packet
-- info (integer) CBOR info value (0..31)
-- value (integer) string length
-- conv (table) conversion routines (passed to decode())
-- ref (table) reference table
-- ctype (enum/cbor) 'BIN' or 'TEXT'
-- return: value2 (string) string from packet
-- pos2 (integer) position past string just extracted
-- ctype2 (enum/cbor) 'BIN' or 'TEXT'
-- ***********************************************************************
local function decbintext(packet,pos,info,value,conv,ref,ctype)
-- ----------------------------------------------------------------------
-- Support for _stringref and _nthstring tags [1]. Strings shorter than
-- the reference mark will NOT be encoded, so these strings will not have
-- a reference upon decoding.
--
-- [1] http://cbor.schmorp.de/stringref
-- ----------------------------------------------------------------------
if info < 31 then
local data = packet:sub(pos,pos + value - 1)
-- --------------------------------------------------
-- make sure the string is long enough to reference
-- --------------------------------------------------
if not ref._stringref[data] then
if #data >= mstrlen(ref._stringref) then
table.insert(ref._stringref,{ ctype = ctype , value = data })
ref._stringref[data] = true
end
end
return data,pos + value,ctype
else
local acc = {}
local t,nvalue
while true do
nvalue,pos,t = decode(packet,pos,conv,ref)
if t == '__break' then
break;
end
if t ~= ctype then
throw(pos,"%s: expecting %s, got %s",ctype,ctype,t)
end
table.insert(acc,nvalue)
end
return table.concat(acc),pos,ctype
end
end
-- ***********************************************************************
-- usage: blob = encbintext(value,sref,stref,ctype)
-- desc: Encode a string into a CBOR BIN or TYPE
-- input: value (string) Lua string to encode
-- sref (table) shared references
-- stref (table) string references
-- ctype (integer) either 0x40 (BIN) or 0x60 (TEXT)
-- return: blob (binary) encoded string
-- ***********************************************************************
local function encbintext(value,sref,stref,ctype)
if stref then
if not stref[value] then
if #value >= mstrlen(stref) then
table.insert(stref,value)
stref[value] = #stref - 1
end
else
return TAG._nthstring(stref[value],sref,stref)
end
end
return cbor_c.encode(ctype,#value) .. value
end
-- ***********************************************************************
--
-- CBOR base TYPES
--
-- Both encoding and decoding functions for CBOR base types are here.
--
-- Usage: blob = cbor.TYPE['name'](n,sref,stref)
-- Desc: Encode a CBOR base type
-- Input: n (integer string table) Lua type (see notes)
-- sref (table/optional) shared reference table
-- stref (table/optional) shared string reference table
-- Return: blob (binary) CBOR encoded value
--
-- Note: UINT and NINT take an integer.
--
-- BIN and TEXT take a string. TEXT will check to see if
-- the text is well formed UTF8 and throw an error if the
-- text is not valid UTF8.
--
-- ARRAY and MAP take a table of an appropriate type. No
-- checking is done of the passed in table, so a table
-- of just name/value pairs passed in to ARRAY will return
-- an empty CBOR encoded array.
--
-- TAG and SIMPLE encoding are handled elsewhere.
--
-- Usage: value2,pos2,ctype = cbor.TYPE[n](packet,pos,info,value,conv,ref)
-- Desc: Decode a CBOR base type
-- Input: packet (binary) binary blob of CBOR data
-- pos (integer) byte offset in packet to start parsing from
-- info (integer) CBOR info (0 .. 31)
-- value (integer) CBOR decoded value
-- conv (table) conversion table (passed to decode())
-- ref (table) used to generate references (TAG types only)
-- Return: value2 (any) decoded CBOR value
-- pos2 (integer) byte offset just past parsed data
-- ctype (enum/cbor) CBOR deocded type
--
-- Note: tag_* is returned for any non-supported TAG types. The
-- actual format is 'tag_' <integer value>---for example,
-- 'tag_1234567890'. Supported TAG types will return the
-- appropriate type name.
--
-- simple is returned for any non-supported SIMPLE types.
-- Supported simple types will return the appropriate type
-- name.
--
-- ***********************************************************************
TYPE =
{
UINT = function(n)
return cbor_c.encode(0x00,n)
end,
[0x00] = function(_,pos,info,value)
if info == 31 then throw(pos,"invalid data") end
return value,pos,'UINT'
end,
-- =====================================================================
NINT = function(n)
return cbor_c.encode(0x20,-1 - n)
end,
[0x20] = function(_,pos,info,value)
if info == 31 then throw(pos,"invalid data") end
return -1 - value,pos,'NINT'
end,
-- =====================================================================
BIN = function(b,sref,stref)
if not b then
return "\95"
else
return encbintext(b,sref,stref,0x40)
end
end,
[0x40] = function(packet,pos,info,value,conv,ref)
return decbintext(packet,pos,info,value,conv,ref,'BIN')
end,
-- =====================================================================
TEXT = function(s,sref,stref)
if not s then
return "\127"
else
assert(UTF8:match(s) > #s,"TEXT: not UTF-8 text")
return encbintext(s,sref,stref,0x60)
end
end,
[0x60] = function(packet,pos,info,value,conv,ref)
return decbintext(packet,pos,info,value,conv,ref,'TEXT')
end,
-- =====================================================================
ARRAY = function(array,sref,stref)
if not array then
return "\159"
elseif type(array) == 'number' then
return cbor_c.encode(0x80,array)
end
local res = ""
if sref then
if sref[array] then
return TAG._sharedref(sref[array],sref,stref)
end
res = TAG._shareable(array)
table.insert(sref,array)
sref[array] = #sref - 1
end
res = res .. cbor_c.encode(0x80,#array)
for _,item in ipairs(array) do
res = res .. encode(item,sref,stref)
end
return res
end,
[0x80] = function(packet,pos,_,value,conv,ref)
-- ---------------------------------------------------------------------
-- Per [1], shared references need to exist before the decoding process.
-- ref._sharedref.REF will be such a reference. If it doesn't exist,
-- then just create a table.
--
-- [1] http://cbor.schmorp.de/value-sharing
-- ---------------------------------------------------------------------
local acc = ref._sharedref.REF or {}
for i = 1 , value do
local avalue,npos,ctype = decode(packet,pos,conv,ref)
if ctype == '__break' then return acc,npos,'ARRAY' end
acc[i] = avalue
pos = npos
end
return acc,pos,'ARRAY'
end,
-- =====================================================================
MAP = function(map,sref,stref)
if not map then
return "\191"
elseif type(map) == 'number' then
return cbor_c.encode(0xA0,map)
end
local ref = ""
if sref then
if sref[map] then
return TAG._sharedref(sref[map],sref,stref)
end
ref = TAG._shareable(map)
table.insert(sref,map)
sref[map] = #sref - 1
end
local res = ""
local cnt = 0
for key,value in pairs(map) do
res = res .. encode(key,sref,stref)
res = res .. encode(value,sref,stref)
cnt = cnt + 1
end
return ref .. cbor_c.encode(0xA0,cnt) .. res
end,
[0xA0] = function(packet,pos,_,value,conv,ref)
local acc = ref._sharedref.REF or {} -- see comment above
for _ = 1 , value do
local nvalue,npos,nctype = decode(packet,pos,conv,ref,true)
if nctype == '__break' then return acc,npos,'MAP' end
local vvalue,npos2 = decode(packet,npos,conv,ref)
acc[nvalue] = vvalue
pos = npos2
end
return acc,pos,'MAP'
end,
-- =====================================================================
[0xC0] = function(packet,pos,info,value,conv,ref)
if info == 31 then throw(pos,"invalid data") end
return TAG[value](packet,pos,conv,ref)
end,
-- =====================================================================
[0xE0] = function(_,pos,info,value)
return SIMPLE[info](pos,value)
end,
}
-- ***********************************************************************
--
-- CBOR TAG values
--
-- Encoding and decoding of CBOR TAG types are here.
--
-- Usage: blob = cbor.TAG['name'](value,sref,stref)
-- Desc: Encode a CBOR tagged value
-- Input: value (any) any Lua type
-- sref (table/optional) shared reference table
-- stref (table/optional) shared string reference table
-- Return: blob (binary) CBOR encoded tagged value
--
-- Note: Some tags only support a subset of Lua types.
--
-- Usage: value,pos2,ctype = cbor.TAG[n](packet,pos,conv,ref)
-- Desc: Decode a CBOR tagged value
-- Input: packet (binary) binary blob of CBOR tagged data
-- pos (integer) byte offset into packet
-- conv (table) conversion routines (passed to decode())
-- ref (table) reference table
-- Return: value (any) decoded CBOR tagged value
-- pos2 (integer) byte offset just past parsed data
-- ctype (enum/cbor) CBOR type of value
--
-- ***********************************************************************
TAG = setmetatable(
{
_datetime = function(value)
return cbor_c.encode(0xC0,0) .. TYPE.TEXT(value)
end,
[0] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype == 'TEXT' then
return value,npos,'_datetime'
else
throw(pos,"_datetime: wanted TEXT, got %s",ctype)
end
end,
-- =====================================================================
_epoch = function(value,sref,stref)
assert(type(value) == 'number',"_epoch expects a number")
return cbor_c.encode(0xC0,1) .. encode(value,sref,stref)
end,
[1] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if isnumber(ctype) then
return value,npos,'_epoch'
else
throw(pos,"_epoch: wanted number, got %s",ctype)
end
end,
-- =====================================================================
_pbignum = function(value,sref,stref)
return cbor_c.encode(0xC0,2) .. TYPE.BIN(value,sref,stref)
end,
[2] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype == 'BIN' then
return value,npos,'_pbignum'
else
throw(pos,"_pbignum: wanted BIN, got %s",ctype)
end
end,
-- =====================================================================
_nbignum = function(value,sref,stref)
return cbor_c.encode(0xC0,3) .. TYPE.BIN(value,sref,stref)
end,
[3] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype == 'BIN' then
return value,npos,'_nbignum'
else
throw(pos,"_nbignum: wanted BIN, got %s",ctype)
end
end,
-- =====================================================================
_decimalfraction = function(value,sref,stref)
assert(type(value) == 'table', "_decimalfractoin expects an array")
assert(#value == 2, "_decimalfraction expects a two item array")
assert(math.type(value[1]) == 'integer',"_decimalfraction expects integer as first element")
assert(math.type(value[2]) == 'integer',"_decimalfraction expects integer as second element")
return cbor_c.encode(0xC0,4) .. TYPE.ARRAY(value,sref,stref)
end,
[4] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype ~= 'ARRAY' then
throw(pos,"_decimalfraction: wanted ARRAY, got %s",ctype)
end
if #value ~= 2 then
throw(pos,"_decimalfraction: wanted ARRAY[2], got ARRAY[%d]",#value)
end
if math.type(value[1]) ~= 'integer' then
throw(pos,"_decimalfraction: wanted integer for exp, got %s",type(value[1]))
end
if math.type(value[2]) ~= 'integer' then
throw(pos,"_decimalfraction: wanted integer for mantissa, got %s",type(value[2]))
end
return value,npos,'_decimalfraction'
end,
-- =====================================================================
_bigfloat = function(value,sref,stref)
assert(type(value) == 'table', "_bigfloat expects an array")
assert(#value == 2, "_bigfloat expects a two item array")
assert(math.type(value[1]) == 'integer',"_bigfloat expects an integer as first element")
assert(math.type(value[2]) == 'integer',"_bigfloat expects an integer as second element")
return cbor_c.encode(0xC0,5) .. TYPE.ARRAY(value,sref,stref)
end,
[5] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype ~= 'ARRAY' then
throw(pos,"_bigfloat: wanted ARRAY, got %s",ctype)
end
if #value ~= 2 then
throw(pos,"_bigfloat: wanted ARRAY[2], got ARRAY[%s]",value)
end
if type(value[1]) ~= 'number' then
throw(pos,"_bigfloat: wanted number for exp, got %s",ctype)
end
if math.type(value[2]) ~= 'integer' then
throw(pos,"_bigfloat: wanted integer for mantissa, got %s",ctype)
end
return value,npos,'_bigfloat'
end,
-- =====================================================================
_tobase64url = function(value,sref,stref)
return cbor_c.encode(0xC0,21) .. encode(value,sref,stref)
end,
[21] = function(packet,pos,conv,ref)
local value,npos = decode(packet,pos,conv,ref)
return value,npos,'_tobase64url'
end,
-- =====================================================================
_tobase64 = function(value,sref,stref)
return cbor_c.encode(0xC0,22) .. encode(value,sref,stref)
end,
[22] = function(packet,pos,conv,ref)
local value,npos = decode(packet,pos,conv,ref)
return value,npos,'_tobase64'
end,
-- =====================================================================
_tobase16 = function(value,sref,stref)
return cbor_c.encode(0xC0,23) .. encode(value,sref,stref)
end,
[23] = function(packet,pos,conv,ref)
local value,npos = decode(packet,pos,conv,ref)
return value,npos,'_tobase16'
end,
-- =====================================================================
_cbor = function(value,sref,stref)
return cbor_c.encode(0xC0,24) .. TYPE.BIN(value,sref,stref)
end,
[24] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype == 'BIN' then
return value,npos,'_cbor'
else
throw(pos,"_cbor: wanted BIN, got %s",ctype)
end
end,
-- =====================================================================
_url = function(value,sref,stref)
return cbor_c.encode(0xC0,32) .. TYPE.TEXT(value,sref,stref)
end,
[32] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype == 'TEXT' then
return value,npos,'_url'
else
throw(pos,"_url: wanted TEXT, got %s",ctype)
end
end,
-- =====================================================================
_base64url = function(value,sref,stref)
return cbor_c.encode(0xC0,33) .. TYPE.TEXT(value,sref,stref)
end,
[33] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype == 'TEXT' then
return value,npos,'_base64url'
else
throw(pos,"_base64url: wanted TEXT, got %s",ctype)
end
end,
-- =====================================================================
_base64 = function(value,sref,stref)
return cbor_c.encode(0xC0,34) .. TYPE.TEXT(value,sref,stref)
end,
[34] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype == 'TEXT' then
return value,npos,'_base64'
else
throw(pos,"_base64: wanted TEXT, got %s",ctype)
end
end,
-- =====================================================================
_regex = function(value,sref,stref)
return cbor_c.encode(0xC0,35) .. TYPE.TEXT(value,sref,stref)
end,
[35] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype == 'TEXT' then
return value,npos,'_regex'
else
throw(pos,"_regex: wanted TEXT, got %s",ctype)
end
end,
-- =====================================================================
_mime = function(value,sref,stref)
return cbor_c.encode(0xC0,36) .. TYPE.TEXT(value,sref,stref)
end,
[36] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype == 'TEXT' then
return value,npos,'_mime'
else
throw(pos,"_mime: wanted TEXT, got %s",ctype)
end
end,
-- =====================================================================
_magic_cbor = function()
return cbor_c.encode(0xC0,55799)
end,
[55799] = function(_,pos)
return '_magic_cbor',pos,'_magic_cbor'
end,
-- **********************************************************
-- Following defined by IANA
-- http://www.iana.org/assignments/cbor-tags/cbor-tags.xhtml
-- **********************************************************
_nthstring = function(value,sref,stref)
return cbor_c.encode(0xC0,25) .. encode(value,sref,stref)
end,
[25] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype == 'UINT' then
value = value + 1
if not ref._stringref[value] then
throw(pos,"_nthstring: invalid index %d",value - 1)
end
return ref._stringref[value].value,npos,ref._stringref[value].ctype
else
throw(pos,"_nthstring: wanted UINT, got %s",ctype)
end
end,
-- =====================================================================
_perlobj = function(value,sref,stref)
return cbor_c.encode(0xC0,26) .. TYPE.ARRAY(value,sref,stref)
end,
[26] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype == 'ARRAY' then
return value,npos,'_perlobj'
else
throw(pos,"_perlobj: wanted ARRAY, got %s",ctype)
end
end,
-- =====================================================================
_serialobj = function(value,sref,stref)
return cbor_c.encode(0xC0,27) .. TYPE.ARRAY(value,sref,stref)
end,
[27] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype == 'ARRAY' then
return value,npos,'_serialobj'
else
throw(pos,"_serialobj: wanted ARRAY, got %s",ctype)
end
end,
-- =====================================================================
-- To cut down on the silliness, not all types are shareable, only
-- ARRAYs and MAPs will be supported. TEXT and BIN have their own
-- reference system; sharing UINT, NINT or SIMPLE just doesn't make
-- sense, and TAGs aren't shareable either. So ARRAY and MAP it is!
-- =====================================================================
_shareable = function(value)
assert(type(value) == 'table',"_shareable: expects a table")
return cbor_c.encode(0xC0,28)
end,
[28] = function(packet,pos,conv,ref)
ref._sharedref.REF = {}
table.insert(ref._sharedref,{ value = ref._sharedref.REF })
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype == 'ARRAY' or ctype == 'MAP' then
ref._sharedref[#ref._sharedref].ctype = ctype
return value,npos,ctype
else
throw(pos,"_shareable: wanted ARRAY or MAP, got %s",ctype)
end
end,
-- =====================================================================
_sharedref = function(value,sref,stref)
return cbor_c.encode(0xC0,29) .. encode(value,sref,stref)
end,
[29] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype == 'UINT' then
value = value + 1
if not ref._sharedref[value] then
throw(pos,"_sharedref: invalid index %d",value - 1)
end
return ref._sharedref[value].value,npos,ref._sharedref[value].ctype
else
throw(pos,"_sharedref: wanted ARRAY or MAP, got %s",ctype)
end
end,
-- =====================================================================
_rational = function(value,sref,stref)
-- -----------------------------------------------------------------
-- Per spec [1], the first value must be an integer (positive or
-- negative) and the second value must be a positive integer greater
-- than 0. Since I'm don't know the format for bignums, there's
-- little error checking if those are in use. That's the way things
-- go.
--
-- The encoding phase is done by hand for this. Here we go ...
-- -----------------------------------------------------------------
assert(type(value) == 'table',"_rational: expecting a table")
assert(#value == 2,"_rational: expecting a table of two values")
assert(math.type(value[1]) == 'integer' or type(value[1] == 'string'),"_rational: bad numerator")
assert(
math.type(value[2]) == 'integer' and value[2] > 0
or type(value[2]) == 'string',
"_rational: bad denominator"
)
local res = cbor_c.encode(0xC0,30) .. cbor_c.encode(0x80,2)
if math.type(value[1]) == 'integer' then
res = res .. __ENCODE_MAP.number(value[1],sref,stref)
else
res = res .. TYPE.BIN(value[1],sref,stref)
end
if math.type(value[2]) == 'integer' then
res = res .. TYPE.UINT(value[2],sref,stref)
else
res = res .. TYPE.BIN(value[2],sref,stref)
end
return res
end,
[30] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype ~= 'ARRAY' then
throw(pos,"_rational wanted ARRAY, got %s",ctype)
end
if #value ~= 2 then
throw(pos,"_rational: wanted ARRAY[2], got ARRAY[%d]",#value)
end
if math.type(value[1]) ~= 'integer' and type(value[1]) ~= 'string' then
throw(pos,"_rationa;: wanted integer or bignum for numerator, got %s",type(value[1]))
end
if math.type(value[2]) ~= 'integer' and type(value[2]) ~= 'string' then
throw(pos,"_rational: wanted integer or bignum for demoninator, got %s",type(value[2]))
end
if math.type(value[2]) == 'integer' and value[2] < 1 then
throw(pos,"_rational: wanted >1 for demoninator")
end
return value,npos,'_rational'
end,
-- =====================================================================
_uuid = function(value,sref,stref)
assert(type(value) == 'string',"_uuid: expecting a string")
assert(#value == 16,"_uuid: expecting a binary string of 16 bytes")
return cbor_c.encode(0xC0,37) .. TYPE.BIN(value,sref,stref)
end,
[37] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype == 'BIN' then
if #value ~= 16 then
throw(pos,"_uuid: invalid data for UUID")
end
return value,npos,'_uuid'
else
throw(pos,"_uuid: wanted BIN, got %s",ctype)
end
end,
-- =====================================================================
_language = function(value,sref,stref)
assert(type(value) == 'table',"_language: expecting a table")
assert(#value == 2,"_language: expecting a table of two values")
assert(type(value[1]) == 'string',"_language: expeting a string")
assert(type(value[2]) == 'string',"_language: expeting a string")
return cbor_c.encode(0xC0,38) .. TYPE.ARRAY(value,sref,stref)
end,
[38] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype ~= 'ARRAY' then
throw(pos,"_language: wanted ARRAY, got %s",ctype)
end
if #value ~= 2 then
throw(pos,"_language: wanted ARRAY(2), got ARRAY(%d)",#value)
end
if type(value[1]) ~= 'string' then
throw(pos,"_langauge: wanted TEXT for language specifier")
end
if type(value[2]) ~= 'string' then
throw(pos,"_language: wanted TEXT for text");
end
return value,npos,'_language'
end,
-- =====================================================================
_id = function(value,sref,stref)
return cbor_c.encode(0xC0,39) .. encode(value,sref,stref)
end,
[39] = function(packet,pos,conv,ref)
local value,npos = decode(packet,pos,conv,ref)
return value,npos,'_id'
end,
-- =====================================================================
-- _stringref is like _magic_cbor, it stands for itself and just
-- indicates that we're using string references for the next object.
-- I'm doing this because this also have to interact with _sharedref.
-- =====================================================================
_stringref = function(_,_,stref)
stref.SEEN = true
return cbor_c.encode(0xC0,256)
end,
[256] = function(packet,pos,conv,ref)
local prev = ref._stringref
ref._stringref = {}
local value,npos,ctype = decode(packet,pos,conv,ref)
ref._stringref = prev
return value,npos,ctype
end,
-- =====================================================================
_bmime = function(value,sref,stref)
return cbor_c.encode(0xC0,257) .. TYPE.BIN(value,sref,stref)
end,
[257] = function(packet,pos,conv,ref)
local value,npos = decode(packet,pos,conv,ref)
return value,npos,'_bmime'
end,
-- =====================================================================
_ipaddress = function(value,sref,stref)
assert(type(value) == 'string',"_ipaddress expects a string")
assert(#value == 4 or #value == 16 or #value == 6,"_ipaddress wrong length")
return cbor_c.encode(0xC0,260) .. TYPE.BIN(value,sref,stref)
end,
[260] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype ~= 'BIN' then
throw(pos,"_ipaddress: wanted BIN, got %s",ctype)
end
if #value ~= 4 and #value ~= 16 and #value ~= 6 then
throw(pos,"_ipaddress: wrong size address: %d",#value)
end
return value,npos,'_ipaddress'
end,
-- =====================================================================
_decimalfractionexp = function(value,sref,stref)
assert(type(value) == 'table',"__decimalfractionexp expects an array")
assert(#value == 2,"_decimalfractionexp expects a two item array")
assert(type(value[1]) == 'string' or math.type(value[1]) == 'integer')
assert(math.type(value[2]) == 'integer')
return cbor_c.encode(0xC0,264) .. TYPE.ARRAY(value,sref,stref)
end,
[264] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype ~= 'ARRAY' then
throw(pos,"_decimalfractionexp: wanted ARRAY, got %s",ctype)
end
if #value ~= 2 then
throw(pos,"_decimalfractionexp: wanted ARRAY(2), got ARRAY(%d)",#value)
end
if type(value[1]) ~= 'string' and math.type(value[1]) ~= 'integer' then
throw(pos,"_decimalfractionexp: wanted integer or bignum for exp, got %s",type(value))
end
if math.type(value[2]) ~= 'integer' then
throw(pos,"_decimalfractionexp: wanted integer or mantissa, got %s",type(value))
end
return value,npos,'_decimalfractionexp'
end,
-- =====================================================================
_bigfloatexp = function(value,sref,stref)
assert(type(value) == 'table',"__bigfloatexp expects an array")
assert(#value == 2,"_bigfloatexp expects a two item array")
assert(type(value[1]) == 'string' or math.type(value[1]) == 'integer')
assert(math.type(value[2]) == 'integer')
return cbor_c.encode(0xC0,265) .. TYPE.ARRAY(value,sref,stref)
end,
[265] = function(packet,pos,conv,ref)
local value,npos,ctype = decode(packet,pos,conv,ref)
if ctype ~= 'ARRAY' then
throw(pos,"_bigfloatexp: wanted ARRAY, got %s",ctype)
end
if #value ~= 2 then
throw(pos,"_bigfloatexp: wanted ARRAY(2), got ARRAY(%d)",#value)
end
if type(value[1]) ~= 'string' and math.type(value[1]) ~= 'integer' then
throw(pos,"_bigfloatexp: wanted integer or bignum for exp, got %s",type(value))
end
if math.type(value[2]) ~= 'integer' then
throw(pos,"_bigfloatexp: wanted integer or mantissa, got %s",type(value))
end
return value,npos,'_bigfloatexp'
end,
-- =====================================================================
_indirection = function(value,sref,stref)
return cbor_c.encode(0xC0,22098) .. encode(value,sref,stref)
end,
[22098] = function(packet,pos,conv,ref)
local value,npos = decode(packet,pos,conv,ref)
return value,npos,'_indirection'
end,
-- =====================================================================
_rains = function(value,sref,stref)
return cbor_c.encode(0xC0,15309736) .. TYPE.MAP(value,sref,stref)
end,
[15309736] = function(packet,pos,conv,ref)
local value,npos = decode(packet,pos,conv,ref)
return value,npos,'_rains'
end,
},
{
__index = function(_,key)
if type(key) == 'number' then
return function(packet,pos,conv,ref)
local value,npos = decode(packet,pos,conv,ref)
return value,npos,string.format('TAG_%d',key)
end
elseif type(key) == 'string' then
return function(value)
return cbor_c.encode(0xC0,tonumber(key)) .. encode(value)
end
end
end
}
)
-- ***********************************************************************
--
-- CBOR SIMPLE data types
--
-- Encoding and decoding of CBOR simple types are here.
--
-- Usage: blob = cbor.SIMPLE['name'](n)
-- Desc: Encode a CBOR simple type
-- Input: n (number/optional) floating point number to encode (see notes)
-- Return: blob (binary) CBOR encoded simple type
--
-- Note: Some functions ignore the passed in parameter.
--
-- WARNING! The functions that do not ignore the parameter may
-- throw an error if floating point precision will be lost
-- during the encoding. Please be aware of what you are doing
-- when calling SIMPLE.half(), SIMPLE.float() or
-- SIMPLE.double().
--
-- Usage: value2,pos,ctype = cbor.SIMPLE[n](pos,value)
-- Desc: Decode a CBOR simple type
-- Input: pos (integer) byte offset in packet
-- value (number/optional) floating point number
-- Return: value2 (any) decoded value as Lua value
-- pos (integer) original pos passed in (see notes)
-- ctype (enum/cbor) CBOR type of value
--
-- Note: The pos parameter is passed in to avoid special cases in
-- the code and to conform to all other decoding routines.
--
-- ***********************************************************************
SIMPLE = setmetatable(
{
[20] = function(pos) return false,pos,'false' end,
[21] = function(pos) return true ,pos,'true' end,
[22] = function(pos) return nil ,pos,'null' end,
[23] = function(pos) return nil ,pos,'undefined' end,
[25] = function(pos,value) return value,pos,'half' end,
[26] = function(pos,value) return value,pos,'single' end,
[27] = function(pos,value) return value,pos,'double' end,
[31] = function(pos) return false,pos,'__break' end,
['false'] = function() return "\244" end,
['true'] = function() return "\245" end,
null = function() return "\246" end,
undefined = function() return "\247" end,
half = function(h) return cbor_c.encode(0xE0,25,h) end,
single = function(s) return cbor_c.encode(0xE0,26,s) end,
double = function(d) return cbor_c.encode(0xE0,27,d) end,
__break = function() return "\255" end,
},
{
__index = function(_,key)
if type(key) == 'number' then
return function(pos,value)
return value,pos,'SIMPLE'
end
elseif type(key) == 'string' then
return function()
return cbor_c.encode(0xE0,tonumber(key))
end
end
end
}
)
-- ***********************************************************************
-- Usage: value,pos2,ctype = cbor.decode(packet[,pos][,conv][,ref][,iskey])
-- Desc: Decode CBOR encoded data
-- Input: packet (binary) CBOR binary blob
-- pos (integer/optional) starting point for decoding
-- conv (table/optional) table of conversion routines
-- ref (table/optional) reference table (see notes)
-- iskey (boolean/optional) is a key in a MAP (see notes)
-- Return: value (any) the decoded CBOR data
-- pos2 (integer) offset past decoded data
-- ctype (enum/cbor) CBOR type of value
--
-- Note: The conversion table should be constructed as:
--
-- {
-- UINT = function(v) return munge(v) end,
-- _datetime = function(v) return munge(v) end,
-- _url = function(v) return munge(v) end,,
-- }
--
-- The keys are CBOR types (listed above). These functions are
-- expected to convert the decoded CBOR type into a more
-- appropriate type for your code. For instance, an _epoch can
-- be converted into a table.
--
-- Users of this function *should not* pass a reference table
-- into this routine---this is used internally to handle
-- references. You need to know what you are doing to use this
-- parameter. You have been warned.
--
-- The iskey is true if the value is being used as a key in a
-- map, and is passed to the conversion routine; this too,
-- is an internal use only variable and you need to know what
-- you are doing to use this. You have been warned.
--
-- This function can throw an error. The returned error object
-- MAY BE a table, in which case it has the format:
--
-- {
-- msg = "Error text",
-- pos = 13 -- position in binary object of error
-- }
--
-- ***********************************************************************
function decode(packet,pos,conv,ref,iskey)
pos = pos or 1
conv = conv or {}
ref = ref or { _stringref = {} , _sharedref = {} }
local ctype,info,value,npos = cbor_c.decode(packet,pos)
local value2,npos2,ctype2 = TYPE[ctype](packet,npos,info,value,conv,ref)
if conv[ctype2] then
value2 = conv[ctype2](value2,iskey)
end
return value2,npos2,ctype2
end
-- ***********************************************************************
-- Usage: value,pos2,ctype[,err] = cbor.pdecode(packet[,pos][,conv][,ref])
-- Desc: Protected call to cbor.decode(), which will return an error
-- Input: packet (binary) CBOR binary blob
-- pos (integer/optional) starting point for decoding
-- conv (table/optional) table of conversion routines (see cbor.decode())
-- ref (table/optional) reference table (see cbor.decode())
-- Return: value (any) the decoded CBOR data, nil on error
-- pos2 (integer) offset past decoded data; if error, position of error
-- ctype (enum/cbor) CBOR type
-- err (string/optional) error message (if any)
-- ***********************************************************************
function pdecode(packet,pos,conv,ref)
local okay,value,npos,ctype = pcall(decode,packet,pos,conv,ref)
if okay then
return value,npos,ctype
else
return nil,value.pos,'__error',value.msg
end
end
-- ***********************************************************************
local function generic(value,sref,stref)
local mt = getmetatable(value)
if not mt then
if type(value) == 'table' then
if #value > 0 then
return TYPE.ARRAY(value,sref,stref)
else
return TYPE.MAP(value,sref,stref)
end
else
error(string.format("Cannot encode %s",type(value)))
end
end
if mt.__tocbor then
return mt.__tocbor(value,sref,stref)
elseif mt.__len then
return TYPE.ARRAY(value,sref,stref)
elseif LUA_VERSION >= "Lua 5.2" and mt.__ipairs then
return TYPE.ARRAY(value,sref,stref)
elseif LUA_VERSION >= "Lua 5.3" and mt.__pairs then
return TYPE.MAP(value,sref,stref)
else
error(string.format("Cannot encode %s",type(value)))
end
end
-- ***********************************************************************
--
-- __ENCODE_MAP
--
-- A table of functions to map Lua values to CBOR encoded values. nil,
-- boolean, number and string are handled directly (if a Lua string is valid
-- UTF8, then it's encoded as a CBOR TEXT.
--
-- For the other four types, only tables are directly supported without
-- metatable support. If a metatable does exist, if the method '__tocbor'
-- is defined, that function is called and the results returned. If '__len'
-- is defined, then it is mapped as a CBOR ARRAY. For Lua 5.2, if
-- '__ipairs' is defined, then it too, is mapped as a CBOR ARRAY. If Lua
-- 5.2 or higher and '__pairs' is defined, then it's mapped as a CBOR MAP.
--
-- Otherwise, an error is thrown.
--
-- Usage: blob = cbor.__ENCODE_MAP[luatype](value,sref,stref)
-- Desc: Encode a Lua type into a CBOR type
-- Input: value (any) a Lua value who's type matches luatype.
-- sref (table/optional) shared reference table
-- stref (table/optional) shared string reference table
-- Return: blob (binary) CBOR encoded data
--
-- ***********************************************************************
__ENCODE_MAP =
{
['nil'] = SIMPLE.null,
['boolean'] = function(b)
if b then
return SIMPLE['true']()
else
return SIMPLE['false']()
end
end,
['number'] = function(value)
if math.type(value) == 'integer' then
if value < 0 then
return TYPE.NINT(value)
else
return TYPE.UINT(value)
end
else
return cbor_c.encode(0xE0,nil,value)
end
end,
['string'] = function(value,sref,stref)
if UTF8:match(value) > #value then
return TYPE.TEXT(value,sref,stref)
else
return TYPE.BIN(value,sref,stref)
end
end,
['table'] = generic,
['function'] = generic,
['userdata'] = generic,
['thread'] = generic,
}
-- ***********************************************************************
-- Usage: blob = cbor.encode(value[,sref][,stref])
-- Desc: Encode a Lua type into a CBOR type
-- Input: value (any)
-- sref (table/optional) shared reference table
-- stref (table/optional) shared string reference table
-- Return: blob (binary) CBOR encoded value
-- ***********************************************************************
function encode(value,sref,stref)
local res = ""
if stref and not stref.SEEN then
res = TAG._stringref(nil,nil,stref)
end
return res .. __ENCODE_MAP[type(value)](value,sref,stref)
end
-- ***********************************************************************
-- Usage: blob[,err] = cbor.pencode(value[,sref][,stref])
-- Desc: Protected call to encode a CBOR type
-- Input: value (any)
-- sref (table/optional) shared reference table
-- stref (table/optional) shared string reference table
-- Return: blob (binary) CBOR encoded value, nil on error
-- err (string/optional) error message
-- ***********************************************************************
function pencode(value,sref,stref)
local okay,value2 = pcall(encode,value,sref,stref)
if okay then
return value2
else
return nil,value2
end
end
-- ***********************************************************************
if LUA_VERSION >= "Lua 5.2" then
return _ENV
end
|
--
-- Created by IntelliJ IDEA.
-- User: Noneatme
-- Date: 23.12.2014
-- Time: 13:36
-- Project: MTA iLife
--
CObject = inherit(CElement)
registerElementClass("object", CObject)
function CObject:constructor()
end
function CObject:destructor()
end
function CObject:setMass(...)
return setObjectMass(self, ...)
end |
love.graphics.setBackgroundColor(0.1, 0.1, 0.1)
love.graphics.setDefaultFilter("nearest", "nearest")
require("lib.steady")
score = 0
local W = require("src.worlds")
currentWorld = W.intro
music = love.audio.newSource("music/main.ogg", "static")
music:setLooping(true)
music:setVolume(0.08)
function love.load()
currentWorld:emit("load")
end
function love.update(dt)
currentWorld:emit("update", dt)
end
function love.fixedUpdate(dt) -- luacheck: ignore
currentWorld:emit("fixedUpdate", dt)
end
function love.draw()
currentWorld:emit("draw")
end
function love.wheelmoved(x, y)
currentWorld:emit("wheelmoved", x, y)
end
function love.keypressed(key)
currentWorld:emit("keypressed", key)
end
|
local contrail = Material( "snowysnowtime/contrails/needler_contrail" )
function EFFECT:Init( data )
self.Position = data:GetStart()
self.EndPos = data:GetOrigin()
self.WeaponEnt = data:GetEntity()
self.Attachment = data:GetAttachment()
self.StartPos = self:GetTracerShootPos( self.Position, self.WeaponEnt, self.Attachment )
self:SetRenderBoundsWS( self.StartPos, self.EndPos )
self.Dir = ( self.EndPos - self.StartPos ):GetNormalized()
self.Dist = self.StartPos:Distance( self.EndPos )
self.LifeTime = 0.2 - ( 1 / self.Dist )
self.DieTime = CurTime() + self.LifeTime
end
function EFFECT:Think()
if ( CurTime() > self.DieTime ) then return false end
return true
end
function EFFECT:Render()
local v1 = ( CurTime() - self.DieTime ) / self.LifeTime
local v2 = ( self.DieTime - CurTime() ) / self.LifeTime
local a = self.EndPos - self.Dir * math.min( 1 - ( v1 * self.Dist ), self.Dist )
render.SetMaterial( contrail )
render.DrawBeam( a, self.EndPos, v2 * 6, 0, self.Dist / 10, Color( 255, 255, 255, v2 * 255 ) )
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.