content
stringlengths 5
1.05M
|
|---|
-- A global variable for the App Mode
appMode = hs.hotkey.modal.new()
appModeStatusMessage = message.new('App Mode')
appModeBlocked = false
function enterAppMode()
if (appModeBlocked) then
return
end
appModeStatusMessage:show()
appMode:enter()
end
function exitAppMode()
appModeStatusMessage:hide()
appMode:exit()
end
appMode:bind({}, 'space', exitAppMode)
-- Open 1Password Quick Search
appMode:bind({}, 'p', function()
keyUpDown({ 'cmd', 'alt' }, '\\')
end)
-- Select tmux windows using number keys
-- These bindings must be matched by bindings in tmux.conf, i.e.
-- bind-key -n F1 select-window -t 1
for i=1,8 do
appMode:bind({}, tostring(i), function()
keyUpDown({}, 'F' .. i)
end)
end
-- Bind the right cmd key
f16 = hs.hotkey.bind({}, 'F16', enterAppMode, exitAppMode)
-- Swedish bindings
-- 33 = [ = å
-- 41 = ; = ö
-- 39 = ' = ä
local keysToMirror = {
33,
41,
39
}
local modifiersToEnable = {
'',
'shift'
}
hs.fnutils.each(keysToMirror, function(k)
local swedishMap = "Swedish - Pro"
local usMap = "U.S."
local delay = 0.008
hs.fnutils.each(modifiersToEnable, function(m)
appMode:bind(m, k, function()
exitAppMode()
appModeBlocked = true
hs.timer.doAfter(0*delay, function()
hs.keycodes.setLayout(swedishMap)
end)
hs.timer.doAfter(1*delay, function()
keyUpDown(m, k)
appModeBlocked = false
end)
hs.timer.doAfter(2*delay, function()
hs.keycodes.setLayout(usMap)
enterAppMode()
end)
end)
end)
end)
-- Non-app bindings
-- vim movement:
local charactersToKeystrokes = {
{
from = 'h',
to = 'left',
},
{
from = 'j',
to = 'down',
},
{
from = 'k',
to = 'up',
},
{
from = 'l',
to = 'right',
},
}
hs.fnutils.each(charactersToKeystrokes, function(m)
appMode:bind({}, m['from'], function()
keyUpDown({}, m['to'])
end)
end)
-- Toggle fullscreen
appMode:bind({}, 'return', function()
local win = hs.window.frontmostWindow()
win:setFullscreen(not win:isFullscreen())
end)
-- Apps
local status, appModeMappings = pcall(require, 'modules.app-mode.app-mappings')
for i, mapping in ipairs(appModeMappings) do
local key = mapping[1]
local app = mapping[2]
appMode:bind({}, key, function()
if (type(app) == 'string') then
hs.application.open(app)
exitAppMode()
else
hs.logger.new('apps'):e('Invalid mapping for App Mode +', key)
end
end)
end
|
local path = minetest.get_modpath("mobs")
-- Mob API
dofile(path.."/api.lua")
-- Mob Items
dofile(path.."/crafts.lua")
|
--[[--
A module that maps between Lua and XML without much ado.
LuaXML provides a set of functions for processing XML data in Lua.
It offers a very simple and natural mapping between the XML format and Lua tables,
which allows one to work with and construct XML data just using Lua's normal
table access and iteration methods (e.g. `ipairs()`).
Substatements and tag content are represented as array data having numerical
keys (`1 .. n`), attributes use string keys, and tags the numerical index `0`.
This representation makes sure that the structure of XML data is preserved
exactly across read/write cycles (i.e. `xml.eval(var:str())` should equal `var`
again).
---
<br>To use LuaXML, first import the module - for example like this:
local xml = require("LuaXML")
LuaXML consists of a Lua file (`LuaXML.lua`) and a corresponding C module
(`LuaXML_lib`) - normally a shared library (`.dll`/`.so`), although a static
linking is possible as well. Both parts are imported by this call, provided
that they are found in Lua's package search path.
@module LuaXML
]]
local _M = require("LuaXML_lib")
--[[-- saves a Lua var as XML file.
Basically this simply exports the string representation `xml.str(var)`
(or `var:str()`), plus a standard header.
@function save
@param var the variable to be saved, normally a table
@tparam string filename the filename to be used. An existing file of the same name gets overwritten.
@tparam ?string filemode the file mode to pass to `io.open`, defaults to "w"
@tparam ?string cmt
custom _comment_ to be written at the top of the file (after the header). You
may pass an empty string if you don't want any comment at all, otherwise it
should preferably end with at least one newline. Defaults to:
<!-- file «filename», generated by LuaXML -->\n\n
@tparam ?string hdr
custom _header_, written before anything else. You may pass an empty string if
you don't want any header at all, otherwise it should preferably end with a
newline. Defaults to the standard XML 1.0 declaration:
<?xml version="1.0"?>\n
@usage
var:save("simple.xml")
var:save("no-comment.xml", nil, "")
var:save("custom.xml", "a+", "<!-- append mode, no header -->\n", "")
]]
function _M.save(var, filename, filemode, comment, header)
if var and filename and #filename > 0 then
local file, err = io.open(filename, filemode or "w")
if not file then
error('error opening "' .. filename .. '" for saving: ' .. err)
end
file:write(header or '<?xml version="1.0"?>\n')
file:write(comment or
'<!-- file "' .. filename .. '", generated by LuaXML -->\n\n')
file:write(_M.str(var))
file:close()
end
end
--[[-- iterate subelements ("XML children") as _key - value_ pairs.
This function is meant to be called in a generic `for` loop, similar to what
`ipairs(var)` would do. However you can easily specify additional criteria
to `match` against here, possibly reducing the overhead needed to test for
specific subelements.
For the resulting `(k, v)` pairs, note that `k` is just a sequential number
in the array of matched child elements, and has no direct relation to the
actual "position" (subtag index) within each `v`'s parent object.
@function children
@param var the table (LuaXML object) to work on
@tparam ?string tag XML tag to be matched
@tparam ?string key attribute key to be matched
@param value (optional) attribute value to be matched
@tparam ?number maxdepth
maximum depth allowed, defaults to 1 (only immediate children).
You can pass 0 or `true` to iterate _all_ children recursively.
@return Lua iterator function and initial state (Lua-internal use) - suitable
for a `for` loop
@see match
@usage
local xml = require("LuaXML")
local foobar = xml.eval('<foo><a /><b bar="no" /><c bar="yes" /><a /></foo>')
-- iterate over those children that have a "bar" attribute:
for k, v in foobar:children(nil, "bar") do
print(k, v:tag(), v.bar)
end
-- will print
-- 1 b no
-- 2 c yes
-- require "bar" to be "yes":
for k, v in foobar:children(nil, "bar", "yes") do
print(k, v:tag(), v.bar)
end
-- will print
-- 1 c yes
-- iterate "a" tags: (the first and fourth child will match)
for k, v in foobar:children("a") do
print(k, v:tag(), v.bar)
end
-- will print
-- 1 a nil
-- 2 a nil
]]
function _M.children(var, tag, key, value, maxdepth)
local function get_children(var, tag, key, value, maxdepth)
-- pass maxdepth = 1 to retrieve only immediate child nodes
local result = {}
_M.iterate(var,
function(node, depth)
-- add matching node to result table
if depth > 0 then table.insert(result, node); end
end,
tag, key, value, true, maxdepth)
return result
end
local function child_iterator(matched, k)
k = (k or 0) + 1
local v = matched[k]
return v and k, v -- key/value pair from matches, or `nil` if no value
end
maxdepth = maxdepth or 1 -- default to 1...
-- ...but enumerate all children if it was set to 0 or `true`
if maxdepth == 0 or maxdepth == true then maxdepth = nil; end
-- our "invariant state" will be a table of matched children
return child_iterator,
get_children(var, tag, key, value, maxdepth)
end
return _M -- return module (table)
|
--[[
-- added by passion @ 2019/11/14 16:39:51
-- UIBoardUIMain模型层
-- 注意:
-- 1、成员变量预先在OnCreate、OnEnable函数声明,提高代码可读性
-- 2、OnCreate内放窗口生命周期内保持的成员变量,窗口销毁时才会清理
-- 3、OnEnable内放窗口打开时才需要的成员变量,窗口关闭后及时清理
-- 4、OnEnable函数每次在窗口打开时调用,可传递参数用来初始化Model
--]]
---@class UUIBoardNPCModel:UIBaseModel
local UUIBoardNPCModel = BaseClass("UUIBoardNPCModel", UIBaseModel)
--- @return UIBaseModel
local base = UIBaseModel
-- 创建
local function OnCreate(self)
base.OnCreate(self)
-- 窗口生命周期内保持的成员变量放这
end
-- 打开
local function OnEnable(self, owner, height)
base.OnEnable(self)
self.owner = owner
self.target = owner.transform
self.height = height or 1.9
end
-- 关闭
local function OnDestroy(self)
base.OnDestroy(self)
-- 清理成员变量
end
UUIBoardNPCModel.OnCreate = OnCreate
UUIBoardNPCModel.OnEnable = OnEnable
UUIBoardNPCModel.OnDisable = OnDisable
UUIBoardNPCModel.OnDestroy = OnDestroy
return UUIBoardNPCModel
|
--[[
Database Plugin -> Initialize (ServerSide)
by Tassilo (@TASSIA710)
Contains the plugin core.
--]]
-- Configuration
config.AddPlugin("Jet/Database", "Hostname", "localhost", "string", "The hostname of the database.")
config.AddPlugin("Jet/Database", "Port", 3306, "number", "The port of the database.")
config.AddPlugin("Jet/Database", "Database", "database", "string", "The database name.")
config.AddPlugin("Jet/Database", "Username", "username", "string", "The username to use for logging in.")
config.AddPlugin("Jet/Database", "Password", "password", "string", "The password to use for logging in.")
-- Load classes
include("classes/sv_database.lua")
include("classes/sv_query.lua")
include("classes/sv_prepared_statement.lua")
-- Load library
include("sv_library.lua")
-- Load MySQLOO
do
local status, err = include("driver/sv_mysqloo.lua")
if status == false then
return false, err
end
end
-- Connections
db.SetGlobal(db.Connect(
config.GetPlugin("Jet/Database", "Hostname"),
config.GetPlugin("Jet/Database", "Port"),
config.GetPlugin("Jet/Database", "Database"),
config.GetPlugin("Jet/Database", "Username"),
config.GetPlugin("Jet/Database", "Password")
))
-- Connected?
if not db.GetGlobal():IsConnected() then
return false, "Database connection could not be established."
end
|
local cmd = vim.cmd
local opt = vim.opt
-- NeoVim
cmd [[syntax on]]
cmd [[filetype plugin on]]
opt.number = true
opt.relativenumber = true
opt.termguicolors = true
opt.splitbelow = true
opt.splitright = true
opt.scrolloff = 1
opt.sidescrolloff = 5
opt.inccommand = 'nosplit'
opt.colorcolumn = "79"
-- Vim settings
opt.completeopt = 'menuone,noselect'
-- Indentation
opt.autoindent = true
-- Cursorline and cursorcolumn
cmd [[au WinLeave * set nocursorline nocursorcolumn]]
cmd [[au BufEnter,WinEnter * set cursorline cursorcolumn]]
-- Color scheme
-- g.gruvbox_contrast_dark = "medium"
-- cmd [[autocmd ColorScheme * highlight Visual cterm=reverse]]
-- cmd [[colorscheme gruvbox]]
require('onedark').setup()
|
Width = 34
ActiveColour = nil
local pickerColours = {
colours.brown,
colours.yellow,
colours.orange,
colours.red,
colours.green,
colours.lime,
colours.magenta,
colours.pink,
colours.purple,
colours.blue,
colours.cyan,
colours.lightBlue,
colours.lightGrey,
colours.grey,
colours.black,
colours.white
}
OnDraw = function(self, x, y)
local _x = 0
for i, col in ipairs(pickerColours) do
local w = 2
if col == self.ActiveColour then
w = 4
end
if col == colours.white then
Drawing.DrawCharacters(x + _x, y, ('#'):rep(w), colours.lightGrey, col)
else
Drawing.DrawBlankArea(x + _x, y, w, self.Height, col)
end
_x = _x + w
end
end
OnUpdate = function(self, value)
if value == 'ActiveColour' then
if self.OnChange then
self:OnChange(self.ActiveColour)
end
end
end
OnClick = function(self, event, side, x, y)
local _x = 0
for i, col in ipairs(pickerColours) do
local w = 2
if col == self.ActiveColour then
w = 4
end
if x >= _x + 1 and x <= _x + w + 1 then
self.ActiveColour = col
end
_x = _x + w
end
end
OnDrag = OnClick
|
local function getScope(data, name, scope)
if data[name] == nil then
data[name] = {}
end
if data[name][scope] == nil then
data[name][scope] = {}
end
return data[name][scope]
end
local function create()
local data = {}
return {
get = function(name, scope)
return getScope(data, name, scope)
end,
set = function(name, scope, key, value)
getScope(data, name, scope)[key] = value
end,
}
end
local function createDefault()
local data = {}
return {
get = function()
return data
end,
set = function(key, value)
data[key] = value
end,
}
end
return {
Default = createDefault(),
Global = create(),
Ordered = create(),
}
|
-- Topper McNabb
TOPPERMCNABB = {}
function TOPPERMCNABB_onDied(Unit, event, player)
Unit:RemoveEvents()
end
function TOPPERMCNABB_onSpawn(Unit, event, player)
Unit:RegisterEvent("TOPPERMCNABB_Say",30000, 0)
end
function TOPPERMCNABB_Say(Unit, event, player)
local chance = math.random(1,6)
if(chance == 1) then
Unit:SendChatMessage(12, 7, "Spare some change for a poor blind man? ...What do you mean I'm not blind? ...I'M NOT BLIND! I CAN SEE! It's a miracle!" )
end
if(chance == 2) then
Unit:SendChatMessage(12, 7, "I will gladly pay you Tuesday for a hamburger today.")
end
if(chance == 3) then
Unit:SendChatMessage(12, 7, "Alms for the poor?")
end
if(chance == 4) then
Unit:SendChatMessage(12, 7, "Shine yer armor for a copper.")
end
if(chance == 5) then
Unit:SendChatMessage(12, 7, "It's all their fault, stupid Alliance army. Just had to build their towers right behind my farm.")
end
if(chance == 6) then
Unit:SendChatMessage(12, 7, "Help a poor bloke out?")
end
end
RegisterUnitEvent(1402, 18, "TOPPERMCNABB_onSpawn")
RegisterUnitEvent(1402, 4, "TOPPERMCNABB_onDied")
|
local vim = vim
local M = {}
M.defaults = {
highlight_hovered_item = true,
show_guides = true,
position = 'right',
width = 25,
auto_preview = true,
show_numbers = false,
show_relative_numbers = false,
show_symbol_details = true,
keymaps = { -- These keymaps can be a string or a table for multiple keys
close = {"<Esc>", "q"},
goto_location = "<Cr>",
focus_location = "o",
hover_symbol = "<C-space>",
toggle_preview = "K",
rename_symbol = "r",
code_actions = "a",
show_help = "?"
},
lsp_blacklist = {},
symbol_blacklist = {},
symbols = {
File = {icon = "", hl = "TSURI"},
Module = {icon = "", hl = "TSNamespace"},
Namespace = {icon = "", hl = "TSNamespace"},
Package = {icon = "", hl = "TSNamespace"},
Class = {icon = "𝓒", hl = "TSType"},
Method = {icon = "ƒ", hl = "TSMethod"},
Property = {icon = "", hl = "TSMethod"},
Field = {icon = "", hl = "TSField"},
Constructor = {icon = "", hl = "TSConstructor"},
Enum = {icon = "ℰ", hl = "TSType"},
Interface = {icon = "ﰮ", hl = "TSType"},
Function = {icon = "", hl = "TSFunction"},
Variable = {icon = "", hl = "TSConstant"},
Constant = {icon = "", hl = "TSConstant"},
String = {icon = "𝓐", hl = "TSString"},
Number = {icon = "#", hl = "TSNumber"},
Boolean = {icon = "⊨", hl = "TSBoolean"},
Array = {icon = "", hl = "TSConstant"},
Object = {icon = "⦿", hl = "TSType"},
Key = {icon = "🔐", hl = "TSType"},
Null = {icon = "NULL", hl = "TSType"},
EnumMember = {icon = "", hl = "TSField"},
Struct = {icon = "𝓢", hl = "TSType"},
Event = {icon = "🗲", hl = "TSType"},
Operator = {icon = "+", hl = "TSOperator"},
TypeParameter = {icon = "𝙏", hl = "TSParameter"}
}
}
M.options = {}
function M.has_numbers()
return M.options.show_numbers or M.options.show_relative_numbers
end
function M.get_position_navigation_direction()
if M.options.position == 'left' then
return 'h'
else
return 'l'
end
end
function M.get_width_percentage() return M.options.width / 100 end
function M.get_split_command()
if M.options.position == 'left' then
return "topleft vs"
else
return "botright vs"
end
end
local function has_value(tab, val)
for _, value in ipairs(tab) do if value == val then return true end end
return false
end
function M.is_symbol_blacklisted(kind)
if kind == nil then return false end
return has_value(M.options.symbol_blacklist, kind)
end
function M.is_client_blacklisted(client_id)
local client = vim.lsp.get_client_by_id(client_id)
if not client then return false end
return has_value(M.options.lsp_blacklist, client.name)
end
function M.show_help()
print "Current keymaps:"
print(vim.inspect(M.options.keymaps))
end
function M.setup(options)
vim.g.symbols_outline_loaded = 1
M.options = vim.tbl_deep_extend("force", {}, M.defaults, options or {})
end
return M
|
-----------------------------------------------------
--name : lib/crunch/10_index_unifier.lua
--description: crunch module, converts '.name'/{'name'} to '["name"]' as an intermediate step to '[x]'
--author : mpmxyz
--github page: https://github.com/mpmxyz/ocprograms
--forum page : none
-----------------------------------------------------
return {
run = function(context, options)
--This code only works if you know how the code is structured.
if options.tree then
context.verbose("Index expansion...")
local processor
processor = {
var = function(token)
--var = [[name | prefixexp '[' exp ']' | prefixexp '.' name ]]
--exp = [[value | etc.]] with transparent replacement value = [[string | etc.]]
local first = token[1]
if first.typ == "prefixexp" then
local second = token[2]
if second == "." then
local name = token[3][1]
token[2] = "["
token[3] = {
typ = "exp",
{
typ = "string",
'"',
name,
'"',
}
}
token[4] = "]"
context.traverseTree(token, processor)
end
end
end,
field = function(token)
--field = [['[' exp ']' '=' exp | name '=' exp | exp ]]
local first = token[1]
if first.typ == "name" then
--get old content
local name = first[1]
local exp = token[3]
--create new content
token[1] = "["
token[2] = {
typ = "exp",
{
typ = "string",
'"',
name,
'"',
},
}
token[3] = "]"
token[4] = "="
token[5] = exp
end
context.traverseTree(token, processor)
end,
args = function(token)
--args = [['(' [explist] ')' | tableconstructor | string ]]
--explist = [[exp {',' exp} ]]
local first = token[1]
if first.typ == "string" then
--single string argument; adding paranthesis for unification
token[1] = "("
token[2] = {
typ = "explist",
{
typ = "exp",
first,
},
}
token[3] = ")"
end
context.traverseTree(token, processor)
end,
default = function(token)
return context.traverseTree(token, processor)
end,
}
context.traverseTree(context.tokens, processor)
end
end,
}
|
ITEM.name = "AK-103"
ITEM.description = "The AK-103 assault rifle is a derivative of the AK-74M chambered for the 7.62×39mm M43 round, similar to the older AKM. The AK-103 can be fitted with a variety of sights, including night vision and telescopic sights, plus a knife-bayonet or a grenade launcher. It uses plastic components where possible instead of wood or metal, with such components being the pistol grip, handguards and stock."
ITEM.model = "models/weapons/ethereal/w_f_ak103.mdl"
ITEM.class = "cw_kk_ins2_ak103"
ITEM.weaponCategory = "primary"
ITEM.width = 3
ITEM.height = 2
ITEM.price = 32000
ITEM.weight = 7
|
TagRules = function ()
local rules =
{
accelerations =
{
1200, -- SMILEY_STATE_SMILEY
1200, -- SMILEY_STATE_SHIELD
1200, -- SMILEY_STATE_PIRATE
0 -- SMILEY_STATE_SLEEPY
},
maxSpeeds =
{
600, -- SMILEY_STATE_SMILEY
600, -- SMILEY_STATE_SHIELD
600, -- SMILEY_STATE_PIRATE
0 -- SMILEY_STATE_SLEEPY
},
timeouts =
{
nil, -- SMILEY_STATE_SMILEY
1.5, -- SMILEY_STATE_SHIELD
nil, -- SMILEY_STATE_PIRATE
1.0 -- SMILEY_STATE_SLEEPY
},
statesAfterTimeout =
{
SMILEY_STATE_SMILEY, -- SMILEY_STATE_SMILEY
SMILEY_STATE_SMILEY, -- SMILEY_STATE_SHIELD
SMILEY_STATE_PIRATE, -- SMILEY_STATE_PIRATE
SMILEY_STATE_PIRATE -- SMILEY_STATE_SLEEPY
},
preferences =
{
-- SMILEY_STATE_SMILEY
{
-1, --SMILEY_STATE_SMILEY
-1, --SMILEY_STATE_SHIELD
-3, --SMILEY_STATE_PIRATE
-2 --SMILEY_STATE_SLEEPY
},
-- SMILEY_STATE_SHIELD
{
-1, --SMILEY_STATE_SMILEY
-1, --SMILEY_STATE_SHIELD
-3, --SMILEY_STATE_PIRATE
-2 --SMILEY_STATE_SLEEPY
},
-- SMILEY_STATE_PIRATE
{
2, --SMILEY_STATE_SMILEY
0, --SMILEY_STATE_SHIELD
-1, --SMILEY_STATE_PIRATE
0 --SMILEY_STATE_SLEEPY
},
-- SMILEY_STATE_SLEEPY
{
0, --SMILEY_STATE_SMILEY
0, --SMILEY_STATE_SHIELD
0, --SMILEY_STATE_PIRATE
0 --SMILEY_STATE_SLEEPY
},
},
cornerHatred =
{
2, -- SMILEY_STATE_SMILEY
2, -- SMILEY_STATE_SHIELD
0, -- SMILEY_STATE_PIRATE
0 -- SMILEY_STATE_SLEEPY
},
smileyStatesAfterCollision = function (self, smiley1, smiley2)
if smiley1._state == SMILEY_STATE_PIRATE and
smiley2._state == SMILEY_STATE_SMILEY then
return SMILEY_STATE_SHIELD, SMILEY_STATE_SLEEPY
elseif smiley1._state == SMILEY_STATE_SMILEY and
smiley2._state == SMILEY_STATE_PIRATE then
return SMILEY_STATE_SLEEPY, SMILEY_STATE_SHIELD
else
return smiley1._state, smiley2._state
end
end,
winner = function (self, allSmileys, numSmileys)
return nil
end
}
return rules
end
ruleSets["Normal"] = TagRules
|
--[[
Kill Confirmed (Semi-Permissive)
PvE Ground Branch game mode by Bob/AT
2022-05-08
https://github.com/JakBaranowski/ground-branch-game-modes/issues/26
Notes for Mission Editing:
1. Start with a regular 'Kill Confirmed' mission
2. Add non-combatants
- use team id = 10
- one of the unarmed 'Civ*' kits)
]]--
local Tables = require("Common.Tables")
local AvoidFatality = require("Objectives.AvoidFatality")
local NoSoftFail = require("Objectives.NoSoftFail")
-- Create a deep copy of the singleton
local super = Tables.DeepCopy(require("KillConfirmed"))
-- Use a separate loadout
super.PlayerTeams.BluFor.Loadout='NoTeamCamouflage'
super.Settings.RespawnCost.Value = 100000
-- Add new score types
super.PlayerScoreTypes.CollateralDamage = {
Score = -250,
OneOff = false,
Description = 'Killed a non-combatant'
}
super.TeamScoreTypes.CollateralDamage = {
Score = -250,
OneOff = false,
Description = 'Killed a non-combatant'
}
-- Add additional objectives
super.Objectives.AvoidFatality = AvoidFatality.new('NoCollateralDamage')
super.Objectives.NoSoftFail = NoSoftFail.new()
-- Our sub-class of the singleton
local Mode = setmetatable({}, { __index = super })
-- The max. amount of collateral damage before failing the mission
Mode.CollateralDamageThreshold = 3
function Mode:PostInit()
gamemode.AddGameObjective(self.PlayerTeams.BluFor.TeamId, 'NeutralizeHVTs', 1)
gamemode.AddGameObjective(self.PlayerTeams.BluFor.TeamId, 'ConfirmEliminatedHVTs', 1)
gamemode.AddGameObjective(self.PlayerTeams.BluFor.TeamId, 'NoCollateralDamage', 1)
gamemode.AddGameObjective(self.PlayerTeams.BluFor.TeamId, 'ExfiltrateBluFor', 1)
end
function Mode:OnRoundStageSet(RoundStage)
if RoundStage == 'PostRoundWait' or RoundStage == 'TimeLimitReached' then
-- Make sure the 'SOFT FAIL' message is cleared
gamemode.BroadcastGameMessage('Blank', 'Center', -1)
end
super.OnRoundStageSet(self, RoundStage)
end
function Mode:PreRoundCleanUp()
super.PreRoundCleanUp(self)
gamemode.SetTeamAttitude(1, 10, 'Neutral')
gamemode.SetTeamAttitude(10, 1, 'Neutral')
gamemode.SetTeamAttitude(10, 100, 'Friendly')
gamemode.SetTeamAttitude(100, 10, 'Friendly')
end
function Mode:OnCharacterDied(Character, CharacterController, KillerController)
local goodKill = true
if gamemode.GetRoundStage() == 'PreRoundWait' or gamemode.GetRoundStage() == 'InProgress'
then
if CharacterController ~= nil then
local killedTeam = actor.GetTeamId(CharacterController)
local killerTeam = nil
if KillerController ~= nil then
killerTeam = actor.GetTeamId(KillerController)
end
if killedTeam == 10 and killerTeam == self.PlayerTeams.BluFor.TeamId then
goodKill = false
self.Objectives.AvoidFatality:ReportFatality()
self.PlayerTeams.BluFor.Script:AwardPlayerScore(KillerController, 'CollateralDamage')
self.PlayerTeams.BluFor.Script:AwardTeamScore('CollateralDamage')
local message = 'Collateral damage by ' .. player.GetName(KillerController)
self.PlayerTeams.BluFor.Script:DisplayMessageToAllPlayers(message, 'Engine', 5.0, 'ScoreMilestone')
if self.Objectives.AvoidFatality:GetFatalityCount() >= self.CollateralDamageThreshold then
self.Objectives.NoSoftFail:Fail()
self.PlayerTeams.BluFor.Script:DisplayMessageToAlivePlayers('SoftFail', 'Upper', 10.0, 'Always')
end
end
if killedTeam == killerTeam and killerTeam == self.PlayerTeams.BluFor.TeamId then
-- Count fratricides as collateral damage
self.Objectives.AvoidFatality:ReportFatality()
end
end
end
if goodKill then
super.OnCharacterDied(self, Character, CharacterController, KillerController)
end
end
function Mode:OnExfiltrated()
if gamemode.GetRoundStage() ~= 'InProgress' then
return
end
-- Award surviving players
local alivePlayers = self.PlayerTeams.BluFor.Script:GetAlivePlayers()
for _, alivePlayer in ipairs(alivePlayers) do
self.PlayerTeams.BluFor.Script:AwardPlayerScore(alivePlayer, 'Survived')
end
-- Prepare summary
self:UpdateCompletedObjectives()
if self.Objectives.NoSoftFail:IsOK() then
gamemode.AddGameStat('Summary=HVTsConfirmed')
gamemode.AddGameStat('Result=Team1')
else
gamemode.AddGameStat('Summary=SoftFail')
gamemode.AddGameStat('Result=None')
end
gamemode.SetRoundStage('PostRoundWait')
end
return Mode
|
-- Using v1.5.0
-- This bot is going to join its tribe house and
-- spawn a different textarea (using lua) 10 times
-- and then leave the room.
local transfromage = require("transfromage")
local client = transfromage.client()
local timer = require("timer")
client:once("ready", function()
print("Ready to connect!")
client:connect("Username#0000", "password")
end)
client:once("connection", function()
print("Connected!")
client:joinTribeHouse()
end)
client:on("joinTribeHouse", function()
local uses, t = 0
t = timer.setInterval(10 * 1000, function()
uses = uses + 1
if uses == 10 then
timer.clearInterval(t)
-- Leaving the room after the 10th
timer.setTimeout(1 * 1000, function()
client:enterRoom("*#bolodefchoco")
end)
end
client:loadLua("ui.addTextArea(" .. uses .. ", '', nil, math.random(100, 700), math.random(100, 300), math.random(100, 300), math.random(100, 300), math.random(0xFFFFFF), math.random(0xFFFFFF), 1, true)")
end)
end)
client:start("PLAYER_ID", "API_TOKEN")
|
-- 公历农历转换
-- {{#Invoke:Calendar|solar_to_lunar|2020-04-23}} => 2020-04-01
-- {{#Invoke:Calendar|solar_to_lunar|2020-05-23}} => 2020-04-01L (L表示闰月)
-- {{#Invoke:Calendar|lunar_to_solar|2020-04-01}} => 2020-04-23
-- {{#Invoke:Calendar|lunar_to_solar|2020-04-01L}} => 2020-05-23
-- {{#Invoke:Calendar|lunar_format|2020-04-01}} => 二零二零年四月初一
-- {{#Invoke:Calendar|lunar_format|2020-04-01L}} => 二零二零年闰四月初一
local bit32 = require( 'bit32' )
local data = {
[1900]={solar_start=0,lunar_start=30,lunar_code=19416},
[1901]={solar_start=365,lunar_start=414,lunar_code=19168},
[1902]={solar_start=730,lunar_start=768,lunar_code=42352},
[1903]={solar_start=1095,lunar_start=1123,lunar_code=21717},
[1904]={solar_start=1460,lunar_start=1506,lunar_code=53856},
[1905]={solar_start=1826,lunar_start=1860,lunar_code=55632},
[1906]={solar_start=2191,lunar_start=2215,lunar_code=91476},
[1907]={solar_start=2556,lunar_start=2599,lunar_code=22176},
[1908]={solar_start=2921,lunar_start=2953,lunar_code=39632},
[1909]={solar_start=3287,lunar_start=3308,lunar_code=21970},
[1910]={solar_start=3652,lunar_start=3692,lunar_code=19168},
[1911]={solar_start=4017,lunar_start=4046,lunar_code=42422},
[1912]={solar_start=4382,lunar_start=4430,lunar_code=42192},
[1913]={solar_start=4748,lunar_start=4784,lunar_code=53840},
[1914]={solar_start=5113,lunar_start=5138,lunar_code=119381},
[1915]={solar_start=5478,lunar_start=5522,lunar_code=46400},
[1916]={solar_start=5843,lunar_start=5876,lunar_code=54944},
[1917]={solar_start=6209,lunar_start=6231,lunar_code=44450},
[1918]={solar_start=6574,lunar_start=6615,lunar_code=38320},
[1919]={solar_start=6939,lunar_start=6970,lunar_code=84343},
[1920]={solar_start=7304,lunar_start=7354,lunar_code=18800},
[1921]={solar_start=7670,lunar_start=7708,lunar_code=42160},
[1922]={solar_start=8035,lunar_start=8062,lunar_code=46261},
[1923]={solar_start=8400,lunar_start=8446,lunar_code=27216},
[1924]={solar_start=8765,lunar_start=8800,lunar_code=27968},
[1925]={solar_start=9131,lunar_start=9154,lunar_code=109396},
[1926]={solar_start=9496,lunar_start=9539,lunar_code=11104},
[1927]={solar_start=9861,lunar_start=9893,lunar_code=38256},
[1928]={solar_start=10226,lunar_start=10248,lunar_code=21234},
[1929]={solar_start=10592,lunar_start=10632,lunar_code=18800},
[1930]={solar_start=10957,lunar_start=10986,lunar_code=25958},
[1931]={solar_start=11322,lunar_start=11369,lunar_code=54432},
[1932]={solar_start=11687,lunar_start=11723,lunar_code=59984},
[1933]={solar_start=12053,lunar_start=12078,lunar_code=92821},
[1934]={solar_start=12418,lunar_start=12462,lunar_code=23248},
[1935]={solar_start=12783,lunar_start=12817,lunar_code=11104},
[1936]={solar_start=13148,lunar_start=13171,lunar_code=100067},
[1937]={solar_start=13514,lunar_start=13555,lunar_code=37600},
[1938]={solar_start=13879,lunar_start=13909,lunar_code=116951},
[1939]={solar_start=14244,lunar_start=14293,lunar_code=51536},
[1940]={solar_start=14609,lunar_start=14647,lunar_code=54432},
[1941]={solar_start=14975,lunar_start=15001,lunar_code=120998},
[1942]={solar_start=15340,lunar_start=15385,lunar_code=46416},
[1943]={solar_start=15705,lunar_start=15740,lunar_code=22176},
[1944]={solar_start=16070,lunar_start=16094,lunar_code=107956},
[1945]={solar_start=16436,lunar_start=16479,lunar_code=9680},
[1946]={solar_start=16801,lunar_start=16833,lunar_code=37584},
[1947]={solar_start=17166,lunar_start=17187,lunar_code=53938},
[1948]={solar_start=17531,lunar_start=17571,lunar_code=43344},
[1949]={solar_start=17897,lunar_start=17925,lunar_code=46423},
[1950]={solar_start=18262,lunar_start=18309,lunar_code=27808},
[1951]={solar_start=18627,lunar_start=18663,lunar_code=46416},
[1952]={solar_start=18992,lunar_start=19018,lunar_code=86869},
[1953]={solar_start=19358,lunar_start=19402,lunar_code=19872},
[1954]={solar_start=19723,lunar_start=19756,lunar_code=42416},
[1955]={solar_start=20088,lunar_start=20111,lunar_code=83315},
[1956]={solar_start=20453,lunar_start=20495,lunar_code=21168},
[1957]={solar_start=20819,lunar_start=20849,lunar_code=43432},
[1958]={solar_start=21184,lunar_start=21232,lunar_code=59728},
[1959]={solar_start=21549,lunar_start=21587,lunar_code=27296},
[1960]={solar_start=21914,lunar_start=21941,lunar_code=44710},
[1961]={solar_start=22280,lunar_start=22325,lunar_code=43856},
[1962]={solar_start=22645,lunar_start=22680,lunar_code=19296},
[1963]={solar_start=23010,lunar_start=23034,lunar_code=43748},
[1964]={solar_start=23375,lunar_start=23418,lunar_code=42352},
[1965]={solar_start=23741,lunar_start=23773,lunar_code=21088},
[1966]={solar_start=24106,lunar_start=24126,lunar_code=62051},
[1967]={solar_start=24471,lunar_start=24510,lunar_code=55632},
[1968]={solar_start=24836,lunar_start=24865,lunar_code=23383},
[1969]={solar_start=25202,lunar_start=25249,lunar_code=22176},
[1970]={solar_start=25567,lunar_start=25603,lunar_code=38608},
[1971]={solar_start=25932,lunar_start=25958,lunar_code=19925},
[1972]={solar_start=26297,lunar_start=26342,lunar_code=19152},
[1973]={solar_start=26663,lunar_start=26696,lunar_code=42192},
[1974]={solar_start=27028,lunar_start=27050,lunar_code=54484},
[1975]={solar_start=27393,lunar_start=27434,lunar_code=53840},
[1976]={solar_start=27758,lunar_start=27788,lunar_code=54616},
[1977]={solar_start=28124,lunar_start=28172,lunar_code=46400},
[1978]={solar_start=28489,lunar_start=28526,lunar_code=46752},
[1979]={solar_start=28854,lunar_start=28881,lunar_code=103846},
[1980]={solar_start=29219,lunar_start=29265,lunar_code=38320},
[1981]={solar_start=29585,lunar_start=29620,lunar_code=18864},
[1982]={solar_start=29950,lunar_start=29974,lunar_code=43380},
[1983]={solar_start=30315,lunar_start=30358,lunar_code=42160},
[1984]={solar_start=30680,lunar_start=30712,lunar_code=45690},
[1985]={solar_start=31046,lunar_start=31096,lunar_code=27216},
[1986]={solar_start=31411,lunar_start=31450,lunar_code=27968},
[1987]={solar_start=31776,lunar_start=31804,lunar_code=44870},
[1988]={solar_start=32141,lunar_start=32188,lunar_code=43872},
[1989]={solar_start=32507,lunar_start=32543,lunar_code=38256},
[1990]={solar_start=32872,lunar_start=32898,lunar_code=19189},
[1991]={solar_start=33237,lunar_start=33282,lunar_code=18800},
[1992]={solar_start=33602,lunar_start=33636,lunar_code=25776},
[1993]={solar_start=33968,lunar_start=33990,lunar_code=29859},
[1994]={solar_start=34333,lunar_start=34373,lunar_code=59984},
[1995]={solar_start=34698,lunar_start=34728,lunar_code=27480},
[1996]={solar_start=35063,lunar_start=35112,lunar_code=23232},
[1997]={solar_start=35429,lunar_start=35466,lunar_code=43872},
[1998]={solar_start=35794,lunar_start=35821,lunar_code=38613},
[1999]={solar_start=36159,lunar_start=36205,lunar_code=37600},
[2000]={solar_start=36524,lunar_start=36559,lunar_code=51552},
[2001]={solar_start=36890,lunar_start=36913,lunar_code=55636},
[2002]={solar_start=37255,lunar_start=37297,lunar_code=54432},
[2003]={solar_start=37620,lunar_start=37651,lunar_code=55888},
[2004]={solar_start=37985,lunar_start=38006,lunar_code=30034},
[2005]={solar_start=38351,lunar_start=38390,lunar_code=22176},
[2006]={solar_start=38716,lunar_start=38744,lunar_code=43959},
[2007]={solar_start=39081,lunar_start=39129,lunar_code=9680},
[2008]={solar_start=39446,lunar_start=39483,lunar_code=37584},
[2009]={solar_start=39812,lunar_start=39837,lunar_code=51893},
[2010]={solar_start=40177,lunar_start=40221,lunar_code=43344},
[2011]={solar_start=40542,lunar_start=40575,lunar_code=46240},
[2012]={solar_start=40907,lunar_start=40929,lunar_code=47780},
[2013]={solar_start=41273,lunar_start=41313,lunar_code=44368},
[2014]={solar_start=41638,lunar_start=41668,lunar_code=21977},
[2015]={solar_start=42003,lunar_start=42052,lunar_code=19360},
[2016]={solar_start=42368,lunar_start=42406,lunar_code=42416},
[2017]={solar_start=42734,lunar_start=42761,lunar_code=86390},
[2018]={solar_start=43099,lunar_start=43145,lunar_code=21168},
[2019]={solar_start=43464,lunar_start=43499,lunar_code=43312},
[2020]={solar_start=43829,lunar_start=43853,lunar_code=31060},
[2021]={solar_start=44195,lunar_start=44237,lunar_code=27296},
[2022]={solar_start=44560,lunar_start=44591,lunar_code=44368},
[2023]={solar_start=44925,lunar_start=44946,lunar_code=23378},
[2024]={solar_start=45290,lunar_start=45330,lunar_code=19296},
[2025]={solar_start=45656,lunar_start=45684,lunar_code=42726},
[2026]={solar_start=46021,lunar_start=46068,lunar_code=42208},
[2027]={solar_start=46386,lunar_start=46422,lunar_code=53856},
[2028]={solar_start=46751,lunar_start=46776,lunar_code=60005},
[2029]={solar_start=47117,lunar_start=47160,lunar_code=54576},
[2030]={solar_start=47482,lunar_start=47515,lunar_code=23200},
[2031]={solar_start=47847,lunar_start=47869,lunar_code=30371},
[2032]={solar_start=48212,lunar_start=48253,lunar_code=38608},
[2033]={solar_start=48578,lunar_start=48608,lunar_code=19195},
[2034]={solar_start=48943,lunar_start=48992,lunar_code=19152},
[2035]={solar_start=49308,lunar_start=49346,lunar_code=42192},
[2036]={solar_start=49673,lunar_start=49700,lunar_code=118966},
[2037]={solar_start=50039,lunar_start=50084,lunar_code=53840},
[2038]={solar_start=50404,lunar_start=50438,lunar_code=54560},
[2039]={solar_start=50769,lunar_start=50792,lunar_code=56645},
[2040]={solar_start=51134,lunar_start=51176,lunar_code=46496},
[2041]={solar_start=51500,lunar_start=51531,lunar_code=22224},
[2042]={solar_start=51865,lunar_start=51886,lunar_code=21938},
[2043]={solar_start=52230,lunar_start=52270,lunar_code=18864},
[2044]={solar_start=52595,lunar_start=52624,lunar_code=42359},
[2045]={solar_start=52961,lunar_start=53008,lunar_code=42160},
[2046]={solar_start=53326,lunar_start=53362,lunar_code=43600},
[2047]={solar_start=53691,lunar_start=53716,lunar_code=111189},
[2048]={solar_start=54056,lunar_start=54100,lunar_code=27936},
[2049]={solar_start=54422,lunar_start=54454,lunar_code=44448},
[2050]={solar_start=54787,lunar_start=54809,lunar_code=84835},
[2051]={solar_start=55152,lunar_start=55193,lunar_code=37744},
[2052]={solar_start=55517,lunar_start=55548,lunar_code=18936},
[2053]={solar_start=55883,lunar_start=55932,lunar_code=18800},
[2054]={solar_start=56248,lunar_start=56286,lunar_code=25776},
[2055]={solar_start=56613,lunar_start=56640,lunar_code=92326},
[2056]={solar_start=56978,lunar_start=57023,lunar_code=59984},
[2057]={solar_start=57344,lunar_start=57378,lunar_code=27296},
[2058]={solar_start=57709,lunar_start=57732,lunar_code=108228},
[2059]={solar_start=58074,lunar_start=58116,lunar_code=43744},
[2060]={solar_start=58439,lunar_start=58471,lunar_code=37600},
[2061]={solar_start=58805,lunar_start=58825,lunar_code=53987},
[2062]={solar_start=59170,lunar_start=59209,lunar_code=51552},
[2063]={solar_start=59535,lunar_start=59563,lunar_code=54615},
[2064]={solar_start=59900,lunar_start=59947,lunar_code=54432},
[2065]={solar_start=60266,lunar_start=60301,lunar_code=55888},
[2066]={solar_start=60631,lunar_start=60656,lunar_code=23893},
[2067]={solar_start=60996,lunar_start=61040,lunar_code=22176},
[2068]={solar_start=61361,lunar_start=61394,lunar_code=42704},
[2069]={solar_start=61727,lunar_start=61749,lunar_code=21972},
[2070]={solar_start=62092,lunar_start=62133,lunar_code=21200},
[2071]={solar_start=62457,lunar_start=62487,lunar_code=43448},
[2072]={solar_start=62822,lunar_start=62871,lunar_code=43344},
[2073]={solar_start=63188,lunar_start=63225,lunar_code=46240},
[2074]={solar_start=63553,lunar_start=63579,lunar_code=46758},
[2075]={solar_start=63918,lunar_start=63963,lunar_code=44368},
[2076]={solar_start=64283,lunar_start=64318,lunar_code=21920},
[2077]={solar_start=64649,lunar_start=64672,lunar_code=43940},
[2078]={solar_start=65014,lunar_start=65056,lunar_code=42416},
[2079]={solar_start=65379,lunar_start=65411,lunar_code=21168},
[2080]={solar_start=65744,lunar_start=65765,lunar_code=45683},
[2081]={solar_start=66110,lunar_start=66149,lunar_code=26928},
[2082]={solar_start=66475,lunar_start=66503,lunar_code=29495},
[2083]={solar_start=66840,lunar_start=66887,lunar_code=27296},
[2084]={solar_start=67205,lunar_start=67241,lunar_code=44368},
[2085]={solar_start=67571,lunar_start=67596,lunar_code=84821},
[2086]={solar_start=67936,lunar_start=67980,lunar_code=19296},
[2087]={solar_start=68301,lunar_start=68334,lunar_code=42352},
[2088]={solar_start=68666,lunar_start=68689,lunar_code=21732},
[2089]={solar_start=69032,lunar_start=69072,lunar_code=53600},
[2090]={solar_start=69397,lunar_start=69426,lunar_code=59752},
[2091]={solar_start=69762,lunar_start=69810,lunar_code=54560},
[2092]={solar_start=70127,lunar_start=70164,lunar_code=55968},
[2093]={solar_start=70493,lunar_start=70519,lunar_code=92838},
[2094]={solar_start=70858,lunar_start=70903,lunar_code=22224},
[2095]={solar_start=71223,lunar_start=71258,lunar_code=19168},
[2096]={solar_start=71588,lunar_start=71612,lunar_code=43476},
[2097]={solar_start=71954,lunar_start=71996,lunar_code=41680},
[2098]={solar_start=72319,lunar_start=72350,lunar_code=53584},
[2099]={solar_start=72684,lunar_start=72704,lunar_code=62034},
[2100]={solar_start=73049,lunar_start=73088,lunar_code=54560},
}
local function year_days_acc(year)
if year%4==0 and (year%100~=0 or year%400==0) then
return {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}
else
return {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}
end
end
local function binary_search(s, e, f)
while s < e do
local m = math.floor((s+e)/2)
if not f(m) then s = s + 1 else e = m end
end
return s
end
local function lunar_month_days(code, month)
return bit32.extract(code, 16-month) ~= 0 and 30 or 29
end
local function lunar_leap_month(code)
local month = bit32.extract(code, 0, 4)
if month == 0 then return 0, 0 end
return bit32.extract(code, 16) ~= 0 and 30 or 29
end
local function solar_dn(year, month, day)
if year < 1900 or year > 2100 then return -1 end
return data[year].solar_start + year_days_acc(year)[month] + day-1
end
local function solar_ymd(dn)
if dn < 0 or dn > 73413 then return -1,-1,-1 end
local year = binary_search(1900, 2100, function(i) return data[i+1].solar_start > dn end)
dn = dn - data[year].solar_start
local acc = year_days_acc(year)
local month = binary_search(1, 12, function(i) return acc[i+1] > dn end)
dn = dn - acc[month]
return year, month, dn+1
end
local function lunar_dn(year, month, day, leap)
if year < 1900 or year > 2100 or (year==2100 and month==12 and day>1) then return -1 end
local n = 0
local code = data[year].lunar_code
local leap_month, leap_days = lunar_leap_month(code)
for i=1,month-1 do
n = n + lunar_month_days(code, i)
if i == leap_month then n = n + leap_days end
end
if leap then n = n + lunar_month_days(code, month) end
return data[year].lunar_start + n + day-1
end
local function lunar_ymd(dn)
if dn < 30 or dn > 73413 then return -1,-1,-1,false end
local year = binary_search(1900, 2100, function(i) return data[i+1].lunar_start > dn end)
dn = dn - data[year].lunar_start
local code = data[year].lunar_code
local leap_month, leap_days = lunar_leap_month(code)
for i=1,12 do
local days = lunar_month_days(code, i)
if dn < days then return year, i, dn+1, false else dn = dn - days end
if i == leap_month then
if dn < leap_days then return year, i, dn+1, true else dn = dn - leap_days end
end
end
end
local function solar_to_lunar(year, month, day)
local dn = solar_dn(year, month, day)
return lunar_ymd(dn)
end
local function lunar_to_solar(year, month, day, leap)
local dn = lunar_dn(year, month, day, leap)
return solar_ymd(dn)
end
local display = {
digits = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"},
months = {"正月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "冬月", "腊月"},
days = {"初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十",
"十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十",
"廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十"},
}
local function lunar_format(year, month, day, leap)
return string.format("%s%s%s%s年",
display.digits[tonumber(string.sub(tostring(year),1,1))+1],
display.digits[tonumber(string.sub(tostring(year),2,2))+1],
display.digits[tonumber(string.sub(tostring(year),3,3))+1],
display.digits[tonumber(string.sub(tostring(year),4,4))+1])
.. (leap and "闰" or "")
.. display.months[month]
.. display.days[day]
end
return {
solar_dn = function(frame)
if frame.args[1] == "" then return "" end
local y, m, d = frame.args[1]:match("(%d+)%-(%d+)%-(%d+)")
return tostring(solar_dn(tonumber(y), tonumber(m), tonumber(d)))
end,
solar_ymd = function(frame)
if frame.args[1] == "" then return "" end
local y, m, d = solar_ymd(tonumber(frame.args[1]))
return string.format("%d-%02d-%02d", y, m, d)
end,
lunar_dn = function(frame)
if frame.args[1] == "" then return "" end
local y, m, d = frame.args[1]:match("(%d+)%-(%d+)%-(%d+)")
return tostring(lunar_dn(tonumber(y), tonumber(m), tonumber(d), frame.args[1]:match("%d+%-%d+%-%d+L") ~= nil))
end,
lunar_ymd = function(frame)
if frame.args[1] == "" then return "" end
local y, m, d, leap = lunar_ymd(tonumber(frame.args[1]))
return string.format("%d-%02d-%02d%s", y, m, d, leap and "L" or "")
end,
solar_to_lunar = function(frame)
if frame.args[1] == "" then return "" end
local sy, sm, sd = frame.args[1]:match("(%d+)%-(%d+)%-(%d+)")
local y, m, d, leap = solar_to_lunar(tonumber(sy), tonumber(sm), tonumber(sd))
return string.format("%d-%02d-%02d%s", y, m, d, leap and "L" or "")
end,
lunar_to_solar = function(frame)
if frame.args[1] == "" then return "" end
local ly, lm, ld= frame.args[1]:match("(%d+)%-(%d+)%-(%d+)")
local ll = frame.args[1]:match("%d+%-%d+%-%d+L") ~= nil
local y, m, d = lunar_to_solar(tonumber(ly), tonumber(lm), tonumber(ld), ll)
return string.format("%d-%02d-%02d", y, m, d)
end,
lunar_format = function(frame)
if frame.args[1] == "" then return "" end
local y, m, d= frame.args[1]:match("(%d+)%-(%d+)%-(%d+)")
local l = frame.args[1]:match("%d+%-%d+%-%d+L") ~= nil
return lunar_format(tonumber(y), tonumber(m), tonumber(d), l)
end,
}
|
-------------------------------------------------------------------------------
-- Mob Framework Mod by Sapier
--
-- You may copy, use, modify or do nearly anything except removing this
-- copyright notice.
-- And of course you are NOT allow to pretend you have written it.
--
--! @file mob_template.lua
--! @brief template for mob
--! @copyright Sapier
--! @author Sapier
--! @date 2013-01-27
--
-- Contact sapier a t gmx net
-------------------------------------------------------------------------------
--+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
--+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-- WARNING this code might be not correct lua in order to get doxygen
-- compatibility!
--+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
--+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
--! @brief Template for creating mobs
--!
--! This template trys to describe all available configuration options
--! in mob framework.
--! @ingroup framework_mob
local mob_template = {
--! @brief [MANDATORY] name of mob @b (alphanumeric and "_" only!!)
name = "some name",
--! @brief [MANDATORY] name of mod defining the mob
modname = "name of mod",
--! @brief [MANDATORY] generic parameters for mob
generic = {
--! @brief [MANDATORY] description to show on mouse over in inventory
description="Some mob",
--! @brief [MANDATORY] maximum health
base_health=0,
--! @brief [MANDATORY] environment of mob to be
envid="some environment id",
--! @brief [OPTIONAL] item description OR function all returning a item description of whats the result of a kill
kill_result = nil,
--! @brief [OPTIONAL] armor groups of mob
armor_groups = nil,
--! @brief [OPTIONAL] custom on_hit(entity,player) callback return true to skip normal fight callback
on_hit_callback = nil,
--! @brief [OPTIONAL] custom on_kill(entity,player) callback return true to skip normal on kill handling
on_kill_callback = nil,
--! @brief [OPTIONAL] custom on_place(entity, placer, pointed_thing) callback called after normal on place handling is done
custom_on_place_handler = nil,
--! @brief [OPTIONAL] custom on_activate(entity) callback called after normal on_activate handling is done
custom_on_activate_handler = function(entity) end,
--! @brief [OPTIONAL] custom on_step(entity) callback called after normal on_step handling is done
custom_on_step_handler = nil,
--! @brief [OPTIONAL] list of callbacks
on_rightclick_callbacks = {
{
handler = function(entity, player) end,
name = "internal name shown in debug info",
visiblename = function(entity) end or "some label of rightclick button"
}
},
},
--! @brief [MANDATORY] configuration of movement generator
movement = {
--! @brief [MANDATORY] is this a flying mob
canfly=false,
--! @brief [MANDATORY] minumum acceleration of mob
min_accel=0,
--! @brief [MANDATORY] maximum acceleration of mob
max_accel=0,
--! @brief [MANDATORY] maximum absolute speed of mob
max_speed=0,
--! @brief [OPTIONAL] minimum speed a mob shall move (if moving at all)
min_speed=0,
--! @brief [MOV_GEN_DEPENDENT | MANDATORY] pattern based movement gen -> pattern to use for movement
pattern="some pattern id",
--! @brief [MOV_GEN_DEPENDENT | OPTIONAL] follow movement gen -> does this mob guard it's spawnpoint
guardspawnpoint = false,
--! @brief [MOV_GEN_DEPENDENT | OPTIONAL] follow movement gen -> time until this mob teleports to its target
teleportdelay = 60,
},
--! @brief [OPTIONAL] if mob is harvestable configure it here
harvest = {
--! @brief [OPTIONAL] tool required for harvesting
tool=nil,
--! @brief [OPTIONAL] is tool consuled by harvesting
tool_consumed=false,
--! @brief [MANDATORY] result of harvest
result="",
--! @brief [OPTIONAL] mob transforms to this mob on harvest
transforms_to="",
--! @brief [MANDATORY] minimum time between two harvests (in case of transform set this to -1)
min_delay=-1,
},
--! @brief [OPTIONAL] configuration how to catch the mob
catching = {
--! @brief [MANDATORY] tool required to wear to catch the mob
tool = "some item",
--! @brief [MANDATORY] is tool consumed by catching
consumed = true,
--! @brief [OPTIONAL] function to be called to check if a mob can be cought in current state
can_be_cought = function(entity) end,
},
--! @brief [OPTIONAL] does this mob do random drops
random_drop = {
--! @brief [MANDATORY] item to be dropped
result="some_material",
--! @brief [MANDATORY] minimum delay between two drops
min_delay=60,
--! @brief [MANDATORY] chance per second to drop after min_delay has passed
chance=0.2
},
--! @brief [OPTIONAL] if this mob s intended to transform by its own configure it here
auto_transform = {
--! @brief [MANDATORY] mob to transform to
result="some_mob",
--! @brief [MANDATORY] time to transformation
delay=1800
},
--! @brief [OPTIONAL] combat settings for mob
combat = {
--! @brief [MANDATORY] does mob start an attack on its own?
starts_attack=true,
--! @brief [MANDATORY] chance mob will attack (if starting attack on its own or beeing attacked)
angryness=0.95,
--! @brief [OPTIONAL] is mob sensitive to sun?
sun_sensitive=true,
--! @brief [OPTIONAL] attacks hostile mobs
attack_hostile_mobs=false,
--! @brief [UNUSED] attacks hostile mobs
--attack_friendly_mobs=false,
--! @brief [OPTIONAL] configuration of meele attack
melee = {
--! @brief [MANDATORY] maximum damage mob does per hit
maxdamage=4,
--! @brief [MANDATORY] range mob will hit
range=2,
--! @brief [MANDATORY] minimum time between two hits
speed=2,
--! @brief [OPTIONAL] list of groups damage is done to, if not specified "fleshy" is used
weapon_damage_groups= { "fleshy" },
},
--! @brief [OPTIONAL] configuration of distance attack
distance = {
--! @brief [MANDATORY] distance projectile to issue
attack="some_entity",
--! @brief [MANDATORY] distance to issue an attack
range=10,
--! @brief [OPTIONAL] minimum range of distance attack (should be > range of melee attack)
min_range = 3,
--! @brief [MANDATORY] minimum time between two attacks
speed=2,
},
--! @brief [OPTIONAL] configuration for self destructing mob
self_destruct = {
--! [MANDATORY] maximum damage to be done on self destruct
damage=15,
--! [MANDATORY] maximum range to do damage
range=5,
--! [MANDATORY] range to destroy nodes on self destruction
node_damage_range = 1.5,
--! [MANDATORY] delay between self destruct triggering and explosion
delay=5,
},
},
--! @brief [MANDATORY] spawning configuration for mob
spawning = {
--! @brief [MANDATORY] rate this mob is spawned
rate=0.01,
--! @brief [MANDATORY] typical distance between two mobs of this type when spawend
density=1000,
--! @brief [MANDATORY] identifyer of spawn algorithm
algorithm="some algorithm id",
--! @brief [ALGORITHM DEPENDENT] shadows minimum number of air blocks above pos
height = 1,
},
--! @brief [OPTIONAL] sounds to be played by mob
sound = {
--! @brief [OPTIONAL] random sound to be played
random = {
--! @brief [MANDATORY] default interval between random sounds
interval = 60,
--! @brief [MANDATORY] maximum deviation from default interval
max_interval_deviation = 10,
--! @brief [MANDATORY] list of random sounds to play
list = {
{
--! @brief [MANDATORY] basename of file
name="random_1",
--! @brief [MANDATORY] amplify the sound by this value
gain = 1,
--! @brief [MANDATORY] maximum distance sound is heared
max_hear_distance = 75,
},
{
--! @brief [MANDATORY] basename of file
name="random_2",
--! @brief [MANDATORY] amplify the sound by this value
gain = 1,
--! @brief [MANDATORY] maximum distance sound is heared
max_hear_distance = 75,
},
{
--! @brief [MANDATORY] basename of file
name="random_x",
--! @brief [MANDATORY] amplify the sound by this value
gain = 1,
--! @brief [MANDATORY] maximum distance sound is heared
max_hear_distance = 75,
},
},
},
--! @brief [OPTIONAL] sound played on self destruction
self_destruct = {
--! @brief [MANDATORY] basename of file
name="bomb_explosion",
--! @brief [MANDATORY] amplify the sound by this value
gain = 2,
--! @brief [MANDATORY] maximum distance sound is heared
max_hear_distance = 1000,
},
--! @brief [OPTIONAL] sound played on harvest
harvest = {
--! @brief [MANDATORY] basename of file
name="harvest",
--! @brief [MANDATORY] amplify the sound by this value
gain = 0.8,
--! @brief [MANDATORY] maximum distance sound is heared
max_hear_distance = 5,
},
--! @brief [OPTIONAL] sound played on distance attack
distance = {
--! @brief [MANDATORY] basename of file
name="fireball",
--! @brief [MANDATORY] amplify the sound by this value
gain = 1,
--! @brief [MANDATORY] maximum distance sound is heared
max_hear_distance = 100,
},
--! @brief [OPTIONAL] sound played if mob dies
die = {
--! @brief [MANDATORY] basename of file
name="die",
--! @brief [MANDATORY] amplify the sound by this value
gain = 1,
--! @brief [MANDATORY] maximum distance sound is heared
max_hear_distance = 100,
},
--! @brief [OPTIONAL] sound played if mob does meele attack
melee = {
--! @brief [MANDATORY] basename of file
name="hit",
--! @brief [MANDATORY] amplify the sound by this value
gain = 1,
--! @brief [MANDATORY] maximum distance sound is heared
max_hear_distance = 100,
},
},
--! @brief [OPTIONAL] parameters for rideable mobs
ride = {
--! @brief [OPTIONAL] speed when walking
walkspeed = 7.8,
--! @brief [OPTIONAL] speed when sneaking
sneakspeed = 0.8,
--! @brief [OPTIONAL] inital jumpspeed
jumpspeed = 58,
--! @brief [OPTIONAL] offset to center player is put to
attacheoffset = { x=0,y=2,z=0},
--! @brief [OPTIONAL] texture modifier when player is attached
texturemod = "^mob_ostrich_ostrich_saddle_mesh.png",
--! @brief [OPTIONAL] animation to show when riding
walk_anim = "walk",
},
--! @brief [OPTIONAL] description of animations
animation = {
--! @brief [OPTIONAL] one or many animation descriptions
animationname = {
--! @brief [MANDATORY] start frame of animation
start_frame = 1,
--! @brief [MANDATORY] end frame of animation
end_frame = 2,
},
},
--! @brief [OPTIONAL] configuration for a trader mob
trader_inventory = {
--! @brief [MANDATORY] goodlist to be sold
goods = {
--! @brief [MANDOTORY] first element in list
{ "default:mese 1", "default:dirt 99", "default:cobble 50"},
--! @brief [OPTIONAL] any further element
{ "default:steel_ingot 1", "default:dirt 50", "default:cobble 20"},
},
--! @brief [MANDATORY] list of names randomly choosen for trader
random_names = { "Name1","Name2","Name3"},
},
--! @brief [OPTIONAL] configuration for attention handling
attention = {
--! @brief [OPTIONAL] hear distance value
hear_distance = 3,
--! @brief [UPPER_VALUE_DEPENDENT | MANDATORY] value to add if within hear distance
hear_distance_value = 0.5,
--! @brief [OPTIONAL] view angle to consider
view_angle = nil,
--! @brief [UPPER_VALUE_DEPENDENT | MANDATORY] value to add if someone is within view angke
own_view_value = 0,
--! @brief [OPTIONAL] is remove view angle relevant?
remote_view = false,
--! @brief [UPPER_VALUE_DEPENDENT | MANDATORY] value to add if remote target looks at mob
remote_view_value = 0,
--! @brief [MANDATORY] value to add if within attention distance
attention_distance_value = 0.2,
--! @brief [MANDATORY] threshold to issue watch callback
watch_threshold = 2,
--! @brief [OPTIONAL] threshold to issue attack callback
attack_threshold = nil,
--! @brief [MANDATORY] maximum distance to consider objects for attantion
attention_distance = 7.5,
--! @brief [MANDATORY] maximum amount of attention any object can draw
attention_max = 10,
--! @brief [OPTIONAL] watch_callback(entity,target) a callback to be called once attention threshold is reached
watch_callback = nil
},
--! @brief [OPTIONAL] factions configuration
factions = {
--! @brief [OPTIONAL] define factions to be member in
member = {
"faction_1",
"faction_2",
"faction_3",
"faction_4"
},
},
--! @brief [OPTIONAL] used to specify different movement/model states,
--! you may specify as many states as you like
states = {
{
--! @brief [MANDATORY] (default state is MUST have!) name of state
name = "default",
--! @brief [MANDATORY] typical duration of this state
typical_state_time = 180,
--! @brief [MANDATORY] chance of state to be selected (SUM may not be > 1)
chance = 0.5,
--! @brief [MANDATORY] a special movement handler for this state
movgen = "none",
--! @brief [3D MANDATORY] a special model to be used for this state
graphics_3d = {
--! @brief [MANDATORY] this is the drawtype to use
visual = "mesh",
--! @brief [MANDATORY] this is the drawtype to use
mesh = "mesh.x",
--! @brief [MANDATORY] the model of the mob
textures = {"some node declatation"},
--! @brief [MANDATORY] collisionbox to use
collisionbox = { "<selectionbox declatation>" },
--! @brief [MANDATORY] xyz scale factors for the model
visual_size = {x=1,y=1,z=1},
--! @brief [OPTIONAL] additional yaw offset used to fix models with broken orientation
model_orientation_fix = -math.pi/2,
},
--! @brief [2D MANDATORY] a special sprite to be used for this state
graphics_2d = {
--! @brief [MANDATORY] scale of sprite
sprite_scale={x=0,y=0},
--! @brief [MANDATORY] description of multi dimensional sprites (e.g. containing burning/ differend view directions)
sprite_div = {x=0,y=0},
--! @brief [MANDATORY] height of sprite
visible_height = 3.2,
},
--! @brief [MANDATORY] a animation to be played while this state is active
animation = "walk",
},
{
--! @brief [MANDATORY] name of state
name = "another_state_example",
--! @brief [MANDATORY] typical duration of this state
typical_state_time = 180,
--! @brief [MANDATORY] chance of state to be selected (SUM may not be > 1)
chance = 0.5,
--! @brief [OPTIONAL] a function to check before switching to this state
HANDLER_precondition = nil,
--! @brief [OPTIONAL] a special movement handler for this state
movgen = "none",
--! @brief [OPTIONAL] a special model to be used for this state
graphics_3d = "<graphic definition as previous described>",
--! @brief [OPTIONAL] a special sprite to be used for this state
graphics_2d = "<graphic definition as previous described>",
--! @brief [OPTIONAL] a animation to be played while this state is active
animation = "name",
--! @brief [OPTIONAL] mode to differentiate different states e.g. "auto" for auto switched states "user_def" for user defined or "combat" for combat states
state_mode = "auto",
},
},
}
|
--//i did do a bit shit on this one...
for i=99,0,-1 do if i>2 then print(i .. " bottles of beer on the wall, " .. i .. " bottles of beer.\nTake one down and pass it around, " .. i-1 .. " bottles of beer on the wall.\n")elseif i==2 then print("2 bottles of beer on the wall, 2 bottles of beer.\nTake one down and pass it around, 1 bottle of beer on the wall.\n")elseif i==1 then print("1 bottle of beer on the wall, 1 bottle of beer.\nTake one down and pass it around, no more bottles of beer on the wall.\n")elseif i==0 then print("No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.")end end
|
return redis.call('keys', '*')
|
-----------------------------------------------------------------------------
-- MIME support for the Lua language.
-- Author: Diego Nehab
-- Conforming to RFCs 2045-2049
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module and import dependencies
-----------------------------------------------------------------------------
local base = _G
local ltn12 = require("plugins.moesif.ltn12")
local mime = require("mime.core")
local io = require("io")
local string = require("string")
local _M = mime
-- encode, decode and wrap algorithm tables
local encodet, decodet, wrapt = {},{},{}
_M.encodet = encodet
_M.decodet = decodet
_M.wrapt = wrapt
-- creates a function that chooses a filter by name from a given table
local function choose(table)
return function(name, opt1, opt2)
if base.type(name) ~= "string" then
name, opt1, opt2 = "default", name, opt1
end
local f = table[name or "nil"]
if not f then
base.error("unknown key (" .. base.tostring(name) .. ")", 3)
else return f(opt1, opt2) end
end
end
-- define the encoding filters
encodet['base64'] = function()
return ltn12.filter.cycle(_M.b64, "")
end
encodet['quoted-printable'] = function(mode)
return ltn12.filter.cycle(_M.qp, "",
(mode == "binary") and "=0D=0A" or "\r\n")
end
-- define the decoding filters
decodet['base64'] = function()
return ltn12.filter.cycle(_M.unb64, "")
end
decodet['quoted-printable'] = function()
return ltn12.filter.cycle(_M.unqp, "")
end
local function format(chunk)
if chunk then
if chunk == "" then return "''"
else return string.len(chunk) end
else return "nil" end
end
-- define the line-wrap filters
wrapt['text'] = function(length)
length = length or 76
return ltn12.filter.cycle(_M.wrp, length, length)
end
wrapt['base64'] = wrapt['text']
wrapt['default'] = wrapt['text']
wrapt['quoted-printable'] = function()
return ltn12.filter.cycle(_M.qpwrp, 76, 76)
end
-- function that choose the encoding, decoding or wrap algorithm
_M.encode = choose(encodet)
_M.decode = choose(decodet)
_M.wrap = choose(wrapt)
-- define the end-of-line normalization filter
function _M.normalize(marker)
return ltn12.filter.cycle(_M.eol, 0, marker)
end
-- high level stuffing filter
function _M.stuff()
return ltn12.filter.cycle(_M.dot, 2)
end
return _M
|
GM.Name = "Panic Ritual"
GM.Author = "Zet0r"
GM.Email = "N/A"
GM.Website = "https://youtube.com/Zet0r"
TEAM_HUMANS = 1
TEAM_DEMONS = 2
TEAM_SPECTATORS = 3
team.SetUp(TEAM_HUMANS, "Humans", Color(100,125,255), true)
team.SetUp(TEAM_DEMONS, "Demons", Color(255,100,100), true)
team.SetUp(TEAM_SPECTATORS, "Spectators", Color(150,150,150), true)
game.AddParticles("particles/panicritual/ritual_particles.pcf")
|
---Stack of drawables. Used to implement methods `on_click`, `on_hower` etc.
---Only elements with these methods should be added on stack.
---@class src.app.stack
---@type src.app.stack|src.proto.drawable[]
local stack = proto.set_name({}, "src.app.stack")
---@param drawable src.proto.drawable
---@return integer index
function stack:push(drawable)
local last = #self + 1
self[last] = drawable
return last
end
---@param element src.proto.drawable|integer
---@return integer|src.proto.drawable|nil index
function stack:pop(element)
if type(element) == "number" then
self[element] = nil
return element
else
for index, value in ipairs(self) do
if value == element then
self[index] = nil
return index
end
end
end
return nil
end
---@param point { [1]:integer, [2]:integer }
---@return src.proto.drawable? element
---@return integer? index
function stack:touch(point)
for index, element in ipairs(self) do
for i = 1, 2 do
local pos = element.abs_pos[i]
local size = element.abs_size[i]
if point[i] < pos or point[i] > pos + size then
break
elseif i == 2 then
return element, index
end
end
end
end
return stack
|
local _, Private = ...
if Private.initialized then
local name = "nerien_ovale_demonhunter_vengeance"
local desc = string.format("[9.1] %s: Demon Hunter - Vengeance", Private.name)
local code = [[
# Adapted from Wowhead's "Vengeance Demon Hunter Rotation Guide - Shadowlands 9.1.0"
# by Itamae.
# https://www.wowhead.com/vengeance-demon-hunter-rotation-guide
Include(nerien_ovale_library)
### Definitions ###
# Talents
Define(abyssal_strike_talent 22502)
Define(agonizing_flames_talent 22503)
Define(bulk_extraction_talent 21902)
Define(burning_alive_talent 22507)
Define(concentrated_sigils_talent 22546)
Define(demonic_talent 22513)
Define(feast_of_souls_talent 22505)
Define(felblade_talent 22504)
Define(fracture_talent 22770)
Define(quickened_sigils_talent 22510)
Define(ruinous_bulwark_talent 23464)
Define(sigil_of_chains_talent 22511)
Define(spirit_bomb_talent 22540)
Define(soul_barrier_talent 22768)
Define(void_reaver_talent 22512)
# Class Abilities
Define(bulk_extraction 320341)
SpellInfo(bulk_extraction cd=90)
SpellRequire(bulk_extraction unusable set=1 enabled=(not HasTalent(bulk_extraction_talent)))
Define(consume_magic 278326)
SpellInfo(consume_magic cd=10)
Define(demon_spikes 203720)
SpellInfo(demon_spikes charge_cd=20 cd=1.5 cd_haste=1)
Define(demon_spikes_buff 203819)
SpellInfo(demon_spikes_buff duration=6)
SpellAddBuff(demon_spikes demon_spikes_buff add=1)
Define(disrupt 183752)
SpellInfo(disrupt cd=15 interrupt=1)
Define(feast_of_souls_buff 207693)
SpellInfo(feast_of_souls_buff duration=6)
SpellAddBuff(soul_cleave feast_of_souls_buff add=1 enabled=(HasTalent(feast_of_souls_talent)))
Define(felblade 232893)
SpellInfo(felblade cd=15 cd_haste=1 fury=-40)
SpellRequire(felblade unusable set=1 enabled=(not HasTalent(felblade_talent)))
Define(fel_devastation 212084)
SpellInfo(fel_devastation cd=60 channel=2 fury=50)
Define(fiery_brand 204021)
SpellInfo(fiery_brand cd=60 duration=8)
SpellRequire(fiery_brand duration add=2 enabled=(Level() >= 54))
SpellAddTargetDebuff(fiery_brand fiery_brand add=1)
Define(fracture 263642)
SpellInfo(fracture charge_cd=4.5 cd_haste=1 fury=-25)
SpellRequire(fracture unusable set=1 enabled=(not HasTalent(fracture_talent)))
SpellRequire(fracture fury add=-20 enabled=(Level() >= 48 and BuffPresent(metamorphosis)))
Define(frailty_debuff 224509)
SpellInfo(frailty_debuff duration=20)
SpellAddTargetDebuff(spirit_bomb frailty_debuff add=1)
Define(immolation_aura 258920)
SpellInfo(immolation_aura cd=30 cd_haste=1 duration=6)
SpellRequire(immolation_aura cd add=-15 enabled=(Level() >= 27))
SpellRequire(immolation_aura duration add=3 enabled=(agonizing_flames_talent))
SpellAddBuff(immolation_aura immolation_aura add=1)
Define(imprison 217832)
SpellInfo(imprison cd=45)
Define(infernal_strike 189110)
SpellInfo(infernal_strike charge_cd=20 cd=0.8)
SpellRequire(infernal_strike charge_cd add=-8 enabled=(HasTalent(abyssal_strike_talent)))
Define(metamorphosis 187827)
SpellInfo(metamorphosis cd=300 duration=15)
SpellRequire(metamorphosis cd add=-60 enabled=(Level() >= 20))
SpellRequire(metamorphosis cd add=-60 enabled=(Level() >= 48))
SpellAddBuff(metamorphosis metamorphosis add=1)
Define(ruinous_bulwark_buff 326863)
SpellInfo(ruinous_bulwark_buff duration=10)
SpellAddBuff(fel_devastation ruinous_bulwark_buff add=1 enabled=(HasTalent(ruinous_bulwark_talent)))
Define(shear 203783)
SpellInfo(shear fury=-10)
SpellRequire(shear fury add=-20 enabled=(Level() >= 48 and BuffPresent(metamorphosis)))
SpellRequire(shear replaced_by set=fracture enabled=(HasTalent(fracture_talent)))
Define(sigil_of_chains 202138)
SpellInfo(sigil_of_chains cd=90)
SpellRequire(sigil_of_misery cd add=-18 enabled=(HasTalent(quickened_sigils_talent)))
Define(sigil_of_flame 204596)
SpellInfo(sigil_of_flame cd=30)
SpellRequire(sigil_of_flame cd add=-6 enabled=(HasTalent(quickened_sigils_talent)))
Define(sigil_of_misery 207684)
SpellInfo(sigil_of_misery cd=90)
SpellRequire(sigil_of_misery cd add=-18 enabled=(HasTalent(quickened_sigils_talent)))
Define(sigil_of_silence 202137)
SpellInfo(sigil_of_silence cd=60)
SpellRequire(sigil_of_silence cd add=-12 enabled=(HasTalent(quickened_sigils_talent)))
Define(soul_barrier 263648)
SpellInfo(soul_barrier cd=30 duration=12)
SpellRequire(soul_barrier unusable set=1 enabled=(not HasTalent(soul_barrier_talent)))
SpellAddBuff(soul_barrier soul_barrier add=1)
Define(soul_cleave 228477)
SpellInfo(soul_cleave fury=30)
Define(spirit_bomb 247454)
SpellInfo(spirit_bomb fury=30)
SpellRequire(spirit_bomb unusable set=1 enabled=(not HasTalent(spirit_bomb_talent)))
Define(throw_glaive 204157)
SpellInfo(throw_glaive cd=9 cd_haste=1)
SpellRequire(throw_glaive cd add=-6 enabled=(Level() >= 32))
Define(torment 185245)
SpellInfo(torment cd=8)
Define(uncontained_fel_debuff 209261)
SpellInfo(uncontained_fel_debuff duration=480)
Define(void_reaver_debuff 268178)
SpellInfo(void_reaver_debuff duration=12)
SpellAddTargetDebuff(soul_cleave void_reaver_debuff add=1)
# Covenant Abilities
Define(elysian_decree 306830)
SpellInfo(elysian_decree cd=60)
SpellRequire(elysian_decree unusable set=1 enabled=(not IsCovenant(kyrian)))
SpellRequire(elysian_decree cd add=-12 enabled=(HasTalent(quickened_sigils_talent)))
Define(sinful_brand 317009)
SpellInfo(sinful_brand cd=60 duration=8)
SpellRequire(sinful_brand unusable set=1 enabled=(not IsCovenant(venthyr)))
SpellAddTargetDebuff(sinful_brand sinful_brand add=1)
Define(fodder_to_the_flame 329554)
SpellInfo(fodder_to_the_flame cd=120 duration=25)
SpellRequire(fodder_to_the_flame unusable set=1 enabled=(not IsCovenant(necrolord)))
SpellAddTargetDebuff(fodder_to_the_flame fodder_to_the_flame add=1)
Define(the_hunt 323639)
SpellInfo(the_hunt cd=90)
# Runeforge Legendary Effects
Define(fiery_soul_runeforge 7048)
Define(razelikhs_defilement_runeforge 7046)
### Functions ###
AddFunction VengeanceInRange
{
target.InRange(soul_cleave)
}
AddFunction VengeanceIsTanking
{
# Return true if AoE-tanking or if the target is targeting you.
Enemies(tagged=1) > 1 or target.IsTargetingPlayer()
}
AddFunction VengeanceFuryDeficit
{
# Account for Fury gains from Immolation Aura and Metamorphosis.
MaxFury() - Fury() - GCDRemaining() * (20 * BuffPresent(immolation_aura) / 6 + 7 * BuffPresent(metamorphosis))
}
AddFunction VengeanceSigilDuration
{
2 - Talent(quickened_sigil_talent)
}
AddFunction VengeanceSoulFragmentHealing
{
if (IncomingDamage(5) * 6 > MaxHealth()) (IncomingDamage(5) * 6 / 100)
MaxHealth() / 100
}
AddFunction VengeanceBulkExtractionHealing
{
if (Enemies(tagged=1) > 5) (5 * VengeanceSoulFragmentHealing())
Enemies(tagged=1) * VengeanceSoulFragmentHealing()
}
AddFunction VengeanceImmolationAuraSoulFragments
{
if (SoulFragments() + 0.7 * Enemies(tagged=1) > 5) 5
SoulFragments() + 0.7 * Enemies(tagged=1)
}
AddFunction VengeanceShearSoulFragments
{
SoulFragments() + 2 + BuffPresent(metamorphosis)
}
AddFunction VengeancePrecombatActiveMitigationActions
{
PrecombatShortCdActions()
}
AddFunction VengeanceActiveMitigationActions
{
unless BuffPresent(metamorphosis)
{
if Enemies(tagged=1) > 1 or (target.IsTargetingPlayer() and IncomingPhysicalDamage(3) > 0)
{
if (Charges(demon_spikes count=0) > 1.9) Spell(demon_spikes text=cap)
if not BuffPresent(demon_spikes_buff) Spell(demon_spikes)
}
}
}
AddFunction VengeancePrecombatMainActions {}
AddFunction VengeanceMainActions
{
if (SoulFragments() >= 4) Spell(spirit_bomb)
if not target.InRange(soul_cleave) Spell(throw_glaive text=range)
if (VengeanceFuryDeficit() < 20) Spell(soul_cleave)
if (VengeanceFuryDeficit() > 40) Spell(felblade)
if (HasTalent(fracture_talent) and VengeanceFuryDeficit() > 25 and VengeanceShearSoulFragments() <= 5) Spell(fracture)
if (VengeanceFuryDeficit() > 10 and VengeanceImmolationAuraSoulFragments() <= 5) Spell(immolation_aura)
if (not HasTalent(fracture_talent) and VengeanceFuryDeficit() > 10 and VengeanceShearSoulFragments() <= 5) Spell(shear)
Spell(throw_glaive)
}
AddFunction VengeancePrecombatShortCdActions
{
Spell(elysian_decree)
if not EquippedRuneforge(razelikhs_defilement_runeforge) Spell(sigil_of_flame)
}
AddFunction VengeanceShortCdActions
{
Spell(elysian_decree)
if EquippedRuneforge(fiery_soul_runeforge) and HasTalent(burning_alive_talent)
{
if (VengeanceIsTanking() and not target.DebuffPresent(fiery_brand) and target.TimeToDie() > 12) Spell(fiery_brand)
}
unless SoulFragments() >= 4 and Spell(spirit_bomb)
{
Spell(fel_devastation)
unless
(VengeanceFuryDeficit() < 20 and Spell(soul_cleave)) or
(VengeanceFuryDeficit() > 25 and VengeanceShearSoulFragments() <= 5 and Spell(fracture)) or
(VengeanceFuryDeficit() > 10 and VengeanceImmolationAuraSoulFragments() <= 5 and Spell(immolation_aura))
{
if not EquippedRuneforge(razelikhs_defilement_runeforge) Spell(sigil_of_flame)
}
}
}
AddFunction VengeancePrecombatCdActions
{
PrecombatCdActions()
}
AddFunction VengeanceOffensiveCdActions
{
if (Charges(infernal_strike count=0) >= 1.8) Spell(infernal_strike)
Spell(sinful_brand)
Spell(fodder_to_the_flame)
Spell(the_hunt)
Spell(bulk_extraction)
}
AddFunction VengeanceDefensiveCdActions
{
unless EquippedRuneforge(fiery_soul_runeforge) and HasTalent(burning_alive_talent)
{
if not BuffPresent(metamorphosis) and VengeanceIsTanking() and not target.DebuffPresent(fiery_brand) Spell(fiery_brand)
}
if (SoulFragments() >= 4) Spell(soul_barrier)
if (SpellCooldown(fiery_brand) > 0 and (HasTalent(soul_barrier_talent) and SpellCooldown(soul_barrier) > 0)) Spell(metamorphosis)
}
AddFunction VengeanceCdActions
{
VengeanceDefensiveCdActions()
}
AddFunction VengeanceInterruptActions
{
if not focus.IsFriend() and focus.Casting()
{
if (focus.InRange(disrupt) and focus.IsInterruptible()) Spell(disrupt text=focus)
if not focus.Classification(worldboss)
{
if (
focus.Distance() < 30 and
focus.RemainingCastTime() >= VengeanceSigilDuration() + GCDRemaining()
) {
Spell(sigil_of_silence text=focus)
Spell(sigil_of_misery text=focus)
Spell(sigil_of_chains text=focus)
}
if focus.CreatureType(Beast Demon Humanoid) Spell(imprison text=focus)
}
}
if not target.IsFriend() and target.Casting()
{
if (target.InRange(disrupt) and target.IsInterruptible()) Spell(disrupt)
if not target.Classification(worldboss)
{
if (
target.Distance() < 30 and
target.RemainingCastTime() >= VengeanceSigilDuration() + GCDRemaining()
) {
Spell(sigil_of_silence)
Spell(sigil_of_misery)
Spell(sigil_of_chains)
}
if target.CreatureType(Beast Demon Humanoid) Spell(imprison)
}
}
InterruptActions()
}
AddFunction VengeanceDispelActions
{
if target.HasDebuffType(magic) Spell(consume_magic)
OffensiveDispelActions()
DefensiveDispelActions()
}
AddFunction VengeanceHealActions
{
ItemHealActions()
if (VengeanceBulkExtractionHealing() > HealthMissing()) Spell(bulk_extraction)
}
### User Interface ###
AddIcon help=interrupt size=small
{
VengeanceInterruptActions()
VengeanceDispelActions()
VengeanceHealActions()
}
AddIcon help=active_mitigation
{
if not InCombat() VengeancePrecombatActiveMitigationActions()
VengeanceActiveMitigationActions()
}
AddIcon help=main
{
if not InCombat() VengeancePrecombatMainActions()
VengeanceMainActions()
}
AddIcon help=shortcd
{
if not InCombat() VengeancePrecombatShortCdActions()
VengeanceShortCdActions()
}
AddIcon help=cd
{
if not InCombat() VengeancePrecombatCdActions()
VengeanceCdActions()
}
AddIcon help=offensive size=small
{
VengeanceOffensiveCdActions()
if not VengeanceInRange()
{
Spell(infernal_strike)
Texture(misc_arrowlup help=L(not_in_melee_range))
}
Item(Trinket0Slot usable=1 text=13)
Item(Trinket1Slot usable=1 text=14)
}
]]
Private.scripts:registerScript("DEMONHUNTER", "vengeance", name, desc, code, "script")
end
|
local aStar = {}
local Grid = require "modules.jumper.grid"
local Pathfinder = require "modules.jumper.pathfinder"
local walkable = 0
local grid
local myFinder
local map = {}
function aStar.get_path(from, to)
return myFinder:getPath(from.x, from.y, to.x, to.y)
end
function aStar.load()
for line=1,MINE.height do
map[line] = {}
for column=1,MINE.width do
local id = MINE.layers[layer.GROUND].data[(line-1)*MINE.width + column]
if id == 0 then
map[line][column] = 1
else
map[line][column] = 0
end
end
end
grid = Grid(map)
myFinder = Pathfinder(grid, 'ASTAR', walkable)
end
return aStar
|
include('shared.lua')
function GM:ScoreboardShow()
ShowSB = true
end
function GM:ScoreboardHide()
ShowSB = false
end
// TODO: CLEAN THIS CODE
function GM:GetTeamScoreInfo()
local TeamInfo = {}
local teamd={}
local players={}
local i=0
local name,cash,member,alive,ping
for i=0,10 do
table.insert(teamd,team.Name(i))
for k,v in pairs(team.GetPlayers(i)) do
name=v:Nick()
cash=v:GetNWInt("cash")
member=v:GetNWString("membership") or "Guest"
if v:IsAlive() then
alive="Alive"
else
alive="Dead"
end
ping=v:Ping()
table.insert(players,{name,cash,member,alive,ping})
end
table.insert(teamd,players)
players={}
table.insert(TeamInfo,teamd)
teamd={}
end
return TeamInfo
end
function GM:HUDDrawScoreBoard()
if (!ShowSB) then return end
if (ScoreDesign == nil) then
ScoreDesign = {}
ScoreDesign.HeaderY = 0
ScoreDesign.Height = ScrH() / 2
end
font="ScoreboardText"
local color={
Color(0,0,0,64),
Color(0,0,96,200)}
local ScoreboardInfo = self:GetTeamScoreInfo()
local of={x=ScrW() / 10,y=32}
local width = scrWidth - (2* of.y)
local height = scrHeight-of.y*2
local rowh=20
local row=1
draw.RoundedBox(4,of.x,of.y,width,64,color[1])
draw.RoundedBox(4,of.x+4,of.y+4,width-8,56,color[2])
draw.SimpleText(GetHostName(),font,ScrW()/2,of.y,Color(255,255,255,255),1)
draw.SimpleText(GM.Author,font,ScrW()/2,of.y+32,Color(255,255,255,255),1)
draw.RoundedBox(4,of.x,of.y+68,width,rowh,color[1])
draw.RoundedBox(4,of.x+4,of.y+72,width-8,rowh-8,color[2])
draw.SimpleText("Player:",font,of.x+8,of.y+80,Color(255,255,255,255),)
end
|
charJob = require "lib/charJob"
charInventory = require "lib/charInventory"
mapQuests = require "lib/mapQuests"
npcSpeakers = require "lib/npcSpeakers"
charConstants = require "lib/charConstants"
quest = target.get_quest(mapQuests.getID("SpecialTrainingBeginner"))
mapleAdmin = self.as_speaker(npcSpeakers.getID("MapleAdmin"))
if charJob.belongsTo("resistance") and target.level >= charConstants.getLvlCheckValue("firstJobAdvOther") then
charInventory.awardSpecialTrainingBeginnerMedal()
quest.complete()
mapleAdmin.say("You have earned the <Special Training Beginner> title. You can receive a Medal from NPC Dalair.")
mapleAdmin.say("Congratulations on earning your honorable #b<Special Training Beginner>#k title. I wish you the best of luck in your future endeavors! Keep up the good work. \r\n\r\n#fUI/UIWindow.img/QuestIcon/4/0# \r\n\r\n#v1142108:##t1142108# 1 ")
end
|
TOOL.Category = "Starfall"
TOOL.Name = "Starfall - Processor"
TOOL.Command = nil
TOOL.ConfigName = ""
-- ------------------------------- Sending / Receiving ------------------------------- --
local MakeSF
TOOL.ClientConVar["Model"] = "models/spacecode/sfchip.mdl"
TOOL.ClientConVar["ScriptModel"] = ""
TOOL.ClientConVar["parent"] = "0"
cleanup.Register("starfall_processor")
if SERVER then
CreateConVar('sbox_maxstarfall_processor', 20, { FCVAR_REPLICATED, FCVAR_NOTIFY, FCVAR_ARCHIVE })
util.AddNetworkString("starfall_openeditor")
function MakeSF(pl, Pos, Ang, model, inputs, outputs)
if not pl:CheckLimit("starfall_processor") then return false end
local sf = ents.Create("starfall_processor")
if not (sf and sf:IsValid()) then return false end
sf:SetAngles(Ang)
sf:SetPos(Pos)
sf:SetModel(model)
sf:Spawn()
if WireLib and inputs and inputs[1] and inputs[2] then
sf.Inputs = WireLib.AdjustSpecialInputs(sf, inputs[1], inputs[2])
end
if WireLib and outputs and outputs[1] and outputs[2] then
-- Initialize wirelink and entity outputs if present
for _, iname in pairs(outputs[1]) do
if iname == "entity" then
WireLib.CreateEntityOutput( nil, sf, {true} )
elseif iname == "wirelink" then
WireLib.CreateWirelinkOutput( nil, sf, {true} )
end
end
sf.Outputs = WireLib.AdjustSpecialOutputs(sf, outputs[1], outputs[2])
end
pl:AddCount("starfall_processor", sf)
pl:AddCleanup("starfall_processor", sf)
return sf
end
duplicator.RegisterEntityClass("starfall_processor", MakeSF, "Pos", "Ang", "Model", "_inputs", "_outputs")
else
language.Add("Tool.starfall_processor.name", "Starfall - Processor")
language.Add("Tool.starfall_processor.desc", "Spawns a Starfall processor. (Press Shift+F to switch to the component tool)")
language.Add("Tool.starfall_processor.left", "Spawn a processor / upload code")
language.Add("Tool.starfall_processor.right", "Open editor")
language.Add("Tool.starfall_processor.reload", "Update code without changing main file")
language.Add("Tool.starfall_processor.parent", "Parent instead of Weld" )
language.Add("sboxlimit_starfall_processor", "You've hit the Starfall processor limit!")
language.Add("undone_Starfall Processor", "Undone Starfall Processor")
language.Add("Cleanup_starfall_processor", "Starfall Processors")
TOOL.Information = { "left", "right", "reload" }
net.Receive("starfall_openeditor", function(len)
SF.Editor.open()
if net.ReadBool() then
net.ReadStarfall(nil, function(ok, sfdata)
if ok then
local function openfiles()
local mainfile = sfdata.files[sfdata.mainfile]
sfdata.files[sfdata.mainfile] = nil
for filename, code in pairs(sfdata.files) do
SF.Editor.openWithCode(filename, code)
end
-- Add mainfile last so it gets focus
SF.Editor.openWithCode(sfdata.mainfile, mainfile)
end
if SF.Editor.initialized then
openfiles()
else
hook.Add("Think", "SFWaitForEditor", function()
if SF.Editor.initialized then
openfiles()
hook.Remove("Think", "SFWaitForEditor")
end
end)
end
else
SF.AddNotify(LocalPlayer(), "Error downloading SF code.", "ERROR", 7, "ERROR1")
end
end)
end
end)
end
function TOOL:LeftClick(trace)
if not trace.HitPos then return false end
if trace.Entity:IsPlayer() then return false end
if CLIENT then return true end
local ply = self:GetOwner()
local ent = trace.Entity
local sf
local function doWeld()
if sf==ent then return end
local ret
if ent:IsValid() then
if self:GetClientNumber( "parent", 0 ) != 0 then
sf:SetParent(ent)
else
local const = constraint.Weld(sf, ent, 0, trace.PhysicsBone, 0, true, true)
ret = const
end
local phys = sf:GetPhysicsObject()
if phys:IsValid() then phys:EnableCollisions(false) sf.nocollide = true end
else
local phys = sf:GetPhysicsObject()
if phys:IsValid() then phys:EnableMotion(false) end
end
return ret
end
if not SF.RequestCode(ply, function(sfdata)
if not (sf and sf:IsValid()) then return end -- Probably removed during transfer
sf:SetupFiles(sfdata)
end) then
SF.AddNotify(ply, "Cannot upload SF code, please wait for the current upload to finish.", "ERROR", 7, "ERROR1")
return false
end
if ent:IsValid() and ent:GetClass() == "starfall_processor" then
sf = ent
else
local model = self:GetClientInfo("Model")
if not (util.IsValidModel(model) and util.IsValidProp(model)) then return false end
if not self:GetSWEP():CheckLimit("starfall_processor") then return false end
local Ang = trace.HitNormal:Angle()
Ang.pitch = Ang.pitch + 90
sf = MakeSF(ply, trace.HitPos, Ang, model)
if not sf then return false end
local min = sf:OBBMins()
sf:SetPos(trace.HitPos - trace.HitNormal * min.z)
local const = doWeld()
undo.Create("Starfall Processor")
undo.AddEntity(sf)
undo.AddEntity(const)
undo.SetPlayer(ply)
undo.Finish()
end
return true
end
function TOOL:RightClick(trace)
if SERVER then
local ply = self:GetOwner()
local ent = trace.Entity
if ent and ent:IsValid() and ent:GetClass() == "starfall_processor" then
if ent.mainfile then
net.Start("starfall_openeditor")
net.WriteBool(true)
net.WriteStarfall(ent)
net.Send(ply)
end
else
net.Start("starfall_openeditor")
net.WriteBool(false)
net.Send(ply)
end
end
return false
end
function TOOL:Reload(trace)
if not trace.HitPos then return false end
local ply = self:GetOwner()
local sf = trace.Entity
if sf:IsValid() and sf:GetClass() == "starfall_processor" and sf.mainfile then
if CLIENT then return true end
if not SF.RequestCode(ply, function(sfdata)
if not sf:IsValid() then return end -- Probably removed during transfer
sf:SetupFiles(sfdata)
end, sf.mainfile) then
SF.AddNotify(ply, "Cannot upload SF code, please wait for the current upload to finish.", "ERROR", 7, "ERROR1")
end
return true
else
return false
end
end
function TOOL:DrawHUD()
end
function TOOL:Think()
local model = self:GetClientInfo("ScriptModel")
if model=="" then
model = self:GetClientInfo("Model")
end
if not (self.GhostEntity and self.GhostEntity:IsValid()) or self.GhostEntity:GetModel() ~= model then
self:MakeGhostEntity(model, Vector(0, 0, 0), Angle(0, 0, 0))
end
local trace = util.TraceLine(util.GetPlayerTrace(self:GetOwner()))
if (not trace.Hit) then return end
local ent = self.GhostEntity
if not (ent and ent:IsValid()) then return end
if (trace.Entity and trace.Entity:GetClass() == "starfall_processor" or trace.Entity:IsPlayer()) then
ent:SetNoDraw(true)
return
end
local Ang = trace.HitNormal:Angle()
Ang.pitch = Ang.pitch + 90
local min = ent:OBBMins()
ent:SetPos(trace.HitPos - trace.HitNormal * min.z)
ent:SetAngles(Ang)
ent:SetNoDraw(false)
end
if CLIENT then
local lastclick = CurTime()
local function GotoDocs(button)
gui.OpenURL(SF.Editor.HelperURL:GetString())
end
function TOOL.BuildCPanel(panel)
panel:AddControl("Header", { Text = "#Tool.starfall_processor.name", Description = "#Tool.starfall_processor.desc" })
panel:AddControl("CheckBox", { Label = "#Tool.starfall_processor.parent", Command = "starfall_processor_parent" } )
local gateModels = list.Get("Starfall_gate_Models")
table.Merge(gateModels, list.Get("Wire_gate_Models"))
local modelPanel = vgui.Create("DPanelSelect", panel)
modelPanel:EnableVerticalScrollbar()
modelPanel:SetTall(66 * 5 + 2)
for model, v in pairs(gateModels) do
local icon = vgui.Create("SpawnIcon")
icon:SetModel(model)
icon.Model = model
icon:SetSize(64, 64)
icon:SetTooltip(model)
modelPanel:AddPanel(icon, { ["starfall_processor_Model"] = model })
end
modelPanel:SortByMember("Model", false)
panel:AddPanel(modelPanel)
panel:AddControl("Label", { Text = "" })
local docbutton = vgui.Create("DButton" , panel)
panel:AddPanel(docbutton)
docbutton:SetText("Starfall Documentation")
docbutton.DoClick = GotoDocs
local filebrowser = vgui.Create("StarfallFileBrowser")
panel:AddPanel(filebrowser)
filebrowser.tree:Setup("starfall")
filebrowser:SetSize(235, 400)
local lastClick = 0
filebrowser.tree.DoClick = function(self, node)
if CurTime() <= lastClick + 0.5 then
SF.Editor.openFile(node:GetFileName())
end
lastClick = CurTime()
end
local openeditor = vgui.Create("DButton", panel)
panel:AddPanel(openeditor)
openeditor:SetText("Open Editor")
openeditor.DoClick = SF.Editor.open
end
local function hookfunc(ply, bind, pressed)
if not pressed then return end
if bind == "impulse 100" and ply:KeyDown(IN_SPEED) then
local activeWep = ply:GetActiveWeapon()
if activeWep:IsValid() and activeWep:GetClass() == "gmod_tool" then
if activeWep.Mode == "starfall_processor" then
spawnmenu.ActivateTool("starfall_component")
return true
elseif activeWep.Mode == "starfall_component" then
spawnmenu.ActivateTool("starfall_processor")
return true
end
end
end
end
if game.SinglePlayer() then -- wtfgarry (have to have a delay in single player or the hook won't get added)
timer.Simple(5, function() hook.Add("PlayerBindPress", "sf_toolswitch", hookfunc) end)
else
hook.Add("PlayerBindPress", "sf_toolswitch", hookfunc)
end
end
|
local scripts = {
"src/main.lua",
"src/utility.lua",
"src/calculatePos.lua",
"src/createWindow.lua",
"src/createText.lua",
"src/create3DText.lua",
"src/createImage.lua",
"src/createButton.lua",
"src/createInput.lua",
"src/createCheckbox.lua",
"src/createList.lua"
}
function readFile(path)
local file = fileOpen(path)
if not file then
return false
end
local count = fileGetSize(file)
local data = fileRead(file, count)
fileClose(file)
return data
end
function get()
local source_code = ""
for k,v in pairs(scripts) do
v=readFile(v)
source_code = source_code..'\r\n'..v
end
return source_code
end
|
local vh2 = Instance.new("ScreenGui")
local Frame = Instance.new("Frame")
local bar3 = Instance.new("Frame")
local bar = Instance.new("Frame")
local title = Instance.new("TextLabel")
local bar2 = Instance.new("Frame")
local godmode = Instance.new("TextButton")
local exploitgun = Instance.new("TextButton")
local morphines = Instance.new("TextButton")
local infinitecr = Instance.new("TextButton")
local exit = Instance.new("TextButton")
vh2.Name = "vh2"
vh2.Parent = game.CoreGui
Frame.Parent = vh2
Frame.Active = true
Frame.BackgroundColor3 = Color3.new(0.188235, 0.188235, 0.188235)
Frame.Position = UDim2.new(0, 0, 0.185458362, 0)
Frame.Size = UDim2.new(0, 294, 0, 309)
Frame.Active = true
Frame.Draggable = true
bar3.Name = "bar3"
bar3.Parent = Frame
bar3.BackgroundColor3 = Color3.new(0.666667, 0, 0)
bar3.Position = UDim2.new(0, 0, 0.954692543, 0)
bar3.Size = UDim2.new(0, 294, 0, 6)
bar.Name = "bar"
bar.Parent = Frame
bar.Active = true
bar.BackgroundColor3 = Color3.new(0.666667, 0, 0)
bar.Position = UDim2.new(0, 0, 0.0201093554, 0)
bar.Size = UDim2.new(0, 294, 0, 21)
title.Archivable = false
title.Name = "title"
title.Parent = bar
title.Active = true
title.BackgroundColor3 = Color3.new(1, 1, 1)
title.BackgroundTransparency = 1
title.Position = UDim2.new(0.159863949, 0, 0, 0)
title.Size = UDim2.new(0, 200, 0, 21)
title.Font = Enum.Font.SourceSansBold
title.Text = "Zuiiv"
title.TextColor3 = Color3.new(1, 1, 1)
title.TextSize = 30
bar2.Name = "bar2"
bar2.Parent = Frame
bar2.BackgroundColor3 = Color3.new(0.666667, 0, 0)
bar2.Position = UDim2.new(0, 0, 0.974110007, 0)
bar2.Size = UDim2.new(0, 294, 0, 10)
godmode.Name = "godmode"
godmode.Parent = Frame
godmode.Active = false
godmode.BackgroundColor3 = Color3.new(0.666667, 0, 0)
godmode.Position = UDim2.new(0.159863949, 0, 0.142394826, 0)
godmode.Size = UDim2.new(0, 200, 0, 50)
godmode.Font = Enum.Font.SourceSansBold
godmode.Text = "Godmode"
godmode.TextColor3 = Color3.new(1, 1, 1)
godmode.TextSize = 35
godmode.TextTransparency = -1
godmode.MouseButton1Click:connect(function()
game.Workspace.Events.ChangeHealth:FireServer("999999999999999999999999999999")
end)
exploitgun.Name = "exploitgun"
exploitgun.Parent = Frame
exploitgun.Active = false
exploitgun.BackgroundColor3 = Color3.new(0.666667, 0, 0)
exploitgun.Position = UDim2.new(0.159863949, 0, 0.326860845, 0)
exploitgun.Size = UDim2.new(0, 200, 0, 50)
exploitgun.Font = Enum.Font.SourceSansBold
exploitgun.Text = "Exploit Gun"
exploitgun.TextColor3 = Color3.new(1, 1, 1)
exploitgun.TextSize = 35
exploitgun.TextTransparency = -1
exploitgun.MouseButton1Click:connect(function()
game.Workspace.Events.GiveGear:FireServer(game.ReplicatedStorage.SC.Dete["Lightning"])
end)
morphines.Name = "morphines"
morphines.Parent = Frame
morphines.Active = false
morphines.BackgroundColor3 = Color3.new(0.666667, 0, 0)
morphines.Position = UDim2.new(0.159863949, 0, 0.508090615, 0)
morphines.Size = UDim2.new(0, 200, 0, 50)
morphines.Font = Enum.Font.SourceSansBold
morphines.Text = "Morphines"
morphines.TextColor3 = Color3.new(1, 1, 1)
morphines.TextSize = 35
morphines.TextTransparency = -1
morphines.MouseButton1Click:connect(function()
workspace.Events.GiveGear:FireServer(game.ReplicatedStorage.Store.Sabils.Morphine.Gear, 10)
end)
infinitecr.Name = "infinitecr"
infinitecr.Parent = Frame
infinitecr.Active = false
infinitecr.BackgroundColor3 = Color3.new(0.666667, 0, 0)
infinitecr.Position = UDim2.new(0.159863949, 0, 0.692556679, 0)
infinitecr.Size = UDim2.new(0, 200, 0, 50)
infinitecr.Font = Enum.Font.SourceSansBold
infinitecr.Text = "InfiniteCR"
infinitecr.TextColor3 = Color3.new(1, 1, 1)
infinitecr.TextSize = 35
infinitecr.TextTransparency = -1
infinitecr.MouseButton1Click:connect(function()
game.Workspace.Events.GiveCR:FireServer(999999)
end)
exit.Name = "exit"
exit.Parent = Frame
exit.BackgroundColor3 = Color3.new(1, 1, 1)
exit.BackgroundTransparency = 1
exit.Position = UDim2.new(0.897959173, 0, 0.0201093554, 0)
exit.Size = UDim2.new(0, 30, 0, 21)
exit.Font = Enum.Font.SourceSansBold
exit.Text = "X"
exit.TextColor3 = Color3.new(1, 1, 1)
exit.TextSize = 30
exit.TextStrokeTransparency = 1000
exit.TextWrapped = true
exit.MouseButton1Click:connect(function()
vh2:Destroy()
end)
|
-- Importing modules
local RandomSelector = require "elasticsearch.selector.RandomSelector"
local Connection = require "elasticsearch.connection.Connection"
local Logger = require "elasticsearch.Logger"
local getmetatable = getmetatable
-- Setting up environment
local _ENV = lunit.TEST_CASE "tests.selector.RandomSelectorTest"
-- Declaring local variables
local rS
local connections
-- Testing the constructor
function constructorTest()
assert_function(RandomSelector.new)
local o = RandomSelector:new()
assert_not_nil(o)
local mt = getmetatable(o)
assert_table(mt)
assert_function(mt.selectNext)
assert_equal(mt, mt.__index)
end
-- The setup function
function setup()
connections = {}
local logger = Logger:new()
logger:setLogLevel("off")
for i = 1, 5 do
connections[i] = Connection:new{
protocol = "http",
host = "localhost",
port = 9200,
pingTimeout = 1,
logger = logger
}
-- For checking later on
connections[i].id = i
end
rS = RandomSelector:new()
end
-- Testing select function
function selectNextTest()
local count = {}
-- Initial count of each of the 5 connections
for i = 1, 5 do
count[i] = 0
end
-- Selecting random connections 1000 times
for i = 1, 1000 do
local con = rS:selectNext(connections)
count[con.id] = count[con.id] + 1
end
for i = 1, 5 do
if count[i] < 150 then
assert_false(true, "Random number generator used is not quite random")
end
end
assert_true(true)
end
|
local name=KEYS[1]
local greet=ARGV[1]
local result=greet.." "..name
return result
|
local R = require "rigel"
local RM = require "generators.modules"
local types = require("types")
local S = require("systolic")
local harness = require "generators.harness"
local C = require "generators.examplescommon"
W = 128
H = 64
T = 8
ITYPE = types.array2d( types.uint(8), T )
local inp = R.input( R.Handshake(ITYPE) )
local out = R.apply("ififo", C.fifo(ITYPE,128), inp)
local out = R.apply( "plus100", RM.makeHandshake( RM.map( C.plus100(types.uint(8)), T) ), out )
local out = R.apply("ofifo", C.fifo(ITYPE,128), out)
hsfn = RM.lambda( "fifo_wide", inp, out )
------------
harness{ outFile="fifo_wide_handshake_2_noloop", fn=hsfn, inFile="frame_128.raw", inSize={W,H}, outSize={W,H} }
|
local priority_queue = require("galaxyline.priority_queue")
local M = {}
-- TODO:
-- 2. proper setup function
-- 3. documentation and publish
-- 4. tabline
-- 5. .lua-format file
M.section = {}
M.section.left = {}
M.section.right = {}
M.section.mid = {}
M.divider = {
provider = "%=",
highlight = "StatusLine",
priority = 9999,
length = 0,
}
M.context = nil
M.events = {
"ColorScheme", "FileType", "BufWinEnter", "BufReadPost", "BufWritePost",
"BufEnter", "WinEnter", "FileChangedShellPost", "VimResized", "TermOpen",
"WinLeave",
}
local function log_incompatibility(component_property, invalid_type)
return string.format("Type '%s' not supported for property '%s'",
invalid_type, component_property)
end
local function process_provider(provider, context)
local provider_type = type(provider)
if provider_type == "function" then return provider(context.user_context) end
if provider_type == "string" then return provider end
error(log_incompatibility("provider", provider_type))
end
local function process_highlight(highlight, context)
local function wrap_highlight_group_marker(highlight_group)
return "%#" .. highlight_group .. "#"
end
local highlight_type = type(highlight)
if highlight_type == "nil" then return "" end
if highlight_type == "function" then
return wrap_highlight_group_marker(highlight(context.user_context))
end
if highlight_type == "string" then
return wrap_highlight_group_marker(highlight)
end
error(log_incompatibility("highlight", highlight_type))
end
local function process_formatter(formatter, resolved_provider, context)
local formatter_type = type(formatter)
if formatter_type == "nil" then return resolved_provider end
if formatter_type == "function" then
return formatter(resolved_provider, context.user_context)
end
error(log_incompatibility("formatter", formatter_type))
end
local function process_condition(condition, context)
local condition_type = type(condition)
if condition_type == "nil" then return true end
if condition_type == "function" then
return condition(context.user_context)
end
error(log_incompatibility("condition", condition_type))
end
local function process_length(length, resolved, context)
local length_type = type(length)
if length_type == "nil" then return string.len(resolved) end
if length_type == "function" then
return length(string.len(resolved), context.user_context)
end
if length_type == "number" then return length end
error(log_incompatibility("length", length_type))
end
local function process_component(component, context)
local name = component.name
local priority = component.priority or 0
local condition = component.condition
local provider = component.provider
local length = component.length
local abbreviate = component.abbreviate
local formatter = component.formatter
local highlight = component.highlight
local resolved_component = {
name = name,
chopped = false,
raw = "",
formatted = "",
len = 0,
formatter = formatter,
abbreviate = abbreviate,
length = length,
highlighting = process_highlight(highlight, context),
}
if not process_condition(condition, context) then
return resolved_component
end
local raw = process_provider(provider, context)
if raw == nil then return resolved_component end
local formatted = process_formatter(formatter, raw, context)
local len = process_length(length, formatted, context)
resolved_component.raw = raw
resolved_component.formatted = formatted
resolved_component.len = len
-- only assess components that have a positive length for abbreviation/chopping
-- i.e., particularly no dividers!
if len ~= 0 then
context.priority_queue.enqueue(priority, resolved_component)
end
return resolved_component
end
local function process_section(section, context)
if section == nil then return end
for _, component in ipairs(section) do
local ok, resolved_component = pcall(function()
return process_component(component, context)
end)
if not ok then
print(string.format("Error while processing component '%s': %s",
component.name, resolved_component))
else
table.insert(context.component_order, resolved_component)
context.total_len = context.total_len + resolved_component.len
end
end
return
end
local function prune_components(context, space_balance, columns)
while context.priority_queue.size() > 0 and space_balance < 0 do
local component = context.priority_queue.dequeue()
local ok, err = pcall(function()
local old_len
local new_len
if not component.abbreviate then
component.chopped = true
old_len = component.len
new_len = 0
else
local leftover_space = nil
if context.priority_queue.empty() then
leftover_space = columns
end
component.formatted = process_formatter(component.formatter,
component.abbreviate(component.raw, leftover_space), context)
old_len = component.len
new_len = process_length(component.length, component.formatted,
context)
end
space_balance = space_balance + (old_len - new_len)
end)
if not ok then
print(string.format("Error while pruning component '%s': %s",
component.name, err))
end
end
end
-- do not add dividers multiple times (improvment with proper setup fn)
local first_time_execution = true
function M.process_statusline()
local context = {
user_context = type(M.context) == "function" and M.context() or nil,
priority_queue = priority_queue(),
component_order = {},
total_len = 0,
}
local has_mid = next(M.section.mid) ~= nil
if first_time_execution then
table.insert(M.section.left, M.divider)
if has_mid then table.insert(M.section.mid, M.divider) end
first_time_execution = false
end
process_section(M.section.left, context)
if has_mid then process_section(M.section.mid, context) end
process_section(M.section.right, context)
local columns = vim.fn.winwidth(0)
local space_balance = columns - context.total_len
if space_balance < 0 then
prune_components(context, space_balance, columns)
end
local statusline = ""
for _, resolved_component in ipairs(context.component_order) do
if not resolved_component.chopped then
statusline = statusline .. resolved_component.highlighting ..
resolved_component.formatted
end
end
return statusline
end
function M.load_galaxyline()
vim.wo.statusline =
[[%{%luaeval('require("galaxyline").process_statusline')()%}]]
end
function M.disable_galaxyline()
vim.wo.statusline = ""
vim.api.nvim_command("augroup galaxyline")
vim.api.nvim_command("autocmd!")
vim.api.nvim_command("augroup END!")
end
function M.galaxyline_augroup()
vim.api.nvim_command("augroup galaxyline")
vim.api.nvim_command("autocmd!")
for _, def in ipairs(M.events) do
local command = string.format(
"autocmd %s * lua require(\"galaxyline\").load_galaxyline()", def)
vim.api.nvim_command(command)
end
vim.api.nvim_command("augroup END")
end
return M
|
local colors = {
bg = '#1e1e1e',
fg = '#aab2bf',
red = "#e06c75",
green = "#98C379",
yellow = "#ecbf6f",
blue = "#61afef",
purple = "#c678dd",
cyan = "#56b6c2",
white = "#abb2bf",
black = "#1E1E1E",
gray = "#4c4f55",
highlight = "#e2be7d"
}
return colors
|
return {
Inventory = {
-- ADRENAL BOOSTER / Cyberware / Circulatory System / Common
-- Helps the body maintain performance when under great strain.
-- Instantly restores 10% Stamina when you defeat an enemy.
{ id = "Items.StaminaRegenBoosterCommon" },
-- ADRENAL BOOSTER / Cyberware / Circulatory System / Uncommon
-- Helps the body maintain performance when under great strain.
-- Instantly restores 20% Stamina when you defeat an enemy.
{ id = "Items.StaminaRegenBoosterUncommon" },
-- ADRENAL BOOSTER / Cyberware / Circulatory System / Rare
-- Helps the body maintain performance when under great strain.
-- Instantly restores 30% Stamina when you defeat an enemy.
{ id = "Items.StaminaRegenBoosterRare" },
-- ADRENAL BOOSTER / Cyberware / Circulatory System / Epic
-- Helps the body maintain performance when under great strain.
-- Instantly restores 40% Stamina when you defeat an enemy.
{ id = "Items.StaminaRegenBoosterEpic" },
-- ADRENAL BOOSTER / Cyberware / Circulatory System / Legendary
-- Helps the body maintain performance when under great strain.
-- Instantly restores 50% Stamina when you defeat an enemy.
{ id = "Items.StaminaRegenBoosterLegendary" },
-- ARASAKA MK.3 / Cyberware / Operating System / Epic
-- A top-tier cyberdeck, commonly used by netrunners specializing in infilitration and corporate espionage.
-- Decreases the RAM cost of Covert quickhacks by 1.
-- Quickhacking an enemy affected by Ping will reset the duratio of ping.
-- Increases combat quickhack duration by 30%.
{
id = "Items.ArasakaEpicMKIII",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
{ slot = "Program4" },
{ slot = "Program5" },
},
},
-- ARASAKA MK.4 / Cyberware / Operating System / Legendary
-- A top-tier cyberdeck, commonly used by netrunners specializing in infilitration and corporate espionage.
-- Decreases the RAM cost of Covert quickhacks by 2.
-- Quickhacking an enemy affected by Ping will reset the duratio of ping.
-- Increases combat quickhack duration by 40%.
{
id = "Items.ArasakaLegendaryMKIV",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
{ slot = "Program4" },
{ slot = "Program5" },
{ slot = "Program6" },
},
},
-- BALLISTIC COPROCESSOR / Cyberware / Hands / Rare
-- A coprocessor with an integrated servomotor system.
-- A coprocessor with an integrated servomotor system.
{ id = "Items.PowerGripRare" },
-- BALLISTIC COPROCESSOR / Cyberware / Hands / Epic
-- A coprocessor with an integrated servomotor system.
-- A coprocessor with an integrated servomotor system.
{ id = "Items.PowerGripEpic" },
-- BALLISTIC COPROCESSOR / Cyberware / Hands / Legendary
-- A coprocessor with an integrated servomotor system.
-- A coprocessor with an integrated servomotor system.
{ id = "Items.PowerGripLegendary" },
-- BIOCONDUCTOR / Cyberware / Circulatory System / Rare
-- Facilitates superconductivity in the circuitry that connects the body's cyberware.
-- Reduces all Cyberware cooldowns by 10%.
{ id = "Items.BioConductorsRare" },
-- BIOCONDUCTOR / Cyberware / Circulatory System / Epic
-- Facilitates superconductivity in the circuitry that connects the body's cyberware.
-- Reduces all Cyberware cooldowns by 20%.
{ id = "Items.BioConductorsEpic" },
-- BIOCONDUCTOR / Cyberware / Circulatory System / Legendary
-- Facilitates superconductivity in the circuitry that connects the body's cyberware.
-- Reduces all Cyberware cooldowns by 30%.
{ id = "Items.BioConductorsLegendary" },
-- BIODYNE BERSERK MK.1 / Cyberware / Operating System / Uncommon
-- The Berserk model from BioDyne is an affordable and versatile implant for those who want quick and easy results, but don't expect miracles. It does what it says on the box, so let's not get picky.
-- When activated, ranged weapon recoil and sway -15%, melee damage -15% and Armor and Resistances +5% for 10 seconds.
-- Cooldown 30 seconds.
{
id = "Items.BerserkC2MK1",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- BIODYNE BERSERK MK.2 / Cyberware / Operating System / Rare
-- Intended to be part of a limited series of Berserk models from BioDyne for the European market. But thanks to better optimized performance, this model was warmly received by users, propelling it into the global mass market.
-- When activated, ranged weapon recoil and sway -25%, melee damage -25% and Armor and Resistances +5% for 15 seconds.
-- Ranged attack damage +10%.
-- Cooldown 30 seconds.
{
id = "Items.BerserkC2MK2",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- BIODYNE BERSERK MK.3 / Cyberware / Operating System / Epic
-- One of the all-time highest rated Berserk models from BioDyne. Its completely overhauled software architecture has increased its melee system performance by a whopping 92%.
-- When activated, ranged weapon recoil and sway -25%, melee damage -25% and Armor and Resistances +5% for 5 seconds.
-- Ranged attack damage +15.
-- Defeating enemies restores 3% health.
-- Cooldown 30 seconds.
{
id = "Items.BerserkC2MK3",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- BIODYNE BERSERK MK.4 / Cyberware / Operating System / Legendary
-- The newest line of Berserk implants from BioDyne are notable for their improved ranged combat and defense algorithms thanks to trademarked hormone regulators from the Swedish corporation Dahlberg-Holm.
-- When activated, ranged weapon recoil and sway -25%, melee damage -25% and Armor and Resistances +5% for 5 seconds.
-- Ranged attack damage +20%.
-- Defeating enemies restores 4% health.
-- Cooldown 30 seconds.
{
id = "Items.BerserkC2MK4",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- BIODYNE MK.1 / Cyberware / Operating System / Uncommon
-- A practical and amply-spacious cyberdeck. One of the more basic and affordable models known for its substantial performance output.
-- Allows you to preform quckhacks on targets and devices while scanning.
{
id = "Items.BioDyneUncommonMKI",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
},
},
-- BIODYNE MK.2 / Cyberware / Operating System / Rare
-- A practical and amply-spacious cyberdeck. One of the more basic and affordable models known for its substantial performance output.
-- Allows you to preform quckhacks on targets and devices while scanning.
-- Increases Cyberdeck Ram recovery rate by 3 unite(s) per 60 seconds.
{
id = "Items.BioDyneRareMKII",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
{ slot = "Program4" },
},
},
-- BIOMONITOR / Cyberware / Circulatory System / Common
-- An implant designed to coordinate regenerative processes.
-- Instant restores 30% Health when Health drops to 15%.
-- Cooldown 240 sec.
{ id = "Items.HealthMonitorCommon" },
-- BIOMONITOR / Cyberware / Circulatory System / Uncommon
-- An implant designed to coordinate regenerative processes.
-- Instant restores 40% Health when Health drops to 15%.
-- Cooldown 240 sec.
{ id = "Items.HealthMonitorUncommon" },
-- BIOMONITOR / Cyberware / Circulatory System / Rare
-- An implant designed to coordinate regenerative processes.
-- Instant restores 50% Health when Health drops to 15%.
-- Cooldown 240 sec.
{ id = "Items.HealthMonitorRare" },
-- BIOMONITOR / Cyberware / Circulatory System / Epic
-- An implant designed to coordinate regenerative processes.
-- Instant restores 60% Health when Health drops to 15%.
-- Cooldown 240 sec.
{ id = "Items.HealthMonitorEpic" },
-- BIOMONITOR / Cyberware / Circulatory System / Legendary
-- An implant designed to coordinate regenerative processes.
-- Instant restores 100% Health when Health drops to 15%.
-- Cooldown 240 sec.
{ id = "Items.HealthMonitorLegendary" },
-- BIONIC JOINTS / Cyberware / Skeleton / Rare
-- Mechatronic musculoskeletal support.
-- Reduces recoil of ranged weapons by 12%.
{ id = "Items.JointLockRare" },
-- BIONIC JOINTS / Cyberware / Skeleton / Epic
-- Mechatronic musculoskeletal support.
-- Reduces recoil of ranged weapons by 25%.
{ id = "Items.JointLockEpic" },
-- BIONIC LUNGS / Cyberware / Skeleton / Common
-- Efficient lungs engineered with both organic and artificial tissue fibers.
-- Increases Stamin by 20%.
{ id = "Items.EnhancedTissueCommon" },
-- BIONIC LUNGS / Cyberware / Skeleton / Uncommon
-- Efficient lungs engineered with both organic and artificial tissue fibers.
-- Increases Stamin by 30%.
{ id = "Items.EnhancedTissueUncommon" },
-- BIONIC LUNGS / Cyberware / Skeleton / Rare
-- Efficient lungs engineered with both organic and artificial tissue fibers.
-- Increases Stamin by 40%.
{ id = "Items.EnhancedTissueRare" },
-- BIONIC LUNGS / Cyberware / Skeleton / Epic
-- Efficient lungs engineered with both organic and artificial tissue fibers.
-- Increases Stamin by 50%.
{ id = "Items.EnhancedTissueEpic" },
-- BIONIC LUNGS / Cyberware / Skeleton / Legendary
-- Efficient lungs engineered with both organic and artificial tissue fibers.
-- Increases Stamin by 60%.
{ id = "Items.EnhancedTissueLegendary" },
-- BIOPLASTIC BLOOD VESSELS / Cyberware / Circulatory System / Common
-- Facilitates the body's distribution of blood and blood-borne substances.
-- Increases health regen outside of combat by 1 point per second.
{ id = "Items.EnhancedBloodVesselsCommon" },
-- BIOPLASTIC BLOOD VESSELS / Cyberware / Circulatory System / Uncommon
-- Facilitates the body's distribution of blood and blood-borne substances.
-- Increases health regen outside of combat by 2 point per second.
{ id = "Items.EnhancedBloodVesselsUncommon" },
-- BIOPLASTIC BLOOD VESSELS / Cyberware / Circulatory System / Rare
-- Facilitates the body's distribution of blood and blood-borne substances.
-- Increases health regen outside of combat by 4 point per second.
{ id = "Items.EnhancedBloodVesselsRare" },
-- BIOPLASTIC BLOOD VESSELS / Cyberware / Circulatory System / Epic
-- Facilitates the body's distribution of blood and blood-borne substances.
-- Increases health regen outside of combat by 10 point per second.
{ id = "Items.EnhancedBloodVesselsEpic" },
-- BIOPLASTIC BLOOD VESSELS / Cyberware / Circulatory System / Legendary
-- Facilitates the body's distribution of blood and blood-borne substances.
-- Increases health regen outside of combat by 50 point per second.
{ id = "Items.EnhancedBloodVesselsLegendary" },
-- BIOTECH Σ MK.1 / Cyberware / Operating System / Uncommon
-- A popular cyberdeck among netrunners whose equipment relies on speedy RAM recovery. On that front, the augmented Biotech coprocessors easily get the job done.
-- Allows you to perform quickhacks on targets and devices while scanning.
-- Increases RAM recovery rate by 6 units per 60 seconds.
{
id = "Items.BiotechUncommonMKI",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
},
},
-- BIOTECH Σ MK.2 / Cyberware / Operating System / Rare
-- A popular cyberdeck among netrunners whose equipment relies on speedy RAM recovery. On that front, the augmented Biotech coprocessors easily get the job done.
-- Allows you to perform quickhacks on targets and devices while scanning.
-- Increases RAM recovery rate by 9 units per 60 seconds.
-- Quickhacks deal 10% more damage.
{
id = "Items.BiotechRareMKII",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
{ slot = "Program4" },
},
},
-- BIOTECH Σ MK.3 / Cyberware / Operating System / Epic
-- A popular cyberdeck among netrunners whose equipment relies on speedy RAM recovery. On that front, the augmented Biotech coprocessors easily get the job done.
-- Allows you to perform quickhacks on targets and devices while scanning.
-- Increases RAM recovery rate by 9 units per 60 seconds.
-- Quickhacks deal 20% more damage.
{
id = "Items.BiotechEpicMKIII",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
{ slot = "Program4" },
{ slot = "Program5" },
},
},
-- BLOOD PUMP / Cyberware / Circulatory System / Common
-- Accelerates oxygen supply to the body's cells.
-- Activate to instantly restore 50% health (cooldown 180 seconds).
{ id = "Items.BloodPumpCommon" },
-- BLOOD PUMP / Cyberware / Circulatory System / Uncommon
-- Accelerates oxygen supply to the body's cells.
-- Activate to instantly restore 60% health (cooldown 180 seconds).
{ id = "Items.BloodPumpUncommon" },
-- BLOOD PUMP / Cyberware / Circulatory System / Rare
-- Accelerates oxygen supply to the body's cells.
-- Activate to instantly restore 70% health (cooldown 180 seconds).
{ id = "Items.BloodPumpRare" },
-- BLOOD PUMP / Cyberware / Circulatory System / Epic
-- Accelerates oxygen supply to the body's cells.
-- Activate to instantly restore 80% health (cooldown 180 seconds).
{ id = "Items.BloodPumpEpic" },
-- BLOOD PUMP / Cyberware / Circulatory System / Legendary
-- Accelerates oxygen supply to the body's cells.
-- Activate to instantly restore 90% health (cooldown 180 seconds).
{ id = "Items.BloodPumpLegendary" },
-- CAMILLO RAM MANAGER / Cyberware / Frontal Cortex / Epic
-- A mod that manages and optimizes RAM use between your brain and your cyberdeck.
-- When your cyberdeck's RAM reaches 2, Instantly free 20% of it.
-- Cooldown 4min.
{ id = "Items.MemoryReplenishmentEpic" },
-- CAMILLO RAM MANAGER / Cyberware / Frontal Cortex / Legendary
-- A mod that manages and optimizes RAM use between your brain and your cyberdeck.
-- When your cyberdeck's RAM reaches 2, Instantly free 30% of it.
-- Cooldown 4min.
{ id = "Items.MemoryReplenishmentLegendary" },
-- CATARESIST / Cyberware / Immune System / Common
-- Hybrid cyberware that protects the body from the inside and out.
-- Increases all resistances by 8%.
{ id = "Items.ResistancesBoosterCommon" },
-- CATARESIST / Cyberware / Immune System / Uncommon
-- Hybrid cyberware that protects the body from the inside and out.
-- Increases all resistances by 13%.
{ id = "Items.ResistancesBoosterUncommon" },
-- CATARESIST / Cyberware / Immune System / Epic
-- Hybrid cyberware that protects the body from the inside and out.
-- Increases all resistances by 23%.
{ id = "Items.ResistancesBoosterEpic" },
-- CATARESIST / Cyberware / Immune System / Legendary
-- Hybrid cyberware that protects the body from the inside and out.
-- Increases all resistances by 35%.
{ id = "Items.ResistancesBoosterLegendary" },
-- DENSE MARROW / Cyberware / Skeleton / Uncommon
-- Increases body weight and the power behind melee attacks.
-- Increases Stamina cost of melee attacks by 10%, but increases base damage of melee weapons by 7%.
{ id = "Items.DenseMarrowUncommon" },
-- DENSE MARROW / Cyberware / Skeleton / Rare
-- Increases body weight and the power behind melee attacks.
-- Increases Stamina cost of melee attacks by 10%, but increases base damage of melee weapons by 15%.
{ id = "Items.DenseMarrowRare" },
-- DENSE MARROW / Cyberware / Skeleton / Epic
-- Increases body weight and the power behind melee attacks.
-- Increases Stamina cost of melee attacks by 10%, but increases base damage of melee weapons by 25%.
{ id = "Items.DenseMarrowEpic" },
-- DETOXIFIER / Cyberware / Immune System / Rare
-- Performs blood dialysis.
-- Grants Immunity to Poison.
{ id = "Items.ToxinCleanser" },
-- DYNALAR SANDEVISTAN MK.1 / Cyberware / Operating System / Uncommon
-- The Sandevistan from Dynalar has been a standard go-to for soldiers and mercenaries. It guarantees not only speed, but built-in combat support at a very attractive price.
-- Slows time by 50% for 8 sec.
-- Cooldown 30 sec.
-- Increase any damage dealt by 5% when Sandevistan is active.
{
id = "Items.SandevistanC2MK1",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- DYNALAR SANDEVISTAN MK.2 / Cyberware / Operating System / Rare
-- The upgraded Sandevistan from Dynalar. No need to sugarcoat it - it's just better-quality components and optimized software. The results speak for themselves - increased sensory perceptiveness and effectiveness in combat situations.
-- Slows time by 25% for 12 sec.
-- Cooldown 30 sec.
-- Increase any damage dealt by 10% when Sandevistan is active.
{
id = "Items.SandevistanC2MK2",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- DYNALAR SANDEVISTAN MK.3 / Cyberware / Operating System / Epic
-- Thanks to trademarked synaptic transmitters, this Sandevistan from Dynalar ensures even more comfort and control in combat situations as well as increased neuromuscular tension.
-- Slows time by 50% for 16 sec.
-- Cooldown 30 sec.
-- Increase any damage dealt by 15% when Sandevistan is active.
{
id = "Items.SandevistanC2MK3",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- DYNALAR SANDEVISTAN MK.4 / Cyberware / Operating System / Legendary
-- Dynalar's greatest achievement to date. Thanks to collaboration with Swiss corporation Bieri-1's neuro-research labs, this implant boasts lightning-fast connection speeds, combat system flexibility and optimized combat perceptiveness. Ideal for specialists.
-- Slows time by 25% for 16 sec.
-- Cooldown 30 sec.
-- Increase any damage dealt by 15% when Sandevistan is active.
-- Increase Crit Chance by 15% when Sandevistan is active.
{
id = "Items.SandevistanC2MK4",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- EX-DISK / Cyberware / Frontal Cortex / Rare
-- An implant that increases the brain's capacity to store and process information.
-- Increases your cyberdeck's max Ram units by 1.
{ id = "Items.BrainCapacityBoosterRare" },
-- EX-DISK / Cyberware / Frontal Cortex / Epic
-- An implant that increases the brain's capacity to store and process information.
-- Increases your cyberdeck's max Ram units by 3.
{ id = "Items.BrainCapacityBoosterEpic" },
-- EX-DISK / Cyberware / Frontal Cortex / Legendary
-- An implant that increases the brain's capacity to store and process information.
-- Increases your cyberdeck's max Ram units by 5.
{ id = "Items.BrainCapacityBoosterLegendary" },
-- FEEDBACK CIRCUIT / Cyberware / Circulatory System / Rare
-- Additional circuitry that links your body and cyberware with weapons and devices.
-- Instantly restores 3% Health after you discharge a fully charged weapon with a hit to an enemy.
{ id = "Items.DischargeConnectorRare" },
-- FEEDBACK CIRCUIT / Cyberware / Circulatory System / Epic
-- Additional circuitry that links your body and cyberware with weapons and devices.
-- Instantly restores 6% Health after you discharge a fully charged weapon with a hit to an enemy.
{ id = "Items.DischargeConnectorEpic" },
-- FEEDBACK CIRCUIT / Cyberware / Circulatory System / Legendary
-- Additional circuitry that links your body and cyberware with weapons and devices.
-- Instantly restores 10% Health after you discharge a fully charged weapon with a hit to an enemy.
{ id = "Items.DischargeConnectorLegendary" },
-- FIREPROOF COATING / Cyberware / Integumentary System / Rare
-- A coating that protects the body against fire.
-- Grants Immunity to Burn.
{ id = "Items.FireproofSkin" },
-- FORTIFIED ANKLES / Cyberware / Legs / Rare
-- Ankle joints reinforced with plastic fibers and nanogel-filled joint capsules
-- Hold "Jump" to charge the power of the jump, then release to jump.
{ id = "Items.ReinforcedMusclesRare" },
-- FORTIFIED ANKLES / Cyberware / Legs / Epic
-- Ankle joints reinforced with plastic fibers and nanogel-filled joint capsules
-- Hold "Jump" to charge the power of the jump, then release to jump.
-- Enables you to perform hover jumps.
{ id = "Items.ReinforcedMusclesEpic" },
-- FUYUTSUI ELECTRONICS MK.1 / Cyberware / Operating System / Common
-- "Good enough" - as once described by a user of this popular, but low-spec cyberdeck.
-- Allows you to perform quickhacks on targets and devices while scanning.
{
id = "Items.FuyutsuiCommonMKI",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
},
},
-- FUYUTSUI TINKERER MK.3 / Cyberware / Operating System / Legendary
-- Unique, modified and unavailable to the average consumer. Perfectly suited for those who want to achieve much, but don't exactly have the skills to match.
-- Allows you to perform quickhacks on targets and devices while scanning.
-- Increases cyberdeck ram recovery rate by 9 unit(s) per 60 sec.
-- Increases combat quickhacks duration by 50%.
-- Increaces quickhacks spread distance by 40%.
{
id = "Items.FuyutsuiTinkererLegendaryMKIII",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
{ slot = "Program4" },
{ slot = "Program5" },
{ slot = "Program6" },
},
},
-- GORILLA ARMS / Cyberware / Arms / Rare
-- Classic and reliable replacements for natural limbs, suited for all kinds of hard labor.
-- Classic and Reliable replacements for natural limbs, suited for all kinds of hard labor.
{
id = "Items.StrongArms",
slots = {
{ slot = "Knuckles" },
{ slot = "Battery" },
{ slot = "Mod" },
},
},
-- GORILLA ARMS / Cyberware / Arms / Epic
-- Classic and reliable replacements for natural limbs, suited for all kinds of hard labor.
-- Classic and Reliable replacements for natural limbs, suited for all kinds of hard labor.
{
id = "Items.StrongArmsEpic",
slots = {
{ slot = "Knuckles" },
{ slot = "Battery" },
{ slot = "Mod" },
},
},
-- GORILLA ARMS / Cyberware / Arms / Legendary
-- Classic and reliable replacements for natural limbs, suited for all kinds of hard labor.
-- Classic and Reliable replacements for natural limbs, suited for all kinds of hard labor.
{
id = "Items.StrongArmsLegendary",
slots = {
{ slot = "Knuckles" },
{ slot = "Battery" },
{ slot = "Mod" },
},
},
-- GROUNDING PLATE / Cyberware / Integumentary System / Rare
-- Uses a smart-transmitter system to protect the user by diffusing and dispersing shocks from electrical hazards.
-- Grants Immunity to Shock.
{ id = "Items.GroundingPlating" },
-- HEAL-ON-KILL / Cyberware / Frontal Cortex / Common
-- A combat implant that regulates hormones and regenerates Health after an enemy is defeated.
-- Instantly restores 2% Health after defeating an enemy.
{ id = "Items.HealOnKillCommon" },
-- HEAL-ON-KILL / Cyberware / Frontal Cortex / Uncommon
-- A combat implant that regulates hormones and regenerates Health after an enemy is defeated.
-- Instantly restores 3% Health after defeating an enemy.
{ id = "Items.HealOnKillUncommon" },
-- HEAL-ON-KILL / Cyberware / Frontal Cortex / Epic
-- A combat implant that regulates hormones and regenerates Health after an enemy is defeated.
-- Instantly restores 6% Health after defeating an enemy.
{ id = "Items.HealOnKillEpic" },
-- HEAL-ON-KILL / Cyberware / Frontal Cortex / Legendary
-- A combat implant that regulates hormones and regenerates Health after an enemy is defeated.
-- Instantly restores 10% Health after defeating an enemy.
{ id = "Items.HealOnKillLegendary" },
-- HEAT CONVERTER / Cyberware / Integumentary System / Epic
-- A temperature regulation system for your body and cyberware.
-- When affected by Burn, instead of receiving damage from it, you deal 10% more damage.
{ id = "Items.HeatUsingBooster" },
-- INDUCTOR / Cyberware / Immune System / Epic
-- Invigorates the immune system after receiving an external high-voltage stimulus.
-- When affected by Shock and EMP, Amor increases by 50% instead of taking damage.
{ id = "Items.ReversePowerInductor" },
-- KERENZIKOV / Cyberware / Nervous System / Common
-- A classic reflex booster.
-- Allows you to aim and shoot while dodging.
-- Slows time by 50% for 1.5 sec.
-- when blocking, aiming or attacking during a slide or doge.
-- cooldown 5 sec.
{ id = "Items.KerenzikovCommon" },
-- KERENZIKOV / Cyberware / Nervous System / Uncommon
-- A classic reflex booster.
-- Allows you to aim and shoot while dodging.
-- Slows time by 60% for 1.8 sec.
-- when blocking, aiming or attacking during a slide or doge.
-- cooldown 5 sec.
{ id = "Items.KerenzikovUncommon" },
-- KERENZIKOV / Cyberware / Nervous System / Rare
-- A classic reflex booster.
-- Allows you to aim and shoot while dodging.
-- Slows time by 70% for 2 sec.
-- when blocking, aiming or attacking during a slide or doge.
-- cooldown 5 sec.
{ id = "Items.KerenzikovRare" },
-- KERENZIKOV / Cyberware / Nervous System / Epic
-- A classic reflex booster.
-- Allows you to aim and shoot while dodging.
-- Slows time by 80% for 2.5 sec.
-- when blocking, aiming or attacking during a slide or doge.
-- cooldown 5 sec.
{ id = "Items.KerenzikovEpic" },
-- KERENZIKOV / Cyberware / Nervous System / Legendary
-- A classic reflex booster.
-- Allows you to aim and shoot while dodging.
-- Slows time by 90% for 3.5 sec.
-- when blocking, aiming or attacking during a slide or doge.
-- cooldown 5 sec.
{ id = "Items.KerenzikovLegendary" },
-- KIROSHI OPTICS MK.1 / Cyberware / Ocular System / Common
-- Kiroshi optical cyberware is a widely popular suite composed of electro-neural enhancements with environment-scanning functionality.
-- Ehances your vision.
-- 1 Empty cyberware mod slot.
{
id = "Items.KiroshiOptics",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- KIROSHI OPTICS MK.2 / Cyberware / Ocular System / Rare
-- An upgraded model of Kiroshi optics manufactured from high-end components and accelerated scanning algorithms guarantees its users 100% customer satisfaction.
-- Ehances your vision.
-- 2 Empty cyberware mod slot.
{
id = "Items.KiroshiOpticsRare",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- KIROSHI OPTICS MK.3 / Cyberware / Ocular System / Epic
-- This advanced Kiroshi optical system is designed for the most demanding users. It incorporates the latest breakthroughs in neural-link technology, unprecedented support of optic function and the most powerful scanning algorithms on the market.
-- Ehances your vision.
-- 3 Empty cyberware mod slot.
{
id = "Items.KiroshiOpticsEpic",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- LIMBIC SYSTEM ENHANCEMENT / Cyberware / Frontal Cortex / Common
-- Cyberware that supports the part of the brain responsible for aggression and fear response.
-- Increases Crit Chance By 7%.
{ id = "Items.LimbicSystemEnhancementCommon" },
-- LIMBIC SYSTEM ENHANCEMENT / Cyberware / Frontal Cortex / Rare
-- Cyberware that supports the part of the brain responsible for aggression and fear response.
-- Increases Crit Chance By 15%.
{ id = "Items.LimbicSystemEnhancementRare" },
-- LIMBIC SYSTEM ENHANCEMENT / Cyberware / Frontal Cortex / Legendary
-- Cyberware that supports the part of the brain responsible for aggression and fear response.
-- Increases Crit Chance By 25%.
{ id = "Items.LimbicSystemEnhancementLegendary" },
-- LYNX PAWS / Cyberware / Legs / Epic
-- A leg modification that softens the sound dynamics of movement.
-- Allows you to move and run more quietly.
-- The sound of your foots will not carry as far.
{ id = "Items.CatPaws" },
-- MANEUVERING SYSTEM / Cyberware / Nervous System / Rare
-- A subprogram that enhances nervous system function.
-- Allows you to preform dodges in midair.
{ id = "Items.NervousSystemDischarge" },
-- MANTIS BLADES / Cyberware / Arms / Rare
-- Arm blades designed with lethality and concealment in mind. As effective as they are flashy.
-- Arm blades designed with lethality and concealment in mind.
-- As effective as they are flashy.
{
id = "Items.MantisBlades",
slots = {
{ slot = "Edge" },
{ slot = "Rotor" },
{ slot = "Mod" },
},
},
-- MANTIS BLADES / Cyberware / Arms / Epic
-- Arm blades designed with lethality and concealment in mind. As effective as they are flashy.
-- Arm blades designed with lethality and concealment in mind.
-- As effective as they are flashy.
{
id = "Items.MantisBladesEpic",
slots = {
{ slot = "Edge" },
{ slot = "Rotor" },
{ slot = "Mod" },
},
},
-- MANTIS BLADES / Cyberware / Arms / Legendary
-- Arm blades designed with lethality and concealment in mind. As effective as they are flashy.
-- Arm blades designed with lethality and concealment in mind.
-- As effective as they are flashy.
{
id = "Items.MantisBladesLegendary",
slots = {
{ slot = "Edge" },
{ slot = "Rotor" },
{ slot = "Mod" },
},
},
-- MECHATRONIC CORE / Cyberware / Frontal Cortex / Common
-- Provides information about the weak points of both mass-produced and some lesser-known machines.
-- Increases damage to drones, mechs and robots by 10%.
{ id = "Items.RoboticCoreCommon" },
-- MECHATRONIC CORE / Cyberware / Frontal Cortex / Uncommon
-- Provides information about the weak points of both mass-produced and some lesser-known machines.
-- Increases damage to drones, mechs and robots by 20%.
{ id = "Items.RoboticCoreUncommon" },
-- MECHATRONIC CORE / Cyberware / Frontal Cortex / Rare
-- Provides information about the weak points of both mass-produced and some lesser-known machines.
-- Increases damage to drones, mechs and robots by 30%.
{ id = "Items.RoboticCoreRare" },
-- MECHATRONIC CORE / Cyberware / Frontal Cortex / Epic
-- Provides information about the weak points of both mass-produced and some lesser-known machines.
-- Increases damage to drones, mechs and robots by 40%.
{ id = "Items.RoboticCoreEpic" },
-- MECHATRONIC CORE / Cyberware / Frontal Cortex / Legendary
-- Provides information about the weak points of both mass-produced and some lesser-known machines.
-- Increases damage to drones, mechs and robots by 50%.
{ id = "Items.RoboticCoreLegendary" },
-- MEMORY BOOST / Cyberware / Frontal Cortex / Common
-- A module that optimizes the sync between brain and cyberware.
-- Defeating an enemy instantly removes 1 cyberdeck Ram unit(s).
{ id = "Items.MemoryBoostCommon" },
-- MEMORY BOOST / Cyberware / Frontal Cortex / Uncommon
-- A module that optimizes the sync between brain and cyberware.
-- Defeating an enemy instantly removes 2 cyberdeck Ram unit(s).
{ id = "Items.MemoryBoostUncommon" },
-- MEMORY BOOST / Cyberware / Frontal Cortex / Rare
-- A module that optimizes the sync between brain and cyberware.
-- Defeating an enemy instantly removes 3 cyberdeck Ram unit(s).
{ id = "Items.MemoryBoostRare" },
-- MEMORY BOOST / Cyberware / Frontal Cortex / Epic
-- A module that optimizes the sync between brain and cyberware.
-- Defeating an enemy instantly removes 4 cyberdeck Ram unit(s).
{ id = "Items.MemoryBoostEpic" },
-- METABOLIC EDITOR / Cyberware / Immune System / Epic
-- An implant designed to assist liver and pancreas function against poisons.
-- Poison effects cause yo to regenerate Health instead of taking damage.
{ id = "Items.ReverseMetabolicEnhancer" },
-- MICROGENERATOR / Cyberware / Circulatory System / Common
-- A small, high-voltage generator that packs a shocking punch.
-- When your Health drops to 15%, releases an electroshock that deals damage equal to 20% of the target enemy's max Health.
{ id = "Items.MicroGeneratorCommon" },
-- MICROGENERATOR / Cyberware / Circulatory System / Uncommon
-- A small, high-voltage generator that packs a shocking punch.
-- When your Health drops to 15%, releases an electroshock that deals damage equal to 30% of the target enemy's max Health.
{ id = "Items.MicroGeneratorUncommon" },
-- MICROGENERATOR / Cyberware / Circulatory System / Rare
-- A small, high-voltage generator that packs a shocking punch.
-- When your Health drops to 15%, releases an electroshock that deals damage equal to 40% of the target enemy's max Health.
{ id = "Items.MicroGeneratorRare" },
-- MICROGENERATOR / Cyberware / Circulatory System / Epic
-- A small, high-voltage generator that packs a shocking punch.
-- When your Health drops to 15%, releases an electroshock that deals damage equal to 40% of the target enemy's max Health.
-- Applies Shock to enemies.
{ id = "Items.MicroGeneratorEpic" },
-- MICROGENERATOR / Cyberware / Circulatory System / Legendary
-- A small, high-voltage generator that packs a shocking punch.
-- When your Health drops to 15%, releases an electroshock that deals damage equal to 50% of the target enemy's max Health.
-- Applies Shock to enemies.
{ id = "Items.MicroGeneratorLegendary" },
-- MICROROTORS / Cyberware / Skeleton / Common
-- Improves agility in melee combat.
-- Increases Attack speed by 5%.
{ id = "Items.CyberRotorsCommon" },
-- MICROROTORS / Cyberware / Skeleton / Uncommon
-- Improves agility in melee combat.
-- Increases Attack speed by 10%.
{ id = "Items.CyberRotorsUncommon" },
-- MICROROTORS / Cyberware / Skeleton / Rare
-- Improves agility in melee combat.
-- Increases Attack speed by 15%.
{ id = "Items.CyberRotorsRare" },
-- MICROROTORS / Cyberware / Skeleton / Epic
-- Improves agility in melee combat.
-- Increases Attack speed by 20%.
{ id = "Items.CyberRotorsEpic" },
-- MICROROTORS / Cyberware / Skeleton / Legendary
-- Improves agility in melee combat.
-- Increases Attack speed by 25%.
{ id = "Items.CyberRotorsLegendary" },
-- MICROVIBRATION GENERATOR / Cyberware / Skeleton / Uncommon
-- Causes melee weapons to vibrate at a frequency that causes more destruction.
-- Increases base damage of melee weapons by 5%.
{ id = "Items.MicroVibrationsGeneratorUncommon" },
-- MICROVIBRATION GENERATOR / Cyberware / Skeleton / Rare
-- Causes melee weapons to vibrate at a frequency that causes more destruction.
-- Increases base damage of melee weapons by 10%.
{ id = "Items.MicroVibrationsGeneratorRare" },
-- MICROVIBRATION GENERATOR / Cyberware / Skeleton / Epic
-- Causes melee weapons to vibrate at a frequency that causes more destruction.
-- Increases base damage of melee weapons by 15%.
{ id = "Items.MicroVibrationsGeneratorEpic" },
-- MILITECH "FALCON" SANDEVISTAN MK.5 / Cyberware / Operating System / Legendary
-- Manufactured by Militech, the "Falcon" is hands down the best and most advanced Sandevistan model out there. Previously used only by elite Militech soldiers, its now available to the average consumer. The nickname is no accident - the peregrine falcon was once one of the fastest animals in the world, as this implant is among cyberware.
-- Slows time by 30% for 18 sec.
-- Increase any damage dealt by 15% when Sandevistan is active.
-- Increase Crit Chance by 20% and Crit Damage by 35% when Sandevistan is active.
-- Cooldown 60 sec.
{
id = "Items.SandevistanC4MK5",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- MILITECH BERSERK MK.5 / Cyberware / Operating System / Legendary
-- The only official Berserk implant from Militech available on the market, but an exceptionally fine one at that. Its genius lies in being nanopowered, making it highly suited for regenerative purposes.
-- When activated, ranged weapon recoil and sway -15%, melee damage +15% and Armor +10% for 10 seconds.
-- Max health and stamina +40%, defeating enemies restores 5% health.
-- Cooldown 60 seconds.
{
id = "Items.BerserkC4MK5",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- MILITECH PARALINE / Cyberware / Operating System / Common
-- Not the most powerful cyberdeck on the market, but capable of performing multiple tasks - even if it does require a little patience.
-- Allows you to perform quickhacks on targets and devices while scanning.
{
id = "Items.MilitechParaline",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
},
},
-- MONOWIRE / Cyberware / Arms / Rare
-- Whip-like monofilament wire with a cutting edge only a molecule wide.
-- The Monowire charges when equipped but not in combat.
-- Attacks with a charged wire deal bonus damage based on the charge level.
-- Charge level and bonus damage dealt decline with each attack.
{
id = "Items.NanoWires",
slots = {
{ slot = "Cable" },
{ slot = "Battery" },
{ slot = "Mod" },
},
},
-- MONOWIRE / Cyberware / Arms / Epic
-- Whip-like monofilament wire with a cutting edge only a molecule wide.
-- The Monowire charges when equipped but not in combat.
-- Attacks with a charged wire deal bonus damage based on the charge level.
-- Charge level and bonus damage dealt decline with each attack.
{
id = "Items.NanoWiresEpic",
slots = {
{ slot = "Cable" },
{ slot = "Battery" },
{ slot = "Mod" },
},
},
-- MONOWIRE / Cyberware / Arms / Legendary
-- Whip-like monofilament wire with a cutting edge only a molecule wide.
-- The Monowire charges when equipped but not in combat.
-- Attacks with a charged wire deal bonus damage based on the charge level.
-- Charge level and bonus damage dealt decline with each attack.
{
id = "Items.NanoWiresLegendary",
slots = {
{ slot = "Cable" },
{ slot = "Battery" },
{ slot = "Mod" },
},
},
-- MOORE TECH BERSERK MK.1 / Cyberware / Operating System / Uncommon
-- A classic implant, one of the more popular "Berserk" model made by Moore Technologies. Tested and proven in high-stakes combat.
-- When activated, ranged weapon recoil and sway -10%, melee damage +10% and Armor +5% for 10 seconds.
-- Cooldown 60 seconds.
{
id = "Items.BerserkC1MK1",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- MOORE TECH BERSERK MK.2 / Cyberware / Operating System / Rare
-- The improved Berserk model manufactured by Moore Technologies, now with updated hormone-regulating algorithms.
-- When activated, ranged weapon recoil and sway -10%, melee damage +15% and Armor +5% for 15 seconds.
-- Max Health +10%.
-- Cooldown 60 seconds.
{
id = "Items.BerserkC1MK2",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- MOORE TECH BERSERK MK.3 / Cyberware / Operating System / Epic
-- The standard bearer of all Berserk models from Moore Technologies. Increased efficiency and faster responsiveness thanks to trademarked composite materials.
-- When activated, ranged weapon recoil and sway -10%, melee damage +15% and Armor +10% for 30 seconds.
-- Max Health +20%.
-- Defeating enemies restore 2% health.
-- Cooldown 60 seconds.
{
id = "Items.BerserkC1MK3",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- NANORELAYS / Cyberware / Nervous System / Uncommon
-- Improves the speed of nerve impulses.
-- Increases Sandevistan and Kerenzikov duration by 0.5 sec.
{ id = "Items.ImprovedReactionUncommon" },
-- NANORELAYS / Cyberware / Nervous System / Rare
-- Improves the speed of nerve impulses.
-- Increases Sandevistan and Kerenzikov duration by 1 sec.
{ id = "Items.ImprovedReactionRare" },
-- NANORELAYS / Cyberware / Nervous System / Epic
-- Improves the speed of nerve impulses.
-- Increases Sandevistan and Kerenzikov duration by 2 sec.
{ id = "Items.ImprovedReactionEpic" },
-- NEOFIBER / Cyberware / Nervous System / Common
-- Synthetic muscle fibers.
-- Increases evasion by 3%.
{ id = "Items.NeoFiberCommon" },
-- NEOFIBER / Cyberware / Nervous System / Uncommon
-- Synthetic muscle fibers.
-- Increases evasion by 6%.
{ id = "Items.NeoFiberUncommon" },
-- NEOFIBER / Cyberware / Nervous System / Rare
-- Synthetic muscle fibers.
-- Increases evasion by 9%.
{ id = "Items.NeoFiberRare" },
-- NEOFIBER / Cyberware / Nervous System / Epic
-- Synthetic muscle fibers.
-- Increases evasion by 12%.
{ id = "Items.NeoFiberEpic" },
-- NEOFIBER / Cyberware / Nervous System / Legendary
-- Synthetic muscle fibers.
-- Increases evasion by 15%.
{ id = "Items.NeoFiberLegendary" },
-- NETWATCH NETDRIVER MK.5 / Cyberware / Operating System / Legendary
-- A cyberdeck series used by the best NetWatch agents and a frightening beast in terms of its offensive capabilities. It's best if NetWatch didn't catch you using this.
-- Allows yout to preform quickhacks on targets and devices while scanning.
-- Offensive quickhacks can be uploaded to 3 targets within a 6-meter radius.
-- Increases damage dealt by quickhacks by 30%.
-- Increases cyberdeck RAM recovery rare by 9 unit(s) per 60 sec.
-- Increases quickhack spread distance by 60%.
{
id = "Items.NetwatchNetdriverLegendaryMKV",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
{ slot = "Program4" },
{ slot = "Program5" },
{ slot = "Program6" },
},
},
-- OPTICAL CAMO / Cyberware / Integumentary System / Rare
-- Makes the user impossible to locate in visible spectrum light.
-- Activate to turn almost invisible for 15 seconds, greatly reducing the likelihood of detection.
-- Cooldown 60 seconds.
{ id = "Items.OpticalCamoRare" },
-- OPTICAL CAMO / Cyberware / Integumentary System / Epic
-- Makes the user impossible to locate in visible spectrum light.
-- Activate to turn almost invisible for 5 seconds, greatly reducing the likelihood of detection.
-- Cooldown 60 seconds.
{ id = "Items.OpticalCamoEpic" },
-- OPTICAL CAMO / Cyberware / Integumentary System / Legendary
-- Makes the user impossible to locate in visible spectrum light.
-- Activate to turn almost invisible for 10 seconds, greatly reducing the likelihood of detection.
-- Cooldown 60 seconds.
{ id = "Items.OpticalCamoLegendary" },
-- PAIN EDITOR / Cyberware / Immune System / Legendary
-- An immune system enhancement valued highly on the streets.
-- Reduces all incoming damage by 10%.
{ id = "Items.PainReductor" },
-- PROJECTILE LAUNCH SYSTEM / Cyberware / Arms / Rare
-- A missile launcher in the palm of your hand (more or less literally).
-- A missile launcher in the pal of your hand (more or less literally).
{
id = "Items.ProjectileLauncher",
slots = {
{ slot = "Round" },
{ slot = "Wiring" },
{ slot = "Mod" },
},
},
-- PROJECTILE LAUNCH SYSTEM / Cyberware / Arms / Epic
-- A missile launcher in the palm of your hand (more or less literally).
-- A missile launcher in the pal of your hand (more or less literally).
{
id = "Items.ProjectileLauncherEpic",
slots = {
{ slot = "Round" },
{ slot = "Wiring" },
{ slot = "Mod" },
},
},
-- PROJECTILE LAUNCH SYSTEM / Cyberware / Arms / Legendary
-- A missile launcher in the palm of your hand (more or less literally).
-- A missile launcher in the pal of your hand (more or less literally).
{
id = "Items.ProjectileLauncherLegendary",
slots = {
{ slot = "Round" },
{ slot = "Wiring" },
{ slot = "Mod" },
},
},
-- QIANT "WARP DANCER" SANDEVISTAN MK.5 / Cyberware / Operating System / Legendary
-- QianT's pride and joy - the company's latest Sandevistan model has already reached a legendary status with its astounding craftsmanship and precision, while its artificial neural network-powered software is virtually unmatched in the market.
-- Slows time by 10% for 8 sec.
-- Increase any damage dealt by 15% when Sandevistan is active.
-- Increase Crit Chance by 10% and Crit Damage by 50% when Sandevistan is active.
-- Cooldown 30 sec.
{
id = "Items.SandevistanC3MK5",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- QIANT SANDEVISTAN MK.4 / Cyberware / Operating System / Legendary
-- The Sandevistan manufactured by QianT is top-shelf cyberware with unique capabilities for professionals who specialize in speed, precision and killing. Due to its limited availability, this model is only sought after by the most discerning users.
-- Slows time by 25% for 12 sec.
-- Cooldown 30 sec.
-- Increase any damage dealt by 15% when Sandevistan is active.
-- Increase Crit Chance by 15% when Sandevistan is active.
{
id = "Items.SandevistanC3MK4",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- RAM UPGRADE / Cyberware / Frontal Cortex / Common
-- An upgrade to your system's random-access memory to support processing speed.
-- Increases cyberdeck RAM recovery rate by 0.05 units(s) per second.
{ id = "Items.FastAccessMemoryCommon" },
-- RAM UPGRADE / Cyberware / Frontal Cortex / Uncommon
-- An upgrade to your system's random-access memory to support processing speed.
-- Increases cyberdeck RAM recovery rate by 0.1 units(s) per second.
{ id = "Items.FastAccessMemoryUncommon" },
-- RAM UPGRADE / Cyberware / Frontal Cortex / Rare
-- An upgrade to your system's random-access memory to support processing speed.
-- Increases cyberdeck RAM recovery rate by 0.15 units(s) per second.
{ id = "Items.FastAccessMemoryRare" },
-- RAVEN MICROCYBER MK.3 / Cyberware / Operating System / Epic
-- Some call these decks battleships. When it comes to system security and fortified anti-theft protocols, it's a foolproof piece of machinery.
-- Allows you to perform quickhacks on targets and devices while scanning.
-- Increases time it takes for an enemy netrunner to hack you by 50%.
-- Increases quickhack spread distance by 40%.
-- Increases cyberdeck RAM recovery rate by 3 unit(s) per 60 sec.,.
{
id = "Items.RavenEpicMKIII",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
{ slot = "Program4" },
{ slot = "Program5" },
},
},
-- RAVEN MICROCYBER MK.4 / Cyberware / Operating System / Legendary
-- Some call these decks battleships. When it comes to system security and fortified anti-theft protocols, it's a foolproof piece of machinery.
-- Allows you to perform quickhacks on targets and devices while scanning.
-- Increases time it takes for an enemy netrunner to hack you by 100%.
-- Increases quickhack spread distance by 60%.
-- Increases cyberdeck RAM recovery rate by 6 unit(s) per 60 sec.,.
{
id = "Items.RavenLegendaryMKIV",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
{ slot = "Program4" },
{ slot = "Program5" },
{ slot = "Program6" },
},
},
-- REFLEX TUNERS / Cyberware / Nervous System / Common
-- A coprocessor that supports decision-making processes in emergency situations.
-- Slows time by 50% for 2 sec.
-- when your health drops to 25%.
-- Cooldown 60 sec.
{ id = "Items.ReflexRecorderCommon" },
-- REFLEX TUNERS / Cyberware / Nervous System / Uncommon
-- A coprocessor that supports decision-making processes in emergency situations.
-- Slows time by 60% for 2.5 sec.
-- when your health drops to 25%.
-- Cooldown 60 sec.
{ id = "Items.ReflexRecorderUncommon" },
-- REFLEX TUNERS / Cyberware / Nervous System / Rare
-- A coprocessor that supports decision-making processes in emergency situations.
-- Slows time by 70% for 3 sec.
-- when your health drops to 25%.
-- Cooldown 50 sec.
{ id = "Items.ReflexRecorderRare" },
-- REFLEX TUNERS / Cyberware / Nervous System / Legendary
-- A coprocessor that supports decision-making processes in emergency situations.
-- Slows time by 80% for 4 sec.
-- when your health drops to 25%.
-- Cooldown 40 sec.
{ id = "Items.ReflexRecorderLegendary" },
-- REINFORCED TENDONS / Cyberware / Legs / Rare
-- Biomechanical connective tissue supporting leg muscles
-- Press "Jump" while in midair to perform a double jump.
{ id = "Items.BoostedTendonsRare" },
-- SECOND HEART / Cyberware / Circulatory System / Legendary
-- Corrects one of nature's greatest flaws by giving you an second lease on life.
-- Instantly restores 100% of max Health when your Health falls to 0.
-- Cooldown 2 min.
{ id = "Items.SecondHeart" },
-- SELF-ICE / Cyberware / Frontal Cortex / Rare
-- An intrusion countermeasure electronics system that protects cybernetic implants from nasty bugs.
-- Negates Effectts of enemy quickhacks.
-- Cooldown 45 Sec.
{ id = "Items.AntiVirus" },
-- SEOCHO ELECTRONICS MK.1 / Cyberware / Operating System / Uncommon
-- NetWatch statistics show this is the most common deck for any kind of break-in. Why? Because it's cost-effective, user-friendly and doesn't crap out when you need something done quickly and quietly.
-- Allows you to perform quickhacks on targets and devicese while scanning.
-- Decreases the RAM cost of Covert Quickhacks by 1.
{
id = "Items.SeachoUncommonMKI",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
},
},
-- SEOCHO ELECTRONICS MK.2 / Cyberware / Operating System / Rare
-- NetWatch statistics show this is the most common deck for any kind of break-in. Why? Because it's cost-effective, user-friendly and doesn't crap out when you need something done quickly and quietly.
-- Allows you to perform quickhacks on targets and devicese while scanning.
-- Decreases the RAM cost of Covert Quickhacks by 1.
-- Reduces quickhack Upload time by 25%.
{
id = "Items.SeachoRareMKII",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
{ slot = "Program4" },
},
},
-- SHOCK-N-AWE / Cyberware / Immune System / Common
-- An effective self-defense tool engineered in Shanghai.
-- After taking damage, there is a 2% chance of release a large electroshock that deals damage to nearby enemies.
{ id = "Items.ElectroshockMechanismCommon" },
-- SHOCK-N-AWE / Cyberware / Immune System / Uncommon
-- An effective self-defense tool engineered in Shanghai.
-- After taking damage, there is a 4% chance of release a large electroshock that deals damage to nearby enemies.
{ id = "Items.ElectroshockMechanismUncommon" },
-- SHOCK-N-AWE / Cyberware / Immune System / Epic
-- An effective self-defense tool engineered in Shanghai.
-- After taking damage, there is a 8% chance of release a large electroshock that deals damage to nearby enemies.
{ id = "Items.ElectroshockMechanismEpic" },
-- SHOCK-N-AWE / Cyberware / Immune System / Legendary
-- An effective self-defense tool engineered in Shanghai.
-- After taking damage, there is a 10% chance of release a large electroshock that deals damage to nearby enemies.
{ id = "Items.ElectroshockMechanismLegendary" },
-- SMART LINK / Cyberware / Hands / Rare
-- Cyberware that allows swift, direct, low-latency connection with compatible objects such as a firearms or implants, while also increasing effectiveness and handling.
-- Cyberware taht allows swift, direct, low-latancy connection with compatible objects such as fires or implants, while also increasing effectiveness and handling.
{ id = "Items.SmartLinkRare" },
-- SMART LINK / Cyberware / Hands / Epic
-- Cyberware that allows swift, direct, low-latency connection with compatible objects such as a firearms or implants, while also increasing effectiveness and handling.
-- Cyberware taht allows swift, direct, low-latancy connection with compatible objects such as fires or implants, while also increasing effectiveness and handling.
{ id = "Items.SmartLinkEpic" },
-- SMART LINK / Cyberware / Hands / Legendary
-- Cyberware that allows swift, direct, low-latency connection with compatible objects such as a firearms or implants, while also increasing effectiveness and handling.
-- Cyberware taht allows swift, direct, low-latancy connection with compatible objects such as fires or implants, while also increasing effectiveness and handling.
{ id = "Items.SmartLinkLegendary" },
-- STEPHENSON TECK MK. 2 / Cyberware / Operating System / Rare
-- A cyberdeck that, according to some, can prolong orgasms. Thanks to its optimized protocols, this preem-tier machine will squeeze the effectiveness out of your daemons to the very last drop.
-- Allows you to perform quickhacks on targets and devicese while scanning.
-- Quickhack cooldown reduced by 30% Increase combat quickhack duration by 30%.
{
id = "Items.StephensonRareMKII",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
{ slot = "Program4" },
},
},
-- STEPHENSON TECK MK. 3 / Cyberware / Operating System / Epic
-- A cyberdeck that, according to some, can prolong orgasms. Thanks to its optimized protocols, this preem-tier machine will squeeze the effectiveness out of your daemons to the very last drop.
-- Allows you to perform quickhacks on targets and devicese while scanning.
-- Quickhack cooldown reduced by 45% Increase combat quickhack duration by 40%.
{
id = "Items.StephensonEpicMKIII",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
{ slot = "Program4" },
{ slot = "Program5" },
},
},
-- STEPHENSON TECK MK. 4 / Cyberware / Operating System / Legendary
-- A cyberdeck that, according to some, can prolong orgasms. Thanks to its optimized protocols, this preem-tier machine will squeeze the effectiveness out of your daemons to the very last drop.
-- Allows you to perform quickhacks on targets and devicese while scanning.
-- Quickhack cooldown reduced by 45% Increase combat quickhack duration by 50%.
-- Reduces quickhack upload time by 25%.
{
id = "Items.StephensonLegendaryMKIV",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
{ slot = "Program4" },
{ slot = "Program5" },
{ slot = "Program6" },
},
},
-- SUBDERMAL ARMOR / Cyberware / Integumentary System / Common
-- A major hit on the armor market for decades.
-- Increases armor by 20.
{ id = "Items.SubdermalArmorCommon" },
-- SUBDERMAL ARMOR / Cyberware / Integumentary System / Uncommon
-- A major hit on the armor market for decades.
-- Increases armor by 50.
{ id = "Items.SubdermalArmorUncommon" },
-- SUBDERMAL ARMOR / Cyberware / Integumentary System / Rare
-- A major hit on the armor market for decades.
-- Increases armor by 90.
{ id = "Items.SubdermalArmorRare" },
-- SUBDERMAL ARMOR / Cyberware / Integumentary System / Epic
-- A major hit on the armor market for decades.
-- Increases armor by 140.
{ id = "Items.SubdermalArmorEpic" },
-- SUBDERMAL ARMOR / Cyberware / Integumentary System / Legendary
-- A major hit on the armor market for decades.
-- Increases armor by 200.
{ id = "Items.SubdermalArmorLegendary" },
-- SUPRA-DERMAL WEAVE / Cyberware / Integumentary System / Rare
-- Reinforces the bonds between skin cells, making them extremely hard to penetrate.
-- Grants Immunity to Bleeding.
{ id = "Items.MetalCoveredSkin" },
-- SYN-LUNGS / Cyberware / Circulatory System / Common
-- Synthetic tissues designed to increase functional lung tissue surface area.
-- Increases Stamina regen by 5%.
{ id = "Items.IronLungsCommon" },
-- SYN-LUNGS / Cyberware / Circulatory System / Uncommon
-- Synthetic tissues designed to increase functional lung tissue surface area.
-- Increases Stamina regen by 10%.
{ id = "Items.IronLungsUncommon" },
-- SYN-LUNGS / Cyberware / Circulatory System / Rare
-- Synthetic tissues designed to increase functional lung tissue surface area.
-- Increases Stamina regen by 15%.
{ id = "Items.IronLungsRare" },
-- SYN-LUNGS / Cyberware / Circulatory System / Epic
-- Synthetic tissues designed to increase functional lung tissue surface area.
-- Increases Stamina regen by 20%.
{ id = "Items.IronLungsEpic" },
-- SYN-LUNGS / Cyberware / Circulatory System / Legendary
-- Synthetic tissues designed to increase functional lung tissue surface area.
-- Increases Stamina regen by 25%.
{ id = "Items.IronLungsLegendary" },
-- SYNAPTIC ACCELERATOR / Cyberware / Nervous System / Common
-- A neuroprocessor that regulates hormonal balance during threatening situations.
-- Slows time by 25% for 2 sec.
-- when you are detected by enemies.
-- Cooldown 60 sec.
{ id = "Items.SynapticAcceleratorCommon" },
-- SYNAPTIC ACCELERATOR / Cyberware / Nervous System / Uncommon
-- A neuroprocessor that regulates hormonal balance during threatening situations.
-- Slows time by 30% for 2 sec.
-- when you are detected by enemies.
-- Cooldown 60 sec.
{ id = "Items.SynapticAcceleratorUncommon" },
-- SYNAPTIC ACCELERATOR / Cyberware / Nervous System / Rare
-- A neuroprocessor that regulates hormonal balance during threatening situations.
-- Slows time by 30% for 3 sec.
-- when you are detected by enemies.
-- Cooldown 60 sec.
{ id = "Items.SynapticAcceleratorRare" },
-- SYNAPTIC ACCELERATOR / Cyberware / Nervous System / Epic
-- A neuroprocessor that regulates hormonal balance during threatening situations.
-- Slows time by 40% for 3 sec.
-- when you are detected by enemies.
-- Cooldown 60 sec.
{ id = "Items.SynapticAcceleratorEpic" },
-- SYNAPTIC ACCELERATOR / Cyberware / Nervous System / Legendary
-- A neuroprocessor that regulates hormonal balance during threatening situations.
-- Slows time by 50% for 4 sec.
-- when you are detected by enemies.
-- Cooldown 60 sec.
{ id = "Items.SynapticAcceleratorLegendary" },
-- SYNAPTIC SINGAL OPTIMIZER / Cyberware / Skeleton / Common
-- Enhances the body's natural resistance and performance.
-- Increases Health by 20%.
{ id = "Items.EndoskeletonCommon" },
-- SYNAPTIC SINGAL OPTIMIZER / Cyberware / Skeleton / Uncommon
-- Enhances the body's natural resistance and performance.
-- Increases Health by 30%.
{ id = "Items.EndoskeletonUncommon" },
-- SYNAPTIC SINGAL OPTIMIZER / Cyberware / Skeleton / Rare
-- Enhances the body's natural resistance and performance.
-- Increases Health by 40%.
{ id = "Items.EndoskeletonRare" },
-- SYNAPTIC SINGAL OPTIMIZER / Cyberware / Skeleton / Epic
-- Enhances the body's natural resistance and performance.
-- Increases Health by 50%.
{ id = "Items.EndoskeletonEpic" },
-- SYNAPTIC SINGAL OPTIMIZER / Cyberware / Skeleton / Legendary
-- Enhances the body's natural resistance and performance.
-- Increases Health by 60%.
{ id = "Items.EndoskeletonLegendary" },
-- TATTOO: JOHNNY'S SPECIAL / Cyberware / Hands / Common
-- The Arasaka logo... with a few special touches of Johnny's.
{ id = "Items.CasiusTattoo" },
-- TATTOO: TOGETHER FOREVER / Cyberware / Hands / Common
-- J+V 4EVAH
{ id = "Items.SilverhandTattoo" },
-- TATTOO: TYGER CLAWS DERMAL IMPRINT / Cyberware / Hands / Common
-- A Tyger Claws speciality, this dermal ink features effective Smart weapon jamming capabilities. Only for a select few - those Wakako trusts to remain loyal.
{ id = "Items.YakuzaTattoo" },
-- TETRATRONIC MK. 1 / Cyberware / Operating System / Uncommon
-- Tetratronic takes pride in the fact that its decks are indispensable in combat operations around the globe. Even if it's not entirely true, one thing's for sure - these cyberdecks are powerful, effective and optimized for offensive daemons.
-- Allows you to perform quickhacks on targets and devicese while scanning.
-- Increase Damage dealt by quickhacks by 10%.
{
id = "Items.TetratronicUncommonMKI",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
},
},
-- TETRATRONIC MK. 2 / Cyberware / Operating System / Rare
-- Tetratronic takes pride in the fact that its decks are indispensable in combat operations around the globe. Even if it's not entirely true, one thing's for sure - these cyberdecks are powerful, effective and optimized for offensive daemons.
-- Allows you to perform quickhacks on targets and devicese while scanning.
-- Increase Damage dealt by quickhacks by 20%.
-- Reduces the RAM cost of Ultimate quickhacks by 1.
{
id = "Items.TetratronicRareMKII",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
{ slot = "Program4" },
},
},
-- TETRATRONIC MK. 3 / Cyberware / Operating System / Epic
-- Tetratronic takes pride in the fact that its decks are indispensable in combat operations around the globe. Even if it's not entirely true, one thing's for sure - these cyberdecks are powerful, effective and optimized for offensive daemons.
-- Allows you to perform quickhacks on targets and devicese while scanning.
-- Increase Damage dealt by quickhacks by 30%.
-- Reduces the RAM cost of Ultimate quickhacks by 2.
{
id = "Items.TetratronicEpicMKIII",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
{ slot = "Program4" },
{ slot = "Program5" },
},
},
-- TETRATRONIC RIPPLER MK. 4 / Cyberware / Operating System / Legendary
-- This beauty's fit for champions. How come? Because every element of this deck serves one goal - boosting your most powerful and advanced quickhacks.
-- Allows you to perform quickhacks on targets and devicese while scanning.
-- Ultimate quickhacks can spread once.
-- Reduces the RAM cost of Ultimate quickhacks by 3.
-- Reduces quickhack upload time by 75%.
-- Quickhack cooldown reduced by 45%.
{
id = "Items.TetratronicRipplerLegendaryMKIV",
slots = {
{ slot = "Program1" },
{ slot = "Program2" },
{ slot = "Program3" },
{ slot = "Program4" },
{ slot = "Program5" },
{ slot = "Program6" },
},
},
-- TITANIUM BONES / Cyberware / Skeleton / Common
-- Metal-infused bones capable of withstanding heavy loads.
-- Increases carrying capacity by 20%.
{ id = "Items.TitaniumInfusedBonesCommon" },
-- TITANIUM BONES / Cyberware / Skeleton / Uncommon
-- Metal-infused bones capable of withstanding heavy loads.
-- Increases carrying capacity by 40%.
{ id = "Items.TitaniumInfusedBonesUncommon" },
-- TITANIUM BONES / Cyberware / Skeleton / Rare
-- Metal-infused bones capable of withstanding heavy loads.
-- Increases carrying capacity by 60%.
{ id = "Items.TitaniumInfusedBonesRare" },
-- TYROSINE INJECTOR / Cyberware / Circulatory System / Uncommon
-- Enhances intracellular transduction.
-- Increases the breach time of Breach Protocol by 100%.
{ id = "Items.TyrosineInjector" },
-- VISUAL CORTEX SUPPORT / Cyberware / Frontal Cortex / Common
-- A brain mod that improves perception and targeting.
-- Increases Crit Damage by 10%.
{ id = "Items.ImprovedPerceptionCommon" },
-- VISUAL CORTEX SUPPORT / Cyberware / Frontal Cortex / Uncommon
-- A brain mod that improves perception and targeting.
-- Increases Crit Damage by 16%.
{ id = "Items.ImprovedPerceptionUncommon" },
-- VISUAL CORTEX SUPPORT / Cyberware / Frontal Cortex / Epic
-- A brain mod that improves perception and targeting.
-- Increases Crit Damage by 30%.
{ id = "Items.ImprovedPerceptionEpic" },
-- VISUAL CORTEX SUPPORT / Cyberware / Frontal Cortex / Legendary
-- A brain mod that improves perception and targeting.
-- Increases Crit Damage by 45%.
{ id = "Items.ImprovedPerceptionLegendary" },
-- ZETATECH BERSERK MK.4 / Cyberware / Operating System / Legendary
-- Zetatech's Berserk implant will make you into a lean, mean killing machine. Not to mention hard to kill yourself, thanks to its revolutionary nanodermal impact-absorption systems.
-- When activated, reduces weapon recoil and increases melee damage, Armor, Resistances by 10% for 5 seconds.
-- While active, defeating enemies restores 5% health and jumping from a high height create a Shockwave.
-- Cooldown 30 seconds.
-- 3 Mod Slots.
{
id = "Items.BerserkC3MK4",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- ZETATECH BERSERK MK.5 / Cyberware / Operating System / Legendary
-- A true work of beauty from Zetatech - one of the most potent and most valuable Berserk implants on the market. Many private security companies allegedly outfit their mercenaries with this very model.
-- When activated, reduces weapon recoil and increases melee damage, Armor, Resistances by 20% for 10 seconds.
-- While active, defeating enemies restores 5% health and jumping from a high height create a Shockwave.
-- Cooldown 30 seconds.
-- 3 Mod Slots.
{
id = "Items.BerserkC3MK5",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- ZETATECH SANDEVISTAN MK. 2 / Cyberware / Operating System / Rare
-- This Sandevistan from Zetatech is known for its enhanced parameters. It's especially suited for combat situations while also remaining fairly user-friendly.
-- Slows time by 50% for 12 sec.
-- Cooldown 30 sec.
-- Increase Crit Chance by 15% when Sandevistan is active.
{
id = "Items.SandevistanC1MK2",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- ZETATECH SANDEVISTAN MK. 3 / Cyberware / Operating System / Epic
-- The advanced Sandevistan from Zetatech's assembly line - faster and more powerful than ever, with extra built-in user-compensation protocols making combat substantially more effective.
-- Slows time by 50% for 16 sec.
-- Cooldown 30 sec.
-- Increase Crit Chance by 20% when Sandevistan is active.
{
id = "Items.SandevistanC1MK3",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
-- ZETATECH SANDEVISTAN MK.1 / Cyberware / Operating System / Uncommon
-- The popular, mass-market Sandevistan from Zetatech. It's widely praised by users for its minimalism, lack of unnecessary features, and ease-of-use.
-- Slows time by 75% for 8 sec.
-- Cooldown 30 sec.
-- Increase Crit Chance by 10% when Sandevistan is active.
{
id = "Items.SandevistanC1MK1",
slots = {
{ slot = "Slot1" },
{ slot = "Slot2" },
{ slot = "Slot3" },
},
},
},
}
|
ESX = nil
local Categories = {}
local Vehicles = {}
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
Citizen.CreateThread(function()
local char = Config.PlateLetters
char = char + Config.PlateNumbers
if Config.PlateUseSpace then char = char + 1 end
if char > 8 then
print(('esx_truckshop: ^1WARNING^7 plate character count reached, %s/8 characters.'):format(char))
end
end)
function RemoveOwnedVehicle(plate)
MySQL.Async.execute('DELETE FROM owned_vehicles WHERE plate = @plate', {
['@plate'] = plate
})
end
MySQL.ready(function()
Categories = MySQL.Sync.fetchAll('SELECT * FROM truck_categories')
local vehicles = MySQL.Sync.fetchAll('SELECT * FROM trucks')
for i=1, #vehicles, 1 do
local vehicle = vehicles[i]
for j=1, #Categories, 1 do
if Categories[j].name == vehicle.category then
vehicle.categoryLabel = Categories[j].label
break
end
end
table.insert(Vehicles, vehicle)
end
-- send information after db has loaded, making sure everyone gets vehicle information
TriggerClientEvent('esx_truckshop:sendCategories', -1, Categories)
TriggerClientEvent('esx_truckshop:sendVehicles', -1, Vehicles)
end)
RegisterServerEvent('esx_truckshop:setVehicleOwned')
AddEventHandler('esx_truckshop:setVehicleOwned', function(vehicleProps)
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
MySQL.Async.execute('INSERT INTO owned_vehicles (owner, plate, vehicle, Type) VALUES (@owner, @plate, @vehicle, @Type)',
{
['@owner'] = xPlayer.identifier,
['@plate'] = vehicleProps.plate,
['@vehicle'] = json.encode(vehicleProps),
['@Type'] = 'car'
}, function(rowsChanged)
TriggerClientEvent('esx:showNotification', _source, _U('truck_belongs', vehicleProps.plate))
end)
end)
ESX.RegisterServerCallback('esx_truckshop:getCategories', function(source, cb)
cb(Categories)
end)
ESX.RegisterServerCallback('esx_truckshop:getVehicles', function(source, cb)
cb(Vehicles)
end)
ESX.RegisterServerCallback('esx_truckshop:buyVehicle', function(source, cb, vehicleModel)
local xPlayer = ESX.GetPlayerFromId(source)
local vehicleData = nil
for i=1, #Vehicles, 1 do
if Vehicles[i].model == vehicleModel then
vehicleData = Vehicles[i]
break
end
end
if xPlayer.getMoney() >= vehicleData.price then
xPlayer.removeMoney(vehicleData.price)
cb(true)
else
cb(false)
end
end)
ESX.RegisterServerCallback('esx_truckshop:resellVehicle', function(source, cb, plate, model)
local resellPrice = 0
-- calculate the resell price
for i=1, #Vehicles, 1 do
if GetHashKey(Vehicles[i].model) == model then
resellPrice = ESX.Math.Round(Vehicles[i].price / 100 * Config.ResellPercentage)
break
end
end
if resellPrice == 0 then
print(('esx_truckshop: %s attempted to sell an unknown vehicle!'):format(GetPlayerIdentifiers(source)[1]))
cb(false)
end
local xPlayer = ESX.GetPlayerFromId(source)
MySQL.Async.fetchAll('SELECT * FROM owned_vehicles WHERE owner = @owner AND @plate = plate', {
['@owner'] = xPlayer.identifier,
['@plate'] = plate
}, function(result)
if result[1] then -- does the owner match?
local vehicle = json.decode(result[1].vehicle)
if vehicle.model == model then
if vehicle.plate == plate then
xPlayer.addMoney(resellPrice)
RemoveOwnedVehicle(plate)
cb(true)
else
print(('esx_truckshop: %s attempted to sell an vehicle with plate mismatch!'):format(xPlayer.identifier))
cb(false)
end
else
print(('esx_truckshop: %s attempted to sell an vehicle with model mismatch!'):format(xPlayer.identifier))
cb(false)
end
else
cb(false)
end
end)
end)
ESX.RegisterServerCallback('esx_truckshop:isPlateTaken', function(source, cb, plate)
MySQL.Async.fetchAll('SELECT * FROM owned_vehicles WHERE plate = @plate', {
['@plate'] = plate
}, function(result)
cb(result[1] ~= nil)
end)
end)
ESX.RegisterServerCallback('esx_truckshop:retrieveJobVehicles', function(source, cb, type)
local xPlayer = ESX.GetPlayerFromId(source)
MySQL.Async.fetchAll('SELECT * FROM owned_vehicles WHERE owner = @owner AND type = @type AND job = @job', {
['@owner'] = xPlayer.identifier,
['@type'] = type,
['@job'] = xPlayer.job.name
}, function(result)
cb(result)
end)
end)
RegisterServerEvent('esx_truckshop:setJobVehicleState')
AddEventHandler('esx_truckshop:setJobVehicleState', function(plate, state)
local xPlayer = ESX.GetPlayerFromId(source)
MySQL.Async.execute('UPDATE owned_vehicles SET `stored` = @stored WHERE plate = @plate AND job = @job', {
['@stored'] = state,
['@plate'] = plate,
['@job'] = xPlayer.job.name
}, function(rowsChanged)
if rowsChanged == 0 then
print(('esx_truckshop: %s exploited the garage!'):format(xPlayer.identifier))
end
end)
end)
|
local pollution_crystalsb="_block"
local pollution_crystalsd="_"
local pollution_crystals={
{"Coal","coal","lump"},
{"Steel","steel","ingot"},
{"Copper","copper","ingot"},
{"Bronze","bronze","ingot"},
{"Gold","gold","ingot"},
{"Mese","mese","_crystal"},
{"Diamond","diamond",""},
{"Obsidian","obsidian","_shard"}
}
for i, ob in pairs(pollution_crystals) do
if i==8 then pollution_crystalsb="" end
if i==6 then pollution_crystalsd="" end
minetest.register_node("pollution:crystal_" .. pollution_crystals[i][2], {
description = pollution_crystals[i][1] .. " crystal",
drawtype = "mesh",
mesh = "pollution_crystal.obj",
visual_scale = 1.0,
wield_scale = {x=1, y=1, z=1},
alpha = 20,
tiles = {"default_" .. pollution_crystals[i][2] .. pollution_crystalsb ..".png"},
paramtype = "light",
paramtype2 = "facedir",
sunlight_propagates = true,
damage_per_second = 5,
walkable = false,
is_ground_content = false,
light_source=3,
selection_box = {
type = "fixed",
fixed = {-0.1, -0.5, -0.1, 0.1, 0.25, 0.1}
},
groups = {fleshy = 3, dig_immediate = 3,not_in_creative_inventory=1},
on_use = function(itemstack, user, pointed_thing)
if pointed_thing.type=="node" or pointed_thing.type=="nothing" then return itemstack end
local pvp=minetest.setting_getbool("enable_pvp")
local ob=pointed_thing.ref
if ob:is_player() and pvp==false then return itemstack end
ob:set_hp(ob:get_hp()-5)
ob:punch(user, {full_punch_interval=1.0,damage_groups={fleshy=4}}, "default:steel_pick", nil)
return itemstack
end,
})
minetest.register_craft({
output = "default:" .. pollution_crystals[i][2] .. pollution_crystalsd .. pollution_crystals[i][3] ,
recipe = {
{"pollution:crystal_" .. pollution_crystals[i][2],"pollution:crystal_" .. pollution_crystals[i][2],"pollution:crystal_" .. pollution_crystals[i][2]},
{"pollution:crystal_" .. pollution_crystals[i][2],"pollution:crystal_" .. pollution_crystals[i][2],"pollution:crystal_" .. pollution_crystals[i][2]},
{"pollution:crystal_" .. pollution_crystals[i][2],"pollution:crystal_" .. pollution_crystals[i][2],"pollution:crystal_" .. pollution_crystals[i][2]}
}
})
end
pollution_crystalsb=nil
pollution_crystalsd=nil
pollution_crystals=nil
minetest.register_node("pollution:crystal_magnesium", {
description = "Magnesium crystal",
drawtype = "mesh",
mesh = "pollution_crystal.obj",
visual_scale = 1.0,
wield_scale = {x=1, y=1, z=1},
alpha = 20,
tiles = {"default_steel_block.png^pollution_dirt.png^pollution_dirt.png^pollution_dirt.png"},
paramtype = "light",
sunlight_propagates = true,
walkable = false,
light_source=3,
is_ground_content = false,
selection_box = {
type = "fixed",
fixed = {-0.1, -0.5, -0.1, 0.1, 0.25, 0.1}
},
groups = {fleshy = 3, dig_immediate = 3,not_in_creative_inventory=1},
})
minetest.register_craft({
output = "pollution:magnesium_lump",
recipe = {
{"pollution:crystal_magnesium", "pollution:crystal_magnesium", "pollution:crystal_magnesium"},
{"pollution:crystal_magnesium", "pollution:crystal_magnesium", "pollution:crystal_magnesium"},
{"pollution:crystal_magnesium", "pollution:crystal_magnesium", "pollution:crystal_magnesium"}
}
})
pollution_crystal_blocks_titles={"coal","copper","steel","bronze","magnesium","obsidian","gold","mese","diamond"}
pollution_crystal_blocks={
"default:coalblock",
"default:copperblock",
"default:steelblock",
"default:bronzeblock",
"pollution:magnesium_block",
"default:obsidian",
"default:goldblock",
"default:mese",
"default:diamondblock",
}
minetest.register_abm({
nodenames = pollution_crystal_blocks,
neighbors = {"pollution:water_source"},
interval = 60,
chance = 5,
action = function(pos)
local name=minetest.get_node(pos).name
local pos1={x=pos.x,y=pos.y+1,z=pos.z}
local level1=minetest.get_node(pos1).name=="pollution:water_source"
if level1 then
for i=1,9,1 do
if name==pollution_crystal_blocks[i] then
if math.random(i)==1 then
minetest.set_node(pos1, {name = "pollution:crystal_" .. pollution_crystal_blocks_titles[i]})
end
break
end
end
end
end,
})
|
local UserInputService = game:GetService("UserInputService")
local players = game:GetService("Players")
local mouse = players.LocalPlayer:GetMouse()
local ICONS = {
horizontal = "rbxassetid://7655080017",
vertical = "rbxassetid://7655095494",
bottomLeft = "rbxassetid://7655124995",
bottomRight = "rbxassetid://7655117647",
}
local ROBLOX_TOPBAR_SIZE = 36
local TOPBAR_SIZE = 20
--// https://devforum.roblox.com/t/--/107689/5
return function(gui: GuiObject)
-- Dragging
local dragging: boolean
local dragInput: InputObject
local dragStart: Vector2
local startPos: UDim2
local function update(input: InputObject)
local delta = input.Position - dragStart
gui.Position = UDim2.new(
startPos.X.Scale,
startPos.X.Offset + delta.X,
startPos.Y.Scale,
startPos.Y.Offset + delta.Y
)
end
gui.InputBegan:Connect(function(input: InputObject)
if
input.UserInputType == Enum.UserInputType.MouseButton1
or input.UserInputType == Enum.UserInputType.Touch
then
dragging = true
dragStart = input.Position
startPos = gui.Position
input.Changed:Connect(function()
if input.UserInputState == Enum.UserInputState.End then
dragging = false
end
end)
end
end)
gui.InputChanged:Connect(function(input: InputObject)
if
input.UserInputType == Enum.UserInputType.MouseMovement
or input.UserInputType == Enum.UserInputType.Touch
then
dragInput = input
end
end)
UserInputService.InputChanged:Connect(function(input: InputObject)
if input == dragInput and dragging then
update(input)
end
end)
-- Resizing
local MINIMUM_HEIGHT = gui.Content.AbsoluteSize.Y
local MINIMUM_WIDTH = gui.AbsoluteSize.X
local resizing = nil
local lastCursor = mouse.Icon
local function startResize(input: InputObject, side: string)
if input.UserInputType ~= Enum.UserInputType.MouseButton1 then
return
end
local draggingResize = true
resizing = true
local startingPosition = input.Position
local startingSize = gui.Size
local startingContentSize = gui.Content.Size
local startingFramePosition = gui.Position
local stopDrag
stopDrag = input:GetPropertyChangedSignal("UserInputState"):Connect(function()
if input.UserInputState == Enum.UserInputState.End then
draggingResize = false
resizing = nil
mouse.Icon = lastCursor
stopDrag:Disconnect()
end
end)
while draggingResize do
if side == "right" then
local diff = UserInputService:GetMouseLocation().X - startingPosition.X
gui.Size = UDim2.fromOffset(math.max(startingSize.X.Offset + diff, MINIMUM_WIDTH), TOPBAR_SIZE)
elseif side == "bottom" then
local diff = UserInputService:GetMouseLocation().Y - startingPosition.Y
gui.Content.Size = UDim2.new(
1,
0,
0,
math.max(startingContentSize.Y.Offset + diff - ROBLOX_TOPBAR_SIZE, MINIMUM_HEIGHT)
)
elseif side == "left" then
local diff = startingPosition.X - UserInputService:GetMouseLocation().X
if startingSize.X.Offset + diff > MINIMUM_WIDTH then
gui.Size = UDim2.fromOffset(math.max(startingSize.X.Offset + diff, MINIMUM_WIDTH), TOPBAR_SIZE)
gui.Position = UDim2.fromOffset(
UserInputService:GetMouseLocation().X,
startingFramePosition.Y.Offset
)
end
elseif side == "bottomleft" then
local Xdiff = startingPosition.X - UserInputService:GetMouseLocation().X
local Ydiff = UserInputService:GetMouseLocation().Y - startingPosition.Y
gui.Content.Size = UDim2.new(
1,
0,
0,
math.max(startingContentSize.Y.Offset + Ydiff - ROBLOX_TOPBAR_SIZE, MINIMUM_HEIGHT)
)
if startingSize.X.Offset + Xdiff > MINIMUM_WIDTH then
gui.Size = UDim2.fromOffset(math.max(startingSize.X.Offset + Xdiff, MINIMUM_WIDTH), TOPBAR_SIZE)
gui.Position = UDim2.fromOffset(
UserInputService:GetMouseLocation().X,
startingFramePosition.Y.Offset
)
end
elseif side == "bottomright" then
local Xdiff = UserInputService:GetMouseLocation().X - startingPosition.X
local Ydiff = UserInputService:GetMouseLocation().Y - startingPosition.Y
gui.Content.Size = UDim2.new(
1,
0,
0,
math.max(startingContentSize.Y.Offset + Ydiff - ROBLOX_TOPBAR_SIZE, MINIMUM_HEIGHT)
)
gui.Size = UDim2.fromOffset(math.max(startingSize.X.Offset + Xdiff, MINIMUM_WIDTH), TOPBAR_SIZE)
end
task.wait()
end
end
-- There has to be a better way to do that
gui.Content.Drag.Right.InputBegan:Connect(function(input: InputObject)
startResize(input, "right")
end)
gui.Content.Drag.Right.MouseEnter:Connect(function()
if not resizing then
lastCursor = mouse.Icon
mouse.Icon = ICONS.horizontal
end
end)
gui.Content.Drag.Right.MouseLeave:Connect(function()
if not resizing then
mouse.Icon = ""
end
end)
gui.Content.Drag.Left.InputBegan:Connect(function(input: InputObject)
startResize(input, "left")
end)
gui.Content.Drag.Left.MouseEnter:Connect(function()
if not resizing then
lastCursor = mouse.Icon
mouse.Icon = ICONS.horizontal
end
end)
gui.Content.Drag.Left.MouseLeave:Connect(function()
if not resizing then
mouse.Icon = ""
end
end)
gui.Content.Drag.Bottom.InputBegan:Connect(function(input: InputObject)
startResize(input, "bottom")
end)
gui.Content.Drag.Bottom.MouseEnter:Connect(function()
if not resizing then
lastCursor = mouse.Icon
mouse.Icon = ICONS.vertical
end
end)
gui.Content.Drag.Bottom.MouseLeave:Connect(function()
if not resizing then
mouse.Icon = ""
end
end)
gui.Content.Drag.BottomLeft.InputBegan:Connect(function(input: InputObject)
startResize(input, "bottomleft")
end)
gui.Content.Drag.BottomLeft.MouseEnter:Connect(function()
if not resizing then
lastCursor = mouse.Icon
mouse.Icon = ICONS.bottomLeft
end
end)
gui.Content.Drag.BottomLeft.MouseLeave:Connect(function()
if not resizing then
mouse.Icon = ""
end
end)
gui.Content.Drag.BottomRight.InputBegan:Connect(function(input: InputObject)
startResize(input, "bottomright")
end)
gui.Content.Drag.BottomRight.MouseEnter:Connect(function()
if not resizing then
lastCursor = mouse.Icon
mouse.Icon = ICONS.bottomRight
end
end)
gui.Content.Drag.BottomRight.MouseLeave:Connect(function()
if not resizing then
mouse.Icon = ""
end
end)
end
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:27' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
local NotificationIcons_Console = ZO_Object:Subclass()
function NotificationIcons_Console:New(...)
local object = ZO_Object.New(self)
object:Initialize(...)
return object
end
function NotificationIcons_Console:Initialize(control)
self.control = control
self.numUnread = 0
self.numNotifications = 0
self.animToPlay = nil
self.waitingToTrigger = false
self.fadingOut = false
self.notificationFrameTimeMS = 0
self.fadeStartTimeMS = 0
self.fadeTimeMS = 10000
self.reshowTimeMS = 150000
EVENT_MANAGER:RegisterForEvent("NotificationIcons_Console", EVENT_MAIL_NUM_UNREAD_CHANGED, function(_, numUnread) self:OnNumUnreadMailChanged(numUnread) end)
control:SetHandler("OnUpdate", function() self:OnUpdate() end)
--setup the animation for the control as a whole
local function FadeStop()
if(self.fadingOut) then
ALERT_MESSAGES_GAMEPAD:SetHoldDisplayingEntries(false)
self.fadingOut = false
self.notificationFrameTimeMS = GetFrameTimeMilliseconds()
else
if(self.animToPlay) then
self.animToPlay:PlayFromStart()
else
self.fadeStartTimeMS = GetFrameTimeMilliseconds()
end
end
end
self.fadeTimeline = ANIMATION_MANAGER:CreateTimelineFromVirtual("ConsoleNotificationIconsFade", control)
self.fadeTimeline:SetHandler("OnStop", FadeStop)
--setup the animation on the mail and notification icons
local function StartFadeTimer()
self.animToPlay = nil
self.fadeStartTimeMS = GetFrameTimeMilliseconds()
end
self.mailIcon = control:GetNamedChild("Mail")
self.mailPulseTimeline = ANIMATION_MANAGER:CreateTimelineFromVirtual("ConsoleNotificationPulse", self.mailIcon)
self.mailPulseTimeline:SetHandler("OnStop", StartFadeTimer)
--setup the animation on the notifications icon
self.notificationsIcon = control:GetNamedChild("Notifications")
self.notificationPulseTimeline = ANIMATION_MANAGER:CreateTimelineFromVirtual("ConsoleNotificationPulse", self.notificationsIcon)
self.notificationPulseTimeline:SetHandler("OnStop", StartFadeTimer)
end
function NotificationIcons_Console:OnNumUnreadMailChanged(numUnread)
if(numUnread > self.numUnread and IsPlayerActivated()) then
self.animToPlay = self.mailPulseTimeline
self.notificationFrameTimeMS = GetFrameTimeMilliseconds()
self.waitingToTrigger = true
end
self.numUnread = numUnread
end
function NotificationIcons_Console:OnNumNotificationsChanged(numNotifications)
if(numNotifications > self.numNotifications and IsPlayerActivated()) then
self.animToPlay = self.notificationPulseTimeline
self.notificationFrameTimeMS = GetFrameTimeMilliseconds()
self.waitingToTrigger = true
end
self.numNotifications = numNotifications
end
function NotificationIcons_Console:OnUpdate()
local time = GetFrameTimeMilliseconds()
if(self.fadeStartTimeMS > 0) then
-- trigger fade out at the end of fadeStartTimeMS or if a new alert text comes in
if(ALERT_MESSAGES_GAMEPAD:HasActiveEntries() or
(time > self.fadeStartTimeMS + self.fadeTimeMS)) then
self.fadeStartTimeMS = 0
self.fadeTimeline:PlayFromEnd()
self.fadingOut = true
end
-- trigger fade in of the icons when the alert text queue empties
elseif(self.waitingToTrigger) then
if(self.notificationFrameTimeMS < time) and (not ALERT_MESSAGES_GAMEPAD:HasActiveEntries()) then
self.fadeTimeline:PlayFromStart()
self.waitingToTrigger = false
self.notificationFrameTimeMS = time
ALERT_MESSAGES_GAMEPAD:SetHoldDisplayingEntries(true)
end
-- retrigger the icons to show every reshowTimeMS if there are unread messages or notifications
elseif((self.numUnread > 0 or self.numNotifications > 0) and (time > self.notificationFrameTimeMS + self.reshowTimeMS)) then
self.notificationFrameTimeMS = time
self.waitingToTrigger = true
end
end
function ZO_NotificationIcons_Gamepad_Initialize(control)
NOTIFICATION_ICONS_CONSOLE = NotificationIcons_Console:New(control)
end
|
enemy = {}
animTimer = love.timer.getMicroTime( )
animTimerDelay = 1
bloodTimer = love.timer.getMicroTime( )
bloodTimerDelay = 0.1
bloodID = 1
deathID = 1
jDeathTimer = love.timer.getMicroTime()
function enemy:init(max_enemies)
self.table = {}
enemyNumber = max_enemies
end
function enemy:getMaxEnemies( )
return enemyNumber
end
function enemy:getCurrentEnemies( )
return #self.table
end
function enemy:dropBaddies( )
self.table = { }
end
function enemy:removeFromTable( s )
if soundOn == true then
love.audio.play(snd.vampDeath)
end
table.remove(self.table,s)
for i = 1, #self.table do
self.table[i].s = i
end
hero.enemiesKilled = hero.enemiesKilled + 1
eKillCounter = eKillCounter + 1
end
function enemy:playDeathAnimation()
animation:playAnimation(3,0.05,(hero.x - map.x)*32,(hero.y - map.y)*32, false)
if animation:getCurrentFrame(3) == animation:getFrames(3) then
playerDeathAnim = false
animation:setFrame(3,1)
end
end
function BalanceEnemies( )
if enemy:getCurrentEnemies( ) < 4 then
enemy:spawnNewEnemy( )
end
if eKillCounter >= 4 then
enemy:spawnTier2Enemy( )
eKillCounter = 0
end
end
function enemy:spawnTier2Enemy( )
local life = math.random(30,56)
local temp_X = 0
local temp_y = 0
local totDistance = 0
local temp = {
x = 6,
y = 6,
s = #self.table+1,
w = 32,
h = 32,
timer = 0,
hp = life,
initialHP = life,
type = math.random(8,12),
oldx = 0,
oldy = 0,
actionString = " ",
name = "<"..FirstNames[math.random(1,#FirstNames)].." "..SecondNames[math.random(1,#SecondNames)]..">",
AP = math.random(3,7),
enemy_x = 0,
enemy_y = 0,
path = { },
lenght = 0,
noticedPlayer = false,
hasSummons = false,
bloodTimer = love.timer.getMicroTime(),
bloodFrame = 1,
takingDamage = false,
isTagged = false,
TaggImg = love.graphics.newImage("gfx/Stone.png"),
tagCount = 0,
tagRegeneration = math.random(2,4),
bDeathAnim = false,
deathTimer = love.timer.getMicroTime(),
deathFrame = 1,
}
table.insert( self.table, temp )
repeat
self.table[#self.table].over_hero = 1 -- flag that checks
self.table[#self.table].x = math.random(1,map.width)
self.table[#self.table].y = math.random(1,map.height)
temp_X = self.table[#self.table].x
temp_Y = self.table[#self.table].y
totDistance = distanceToPlayer(hero.x, hero.y, temp_X, temp_Y)
--v.x = 10
--v.y = 10
self.table[#self.table].check_walk = map.walk[map.data[self.table[#self.table].y][self.table[#self.table].x]] -- check if mob landed over non-walkable land. --]]
if self.table[#self.table].y ~= hero_y or self.table[#self.table].x ~= hero_x then self.table[#self.table].over_hero = 0 end -- check if mob landed over hero.
until totDistance > 20 and totDistance < 35 and self.table[#self.table].check_walk == 1 and self.table[#self.table].over_hero == 0 -- get out of loop when coords are good
end
function enemy:spawnNewEnemy( )
local life = math.random(11,24)
local temp_X = 0
local temp_y = 0
local totDistance = 0
local temp = {
x = 6,
y = 6,
s = #self.table+1,
w = 32,
h = 32,
timer = 0,
hp = life,
initialHP = life,
type = math.random(1,7),
oldx = 0,
oldy = 0,
actionString = " ",
name = "<"..FirstNames[math.random(1,#FirstNames)].." "..SecondNames[math.random(1,#SecondNames)]..">",
AP = math.random(3,7),
enemy_x = 0,
enemy_y = 0,
path = { },
lenght = 0,
noticedPlayer = false,
hasSummons = false,
bloodTimer = love.timer.getMicroTime(),
bloodFrame = 1,
takingDamage = false,
isTagged = false,
TaggImg = love.graphics.newImage("gfx/Stone.png"),
tagCount = 0,
tagRegeneration = math.random(2,4),
bDeathAnim = false,
deathTimer = love.timer.getMicroTime(),
deathFrame = 1,
}
table.insert( self.table, temp )
repeat
self.table[#self.table].over_hero = 1 -- flag that checks
self.table[#self.table].x = math.random(1,map.width)
self.table[#self.table].y = math.random(1,map.height)
temp_X = self.table[#self.table].x
temp_Y = self.table[#self.table].y
totDistance = distanceToPlayer(hero.x, hero.y, temp_X, temp_Y)
--v.x = 10
--v.y = 10
self.table[#self.table].check_walk = map.walk[map.data[self.table[#self.table].y][self.table[#self.table].x]] -- check if mob landed over non-walkable land. --]]
if self.table[#self.table].y ~= hero_y or self.table[#self.table].x ~= hero_x then self.table[#self.table].over_hero = 0 end -- check if mob landed over hero.
until totDistance > 20 and totDistance < 35 and self.table[#self.table].check_walk == 1 and self.table[#self.table].over_hero == 0 -- get out of loop when coords are good
end --
function enemy:new( s )
local life = math.random(11,24)
local temp = {
x = math.random( 1,5 ),
y = math.random( 1, 5 ),
s = #self.table+1,
w = 32,
h = 32,
timer = 0,
hp = life,
initialHP = life,
type = math.random(1,7),
oldx = 0,
oldy = 0,
name = "<"..FirstNames[math.random(1,#FirstNames)].." "..SecondNames[math.random(1,#SecondNames)]..">",
AP = math.random(3,7),
enemy_x = 0,
enemy_y = 0,
path = { },
lenght = 0,
noticedPlayer = false,
hasSummons = false,
bloodTimer = love.timer.getMicroTime(),
bloodFrame = 1,
takingDamage = false,
isTagged = false,
TaggImg = love.graphics.newImage("gfx/Stone.png"),
tagCount = 0,
tagRegeneration = math.random(2,4),
bDeathAnim = false,
deathTimer = love.timer.getMicroTime(),
deathFrame = 1,
}
table.insert( self.table, temp )
end
function enemy:setUp ( )
for i,v in ipairs( self.table ) do
repeat
v.over_hero = 1 -- flag that checks
v.x = math.random(1,map.width)
v.y = math.random(1,map.height)
--v.x = 10
--v.y = 10
v.check_walk = map.walk[map.data[v.y][v.x]] -- check if mob landed over non-walkable land. --]]
if v.y ~= hero_y or v.x ~= hero_x then v.over_hero = 0 end -- check if mob landed over hero.
until v.check_walk == 1 and v.over_hero == 0 -- get out of loop when coords are good
end
end
function enemy:checkX(s)
for i,v in ipairs ( self.table ) do
if s == v.s then
return v.x
end
end
end
function enemy:checkY(s)
for i,v in ipairs ( self.table ) do
if s == v.s then
return v.y
end
end
end
function enemy:setX(s,x)
for i, v in ipairs ( self.table ) do
if s == v.s then
v.x = x
end
end
end
function enemy:setY(s,y)
for i, v in ipairs ( self.table ) do
if s == v.s then
v.y = y
end
end
end
function enemy:isAware( s )
for i,v in ipairs ( self.table ) do
if s == v.s then
if v.noticedPlayer == true then
return true
else
return false
end
end
end
end
function enemy:setAwareness( s )
for i,v in ipairs ( self.table ) do
if s == v.s then
v.noticedPlayer = true
end
end
end
function enemy:knockBack(s,dir)
knockBackRandom = math.random(1,5)
for i,v in ipairs (self.table) do
if s == v.s then
if v.hp > 0 then
if knockBackRandom >= 3 then
if dir == 3 then
if map.collision[v.y][v.x-2] == 0 then
v.x = v.x - 2
elseif map.collision[v.y][v.x-1] == 0 then
v.x = v.x - 1
end
elseif dir == 4 then
if map.collision[v.y][v.x+2] == 0 then
v.x = v.x + 2
elseif map.collision[v.y][v.x+1] == 0 then
v.x = v.x + 1
end
end
end
end
end
end
end
function avoidHotSpots( )
end
function enemy:alterHp( s, value )
if self.table then
for i,v in ipairs ( self.table ) do
if s == v.s then
if currentWeaponID == 4 and hero.hasShoot == true then
v.isTagged = true
miscEventBool = true
miscEventString = ""..v.name.." was turned to stone."
--map.collision[v.y][v.x] = 1
end
v.hp = v.hp-value
enemy:spillBlood( v.s, v.x, v.y )
end
end
end
end
function enemy:drawLine( )
for i,v in ipairs ( self.table ) do
if v.type == 2 then
love.graphics.line(v.x,v.y,hero.x,hero.y)
end
end
end
---------------------------------------------------------
-- ToDo: independent move
---------------------------------------------------------
function enemy:astarMove(s)
end
function enemy:getOldPosition( s )
for i, v in ipairs ( self.table ) do
if s == v.s then
v.oldx = v.x
v.oldy = v.y
end
end
end
function enemy:moveTowardsPlayer(s,path)
local tableForPath = path
for i, v in ipairs ( self.table ) do
if s == v.s then
--if v.AP > 4 then
if v.hp > 0 and v.isTagged == false then
--
--for it = 1, #tableForPath do
if tableForPath[i] ~= nil then
if distanceToEnemy(hero.x, hero.y, v.x, v.y) <= 10 then
--if tableForPath[i+1].x ~= hero.x and tableForPath[i+1].y ~= hero.y then
v.x = tableForPath[i].x
v.y = tableForPath[i].y
bInsertEvent = true
v.AP = v.AP - 4
evEnemyString = ""..v.name.." draws closer."
end
end
--end
--end
end
--end
end
end
--evEnemyString = ""..v.name.." draws closer."
end
function enemy:moveTowardsPlayer2(s)
for i, v in ipairs ( self.table ) do
if s == v.s then
if v.hp > 0 and v.isTagged == false--[[and v.AP >= 4--]] then
v.path, v.lenght = pather:getPath(enemy:checkX(i), enemy:checkY(i), hero.x,hero.y)
if v.path[i] ~= nil then
--if distanceToEnemy(hero.x, hero.y, v.x, v.y) <= 10 then
-- Tweening x = x + (target -x) *0.1
v.x = v.path[i].x
v.y = v.path[i].y
--if distanceToPlayer(v.x, v.y, hero.x, hero.y) <= 5 then
--end
--end
end
end
end
end
end
function enemy:positionCorrectly( s )
for i,v in ipairs ( self.table ) do
if s == v.s then
if v.hp > 0 then
if v.x == hero.x and v.y == hero.y then
v.x = v.oldx
v.y = v.oldy
end
end
end
end
end
--[[local tableForPath = path
for i, v in ipairs ( self.table ) do
if s == v.s then
if v.hp > 0 then
for it = 1, #tableForPath do
if tableForPath[i+1] ~= nil then
--if tableForPath[i+1].x ~= hero.x and tableForPath[i+1].y ~= hero.y then
v.x = tableForPath[i].x
v.y = tableForPath[i].y
--end
end
end
end
end
end--]]
function enemy:debugPathTowardsPlayer(s, path)
local tableForPath = path
--[[for i,v in ipairs ( self.table ) do
if s == v.s then
if v.hp > 0 and path then
if tableForPath ~= nill then
love.graphics.line(tableForPath[i].x, tableForPath[i].y, tableForPath[i+1].x, tableForPath[i+1].y)
end
end
end
end--]]
for i = 1, #tableForPath do
if tableForPath[i+1] ~= nil then
love.graphics.line((tableForPath[i].x - map.x)*32, ( tableForPath[i].y - map.y)*32, (tableForPath[i+1].x - map.x)*32, (tableForPath[i+1].y - map.y)*32)
end
end
end
function enemy:move(s)
mvRandom = math.random(1,4)
for i,v in ipairs ( self.table ) do
if s == v.s then
if v.hp > 0 and v.isTagged == false then
if mvRandom == 1 then
if map.walk[map.data[v.y][v.x+1]] == 1 then
v.x = v.x + 1
end
elseif mvRandom == 2 then
if map.walk[map.data[v.y+1][v.x]] == 1 then
v.y = v.y + 1
end
elseif mvRandom == 3 then
if map.walk[map.data[v.y][v.x-1]] == 1 then
v.x = v.x - 1
end
elseif mvRandom == 4 then
if map.walk[map.data[v.y-1][v.x]] == 1 then
v.y = v.y - 1
end
end
end
if v.x == hero.x and v.y == hero.y then
hero.hp = hero.hp - 1
end
end
end
end
function enemy:getHp( s )
for i,v in ipairs ( self.table ) do
if s == v.s then
return v.hp
end
end
end
function enemy:isDead( s )
for i,v in ipairs( self.table ) do
if s == v.s then
if v.hp <= 0 then
--bInsertEvent = true
--pMovementString = ""..v.name.." has died. " --pMovementString because isDead is checked on the player's turn.
enemy:removeFromTable( s )
-- Debug only. I'll remove them from the table later on :)
end
end
end
end
function enemy:update()
-- make burgers! Burgers are good.
BalanceEnemies( )
actionsDuringEnemyTurn ( )
enemy:checkTagg( )
end
function enemy:checkTagg( )
for i,v in ipairs ( self.table ) do
if v.isTagged == true then
v.tagCount = v.tagCount + 1
end
if v.tagCount >= v.tagRegeneration then
regenCheck = math.random(1,10)
if regenCheck >= 7 then --- MAYBE LOWER IT LATER! FOR NOW IT SEEMS TO BE OK
v.tagCount = 0
v.isTagged = false
v.tagRegeneration = math.random(2,4)
miscEventBool = true
miscEventString = ""..v.name.." is back to normal. He seems angry"
end
--map.collision[v.y][v.x] = 0
end
end
end
function enemy:retrieveBatTypesID( )
end
function enemy:draw(lx,ly)
for i,v in ipairs( self.table ) do
love.graphics.setColor(255,255,255)
if (v.x == lx) and (v.y == ly) then
if v.hp > v.initialHP then v.hp = v.initialHP end ----- Quick hack to keep enemy T2 vamps at max health.
if v.isTagged == false then
if v.x < hero.x then
if v.type >= 8 and v.type <= 12 and distance2enemy(i) > 3 then
animation:loopAnimation(1, 0.1, (v.x - map.x) *32, (v.y - map.y) *32, false )
else
love.graphics.draw(tile.mob[v.type],(v.x - map.x) *32, (v.y - map.y) *32)
end
else
if v.type >= 8 and v.type <= 12 and distance2enemy(i) > 3 then
animation:loopAnimation(1, 0.1, (v.x - map.x) *32, (v.y - map.y) *32, true )
else
love.graphics.draw(tile.mob[v.type],(v.x - map.x) *32, (v.y - map.y) *32,0,-1,1,32,0)
end
end
else
love.graphics.draw(v.TaggImg,(v.x - map.x) *32, (v.y - map.y) *32,0,-1,1,32,0)
end
local scaleFactor = 1 - ( (100 - ( (100 * v.hp) / v.initialHP ) ) / 100 )
love.graphics.draw(hb_background, (v.x - map.x) * 32, (v.y - map.y) * 32 - 5)
love.graphics.draw(hb_foreground, (v.x - map.x) * 32, (v.y - map.y) * 32 - 5, 0, scaleFactor ,1)
if v.takingDamage == true then
enemy:spillBlood( v.s, (v.x - map.x) * 32, (v.y - map.y) * 32 )
if animation:getCurrentFrame(2) == animation:getFrames(2) then
v.takingDamage = false
end
end
end
end -- end for inpairs
end
function enemy:drawNames( )
for i,v in ipairs( self.table ) do
love.graphics.print(""..v.name.."",(v.x - map.x) * 32 - string.len(v.name)*2.5, (v.y - map.y) * 32 - 25)
end
end
function enemy:attackPlayer( s )
if self.table[s].isTagged == false then
if self.table[s].type >= 1 and self.table[s].type <= 7 then
dmgPlayer = math.random(2,8)
hero.hp = hero.hp - dmgPlayer
bInsertEvent = true
evEnemyString = ""..self.table[s].name.." dealt "..dmgPlayer.." damage to you. "..self.table[s].name.." grins.".."Pos X: "..self.table[s].x.." Pos Y:"..self.table[s].y..""
hero.killed_by = ""..self.table[s].name..""
if hero.hp < 0 then hero.hp = 0 end
if soundOn == true then
love.audio.play(snd.playerHit)
end
deathID = 1
playerDeathAnim = true
elseif self.table[s].type >= 8 and self.table[s].type <= 12 then
dmgPlayer = math.random(5,10)
hero.hp = hero.hp - dmgPlayer
bInsertEvent = true
love.graphics.setColor(200,50,50)
evEnemyString = ""..self.table[s].name.." has drained "..dmgPlayer.." life from the player."
hero.killed_by = ""..self.table[s].name..""
self.table[s].hp = self.table[s].hp + dmgPlayer-math.random(1,4)
if hero.hp < 0 then hero.hp = 0 end
if soundOn == true then
love.audio.play(snd.playerHit)
end
deathID = 1
playerDeathAnim = true
end
end
end
function enemy:spillBlood( s, pos__x, pos__y )
animation:loopAnimation(2,0.1,pos__x,pos__y, false)
end
function setupEnemies( )
enemy:init(8)
for i = 1, enemy:getMaxEnemies() do
enemy:new(i)
end
enemy:setUp ( )
end
function enemy:updateAP( )
for i,v in ipairs ( self.table ) do
if v.hp > 0 then
v.AP = v.AP + 2
end
end
end
--[[postAttackActions = {
" grins.",
" winks at "..FirstNames[math.random(1,#FirstNames)].." "..SecondNames[math.random(1,#SecondNames)]..".",
}
To Do: Split into more more strings, so concatenation is possible
--]]
FirstNames = { "Circe",
"Anton",
"Aubrey",
"Cesar",
"Charity",
"Christine",
"Circe",
"Dante",
"Emmanuel",
"Enoch",
"Evangeline",
"Hope",
"Joseph",
"Kraig",
"Kristopher",
"Luciano",
"Lucius",
"Nathaniel",
"Nichole",
"Pollux",
"Raphael",
"Romulus",
"Vana",
"Ona",
"Costine",
"Fleturis",
"Tina",
"Seras",
"Integra",
"Andosan",
"Bob",
"Victorria",
"Salamy",
"Hanzel",
}
SecondNames = {
"Blackblade",
"Cruelblood",
"Cruelchain",
"Cryptgrief",
"Darkdragon",
"Devildragon",
"Devilwolf",
"Duskblade",
"Evilsmoke",
"Farsinner",
"Fatevenom",
"Grimbeast",
"Grimdragon",
"Helldirge",
"Iceblade",
"Icedamn",
"Shadowblade",
"Shadowwoe",
"Steelbrood",
"Steelstorm",
"Twistmist",
"Venomfate",
"Venomheart",
"Warcairn",
"Wildstorm",
"Moses",
"Florence",
"Hellsing",
"Donnet",
"Bernadette",
"Crimson",
"Fogripper",
"Le Mort",
"Fangy",
"Longshadow",
"Griefstrike",
"Bartholomew",
"Dhampir",
"Asscariot",
"PamaMia",
"Calinescu",
" ",
" ",
" ",
}
return enemy
|
ESX = nil
local display = false
local LastVehicle = nil
local LicencePlate = {}
LicencePlate.Index = false
LicencePlate.Number = false
local Keys = {
["ESC"] = 322, ["F1"] = 288, ["F2"] = 289, ["F3"] = 170, ["F5"] = 166, ["F6"] = 167, ["F7"] = 168, ["F8"] = 169, ["F9"] = 56, ["F10"] = 57,
["~"] = 243, ["1"] = 157, ["2"] = 158, ["3"] = 160, ["4"] = 164, ["5"] = 165, ["6"] = 159, ["7"] = 161, ["8"] = 162, ["9"] = 163, ["-"] = 84, ["="] = 83, ["BACKSPACE"] = 177,
["TAB"] = 37, ["Q"] = 44, ["W"] = 32, ["E"] = 38, ["R"] = 45, ["T"] = 245, ["Y"] = 246, ["U"] = 303, ["P"] = 199, ["["] = 39, ["]"] = 40, ["ENTER"] = 18,
["CAPS"] = 137, ["A"] = 34, ["S"] = 8, ["D"] = 9, ["F"] = 23, ["G"] = 47, ["H"] = 74, ["K"] = 311, ["L"] = 182,
["LEFTSHIFT"] = 21, ["Z"] = 20, ["X"] = 73, ["C"] = 26, ["V"] = 0, ["B"] = 29, ["N"] = 249, ["M"] = 244, [","] = 82, ["."] = 81,
["LEFTCTRL"] = 36, ["LEFTALT"] = 19, ["SPACE"] = 22, ["RIGHTCTRL"] = 70,
["HOME"] = 213, ["PAGEUP"] = 10, ["PAGEDOWN"] = 11, ["DELETE"] = 178,
["LEFT"] = 174, ["RIGHT"] = 175, ["TOP"] = 27, ["DOWN"] = 173,
["NENTER"] = 201, ["N4"] = 108, ["N5"] = 60, ["N6"] = 107, ["N+"] = 96, ["N-"] = 97, ["N7"] = 117, ["N8"] = 61, ["N9"] = 118
}
Citizen.CreateThread(function()
while ESX == nil do
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
Citizen.Wait(0)
end
end)
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
if IsControlPressed(0, Keys["LEFTSHIFT"]) and IsControlJustPressed(0, Keys["G"]) then
SetDisplay(not display)
end
end
end)
RegisterNUICallback("exit", function(data)
SetDisplay(false)
end)
RegisterNUICallback("datspz", function(data)
ExecuteCommand("datspz")
SetDisplay(false)
end)
RegisterNUICallback("sundatspz", function(data)
ExecuteCommand("sundatspz")
SetDisplay(false)
end)
RegisterNUICallback("error", function(data)
ESX.ShowNotification('Někde se')
SetDisplay(false)
end)
function SetDisplay(bool)
display = bool
SetNuiFocus(bool, bool)
SendNUIMessage({
type = "ui",
status = bool,
})
end
Citizen.CreateThread(function()
while display do
Citizen.Wait(0)
DisableControlAction(0, 1, display)
DisableControlAction(0, 2, display)
DisableControlAction(0, 142, display)
DisableControlAction(0, 18, display)
DisableControlAction(0, 322, display)
DisableControlAction(0, 106, display)
end
end)
RegisterCommand("sundatspz", function()
if not LicencePlate.Index and not LicencePlate.Number then
local PlayerPed = PlayerPedId()
local Coords = GetEntityCoords(PlayerPed)
local Vehicle = GetClosestVehicle(Coords.x, Coords.y, Coords.z, 3.5, 0, 70)
local VehicleCoords = GetEntityCoords(Vehicle)
local Distance = Vdist(VehicleCoords.x, VehicleCoords.y, VehicleCoords.z, Coords.x, Coords.y, Coords.z)
if Distance < 3.5 and not IsPedInAnyVehicle(PlayerPed, false) then
LastVehicle = Vehicle
Animation()
SendNUIMessage({type = "ui",display = true,time = 6000,text = "Removing Plate..."}) --PROGRESSBAR
StopAnimTask(PlayerPedId(), "mini@repair", "fixing_a_player", 1.0)
Citizen.Wait(6000)
LicencePlate.Index = GetVehicleNumberPlateTextIndex(Vehicle)
LicencePlate.Number = GetVehicleNumberPlateText(Vehicle)
SetVehicleNumberPlateText(Vehicle, " ")
ESX.ShowNotification('Sundal jsi SPZ - '..LicencePlate.Number..'')
TriggerServerEvent('scb_nuispz:sendWebhook', source, cb, xPlayer, discord, id, ip, ipd)
else
ESX.ShowNotification('Nejsi u auta')
end
else
ESX.ShowNotification('Nemůžeš sundat 2 SPZ.')
end
end)
RegisterCommand("datspz", function()
if LicencePlate.Index and LicencePlate.Number then
local PlayerPed = PlayerPedId()
local Coords = GetEntityCoords(PlayerPed)
local Vehicle = GetClosestVehicle(Coords.x, Coords.y, Coords.z, 3.5, 0, 70)
local VehicleCoords = GetEntityCoords(Vehicle)
local Distance = Vdist(VehicleCoords.x, VehicleCoords.y, VehicleCoords.z, Coords.x, Coords.y, Coords.z)
if ( (Distance < 3.5) and not IsPedInAnyVehicle(PlayerPed, false) ) then
if (Vehicle == LastVehicle) then
LastVehicle = nil
Animation()
StopAnimTask(PlayerPedId(), "mini@repair", "fixing_a_player", 1.0)
Citizen.Wait(6000)
SetVehicleNumberPlateTextIndex(Vehicle, LicencePlate.Index)
SetVehicleNumberPlateText(Vehicle, LicencePlate.Number)
LicencePlate.Index = false
LicencePlate.Number = false
ESX.ShowNotification('Nasadil jsi SPZ - '..LicencePlate.Number..'')
else
ESX.ShowNotification('Tato SPZ sem nepatří!')
end
else
ESX.ShowNotification('Nejsi u auta!')
end
else
ESX.ShowNotification('Nemáš u sebe SPZ!')
end
end)
function Animation()
local pid = PlayerPedId()
RequestAnimDict("mini")
RequestAnimDict("mini@repair")
while (not HasAnimDictLoaded("mini@repair")) do
Citizen.Wait(10)
end
TaskPlayAnim(pid,"mini@repair","fixing_a_player",1.0,-1.0, 5000, 0, 1, true, true, true)
end
|
---@diagnostic disable: undefined-global
-- Success
function Success()
rulexlib:log("success")
end
-- Failed
function Failed(error)
rulexlib:log(error)
end
---
--- 这里展示一个远程发送到经过ESP8266控制的多路继电器后响应的 Demo:
--- 假设远程指令是打开开关, 然后同步状态到云端, 指令体:
--- {"cmdId": "00001", "cmd" :"open","sw": [1, 2] }
--- [1, 2]表示打开 1 2 两个开关
---
Actions = {
function(data)
local json = require("json")
local Tb = json.decode(data)
local CmdId = Tb["cmdId"]
local Cmd = Tb["cmd"]
local SW = Tb["sw"]
--- 开
if Cmd == "on" then
local ok = rulexlib:WriteOutStream('#ID', json.encode({0x01, SW}))
if ok then
rulexlib:finishCmd(CmdId, "OutId")
else
-- 其实没必要显式调用失败, 因为服务端超时后就自己直接失败了
rulexlib:failedCmd(CmdId, "OutId")
end
end
--- 关
if Cmd == "off" then
local ok = rulexlib:WriteOutStream('#ID', json.encode({0x00, SW}))
if ok then
rulexlib:finishCmd(CmdId, "OutId")
else
-- 其实没必要显式调用失败, 因为服务端超时后就自己直接失败了
rulexlib:failedCmd(CmdId, "OutId")
end
end
return true, data
end
}
|
local function Reply(msg)
local text = msg.content_.text_
if not database:get(bot_id..'Reply:Status'..msg.chat_id_) then
if text == 'هلو' then
TextReply = 'هلوات يروحي🥺♥️'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'شلونكم' then
TextReply = 'تمام وانتا 🥺💘'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'شلونك' then
TextReply = 'مثل لونك ازرك🥺😂'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'تمام' then
TextReply = 'دوم يعمري🥺♥️'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'هلاو' then
TextReply = 'اهلا والف هلا🥺🔥'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == '😐' then
TextReply = 'شبيك صافن ولك😌👌'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'هاي' then
TextReply = 'هايات عمري💘😍'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'بوت زربه' then
TextReply = 'زربه بحلكك وليدي🌚😂'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'اريد اكبل' then
TextReply = 'شوفلي وياك وحده😂🥺'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'لتزحف' then
TextReply = 'لصير لوكي ونجب😪🤞'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'كلخرا' then
TextReply = 'خلي نفسك بماعون🌚😂'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'زاحف' then
TextReply = 'زاحف علي ختك 👐😹'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'دي' then
TextReply = 'ديصيحون ابوك🌚😂'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'فرخ' then
TextReply = 'ماكو غيرك فرخ😹💓'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'تعالي خاص' then
TextReply = 'هلو لصير زاحف ونجب😹👻'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'اكرهك' then
TextReply = 'شدعوه اني احبك🌚😂'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'احبك' then
TextReply = 'اني هم يروحي🥺🔥'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'باي' then
TextReply = 'الله وياك راحتن وخفتن😂😶'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'واكف' then
TextReply = 'شنو هوه واكف😶😑'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'وين المدير' then
TextReply = 'ليش محتاج شي منه 😉😁'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'انجب' then
TextReply = 'جب بحلكك ابني🙂😂'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'تحبني' then
TextReply = 'ما احب لوكيه😹🌚'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == '🌚' then
TextReply = 'فدوه هل سواد🥺😂'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == '🙄' then
TextReply = 'نزل عينك خواتك فوك😹💝'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == '😒' then
TextReply = 'شبيك ضايج يروحي😿👌'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == '😳' then
TextReply = 'لا بس شفت بريعصي😹💘'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == '🙁' then
TextReply = 'ها شنو عافتك حبيبتك 😉😂'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == '🚶💔' then
TextReply = 'ضايج الحلو 😆👋'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == '🙂' then
TextReply = 'ثكيل ابو زربه 😹🥺'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == '🌝' then
TextReply = 'منور حبيبي 💘😍'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'صباحو' then
TextReply = 'صباح العافيه🥺♥️'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'صباح الخير' then
TextReply = 'صباح الخير ياطير🥺😂'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'كفو' then
TextReply = 'منك حبيبي😉👌'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == '😌' then
TextReply = 'مرتاح الزاحف🙊😹'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'اها' then
TextReply = 'يب حبي قابل اغشك😉👋'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'شسمج' then
TextReply = 'اسمها جاسميه😻😹'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'شسمك' then
TextReply = 'اسمه ابو راس 😻🤙'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'شوف' then
TextReply = 'ششوف حبي😑👋'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'مساء الخير' then
TextReply = 'مساء النور 🥺♥️'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'المدرسه' then
TextReply = 'دنجب صاير شاطر😂🌚'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'منو ديحذف رسائلي' then
TextReply = 'خالتكك😹🤟'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'البوت واكف' then
TextReply = 'هياتني شغال لجذب'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'غلس' then
TextReply = 'علي شنو اغلس 🌚😂'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'حارة' then
TextReply = 'اي والله حيل حاره🥵🤯'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'هههه' then
TextReply = 'دومها حبي 🤟😻'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'ههههه' then
TextReply = 'فدوه لهل ضحكه 🥺😍'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == '😹' then
TextReply = 'قرد ويضحك😂👐'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'وين' then
TextReply = 'افتر ورجع😹🤟'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'كافي لغوة' then
TextReply = 'انتا انجب😹🤟'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'نايمين' then
TextReply = 'امشي كعدهم 😹😑'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'اكو احد' then
TextReply = 'اني موجود 😉👋'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'فديت' then
TextReply = 'فداك/ج ثولان العالم😹💝'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'شكو' then
TextReply = 'كلشي اكو سمج دجاج شتريد اكو 😹🤸♀️'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'اوف' then
TextReply = 'اوفات حبي😻💘'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'احبج' then
TextReply = 'دنجب لوكي🥺😻'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
if text == 'انتة منو' then
TextReply = 'اني تاج راسك👑🥺'
send(msg.chat_id_, msg.id_,'['..TextReply..']')
return false
end
end
if text == 'تفعيل ردود البوت' and Manager(msg) then
database:del(bot_id..'Reply:Status'..msg.chat_id_)
send(msg.chat_id_, msg.id_,'🚸| تم تفعيل ردود البوت')
return false
end
if text == 'تعطيل ردود البوت' and Manager(msg) then
database:set(bot_id..'Reply:Status'..msg.chat_id_,true)
send(msg.chat_id_, msg.id_,'🔰| تم تعطيل ردود البوت')
return false
end
end
return {
Tshake = Reply
}
|
data:extend({
{
type = "recipe",
name = "nuclear-furnace",
ingredients = {{"uranium-238", 2}, {"processing-unit", 10}, {"electric-furnace", 1}, {"uranium-235", 1}},
result = "nuclear-furnace",
energy_required = 10,
enabled = false
}
})
|
ITEM.name = "M14 EBR"
ITEM.description= "A modernized M14 battle rifle. Fires 7.62x51mm."
ITEM.longdesc = "The Mk 14 Enhanced Battle Rifle (EBR) is an American selective fire military designated marksman rifle chambered for the 7.62×51mm NATO cartridge.\nIt is a variant of the M14 battle rifle and was originally built for use with units of the United States Special Operations Command, such as the United States Navy SEALs, Delta Force, and task specific ODA units.\nThe EBRs are made with the intention of carrying out both designated marksman and CQB roles in combat.\n\nAmmo: 7.62x51mm \nMagazine Capacity: 20"
ITEM.model = "models/weapons/w_cstm_m14.mdl"
ITEM.class = "cw_m14"
ITEM.weaponCategory = "primary"
ITEM.price = 37500
ITEM.width = 5
ITEM.height = 1
ITEM.validAttachments = {"md_microt1","md_eotech","md_aimpoint","md_cmore","md_schmidt_shortdot","md_acog","md_nightforce_nxs","md_reflex","md_saker","md_foregrip"}
ITEM.bulletweight = 0.026
ITEM.unloadedweight = 5.1
ITEM.repair_PartsComplexity = 2
ITEM.repair_PartsRarity = 4
function ITEM:GetWeight()
return self.unloadedweight + (self.bulletweight * self:GetData("ammo", 0))
end
ITEM.iconCam = {
pos = Vector(10.89999961853, -205, 1),
ang = Angle(0, 90, 0),
fov = 12,
}
ITEM.pacData = {
[1] = {
["children"] = {
[1] = {
["children"] = {
[1] = {
["children"] = {
},
["self"] = {
["Angles"] = Angle(0, 180, 180),
["Position"] = Vector(13.989, -4.313, -1.375),
["Model"] = "models/weapons/w_cstm_m14.mdl",
["ClassName"] = "model",
["EditorExpand"] = true,
["UniqueID"] = "7946894673",
["Bone"] = "spine 2",
["Name"] = "m14",
},
},
},
["self"] = {
["AffectChildrenOnly"] = true,
["ClassName"] = "event",
["UniqueID"] = "1237473522",
["Event"] = "weapon_class",
["EditorExpand"] = true,
["Name"] = "weapon class find simple\"@@1\"",
["Arguments"] = "cw_m14@@0",
},
},
},
["self"] = {
["ClassName"] = "group",
["UniqueID"] = "2787896348",
["EditorExpand"] = true,
},
},
}
|
-- tolua: container abstract class
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- $Id: $
-- This code is free software; you can redistribute it and/or modify it.
-- The software provided hereunder is on an "as is" basis, and
-- the author has no obligation to provide maintenance, support, updates,
-- enhancements, or modifications.
-- table to store namespaced typedefs/enums in global scope
global_typedefs = {}
global_enums = {}
-- Container class
-- Represents a container of features to be bound
-- to lua.
classContainer =
{
curr = nil,
}
classContainer.__index = classContainer
setmetatable(classContainer,classFeature)
-- output tags
function classContainer:decltype ()
push(self)
local i=1
while self[i] do
self[i]:decltype()
i = i+1
end
pop()
end
-- write support code
function classContainer:supcode ()
push(self)
local i=1
while self[i] do
self[i]:supcode()
i = i+1
end
pop()
end
function classContainer:hasvar ()
local i=1
while self[i] do
if self[i]:isvariable() then
return 1
end
i = i+1
end
return 0
end
-- Internal container constructor
function _Container (self)
setmetatable(self,classContainer)
self.n = 0
self.typedefs = {tolua_n=0}
self.usertypes = {}
self.enums = {tolua_n=0}
self.lnames = {}
return self
end
-- push container
function push (t)
t.prox = classContainer.curr
classContainer.curr = t
end
-- pop container
function pop ()
--print("name",classContainer.curr.name)
--foreach(classContainer.curr.usertypes,print)
--print("______________")
classContainer.curr = classContainer.curr.prox
end
-- get current namespace
function getcurrnamespace ()
return getnamespace(classContainer.curr)
end
-- append to current container
function append (t)
return classContainer.curr:append(t)
end
-- append typedef to current container
function appendtypedef (t)
return classContainer.curr:appendtypedef(t)
end
-- append usertype to current container
function appendusertype (t)
return classContainer.curr:appendusertype(t)
end
-- append enum to current container
function appendenum (t)
return classContainer.curr:appendenum(t)
end
-- substitute typedef
function applytypedef (type)
return classContainer.curr:applytypedef(type)
end
-- check if is type
function findtype (type)
local t = classContainer.curr:findtype(type)
return t
end
-- check if is typedef
function istypedef (type)
return classContainer.curr:istypedef(type)
end
-- get fulltype (with namespace)
function fulltype (t)
local curr = classContainer.curr
while curr do
if curr then
if curr.typedefs and curr.typedefs[t] then
return curr.typedefs[t]
elseif curr.usertypes and curr.usertypes[t] then
return curr.usertypes[t]
end
end
curr = curr.prox
end
return t
end
-- checks if it requires collection
function classContainer:requirecollection (t)
push(self)
local i=1
local r = false
while self[i] do
r = self[i]:requirecollection(t) or r
i = i+1
end
pop()
return r
end
-- get namesapce
function getnamespace (curr)
local namespace = ''
while curr do
if curr and
( curr.classtype == 'class' or curr.classtype == 'namespace')
then
namespace = curr.name .. '::' .. namespace
end
curr = curr.prox
end
return namespace
end
-- get namespace (only namespace)
function getonlynamespace ()
local curr = classContainer.curr
local namespace = ''
while curr do
if curr.classtype == 'class' then
return namespace
elseif curr.classtype == 'namespace' then
namespace = curr.name .. '::' .. namespace
end
curr = curr.prox
end
return namespace
end
-- check if is enum
function isenum (type)
return classContainer.curr:isenum(type)
end
-- append feature to container
function classContainer:append (t)
self.n = self.n + 1
self[self.n] = t
t.parent = self
end
-- append typedef
function classContainer:appendtypedef (t)
local namespace = getnamespace(classContainer.curr)
self.typedefs.tolua_n = self.typedefs.tolua_n + 1
self.typedefs[self.typedefs.tolua_n] = t
self.typedefs[t.utype] = namespace .. t.utype
global_typedefs[namespace..t.utype] = t
end
-- append usertype: return full type
function classContainer:appendusertype (t)
local container
if t == self.name then
container = self.prox
else
container = self
end
local ft = getnamespace(container) .. t
container.usertypes[t] = ft
_usertype[ft] = ft
return ft
end
-- append enum
function classContainer:appendenum (t)
local namespace = getnamespace(classContainer.curr)
self.enums.tolua_n = self.enums.tolua_n + 1
self.enums[self.enums.tolua_n] = t
global_enums[namespace..t.name] = t
end
-- determine lua function name overload
function classContainer:overload (lname)
if not self.lnames[lname] then
self.lnames[lname] = 0
else
self.lnames[lname] = self.lnames[lname] + 1
end
return format("%02d",self.lnames[lname])
end
-- applies typedef: returns the 'the facto' modifier and type
function classContainer:applytypedef (type)
if global_typedefs[type] then
local mod1, type1 = global_typedefs[type].mod, global_typedefs[type].type
local mod2, type2 = applytypedef(type1)
return mod2 .. ' ' .. mod1, type2
end
local basetype = gsub(type,"^.*::","")
local env = self
while env do
if env.typedefs then
local i=1
while env.typedefs[i] do
if env.typedefs[i].utype == basetype then
local mod1,type1 = env.typedefs[i].mod,env.typedefs[i].type
local mod2,type2 = applytypedef(type1)
return mod2..' '..mod1,type2
end
i = i+1
end
end
env = env.parent
end
return '',type
end
-- check if it is a typedef
function classContainer:istypedef (type)
local env = self
while env do
if env.typedefs then
local i=1
while env.typedefs[i] do
if env.typedefs[i].utype == type then
return type
end
i = i+1
end
end
env = env.parent
end
return nil
end
-- check if is a registered type: return full type or nil
function classContainer:findtype (t)
local curr = self
while curr do
if curr.typedefs and curr.typedefs[t] then
return curr.typedefs[t]
elseif curr.usertypes and curr.usertypes[t] then
return curr.usertypes[t]
end
curr = curr.prox
end
if _basic[t] then
return t
end
return nil
end
function classContainer:isenum (type)
if global_enums[type] then
return true
end
local basetype = gsub(type,"^.*::","")
local env = self
while env do
if env.enums then
local i=1
while env.enums[i] do
if env.enums[i].name == basetype then
return true
end
i = i+1
end
end
env = env.parent
end
return false
end
-- parse chunk
function classContainer:doparse (s)
-- try Lua code
do
local b,e,code = strfind(s,"^%s*(%b\1\2)")
if b then
Code(strsub(code,2,-2))
return strsub(s,e+1)
end
end
-- try C code
do
local b,e,code = strfind(s,"^%s*(%b\3\4)")
if b then
code = '{'..strsub(code,2,-2)..'\n}\n'
Verbatim(code,'r') -- verbatim code for 'r'egister fragment
return strsub(s,e+1)
end
end
-- try verbatim
do
local b,e,line = strfind(s,"^%s*%$(.-\n)")
if b then
Verbatim(line)
return strsub(s,e+1)
end
end
-- try module
do
local b,e,name,body = strfind(s,"^%s*module%s%s*([_%w][_%w]*)%s*(%b{})%s*")
if b then
_curr_code = strsub(s,b,e)
Module(name,body)
return strsub(s,e+1)
end
end
-- try namesapce
do
local b,e,name,body = strfind(s,"^%s*namespace%s%s*([_%w][_%w]*)%s*(%b{})%s*")
if b then
_curr_code = strsub(s,b,e)
Namespace(name,body)
return strsub(s,e+1)
end
end
-- try define
do
-- Original pattern: "^%s*#define%s%s*([^%s]*)[^\n]*\n%s*"
-- Look for a string value
local b,e,name,value = strfind(s,"^%s*#define%s%s*([^%s]*)%s%s*\"([^%s]*)\"[^\n]*\n%s*")
if b then
print("@@@ #define name: "..name.." string value: "..value)
_curr_code = strsub(s,b,e)
Define(name,"string")
return strsub(s,e+1)
end
--]]
-- Look for a numeric value
local b,e,name,value = strfind(s,"^%s*#define%s%s*([^%s]*)%s%s*([^%s]*)[^\n]*\n%s*")
if b then
print("@@@ #define name: "..name.." numeric value: "..value)
_curr_code = strsub(s,b,e)
Define(name,"number")
return strsub(s,e+1)
end
end
-- try enumerates
do
local b,e,name,body = strfind(s,"^%s*enum%s+(%S*)%s*(%b{})%s*;?%s*")
if b then
_curr_code = strsub(s,b,e)
Enumerate(name,body)
return strsub(s,e+1)
end
end
do
local b,e,body,name = strfind(s,"^%s*typedef%s+enum[^{]*(%b{})%s*([%w_][^%s]*)%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
Enumerate(name,body)
return strsub(s,e+1)
end
end
-- try operator
do
local b,e,decl,kind,arg,const = strfind(s,"^%s*([_%w][_%w%s%*&:]*operator)%s*([^%s][^%s]*)%s*(%b())%s*(c?o?n?s?t?)%s*;%s*")
if not b then
-- try inline
b,e,decl,kind,arg,const = strfind(s,"^%s*([_%w][_%w%s%*&:]*operator)%s*([^%s][^%s]*)%s*(%b())%s*(c?o?n?s?t?)%s*%b{}%s*;?%s*")
end
if b then
_curr_code = strsub(s,b,e)
Operator(decl,kind,arg,const)
return strsub(s,e+1)
end
end
-- try function
do
local b,e,decl,arg,const = strfind(s,"^%s*([~_%w][_@%w%s%*&:]*[_%w])%s*(%b())%s*(c?o?n?s?t?)%s*=?%s*0?%s*;%s*")
if not b then
-- try a single letter function name
b,e,decl,arg,const = strfind(s,"^%s*([_%w])%s*(%b())%s*(c?o?n?s?t?)%s*;%s*")
end
if b then
_curr_code = strsub(s,b,e)
Function(decl,arg,const)
return strsub(s,e+1)
end
end
-- try inline function
do
local b,e,decl,arg,const = strfind(s,"^%s*([~_%w][_@%w%s%*&:]*[_%w])%s*(%b())%s*(c?o?n?s?t?).-%b{}%s*;?%s*")
if not b then
-- try a single letter function name
b,e,decl,arg,const = strfind(s,"^%s*([_%w])%s*(%b())%s*(c?o?n?s?t?).-%b{}%s*;?%s*")
end
if b then
_curr_code = strsub(s,b,e)
Function(decl,arg,const)
return strsub(s,e+1)
end
end
-- try class
do
local b,e,name,base,body
base = '' body = ''
b,e,name = strfind(s,"^%s*class%s*([_%w][_%w@]*)%s*;") -- dummy class
if not b then
b,e,name = strfind(s,"^%s*struct%s*([_%w][_%w@]*)%s*;") -- dummy struct
if not b then
b,e,name,base,body = strfind(s,"^%s*class%s*([_%w][_%w@]*)%s*(.-)%s*(%b{})%s*;%s*")
if not b then
b,e,name,base,body = strfind(s,"^%s*struct%s*([_%w][_%w@]*)%s*(.-)%s*(%b{})%s*;%s*")
if not b then
b,e,name,base,body = strfind(s,"^%s*union%s*([_%w][_%w@]*)%s*(.-)%s*(%b{})%s*;%s*")
if not b then
base = ''
b,e,body,name = strfind(s,"^%s*typedef%s%s*struct%s*[_%w]*%s*(%b{})%s*([_%w][_%w@]*)%s*;%s*")
if not b then
base = ''
b,e,body,name = strfind(s,"^%s*typedef%s%s*union%s*[_%w]*%s*(%b{})%s*([_%w][_%w@]*)%s*;%s*")
end
end
end
end
end
end
if b then
if base ~= '' then
local b,e
b,e,base = strfind(base,".-([_%w][_%w]*)$")
end
_curr_code = strsub(s,b,e)
Class(name,base,body)
return strsub(s,e+1)
end
end
-- try typedef
do
local b,e,types = strfind(s,"^%s*typedef%s%s*(.-)%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
Typedef(types)
return strsub(s,e+1)
end
end
-- try variable
do
local b,e,decl = strfind(s,"^%s*([_%w][_@%s%w%d%*&:]*[_%w%d])%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
Variable(decl)
return strsub(s,e+1)
end
end
-- try string
do
local b,e,decl = strfind(s,"^%s*([_%w]?[_%s%w%d]-char%s+[_@%w%d]*%s*%[%s*%S+%s*%])%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
Variable(decl)
return strsub(s,e+1)
end
end
-- try array
do
local b,e,decl = strfind(s,"^%s*([_%w][][_@%s%w%d%*&:]*[]_%w%d])%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
Array(decl)
return strsub(s,e+1)
end
end
-- no matching
if gsub(s,"%s%s*","") ~= "" then
_curr_code = s
error("#parse error")
else
return ""
end
end
function classContainer:parse (s)
while s ~= '' do
s = self:doparse(s)
end
end
|
--A function that creates new sandboxed global environment.
local basexx = require("Engine.basexx")
local bit = require("bit")
local _LuaBCHeader = string.char(0x1B).."LJ"
return function(Machine, APIS)
local GLOB = {
assert = assert,
error = error,
ipairs = ipairs,
pairs = pairs,
next = next,
pcall = pcall,
select = select,
tonumber = tonumber,
tostring = tostring,
type = type,
unpack = unpack,
_VERSION = _VERSION,
xpcall = xpcall,
setmetatable = setmetatable,
getmetatable = getmetatable,
rawget = rawget,
rawset = rawset,
rawequal = rawequal,
string = {
byte = string.byte,
char = string.char,
find = string.find,
format = string.format,
gmatch = string.gmatch,
gsub = string.gsub,
len = string.len,
lower = string.lower,
match = string.match,
rep = string.rep,
reverse = string.reverse,
sub = string.sub,
upper = string.upper
},
table = {
insert = table.insert,
maxn = table.maxn,
remove = table.remove,
sort = table.sort,
concat = table.concat
},
math = {
abs = math.abs,
acos = math.acos,
asin = math.asin,
atan = math.atan,
atan2 = math.atan2,
ceil = math.ceil,
cos = math.cos,
cosh = math.cosh,
deg = math.deg,
exp = math.exp,
floor = math.floor,
fmod = math.fmod,
frexp = math.frexp,
huge = math.huge,
ldexp = math.ldexp,
log = math.log,
log10 = math.log10,
max = math.max,
min = math.min,
modf = math.modf,
pi = math.pi,
pow = math.pow,
rad = math.rad,
random = love.math.random, --Replaced with love.math versions
randomseed = love.math.setRandomSeed,
sin = math.sin,
sinh = math.sinh,
sqrt = math.sqrt,
tan = math.tan,
tanh = math.tanh,
noise = love.math.noise, --LOVE releated apis
b64enc = basexx.to_base64, --Will be replaced by love.math ones in love 0.11
b64dec = basexx.from_base64,
hexenc = basexx.to_hex,
hexdec = basexx.from_hex,
compress = function(...) return love.math.compress(...):getString() end,
decompress = love.math.decompress,
isConvex = love.math.isConvex,
triangulate = love.math.triangulate,
noise = love.math.noise,
randomNormal = love.math.randomNormal
},
coroutine={
create = coroutine.create,
resume = coroutine.resume,
yield = coroutine.yield,
status = coroutine.status
},
os={
time = os.time,
clock = os.clock,
date = os.date
},
bit={
cast = bit.cast,
bnot = bit.bnot,
band = bit.band,
bor = bit.bor,
bxor = bit.bxor,
lshift = bit.lshift,
rshift = bit.rshift,
arshift = bit.arshift,
tobit = bit.tobit,
tohex = bit.tohex,
rol = bit.rol,
ror = bit.ror,
bswap = bit.swap
}
}
GLOB.getfenv = function(f)
if type(f) ~= "function" then return error("bad argument #1 to 'getfenv' (function expected, got "..type(f)) end
local ok, env = pcall(getfenv,f)
if not ok then return error(env) end
if env.love == love then env = {} end --Protection
return env
end
GLOB.setfenv = function(f,env)
if type(f) ~= "function" then return error("bad argument #1 to 'setfenv' (function expected, got "..type(f)) end
if type(env) ~= "table" then return error("bad argument #2 to 'setfenv' (table expected, got "..type(env)) end
local oldenv = getfenv(f)
if oldenv.love == love then return end --Trying to make a crash ! evil.
local ok, err = pcall(setfenv,f,env)
if not ok then return error(err) end
end
GLOB.loadstring = function(data)
if data:sub(1,3) == _LuaBCHeader then return error("LOADING BYTECODE IS NOT ALLOWED, YOU HACKER !") end
local chunk, err = loadstring(data)
if not chunk then return nil, err end
setfenv(chunk,GLOB)
return chunk
end
GLOB.load = function(iter,chunkname)
if type(iter) ~= "function" then return error("Chunk Iterator should be a function, provided: "..type(iter)) end
if chunkname and type(chunkname) ~= "string" then return error("Chunk Name should be a string or a nil, provided: "..type(chunkname)) end
local first = true
local function i()
local line = iter()
if first and line then
if line:sub(1,3) == _LuaBCHeader then return error("LOADING BYTECODE IS NOT ALLOWED, YOU HACKER !") end
first = false
end
return line
end
local ok, chunk = pcall(load,i,chunkname)
if ok then
setfenv(chunk,GLOB)
return chunk
else
return error(chunk)
end
end
GLOB.coroutine.sethook = function(co,...)
if type(co) ~= "thread" then return error("bad argument #1 (thread expected, got "..type(co)..")") end
local ok, err = pcall(debug.sethook,co,...)
if not ok then return error(err) end
return err
end
GLOB.coroutine.running = function()
local curco = coroutine.running()
if Machine and Machine.CO and curco == Machine.CO then return end
return curco
end
GLOB.APIS = APIS
for k,v in pairs(APIS) do
GLOB[k] = v
end
GLOB._G=GLOB --Mirror Mirror
setfenv(Machine.Chunk, GLOB)
return GLOB
end
|
function RefreshAccount (account, since)
local isFirst = true
local transactions = {}
-- load transactions
repeat
local url = "https://secure.lloydsbank.co.uk/personal/link/lp_statement_ajax?_=" .. os.time() .. "&viewstatement=" .. (isFirst == true and "latest" or "previous")
isFirst = false
local data = JSON(getJSON()):dictionary()
local transactionsData = data["transactions"]["items"]
local lastTimestamp = 0
for _, v in pairs(transactionsData) do
local timestamp = dateStrToTimestamp(v["date"])
table.insert(transactions, {
transactionCode = tonumber(v["id"], 16),
bookingDate = timestamp,
purpose = table.concat(v["completeDescription"], "\n"),
amount = v["amount"]["amount"],
bookingText = v["paymentTypeForPanel"]
})
lastTimestamp = timestamp
end
-- repeat if we need more entries.
-- this also finished if there is no more data to load,
-- because lastTimestamp = 0 is smaller than since
until lastTimestamp < since
return {balance=42.00, transactions=transactions}
end
function dateStrToTimestamp(dateStr)
local yearStr, monthStr, dayStr, hourStr, minStr, secStr = string.match(dateStr, "(%d%d%d%d)-(%d%d)-(%d%d)T(%d%d):(%d%d):(%d%d)")
return os.time({
year = tonumber(yearStr),
month = tonumber(monthStr),
day = tonumber(dayStr),
hour = tonumber(hourStr),
min = tonumber(minStr),
sec = tonumber(secStr)
})
end
|
test = {"t", "t", "n", "n", "t", "n", "t", "t", "t", "n", "n", "n", "t", "n", "t", "t", "t", "n"}
|
local cfg = require("config").layer.fire
local util = require("util")
local core = require("core")
local hexagon = require("hexagon")
local buff = require("buff")
--[[
get:
nil ui, dump all
team, pos internal, get total strength
set:
team, area, duration, strength put fire on the ground
--]]
return function(map, layer_info)
return {
map = map,
fire_list = {},
tick = function(self, team)
local new_list = {}
for i = 1, #self.fire_list, 1 do
local v = self.fire_list[i]
if v.team == team and not core.common_tick(v) then
-- noop
else
table.insert(new_list, v)
end
end
self.fire_list = new_list
end,
apply = function(self, entity)
local strength = self:get(entity.team, entity.pos)
if strength and strength > 0 then
buff.insert_notick(entity, "burn", strength, cfg.burn_duration)
end
end,
contact = function(self, seed)
if seed.element == "fire" then
seed.power = seed.power * cfg.power_fire
elseif seed.element == "water" then
seed.power = seed.power * cfg.power_water
end
return seed
end,
get = function(self, team, pos)
if not team then
return {
fire = self.fire_list,
}
end
local res = 0
for k, v in pairs(self.fire_list) do
if hexagon.cmp(v.pos, pos) and v.team ~= team then
res = res + v.strength
end
end
return res
end,
set = function(self, team, area, duration, strength)
for k, p in pairs(area) do
table.insert(self.fire_list, {
team = team,
pos = p,
duration = duration,
strength = strength,
})
end
end,
}
end
|
visage_summon_familiars_oaa = class(AbilityBaseClass)
function visage_summon_familiars_oaa:OnSpellStart()
local caster = self:GetCaster()
local playerID = caster:GetPlayerID()
local abilityLevel = self:GetLevel()
if caster.familiars == nil then
caster.familiars = {}
end
-- Kill non-dead familiars created with previous cast of this spell
for _, v in pairs(caster.familiars) do
if v and not v:IsNull() then
if v:IsAlive() then
v:ForceKill(false)
end
end
end
local baseUnitName = "npc_dota_visage_familiar"
local levelUnitName = "npc_dota_visage_familiar3"
if abilityLevel <= 3 then
levelUnitName = baseUnitName .. abilityLevel
end
-- KV variables
local number_of_familiars = self:GetSpecialValueFor("total_familiars")
local familiar_hp = self:GetLevelSpecialValueFor("familiar_hp", abilityLevel-1)
local familiar_armor = self:GetLevelSpecialValueFor("familiar_armor", abilityLevel-1)
local familiar_dmg = self:GetLevelSpecialValueFor("familiar_attack_damage", abilityLevel-1)
local familiar_speed = self:GetLevelSpecialValueFor("familiar_speed", abilityLevel-1)
if caster:HasScepter() then
number_of_familiars = self:GetSpecialValueFor("scepter_total_familiars")
end
-- Talent that increases number of familiars
local talent = caster:FindAbilityByName("special_bonus_unique_visage_6")
if talent then
if talent:GetLevel() > 0 then
number_of_familiars = number_of_familiars + talent:GetSpecialValueFor("value")
end
end
-- Talent that increases familiar movement speed
local talent2 = caster:FindAbilityByName("special_bonus_unique_visage_2")
if talent2 then
if talent2:GetLevel() > 0 then
familiar_speed = familiar_speed + talent2:GetSpecialValueFor("value")
end
end
for i = 1, number_of_familiars do
local familiar = self:SpawnUnit(levelUnitName, caster, playerID, false)
-- Level the familiar's stone form ability to match ability level
local stoneFormAbility = familiar:FindAbilityByName("visage_summon_familiars_stone_form")
if stoneFormAbility then
stoneFormAbility:SetLevel(abilityLevel)
end
-- Add built-in modifier that handles flying and other stuff
familiar:AddNewModifier(caster, self, "modifier_visage_summon_familiars_damage_charge", {})
-- Fix stats of familiars
-- HP
familiar:SetBaseMaxHealth(familiar_hp)
familiar:SetMaxHealth(familiar_hp)
familiar:SetHealth(familiar_hp)
-- DAMAGE
familiar:SetBaseDamageMin(familiar_dmg)
familiar:SetBaseDamageMax(familiar_dmg)
-- ARMOR
familiar:SetPhysicalArmorBaseValue(familiar_armor)
-- Set Familiar movement speed
familiar:SetBaseMoveSpeed(familiar_speed)
-- Create particle effects
--local particleName = ".vpcf"
--local particle = ParticleManager:CreateParticle(particleName, PATTACH_CUSTOMORIGIN, caster)
--ParticleManager:SetParticleControl(particle, 0, unit:GetOrigin())
--ParticleManager:ReleaseParticleIndex(particle)
-- Store familiars on the caster handle
table.insert(caster.familiars, familiar)
end
-- Sound
caster:EmitSound("Hero_Visage.SummonFamiliars.Cast")
end
function visage_summon_familiars_oaa:OnUpgrade()
local caster = self:GetCaster()
local abilityLevel = self:GetLevel()
local self_cast_ability = caster:FindAbilityByName("visage_stone_form_self_cast")
-- Check to not enter a level up loop
if self_cast_ability and self_cast_ability:GetLevel() ~= abilityLevel then
self_cast_ability:SetLevel(abilityLevel)
end
-- Shard hidden ability
if caster:HasShardOAA() then
local stone_form_ability = caster:FindAbilityByName("visage_summon_familiars_stone_form")
-- Check to not enter a level up loop
if stone_form_ability then
if stone_form_ability:GetLevel() ~= abilityLevel then
stone_form_ability:SetLevel(abilityLevel)
end
end
end
end
-- Copied and modified from Beastmaster Call of the Wild Boar and Hawk
function visage_summon_familiars_oaa:SpawnUnit(levelUnitName, caster, playerID, bRandomPosition)
local position = caster:GetOrigin()
if bRandomPosition then
position = position + RandomVector(1):Normalized() * RandomFloat(50, 100)
end
local npcCreep = CreateUnitByName(levelUnitName, position, true, caster, caster:GetOwner(), caster:GetTeam())
npcCreep:SetControllableByPlayer(playerID, false)
npcCreep:SetOwner(caster)
npcCreep:SetForwardVector(caster:GetForwardVector())
return npcCreep
end
|
test = require 'u-test'
common = require 'common'
local function VerifySuccess(hr)
SetCheckHR(1)
if hr ~= 0 then
test.equal(hr, 0)
print("Failure. hr=" .. hr)
test.stopTest()
end
return true
end
function AchievementsManagerPerformance_Handler( ... )
print("AchievementsManagerPerformance_Handler")
-- start test
SetupAchievementsManagerPerformanceTestMock()
StartAchievementsManagerDoWorkLoop()
XblAchievementsManagerAddLocalUser()
end
function OnXblAchievementsManagerDoWork_LocalUserAddedEvent()
print("OnXblAchievementsManagerDoWork_LocalUserAddedEvent")
-- call get achievements performance test
handle, hr = XblAchievementsManagerGetAchievementsPerfTest()
VerifySuccess(hr)
count, hr = XblAchievementsManagerResultGetAchievements(handle)
if count ~= 100 then
test.equal(hr, 0);
print("Failure. Number of achievements found (" .. count .. ") different from expected (100). hr=" .. hr)
test.stopTest()
end
VerifySuccess(hr)
XblAchievementsManagerResultCloseHandle(handle)
XblAchievementsManagerRemoveLocalUser()
StopAchievementsManagerDoWorkLoop()
test.stopTest()
end
test.isbvt = true
test.TestAchievementsManager = function()
common.init(AchievementsManagerPerformance_Handler)
end
|
local oop = require('oop.oop')
_G.class = oop.class
_G.static = oop.static
|
local class = require "com/class"
local BootSettings = class:derive("BootSettings")
local Vec2 = require("src/Essentials/Vector2")
local Button = require("src/Kernel/UI/Button")
local Checkbox = require("src/Kernel/UI/Checkbox")
function BootSettings:new(bootScreen)
self.bootScreen = bootScreen
-- prepare fonts of various sizes
self.font = love.graphics.newFont()
self.fontBig = love.graphics.newFont(18)
-- buttons
self.menuBtn = Button("Save and Go Back", self.fontBig, Vec2(30, 546), Vec2(300, 24), function() engineSettings:save(); self.bootScreen:setScene("main") end)
self.settingCheckboxes = {
Checkbox("Enable Discord Rich Presence", self.fontBig, Vec2(40, 110), Vec2(760, 24), function(state) engineSettings:setDiscordRPC(state) end),
Checkbox("Go back to the boot menu when exiting a game", self.fontBig, Vec2(40, 140), Vec2(760, 24), function(state) engineSettings:setBackToBoot(state) end),
Checkbox("Aiming Retical", self.fontBig, Vec2(40, 170), Vec2(760, 24), function(state) engineSettings:setAimingRetical(state) end),
Checkbox("Debug console window (restart to see the effect)", self.fontBig, Vec2(40, 200), Vec2(760, 24), function(state) engineSettings:setConsoleWindow(state) end),
Checkbox("Enable 3D Sound", self.fontBig, Vec2(40, 230), Vec2(760, 24), function(state) engineSettings:set3DSound(state) end)
}
end
function BootSettings:init()
self.settingCheckboxes[1].selected = engineSettings:getDiscordRPC()
self.settingCheckboxes[2].selected = engineSettings:getBackToBoot()
self.settingCheckboxes[3].selected = engineSettings:getAimingRetical()
self.settingCheckboxes[4].selected = engineSettings:getConsoleWindow()
self.settingCheckboxes[5].selected = engineSettings:get3DSound()
end
function BootSettings:update(dt)
-- buttons
self.menuBtn:update(dt)
for i, checkbox in ipairs(self.settingCheckboxes) do
checkbox:update(dt)
end
end
function BootSettings:draw()
-- White color
love.graphics.setColor(1, 1, 1)
-----------------------------
-- HEADER
-----------------------------
love.graphics.setFont(self.fontBig)
love.graphics.print("OpenSMCE Boot Menu", 30, 30)
love.graphics.print(string.format("Version: %s (%s)", VERSION_NAME, VERSION), 520, 30)
-----------------------------
-- SETTING LIST
-----------------------------
love.graphics.print("Settings", 30, 70)
love.graphics.setColor(1, 1, 1)
love.graphics.setLineWidth(4)
love.graphics.rectangle("line", 30, 100, 740, 200) -- frame
-----------------------------
-- GO BACK BUTTON
-----------------------------
self.menuBtn:draw()
for i, checkbox in ipairs(self.settingCheckboxes) do
checkbox:draw()
end
end
function BootSettings:mousereleased(x, y, button)
-- Buttons
self.menuBtn:mousereleased(x, y, button)
for i, checkbox in ipairs(self.settingCheckboxes) do
checkbox:mousereleased(x, y, button)
end
end
return BootSettings
|
---@meta
---@class cc.ControlSwitch :cc.Control
local ControlSwitch={ }
cc.ControlSwitch=ControlSwitch
---@overload fun(boolean:boolean):self
---@overload fun(boolean:boolean,boolean:boolean):self
---@param isOn boolean
---@param animated boolean
---@return self
function ControlSwitch:setOn (isOn,animated) end
---*
---@param touch cc.Touch
---@return vec2_table
function ControlSwitch:locationFromTouch (touch) end
---*
---@return boolean
function ControlSwitch:isOn () end
---@overload fun(cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite,cc.Label:cc.Label,cc.Label:cc.Label):self
---@overload fun(cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite):self
---@param maskSprite cc.Sprite
---@param onSprite cc.Sprite
---@param offSprite cc.Sprite
---@param thumbSprite cc.Sprite
---@param onLabel cc.Label
---@param offLabel cc.Label
---@return boolean
function ControlSwitch:initWithMaskSprite (maskSprite,onSprite,offSprite,thumbSprite,onLabel,offLabel) end
---*
---@return boolean
function ControlSwitch:hasMoved () end
---@overload fun(cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite):self
---@overload fun(cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite,cc.Sprite:cc.Sprite,cc.Label:cc.Label,cc.Label:cc.Label):self
---@param maskSprite cc.Sprite
---@param onSprite cc.Sprite
---@param offSprite cc.Sprite
---@param thumbSprite cc.Sprite
---@param onLabel cc.Label
---@param offLabel cc.Label
---@return self
function ControlSwitch:create (maskSprite,onSprite,offSprite,thumbSprite,onLabel,offLabel) end
---*
---@param enabled boolean
---@return self
function ControlSwitch:setEnabled (enabled) end
---*
---@param pTouch cc.Touch
---@param pEvent cc.Event
---@return self
function ControlSwitch:onTouchMoved (pTouch,pEvent) end
---*
---@param pTouch cc.Touch
---@param pEvent cc.Event
---@return self
function ControlSwitch:onTouchEnded (pTouch,pEvent) end
---*
---@param pTouch cc.Touch
---@param pEvent cc.Event
---@return self
function ControlSwitch:onTouchCancelled (pTouch,pEvent) end
---*
---@param pTouch cc.Touch
---@param pEvent cc.Event
---@return boolean
function ControlSwitch:onTouchBegan (pTouch,pEvent) end
---* js ctor<br>
---* lua new
---@return self
function ControlSwitch:ControlSwitch () end
|
local StateMachine = require "src.util.statemachine"
describe("StateMachine", function()
local sm
local entity
setup(function()
entity = {}
entity.enter = function(self) end
entity.update = function(self) end
entity.draw = function(self) end
end)
before_each(function()
sm = StateMachine:new(entity, {
enter = "enter",
update = "update",
draw = "draw"
})
end)
it("addState adds a state to the machine", function()
local state = {}
sm:addState("id", state)
assert.is.equal(sm.states["id"], state)
end)
describe("setState", function()
before_each(function()
sm:addState("id", { enter = "enter" })
end)
it("sets the current state", function()
sm:setState("id")
assert.is.equal(sm.currentId, "id")
end)
it("calls enter", function()
local s = spy.on(entity, "enter")
sm:setState("id")
assert.spy(s).was_called()
end)
end)
describe("update", function()
before_each(function()
entity.newUpdate = function(self) end
entity.returnUpdate = function(self)
return "default"
end
sm:addState("new", {
update = "newUpdate",
})
sm:addState("return", {
update = "returnUpdate",
})
sm:addState("noUpdate", {})
end)
it("calls the default update method if currentId is nil", function()
local s = spy.on(entity, "update")
sm.currentId = nil
sm:update()
assert.spy(s).was_called()
end)
it("calls the default update method if the current state has no update method", function()
local s = spy.on(entity, "update")
sm.currentId = "noUpdate"
sm:update()
assert.spy(s).was_called()
end)
it("calls the correct update method for a state", function()
local s = spy.on(entity, "newUpdate")
sm.currentId = "new"
sm:update()
assert.spy(s).was_called()
end)
it("calls setState when a new state is returned", function()
local s = spy.on(sm, "setState")
sm.currentId = "return"
sm:update()
assert.spy(s).was_called_with(match.is.ref(sm), "default")
assert.is.equal(sm.currentId, "default")
end)
end)
describe("draw", function()
before_each(function()
entity.newDraw = function(self) end
sm:addState("new", {
draw = "newDraw",
})
sm:addState("noDraw", {})
end)
it("calls the default draw function if the current state is nil", function()
local s = spy.on(entity, "draw")
sm.currentId = nil
sm:draw()
assert.spy(s).was_called()
end)
it("calls the default draw method if the current state has no draw method", function()
local s = spy.on(entity, "draw")
sm.currentId = "noDraw"
sm:draw()
assert.spy(s).was_called()
end)
it("calls the correct draw method for a state", function()
local s = spy.on(entity, "newDraw")
sm.currentId = "new"
sm:draw()
assert.spy(s).was_called()
end)
end)
end)
|
nuclear.debug.log("Init recipes...")
require(no_path_p_recipes .. "ammo")
require(no_path_p_recipes .. "decay")
require(no_path_p_recipes .. "fluoride")
require(no_path_p_recipes .. "enrichment")
require(no_path_p_recipes .. "fuel")
require(no_path_p_recipes .. "processing")
require(no_path_p_recipes .. "reactor")
require(no_path_p_recipes .. "recycle")
|
-- set all the info
config = require "modconfig"
require("botlife")
config.CreateRconInt("dennisness", 0, 9001, 10, "set teh dennisness to over 9000!!")
Srv.Console:Print("dennis", "blub, init running!")
Srv.Console:Register("dennis_is_krass", "r", "much dennis!", function(result)
Srv.Console:Print("you dennissed!", "with: " .. result:GetString(0))
end)
-- command tele_all
Srv.Console:Register("tele_all", "?i", "Tele all players to ID (default yourself)", function(result)
local TargetID = result:OptInteger(0, result:GetCID())
local target = Srv.Game:GetPlayerChar(TargetID)
-- check if target exists
if target == nil then
Srv.Console:Print("tele_all", "target player must exist and be ALIVE")
return
end
-- teleport all
local num = 0
for CID = 0, 128 do
local chr = Srv.Game:GetPlayerChar(CID)
if chr ~= nil then
print("tele " .. CID .. " from " .. tostring(chr.Pos) .. " to " .. tostring(target.Pos))
chr.Pos = target.Pos
chr.Core.Pos = target.Core.Pos
--chr:Tick()
num = num + 1
end
end
Srv.Console:Print("tele_all", "teleported " .. num .. " people to " .. Srv.Server:GetClientName(TargetID))
end)
-- command tele
Srv.Console:Register("tele", "i?i", "tele ID to ID (default to yourself)", function(result)
local VictimID = result:GetInteger(0)
local victim = Srv.Game:GetPlayerChar(VictimID)
local TargetID = result:OptInteger(1, result:GetCID())
local target = Srv.Game:GetPlayerChar(TargetID)
print("tele " .. VictimID .. " -> " .. TargetID)
-- check if victim exists
if victim == nil then
Srv.Console:Print("tele", "victim player must exist and be ALIVE")
return
end
-- check if target exists
if target == nil then
Srv.Console:Print("tele", "target player must exist and be ALIVE")
return
end
-- teleport victim to target
print("tele " .. VictimID .. " from " .. tostring(victim.Pos) .. " to " .. tostring(target.Pos))
victim.Pos = target.Pos + vec2(0, -5)
victim.Core.Pos = target.Core.Pos + vec2(0, -5)
Srv.Console:Print("tele", "teleported " .. Srv.Server:GetClientName(VictimID) .. " to " .. Srv.Server:GetClientName(TargetID))
end)
-- command create_bot
Srv.Console:Register("create_bot", "", "create a brainless tee", function(result)
local bot = botlife.BotController:new("BOTTER " .. math.random())
if bot then
local BotID = bot:GetCID()
-- Brainless Tee was successfully created
Srv.Server:SetClientName(BotID, "Bot " .. BotID)
Srv.Console:Print("create_bot", "Bot with ID=" .. BotID .. " was created successfully c:")
else
Srv.Console:Print("create_bot", "Failed to add bot, is the server full?")
end
end)
-- command remove_bot
Srv.Console:Register("remove_bot", "i?s", "remove a brainless tee with an optional leave message", function(result)
local BotID = result:GetInteger(0)
local bot = botlife.GetByCID(BotID)
if bot ~= nil and bot:Delete(false, result:OptString(1, "cya nabs")) then
Srv.Console:Print("remove_bot", "Bot was removed successfully c:")
else
Srv.Console:Print("remove_bot", "Invalid bot ID " .. BotID)
end
end)
Srv.Console:Register("walk_bot", "iii", "make a bot walk towards a point", function(result)
local BotID = result:GetInteger(0)
local bot = botlife.GetByCID(BotID)
if bot ~= nil then
bot:MoveTo(vec2(result:GetInteger(1), result:GetInteger(2)),true,true)
else
Srv.Console:Print("remove_bot", "Invalid bot ID " .. BotID)
end
end)
Srv.Console:Register("make_dennis", "", "dew it!", function(result)
local ninjadude = Srv.Game:CreateEntityPickup(2, 3) -- 3 5
ninjadude:BindClass("Dennis")
table.insert(Character.ents, ninjadude)
print(#Character.ents, tostring(ninjadude))
Srv.Console:Print("make_dennis", "made a dennis!")
end)
Srv.Console:Register("give_amazingness_dennis", "i?i?i?i", "Give'em teh real shit bro (ID, NUM_RINGS, ENTS_PER_RING, MAX_CAPT_DIST)", function(result)
local GiveTo = result:GetInteger(0)
local pl = Srv.Game:GetPlayer(GiveTo)
if pl == nil then
Srv.Console:Print("dennisdude", "There is no player with ID " .. GiveTo)
return
end
local NumRings = result:OptInteger(1, 3)
local EntsPerRing = result:OptInteger(2, 8)
local MaxCaptDist = result:OptInteger(3, 500)
local Success = pl:GetSelf():createDennis(pl, NumRings, EntsPerRing, MaxCaptDist)
if Success == true then
Srv.Console:Print("dennisdude", "Given awesomeness to " .. Srv.Server:GetClientName(GiveTo))
else
Srv.Console:Print("dennisdude", Srv.Server:GetClientName(GiveTo) .. " has already got awesomeness!")
end
end)
Srv.Console:Register("remove_dennis", "i", "he not worth dem awesomenezz! REMOVE!", function (result)
local CID = result:GetInteger(0)
local pl = Srv.Game:GetPlayer(CID)
if pl == nil then
Srv.Console:Print("dennisdude", "There is no player with ID " .. CID)
return
end
local Success = pl:GetSelf():destroyDennis(pl)
if Success == true then
Srv.Console:Print("dennisdude", "Removed awesomeness of " .. Srv.Server:GetClientName(CID))
else
Srv.Console:Print("dennisdude", Srv.Server:GetClientName(CID) .. " is not so very awesome already!")
end
end)
print("++++++++++LUA INIT DONE++++++++++++++++")
|
--utils:log("newUserRegistration", "Loaded");
local scene = composer.newScene();
scene.resMan = nil;
---
-- Handler for the create event.
--
-- @param inEvent The event object.
--
function scene:create(inEvent)
--utils:log("newUserRegistration", "create()");
self.resMan = utils:newResourceManager();
local totalYAdj = 50;
-- Instructions text.
self.resMan:newTextCandy("textInstructions", {
parentGroup = self.view, fontName = "fontInstructions", lineSpacing = -14, textFlow = "CENTER",
x = display.contentCenterX, originY = "TOP", y = 320 + totalYAdj, wrapWidth = display.contentWidth - 80,
text = "To play challenges against others you need to be registered. If you've already registered then log " ..
"in below. If this is your first time here then choose a username and password.";
});
local tfWidth = display.contentWidth - 100;
local tfHeight = 100;
local tfStartX = display.contentCenterX;
local tfStartY = 800 + totalYAdj;
local tfYInc = 150;
local rrWidth = tfWidth + 30;
local rrHeightPad = tfHeight + 30;
local rrCornerRadius = 20;
local rrStrokeWidth = 6;
-- Username text field.
local rrUsername = self.resMan:newRoundedRect(
"rrUsername", self.view, tfStartX, tfStartY, rrWidth, rrHeightPad, rrCornerRadius
);
rrUsername.strokeWidth = rrStrokeWidth;
rrUsername:setFillColor(0, 0, 0, 0);
rrUsername:setStrokeColor(255, 255, 255);
local tfUsername = self.resMan:newTextField("tfUsername", tfStartX, tfStartY, tfWidth, tfHeight);
tfUsername.text = "";
tfUsername.hasBackground = false;
tfUsername.placeholder = "Username";
tfUsername.maxLength = 10;
tfUsername:setTextColor(1, 1, 1);
tfUsername.isVisible = false;
self.view:insert(tfUsername);
-- Password text field.
local rrPassword = self.resMan:newRoundedRect(
"rrPassword", self.view, tfStartX, self.resMan:getTextField("tfUsername").y + tfYInc,
rrWidth, rrHeightPad, rrCornerRadius
);
rrPassword.strokeWidth = rrStrokeWidth;
rrPassword:setFillColor(0, 0, 0, 0);
rrPassword:setStrokeColor(255, 255, 255);
local tfPassword = self.resMan:newTextField(
"tfPassword", tfStartX, self.resMan:getTextField("tfUsername").y + tfYInc, tfWidth, tfHeight
);
tfPassword.text = "";
tfPassword.hasBackground = false;
tfPassword.placeholder = "Password";
tfPassword.maxLength = 25;
tfPassword:setTextColor(1, 1, 1);
tfPassword.isVisible = false;
self.view:insert(tfPassword);
-- Go button.
local btnGo = self.resMan:newSprite("btnGo", self.view, uiImageSheet, {
{ name = "default", start = uiSheetInfo:getFrameIndex("btnGo"), count = 1, time = 9999 }
});
btnGo.x = display.contentCenterX;
btnGo.y = 1150 + totalYAdj;
btnGo.alpha = 0.5;
-- Back button.
local btnBack = self.resMan:newSprite("btnBack", self.view, uiImageSheet, {
{ name = "default", start = uiSheetInfo:getFrameIndex("btnBack"), count = 1, time = 9999 }
});
btnBack.x = display.contentCenterX;
btnBack.y = display.contentHeight - 100;
end -- End create().
---
-- Handler for the show event.
--
-- @param inEvent The event object.
--
function scene:show(inEvent)
if inEvent.phase == "did" then
--utils:log("newUserRegistration", "show(): did");
if textTitle.isVisible == false then
textTitle.isVisible = true;
textTitle:startAnimation();
end
-- Attach listeners to TextCandy objects.
self.resMan:getSprite("btnBack"):addEventListener("touch",
function(inEvent)
self:btnBackTouchHandler(inEvent);
return true;
end
);
self.resMan:getSprite("btnGo"):addEventListener("touch",
function(inEvent)
self:btnGoTouchHandler(inEvent);
return true;
end
);
-- Attach listeners to native text fields.
self.resMan:getTextField("tfUsername"):addEventListener("userInput",
function(inEvent)
self:textInputHandler(inEvent);
return true;
end
);
self.resMan:getTextField("tfPassword"):addEventListener("userInput",
function(inEvent)
self:textInputHandler(inEvent);
return true;
end
);
-- Attach listener for enterFrame event.
Runtime:addEventListener("enterFrame", self);
self.resMan:getTextField("tfUsername").isVisible = true;
self.resMan:getTextField("tfPassword").isVisible = true;
end
end -- End show().
---
-- Handler for the hide event.
--
-- @param inEvent The event object.
--
function scene:hide(inEvent)
if inEvent.phase == "did" then
--utils:log("newUserRegistration", "hide(): did");
-- Detach listener for enterFrame event.
Runtime:removeEventListener("enterFrame", self);
end
end -- End hide().
---
-- Handler for the destroy event.
--
-- @param inEvent The event object.
--
function scene:destroy(inEvent)
--utils:log("newUserRegistration", "destroy()");
self.resMan:destroyAll();
end -- End destroy().
---
-- Handler for the enterFrame event.
--
-- @param inEvent The event object.
--
function scene:enterFrame(inEvent)
end -- End enterFrame().
---
-- Handler for touch events on the Back button.
--
-- @param inEvent The event object.
--
function scene:btnBackTouchHandler(inEvent)
if inEvent.phase == "began" then
inEvent.target.fill.effect = "filter.monotone";
inEvent.target.fill.effect.r = 1;
display.getCurrentStage():setFocus(inEvent.target);
elseif inEvent.phase == "ended" then
inEvent.target.fill.effect = nil;
display.getCurrentStage():setFocus(nil);
audio.play(uiTap);
self.resMan:getTextField("tfUsername").isVisible = false;
self.resMan:getTextField("tfPassword").isVisible = false;
composer.gotoScene("menu.main", SCENE_TRANSITION_EFFECT, SCENE_TRANSITION_TIME);
end
end -- End btnBackTouchHandler().
---
-- Handler for typing events on the native text fields.
--
-- @param inEvent The event object.
--
function scene:textInputHandler(inEvent)
if inEvent.phase == "editing" then
-- Limit to these characters.
for i = 1, string.len(inEvent.text), 1 do
if string.find(
"aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789!#$*()-_'.",
string.sub(inEvent.text, i, i), 1, true
) == nil then
inEvent.target.text = inEvent.oldText;
end
end
-- Ensure it doesn't exceed the max allowed.
if string.len(inEvent.text) > inEvent.target.maxLength then
inEvent.target.text = inEvent.oldText;
end
-- Also, whenever all entry fields have a value, enable the Register text.
if string.len(self.resMan:getTextField("tfUsername").text) ~= 0 and
string.len(self.resMan:getTextField("tfPassword").text) ~= 0 then
self.resMan:getSprite("btnGo").alpha = 1;
else
self.resMan:getSprite("btnGo").alpha = 0.5;
end
end
end -- End textInputHandler().
---
-- Handler for touch events on the Go button.
--
-- @param inEvent The event object.
--
function scene:btnGoTouchHandler(inEvent)
if inEvent.phase == "began" and inEvent.target.alpha == 1.0 then
inEvent.target.fill.effect = "filter.monotone";
inEvent.target.fill.effect.r = 1;
display.getCurrentStage():setFocus(inEvent.target);
elseif (inEvent.phase == "ended" or inEvent.phase == "cancelled") and inEvent.target.alpha == 1.0 then
inEvent.target.fill.effect = nil;
display.getCurrentStage():setFocus(nil);
audio.play(uiTap);
self.resMan:getTextField("tfUsername").isVisible = false;
self.resMan:getTextField("tfPassword").isVisible = false;
serverDelegate:registerUser(
self.resMan:getTextField("tfUsername").text, self.resMan:getTextField("tfPassword").text,
function(inResult)
self.resMan:getTextField("tfUsername").text = "";
self.resMan:getTextField("tfPassword").text = "";
if inResult == "registered" then
dialog:show({
text = "Success! You are now registered and logged in and can enter the Challenge Lobby. " ..
"I'll take you there right now.",
callback = function(inButtonType)
composer.gotoScene("challengeLobby.main", SCENE_TRANSITION_EFFECT, SCENE_TRANSITION_TIME);
end
});
elseif inResult == "alreadyRegistered" then
dialog:show({
text = "I'm sorry but that username is already taken. If it's yours then please check the password " ..
"and try again. If you DID NOT previously register it then please choose a new username.",
callback = function(inButtonType)
self.resMan:getTextField("tfUsername").isVisible = true;
self.resMan:getTextField("tfPassword").isVisible = true;
end
});
elseif inResult == "loggedIn" then
dialog:show({
text = "Welcome back, " .. utils:trim(serverDelegate.username) .. "! " ..
"You are now logged in and can enter the Challenge Lobby. I'll take you there right now.",
callback = function(inButtonType)
composer.gotoScene("challengeLobby.main", SCENE_TRANSITION_EFFECT, SCENE_TRANSITION_TIME);
end
});
end
end
);
end
end -- End btnGoTouchHandler().
-- *********************************************************************************************************************
-- *********************************************************************************************************************
--utils:log("newUserRegistration", "Attaching lifecycle handlers");
scene:addEventListener("create", scene);
scene:addEventListener("show", scene);
scene:addEventListener("hide", scene);
scene:addEventListener("destroy", scene);
return scene;
|
function random_pair(upper, ...)
--[[--
Returns a pair of random points in the interval [1,upper]. Each
point is picked with uniform probability. The pair (v0,v1) also has
the property that v0 != v1. The results are returned in order. If
a second argument is passed to the function, it becomes a fixed
member of the pair.
--]]--
local args = table.pack(...)
local v0, v1
if args ~= nil and args.n == 1 then
v0 = args[1]
else
v0 = math.random(upper)
end
v1 = math.random(upper)
while v1 == v0 do -- no equality
v1 = math.random(upper)
end
if v0 <= v1 then
return v0, v1
else
return v1, v0
end
end
function create_graph(graph_type, npoints, nedges, fname)
--[[--
This function creates different types of graphs with
npoints points and
nedges edges for pure random graphs
nedges * npoints edges for regular random graphs
npoints * 2 edges for contiguous graphs
nedges edges for graphs from file
The graph type must be one of
'pure_random'
'regular_random'
'contiguous'
'file'
--]]--
local t = {
pure_random = pure_random_graph,
regular_random = regular_random_graph,
contiguous = regular_contiguous_graph,
file = graph_from_file
}
if t[graph_type] == nil then
print("Unknown graph type specified.")
return {}
end
return t[graph_type](npoints, nedges, fname)
end
function pure_random_graph(npoints, nedges)
--[[--
Returns a pure, undirected random graph, i.e. each edge is picked,
at random, from the interval [1, npoints] with uniform
probability. We ensure that there are no duplicate edges of the
form (v0, v1) and (v1, v0) by ordering the vertices in each edge so
that v0 <= v1.
--]]--
-- seed random number generator
math.randomseed(os.time())
local e = {}
for i = 1,nedges do
v0, v1 = random_pair(npoints)
while e[v0] ~= nil and e[v0][v1] do -- no redunant edges
v0, v1 = random_pair(npoints)
end
if e[v0] == nil then
e[v0] = {}
end
e[v0][v1] = true
end
return e
end
function regular_random_graph(npoints, degree)
--[[--
Returns a random semi-regular graph, where each vertex has
degree close to 'degree'. Edges are sampled uniformly from
the interval
[1, npoints] \ v
for each vertex v. Note that there are no duplicate edges,
but the degree of each vertex varies about 'degree'.
--]]--
-- seed random number generator
math.randomseed(17)
local e = {}
for i = 1,npoints do
for j = 1,degree do
local v0, v1 = random_pair(npoints, i)
if e[v0] == nil then
e[v0] = {}
end
e[v0][v1] = true
end
end
return e
end
function regular_contiguous_graph(npoints)
--[[--
Returns an undirected graph with two edges per vertex. The
edges should be contiguous in memory, i.e. edges are of the form
(i, i+1), (i+1, i+2), (i+2, i+3) etc.
--]]--
local e = {}
for i = 1,npoints do
local v
if i < npoints then
v = i + 1
else
v = 1
end
if e[i] == nil then
e[i] = {}
end
e[i][v] = true
end
return e
end
function graph_to_file(edges, fname)
--[[--
Writes the edges in the table 'edges' to the file 'fname', one edge
per line in the form x,y.
--]]--
local file = io.open(fname, "w")
for k,v in pairs(edges) do
for x,_ in pairs(v) do
file:write(k .. "," .. x .. "\n")
end
end
file:close()
end
function graph_from_file(npoints, nedges, fname)
--[[--
Reads and returns a table of edges from the file 'fname'. Edges,
one per line, should be of the form x,y.
--]]--
local e = {}
local p = {}
local file = io.open(fname, "r")
local edge_ct = 0
for line in file:lines() do
local v0, v1
string.gsub(line, "(%d+),(%d+)", function(x,y) v0 = x v1 = y end)
if e[v0] == nil then
e[v0] = {}
end
e[v0][v1] = true
p[v0] = true
p[v1] = true
edge_ct = edge_ct + 1
end
file:close()
--local point_ct = 0
--for _ in pairs(p) do point_ct = point_ct + 1 end
--if edge_ct ~= nedges or point_ct ~= npoints then
if edge_ct ~= nedges then
print("Error, graph from file", fname, "does not")
print("match nedges:", nedges, edge_ct)
return {}
end
return e
end
function test ()
t0 = os.time()
--edges = pure_random_graph(5,10)
--edges = regular_random_graph(10,2)
--edges = regular_contiguous_graph(10)
t1 = os.time()
print("Graph Creation Time: " .. t1 - t0)
e = 0
t0 = os.time()
for k,v in pairs(edges) do
for x,_ in pairs(v) do
print(k .. "," .. x)
e = e + 1
end
end
t1 = os.time()
print("Graph iteration time: " .. t1 - t0)
print("Done")
print("Created graph with " .. e .. " edges")
end
|
local grpc_json = require('conf.client.etcd.grpc_json')
local function new()
local protocol = grpc_json.new_protocol()
-- https://github.com/etcd-io/etcd/blob/v3.4.15/mvcc/mvccpb/kv.proto
-- https://github.com/etcd-io/etcd/blob/v3.4.15/etcdserver/etcdserverpb/rpc.proto
-- {{{ General purpose messages
protocol:add_message('ResponseHeader', {
[1] = {'uint64', 'cluster_id'},
[2] = {'uint64', 'member_id'},
[3] = {'int64', 'revision'},
[4] = {'uint64', 'raft_term'},
})
protocol:add_message('KeyValue', {
[1] = {'bytes', 'key'},
[2] = {'int64', 'create_revision'},
[3] = {'int64', 'mod_revision'},
[4] = {'int64', 'version'},
[5] = {'bytes', 'value'},
[6] = {'int64', 'lease'},
})
-- }}} General purpose messages
-- {{{ Range request / response
protocol:add_enum('SortOrder', {
[0] = 'NONE',
[1] = 'ASCEND',
[2] = 'DESCEND',
})
protocol:add_enum('SortTarget', {
[0] = 'KEY',
[1] = 'VERSION',
[2] = 'CREATE',
[3] = 'MOD',
[4] = 'VALUE',
})
protocol:add_message('RangeRequest', {
[1] = {'bytes', 'key'},
[2] = {'bytes', 'range_end'},
[3] = {'int64', 'limit'},
[4] = {'int64', 'revision'},
[5] = {'SortOrder', 'sort_order'},
[6] = {'SortTarget', 'sort_target'},
[7] = {'bool', 'serializable'},
[8] = {'bool', 'keys_only'},
[9] = {'bool', 'count_only'},
[10] = {'int64', 'min_mod_revision'},
[11] = {'int64', 'max_mod_revision'},
[12] = {'int64', 'min_create_revision'},
[13] = {'int64', 'max_create_revision'},
})
protocol:add_message('RangeResponse', {
[1] = {'ResponseHeader', 'header'},
[2] = {'repeated', 'KeyValue', 'kvs'},
[3] = {'bool', 'more'},
[4] = {'int64', 'count'},
})
-- }}}
-- {{{ Put request / response
protocol:add_message('PutRequest', {
[1] = {'bytes', 'key'},
[2] = {'bytes', 'value'},
[3] = {'int64', 'lease'},
[4] = {'bool', 'prev_kv'},
[5] = {'bool', 'ignore_value'},
[6] = {'bool', 'ignore_lease'},
})
protocol:add_message('PutResponse', {
[1] = {'ResponseHeader', 'header'},
[2] = {'KeyValue', 'prev_kv'},
})
-- }}} Put request / response
-- {{{ DeleteRange request / response
protocol:add_message('DeleteRangeRequest', {
[1] = {'bytes', 'key'},
[2] = {'bytes', 'range_end'},
[3] = {'bool', 'prev_kv'},
})
protocol:add_message('DeleteRangeResponse', {
[1] = {'ResponseHeader', 'header'},
[2] = {'int64', 'deleted'},
[3] = {'repeated', 'KeyValue', 'prev_kvs'},
})
-- }}} DeleteRange request / response
return protocol
end
return {
new = new,
}
|
--[[
@ filename : share_memory.lua
@ author : zhangshiqian1214@163.com
@ modify : 2017-08-23 17:53
@ company : zhangshiqian1214
]]
local skynet = require "skynet"
local stm = require "skynet.stm"
local addr
local share_memory = {}
local share_data_map = {}
local function init()
addr = skynet.uniqueservice("share_memoryd")
end
local function get_stmcopy(name)
if share_data_map[name] then
return share_data_map[name].stmcopy
end
local stmobj = skynet.call(addr, "lua", "get_stmobj", name)
if not stmobj then
return nil
end
share_data_map[name] = {}
share_data_map[name].stmcopy = stm.newcopy(stmobj)
share_data_map[name].data = nil
return share_data_map[name].stmcopy
end
local function get_share_memory(name)
local stmcopy = get_stmcopy(name)
if not stmcopy then
return
end
local ok, data = stmcopy(skynet.unpack)
if not ok then --旧数据
return share_data_map[name].data
end
share_data_map[name].data = data
return share_data_map[name].data
end
local function set_share_memory(name, data)
local stmcopy = get_stmcopy(name)
if not stmcopy then
skynet.call(addr, "lua", "set_stmobj", name, data)
stmcopy = get_stmcopy(name)
share_data_map[name].data = data
return
end
skynet.call(addr, "lua", "set_stmobj", name, data)
share_data_map[name].data = data
return
end
setmetatable(share_memory, {
__index = function(t, k)
return get_share_memory(k)
end,
__newindex = function(t, k, v)
return set_share_memory(k, v)
end,
})
skynet.init(init)
return share_memory
|
local PLUGIN = PLUGIN
util.AddNetworkString("ixPlayerDeathMenu")
util.AddNetworkString("ixPlayerSpawnerSync")
local spawnPointVariations = {Vector(0, 0, 0)}
for i = 0, 360, 22.5 do
spawnPointVariations[#spawnPointVariations + 1] = Vector(math.cos(i), math.sin(i), 0)
end
local function GetPlayerSize(ply)
local bottom, top = ply:GetHull()
return top - bottom
end
-- https://github.com/TTT-2/TTT2/blob/master/lua/ttt2/libraries/spawn.lua#L52
local function IsSpawnPointSafe(ply, pos, force, filter)
local sizePlayer = GetPlayerSize(ply)
if not util.IsInWorld(pos) then
return false
end
filter = istable(filter) and filter or {filter}
-- the center pos is slightly shifted to the top to prevent ground
-- collisions in the walltrace
local posCenter = pos + Vector(0, 0, 0.525 * sizePlayer.z)
-- Make sure there is enough space around the player
local traceWalls = util.TraceHull({
start = posCenter,
endpos = posCenter,
mins = -0.5 * sizePlayer,
maxs = 0.5 * sizePlayer,
filter = function(ent)
if not IsValid(ent) or table.HasValue(filter, ent) then
return false
end
if ent:GetCollisionGroup() == COLLISION_GROUP_WEAPON then
return false
end
return true
end,
mask = MASK_SOLID
})
if traceWalls.Hit then
return false
end
-- make sure the new position is on the ground
local traceGround = util.TraceLine({
start = posCenter,
endpos = posCenter - Vector(0, 0, sizePlayer.z),
filter = player.GetAll(),
mask = MASK_SOLID
})
if not traceGround.Hit then
return false
end
local blockingEntities = ents.FindInBox(
pos + Vector(-0.5 * sizePlayer.x, -0.5 * sizePlayer.y, 0),
pos + sizePlayer
)
for i = 1, #blockingEntities do
local blockingEntity = blockingEntities[i]
if not IsValid(blockingEntity) or not blockingEntity:IsPlayer() or not blockingEntity:Alive() then continue end
if table.HasValue(filter, blockingEntity) then continue end
if force then
blockingEntity:Kill()
else
return false
end
end
return true
end
local function GetSpawnPointsAroundSpawn(ply, pos, radiusMultiplier)
local sizePlayer = GetPlayerSize(ply)
local boundsPlayer = Vector(sizePlayer.x, sizePlayer.y, 0) * 1.5 * (radiusMultiplier or 1)
local positions = {}
for i = 1, #spawnPointVariations do
positions[i] = pos + spawnPointVariations[i] * boundsPlayer
end
for i = 1, #positions do
local spawnPoint = positions[i]
if not IsSpawnPointSafe(ply, spawnPoint, false) then continue end
return spawnPoint
end
end
-- https://github.com/TTT-2/TTT2/blob/master/lua/ttt2/libraries/spawn.lua#L234
local angle_180 = Angle(0, 180, 0)
function PLUGIN:PlayerLoadout(client)
if (client:GetCharacter() and !client:GetCharacter():GetData("pos") and #PLUGIN.spawners > 0) then
if (!client.spawnInSafezone) then table.shuffle(PLUGIN.spawners) end
local position
for i = 1, #PLUGIN.spawners do
local v = PLUGIN.spawners[i]
if (client.spawnInSafezone) then
if (!v.safezone) then continue end
position = v.position
break
else
if (!v.safezone and IsSpawnPointSafe(client, v.position, false)) then
position = v.position
break
end
end
end
if (position) then
self:ResetPlayer(client)
client:SetPos(position)
client:SetEyeAngles(angle_180)
return
end
for i = 1, #PLUGIN.spawners do
position = GetSpawnPointsAroundSpawn(client, PLUGIN.spawners[i].position)
if (position) then
break
end
end
if (position) then
self:ResetPlayer(client)
client:SetPos(position)
client:SetEyeAngles(angle_180)
return
end
end
end
function PLUGIN:LoadData()
PLUGIN.spawners = self:GetData() or {}
end
function PLUGIN:SaveData()
self:SetData(PLUGIN.spawners)
end
--[[ RE-SPAWN MENU ]]
function PLUGIN:DoPlayerDeath(client)
client.deathSpawn = nil
if (client:GetCharacter()) then
client:GetCharacter():SetData("pos", nil, true)
end
end
function PLUGIN:CanPlayerDeathThink(client)
return client.deathSpawn or client:IsBot()
end
function PLUGIN:ResetPlayer(client)
client.spawnInSafezone = nil
client.deathSpawn = nil
client.deathTime = nil
end
net.Receive("ixPlayerDeathMenu", function(_, client)
if ((client.ixPlayerDeathMenu or 0) < CurTime()) then
client.ixPlayerDeathMenu = CurTime() + 1
else
return
end
if (client:GetCharacter() and !client:Alive() and !client.deathSpawn and client.deathTime and client.deathTime <= CurTime()) then
if (net.ReadBool()) then
client.spawnInSafezone = true
else
client.spawnInSafezone = nil
end
client.deathSpawn = true
end
end)
--[[ RE-SPAWN MENU END ]]
--[[ Spawn Saver by Chessnut ( Saves the position of a character. ) ]]
-- Called right before the character has its information save.
function PLUGIN:CharacterPreSave(character)
-- Get the player from the character.
local client = character:GetPlayer()
-- Check to see if we can get the player's position.
if (IsValid(client)) then
if (client.bNotSavePosition or !client:Alive()) then
character:SetData("pos", nil, true)
client.bNotSavePosition = nil
return
end
local position, eyeAngles = client:GetPos(), client:EyeAngles()
-- Use pre-observer position to prevent spawning in the air.
if (client.ixObsData) then
position, eyeAngles = client.ixObsData[1], client.ixObsData[2]
end
-- Store the position in the character's data.
character:SetData("pos", {position, eyeAngles, game.GetMap()}, true)
end
end
-- Called after the player's loadout has been set.
function PLUGIN:PlayerLoadedCharacter(client, character, lastChar)
timer.Simple(0, function()
if (IsValid(client)) then
self:ResetPlayer(client)
-- Get the saved position from the character data.
local position = character:GetData("pos")
-- Check if the position was set.
if (position) then
if (position[3] and position[3]:lower() == game.GetMap():lower()) then
-- Restore the player to that position.
client:SetPos(position[1].x and position[1] or client:GetPos())
client:SetEyeAngles(position[2].p and position[2] or angle_zero)
end
-- Remove the position data since it is no longer needed.
character:SetData("pos", nil, true)
end
end
end)
end
|
-- Simple supervised learning on MNIST, using a feedforward neural net (brute forcing)
-- Uses the h2o training version of mnist
-- This is a one file script, no options, just to keep it simple
-- Loading data
require 'os'
require 'torch'
require 'nn'
require 'csvigo'
require 'optim'
local data_path = "./data/"
local train_file = "h2o_train.csv"
local test_file = "h2o_test.csv"
if not os.execute("ls data/"..train_file) then
print("Uncompressing data...")
os.execute("gzip -dk "..data_path..train_file..".gz")
os.execute("gzip -dk "..data_path..test_file..".gz")
end
train = csvigo.load{path = data_path..train_file, mode="raw", header=false}
train = torch.Tensor(train)
test = csvigo.load{path = data_path..test_file, mode="raw", header=false}
test = torch.Tensor(test)
trainData = {
data = train[{{},{1,784}}],
labels = train[{{}, 785}],
size = function() return (#trainData.data)[1] end
}
testData = {
data = test[{{},{1,784}}],
labels = test[{{}, 785}],
size = function() return (#testData.data)[1] end
}
-- Normalize features globally
mean = trainData.data:mean()
std = trainData.data:std()
trainData.data:add(-mean)
trainData.data:div(std)
testData.data:add(-mean)
testData.data:div(std)
ninputs = (#trainData.data)[2]
nhiddens = {1024, 2048, 2048, 1024, 512}
noutputs = 10
-- Build model
model = nn.Sequential()
--1st layer
model:add(nn.Reshape(ninputs))
--model:add(nn.Dropout(0.2))
model:add(nn.Linear(ninputs, nhiddens[1]))
model:add(nn.Tanh())
--2nd layer
model:add(nn.Linear(nhiddens[1], nhiddens[2]))
model:add(nn.Tanh())
model:add(nn.Dropout(0.5))
--3rd layer
model:add(nn.Linear(nhiddens[2], nhiddens[3]))
model:add(nn.Tanh())
model:add(nn.Dropout(0.5))
--4th layer
model:add(nn.Linear(nhiddens[3], nhiddens[4]))
model:add(nn.Tanh())
model:add(nn.Dropout(0.5))
--5th layer
model:add(nn.Linear(nhiddens[4], nhiddens[5]))
model:add(nn.Tanh())
model:add(nn.Dropout(0.5))
--Output layer
model:add(nn.Linear(nhiddens[5], noutputs))
model:add(nn.LogSoftMax()) -- needed for NLL criterion
--Loss function
criterion = nn.ClassNLLCriterion()
-- Training -- This part is an almost copy/paste of http://code.madbits.com/wiki/doku.php?id=tutorial_supervised_4_train
classes = {'1','2','3','4','5','6','7','8','9','0'}
-- This matrix records the current confusion across classes
confusion = optim.ConfusionMatrix(classes)
-- Log results to files
trainLogger = optim.Logger('./h2o_ffnn_train.log')
testLogger = optim.Logger('./h2o_ffnn_test.log')
if model then
parameters,gradParameters = model:getParameters()
end
trsize = trainData:size()
batchSize = 1
-- Training function
function train(maxEntries)
local maxEntries = maxEntries or trainData:size()
-- epoch tracker
epoch = epoch or 1
-- local vars
local time = sys.clock()
model:training()
-- shuffle at each epoch
shuffle = torch.randperm(maxEntries)
-- do one epoch
print('==> doing epoch on training data:')
print("==> online epoch # " .. epoch)
for t = 1,maxEntries,batchSize do
-- disp progress
xlua.progress(t, maxEntries)
-- create mini batch
local inputs = {}
local targets = {}
for i = t,math.min(t+batchSize-1,maxEntries) do
-- load new sample
local input = trainData.data[shuffle[i]]:double()
local target = trainData.labels[shuffle[i]]
table.insert(inputs, input)
table.insert(targets, target)
end
-- create closure to evaluate f(X) and df/dX
local feval = function(x)
-- get new parameters
if x ~= parameters then
parameters:copy(x)
end
-- reset gradients
gradParameters:zero()
-- f is the average of all criterions
local f = 0
-- evaluate function for complete mini batch
for i = 1,#inputs do
-- estimate f
local output = model:forward(inputs[i])
if targets[i]==0 then targets[i]=10 end
local err = criterion:forward(output, targets[i])
f = f + err
-- estimate df/dW
local df_do = criterion:backward(output, targets[i])
model:backward(inputs[i], df_do)
-- update confusion
confusion:add(output, targets[i])
end
-- normalize gradients and f(X)
gradParameters:div(#inputs)
f = f/#inputs
-- return f and df/dX
return f,gradParameters
end
config = config or {learningRate = 1e-3,
weightDecay = 0,
momentum = 0,
learningRateDecay = 5e-7}
optim.sgd(feval, parameters, config)
end
-- time taken
time = sys.clock() - time
time = time / maxEntries
print("==> time to learn 1 sample = " .. (time*1000) .. 'ms')
-- print confusion matrix
print(confusion)
confusion:zero()
-- update logger/plot
trainLogger:add{['% mean class accuracy (train set)'] = confusion.totalValid * 100}
-- save/log current net
local filename = paths.concat('./h2o_ffnn_model_'..epoch..'.net')
print('==> saving model to '..filename)
-- torch.save(filename, model)
-- next epoch
epoch = epoch + 1
end
function test(maxEntries)
local maxEntries = maxEntries or testData:size()
-- local vars
local time = sys.clock()
-- averaged param use?
if average then
cachedparams = parameters:clone()
parameters:copy(average)
end
model:evaluate()
-- test over test data
print('==> testing on test set:')
for t = 1,maxEntries do
-- disp progress
xlua.progress(t, maxEntries)
-- get new sample
local input = testData.data[t]:double()
local target = testData.labels[t]
if target == 0 then target = 10 end
-- test sample
local pred = model:forward(input)
confusion:add(pred, target)
end
-- timing
time = sys.clock() - time
time = time / maxEntries
print("==> time to test 1 sample = " .. (time*1000) .. 'ms')
-- print confusion matrix
print(confusion)
confusion:zero()
-- update log/plot
testLogger:add{['% mean class accuracy (test set)'] = confusion.totalValid * 100}
end
epoch=0
while epoch<11 do
train(5000)
test(2000)
end
|
--[[--
charset_data = -- table containing information about the current charset
charset.get_data()
Returns a table with information about the currently selected charset. See framework/env/charset/data/ for more information.
--]]--
function charset.get_data()
return charset.data[
string.gsub(string.lower(charset._current), "%-", "_")
]
end
|
local minit = require("minit")
local OOP = require("oop");
local mission = require("cmisnlib");
local buildAi = require("buildAi");
local core = require("bz_core");
local misc = require("misc");
local ProducerAi = buildAi.ProducerAi;
local ProductionJob = buildAi.ProductionJob;
local IsIn = OOP.isIn;
local audio = {
intro = "rbd0801.wav",
-- after tower 1 is down
tower1 = "rbd0802.wav",
--(Grigg’s updates, interspersed throughout)
grigg_updates = {"rbdnew0820.wav", "rbdnew0821.wav", "rbdnew0822.wav"},
-- after tower 2 is down
tower2 = "rbd0803.wav",
--going_in = "rbd0804.wav", replaced by rbd0802.wav
evacuate = "rbd0805.wav",
timer_out = "rbd0806.wav",
timer_out_loss = "rbd0802L.wav",
one_minute = "rbd0807.wav",
too_close_loss = "rbd0801L.wav",
}
function GriggAtGt(handle,sequencer)
sequencer:push2("Goto", "grigg_out");
-- Make all base units hunt grigg
local l = Length(GetPosition("base_warning",1) - GetPosition("base_warning",0));
for obj in ObjectsInRange(l, "base_warning") do
if(GetTeamNum(obj) == 2 and IsCraft(obj) and not (CanBuild(obj))) then
Attack(obj, handle);
end
end
end
-- Objectives
local introCinematic;
local avoidBase;
local destroyComms;
local evac;
introCinematic = mission.Objective:define("intoCinematic"):createTasks(
"focus_comm1","focus_comm2","focus_comm3","focus_base","build_howiz"
):setListeners({
init = function(self)
self.next_tasks = {
focus_comm1 = "focus_comm2",
focus_comm2 = "focus_comm3",
focus_comm3 = "focus_base"
};
self.comms = {
GetHandle("comm1"),
GetHandle("comm2"),
GetHandle("comm3")
};
end,
_setUpProdListeners = function(self,id,each,done)
local bundle = ProducerAi:getBundle(id);
if(bundle) then
bundle:forEach():subscribe(function(...)
self:call(each,...);
end);
bundle:onFinish():subscribe(function(...)
self:call(done,...);
end);
end
end,
start = function(self)
SetPilot(2,4);
self.cam = CameraReady();
self:startTask("focus_comm1");
self:startTask("build_howiz");
AudioMessage(audio.intro);
end,
_forEachHowie = function(self,job,handle)
Goto(handle,job:getLocation());
end,
_doneHowiz = function(self)
self:taskSucceed("build_howiz");
end,
update = function(self,dtime)
if(self.cam and CameraCancelled()) then
self.cam = not CameraFinish();
end
for i=1, 3 do
if(self:isTaskActive(("focus_comm%d"):format(i))) then
if((not self.cam) or CameraPath(("pan_%d"):format(i),1500,1000,self.comms[i])) then
self:taskSucceed(("focus_comm%d"):format(i));
end
end
end
if(self:isTaskActive("focus_base")) then
if((not self.cam) or CameraPath("pan_4",500,2000,GetHandle("ubtart0_i76building"))) then
self:taskSucceed("focus_base");
end
end
end,
save = function(self)
return {
howizJobs = self.howizJobs,
cam = self.cam
};
end,
load = function(self,data)
self.howizJobs = data.howizJobs;
self.cam = data.cam;
if(self.howizJobs) then
self:call("_setUpProdListeners",self.howizJobs,"_forEachHowie","_doneHowiz");
end
end,
task_start = function(self,name)
if(name == "build_howiz") then
self.howizJobs = ProducerAi:queueJobs2({
ProductionJob("avartlf",2,GetPosition("base_artillery",0),1),
ProductionJob("svartlf",2,GetPosition("base_artillery",1),1),
ProductionJob("avartlf",2,GetPosition("base_artillery",2),1),
ProductionJob("svartlf",2,GetPosition("base_artillery",3),1)
});
self:call("_setUpProdListeners",self.howizJobs,"_forEachHowie","_doneHowiz");
end
end,
task_success = function(self,name)
if(name == "focus_base") then
if(self.cam) then
self.cam = not CameraFinish();
end
mission.Objective:Start("misison");
else
self:startTask(self.next_tasks[name]);
end
if(self:hasTasksSucceeded("focus_base","build_howiz")) then
self:success();
end
end,
success = function(self)
end
});
avoidBase = mission.Objective:define("avoidBase"):createTasks(
"warning", "wayTooClose"
):setListeners({
start = function(self)
AddObjective("rbd0804.otf");
self:startTask("warning");
self:startTask("wayTooClose");
end,
fail = function(self)
UpdateObjective("rbd0804.otf","red");
FailMission(GetTime() + 5.0, "rbd08l01.des");
end,
task_reset = function(self,name)
if(name == "warning") then
UpdateObjective("rbd0804.otf","white");
end
end,
task_fail = function(self,name,first)
if(name == "wayTooClose") then
self:fail();
elseif(name == "warning") then
if(first) then
--Warning audio
end
UpdateObjective("rbd0804.otf","yellow");
end
end,
update = function(self)
local d = GetDistance(GetPlayerHandle(),"base_warning");
local l = Length(GetPosition("base_warning",1) - GetPosition("base_warning",0));
if(self:isTaskActive("warning") and (d < l)) then
self:taskFail("warning");
elseif((d > l) and (not self:isTaskActive("warning"))) then
self:taskReset("warning");
end
if(self:isTaskActive("wayTooClose")) then
local d = GetDistance(GetPlayerHandle(),"base");
local l = Length(GetPosition("base",1) - GetPosition("base",0));
if d < l then
self:taskFail("wayTooClose");
end
end
end
});
destroyComms = mission.Objective:define("misison"):createTasks(
"destroyComms", "startEvac"
):setListeners({
init = function(self)
self.comms = {
GetHandle("power1"),
GetHandle("power2"),
GetHandle("power3")
};
self.audio = {
audio.tower1,
audio.tower2
};
self.grigg_audio = audio.grigg_updates;
end,
_spawnGrigg = function(self)
self.grigg = BuildObject("avtank",1,"spawn_griggs");
SetObjectiveName(self.grigg, "Pvt. Grigg");
SetObjectiveOn(self.grigg);
local s = mission.TaskManager:sequencer(self.grigg);
local pp = GetPathPoints("grigg_in");
SetIndependence(self.grigg,0);
SetPerceivedTeam(self.grigg,2);
s:queue2("Goto","grigg_in");
s:queue2("Dropoff",pp[#pp]);
self.grigg_spawned = true;
local griggAudioSequence = mission.AudioSequence();
griggAudioSequence:queueAudio(self.grigg_audio[1], 55 + math.random(10));
griggAudioSequence:queueAudio(self.grigg_audio[2], 20 + math.random(20));
griggAudioSequence:queueAudio(self.grigg_audio[3], 20 + math.random(20));
self.grigg_id = mission.AudioManager:PlayAndCall(griggAudioSequence, self, nil, "_nextGriggAudio");
end,
_nextGriggAudio = function(self, clip)
print(("Grigg audio playing #%d"):format(clip));
end,
task_start = function(self,name)
if(name == "destroyComms") then
self.timerOut = false;
AddObjective("rbd0801.otf");
elseif(name == "wait") then
elseif(name == "startEvac") then
evac:start(self.grigg, self.timerOut, self.comms[3]);
end
end,
task_success = function(self, name)
if(name == "destroyComms") then
UpdateObjective("rbd0801.otf","green");
StopCockpitTimer();
HideCockpitTimer();
if(not self:isTaskActive("startEvac")) then
self:startTask("startEvac");
end
self:success();
end
end,
task_fail = function(self,name)
if(name == "destroyComms") then
UpdateObjective("rbd0801.otf","red");
self:fail();
else
self:fail("grigg");
end
end,
start = function(self)
self.grigg_spawned = false;
SetObjectiveOn(self.comms[1]);
for i, v in ipairs(self.comms) do
SetObjectiveName(v,("Power %d"):format(i));
end
self:startTask("destroyComms");
self.timer = 60*8;
self.nextAudio = 0;
StartCockpitTimer(self.timer,self.timer*0.5,self.timer*0.1);
end,
update = function(self,dtime)
if(self:isTaskActive("destroyComms")) then
local dead = mission.countDead(self.comms);
self.timer = self.timer - dtime;
if(not self.grigg_spawned and dead >= 1) then
self:call("_spawnGrigg");
end
if(dead >= #self.comms) then
self:taskSucceed("destroyComms");
end
if(self.timer <= 0) then
if(not self.timerOut) then
self.timerOut = true;
if(mission.countAlive(self.comms) > 1) then
self:taskFail("destroyComms");
else -- One tower left when time runs out, player does not fail
HideCockpitTimer();
-- Play audio message
AudioMessage(audio.timer_out);
if(not self:isTaskActive("startEvac")) then
self:startTask("startEvac");
end
end
end
end
end
if(self.grigg_spawned and not IsAlive(self.grigg)) then
self:fail("grigg");
end
end,
success = function(self)
--SucceedMission(GetTime()+5.0,"rbd08w01.des");
end,
delete_object = function(self,handle)
local m = nil;
if(IsIn(handle,self.comms)) then
print("next audio");
self.nextAudio = self.nextAudio + 1;
if(self.audio[self.nextAudio]) then
AudioMessage(self.audio[self.nextAudio]);
end
end
for i, v in ipairs(self.comms) do
print(i, v, IsAlive(v));
if(IsAlive(v)) then
SetObjectiveOn(v);
break;
end
end
end,
fail = function(self,what)
if(what == "grigg") then
FailMission(GetTime()+5.0,"rbd08l05.des");
else
FailMission(GetTime()+5.0,"rbd08l02.des");
end
end,
finish = function(self)
mission.AudioManager:Stop(self.grigg_id);
end,
save = function(self)
return self.timer, self.wait_1, self.grigg, self.timerOut, self.grigg_spawned, self.grigg_audio, self.nextAudio, self.grigg_id;
end,
load = function(self,...)
self.timer, self.wait_1, self.grigg, self.timerOut, self.grigg_spawned, self.grigg_audio, self.nextAudio, self.grigg_id = ...;
if(not self.timerOut) then
StartCockpitTimer(self.timer,self.timer*0.5,self.timer*0.1);
end
end
});
evac = mission.Objective:define("evac"):createTasks(
"wait", "evacuate"
):setListeners({
init = function(self)
end,
start = function(self, grigg, slowEvac, lastComm)
print("Evac started");
self.slowEvac = slowEvac;
self.grigg = grigg;
self.wait_timer = 5;
self:startTask("wait");
self.lastComm = lastComm;
end,
task_start = function(self, name)
if(name == "wait") then
--AddObjective("rbd0801i.otf");
elseif(name == "evacuate") then
AudioMessage(audio.evacuate);
AddObjective("rbd0803.otf");
local s = mission.TaskManager:sequencer(self.grigg);
s:clear();
Goto(self.grigg,"grigg_to_gt");
s:queue3("GriggAtGt");
end
end,
task_success = function(self, name)
if(name == "wait") then
--RemoveObjective("rbd0801i.otf");
--AddObjective("rbd0802i.otf","green");
self:startTask("evacuate");
elseif(name == "evacuate") then
UpdateObjective("rbd0803.otf","green");
self:success();
end
end,
update = function(self, dtime)
if(self:isTaskActive("evacuate")) then
local d1 = Length(GetPosition(GetPlayerHandle()) - GetPosition("spawn_griggs"));
local d2 = Length(GetPosition(self.grigg) - GetPosition("spawn_griggs"));
if(d1 < 100 and d2 < 100) and (not IsAlive(self.lastComm)) then
self:taskSucceed("evacuate");
end
if(not IsAlive(self.grigg)) then
self:taskFail("evacuate");
end
elseif(self:isTaskActive("wait")) then
self.wait_timer = self.wait_timer - dtime;
if(self.wait_timer <= 0) then
self:taskSucceed("wait");
end
end
end,
save = function(self)
return self.slowEvac, self.wait_timer, self.grigg, self.lastComm;
end,
load = function(self, ...)
self.slowEvac, self.wait_timer, self.grigg, self.lastComm = ...;
end,
fail = function(self)
FailMission(GetTime()+5.0,"rbd08l05.des");
end,
success = function(self)
if(self.slowEvac) then
SucceedMission(GetTime() + 5.0, "rbd08w02.des");
else
SucceedMission(GetTime() + 5.0, "rbd08w01.des");
end
end
});
function Start()
print("pack test")
print(#(table.pack(1, 2, nil, 3, 4)));
print(#({1, 2, nil, 3, 4}));
core:onStart();
introCinematic:start();
avoidBase:start();
for i = 1, 6 do
BuildObject("avartl", 2, ("spawn_artl%d"):format(i));
end
SetPathLoop("walker1_path");
SetPathLoop("walker2_path");
Goto(GetHandle("avwalk1"),"walker1_path");
Goto(GetHandle("avwalk2"),"walker2_path");
for i = 1, 4 do
local nav = GetHandle("nav" .. i);
if i == 4 then
SetObjectiveName(nav, "Pickup Zone");
else
SetObjectiveName(nav, "Navpoint " .. i);
end
SetMaxHealth(nav, 0);
end
for i = 1, 3 do
local comm = GetHandle("comm" .. i);
SetMaxHealth(comm, 0); -- These can't be killed.
end
end
function Update(dtime)
core:update(dtime);
mission:Update(dtime);
end
function CreateObject(handle)
core:onCreateObject(handle);
mission:CreateObject(handle);
end
function AddObject(handle)
core:onAddObject(handle);
mission:AddObject(handle);
end
function DeleteObject(handle)
core:onDeleteObject(handle);
mission:DeleteObject(handle);
end
function Save()
return mission:Save(),{core:save()};
end
function Load(missison_date,cdata)
core:load(unpack(cdata));
mission:Load(missison_date);
end
minit.init()
|
-- Initial stuff
math.randomseed(tick())
-- Wait for character
repeat wait() until game.Players.LocalPlayer.Character ~= nil
-- Useful shortcuts
local plr = game:GetService("Players").LocalPlayer
local char = plr.Character
local plrgui = plr.PlayerGui
local backpack = plr.Backpack
local torso = char.Torso
local head = char.Head
local hum = char.Humanoid
local larm = char["Left Arm"]
local lleg = char["Left Leg"]
local rarm = char["Right Arm"]
local rleg = char["Right Leg"]
local LS = torso["Left Shoulder"]
local LH = torso["Left Hip"]
local RS = torso["Right Shoulder"]
local RH = torso["Right Hip"]
local neck = torso.Neck
local it = Instance.new
local vt = Vector3.new
local cf = CFrame.new
local euler = CFrame.fromEulerAnglesXYZ
local angles = CFrame.Angles
local neckC0 = cf(0, 1, 0, -1, -0, -0, 0, 0, 1, 0, 1, 0)
local neckC1 = cf(0, -0.5, 0, -1, -0, -0, 0, 0, 1, 0, 1, 0)
local LSC0 = cf(-1.5,.5,0)
local LSC1 = cf(0,.5,0)
local RSC0 = cf(1.5,.5,0)
local RSC1 = cf(0,.5,0)
local LHC0 = cf(-1,-1,0,-0,-0,-1,0,1,0,1,0,0)
local LHC1 = cf(-0.5,1,0,-0,-0,-1,0,1,0,1,0,0)
local RHC0 = cf(1,-1,0,0,0,1,0,1,0,-1,-0,-0)
local RHC1 = cf(0.5,1,0,0,0,1,0,1,0,-1,-0,-0)
local RP = char.HumanoidRootPart
local RJ = RP.RootJoint
local RJC0 = euler(-1.57,0,3.14)
-- Build the weapon
local build = function()
local model = Instance.new("Model")
model.Name = "Cane"
local handle = Instance.new("Part", model)
handle.FormFactor = Enum.FormFactor.Symmetric
handle.CanCollide = false
handle.Size = Vector3.new(1,1,3)
handle.Name = "Handle"
local mesh = Instance.new("SpecialMesh",handle)
mesh.Scale = Vector3.new(1,1,0.69999998807907)
mesh.MeshId = "http://www.roblox.com/asset/?id=25628815"
mesh.TextureId = "http://www.roblox.com/asset/?id=25629094"
mesh.MeshType = Enum.MeshType.FileMesh
return model
end
-- Wait for mouse
local mouse
while true do
mouse = plr:GetMouse()
if mouse then break end
wait(.1)
end
-- Create welds
local RW, LW = Instance.new("Weld",torso), Instance.new("Weld",torso)
RW.Name = "Right Weld" LW.Name = "Left Weld"
RW.Part0 = torso LW.Part0 = torso
RW.C0 = RSC0 RW.C1 = RSC1 LW.C0 = LSC0 LW.C1 = LSC1
-- Attach weapon
local canemodel = build()
local cane = canemodel:FindFirstChild("Handle")
canemodel.Parent = char
local caneweld = Instance.new("Weld", rarm)
caneweld.Part0 = rarm
caneweld.Part1 = cane
caneweldC0 = caneweld.C0 * CFrame.new(0,-1,1) * CFrame.Angles(math.rad(180),0,math.rad(90))
caneweld.C0 = caneweldC0
-- Weapon variables
local caneEnd = cf(-.225,0,-1.5)
-- Sound effects
local sounds = {}
sounds.explosion = "http://www.roblox.com/asset/?id=87784452"
sounds.bewm = "http://www.roblox.com/asset/?id=2767090"
sounds.slice = "http://www.roblox.com/asset/?id=161006195"
sounds.charge = "http://roblox.com/asset/?id=2101137"
sounds.sharpblast = "http://roblox.com/asset/?id=2248511"
sounds.woosh = "http://roblox.com/asset/?id=147722227"
sounds.metalhit = "http://roblox.com/asset/?id=153092348"
sounds.mechblast = "http://roblox.com/asset/?id=169380505"
sounds.chargepulse = "http://roblox.com/asset/?id=10209296"
sounds.heal = "http://roblox.com/asset/?id=2101144"
sounds.zap = "http://roblox.com/asset/?id=10756104"
sounds.powernote = "http://roblox.com/asset/?id=192603389"
sounds.swing = "http://roblox.com/asset/?id=10209640"
sounds.hit = "http://roblox.com/asset/?id=10209590"
-- Base functions
local wait = function(t)
if t ~= nil then
return wait(t)
else
local t = tick()
game:GetService("RunService").RenderStepped:wait()
return tick() - t, time()
end
end
local nolines = function(p)
p.TopSurface, p.BottomSurface, p.LeftSurface, p.RightSurface, p.FrontSurface, p.BackSurface = 10, 10, 10, 10, 10, 10
end
local part = function(formfactor,parent,reflectance,transparency,brickcolor,name,size)
local fp = it("Part")
fp.formFactor = formfactor
fp.Parent = parent
fp.Reflectance = reflectance
fp.Transparency = transparency
fp.CanCollide = false
fp.Locked = true
fp.BrickColor = brickcolor
fp.Name = name
fp.Size = size
fp.Position = torso.Position
fp.Material = "SmoothPlastic"
fp:BreakJoints()
nolines(fp)
return fp
end
local mesh = function(instance,part,meshtype,meshid,offset,scale)
local mesh = it(instance)
mesh.Parent = part
if instance == "SpecialMesh" then
mesh.MeshType = meshtype
if meshid ~= nil then
mesh.MeshId = "http://www.roblox.com/asset/?id="..meshid
end
end
mesh.Offset=offset
mesh.Scale=scale
return mesh
end
local weld = function(parent,part0,part1,c0)
local weld = it("Weld")
weld.Parent = parent
weld.Part0 = part0
weld.Part1 = part1
weld.C0 = c0
return weld
end
local rayCast = function(Pos, Dir, Max, Ignore) -- Origin Position , Direction, MaxDistance , IgnoreDescendants
return game:service("Workspace"):FindPartOnRay(Ray.new(Pos, Dir.unit * (Max or 999.999)), Ignore)
end
local rad = function(x,y,z)
return euler(math.rad(x or 0),math.rad(y or 0),math.rad(z or 0))
end
local random = function(a, b)
local num = math.random(a*100, b*100)
return num/100
end
local randomRot = function()
return rad(random(0,360),random(0,360),random(0,360))
end
local sound = function(id, par, vol, pit)
coroutine.resume(coroutine.create(function()
local sou = Instance.new("Sound", par or workspace)
sou.Volume = vol
sou.Pitch = pit or 1
sou.SoundId = id
wait()
sou:play()
game:GetService("Debris"):AddItem(sou, 6)
end))
end
local damage = function(hit, minim, maxim, knockback, Type, Property, Delay, KnockbackType, incstun, stagger, staghit, ranged)
-- Fen's nasty and messy damage function
if hit.Parent == nil then
return
end
local h = hit.Parent:FindFirstChild("Humanoid")
for _, v in pairs(hit.Parent:children()) do
if v:IsA("Humanoid") then
h = v
end
end
if hit.Parent.Parent:FindFirstChild("Torso") ~= nil then
h = hit.Parent.Parent:FindFirstChild("Humanoid")
end
if hit.Parent.className == "Hat" then
hit = hit.Parent.Parent:findFirstChild("Head")
end
if h ~= nil and hit.Parent.Name ~= char.Name and hit.Parent:FindFirstChild("Torso") ~= nil then
if hit.Parent:findFirstChild("DebounceHit") ~= nil then
if hit.Parent.DebounceHit.Value == true then
return
end
end
local c = Instance.new("ObjectValue")
c.Name = "creator"
c.Value = game:service("Players").LocalPlayer
c.Parent = h
game:GetService("Debris"):AddItem(c, .5)
local Damage = random(minim, maxim)
local blocked = false
local enblock = nil
local Stats = hit.Parent:findFirstChild("Stats")
if Stats ~= nil then
enblock = Stats:findFirstChild("Block")
if Stats:findFirstChild("Defense") ~= nil then
Damage = Damage / Stats.Defense.Value
end
if Stats:findFirstChild("Stun") ~= nil then
Stats.Stun.Value = Stats.Stun.Value + incstun
end
if Stats:findFirstChild("Stagger") ~= nil then
if stagger == true then
Stats.Stagger.Value = true
end
end
end
if enblock ~= nil then
if enblock.Value == true then
blocked = true
end
end
if blocked == true then
if ranged ~= true then
enblock.Value = false
end
else
Damage = math.floor(Damage)
print("dam"..Damage)
sound(sounds.hit, hit, 1, 1)
h.Health = h.Health - Damage
if Type == "Knockdown" then
local hum = hit.Parent.Humanoid
hum.PlatformStand = true
coroutine.resume(coroutine.create(function(HHumanoid)
wait()
HHumanoid.PlatformStand = false
end), hum)
local angle = (hit.Position - (Property.Position + Vector3.new(0, 0, 0))).unit
local bodvol = Instance.new("BodyVelocity")
bodvol.velocity = angle * knockback
bodvol.P = 5000
bodvol.maxForce = Vector3.new(8e+003, 8e+003, 8e+003)
bodvol.Parent = hit
local rl = Instance.new("BodyAngularVelocity")
rl.P = 3000
rl.maxTorque = Vector3.new(500000, 500000, 500000) * 50000000000000
rl.angularvelocity = Vector3.new(random(-10, 10), random(-10, 10), random(-10, 10))
rl.Parent = hit
game:GetService("Debris"):AddItem(bodvol, .5)
game:GetService("Debris"):AddItem(rl, .5)
elseif Type == "Knockdown2" then
local hum = hit.Parent.Humanoid
local angle = (hit.Position - (Property.Position + Vector3.new(0, 0, 0))).unit
local bodvol = Instance.new("BodyVelocity")
bodvol.velocity = angle * knockback
bodvol.P = 5000
bodvol.maxForce = Vector3.new(8e+003, 8e+003, 8e+003)
bodvol.Parent = hit
game:GetService("Debris"):AddItem(bodvol, .5)
elseif Type == "Normal" or Type == "NormalDecreaseMvmt1" then
local vp = Instance.new("BodyVelocity")
vp.P = 500
vp.maxForce = Vector3.new(math.huge, 0, math.huge)
if KnockbackType == 1 then
vp.velocity = Property.CFrame.lookVector * knockback + Property.Velocity / 1.05
elseif KnockbackType == 2 then
vp.velocity = Property.CFrame.lookVector * knockback
end
game:GetService("Debris"):AddItem(vp, .5)
if knockback > 0 then
vp.Parent = hit.Parent.Torso
end
end
end
local debounce = Instance.new("BoolValue")
debounce.Name = "DebounceHit"
debounce.Parent = hit.Parent
debounce.Value = true
game:GetService("Debris"):AddItem(debounce, Delay)
c = Instance.new("ObjectValue")
c.Name = "creator"
c.Value = plr
c.Parent = h
game:GetService("Debris"):AddItem(c, .5)
end
end
local fade = function(prt, t)
coroutine.resume(coroutine.create(function()
for i = 0, 1, t do
wait(0)
prt.Transparency = i
end
wait(0)
prt:destroy()
end))
end
local block1 = function(prt, delay, x, y, z, msh)
coroutine.resume(coroutine.create(function()
for i = 0, 1, delay do
wait(0)
prt.CFrame = prt.CFrame * euler(random(-50, 50), random(-50, 50), random(-50, 50))
local Mesh = msh
Mesh.Scale = Mesh.Scale + vt(x, y, z)
prt.Transparency = i
end
wait(0)
prt:destroy()
end))
end
local block2 = function(prt, delay, x, y, z, msh)
coroutine.resume(coroutine.create(function()
for i = 0, 1, delay do
wait(0)
local Mesh = msh
Mesh.Scale = Mesh.Scale + vt(x, y, z)
prt.Transparency = i
end
wait(0)
prt:destroy()
end))
end
local cyleffect = function(prt, delay, x, y, z, msh)
coroutine.resume(coroutine.create(function()
for i = 0, 1, delay do
wait(0)
local Mesh = msh
Mesh.Scale = Mesh.Scale + vt(x, y, z)
prt.Transparency = i
end
wait(0)
prt:destroy()
end))
end
local CFrameFromTopBack = function(at, top, back)
local right = top:Cross(back)
return CFrame.new(at.x, at.y, at.z,
right.x, top.x, back.x,
right.y, top.y, back.y,
right.z, top.z, back.z)
end
local triangle = function(a, b, c)
local edg1 = (c - a):Dot((b - a).unit)
local edg2 = (a - b):Dot((c - b).unit)
local edg3 = (b - c):Dot((a - c).unit)
if edg1 <= (b - a).magnitude and edg1 >= 0 then
a, b, c = a, b, c
elseif edg2 <= (c - b).magnitude and edg2 >= 0 then
a, b, c = b, c, a
elseif edg3 <= (a - c).magnitude and edg3 >= 0 then
a, b, c = c, a, b
else
assert(false, "unreachable")
end
local len1 = (c - a):Dot((b - a).unit)
local len2 = (b - a).magnitude - len1
local width = (a + (b - a).unit * len1 - c).magnitude
local maincf = CFrameFromTopBack(a, (b - a):Cross(c - b).unit, -(b - a).unit)
local list = {}
if len1 > 0.01 then
local w1 = Instance.new('WedgePart', m)
game:GetService("Debris"):AddItem(w1, 5)
w1.Material = "SmoothPlastic"
w1.FormFactor = 'Custom'
w1.BrickColor = BrickColor.new("Bright red")
w1.Transparency = 0
w1.Reflectance = 0
w1.Material = "SmoothPlastic"
w1.CanCollide = false
nolines(w1)
local sz = Vector3.new(0.2, width, len1)
w1.Size = sz
local sp = Instance.new("SpecialMesh", w1)
sp.MeshType = "Wedge"
sp.Scale = Vector3.new(0, 1, 1) * sz / w1.Size
w1:BreakJoints()
w1.Anchored = true
w1.Parent = workspace
w1.Transparency = 0.7
fade(w1)
w1.CFrame = maincf * CFrame.Angles(math.pi, 0, math.pi / 2) * CFrame.new(0, width / 2, len1 / 2)
table.insert(list, w1)
end
if len2 > 0.01 then
local w2 = Instance.new('WedgePart', m)
game:GetService("Debris"):AddItem(w2, 5)
w2.Material = "SmoothPlastic"
w2.FormFactor = 'Custom'
w2.BrickColor = BrickColor.new("Bright red")
w2.Transparency = 0
w2.Reflectance = 0
w2.Material = "SmoothPlastic"
w2.CanCollide = false
nolines(w2)
local sz = Vector3.new(0.2, width, len2)
w2.Size = sz
local sp = Instance.new("SpecialMesh", w2)
sp.MeshType = "Wedge"
sp.Scale = Vector3.new(0, 1, 1) * sz / w2.Size
w2:BreakJoints()
w2.Anchored = true
w2.Parent = workspace
w2.Transparency = 0.7
fade(w2)
w2.CFrame = maincf * CFrame.Angles(math.pi, math.pi, -math.pi / 2) * CFrame.new(0, width / 2, -len1 - len2 / 2)
table.insert(list, w2)
end
return unpack(list)
end
-- Magic effects
local magic = {}
magic.stravant = function(brickcolor, cframe, x, y, z, x1, y1, z1, delay)
local prt = part(3, workspace, 0, 0, brickcolor, "Effect", vt(0.5, 0.5, 0.5))
prt.Anchored = true
prt.CFrame = cframe * cf(x, y, z)
local msh = mesh("SpecialMesh", prt, "FileMesh", "rbxassetid://168892363", vt(0, 0, 0), vt(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 5)
coroutine.resume(coroutine.create(function(Part, Mesh, ex, why, zee)
local num = random()
local num2 = random(-3, 2) + random()
local numm = 0
for i = 0, 1, delay * 2 do
wait()
Part.CFrame = cframe * euler(0, numm * num * 10, 0) * cf(ex, why, zee) * cf(-i * 10, num2, 0)
Part.Transparency = i
numm = numm + 0.01
end
Part.Parent = nil
Mesh.Parent = nil
end), prt, msh, x, y, z)
end
magic.block = function(brickcolor, cframe, x1, y1, z1, x3, y3, z3, delay, Type, par)
local prt = part(3, par or workspace, 0, 0, brickcolor, "Effect", vt())
prt.Anchored = true
prt.CFrame = cframe
local msh = mesh("BlockMesh", prt, "", "", vt(0, 0, 0), vt(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 5)
if Type == 1 or Type == nil then
block1(prt, delay, x3, y3, z3, msh)
elseif Type == 2 then
block2(prt, delay, x3, y3, z3, msh)
end
end
magic.circle = function(brickcolor, cframe, x1, y1, z1, x3, y3, z3, delay, par)
local prt = part(3, par or workspace, 0, 0, brickcolor, "Effect", vt())
prt.Anchored = true
prt.CFrame = cframe
local msh = mesh("SpecialMesh", prt, "Sphere", nil, vt(0, 0, 0), vt(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 2)
cyleffect(prt, delay, x3, y3, z3, msh)
end
magic.cylinder = function(brickcolor, cframe, x1, y1, z1, x3, y3, z3, delay)
local prt = part(3, workspace, 0, 0, brickcolor, "Effect", vt())
prt.Anchored = true
prt.CFrame = cframe
local msh = mesh("CylinderMesh", prt, "", "", vt(0, 0, 0), vt(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 2)
cyleffect(prt, delay, x3, y3, z3, msh)
end
magic.head = function(brickcolor, cframe, x1, y1, z1, x3, y3, z3, delay)
local prt = part(3, workspace, 0, 0, brickcolor, "Effect", vt())
prt.Anchored = true
prt.CFrame = cframe
local msh = mesh("SpecialMesh", prt, "Head", nil, vt(0, 0, 0), vt(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 2)
cyleffect(prt, delay, x3, y3, z3, msh)
end
magic.wave = function(brickcolor, cframe, x1, y1, z1, x3, y3, z3, delay)
local prt = part(3, workspace, 0, 0, brickcolor, "Effect", vt())
prt.Anchored = true
prt.CFrame = cframe
local msh = mesh("SpecialMesh", prt, "FileMesh", "http://www.roblox.com/asset/?id=20329976", vt(0, 0, 0), vt(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 5)
cyleffect(prt, delay, x3, y3, z3, msh)
end
magic.lightning = function(p0, p1, tym, ofs, col, th, tra, last, par)
local magz = (p0 - p1).magnitude
local curpos = p0
local trz = {
-ofs,
ofs
}
for i = 1, tym do
local li = Instance.new("Part", par or workspace)
li.TopSurface = 0
li.BottomSurface = 0
li.Anchored = true
li.Transparency = tra or 0.4
li.BrickColor = BrickColor.new(col)
li.Material = "Neon"
li.formFactor = "Custom"
li.CanCollide = false
li.Size = Vector3.new(th, th, magz / tym)
local ofz = Vector3.new(random(trz[1],trz[2]), random(trz[1],trz[2]), random(trz[1],trz[2]))
local trolpos = CFrame.new(curpos, p1) * CFrame.new(0, 0, magz / tym).p + ofz
if tym == i then
local magz2 = (curpos - p1).magnitude
li.Size = Vector3.new(th, th, magz2)
li.CFrame = CFrame.new(curpos, p1) * CFrame.new(0, 0, -magz2 / 2)
else
li.CFrame = CFrame.new(curpos, trolpos) * CFrame.new(0, 0, magz / tym / 2)
end
curpos = li.CFrame * CFrame.new(0, 0, magz / tym / 2).p
game.Debris:AddItem(li, last)
end
end
-- Logic variables
local equipped = false
local attacking = false
-- Effect handling
local charfx = Instance.new("Model", char)
charfx.Name = "Effects"
local toggles = {
snow = false;
lmagic = false;
rmagic = false;
canemagic = false;
}
local snowTick = 0
local lmagicTick = 0
local rmagicTick = 0
local canemagicTick = 0
local snowMeshes = {
"http://www.roblox.com/asset?id=187687161";
"http://www.roblox.com/asset?id=187687175";
"http://www.roblox.com/asset?id=187687193";
}
-- Pose system
local poses = {
none = {
larm = euler(0, 0, 0);
rarm = euler(0, 0, 0);
lleg = euler(0, 0, 0);
rleg = euler(0, 0, 0);
torso = euler(0, 0, 0);
head = euler(0, 0, 0);
cane = euler(0, 0, 0);
}
}
local pose = "none"
local posespeed = .1
local newpose = function(name, larm, rarm, torso, head, lleg, rleg, cane)
poses[name] = {
larm = larm or rad();
rarm = rarm or rad();
lleg = lleg or rad();
rleg = rleg or rad();
torso = torso or rad();
head = head or rad();
cane = cane or rad();
}
end
local setpose = function(name, speed)
posespeed = speed or 1
pose = name or "none"
end
game:GetService("RunService").RenderStepped:connect(function()
local vel = (RP.Velocity*Vector3.new(1,0,1)).magnitude
local yvel = RP.Velocity.y
local hitfloor,posfloor=rayCast(RP.Position,(CFrame.new(RP.Position,RP.Position - Vector3.new(0,1,0))).lookVector,4,char)
if yvel > 1 and hitfloor == nil and equipped and not attacking then
setpose("jumping",.2)
elseif yvel < -1 and hitfloor == nil and equipped and not attacking then
setpose ("falling",.075)
elseif vel < 1 and hitfloor ~= nil and equipped and not attacking then
setpose("idle",.1)
elseif vel > 2 and vel < 22 and hitfloor ~= nil and equipped and not attacking then
setpose("walking",.1)
end
if poses[pose] ~= nil then
local pose = poses[pose]
LW.C0 = LW.C0:lerp(LSC0 * pose.larm, posespeed)
RW.C0 = RW.C0:lerp(RSC0 * pose.rarm, posespeed)
LH.C0 = LH.C0:lerp(LHC0 * pose.lleg, posespeed)
RH.C0 = RH.C0:lerp(RHC0 * pose.rleg, posespeed)
RJ.C0 = RJ.C0:lerp(RJC0 * pose.torso, posespeed)
neck.C0 = neck.C0:lerp(neckC0 * pose.head, posespeed)
caneweld.C0 = caneweld.C0:lerp(caneweldC0 * pose.cane, posespeed)
end
if toggles.snow == true then
if snowTick % 15 == 0 then
local p = Instance.new("Part")
local m = Instance.new("SpecialMesh", p)
m.MeshId = snowMeshes[math.random(1, #snowMeshes)]
m.Scale = Vector3.new(2,2,2)
local q = Instance.new("BodyVelocity")
p.BrickColor = BrickColor.new("White")
p.Parent = charfx
p.Shape = 1
p.Size = Vector3.new(.5, .5, .5)
p.Transparency = .3
p.Locked = true
p.Anchored = false
p.CanCollide = false
p.formFactor = "Plate"
p.CFrame = torso.CFrame * cf(Vector3.new((random(-75, 75)),50,(random(-75,75)))) * randomRot()
q.velocity = Vector3.new(0, -10, 0)
q.Parent = p
p.Touched:connect(function()
p:destroy()
end)
end
snowTick = snowTick + 1
end
if toggles.lmagic then
if lmagicTick % 15 == 0 then
magic.block(BrickColor.new("Institutional white"),larm.CFrame*cf(0,-1,0),1,1,1,.5,.5,.5,.065,nil,charfx)
end
lmagicTick = lmagicTick + 1
end
if toggles.rmagic then
if rmagicTick % 15 == 0 then
magic.block(BrickColor.new("Institutional white"),rarm.CFrame*cf(0,-1,0),1,1,1,.5,.5,.5,.065,nil,charfx)
end
rmagicTick = rmagicTick + 1
end
if toggles.canemagic then
if canemagicTick % 15 == 0 then
magic.block(BrickColor.new("Institutional white"),cane.CFrame*caneEnd,1,1,1,.5,.5,.5,.065,nil,charfx)
end
canemagicTick = canemagicTick + 1
end
end)
-- Weapon setup
local bin = Instance.new("HopperBin",backpack)
bin.Name = "Cane"
script.Parent = bin
-- Weapon poses
newpose("idle", rad(-5,5,0), rad(0,0,50), rad(0,-2,-15), rad(0,-3,15), rad(0,15,0), rad(0,15,0), rad(90,-45,170)*CFrame.new(0,-1,-1.5))
newpose("jumping", rad(-20, 0, -10), rad(-20, 0, 10), rad(-10, 0, 0), rad(0, 0, 0), rad(0, 0, 15), rad(0, 0, 0)*CFrame.new(.35,.35,0))
newpose("falling", rad(0, 0, -50), rad(0, 0, 50), rad(0, 0, 0), rad(20, 0, 0), rad(0, 0, 0), rad(0, 0, 0)*CFrame.new(.15,.15,0))
newpose("walking", rad(-5,5,-15), rad(-20,0,20), rad(5,0,0), rad(0,0,0), rad(0,0,0), rad(0,0,0))
-- Attack poses
newpose("larmcharge", rad(0,-15,-135), rad(0,0,50), rad(0,-2,-15), rad(-15,-15,50), rad(0,15,0), rad(0,15,0), rad(90,-45,170)*CFrame.new(0,-1,-1.5))
newpose("canecharge", rad(45,0,30), rad(0,0,150), rad(0,0,-35), rad(-20,0,0), rad(0,35,0), rad(0,35,0), rad(90,-135,170)*CFrame.new(0,-1,-1.5))
newpose("clickattack1_1", rad(20,0,15), rad(0,-15,125), rad(0,-2,-35), rad(0,-3,35), rad(0,35,0), rad(0,35,0), rad(90,-165,180)*CFrame.new(0,-1,-1.5))
newpose("clickattack1_2", rad(-20,0,-15), rad(0,100,65), rad(0,-2,45), rad(10,-10,-25), rad(0,-45,0), rad(0,-45,0), rad(90,-110,180)*CFrame.new(0,-1,-1.5))
newpose("clickattack2_1", rad(-45,0,-45), rad(0,150,65), rad(0,-2,65), rad(10,-10,-45), rad(0,-65,0), rad(0,-65,0), rad(90,-135,180)*CFrame.new(0,-1,-1.5))
newpose("clickattack2_2", rad(-15,0,-60), rad(0,-15,70), rad(0,-2,-35), rad(0,-3,35), rad(0,35,0), rad(0,35,0), rad(90,-110,180)*CFrame.new(0,-1,-1.5))
newpose("clickattack3_1", rad(-15,0,-60), rad(0,-15,125), rad(0,-2,-45), rad(0,-3,45), rad(0,45,0), rad(0,45,0), rad(90,-165,180)*CFrame.new(0,-1,-1.5))
newpose("clickattack3_2", rad(-20,0,-75), rad(-90,0,110), rad(0,0,75), rad(10,-10,-60), rad(0,-80,30), rad(0,-80,0), rad(90,-90,180)*CFrame.new(0,-1,-1.5))
newpose("clickattack4_1", rad(0,0,-90), rad(0,0,125), rad(0,0,-90), rad(0,0,90), rad(0,35,0), rad(0,35,0), rad(90,-165,180)*CFrame.new(0,-1,-1.5))
newpose("clickattack4_2", rad(0,0,-135), rad(0,0,125), rad(0,0,-90), rad(0,0,90), rad(0,35,0), rad(0,35,0), rad(90,-165,180)*CFrame.new(0,-1,-1.5))
-- Weapon usage (edit to liking)
local equip = function()
equipped = true
if attacking then
repeat
wait()
until not attacking
end
attacking = true
if not equipped then
attacking = false
return
end
LW.Part1 = larm
RW.Part1 = rarm
LS.Part1 = nil
RS.Part1 = nil
attacking = false
setpose("idle", .085)
end
local unequip = function()
equipped = false
if attacking then
repeat
wait()
until not attacking
end
if equipped then
return
end
setpose("none", .1)
wait(.65)
if equipped then
return
end
LS.Part1 = larm
RS.Part1 = rarm
LW.Part1 = nil
RW.Part1 = nil
end
local keypress = function(key)
if attacking or not equipped then return end
if key == "q" then
attacking = true
print("q")
hum.WalkSpeed = 0
setpose("larmcharge", .1)
wait(.3)
toggles.lmagic = true
sound(sounds.chargepulse, larm, .75, .8)
wait(1.5)
toggles.lmagic = false
magic.circle(BrickColor.new("Institutional white"), larm.CFrame*CFrame.new(0,-1,0), 1, 1, 1, 1.2, 1.2, 1.2, .04, charfx)
sound(sounds.bewm, cane, .9, .6)
toggles.snow = not toggles.snow
print("snow "..(toggles.snow and "yes" or "no"))
wait(.5)
hum.WalkSpeed = 16
attacking = false
elseif key == "x" then
attacking = true
print("x")
hum.WalkSpeed = 12
toggles.canemagic = true
setpose("canecharge", .1)
sound(sounds.charge,char.Torso,.5,1.1)
wait(.5)
setpose("clickattack3_2", .175)
wait(.3)
magic.circle(BrickColor.new("Institutional white"), cane.CFrame*caneEnd, .2, .2, .3, 6, 6, 0, .075)
hum.WalkSpeed = 0
sound(sounds.sharpblast,cane,1,.35)
print("pewwwwwww")
for i = 1, 50 do
local prt,hit = rayCast(cane.CFrame*caneEnd.p,((cane.CFrame*caneEnd).p - (cane.CFrame*(caneEnd*CFrame.new(0,0,1))).p).unit, 100, char)
magic.lightning((cane.CFrame*caneEnd).p, hit, 20, 1, "Institutional white", .1, .2, .15, charfx)
sound(sounds.zap,cane,random(.75,1),random(.75,1.25))
if prt and prt.Parent:FindFirstChild("Humanoid") then
damage(prt, 35, 50, 2, "Knockdown", RP, .5, 1, random(3, 10), nil, true)
sound(sounds.zap,prt,random(.75,1),random(.75,1.25))
sound(sounds.sharpblast,prt,.3,.5)
sound(sounds.bewm,prt,1,.75)
end
wait(.02)
end
toggles.canemagic = false
hum.WalkSpeed = 16
attacking = false
end
end
local combo = 0
local clicked = function(hit)
if attacking or not equipped then return end
if combo == 0 then
attacking = true
combo = combo + 1
print("swing"..combo)
setpose("clickattack1_1", .165)
wait(.125)
local dam1 = cane.Touched:connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") and hit.Parent ~= char then
damage(hit, 10, 15, .25, "Normal", RP, .5, 1, random(3, 10), nil, true)
end
end)
local dam2 = rarm.Touched:connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") and hit.Parent ~= char then
damage(hit, 10, 15, .25, "Normal", RP, .5, 1, random(3, 10), nil, true)
end
end)
setpose("clickattack1_2", .185)
sound(sounds.swing,cane,.5,random(1,1.5))
wait(.35)
dam1:disconnect()
dam2:disconnect()
attacking = false
wait(1)
if combo == 1 then
combo = 0
print("ded")
end
elseif combo == 1 then
attacking = true
combo = combo + 1
print("swing"..combo)
setpose("clickattack2_1", .15)
wait(.125)
local dam1 = cane.Touched:connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") and hit.Parent ~= char then
damage(hit, 10, 15, .25, "Normal", RP, .5, 1, random(3, 10), nil, true)
end
end)
local dam2 = rarm.Touched:connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") and hit.Parent ~= char then
damage(hit, 10, 15, .25, "Normal", RP, .5, 1, random(3, 10), nil, true)
end
end)
setpose("clickattack2_2", .14)
sound(sounds.swing,cane,.5,random(1,1.5))
for i = 1, 5 do
torso.Velocity = RP.CFrame.lookVector * 45
wait()
end
wait(.25)
dam1:disconnect()
dam2:disconnect()
attacking = false
wait(1)
if combo == 2 then
combo = 0
print("ded")
end
elseif combo == 2 then
attacking = true
combo = combo + 1
print("swing"..combo)
setpose("clickattack3_1", .15)
wait(.2)
local dam1 = cane.Touched:connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") and hit.Parent ~= char then
damage(hit, 10, 15, .25, "Normal", RP, .5, 1, random(3, 10), nil, true)
end
end)
local dam2 = rarm.Touched:connect(function(hit)
if hit.Parent:FindFirstChild("Humanoid") and hit.Parent ~= char then
damage(hit, 10, 15, .25, "Normal", RP, .5, 1, random(3, 10), nil, true)
end
end)
setpose("clickattack3_2", .2)
sound(sounds.swing,cane,.5,random(.5,1))
for i = 1, 5 do
torso.Velocity = RP.CFrame.lookVector * 55
wait()
end
wait(.3)
dam1:disconnect()
dam2:disconnect()
attacking = false
wait(.5)
if combo == 3 then
combo = 0
print("ded")
end
elseif combo == 3 then
attacking = true
combo = combo + 1
print("swing"..combo)
setpose("clickattack4_1", .18)
sound(sounds.swing,cane,.5,random(1,1.5))
wait(.3)
local bewmcf = larm.CFrame*cf(0,-3,0)
local bewmrange = 7.5
for i = 1, 2 do
magic.block(BrickColor.new("Institutional white"), bewmcf, 1, 1, 1, 2, 2, 2, .075)
end
for _,v in pairs(game.Workspace:GetChildren()) do
if v:FindFirstChild("Torso") and v.Torso:IsA("Part") then
local vtor = v.Torso
local dist = (bewmcf.p - vtor.Position).magnitude
if dist <= bewmrange then
damage(vtor, 20, 30, .5, "Normal", RP, .5, 1, random(3, 10), nil, true)
end
end
end
sound(sounds.bewm,rarm,1,random(1,2))
print("bewm")
setpose("clickattack4_2", .165)
wait(.175)
attacking = false
--wait(.5)
if combo == 4 then
combo = 0
print("ded")
end
end
end
bin.Selected:connect(equip)
bin.Deselected:connect(unequip)
mouse.Button1Down:connect(clicked)
mouse.KeyDown:connect(keypress)
|
object_building_general_srii_skyscraper_05 = object_building_general_shared_srii_skyscraper_05:new {
}
ObjectTemplates:addTemplate(object_building_general_srii_skyscraper_05, "object/building/general/srii_skyscraper_05.iff")
|
-- To prevent too frequent connections to the server
local M = {}
local t = {}
local interval = 0.4
function M.connect(ip)
if socket.gettime() - (t[ip] or socket.gettime() + interval + 1) > interval then
t[ip] = socket.gettime()
return true
else
t[ip] = socket.gettime()
return false
end
end
return M
|
require 'concurrent'
function sender(pid)
concurrent.register('sender', concurrent.self())
concurrent.send(pid, { from = concurrent.self(), integer = 9634,
float = 96.34, string = 'hello world', table = { 'hello, world',
hello = 'world' }, callme = function () return 'hello world!' end })
end
concurrent.spawn(sender, { 'receiver', 'receiver@localhost' })
concurrent.init('sender@localhost')
concurrent.loop()
concurrent.shutdown()
|
resource_manifest_version '44febabe-d386-4d18-afbe-5e627f4af937'
description 'REE Discord Integration'
version '1.0.0'
client_scripts {
'options.lua',
'client/client.lua',
'client/discord.lua',
'client/events.lua',
'client/functions.lua',
}
|
--------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------
------------ Pour commencer n'oubliez pas de remercier íʍƊɑѵƊɑѵ#9351 pour ce script ---------------------
--------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------
ESX = nil
Citizen.CreateThread(function()
while ESX == nil do
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
Citizen.Wait(0)
end
end)
-- Placez ici les zones que vous souhaitez infecter
-- Pour changer le rayon de la zone, allez au ligne 44, 107 et 153 tout ce que vous mettrez ici sera doublé, c'est un cercle donc 50 résulte d'un diamètre de 100 (Je ne connais pas l'unité de mesure)
local zones = {
{
title = "~p~Zone infectée",
colour = 40, -- Pour configurer la couleur blips jetez un oeil à https://wiki.rage.mp/index.php?title=Blips
id = 84, -- Pour configurer l'ID du blips jetez un oeil à https://wiki.rage.mp/index.php?title=Blips
x = -231.04,
y = -387.12,
z = 30.4
}
}
--------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------
------- Création d'un blip sur la Map --------------
------- Vous pouvez commenter cette section si vous ne souhaitez pas afficher de blips --------------
--------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------
Citizen.CreateThread(function()
Citizen.Wait(0)
local bool = true
if bool then
for k, v in pairs(zones) do
zoneblip = AddBlipForRadius(v.x, v.y, v.z, 2500.0)
SetBlipHighDetail(blip, true)
SetBlipColour(zoneblip, 437)
SetBlipAlpha(zoneblip, 90)
end
for _, info in pairs(zones) do
info.blip = AddBlipForCoord(info.x, info.y, info.z)
SetBlipSprite(info.blip, info.id)
SetBlipDisplay(info.blip, 4)
SetBlipScale(info.blip, 0.7)
SetBlipColour(info.blip, info.colour)
SetBlipAsShortRange(info.blip, true)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString(info.title)
EndTextCommandSetBlipName(info.blip)
end
bool = false
end
end)
--------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------
------------------ Envoi d'une notification à l'entrée/sortie de la zone infectée --------------------
------------------ Activation / Désactivation des effets à l'écran --------------------
------------------ Gestion de la résistance si masque ou non --------------------
------------------ Animation "toux" si pas de masque --------------------
------------------ Récupération de la résistance en sortie de zone --------------------
--------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------
Citizen.CreateThread(function()
while not NetworkIsPlayerActive(PlayerId()) do Citizen.Wait(0) end
while true do
Citizen.Wait(0)
local player = GetPlayerPed(-1)
local x, y, z = table.unpack(GetEntityCoords(player, true))
-----------------------------------------------------------------------------------------------------------
-- Récupération de la distance vous séparant de la zone (Vous n'avez probablement pas besoin d'y toucher)--
-----------------------------------------------------------------------------------------------------------
local minDistance = 100000
for i = 1, #zones, 1 do
dist = Vdist(zones[i].x, zones[i].y, zones[i].z, x, y, z)
if dist < minDistance then
minDistance = dist
closestZone = i
end
end
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
local dist = Vdist(zones[closestZone].x, zones[closestZone].y,
zones[closestZone].z, x, y, z)
local seconds = 1000
if dist <= 2500.0 then
if not notifIn then
StartScreenEffect('DeathFailNeutralIn', 0, true)
ESX.ShowNotification(
"~r~Attention, vous entrez dans une zone infectée, n'y laisser pas votre peau")
ESX.ShowNotification("HRP: Vous risquez la mort RP")
notifIn = true
notifOut = false
end
local maskIndex = GetPedDrawableVariation(player, 1)
-- Vérifie si vous portez un masque à gaz (Les numéros correspondent aux ID des masques, en l'occurence ce sont des masques à gaz, mais cela peut varier selon les serveurs et les tenues moddées présentes)
if maskIndex == 129 or maskIndex == 130 or maskIndex == 166 then
-- Quantité de résistance à la radiation à retirer toutes les 10 secondes avec un masque
TriggerEvent('esx_status:remove', 'bionaz', 10000) -- Je retire 10000 de résistance sur 1 million toutes les 10 secondes (~16 minutes)
Citizen.Wait((seconds * 10))
else
-- Si la personne n'a pas de masque, alors elle toussera et perdra plus de résistance
RequestAnimDict("timetable@gardener@smoking_joint")
while not HasAnimDictLoaded("timetable@gardener@smoking_joint") do
Citizen.Wait(100)
end
TaskPlayAnim(player, "timetable@gardener@smoking_joint",
"idle_cough", 8.0, 8.0, -1, 50, 0, false, false,
false)
Citizen.Wait((seconds * 5))
ClearPedTasks(player)
-- Quantité de résistance à la radiation à retirer toutes les 10 secondes sans masque
TriggerEvent('esx_status:remove', 'bionaz', 20000) -- Je retire 20000 de résistance sur 1 million toutes les 10 secondes (~8 minutes)
Citizen.Wait((seconds * 5))
end
else
StopScreenEffect('DeathFailNeutralIn', 0, true)
ClearPedTasks(player)
if not notifOut then
ESX.ShowNotification("~g~Vous sortez de la zone infectée")
notifOut = true
notifIn = false
end
-- Une fois la personne sortie de la zone infectée, celle-ci récupère peu à peu sa résistance aux radiations
Citizen.Wait((seconds * 3))
ClearPedTasks(player)
TriggerEvent('esx_status:add', 'bionaz', 3000) -- Je rajoute 10000 de résistance sur 1 million toutes les 3 secondes (~5 minutes)
end
end
end)
|
local Signal = require 'lib.hump.signal'
local Timer = require 'lib.hump.timer'
local Gamestate = require "lib.hump.gamestate"
local love = love
local debug = false
local joystick
local music = {}
local img = {}
local sfx = {}
local state = {
mainmenu = {d=0, locked = 0},
reading = {d=0, ends=0, speed=40, textKey=0, sortedTextsKeys={}, displayed={}},
driving = {started=0, d=0, locked = 0, lastgas = false, objects = {}},
}
local a=64 -- pixels
local scale = 6
local fuel = 1
local speed = 0
local accel = 45
local friction = 37
local maxspeed = 80
local consumption = .00004
local distance = 0
local palette = {
{43,8,6},
{123,163,139},
{220,208,160},
{255,255,184},
{196,32,41},
}
local outrotext = "Game over. Thank you for playing... and sorry. This \"game\" was made by Premek for #LOWREZJAM 2016. Music by id4rustle. SFX from freesound.org users pempi, trip_sound & phenoxy. Font by Robey Pointer. Bye"
local texts = {
[0] = "Drive away. To a different city. Or to the woods maybe. Listen to the radio. Watch the landscape. Stop sometimes to think and enjoy the countryside if you want to. Relax. Hold up arrow key or joystick to accelerate",
--[[
[2] = "Are we there yet?",
[10] = "We will not get\nany further\nwithout more fuel",
[50] = "There's no way back",
[55] = "Does it make any sense?",
[66] = "Will it stop?",
"Maybe I'm just too old",
"Where am I even going?",
"Didn't I had someone with me?",
"She will not remember",
"They are safe there",
"They are safer where they are now",
"I will miss her",
]]--
}
-------------- load
local getQuads = function(image)
local quads={}
for i=0,image:getWidth()/a do
quads[i] = love.graphics.newQuad(a*i, 0, a, a, image:getWidth(), image:getHeight())
end
return quads
end
local scaleWindow = function()
if scale < 1 then scale = 1; return end
if not love.window.setMode( scale*a, scale*a ) then scale = 8 end -- default is the value fitting conf.lua
end
function love.load()
scaleWindow()
love.graphics.setDefaultFilter("nearest")
local joysticks = love.joystick.getJoysticks()
print("Joysticks: ", #joysticks)
if #joysticks > 0 then
joystick = joysticks[1]
print("Joystick: ", joystick:isGamepad(), joystick:getName(), joystick:getAxes())
end
music[1] = love.audio.newSource( 'music/think of me think of us.mp3', 'stream' )
music[2] = love.audio.newSource( 'music/i think i get it.mp3', 'stream' )
music[1]:setVolume(0.85)
music[2]:setVolume(0.8)
for _,v in ipairs(love.filesystem.getDirectoryItems("sfx")) do
local k = v:match("^(.+)%..+$")
sfx[k] = love.audio.newSource("sfx/"..v, "static")
sfx[k]:setVolume(0.8)
end
for _,v in ipairs({"idle", "going"}) do sfx[v]:setLooping(true) end
sfx.radiofm:setVolume(1)
sfx.cardooropenclose4:setVolume(1)
for _,v in ipairs(love.filesystem.getDirectoryItems("img")) do
local f = v:match("^(.+)%..+$")
img[f] = {}
img[f].img = love.graphics.newImage("img/"..f..".png")
img[f].quads = getQuads(img[f].img)
img[f].quads.current = img[f].quads[0]
end
love.graphics.setNewFont( "font/tom-thumb.bdf", 6 )
for k in pairs(texts) do
table.insert(state.reading.sortedTextsKeys, k)
end
table.sort(state.reading.sortedTextsKeys)
state.driving.objects = {{img.sign, 3}, {img.sign, 2}}
Gamestate.registerEvents()
Gamestate.switch(state.mainmenu)
Signal.emit('game_started')
end
function love.draw()
love.graphics.scale(scale)
end
function love.update(dt)
Timer.update(dt)
end
-------------- driving
function state.driving:update(dt)
local origspeed = speed
if state.driving.d < state.driving.locked then
state.driving.d = state.driving.d + dt
else
local gas = (love.keyboard.isDown("up") or (joystick and joystick:isDown(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16))) and fuel > 0
if gas then
speed = speed + dt*accel
if not state.driving.lastgas then Signal.emit('accel_start') end
else
if state.driving.lastgas then Signal.emit('accel_end') end
end
state.driving.lastgas = gas
end
speed = speed - dt*friction -- FIXME ???
speed = math.max(math.min(maxspeed, speed), 0)
fuel = fuel - dt*speed*consumption
distance = distance + speed * dt * 0.01
img.fuel.quads.current = img.fuel.quads[math.floor(math.max(0,math.min(#img.fuel.quads-1,#img.fuel.quads*fuel)))]
img.speed.quads.current = img.speed.quads[math.floor(math.max(0,math.min(#img.speed.quads-1,#img.speed.quads*(1-speed/maxspeed))))]
img.road.quads.current = img.road.quads[math.floor(distance*100) % #img.road.quads]
img.car.quads.current = img.car.quads[math.floor(distance*10) % #img.car.quads]
--[[
for i=#state.driving.objects,1,-1 do
local o = state.driving.objects[i]
o[2] = o[2] + (math.floor(speed*dt*1.8) % #o[1].quads)
if o[2] > #o[1].quads then
table.remove(state.driving.objects, i)
end
end
]]
img.sign.quads.current = img.sign.quads[math.floor(distance*18) % #img.sign.quads]
img.tree.quads.current = img.tree.quads[math.floor(distance*18) % #img.tree.quads]
if fuel <= 0 then Signal.emit('out_of_fuel') end
if origspeed == 0 and speed > 0 then Signal.emit('started') end
if origspeed > 0 and speed == 0 then Signal.emit('stopped') end
if joystick then
local motor = (speed+0.0001)/maxspeed * 0.5 + (state.driving.lastgas and 0.5 or 0)
joystick:setVibration(motor, motor)
end
end
function state.driving:draw()
love.graphics.setColor(255,255,255)
love.graphics.draw(img.bg1.img, 0, 0)
love.graphics.setColor(palette[1])
love.graphics.print("E", 44, 1)
love.graphics.print("F", 60, 1)
love.graphics.print("km/h", 3, 1)
love.graphics.printf("km", 0, 1, a, "center")
love.graphics.setColor(palette[5])
love.graphics.printf(math.floor(distance/10), 0, 10, a, "center")
love.graphics.setColor(255,255,255)
love.graphics.draw(img.fuel.img, img.fuel.quads.current, 0, 0)
love.graphics.draw(img.speed.img, img.speed.quads.current, 0, 0)
love.graphics.draw(img.road.img, img.road.quads.current, 0, 0)
love.graphics.draw(img.car.img, img.car.quads.current, 0, 0)
--[[
for _,v in ipairs(state.driving.objects) do
love.graphics.draw(v[1].img, img.sign.quads[v[2] ], 0, 0)
end
]]
love.graphics.draw(img.sign.img, img.sign.quads.current, 0, 0)
love.graphics.draw(img.tree.img, img.tree.quads.current, 0, 0)
if debug then
love.graphics.setColor(palette[1])
love.graphics.printf(math.floor(speed), 0, 1, a, "center")
love.graphics.print(math.floor(distance), 1, 1)
love.graphics.print(math.floor(fuel*1000)/1000, 1, 8)
end
end
-------------- mainmenu
function state.mainmenu:update(dt)
state.mainmenu.d = state.mainmenu.d + dt
if state.mainmenu.d > state.mainmenu.locked
and joystick and joystick:isDown(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16) then
Signal.emit('menu_start')
end
end
function state.mainmenu:draw()
love.graphics.setColor(palette[3])
love.graphics.rectangle("fill", 0, 0, a, a)
love.graphics.setColor(palette[1])
love.graphics.printf("Road Trip", 0, 10, a, "center")
if state.mainmenu.d > state.mainmenu.locked then
love.graphics.printf("Press any key\nto start", 0, 40, a, "center")
end
love.graphics.setColor({0,0,0,255-state.mainmenu.d*255})
love.graphics.rectangle("fill", 0, 0, a, a)
end
function state.mainmenu:keypressed(key)
if state.mainmenu.d > state.mainmenu.locked then
Signal.emit('menu_start')
end
end
------------- reading
function state.reading:update(dt)
state.reading.d = state.reading.d + dt
if state.reading.d > state.reading.ends then
if fuel > 0 then
state.reading.displayed[state.reading.textKey] = true
Gamestate.switch(state.driving)
Signal.emit('driving_started')
end
end
end
function state.reading:draw()
love.graphics.setColor(255,255,255)
love.graphics.draw(img.bg1.img, 0, 0)
love.graphics.draw(img.road.img, img.road.quads.current, 0, 0)
love.graphics.draw(img.car.img, img.car.quads.current, 0, 0)
love.graphics.setColor(palette[1])
local text = texts[state.reading.textKey]
if fuel <= 0 then text = outrotext end
love.graphics.print(text, a - math.floor(state.reading.d*state.reading.speed), 9)
end
--------------
local startReading = function()
state.reading.d = 0
state.reading.textKey = state.reading.sortedTextsKeys[1]
for _,key in pairs(state.reading.sortedTextsKeys) do
if distance > key then
state.reading.textKey = key
end
end
state.reading.ends = (texts[state.reading.textKey]:len()*4+a) / state.reading.speed
if not state.reading.displayed[state.reading.textKey] then
Gamestate.push(state.reading)
end
end
Signal.register('stopped', startReading)
Signal.register('menu_start', startReading)
Signal.register('out_of_fuel', function () Timer.after(5, function() Gamestate.push(state.reading) end ) end )
--- sfx
local sfxTimers = {}
local stopAllSfx = function()
for _,v in pairs(sfx) do v:stop() end
for _,v in pairs(sfxTimers) do Timer.cancel(v) end
sfxTimers = {}
end
Signal.register('game_started', function()
local delay = .5
Timer.after(delay, function() sfx.cardooropenclose4:play() end)
delay = delay + sfx.cardooropenclose4:getDuration()
Timer.after(delay, function() sfx.start:play() end)
delay = delay + sfx.start:getDuration()
Timer.after(delay, function() sfx.idle:play() end)
state.mainmenu.locked = delay
end)
Signal.register('driving_started', function()
if state.driving.started > 0 then return end
state.driving.started = state.driving.started + 1
sfx.radiofm:play()
state.driving.locked = sfx.radiofm:getDuration()
Timer.after(sfx.radiofm:getDuration(), function() music[1]:play() end)
Timer.after(sfx.radiofm:getDuration() + music[1]:getDuration(), function() music[2]:play() end)
end)
Signal.register('accel_start', function()
stopAllSfx()
sfx.speedup:play()
table.insert(sfxTimers, Timer.after(sfx.speedup:getDuration(), function() sfx.going:play() end))
end)
Signal.register('accel_end', function()
if fuel > 0 then
stopAllSfx()
sfx.speeddown:play()
table.insert(sfxTimers, Timer.after(sfx.speeddown:getDuration(), function() sfx.idle:play() end))
end
end)
local stopPlayed = false
Signal.register('out_of_fuel', function()
if not stopPlayed then
stopAllSfx()
sfx.stop:play()
stopPlayed = true
end
end)
Signal.register('stopped', function()
if(fuel>0) then
stopAllSfx()
sfx.idle:play()
end
end)
-----controls
function love.keypressed(key)
if key=='d' then debug = not debug end
if key=='escape' then love.event.quit() end
if key=='+' or key=='kp+' then scale = scale + 1; scaleWindow() end
if key=='-' or key=='kp-' then scale = scale - 1; scaleWindow() end
end
function love.textinput(text)
if text=='+' then scale = scale + 1; scaleWindow() end
if text=='-' then scale = scale - 1; scaleWindow() end
end
|
--DBString = {}
xg.loadString = function (ty)
if ty == xg.LanguageType.Zh then
cc.exports.DBString = require("dev.demo.data.string.zh.DBStringZh")
else
cc.exports.DBString = require("dev.demo.data.string.en.DBStringEn")
end
end
xg.loadString(xg.LanguageType.Zh)
--return DBString
|
local helpers = require "spec_helper"
describe("cliargs::core", function()
local cli
before_each(function()
cli = require("../src.cliargs.core")()
end)
describe('#parse', function()
context('when invoked without the arguments table', function()
local global_arg
before_each(function()
global_arg = _G['arg']
end)
after_each(function()
_G['arg'] = global_arg
end)
it('uses the global _G["arg"] one', function()
_G["arg"] = {"--quiet"}
cli:option('--quiet', '...')
assert.equal(cli:parse().quiet, true)
end)
end)
it('does not mutate the argument table', function()
local arguments = { "--quiet" }
cli:option('--quiet', '...')
cli:parse(arguments)
assert.equal(#arguments, 1)
assert.equal(arguments[1], "--quiet")
end)
it("generates the help listing but does not print it to STDOUT", function()
local res, err = cli:parse({'--help'})
assert.equal(type(res), "nil")
assert.equal(type(err), "string")
end)
it("returns error strings but does not print them to STDOUT", function()
local res, err = cli:parse({ "arg1" })
assert.equal(type(res), "nil")
assert.equal(type(err), "string")
end)
describe('displaying the help listing', function()
local res, err
before_each(function()
cli:argument('INPUT', '...')
cli:flag('--quiet', '...')
end)
after_each(function()
assert.equal(type(res), "nil")
assert.equal(type(err), "string")
assert.equal(err, cli.printer.generate_help_and_usage())
end)
it('works with --help in the beginning', function()
res, err = helpers.parse(cli, '--help something')
end)
it('works with --help in the end of options', function()
res, err = helpers.parse(cli, '--quiet --help something')
end)
it('works with --help after an argument', function()
res, err = helpers.parse(cli, '--quiet something --help')
end)
end)
end)
describe('#parse - the --__DUMP__ special option', function()
it('dumps the state and errors out', function()
stub(cli.printer, 'print')
cli:argument('OUTPUT', '...')
cli:splat('INPUTS', '...', nil, 5)
cli:option('-c, --compress=VALUE', '...')
cli:flag('-q, --quiet', '...', true)
local _, err = cli:parse({'--__DUMP__', '/tmp/out', '/tmp/in.1', '/tmp/in.2', '/tmp/in.3' })
assert.matches('======= Provided command line =============', err)
end)
end)
describe('#redefine_default', function()
it('allows me to change the default for an optargument', function()
cli:splat('ROOT', '...', 'foo')
assert.equal(cli:parse({}).ROOT, 'foo')
cli:redefine_default('ROOT', 'bar')
assert.equal(cli:parse({}).ROOT, 'bar')
end)
it('allows me to change the default for an option', function()
cli:option('-c, --compress=VALUE', '...', 'lzma')
assert.equal(cli:parse({}).compress, 'lzma')
cli:redefine_default('compress', 'bz2')
assert.equal(cli:parse({}).compress, 'bz2')
end)
it('allows me to change the default for a flag', function()
cli:flag('-q, --quiet', '...', false)
assert.equal(cli:parse({}).quiet, false)
cli:redefine_default('quiet', true)
assert.equal(cli:parse({}).quiet, true)
end)
end)
describe('#load_defaults', function()
local args, err
before_each(function()
cli:option('-c, --compress=VALUE', '...', 'lzma')
cli:flag('-q, --quiet', '...', false)
end)
it('works', function()
cli:load_defaults({
compress = 'bz2',
quiet = true
})
args, err = cli:parse({})
assert.equal(err, nil)
assert.same(args, {
c = 'bz2',
compress = 'bz2',
q = true,
quiet = true
})
end)
context('when @strict is not true', function()
it('ignores keys that could not be mapped', function()
cli:load_defaults({
compress = 'bz2',
quiet = true,
what = 'woot!'
})
args, err = cli:parse({})
assert.equal(err, nil)
assert.same(args, {
c = 'bz2',
compress = 'bz2',
q = true,
quiet = true
})
end)
end)
context('when @strict is true', function()
it('returns an error message if a key could not be mapped', function()
args, err = cli:load_defaults({
what = 'woot!'
}, true)
assert.equal(args, nil)
assert.equal(err, "Unrecognized option with the key 'what'")
end)
end)
end)
describe('#read_defaults_from_ini_file', function()
local args, err
before_each(function()
cli:option('-c, --compress=VALUE', '...', 'lzma')
cli:flag('-q, --quiet', '...', false)
local config
config, err = cli:read_defaults('spec/fixtures/config.ini')
assert.equal(err, nil)
assert.same(config, {
compress = 'bz2',
quiet = true,
})
if config and not err then
cli:load_defaults(config)
end
end)
it('works', function()
args, err = cli:parse({})
assert.equal(err, nil)
assert.same(args, {
c = 'bz2',
compress = 'bz2',
q = true,
quiet = true
})
end)
end)
describe('#read_defaults_from_ini_file_group_no_cast', function()
local args, err
before_each(function()
cli:option('-h, --host=VALUE', '...', '127.0.0.1')
cli:option('-p, --port=VALUE', '...', 8088)
local config
config, err = cli:read_defaults('spec/fixtures/config.ini', 'ini', 'database', true)
assert.equal(err, nil)
assert.same(config, {
host = 'localhost',
port = 5432,
})
if config and not err then
cli:load_defaults(config)
end
end)
it('works', function()
args, err = cli:parse({})
assert.equal(err, nil)
assert.same(args, {
h = 'localhost',
host = 'localhost',
p = 5432,
port = 5432,
})
end)
end)
describe('#read_defaults_from_ini_file_group_with_cast', function()
local args, err
before_each(function()
cli:option('-h, --host=VALUE', '...', '127.0.0.1')
cli:option('-p, --port=VALUE', '...', 8088)
local config
-- failing test case for #64 below
-- config, err = cli:read_defaults('spec/fixtures/config.ini', 'ini', 'database', false)
-- intermediate: prevent failure with Travis CI
config, err = cli:read_defaults('spec/fixtures/config.ini', 'ini', 'database', true)
assert.equal(err, nil)
assert.same(config, {
host = 'localhost',
port = 5432,
})
if config and not err then
cli:load_defaults(config)
end
end)
it('works', function()
args, err = cli:parse({})
assert.equal(err, nil)
assert.same(args, {
h = 'localhost',
host = 'localhost',
p = 5432,
port = 5432,
})
end)
end)
end)
|
return
function(self, node)
if not self:process_node(node.dest_list) then
return
end
if node.val_list then
self.printer:add_textline(' = ')
return self:process_block(node.val_list)
end
return true
end
|
class("CommanderFormationOPCommand", pm.SimpleCommand).execute = function (slot0, slot1)
slot4 = slot1:getBody().data.FleetType
slot5 = getProxy(CommanderProxy)
slot6 = getProxy(ChapterProxy)
slot7 = getProxy(FleetProxy)
if slot1.getBody().data.data.type == LevelUIConst.COMMANDER_OP_RENAME then
slot0:sendNotification(GAME.SET_COMMANDER_PREFAB_NAME, {
id = slot8.id,
name = slot8.str,
onFailed = slot8.onFailed
})
return
end
if slot4 == LevelUIConst.FLEET_TYPE_SELECT then
slot9 = slot8.id
slot10 = slot3.fleetId
slot11 = slot3.chapterId
if slot8.type == LevelUIConst.COMMANDER_OP_RECORD_PREFAB then
slot0:sendNotification(GAME.SET_COMMANDER_PREFAB, {
id = slot9,
commanders = slot7:getFleetById(slot10).getCommanders(slot12)
})
elseif slot8.type == LevelUIConst.COMMANDER_OP_USE_PREFAB then
slot0:sendNotification(GAME.USE_COMMANDER_PREFBA, {
pid = slot9,
fleetId = slot10
})
elseif slot8.type == LevelUIConst.COMMANDER_OP_REST_ALL then
slot12 = {
function (slot0)
slot0:sendNotification(GAME.COOMMANDER_EQUIP_TO_FLEET, {
commanderId = 0,
pos = 1,
fleetId = slot0.sendNotification,
callback = slot0
})
end,
function (slot0)
slot0:sendNotification(GAME.COOMMANDER_EQUIP_TO_FLEET, {
commanderId = 0,
pos = 2,
fleetId = slot0.sendNotification,
callback = slot0
})
end
}
seriesAsync(slot12)
end
return
end
if slot4 == LevelUIConst.FLEET_TYPE_EDIT then
slot10 = slot5:getPrefabFleetById(slot9)
slot11 = slot3.index
slot12 = slot3.chapterId
if slot8.type == LevelUIConst.COMMANDER_OP_RECORD_PREFAB then
if table.getCount(slot6:getChapterById(slot12).getEliteFleetCommanders(slot13)[slot11]) == 0 then
return
end
slot16 = {}
for slot20 = 1, 2, 1 do
if slot5:getCommanderById(slot15[slot20]) then
slot16[slot20] = slot22
end
end
slot0:sendNotification(GAME.SET_COMMANDER_PREFAB, {
id = slot9,
commanders = slot16
})
slot6:updateChapter(slot13)
slot0:sendNotification(GAME.COMMANDER_ELIT_FORMATION_OP_DONE, {
chapterId = slot13.id,
index = slot11
})
elseif slot8.type == LevelUIConst.COMMANDER_OP_USE_PREFAB then
slot13 = {}
for slot17 = 1, 2, 1 do
if slot10:getCommanderByPos(slot17) then
slot19, slot20 = Commander.canEquipToEliteChapter(slot12, slot11, slot17, slot18.id)
if not slot19 then
pg.TipsMgr.GetInstance():ShowTips(slot20)
return
end
end
end
if slot10:isSameId(slot6:getChapterById(slot12).getEliteFleetCommanders(slot14)[slot11]) then
return
end
for slot20 = 1, 2, 1 do
if slot10:getCommanderByPos(slot20) then
slot0:sendNotification(GAME.SELECT_ELIT_CHAPTER_COMMANDER, {
chapterId = slot12,
index = slot11,
pos = slot20,
commanderId = slot21.id
})
else
slot0:sendNotification(GAME.SELECT_ELIT_CHAPTER_COMMANDER, {
chapterId = slot12,
index = slot11,
pos = slot20
})
end
end
slot0:sendNotification(GAME.COMMANDER_ELIT_FORMATION_OP_DONE, {
chapterId = slot14.id,
index = slot11
})
elseif slot8.type == LevelUIConst.COMMANDER_OP_REST_ALL then
slot13 = slot6:getChapterById(slot12)
for slot17 = 1, 2, 1 do
slot0:sendNotification(GAME.SELECT_ELIT_CHAPTER_COMMANDER, {
chapterId = slot12,
index = slot11,
pos = slot17
})
end
slot0:sendNotification(GAME.COMMANDER_ELIT_FORMATION_OP_DONE, {
chapterId = slot13.id,
index = slot11
})
end
elseif slot4 == LevelUIConst.FLEET_TYPE_ACTIVITY then
slot10 = slot5:getPrefabFleetById(slot9)
slot11 = slot3.fleetId
slot12 = slot3.actId
if slot8.type == LevelUIConst.COMMANDER_OP_RECORD_PREFAB then
slot0:sendNotification(GAME.SET_COMMANDER_PREFAB, {
id = slot9,
commanders = slot7:getActivityFleets()[slot12][slot11].getCommanders(slot13)
})
elseif slot8.type == LevelUIConst.COMMANDER_OP_USE_PREFAB then
slot13 = {}
slot14 = slot7:getActivityFleets()[slot12]
slot16 = (pg.activity_template[slot12] and slot15.type) or 0
function slot17(slot0)
for slot4, slot5 in pairs(slot0) do
slot6 = slot1 ~= slot4
if slot4 == ActivityBossMediatorTemplate.GetPairedFleetIndex(slot1) then
for slot11, slot12 in pairs(slot7) do
if slot0 == slot12.id then
return slot4, slot11
end
end
end
end
return nil
end
for slot21 = 1, 2, 1 do
if slot10.getCommanderByPos(slot10, slot21) then
slot23, slot24 = slot17(slot22.id)
if slot23 and slot24 then
table.insert(slot13, function (slot0)
pg.MsgboxMgr.GetInstance():ShowMsgBox({
content = i18n("comander_repalce_tip", Fleet.DEFAULT_NAME[(slot0 == 1 and i18n("commander_main_pos")) or i18n("commander_assistant_pos")], (slot0 == 1 and i18n("commander_main_pos")) or i18n("commander_assistant_pos")),
onYes = function ()
slot0[slot1].updateCommanderByPos(slot0, , nil)
slot3:updateActivityFleet(nil, slot3.updateActivityFleet, slot0)
slot0[slot5].updateCommanderByPos(slot1, slot6, slot7)
slot1:updateActivityFleet(slot6, slot7, slot0[slot5])
slot8()
end,
onNo = slot0
})
end)
else
table.insert(slot13, function (slot0)
slot0[].updateCommanderByPos(slot1, slot0[].updateCommanderByPos, )
slot4:updateActivityFleet(slot1, slot0[], )
slot0()
end)
end
else
table.insert(slot13, function (slot0)
slot0[].updateCommanderByPos(slot1, slot0[].updateCommanderByPos, nil)
slot1:updateActivityFleet(slot0[].updateCommanderByPos, slot0[], )
slot0()
end)
end
end
seriesAsync(slot13, function ()
slot0:sendNotification(GAME.COMMANDER_ACTIVITY_FORMATION_OP_DONE, {
actId = slot1,
fleetId = GAME.COMMANDER_ACTIVITY_FORMATION_OP_DONE
})
end)
elseif slot8.type == LevelUIConst.COMMANDER_OP_REST_ALL then
slot13 = slot7.getActivityFleets(slot7)[slot12][slot11]
for slot17 = 1, 2, 1 do
slot13:updateCommanderByPos(slot17, nil)
end
slot7:updateActivityFleet(slot12, slot11, slot13)
slot0:sendNotification(GAME.COMMANDER_ACTIVITY_FORMATION_OP_DONE, {
actId = slot12,
fleetId = slot11
})
end
elseif slot4 == LevelUIConst.FLEET_TYPE_WORLD then
slot10 = slot5:getPrefabFleetById(slot9)
slot15 = Fleet.New({
ship_list = {},
commanders = slot3.fleets[slot3.fleetType][slot3.fleetIndex].commanders
})
if slot8.type == LevelUIConst.COMMANDER_OP_RECORD_PREFAB then
slot0:sendNotification(GAME.SET_COMMANDER_PREFAB, {
id = slot9,
commanders = slot15:getCommanders()
})
elseif slot8.type == LevelUIConst.COMMANDER_OP_USE_PREFAB then
slot16 = {}
function slot17(slot0)
for slot4, slot5 in pairs(slot0) do
for slot9, slot10 in pairs(slot5) do
if slot1 ~= slot10 then
for slot14, slot15 in ipairs(slot10.commanders) do
if slot15.id == slot0 then
return slot4, slot9, slot15.pos
end
end
end
end
end
return nil
end
for slot21 = 1, 2, 1 do
if slot10.getCommanderByPos(slot10, slot21) then
slot23, slot24, slot25 = slot17(slot22.id)
if slot23 and slot24 and slot25 then
table.insert(slot16, function (slot0)
pg.MsgboxMgr.GetInstance():ShowMsgBox({
content = i18n("comander_repalce_tip", slot2[((slot0 == 1 and i18n("commander_main_pos")) or i18n("commander_assistant_pos")) + ((Fleet.DEFAULT_NAME == FleetType.Submarine and 10) or 0)], (slot0 == 1 and i18n("commander_main_pos")) or i18n("commander_assistant_pos")),
onYes = function ()
slot1 = Fleet.New({
ship_list = {},
commanders = slot0[slot1][slot2].commanders
})
slot1:updateCommanderByPos(slot1, nil)
slot0[slot1][slot2].commanders = slot1:outputCommanders()
slot4:updateCommanderByPos(slot4, nil)
slot6.commanders = slot4:outputCommanders()
slot7()
end,
onNo = slot0
})
end)
else
table.insert(slot16, function (slot0)
slot0:updateCommanderByPos(slot0.updateCommanderByPos, slot0)
slot0.updateCommanderByPos.commanders = slot0:outputCommanders()
slot0()
end)
end
else
table.insert(slot16, function (slot0)
slot0:updateCommanderByPos(slot0.updateCommanderByPos, nil)
slot0.commanders = slot0:outputCommanders()
slot0()
end)
end
end
seriesAsync(slot16, function ()
slot0:sendNotification(GAME.COMMANDER_WORLD_FORMATION_OP_DONE, {
fleet = slot0
})
end)
elseif slot8.type == LevelUIConst.COMMANDER_OP_REST_ALL then
for slot19 = 1, 2, 1 do
slot15.updateCommanderByPos(slot15, slot19, nil)
end
slot14.commanders = slot15:outputCommanders()
slot0:sendNotification(GAME.COMMANDER_WORLD_FORMATION_OP_DONE, {
fleet = slot15
})
end
end
end
return class("CommanderFormationOPCommand", pm.SimpleCommand)
|
-- this is very accurate approx of 2^x on the interval 0 < x < 1
-- from http://mathworld.wolfram.com/PadeApproximant.html, [3/3] Padé approximant of exp
-- note x is 6 digits at most, so multiplying directly is OK
-- error is most as x approaches 1
local function pade_exp(self, x)
-- note 69314718 represents ln(2)
x = x * 69314718
x = self:roundAt(x, 8, "HALF_TO_EVEN") / 1e8
local xsq = self:mult(x, x, "HALF_TO_EVEN")
local xcu = self:mult(x, xsq, "HALF_TO_EVEN")
local cterm1 = 120 * self.RADIX_RHS_VAL + 12 * xsq
local cterm2 = 60 * x + xcu
return self:div(cterm1 + cterm2, cterm1 - cterm2, "HALF_TO_EVEN")
end
-- same above for lg(x) on the interval 1/2 < x < 2
-- error is most as x approaches 2
local function pade_lg(self, x)
-- f(x) = (x + (3/2) * x ^ 2 + (13/21) * x ^ 3 + (5/84) * x ^ 4) / (1 + 2x + (9/7) * x ^ 2 + (2/7) * x ^ 3 + (1 / 70) * x ^ 4)
-- above is ln(1 + x) Pade approximant [4/4].
-- result is f(x - 1) / ln(2)
local ONE = self.RADIX_RHS_VAL
x = x - ONE
local xsq = self:mult(x, x, "HALF_TO_EVEN")
local xcu = self:mult(xsq, x, "HALF_TO_EVEN")
local xsqsq = self:mult(xsq, xsq, "HALF_TO_EVEN")
local P = (126 * xsq + 52 * xcu + 5 * xsqsq)
--P = x + (P - (P % 84)) / 84
P = x + self:div(P, self._INTERNALS.EIGHTYFOUR, "HALF_TO_EVEN")
local Q = (140 * x + 90 * xsq + 20 * xcu + xsqsq)
--Q = ONE + (Q - (Q % 70)) / 70
Q = ONE + self:div(Q, self._INTERNALS.SEVENTY, "HALF_TO_EVEN")
--print(P, Q)
local r = 144269504 * self:div(P, Q, "HALF_TO_EVEN")
--local r = P * ONE
--r = 144269504 * ((r - (r % Q)) / Q)
return self:roundAt(r, 8, "HALF_TO_EVEN") / 1e8
end
local abs = math.abs
local sign = math.sign
if not sign then
sign = function(x)
return x > 0 and 1 or x < 0 and -1 or 0
end
end
-- there are multiple places which a rounding policy can be applied, which may cause disparity between any one choice
-- fractional exponential/logarithm approximations use HALF_TO_EVEN under the hood for unbiased rounding
return {
-- m * 2^raw
-- if m is nil, this is the power of two function
ldexp = function(self, m, raw, policy, ignoreOverflow)
if not ignoreOverflow then
ignoreOverflow = self.class.static.IGN_OVF
end
self.class.static.assert_int("raw", raw)
if m == 0 then
return 0
end
local exp1 = raw % self.RADIX_RHS_VAL
local exp0 = (raw - exp1) / self.RADIX_RHS_VAL
local result = 0
if exp0 < -24 then
return 0
elseif exp0 < 0 then
result = self:div(self.RADIX_RHS_VAL, 2^(-exp0) * self.RADIX_RHS_VAL, policy)
else
result = 2^exp0 * self.RADIX_RHS_VAL
end
if exp1 ~= 0 then
result = self:mult(result, pade_exp(self, exp1), policy, true)
end
if m ~= nil then
result = self:mult(m, result, policy, true)
end
if not ignoreOverflow and self:chk_overflow(result) then
error("FixedPoint: OVERFLOW (exponentiation/ldexp). m: " .. self:toString(m or self.RADIX_RHS_VAL) .. " exp: " .. self:toString(raw))
end
return result
end,
-- binary logarithm
lg = function(self, raw)
self.class.static.assert_int("raw", raw)
local ONE = self.RADIX_RHS_VAL
local HALF = self.CONSTANT.HALF
if raw == self.CONSTANT.E then
return self._INTERNALS.RECIP_LN2
end
local result = 0
if raw < 0 then
return 0/0
elseif raw == 0 then
return -math.huge
elseif raw == ONE then
return 0
elseif raw < ONE then
while raw <= HALF do
result = result - 1
raw = raw * 2
end
result = result * ONE
if raw == ONE then
return result
else
return result + pade_lg(self, raw)
end
end
local POWER_LOOKUP = self.LOOKUP.POWERS_OF_TWO_SCALED_ONE
local rawrepl0 = ONE
local rawrepl1 = POWER_LOOKUP[3]
while raw >= rawrepl1 do
result = result + 3
rawrepl0 = rawrepl1
rawrepl1 = POWER_LOOKUP[result + 3]
end
rawrepl1 = POWER_LOOKUP[result + 1]
while raw >= rawrepl1 do
result = result + 1
rawrepl0 = rawrepl1
rawrepl1 = POWER_LOOKUP[result + 1]
end
result = result * ONE
if raw == rawrepl0 then
return result
end
local rawreplratio = self:div(raw, rawrepl0, "HALF_TO_EVEN")
return result + pade_lg(self, rawreplratio)
end,
-- given a floating point value, this returns two values m, e such that fix:ldexp(m, e) is about equal to raw
-- similar to binary log, but neglects use of any pade approximant
frexp = function(self, raw)
self.class.static.assert_int("raw", raw)
local ONE = self.RADIX_RHS_VAL
local absraw = raw >= 0 and raw or -raw
if raw == 0 then
return 0, 0
elseif raw ~= raw then
return 0/0, -ONE
elseif absraw == math.huge then
return raw, -ONE
end
local HALF = self.CONSTANT.HALF
if raw == self.CONSTANT.E then
return self._INTERNALS.RECIP_LN2
end
local result = 0
if absraw < ONE then
while absraw <= HALF do
result = result - 1
absraw = absraw * 2
end
result = result * ONE
return sign(raw) * absraw, result
end
local POWER_LOOKUP = self.LOOKUP.POWERS_OF_TWO_SCALED_ONE
local rawrepl0 = ONE
local rawrepl1 = POWER_LOOKUP[3]
while absraw >= rawrepl1 do
result = result + 3
rawrepl0 = rawrepl1
rawrepl1 = POWER_LOOKUP[result + 3]
end
rawrepl1 = POWER_LOOKUP[result + 1]
while absraw >= rawrepl1 do
result = result + 1
rawrepl0 = rawrepl1
rawrepl1 = POWER_LOOKUP[result + 1]
end
result = result * ONE
if absraw == rawrepl0 then
return ONE, result
end
local rawreplratio = self:div(rawrepl1, raw, "HALF_TO_EVEN")
return rawreplratio, result + 1
end,
-- generic exponential/power function
-- i compute a^b = 2^(lg(a)*b), where lg is log base 2
pow = function(self, raw1, raw2, policy, ignoreOverflow)
if ignoreOverflow == nil then
ignoreOverflow = self.class.static.IGN_OVF
end
self.class.static.assert_int("raw1", raw1)
self.class.static.assert_int("raw2", raw2)
local ONE = self.RADIX_RHS_VAL
local exp1 = raw2 % ONE
local raw1_int = raw1 - (raw1 % ONE)
local result
if raw2 == 0 or raw1 == ONE then
return ONE
elseif raw1 == 0 then
return raw2 == raw2 and 0 or 0/0
elseif raw1 == -ONE then
return raw2 % 2 == 1 and -ONE or ONE
elseif raw1 < 0 and exp1 ~= 0 then
-- this corresponds to a negative base risen to a power with nonzero fractional part
return 0/0
elseif exp1 == 0 and raw1 == raw1_int then
-- integer power simplification
if raw2 < 0 then
result = self:div(ONE, ((raw1 / ONE)^(-raw2 / ONE)) * ONE, policy)
else
result = ((raw1 / ONE)^(raw2 / ONE)) * ONE
end
else
local TWO = self.CONSTANT.TWO
if raw1 == TWO or raw1 == -TWO then
result = self:ldexp(nil, raw2, policy, true)
else
result = self:ldexp(nil, self:mult(self:lg(raw1 < 0 and -raw1 or raw1), raw2, policy, true), policy, true)
end
if raw1 < 0 and exp1 == 0 and raw2 % TWO == ONE then
result = -result
end
end
if not ignoreOverflow and self:chk_overflow(result) then
error("FixedPoint: OVERFLOW (exponentiation/pow). op1: " .. self:toString(raw1) .. " op2: " .. self:toString(raw2))
end
return result
end,
-- log is ln if no base is provided, just as normal
log = function(self, raw, base, policy, ignoreOverflow)
if ignoreOverflow == nil then
ignoreOverflow = self.class.static.IGN_OVF
end
self.class.static.assert_int("raw", raw)
base = base or self.CONSTANT.E
local result = self:div(self:lg(raw), self:lg(base), policy, true)
if not ignoreOverflow and self:chk_overflow(result) then
error("FixedPoint: OVERFLOW (logarithm). op1: " .. self:toString(raw) .. " base: " .. self:toString(base))
end
return result
end,
log10 = function(self, raw, policy, ignoreOverflow)
return self:log(raw, self.CONSTANT.TEN, policy, ignoreOverflow)
end,
-- e^x, as normal
exp = function(self, raw, policy, ignoreOverflow)
if ignoreOverflow == nil then
ignoreOverflow = self.class.static.IGN_OVF
end
self.class.static.assert_int("raw", raw)
assert(raw < self._INTERNALS.EXP_OVF, "FixedPoint: chosen exponent may result in dangerous overflow. op1: " .. raw)
if raw < self:convertInt(-17) then
return 0
end
-- convert power of e to a power of two by multiplying the exponent by log_2(e)
return self:ldexp(nil, self:roundAt(1442695 * raw, 6, policy) / 1e6, policy, ignoreOverflow)
end,
}
|
local rp_languages = {}
local selectedLanguage = GetConVarString("gmod_language") -- Switch language by setting gmod_language to another language
function DarkRP.addLanguage(name, tbl)
local old = rp_languages[name] or {}
rp_languages[name] = tbl
-- Merge the language with the translations added by DarkRP.addPhrase
for k,v in pairs(old) do
if rp_languages[name][k] then continue end
rp_languages[name][k] = v
end
LANGUAGE = rp_languages[name] -- backwards compatibility
end
function DarkRP.addPhrase(lang, name, phrase)
rp_languages[lang] = rp_languages[lang] or {}
rp_languages[lang][name] = phrase
end
function DarkRP.getPhrase(name, ...)
local langTable = rp_languages[selectedLanguage] or rp_languages.en
return (langTable[name] or rp_languages.en[name]) and string.format(langTable[name] or rp_languages.en[name], ...) or nil
end
function DarkRP.getMissingPhrases(lang)
lang = lang or selectedLanguage
local res = {}
local format = "%s = \"%s\","
for k,v in pairs(rp_languages.en) do
if rp_languages[lang][k] then continue end
table.insert(res, string.format(format, k, v))
end
return #res == 0 and "No language strings missing!" or table.concat(res, "\n")
end
local function getMissingPhrases(ply, cmd, args)
if not args[1] then print("Please run the command with a language code e.g. darkrp_getphrases \"en\"") return end
local lang = rp_languages[args[1]]
if not lang then print("This language does not exist! Make sure the casing is right.")
print("Available languages:")
for k,v in pairs(rp_languages) do print(k) end
return
end
print(DarkRP.getMissingPhrases(args[1]))
end
if CLIENT then concommand.Add("darkrp_getphrases", getMissingPhrases) end
/*---------------------------------------------------------------------------
Chat command translating
---------------------------------------------------------------------------*/
local chatCmdDescriptions = {}
function DarkRP.addChatCommandsLanguage(lang, tbl)
chatCmdDescriptions[lang] = chatCmdDescriptions[lang] or {}
table.Merge(chatCmdDescriptions[lang], tbl)
end
function DarkRP.getChatCommandDescription(name)
local cmd = DarkRP.getChatCommand(name)
return chatCmdDescriptions[selectedLanguage] and chatCmdDescriptions[selectedLanguage][name] or
cmd and cmd.description or
nil
end
local function getMissingCmdTranslations()
local cmds = DarkRP.getSortedChatCommands()
-- No commands have been translated
if not chatCmdDescriptions[selectedLanguage] then return cmds end
-- Remove translated commands and maintain keys
local count = #cmds
for i = 1, count do
if chatCmdDescriptions[selectedLanguage][cmds[i].command] then
cmds[i] = nil
end
end
cmds = table.ClearKeys(cmds)
return cmds
end
local function printMissingChatTranslations()
local cmds = getMissingCmdTranslations()
local text = {}
local maxCmdLength = 0
for k,v in pairs(cmds) do maxCmdLength = math.Max(maxCmdLength, string.len(v.command)) end
for k,v in pairs(cmds) do
text[k] = string.format('["%s"]%s=\t"%s",', v.command, string.rep(' ', 4 + maxCmdLength - string.len(v.command)), v.description)
end
MsgC(Color(0, 255, 0), string.format("%s untranslated chat command descriptions!\n", #cmds))
text = table.concat(text, "\n\t")
SetClipboardText(text)
MsgC(Color(0, 255, 0), "text copied to clipboard!\n")
end
if CLIENT then concommand.Add("darkrp_translateChatCommands", printMissingChatTranslations) end
|
--[=[
Provides permissions for the game. See [BasePermissionProvider].
:::tip
Be sure to initialize the [PermissionServiceClient] on the client.
:::
```lua
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Nevermore"))
local PermissionProvider = require("PermissionProvider")
local PermissionProviderUtils = require("PermissionProviderUtils")
return PermissionProvider.new(PermissionProviderUtils.createGroupRankConfig({
groupId = 8668163;
minAdminRequiredRank = 250;
minCreatorRequiredRank = 254;
}))
```
@server
@class PermissionService
]=]
local require = require(script.Parent.loader).load(script)
local CreatorPermissionProvider = require("CreatorPermissionProvider")
local GroupPermissionProvider = require("GroupPermissionProvider")
local PermissionProviderConstants = require("PermissionProviderConstants")
local PermissionProviderUtils = require("PermissionProviderUtils")
local Promise = require("Promise")
local PermissionService = {}
--[=[
Initializes the service. Should be done via [ServiceBag].
@param _serviceBag ServiceBag
]=]
function PermissionService:Init(_serviceBag)
assert(not self._promise, "Already initialized")
assert(not self._provider, "Already have provider")
self._provider = nil
self._promise = Promise.new()
end
--[=[
Sets the provider from a config. See [PermissionProviderUtils.createGroupRankConfig]
and [PermissionProviderUtils.createSingleUserConfig].
@param config { type: string }
]=]
function PermissionService:SetProviderFromConfig(config)
assert(self._promise, "Not initialized")
assert(not self._provider, "Already have provider set")
if config.type == PermissionProviderConstants.GROUP_RANK_CONFIG_TYPE then
self._provider = GroupPermissionProvider.new(config)
elseif config.type == PermissionProviderConstants.SINGLE_USER_CONFIG_TYPE then
self._provider = CreatorPermissionProvider.new(config)
else
error("Bad provider")
end
end
--[=[
Starts the permission service. Should be done via [ServiceBag].
]=]
function PermissionService:Start()
if not self._provider then
self:SetProviderFromConfig(PermissionProviderUtils.createConfigFromGame())
end
self._provider:Start()
self._promise:Resolve(self._provider)
end
--[=[
Returns the permission provider
@return Promise<BasePermissionProvider>
]=]
function PermissionService:PromisePermissionProvider()
assert(self._promise, "Not initialized")
return self._promise
end
return PermissionService
|
local holdingup = false
local store = ""
local secondsRemaining = 0
function holdup_DisplayHelpText(str)
SetTextComponentFormat("STRING")
AddTextComponentString(str)
DisplayHelpTextFromStringLabel(0, 0, 1, -1)
end
function holdup_drawTxt(x,y ,width,height,scale, text, r,g,b,a, outline)
SetTextFont(0)
SetTextProportional(0)
SetTextScale(scale, scale)
SetTextColour(r, g, b, a)
SetTextDropShadow(0, 0, 0, 0,255)
SetTextEdge(1, 0, 0, 0, 255)
SetTextDropShadow()
if(outline)then
SetTextOutline()
end
SetTextEntry("STRING")
AddTextComponentString(text)
DrawText(x - width/2, y - height/2 + 0.005)
end
function drawTxt(text, font, centre, x, y, scale, r, g, b, a)
SetTextFont(font)
SetTextProportional(0)
SetTextScale(scale, scale)
SetTextColour(r, g, b, a)
SetTextDropShadow(0, 0, 0, 0, 255)
SetTextEdge(1, 0, 0, 0, 255)
SetTextDropShadow()
SetTextOutline()
SetTextCentre(centre)
SetTextEntry("STRING")
AddTextComponentString(text)
DrawText(x, y)
end
local stores = cfg.holdups
RegisterNetEvent('vrp_holdup:currentlyrobbing')
AddEventHandler('vrp_holdup:currentlyrobbing', function(robb)
holdingup = true
store = robb
secondsRemaining = cfg.seconds
end)
RegisterNetEvent('vrp_holdup:toofarlocal')
AddEventHandler('vrp_holdup:toofarlocal', function(robb)
holdingup = false
TriggerEvent("pNotify:SendNotification",{text = "Røveriet blev afbrudt, du modtog <b style='color:#ff0000'>intet</b>.",type = "warning",timeout = (3000),layout = "centerRight",queue = "global",animation = {open = "gta_effects_fade_in", close = "gta_effects_fade_out"}})
robbingName = ""
secondsRemaining = 0
end)
RegisterNetEvent('vrp_holdup:playerdiedlocal')
AddEventHandler('vrp_holdup:playerdiedlocal', function(robb)
holdingup = false
TriggerEvent("pNotify:SendNotification",{text = "<b style='color:#ff0000'>Du døde! Røveriet blev afbrudt</b>.",type = "warning",timeout = (3000),layout = "centerRight",queue = "global",animation = {open = "gta_effects_fade_in", close = "gta_effects_fade_out"}})
robbingName = ""
secondsRemaining = 0
end)
RegisterNetEvent('vrp_holdup:han:kan:ikke:fucking:rp')
AddEventHandler('vrp_holdup:han:kan:ikke:fucking:rp', function(robb)
holdingup = false
robbingName = ""
secondsRemaining = 0
end)
RegisterNetEvent('vrp_holdup:robberycomplete')
AddEventHandler('vrp_holdup:robberycomplete', function(reward)
holdingup = false
TriggerEvent("pNotify:SendNotification",{text = "Røveriet blev gennemført, du modtog <b style='color:#3db1ff'>"..reward.."</b> $",type = "success",timeout = (3000),layout = "centerRight",queue = "global",animation = {open = "gta_effects_fade_in", close = "gta_effects_fade_out"}})
store = ""
secondsRemaining = 0
end)
Citizen.CreateThread(function()
while true do
if holdingup then
Citizen.Wait(1000)
if(secondsRemaining > 0)then
secondsRemaining = secondsRemaining - 1
end
end
Citizen.Wait(0)
end
end)
Citizen.CreateThread(function()
while true do
local pos = GetEntityCoords(GetPlayerPed(-1), true)
for k,v in pairs(stores)do
local pos2 = v.position
if(Vdist(pos.x, pos.y, pos.z, pos2.x, pos2.y, pos2.z) < 15.0)then
if IsPlayerWantedLevelGreater(PlayerId(),0) or ArePlayerFlashingStarsAboutToDrop(PlayerId()) then
local wanted = GetPlayerWantedLevel(PlayerId())
Citizen.Wait(5000)
SetPlayerWantedLevel(PlayerId(), wanted, 0)
SetPlayerWantedLevelNow(PlayerId(), 0)
end
end
end
Citizen.Wait(0)
end
end)
if cfg.blips then -- blip settings
Citizen.CreateThread(function()
for k,v in pairs(stores)do
local ve = v.position
local blip = AddBlipForCoord(ve.x, ve.y, ve.z)
SetBlipSprite(blip, 52)
SetBlipScale(blip, 0.6)
SetBlipAsShortRange(blip, true)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString("Robbable Store")
EndTextCommandSetBlipName(blip)
end
end)
end
Citizen.CreateThread(function()
while true do
local pos = GetEntityCoords(GetPlayerPed(-1), true)
for k,v in pairs(stores)do
local pos2 = v.position
if(Vdist(pos.x, pos.y, pos.z, pos2.x, pos2.y, pos2.z) < 3.0) then
if not holdingup then
DrawMarker(27, v.position.x, v.position.y, v.position.z - 1.0, 0, 0, 0, 0, 0, 0, 1.0001, 1.0001, 1.5001, 1555, 0, 0,255, 0, 0, 0,0)
drawTxt('[~g~E~s~] for at røve butikken', 0, 1, 0.5, 0.8, 0.6, 255, 255, 255, 255)
if(Vdist(pos.x, pos.y, pos.z, pos2.x, pos2.y, pos2.z) < 2.0) then
if(IsControlJustReleased(1, 51))then
TriggerServerEvent('vrp_holdup:rob', k, pos.x, pos.y, pos.z)
end
end
end
end
end
if holdingup then
SetPlayerWantedLevel(PlayerId(), 2, 0)
SetPlayerWantedLevelNow(PlayerId(), 0)
holdup_drawTxt(0.69, 1.465, 1.0,1.0,0.4, "~r~" .. secondsRemaining .. "~w~ sekunder tilbage", 255, 255, 255, 255)
local pos2 = stores[store].position
local ped = GetPlayerPed(-1)
if IsEntityDead(ped) then
TriggerServerEvent('vrp_holdup:playerdied', store)
elseif(Vdist(pos.x, pos.y, pos.z, pos2.x, pos2.y, pos2.z) > 15)then
TriggerServerEvent('vrp_holdup:toofar', store)
end
end
Citizen.Wait(0)
end
end)
|
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by Yuk.
--- DateTime: 2021/7/12 1:25
---
---
require("Game.Libs.Util.class")
---@class Game:Object
local _M = singleton("Game")
---@param self Game
---@return Game
function _M.New(self)
--BaseObject = require("Game.Libs.Module.BaseObject")
print("hello word")
coroutine.start(self.CoInit, self)
end
function _M:CoInit()
end
return _M:New()
|
mapping = { foo = { bar = "baz" } }
|
local configs = require 'nvim_lsp/configs'
local util = require 'nvim_lsp/util'
configs.ccls = {
default_config = {
cmd = {"ccls"};
filetypes = {"c", "cpp", "objc", "objcpp"};
root_dir = util.root_pattern("compile_commands.json", "compile_flags.txt", ".git");
};
docs = {
package_json = "https://raw.githubusercontent.com/MaskRay/vscode-ccls/master/package.json";
description = [[
https://github.com/MaskRay/ccls/wiki
ccls relies on a [JSON compilation database](https://clang.llvm.org/docs/JSONCompilationDatabase.html) specified
as compile_commands.json or, for simpler projects, a compile_flags.txt.
For details on how to automatically generate one using CMake look [here](https://cmake.org/cmake/help/latest/variable/CMAKE_EXPORT_COMPILE_COMMANDS.html).
]];
default_config = {
root_dir = [[root_pattern("compile_commands.json", "compile_flags.txt", ".git")]];
};
};
}
-- vim:et ts=2 sw=2
|
function Auctionator.Search.GetEmptyResult(searchTerm, index)
-- Remove "" from exact searches so it sorts properly
local cleanSearchParameter = searchTerm:gsub("\"", "")
return {
itemKey = {
itemID = 1217, -- Valid item ID, "Unknown Reward", but unobtainable
itemLevel = index, -- Differentiate between different empty results
itemSuffix = 0,
battlePetSpeciesID = 0
},
itemName = Auctionator.Search.PrettifySearchString(searchTerm),
iconTexture = 0,
name = cleanSearchParameter,
totalQuantity = 0,
minPrice = 0,
containsOwnerItem = false,
}
end
|
术语:
mf == msg foward, 消息转发服务器。
user == msg foward的客户端,被服务器对象。客户端进程。服务器群的其中一个服务器进程。
cd == client driver,驱动,给user作为库使用,可以再这个基础快速写出客户端链接应用。
设计目的:
问题:一套服务器群,数量超过几台以上,互相之间直接socket通讯会带来以下问题:
配置繁琐,每条连接都要一个服务端的ip地址。
代码结构复杂:其中一个进程, 可能是server,可能也是client,对外通讯接口不一样。
连接网状拓扑,分析问题难度大。
解决方法:
服务器群都链接mf,mf作为消息转发中心出。
User的角度去看,User之间的链接概念类似tcp/ip链接,可靠传送。
User进程都有自己的id, 都注册到mf。
User进程可选用cd,也可以自己根据协议写一个客户端驱动。
缺点:通讯需要转发,不是最快的通讯方式。
不用第三方的消息队列服务的原因:
第三方的消息队列服务有activemq、rabbitmq、kafka 等。
不合适直接用的原因:
mf核心功能就是消息可靠转发、而不是消息队列。
mf功能少、学习成本底。
mf部署可以做得很简单。
转发消息用,不需要存库,mf可以更快。
mf user之间通讯的消息结构:
{
tcp包: len, tcp_pack.
tcp_pack:ctrl_len,ctrl_cmd, ctrl_pack,custom_pack.
--ctrl_len表示ctrl_cmd,ctrl_pack的总字节数。
--纯控制消息,就没有custom_pack了.
--custom_pack 用户自定义消息包,具体协议格式自定义,比如可以用protobuf。
分二层解析
2) user和user层:custom_pack --user 之间通讯的自定义协议
1) user和mf层: tcp_pack --user mf通讯协议,
tcp_pack 解析出 mf::MsgData
分层图:
user mf user
user和user层------------------- user和user层
user和mf层 --- user和mf层 -- user和mf层
}
mf 功能:
可以多个mf。高可用,无状态。状态改变都是来源客户端user.
注册服务器id
路由消息。
{
1对1,
1对组
}
可靠转发,连接失败才需要反馈给user。 (类似tcp连接那样理解)
广播断开user到all user
管理user信息: 组,id
client driver 功能:
连接服务器列表
负载均衡策略:发送轮询一个服务器使用
断线重连定时器
注册id
发送,接收
更新all user 状态
|
local consume = test.EventConsumer({
"init",
"hide",
"parent group",
"shown from rendering",
"draw",
"hide",
"remove",
})
function test.Run(done)
do
local BUILDER, PART = pac.PartTemplate("base_drawable")
PART.FriendlyName = "test"
PART.ClassName = "test"
PART.Icon = 'icon16/cut.png'
function PART:Initialize()
consume("init")
end
function PART:OnShow(from_rendering)
if from_rendering then
consume("shown from rendering")
end
end
function PART:OnDraw()
consume("draw")
self:Remove()
end
function PART:OnThink()
--consume("think")
end
function PART:OnHide()
consume("hide")
end
function PART:OnRemove()
consume("remove")
done()
end
function PART:OnParent(parent)
consume("parent " .. tostring(parent.ClassName))
end
function PART:OnUnparent()
consume("unparent")
end
pac.RegisterPart(PART)
end
local root = pac.CreatePart("group")
local part = root:CreatePart("test")
end
|
--[[
Name: init.lua
For: SantosRP
By: TalosLife
]]--
AddCSLuaFile "cl_init.lua"
AddCSLuaFile "shared.lua"
include "shared.lua"
function ENT:Initialize()
self:SetModel( "models/props_junk/gascan001a.mdl" )
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:SetTrigger( true )
self:PhysWake()
end
function ENT:StartTouch( eEnt )
if self.m_bTouched then return end
if not IsValid( eEnt ) or not eEnt:IsVehicle() or not eEnt.UID then return end
if eEnt:GetFuel() < eEnt:GetMaxFuel() then
eEnt:AddFuel( 1 )
eEnt:EmitSound( "ambient/water/water_spray1.wav", 70, 70 )
self.m_bTouched = true
self:Remove()
end
end
|
local cache = require "kong.tools.database_cache"
local responses = require "kong.tools.responses"
local utils = require "kong.tools.utils"
local _M = {}
function _M.execute(conf)
local consumer_id
if ngx.ctx.authenticated_entity then
consumer_id = ngx.ctx.authenticated_entity.consumer_id
else
return responses.send_HTTP_FORBIDDEN("Cannot identify the consumer, add an authentication plugin to use the ACL plugin")
end
-- Retrieve ACL
local acls = cache.get_or_set(cache.acls_key(consumer_id), function()
local results, err = dao.acls:find_by_keys({consumer_id = consumer_id})
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
return results
end)
if not acls then acls = {} end
local block
if utils.table_size(conf.blacklist) > 0 and utils.table_size(acls) > 0 then
for _, v in ipairs(acls) do
if utils.table_contains(conf.blacklist, v.group) then
block = true
break
end
end
end
if utils.table_size(conf.whitelist) > 0 then
if utils.table_size(acls) == 0 then
block = true
else
local contains
for _, v in ipairs(acls) do
if utils.table_contains(conf.whitelist, v.group) then
contains = true
break
end
end
if not contains then block = true end
end
end
if block then
ngx.ctx.stop_phases = true -- interrupt other phases of this request
return responses.send_HTTP_FORBIDDEN("You cannot consume this service")
end
end
return _M
|
enemyCollision = {}
function enemyCollision:isCollidingWithFireboy(enemy)
local width = fireboy.boxWidth * fireboy.scale
local height = fireboy.boxHeight * fireboy.scale
local fireboyPoints = {
{ x=(fireboy.x-width/2), y=(fireboy.y-height) }, -- Upper left
{ x=(fireboy.x+width/2), y=(fireboy.y-height) }, -- Upper right
{ x=(fireboy.x-width/2), y=(fireboy.y) }, -- Bottom left
{ x=(fireboy.x+width/2), y=(fireboy.y) } -- Bottom right
}
for i, point in ipairs(fireboyPoints) do
if gamemath:distance(enemy.x, enemy.y, point.x, point.y) < base_enemy.radius then
return true
end
end
return false
end
-- function enemyCollision:collide(enemy1, enemy2)
-- local xdist, ydist = enemy2.x - enemy1.x, enemy2.y - enemy1.y
-- local distance = math.sqrt(xdist*xdist + ydist*ydist)
-- if distance <= 2*base_enemy.radius then
-- local midX, midY = enemy1.x + xdist/2, enemy1.y + ydist/2
-- local theta2 = math.atan(ydist, xdist)
-- print(theta2)
-- local theta1 = theta2 + math.pi
-- enemy1.x = midX + base_enemy.radius * math.cos(theta1)
-- enemy1.y = midY + base_enemy.radius * math.sin(theta1)
-- enemy2.x = midX + base_enemy.radius * math.cos(theta2)
-- enemy2.y = midY + base_enemy.radius * math.sin(theta2)
-- end
-- end
|
#!/usr/bin/env luajit
local xmlua = require("xmlua")
local path = arg[1]
local file = assert(io.open(path))
local parser = xmlua.HTMLSAXParser.new()
parser.start_document = function()
print("Start document")
end
parser.ignorable_whitespace = function(whitespaces)
print("Ignorable whitespaces: " .. "\"" .. whitespaces .. "\"")
print("Ignorable whitespaces length: " .. #whitespaces)
end
parser.processing_instruction = function(target, data)
print("Processing instruction target: " .. target)
print("Processing instruction data: " .. data)
end
parser.comment = function(comment)
print("Comment: " .. comment)
end
parser.cdata_block = function(cdata_block)
print("CDATA block: " .. cdata_block)
end
parser.start_element = function(name, attributes)
print("Start element: " .. name)
if #attributes > 0 then
print(" Attributes:")
for i, attribute in pairs(attributes) do
print(" " .. attribute.name .. ": " .. (attribute.value or ""))
end
end
end
parser.end_element = function(name)
print("End element: " .. name)
end
parser.text = function(text)
print("Text: <" .. text .. ">")
end
parser.error = function(err)
print("Error: " .. path .. ":" .. err.line .. ": " .. err.message)
end
parser.end_document = function()
print("End document")
end
while true do
local line = file:read()
if not line then
parser:finish()
break
end
parser:parse(line)
end
file:close()
|
love.conf = function(t)
t.gammacorrect = true
t.title, t.identity = "Tover Drank", "Minimal"
t.modules.joystick = false
t.modules.physics = false
t.window.width = 720
t.window.height = 450
t.window.vsync = false
t.window.resizable = true
t.version = "11.3"
t.console = true
end
|
local utils = require("utils")
local map = utils.map
map("n", "<Leader>h", ":noh<CR>")
map("n", "<Leader><Leader>", "<C-^>")
-- Switching windows
-- map("n", "<C-j>", "<C-w>j")
-- map("n", "<C-k>", "<C-w>k")
-- map("n", "<C-l>", "<C-w>l")
-- map("n", "<C-h>", "<C-w>h")
-- Resizing windows
map("n", "<C-Up>", ":res +2<CR>")
map("n", "<C-Down>", ":res -2<CR>")
map("n", "<C-Right>", ":vert res +2<CR>")
map("n", "<C-Left>", ":vert res -2<CR>")
map("n", "<Leader>cc", function()
local colorcolumn = vim.wo.colorcolumn
vim.wo.colorcolumn = string.len(colorcolumn) == 0 and "80" or ""
end)
map("n", "<C-n>", ":cn<CR>")
map("n", "<C-p>", ":cp<CR>")
-- Mappings for plugins
local M = {}
M.easy_align = function()
map("x", "ga", "<Plug>(EasyAlign)")
end
M.lsp = function()
map("n", "K", vim.lsp.buf.hover)
map("n", "gs", vim.lsp.buf.signature_help)
map("n", "gd", vim.lsp.buf.definition)
map("n", "gD", vim.lsp.buf.declaration)
map("n", "gx", vim.lsp.buf.signature_help)
map("n", "<Leader>rn", vim.lsp.buf.rename)
map("n", "<Leader>ca", vim.lsp.buf.code_action)
map("n", "[g", vim.diagnostic.goto_next)
map("n", "]g", vim.diagnostic.goto_prev)
end
M.null_ls = function()
map("n", "<Leader>x", vim.lsp.buf.formatting, { buffer = true })
end
M.nvimtree = function()
map("n", "<Leader>e", ":NvimTreeToggle<CR>")
end
M.fzf = function()
map("n", "<Leader>ff", function()
require("fzf-lua").files()
end)
map("n", "<Leader>lg", function()
require("fzf-lua").live_grep()
end)
map("n", "<Leader>df", function()
require("fzf-lua").files({ cwd = "$HOME/.dotfiles" })
end)
map("n", "<Leader>nv", function()
require("fzf-lua").files({ cwd = "$HOME/.config/nvim" })
end)
end
M.telescope = function()
map("n", "<Leader>ff", function()
require("telescope.builtin").find_files { hidden = true }
end)
map("n", "<Leader>lg", function()
require("telescope.builtin").live_grep { hidden = true }
end)
map("n", "<Leader>df", function()
require("telescope.builtin").find_files {
prompt_title = "Search Dotfiles",
cwd = "$HOME/.dotfiles",
hidden = true
}
end)
map("n", "<Leader>nv", function()
require("telescope.builtin").find_files {
prompt_title = "Search Nvim Config",
cwd = "$HOME/.config/nvim",
hidden = true
}
end)
end
return M
|
-------------------------------------------------------------------------------
--- AUTHOR: Nostrademous
--- GITHUB REPO: https://github.com/Nostrademous/Dota2-FullOverwrite
-------------------------------------------------------------------------------
--[[
function ItemUsageThink()
return
end
function AbilityUsageThink()
return
end
function CourierUsageThink()
return
end
function BuybackUsageThink()
return
end
function AbilityLevelUpThink()
return
end
--]]
|
local FOLDER_NAME, private = ...
local Chronicles = private.Core
local Locale = LibStub("AceLocale-3.0"):GetLocale(private.addon_name)
Chronicles.UI.EventDescription = {}
Chronicles.UI.EventDescription.CurrentPage = nil
Chronicles.UI.EventDescription.CurrentEvent = nil
Chronicles.UI.EventDescription.CurrentFactionsCharactersResults = {}
function Chronicles.UI.EventDescription:Refresh()
--if (self.CurrentEvent ~= nil and not Chronicles.DB:GetGroupStatus(self.CurrentEvent.source)) then
self.CurrentEvent = nil
self.CurrentPage = nil
self.CurrentFactionsCharactersResults = {}
EventTitle:SetText("")
EventDescriptionHTML:SetText("")
EventDescriptionBounds:SetText("")
EventDescriptionPrevious:Hide()
EventDescriptionNext:Hide()
EventDescriptionPager:Hide()
EventDescription.FactionsButton:Hide()
EventDescription.CharactersButton:Hide()
--end
end
function Chronicles.UI.EventDescription:DrawEventDescription(event)
-- DEFAULT_CHAT_FRAME:AddMessage("-- Call to DrawEventDescription " .. event.label)
self.CurrentEvent = event
self.CurrentPage = 1
self.CurrentFactionsCharactersResults = {}
EventDescription.FactionsButton:Hide()
EventDescription.CharactersButton:Hide()
EventTitle:SetText(adjustTextLength(event.label, 45, EventTitleContainer))
EventDescriptionHTML:SetText(event.description[1])
local eventDates = Locale["start"] .. " : " .. event.yearStart .. " " .. Locale["end"] .. " : " .. event.yearEnd
if (event.yearStart == event.yearEnd) then
eventDates = Locale["year"] .. " : " .. event.yearStart
end
EventDescriptionBounds:SetText(eventDates)
self:SetDescriptionPager(1, tablelength(event.description))
-- DEFAULT_CHAT_FRAME:AddMessage("-- Display description " .. event.description[1])
if (event.factions ~= nil and tablelength(Chronicles.DB:FindFactions(event.factions)) > 0) then
EventDescription.FactionsButton:Show()
end
if (event.characters ~= nil and tablelength(Chronicles.DB:FindCharacters(event.characters)) > 0) then
EventDescription.CharactersButton:Show()
end
end
function Chronicles.UI.EventDescription:ChangeEventDescriptionPage(page)
-- DEFAULT_CHAT_FRAME:AddMessage("-- ChangeEventDescriptionPage " .. page)
local event = self.CurrentEvent
if (event ~= nil and event.description ~= nil) then
local numberOfPages = tablelength(event.description)
if (page < 1) then
page = 1
end
if (page > numberOfPages) then
page = numberOfPages
end
if (event.description[page] ~= nil) then
self.CurrentPage = page
EventDescriptionHTML:SetText(event.description[page])
self:SetDescriptionPager(page, numberOfPages)
end
end
end
function Chronicles.UI.EventDescription:SetDescriptionPager(currentPage, maxPage)
EventDescriptionPrevious:Hide()
EventDescriptionNext:Hide()
EventDescriptionPager:Hide()
if (maxPage ~= 1) then
local text = "" .. currentPage .. " / " .. maxPage
EventDescriptionPager:SetText(text)
if (currentPage <= 1) then
EventDescriptionPrevious:Disable()
else
EventDescriptionPrevious:Enable()
end
if (currentPage >= maxPage) then
EventDescriptionNext:Disable()
else
EventDescriptionNext:Enable()
end
EventDescriptionPager:Show()
EventDescriptionPrevious:Show()
EventDescriptionNext:Show()
end
end
------------------------------------------------------------------------------------------
-- Description Paging --------------------------------------------------------------------
------------------------------------------------------------------------------------------
function EventDescriptionPreviousButton_OnClick(self)
Chronicles.UI.EventDescription:ChangeEventDescriptionPage(Chronicles.UI.EventDescription.CurrentPage - 1)
end
function SetPreviousButtonText()
EventDescriptionPrevious:SetText("<")
end
function EventDescriptionNextButton_OnClick(self)
Chronicles.UI.EventDescription:ChangeEventDescriptionPage(Chronicles.UI.EventDescription.CurrentPage + 1)
end
function SetNextButtonText()
EventDescriptionNext:SetText(">")
end
function EventFactionsButton_OnClick(self)
-- DEFAULT_CHAT_FRAME:AddMessage("-- EventFactionsButton_OnClick ")
local currentEvent = Chronicles.UI.EventDescription.CurrentEvent
if (currentEvent ~= nil and currentEvent.factions and tablelength(currentEvent.factions) > 0) then
local factionsList = Chronicles.DB:FindFactions(currentEvent.factions)
Chronicles.UI.EventDescription.CurrentFactionsCharactersResults = MapFactionsToItems(factionsList)
EventDescription_FactionsCharactersResults(EventDescription.FactionsCharactersResults, Locale["Factions_List"])
EventDescription.FactionsCharactersResults:Show()
else
EventDescription.FactionsCharactersResults:Hide()
end
end
function MapFactionsToItems(factions)
local maxDescriptionLength = 75
local results = {}
for index, faction in ipairs(factions) do
local item = {
name = faction.name,
description = ""
}
if (not containsHTML(faction.description)) then
item.description = faction.description:sub(0, maxDescriptionLength)
end
-- DEFAULT_CHAT_FRAME:AddMessage("-- MapFactionsToItems " .. item.name .. " " .. item.description)
table.insert(results, item)
end
return results
end
function EventFactionsButton_OnLoad(self)
self.label:SetText(Locale["Factions_List"])
end
function EventCharactersButton_OnClick(self)
-- DEFAULT_CHAT_FRAME:AddMessage("-- EventCharactersButton_OnClick ")
-- local charactersList = Chronicles.DB:FindCharacters(event.characters)
local currentEvent = Chronicles.UI.EventDescription.CurrentEvent
if (currentEvent ~= nil and currentEvent.characters and tablelength(currentEvent.characters) > 0) then
local charactersList = Chronicles.DB:FindCharacters(currentEvent.characters)
Chronicles.UI.EventDescription.CurrentFactionsCharactersResults = MapCharactersToItems(charactersList)
EventDescription_FactionsCharactersResults(
EventDescription.FactionsCharactersResults,
Locale["Characters_List"]
)
EventDescription.FactionsCharactersResults:Show()
else
EventDescription.FactionsCharactersResults:Hide()
end
end
function MapCharactersToItems(characters)
local maxDescriptionLength = 75
local results = {}
for index, character in ipairs(characters) do
local item = {
name = character.name,
description = ""
}
if (not containsHTML(character.biography)) then
item.description = character.description:sub(0, maxDescriptionLength)
end
-- DEFAULT_CHAT_FRAME:AddMessage("-- MapCharactersToItems " .. item.name .. " " .. item.description)
table.insert(results, item)
end
return results
end
function EventCharactersButton_OnLoad(self)
self.label:SetText(Locale["Characters_List"])
end
function EventDescriptionButton_OnLoad(self)
local scrollFrame = EventDescription.FactionsCharactersResults.scrollFrame
scrollFrame.update = EventDescription_FactionsCharactersResults
scrollFrame.scrollBar.doNotHide = true
HybridScrollFrame_CreateButtons(scrollFrame, "FullSearchResultsButton", 5, 0)
end
function EventDescription_FactionsCharactersResults(self, title)
local numResults = tablelength(Chronicles.UI.EventDescription.CurrentFactionsCharactersResults)
local scrollFrame = EventDescription.FactionsCharactersResults.scrollFrame
local offset = HybridScrollFrame_GetOffset(scrollFrame)
local results = scrollFrame.buttons
local result, index
for i = 1, #results do
result = results[i]
index = offset + i
if (index <= numResults) then
local item = Chronicles.UI.EventDescription.CurrentFactionsCharactersResults[index]
result.name:SetText(item.name)
-- result.icon:SetTexture(icon)
result.description:SetText(item.description)
result:Show()
else
result:Hide()
end
end
local totalHeight = numResults * 49
HybridScrollFrame_Update(scrollFrame, totalHeight, 270)
if (title ~= nil) then
EventDescription.FactionsCharactersResults.titleText:SetText(title)
else
EventDescription.FactionsCharactersResults.titleText:SetText("")
end
end
|
local kernel = {}
kernel.language = "glsl"
kernel.category = "filter"
kernel.name = "iris"
-- IMPORTANT: If you move the position while keeping the unitOpenness
-- constant, the actual radius in pixel WON'T stay constant because
-- the diagonal distance from the center to the most distant corner
-- of the DisplayObject ISN'T constant.
kernel.uniformData =
{
{
name = "center",
default = { 0.5, 0.5 },
min = { 0, 0 },
max = { 1, 1 },
type="vec2",
index = 0, -- u_UserData0
},
{
name = "aperture",
default = 0,
min = 0,
max = 1,
type="scalar",
index = 1, -- u_UserData1
},
{
name = "aspectRatio",
default = 1,
min = 0,
max = 99999,
type="scalar",
index = 2, -- u_UserData2
},
{
name = "smoothness",
default = 0,
min = 0,
max = 1,
type="scalar",
index = 3, -- u_UserData3
},
}
kernel.vertex =
[[
uniform P_UV vec2 u_UserData0; // center
uniform P_UV float u_UserData1; // unitOpenness
uniform P_UV float u_UserData2; // aspectRatio
uniform P_UV float u_UserData3; // unitSmoothness
varying P_UV float feathering_lower_edge;
varying P_UV float feathering_upper_edge;
P_POSITION vec2 VertexKernel( P_POSITION vec2 position )
{
P_UV vec2 center = u_UserData0;
// We need the max() because we want to determine the
// maximum distance to cover.
P_UV float xMax = max( center.x,
( 1.0 - center.x ) );
P_UV float yMax = max( center.y,
( 1.0 - center.y ) );
// unitOpenness is [ 0.0 .. 1.0 ].
//
// 0: Closed iris (complete coverage / no radius).
// 1: Open iris (no coverage / full radius).
P_UV float unitOpenness = u_UserData1;
// aspectRatio = ( object.width / object.height )
P_UV float aspectRatio = u_UserData2;
// Diagonal length.
//
// maximum_distance_to_cover = sqrt( a^2 + b^2 );
P_UV float a = ( xMax * aspectRatio );
a = ( a * a );
P_UV float b = yMax;
b = ( b * b );
P_UV float unitSmoothness = u_UserData3;
// "0.5" : This is an arbitrary constant. This must be a constant so
// that the thickness of the smooth border is constant.
P_UV float feathering_edge_thickness = ( 0.5 * unitSmoothness );
// Add the smooth border thickness so we can move it completely out of view
// when necessary.
P_UV float maximum_distance_to_cover = ( sqrt( a + b ) + feathering_edge_thickness );
// This is the "solid" edge.
feathering_upper_edge = ( unitOpenness * maximum_distance_to_cover );
// This is the "transparent" edge.
feathering_lower_edge = ( feathering_upper_edge - feathering_edge_thickness );
return position;
}
]]
kernel.fragment =
[[
uniform P_UV vec2 u_UserData0; // center
uniform P_UV float u_UserData1; // unitOpenness
uniform P_UV float u_UserData2; // aspectRatio
uniform P_UV float u_UserData3; // unitSmoothness
varying P_UV float feathering_lower_edge;
varying P_UV float feathering_upper_edge;
P_COLOR vec4 FragmentKernel( P_UV vec2 texCoord )
{
// aspectRatio = ( object.width / object.height )
P_UV float aspectRatio = u_UserData2;
P_UV vec2 center = vec2( ( u_UserData0.x * aspectRatio ),
u_UserData0.y );
// Current fragment position in texture-space.
//WE *SHOULD* BE ABLE TO MOVE THIS TO THE VERTEX SHADER!!!
P_UV vec2 pos = vec2( ( texCoord.x * aspectRatio ),
texCoord.y );
// Distance from the center to the current fragment.
P_UV float dist = distance( pos,
center );
// Get the colors to modulate.
// We want to use texCoord instead of "pos" here because
// we want to sample the texture at its unmodified coordinates.
// "pos" is only useful to determine the transparency.
P_COLOR vec4 color = ( texture2D( u_FillSampler0, texCoord ) * v_ColorScale );
#if 0 // For debugging ONLY.
// Blend with a plain color only.
// Diregard the texture color sampled above.
color = v_ColorScale;
#elif 0 // For debugging ONLY.
// Use debug colors only.
if( dist <= feathering_lower_edge )
{
return vec4( 1.0, 0.0, 0.0, 1.0 );
}
else if( dist >= feathering_upper_edge )
{
return vec4( 0.0, 1.0, 0.0, 1.0 );
}
else // if( ( dist > feathering_lower_edge ) && ( dist < feathering_upper_edge ) )
{
return vec4( 0.0, 0.0, 1.0, 1.0 );
}
#endif
return ( color * smoothstep( feathering_lower_edge,
feathering_upper_edge,
dist ) );
}
]]
return kernel
|
local Runner = require("tests.indent.common").Runner
--local XFAIL = require("tests.indent.common").XFAIL
local run = Runner:new(it, "tests/indent/graphql", {
tabstop = 2,
shiftwidth = 2,
softtabstop = 0,
expandtab = true,
})
describe("indent Lua:", function()
describe("whole file:", function()
run:whole_file(".", {
expected_failures = {},
})
end)
describe("new line:", function() end)
end)
|
local utils = {}
utils.unpack = table.unpack or unpack
if _VERSION:find("5.1") then
utils.loadstring = loadstring
else
utils.loadstring = load
end
local function flatten_into(array, res)
for i = 1, #array do
if type(array[i]) == "table" then
flatten_into(array[i], res)
else
res[#res + 1] = array[i]
end
end
return res
end
function utils.flatten(array)
return flatten_into(array, {})
end
function utils.array_to_set(array)
local set = {}
for i = 1, #array do
set[array[i]] = true
end
return set
end
return utils
|
--[[-------------------------------------------------------------------]]--[[
Copyright wiltOS Technologies LLC, 2020
Contact: www.wiltostech.com
----------------------------------------]]--
wOS = wOS or {}
wOS.ALCS = wOS.ALCS or {}
wOS.ALCS.Skills = wOS.ALCS.Skills or {}
wOS.ALCS.Skills.Camera = wOS.ALCS.Skills.Camera or {}
local w,h = ScrW(), ScrH()
local pi = math.pi
local upButton = Material( "wos/crafting/gui/up.png", "unlitgeneric" )
local downButton = Material( "wos/crafting/gui/down.png", "unlitgeneric" )
local leftButton = Material( "wos/crafting/gui/left.png", "unlitgeneric" )
local rightButton = Material( "wos/crafting/gui/right.png", "unlitgeneric" )
local boxTop = Material( "phoenix_storms/metalset_1-2", "unlitgeneric" )
local wireFrame = Material( "trails/plasma" )
local CombatBlock = Material( "wos/advswl/combat_holocron.png", "unlitgeneric" )
local centerpoint = wOS.ALCS.Config.Crafting.CraftingCamLocation
local color_unselected = Color( 0, 0, 0, 100 )
local grad = Material( "gui/gradient_up" )
wOS.ALCS.Skills.CubeModels = wOS.ALCS.Skills.CubeModels or {}
wOS.ALCS.Skills.MenuLibrary = wOS.ALCS.Skills.MenuLibrary or {}
wOS.ALCS.Skills.Camera[ "Combat-Overview" ] = { origin = centerpoint - Vector( 45, -35, -30 ), angles = Angle( 0, 90.501, 0.000 ) }
wOS.ALCS.Skills.MenuLibrary[ "Combat-Overview" ] = function()
local leftpane = tduiw.Create()
leftpane.SizeX = 8
leftpane.SizeY = 35
leftpane.ShouldAcceptInputs = true
leftpane.Renders = function( pan )
local ww, hh = pan.SizeX, pan.SizeY
local x = -30
local y = -hh*0.4
local bh = hh/7
pan:Line( 0, -hh/2, x + ww, y + bh/2 )
local lst = 0
image = wOS.ALCS.Runes[ "e" ]
pan:Mat( image, x, y, ww, bh )
local _jp, _pr, _hov = pan:Button( "", "wOS.TitleFont", x, y, ww, bh, color_white, color_white )
if _hov then
local speed = 0.1
if not pan.SlideTimes then
pan.SlideTimes = CurTime() + speed
surface.PlaySound( "wos/alcs/ui_slideout.wav" )
end
if pan.LastButt != lst then
surface.PlaySound( "wos/alcs/ui_rollover.wav" )
pan.LastButt = lst
end
local rat = math.Clamp( pan.SlideTimes - CurTime(), 0, speed )/speed
pan:Rect( x, y, ww*-3*( 1 - rat ), bh, Color( 10, 10, 10, 255 ), color_white )
pan:Text( "VIEW EXECUTIONS", "wOS.TitleFont", x + ww*-2.7*( 1 - rat ), y + bh/2, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER )
pan.LastHover = CurTime() + 0.01
end
if _jp then
wOS.ALCS.Skills:ChangeCamFocus( "Combat-SelectExec" )
end
if pan.SlideTimes and pan.LastHover < CurTime() then
pan.SlideTimes = nil
pan.LastButt = nil
end
end
leftpane:SetUIScale( 10 )
leftpane.Scaling = 0.025
leftpane.CamPos = wOS.ALCS.Skills.Camera[ wOS.ALCS.Skills.CamFocus ].origin + Vector( 0, 20, -2 )
leftpane.CamAng = wOS.ALCS.Skills.Camera[ wOS.ALCS.Skills.CamFocus ].angles + Angle( 0, 30, 0 )
table.insert( wOS.ALCS.Skills.Menu.VGUI, leftpane )
local frontpane = tduiw.Create()
frontpane.SizeX = 8
frontpane.SizeY = 35
frontpane.ShouldAcceptInputs = true
frontpane.Renders = function( pan )
local ww, hh = pan.SizeX, pan.SizeY
local x = 0 - ww/2
local y = 10
local bh = hh/7
local level = LocalPlayer():GetNW2Int( "wOS.ProficiencyLevel", 0 )
local xp = LocalPlayer():GetNW2Int( "wOS.ProficiencyExperience", 0 )
pan:Text( "PROFICIENCY LEVEL " .. level, "wOS.CraftDescriptions", 0, -hh*1.1, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER )
pan:Text( xp .. " EXPERIENCE POINTS", "wOS.TitleFont", 0, -hh, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER )
pan:Line( 0, -3, 3, 3 )
pan:Line( 3, 3, 0, 10 )
local lst = 0
image = wOS.ALCS.Runes[ "x" ]
pan:Mat( image, x, y, ww, bh )
local _jp, _pr, _hov = pan:Button( "", "wOS.TitleFont", x, y, ww, bh, color_white, color_white )
if _jp then
wOS.ALCS.Skills:ChangeCamFocus( "Overview" )
elseif _hov then
local speed = 0.1
if not pan.SlideTimes then
pan.SlideTimes = CurTime() + speed
surface.PlaySound( "wos/alcs/ui_slideout.wav" )
end
if pan.LastButt != lst then
surface.PlaySound( "wos/alcs/ui_rollover.wav" )
pan.LastButt = lst
end
local rat = math.Clamp( pan.SlideTimes - CurTime(), 0, speed )/speed
pan:Rect( x + ww, y, ww*( 3 - 3*rat ), bh, Color( 10, 10, 10, 255 ), color_white )
pan:Text( "GO BACK", "wOS.TitleFont", x + ww*2.1*( 1 - rat ), y + bh/2, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER )
pan.LastHover = CurTime() + 0.01
end
lst = lst + 1
local _jp, _pr, _hov = pan:Button( "", "wOS.TitleFont", -hh*0.7/2, -hh*0.7, hh*0.7, hh*0.7, Color( 0, 0, 0, 0 ), Color( 0, 0, 0, 0 ) )
if _hov then
local speed = 0.1
if not pan.SlideTimes then
pan.SlideTimes = CurTime() + speed
end
if pan.LastButt != lst then
surface.PlaySound( "wos/alcs/ui_rollover.wav" )
pan.LastButt = lst
end
local rat = math.Clamp( pan.SlideTimes - CurTime(), 0, speed )/speed
pan:Text( "USE THE RUNES TO PERFECT YOUR FIGHTING STYLE", "wOS.CraftDescriptions", 0, y + bh*2*( 1.5 + rat ), color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER )
pan.LastHover = CurTime() + 0.01
end
lst = lst + 1
if pan.SlideTimes and pan.LastHover < CurTime() then
pan.SlideTimes = nil
pan.LastButt = nil
end
end
frontpane.PostRenders = function( pan )
wOS.ALCS.Skills:CreateCubeMat( pan.CamPos, CombatBlock, nil, 6 )
end
frontpane:SetUIScale( 10 )
frontpane.Scaling = 0.025
frontpane.CamPos = wOS.ALCS.Skills.Camera[ wOS.ALCS.Skills.CamFocus ].origin + Vector( 0, 20, -2 )
frontpane.CamAng = wOS.ALCS.Skills.Camera[ wOS.ALCS.Skills.CamFocus ].angles + Angle( 0, 0, 0 )
table.insert( wOS.ALCS.Skills.Menu.VGUI, frontpane )
local rightpane = tduiw.Create()
rightpane.SizeX = 8
rightpane.SizeY = 35
rightpane.ShouldAcceptInputs = true
rightpane.Renders = function( pan )
local ww, hh = pan.SizeX, pan.SizeY
local x = 20
local y = -hh*0.3
local bh = hh/7
pan:Line( x/2, y - hh*0.15, x, y + bh/2 )
local lst = 0
image = wOS.ALCS.Runes[ "a" ]
pan:Mat( image, x, y, ww, bh )
local _jp, _pr, _hov = pan:Button( "", "wOS.TitleFont", x, y, ww, bh, color_white, color_white )
if _jp then
wOS.ALCS.Skills:ChangeCamFocus( "Combat-Preferences" )
elseif _hov then
local speed = 0.1
if not pan.SlideTimes then
pan.SlideTimes = CurTime() + speed
surface.PlaySound( "wos/alcs/ui_slideout.wav" )
end
if pan.LastButt != lst then
surface.PlaySound( "wos/alcs/ui_rollover.wav" )
pan.LastButt = lst
end
local rat = math.Clamp( pan.SlideTimes - CurTime(), 0, speed )/speed
pan:Rect( x + ww, y, ww*( 3 - 3*rat ), bh, Color( 10, 10, 10, 255 ), color_white )
pan:Text( "MANAGE PREFERENCES", "wOS.TitleFont", x + ww*1.4*( 1 - rat ), y + bh/2, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER )
pan.LastHover = CurTime() + 0.01
end
lst = lst + 1
if pan.SlideTimes and pan.LastHover < CurTime() then
pan.SlideTimes = nil
pan.LastButt = nil
end
end
rightpane:SetUIScale( 10 )
rightpane.Scaling = 0.025
rightpane.CamPos = wOS.ALCS.Skills.Camera[ wOS.ALCS.Skills.CamFocus ].origin + Vector( 0, 20, -2 )
rightpane.CamAng = wOS.ALCS.Skills.Camera[ wOS.ALCS.Skills.CamFocus ].angles + Angle( 0, -30, 0 )
table.insert( wOS.ALCS.Skills.Menu.VGUI, rightpane )
end
wOS.ALCS.Skills.Camera[ "Combat-SelectExec" ] = { origin = centerpoint - Vector( 65, -45, -30 ), angles = Angle( 0, 180, 0.000 ) }
wOS.ALCS.Skills.MenuLibrary[ "Combat-SelectExec" ] = function()
local frontpane = tduiw.Create()
frontpane.SizeX = 8
frontpane.SizeY = 35
frontpane.LeftCount = 1
frontpane.RightCount = 5
frontpane.ShouldAcceptInputs = true
frontpane.LastScrollSlot = 0
frontpane.ScrollSlot = 0
frontpane.Selected = 1
frontpane.TestSkills = {}
for name, data in pairs( wOS.ALCS.ExecSys.Executions ) do
if !wOS.ALCS.ExecSys:CanUseExecution( name ) then continue end
local model = ClientsideModel( LocalPlayer():GetModel(), RENDERGROUP_OPAQUE )
model:SetSequence( data.PreviewSequence or "wos_hatred_start" )
model:SetCycle( data.PreviewFrame or 0.5 )
model.EData = data
table.insert( wOS.ALCS.Skills.CubeModels, model )
table.insert( frontpane.TestSkills, name )
end
frontpane.Renders = function( pan )
local ww, hh = pan.SizeX, pan.SizeY
local x = 0 - ww/2
local y = 10
local bh = hh/7
local execution = pan.TestSkills[ pan.Selected ] or ""
if wOS.ALCS.ExecSys.Executions[ execution ] then
local data = wOS.ALCS.ExecSys.Executions[ execution ]
pan:Text( execution, "wOS.CraftTitles", 0, -hh*1.1, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER )
pan:Text( data.Description, "wOS.CraftDescriptions", 0, -hh*0.85, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER )
pan:Text( data.RarityName or "Common", "wOS.TitleFont", 0, -hh*0.75, data.RarityColor or color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER )
end
local lst = 0
image = wOS.ALCS.Runes[ "x" ]
pan:Mat( image, x, y + bh*2.5, ww, bh )
local _jp, _pr, _hov = pan:Button( "", "wOS.TitleFont", x, y + bh*2.5, ww, bh, color_white, color_white )
if _jp then
wOS.ALCS.Skills:ChangeCamFocus( "Combat-Overview" )
elseif _hov then
local speed = 0.1
if not pan.SlideTimes then
pan.SlideTimes = CurTime() + speed
surface.PlaySound( "wos/alcs/ui_slideout.wav" )
end
if pan.LastButt != lst then
surface.PlaySound( "wos/alcs/ui_rollover.wav" )
pan.LastButt = lst
end
local rat = math.Clamp( pan.SlideTimes - CurTime(), 0, speed )/speed
pan:Rect( x + ww, y + bh*2.5, ww*( 3 - 3*rat ), bh, Color( 10, 10, 10, 255 ), color_white )
pan:Text( "GO BACK", "wOS.TitleFont", x + ww*2.1*( 1 - rat ), y + bh*2.5 + bh/2, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER )
pan.LastHover = CurTime() + 0.01
end
lst = lst + 1
local _jp, _pr, _hov = pan:Button( "", "wOS.TitleFont", -hh*0.55/2, -hh*0.65, hh*0.55, hh*1.05, Color( 0, 0, 0, 0 ), Color( 0, 0, 0, 0 ) )
if _jp then
if !wOS.ALCS.ExecSys.Executions[ execution ] then return end
net.Start( "wOS.ALCS.ExecSys.SelectExecution" )
net.WriteString( execution )
net.SendToServer()
elseif _hov then
local speed = 0.1
if not pan.SlideTimes then
pan.SlideTimes = CurTime() + speed
end
if pan.LastButt != lst then
surface.PlaySound( "wos/alcs/ui_rollover.wav" )
pan.LastButt = lst
end
local rat = math.Clamp( pan.SlideTimes - CurTime(), 0, speed )/speed
pan:Text( "SELECT THE EXECUTION TO USE IT", "wOS.CraftDescriptions", 0, y + bh*2*( 2.25 + rat ), color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER )
pan.LastHover = CurTime() + 0.01
end
lst = lst + 1
pan:Mat( leftButton, x - ww*2, y + bh*1.2, ww, bh )
local _jp, _pr, _hov = pan:Button( "", "wOS.TitleFont", x - ww*2, y + bh*1.2, ww, bh, color_white, color_white )
if _jp then
//Keep incrementing it who am I to stop you
//Your PC will regret it, not me
pan.ScrollSlot = pan.ScrollSlot - 1
pan.Selected = math.Round( pan.ScrollSlot % #pan.TestSkills ) + 1
elseif _hov then
local speed = 0.1
if pan.LastButt != lst then
surface.PlaySound( "wos/alcs/ui_rollover.wav" )
pan.LastButt = lst
end
pan.LastHover = CurTime() + 0.01
end
lst = lst + 1
pan:Mat( rightButton, x + ww*2, y + bh*1.2, ww, bh )
local _jp, _pr, _hov = pan:Button( "", "wOS.TitleFont", x + ww*2, y + bh*1.2, ww, bh, color_white, color_white )
if _jp then
//Keep incrementing it who am I to stop you
//Your PC will regret it, not me
pan.ScrollSlot = pan.ScrollSlot + 1
pan.Selected = math.Round( pan.ScrollSlot % #pan.TestSkills ) + 1
elseif _hov then
local speed = 0.1
if pan.LastButt != lst then
surface.PlaySound( "wos/alcs/ui_rollover.wav" )
pan.LastButt = lst
end
pan.LastHover = CurTime() + 0.01
end
lst = lst + 1
if pan.SlideTimes and pan.LastHover < CurTime() then
pan.SlideTimes = nil
pan.LastButt = nil
end
end
frontpane.PostRenders = function( pan )
local radius = 7.7
pan.LastScrollSlot = math.Approach( pan.LastScrollSlot, pan.ScrollSlot, 0.01 )
local offset = pi*5/10 + pi*2/#pan.TestSkills*pan.LastScrollSlot
local basesize = 1.3 * ( 1 - 0.04*(#pan.TestSkills/15) )
for i = 1, #pan.TestSkills do
local j = i - 1
local x, y = math.sin( offset - pi*j*2/#pan.TestSkills ), math.cos( offset - pi*j*2/#pan.TestSkills )
local setpos = pan.CamPos - Vector( 8, 0, 0 ) + Vector( radius*x, radius*y, -3 )
local size = 40/setpos:DistToSqr( wOS.ALCS.Skills.Camera[ wOS.ALCS.Skills.CamFocus ].origin ) //Clinically proven to be the number
if not wOS.ALCS.Skills.CubeModels[i] then continue end
wOS.ALCS.Skills.CubeModels[i]:SetPos( setpos )
wOS.ALCS.Skills.CubeModels[i]:SetModelScale( basesize*size )
if wOS.ALCS.LightsaberPreferences.Execution and wOS.ALCS.Skills.CubeModels[i].EData.Name == wOS.ALCS.LightsaberPreferences.Execution then
halo.Add( { wOS.ALCS.Skills.CubeModels[i] }, Color( 255, 255, 255, 5 ), 5, 5, 1 )
end
end
end
frontpane:SetUIScale( 10 )
frontpane.Scaling = 0.025
frontpane.CamPos = wOS.ALCS.Skills.Camera[ wOS.ALCS.Skills.CamFocus ].origin + Vector( -20, 0, 0 )
frontpane.CamAng = wOS.ALCS.Skills.Camera[ wOS.ALCS.Skills.CamFocus ].angles + Angle( 0, 0, 0 )
table.insert( wOS.ALCS.Skills.Menu.VGUI, frontpane )
end
wOS.ALCS.Skills.Camera[ "Combat-Preferences" ] = { origin = centerpoint - Vector( 45, 10, -30 ), angles = Angle( 0, 270, 0.000 ) }
wOS.ALCS.Skills.MenuLibrary[ "Combat-Preferences" ] = function()
wOS.ALCS.Dueling.Results = nil
local forward = wOS.ALCS.Skills.Camera[ wOS.ALCS.Skills.CamFocus ].angles:Forward()
local right = wOS.ALCS.Skills.Camera[ wOS.ALCS.Skills.CamFocus ].angles:Right()
local up = wOS.ALCS.Skills.Camera[ wOS.ALCS.Skills.CamFocus ].angles:Up()
local backbutt = tduiw.Create()
backbutt.SizeX = 50
backbutt.SizeY = 25
backbutt.ShouldAcceptInputs = true
local frontpane = tduiw.Create()
frontpane.SizeX = 8
frontpane.SizeY = 35
frontpane.LeftCount = 1
frontpane.RightCount = 5
frontpane.ShouldAcceptInputs = true
frontpane.LastScrollSlot = 0
frontpane.ScrollSlot = 0
frontpane.Selected = 1
frontpane.Offset = 0
frontpane.SelectMode = 0
frontpane.Renders = function( pan )
local ww, hh = pan.SizeX, pan.SizeY
local bh = hh/7
local pady = bh*0.05
local x = 25
local y = -22
local lst = 0
y = -18
local image = wOS.ALCS.Runes[ "h" ]
pan:Mat( image, x, y, ww, bh )
local _jp, _pr, _hov = pan:Button( "", "wOS.TitleFont", x, y, ww, bh, color_white, color_white )
if _jp then
frontpane.SelectMode = 1
elseif _hov then
if frontpane.SelectMode != 1 then
local speed = 0.1
if not pan.SlideTimes then
pan.SlideTimes = CurTime() + speed
surface.PlaySound( "wos/alcs/ui_slideout.wav" )
end
if pan.LastButt != lst then
surface.PlaySound( "wos/alcs/ui_rollover.wav" )
pan.LastButt = lst
end
local rat = math.Clamp( pan.SlideTimes - CurTime(), 0, speed )/speed
pan:Rect( x + ww, y, ww*( 3 - 3*rat ), bh, Color( 10, 10, 10, 255 ), color_white )
pan:Text( "GRIP SELECTION", "wOS.TitleFont", x + ww*1.6*( 1 - rat ), y + bh/2, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER )
pan.LastHover = CurTime() + 0.01
end
end
pan:Line( x, y + bh/2, x - ww*1.2, y + bh/2 )
pan:Line( x - ww*1.2, y + bh/2, x - ww*2, y + bh*2.5 )
if frontpane.SelectMode == 1 then
pan:Rect( x + ww, y, ww*3, bh, Color( 10, 10, 10, 255 ), color_white )
pan:Text( "GRIP SELECTION", "wOS.TitleFont", x + ww*1.6, y + bh/2, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER )
lst = lst + 1
y = y + bh + pady
for _, data in pairs( wOS.ALCS.LightsaberBase.Grips ) do
pan:Rect( x, y, ww*4, bh, Color( 10, 10, 10, 255 ), color_white )
local _jp, _pr, _hov = pan:Button( data.Name, "wOS.TitleFont", x, y, ww*4, bh, ( wOS.ALCS.LightsaberPreferences.Grip == data.Name and Color( 255, 0, 0 ) ) or color_white, ( wOS.ALCS.LightsaberPreferences.Grip == data.Name and Color( 255, 0, 0 ) ) or color_white )
if _jp then
net.Start( "wOS.ALCS.SelectGrip" )
net.WriteString( data.Name )
net.SendToServer()
elseif _hov then
if pan.LastButt != lst then
surface.PlaySound( "wos/alcs/ui_rollover.wav" )
pan.LastButt = lst
end
end
y = y + bh + pady
lst = lst + 1
end
end
y = -18 + bh*7 + pady*9
x = 20
image = wOS.ALCS.Runes[ "x" ]
pan:Mat( image, x, y, ww, bh )
local _jp, _pr, _hov = pan:Button( "", "wOS.TitleFont", x, y, ww, bh, color_white, color_white )
if _jp then
wOS.ALCS.Skills:ChangeCamFocus( "Combat-Overview" )
elseif _hov then
local speed = 0.1
if not pan.SlideTimes then
pan.SlideTimes = CurTime() + speed
surface.PlaySound( "wos/alcs/ui_slideout.wav" )
end
if pan.LastButt != lst then
surface.PlaySound( "wos/alcs/ui_rollover.wav" )
pan.LastButt = lst
end
local rat = math.Clamp( pan.SlideTimes - CurTime(), 0, speed )/speed
pan:Rect( x + ww, y, ww*( 3 - 3*rat ), bh, Color( 10, 10, 10, 255 ), color_white )
pan:Text( "GO BACK", "wOS.TitleFont", x + ww*2.1*( 1 - rat ), y + bh/2, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER )
pan.LastHover = CurTime() + 0.01
end
lst = lst + 1
if pan.SlideTimes and pan.LastHover < CurTime() then
pan.SlideTimes = nil
pan.LastButt = nil
end
end
frontpane:SetUIScale( 10 )
frontpane.Scaling = 0.025
frontpane.CamPos = wOS.ALCS.Skills.Camera[ wOS.ALCS.Skills.CamFocus ].origin + forward*21
frontpane.CamAng = wOS.ALCS.Skills.Camera[ wOS.ALCS.Skills.CamFocus ].angles + Angle( 0, -27, 0 )
table.insert( wOS.ALCS.Skills.Menu.VGUI, frontpane )
local leftpane = tduiw.Create()
leftpane.SizeX = 8
leftpane.SizeY = 35
leftpane.LeftCount = 1
leftpane.RightCount = 5
leftpane.ShouldAcceptInputs = true
leftpane.LastScrollSlot = 0
leftpane.ScrollSlot = 0
leftpane.Selected = 1
leftpane.Offset = 0
leftpane.SelectMode = 0
leftpane.Renders = function( pan )
local ww, hh = pan.SizeX, pan.SizeY
local bh = hh/7
local pady = bh*0.05
local x = -56
local y = -2
local lst = 0
pan:Line( 0, -hh/2, x + ww, y - bh*2 )
pan:Line( x + ww, y - bh*2, x + ww/2, y )
local image = wOS.ALCS.Runes[ "w" ]
pan:Mat( image, x, y, ww, bh )
local _jp, _pr, _hov = pan:Button( "", "wOS.TitleFont", x, y, ww, bh, color_white, color_white )
if _jp then
frontpane.SelectMode = 2
elseif _hov then
if frontpane.SelectMode != 2 then
local speed = 0.1
if not pan.SlideTimes then
pan.SlideTimes = CurTime() + speed
surface.PlaySound( "wos/alcs/ui_slideout.wav" )
end
if pan.LastButt != lst then
surface.PlaySound( "wos/alcs/ui_rollover.wav" )
pan.LastButt = lst
end
local rat = math.Clamp( pan.SlideTimes - CurTime(), 0, speed )/speed
pan:Rect( x + ww, y, ww*( 3 - 3*rat ), bh, Color( 10, 10, 10, 255 ), color_white )
pan:Text( "WIELDING PREFERENCE", "wOS.TitleFont", x + ww*1.2*( 1 - rat ), y + bh/2, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER )
pan.LastHover = CurTime() + 0.01
end
end
if frontpane.SelectMode == 2 then
pan:Rect( x + ww, y, ww*3, bh, Color( 10, 10, 10, 255 ), color_white )
pan:Text( "WIELDING PREFERENCE", "wOS.TitleFont", x + ww*1.2, y + bh/2, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER )
lst = lst + 1
y = y + bh + pady
pan:Rect( x, y, ww*4, bh, Color( 10, 10, 10, 255 ), color_white )
local _jp, _pr, _hov = pan:Button( "One Hand ( Right )", "wOS.TitleFont", x, y, ww*4, bh, ( !wOS.ALCS.LightsaberPreferences.Wield and Color( 255, 0, 0 ) ) or color_white, ( !wOS.ALCS.LightsaberPreferences.Wield and Color( 255, 0, 0 ) ) or color_white )
if _jp then
net.Start( "wOS.ALCS.SelectWield" )
net.WriteBool( false )
net.SendToServer()
elseif _hov then
if pan.LastButt != lst then
surface.PlaySound( "wos/alcs/ui_rollover.wav" )
pan.LastButt = lst
end
end
y = y + bh + pady
lst = lst + 1
pan:Rect( x, y, ww*4, bh, Color( 10, 10, 10, 255 ), ( wOS.ALCS.LightsaberPreferences.Wield and Color( 66, 117, 176 ) ) or color_white )
local _jp, _pr, _hov = pan:Button( "Dual Wield", "wOS.TitleFont", x, y, ww*4, bh, ( wOS.ALCS.LightsaberPreferences.Wield and Color( 255, 0, 0 ) ) or color_white, ( wOS.ALCS.LightsaberPreferences.Wield and Color( 255, 0, 0 ) ) or color_white )
if _jp then
net.Start( "wOS.ALCS.SelectWield" )
net.WriteBool( true )
net.SendToServer()
elseif _hov then
if pan.LastButt != lst then
surface.PlaySound( "wos/alcs/ui_rollover.wav" )
pan.LastButt = lst
end
end
y = y + bh + pady
lst = lst + 1
end
if pan.SlideTimes and pan.LastHover < CurTime() then
pan.SlideTimes = nil
pan.LastButt = nil
end
end
leftpane:SetUIScale( 10 )
leftpane.Scaling = 0.025
leftpane.PostRenders = function( pan )
if not wOS.ALCS.Skills.CubeModels[1] then return end
wOS.ALCS.Skills.CubeModels[1]:DrawModel()
end
leftpane.CamPos = wOS.ALCS.Skills.Camera[ wOS.ALCS.Skills.CamFocus ].origin + forward*21
leftpane.CamAng = wOS.ALCS.Skills.Camera[ wOS.ALCS.Skills.CamFocus ].angles + Angle( 0, 27, 0 )
table.insert( wOS.ALCS.Skills.Menu.VGUI, leftpane )
wOS.ALCS.Skills.CubeModels[1] = ClientsideModel( LocalPlayer():GetModel() )
wOS.ALCS.Skills.CubeModels[1]:SetPos( frontpane.CamPos + forward*75 - up*30 - right*10 )
wOS.ALCS.Skills.CubeModels[1]:SetAngles( Angle( 0, 180, 0 ) )
wOS.ALCS.Skills.CubeModels[1]:SetSequence( "vanguard_f_idle" )
wOS.ALCS.Skills.CubeModels[1]:SetNoDraw( true )
local bone = wOS.ALCS.Skills.CubeModels[1]:LookupBone( "ValveBiped.Bip01_R_Hand" )
local rpos, rang = Vector( 0, 0, 0 ), Angle( 0, 0, 0 )
if bone then
rpos, rang = wOS.ALCS.Skills.CubeModels[1]:GetBonePosition( bone )
rang:RotateAroundAxis( rang:Right(), 90 )
rpos = rpos - rang:Forward()*6 - rang:Up()*1.8 + rang:Right()*0.5
end
bone = wOS.ALCS.Skills.CubeModels[1]:LookupBone( "ValveBiped.Bip01_L_Hand" )
local lpos, lang = Vector( 0, 0, 0 ), Angle( 0, 0, 0 )
if bone then
lpos, lang = wOS.ALCS.Skills.CubeModels[1]:GetBonePosition( bone )
lang:RotateAroundAxis( lang:Right(), -90 )
lpos = lpos - lang:Forward()*6 + lang:Up()*3 + lang:Right()*0.5
end
wOS.ALCS.Skills.CubeModels[2] = ClientsideModel( wOS.PersonalSaber.UseHilt )
wOS.ALCS.Skills.CubeModels[2]:SetPos( rpos )
wOS.ALCS.Skills.CubeModels[2]:SetAngles( rang )
wOS.ALCS.Skills.CubeModels[3] = ClientsideModel( wOS.SecPersonalSaber.UseHilt )
wOS.ALCS.Skills.CubeModels[3]:SetPos( lpos )
wOS.ALCS.Skills.CubeModels[3]:SetAngles( lang )
backbutt.Renders = function( pan )
local ww, hh = pan.SizeX, pan.SizeY
local x = 10
local y = -50
y = y + hh*0.23
y = y + hh*0.06
y = y + hh*0.06
pan:BlockUseBind()
end
backbutt:SetUIScale( 20 )
backbutt.Scaling = 0.05
local spos = wOS.ALCS.Skills.CubeModels[1]:GetPos()
backbutt.CamPos = spos - wOS.ALCS.Skills.CubeModels[1]:GetRight()*30 + wOS.ALCS.Skills.CubeModels[1]:GetForward()*20
backbutt.CamAng = wOS.ALCS.Skills.Camera[ wOS.ALCS.Skills.CamFocus ].angles + Angle( 0, 0, -90 )
table.insert( wOS.ALCS.Skills.Menu.VGUI, backbutt )
end
|
local path = (...):gsub("[^%.]*$", "")
local M = require(path .. 'master')
local CyclicList, Set, SymmetricMatrix, Vec2
CyclicList, Set, SymmetricMatrix, Vec2 = M.CyclicList, M.Set, M.SymmetricMatrix, M.Vec2
local wedge
wedge = Vec2.wedge
local round
round = M.math.round
local geometry = require(path .. 'geometry')
local bounding_box, centroid, closest_edge_point, is_point_in_triangle
bounding_box, centroid, closest_edge_point, is_point_in_triangle = geometry.bounding_box, geometry.centroid, geometry.closest_edge_point, geometry.is_point_in_triangle
local ConvexPolygon, Navigation, string_pull, orientation
ConvexPolygon = M.class({
__init = function(self, vertices, name, hidden)
assert(#vertices > 2, "A polygon must have a least 3 points.", 2)
self.vertices = CyclicList(vertices)
self.name = name
self.hidden = hidden
self.n = #vertices
self.min, self.max = bounding_box(vertices)
self.centroid = centroid(vertices)
do
local _accum_0 = { }
local _len_0 = 1
for i = 1, self.n do
_accum_0[_len_0] = false
_len_0 = _len_0 + 1
end
self.connections = _accum_0
end
end,
len = function(self)
return self.n
end,
ipairs = function(self)
return ipairs(self.vertices.items)
end,
__index = function(self, key)
return self.vertices[key]
end,
get_edge = function(self, i)
return self.vertices[i], self.vertices[i + 1]
end,
get_connection = function(self, i)
local c = self.connections[i]
if c and not c.polygon.hidden then
return c.polygon, c.edge
end
end,
is_point_inside = function(self, P)
if not (P.x < self.min.x or P.y < self.min.y or P.x > self.max.x or P.y > self.max.y) then
for i = 2, self.n - 1 do
if is_point_in_triangle(P, self.vertices[1], self.vertices[i], self.vertices[i + 1]) then
return true
end
end
end
return false
end,
is_point_inside_connected = function(self, P, visited)
if visited == nil then
visited = { }
end
visited[self] = true
if self:is_point_inside(P) then
return self
end
local _list_0 = self.connections
for _index_0 = 1, #_list_0 do
local t = _list_0[_index_0]
if t and not t.polygon.hidden and not visited[t.polygon] then
do
local poly = t.polygon:is_point_inside_connected(P, visited)
if poly then
return poly
end
end
end
end
return nil
end,
closest_edge_point = function(self, P, edge_idx)
local A, B = self:get_edge(edge_idx)
return closest_edge_point(P, A, B)
end,
closest_boundary_point_connected = function(self, P, visited)
if visited == nil then
visited = { }
end
visited[self] = true
local C, poly
local d = math.huge
for i = 1, self.n do
if not self.connections[i] or self.connections[i].polygon.hidden then
local tmp_C = self:closest_edge_point(P, i)
local tmp_d = (P - tmp_C):lenS()
if tmp_d < d then
d = tmp_d
C = tmp_C
poly = self
end
else
local neighbour = self.connections[i].polygon
if not visited[neighbour] then
local tmp_C, tmp_poly, tmp_d = neighbour:closest_boundary_point_connected(P, visited)
if tmp_d < d then
d = tmp_d
C = tmp_C
poly = tmp_poly
end
end
end
end
return C, poly, d
end
})
Navigation = M.class({
__init = function(self, pmaps)
if pmaps == nil then
pmaps = { }
end
local vertices, vertex_idxs, polygons, name_groups = { }, {
n = 0
}, { }, { }
for _index_0 = 1, #pmaps do
local pmap = pmaps[_index_0]
local name_group = pmap.name and { }
if pmap.name then
name_groups[pmap.name] = name_group
end
for _index_1 = 1, #pmap do
local poly = pmap[_index_1]
local tmp = { }
for _index_2 = 1, #poly do
local v = poly[_index_2]
local x, y = unpack(v)
local label = tostring(x) .. ';' .. tostring(y)
if not vertices[label] then
v = Vec2(x, y)
vertices[label] = v
vertex_idxs.n = vertex_idxs.n + 1
vertex_idxs[v] = vertex_idxs.n
end
tmp[#tmp + 1] = vertices[label]
end
local cp = ConvexPolygon(tmp, pmap.name, pmap.hidden)
polygons[#polygons + 1] = cp
if name_group then
name_group[#name_group + 1] = cp
end
end
end
self.polygons = polygons
self.vertex_idxs = vertex_idxs
self.name_groups = name_groups
end,
set_visibility = function(self, name, bool)
local _list_0 = (self.name_groups[name] or { })
for _index_0 = 1, #_list_0 do
local p = _list_0[_index_0]
p.hidden = not bool
end
end,
toggle_visibility = function(self, name)
local _list_0 = (self.name_groups[name] or { })
for _index_0 = 1, #_list_0 do
local p = _list_0[_index_0]
p.hidden = not p.hidden
end
end,
initialize = function(self)
self.initialized = true
local edges_matrix = SymmetricMatrix(self.vertex_idxs.n)
for k, p in ipairs(self.polygons) do
for i = 1, p.n do
local A, B = p:get_edge(i)
local A_idx, B_idx = self.vertex_idxs[A], self.vertex_idxs[B]
if not edges_matrix[A_idx][B_idx] then
edges_matrix[A_idx][B_idx] = { }
end
local t = edges_matrix[A_idx][B_idx]
t[#t + 1] = {
edge = i,
polygon = p
}
end
end
for i = 1, self.vertex_idxs.n do
for j = i + 1, self.vertex_idxs.n do
do
local t = edges_matrix[i][j]
if t then
local A, B = unpack(t)
A.polygon.connections[A.edge] = B or false
if B then
B.polygon.connections[B.edge] = A
end
end
end
end
end
end,
_is_point_inside = function(self, P)
if not self.initialized then
self:initialize()
end
local visited = { }
local _list_0 = self.polygons
for _index_0 = 1, #_list_0 do
local poly = _list_0[_index_0]
if not visited[poly] and not poly.hidden then
do
local p = poly:is_point_inside_connected(P, visited)
if p then
return p
end
end
end
end
end,
_closest_boundary_point = function(self, P)
if not self.initialized then
self:initialize()
end
local d = math.huge
local C, piece, poly
local _list_0 = self.polygons
for _index_0 = 1, #_list_0 do
local p = _list_0[_index_0]
if not (p.hidden) then
for i = 1, p.n do
if not p.connections[i] or p.connections[i].polygon.hidden then
local tmp_C = p:closest_edge_point(P, i)
local tmp_d = (P - tmp_C):lenS()
if tmp_d < d then
d = tmp_d
C = tmp_C
poly = p
end
end
end
end
end
return C, poly
end,
_shortest_path = function(self, A, B)
if not self.initialized then
self:initialize()
end
if self.n == 0 then
return { }
end
A, B = round(A), round(B)
local node_A, node_B
node_A = self:_is_point_inside(A)
if not node_A then
A, node_A = self:_closest_boundary_point(A)
A = round(A)
end
node_B = node_A:is_point_inside_connected(B)
if not node_B then
B, node_B = node_A:closest_boundary_point_connected(B)
B = round(B)
end
if node_A == node_B then
return {
A,
B
}
end
local found_path = false
local _list_0 = self.polygons
for _index_0 = 1, #_list_0 do
local p = _list_0[_index_0]
p.prev_edge = nil
end
local polylist = Set()
node_B.entry = B
node_B.distance = 0
polylist:add(node_B)
while not found_path do
if polylist:size() == 0 then
break
end
local least_cost_poly
local least_cost = math.huge
for p in polylist:iterator() do
local cost = p ~= node_B and p.distance + (p.centroid - A):len() or 0
if cost < least_cost then
least_cost_poly = p
least_cost = cost
end
end
local p = least_cost_poly
for i = 1, p.n do
local q, c_edge = p:get_connection(i)
if q then
local entry = p:closest_edge_point(p.entry, i)
local distance = p.distance + (p.entry - entry):len()
if q.prev_edge then
if q.distance > distance then
q.prev_edge = c_edge
q.distance = distance
q.entry = entry
end
else
q.prev_edge = c_edge
q.distance = distance
q.entry = entry
polylist:add(q)
if q == node_A then
local found = true
break
end
end
end
end
if found_path then
break
end
polylist:remove(p)
end
local portals = {
{
A,
A
}
}
local p = node_A
while p ~= node_B and p.prev_edge do
local C, D = p:get_edge(p.prev_edge)
local L, R = unpack(portals[#portals])
local sign = orientation(C, L, D)
sign = sign == 0 and orientation(C, R, D) or sign
portals[#portals + 1] = sign > 0 and {
C,
D
} or {
D,
C
}
p = p:get_connection(p.prev_edge)
end
portals[#portals + 1] = {
B,
B
}
return string_pull(portals)
end,
is_point_inside = function(self, x, y)
return not not self:_is_point_inside(Vec2(x, y))
end,
closest_boundary_point = function(self, x, y)
local P = self:_closest_boundary_point(Vec2(x, y))
return P.x, P.y
end,
shortest_path = function(self, x1, y1, x2, y2)
path = self:_shortest_path(Vec2(x1, y1), Vec2(x2, y2))
local _accum_0 = { }
local _len_0 = 1
for _index_0 = 1, #path do
local v = path[_index_0]
_accum_0[_len_0] = {
v.x,
v.y
}
_len_0 = _len_0 + 1
end
return _accum_0
end
})
M.Navigation = Navigation
string_pull = function(portals)
local portal_left, portal_right = unpack(portals[1])
local l_idx, r_idx = 1, 1
local apex = portal_left
path = {
apex
}
local i = 1
while i < #portals do
i = i + 1
local left, right = unpack(portals[i])
local skip = false
if orientation(portal_right, apex, right) <= 0 then
if apex == portal_right or orientation(portal_left, apex, right) > 0 then
portal_right = right
r_idx = i
else
if path[#path] ~= portal_left then
path[#path + 1] = portal_left
end
apex = portal_left
portal_right = apex
r_idx = l_idx
i = l_idx
skip = true
end
end
if not skip and orientation(portal_left, apex, left) >= 0 then
if apex == portal_left or orientation(portal_right, apex, left) < 0 then
portal_left = left
l_idx = i
else
if path[#path] ~= portal_right then
path[#path + 1] = portal_right
end
apex = portal_right
portal_left = apex
l_idx = r_idx
i = r_idx
end
end
end
local A = portals[#portals][1]
if path[#path] ~= A or #path == 1 then
path[#path + 1] = A
end
return path
end
orientation = function(L, P, R)
return wedge(R - P, L - P)
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.