content stringlengths 5 1.05M |
|---|
--インフェルニティ・サプレッション
--Scripted by mallu11
function c101102075.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(101102075,0))
e1:SetCategory(CATEGORY_DISABLE+CATEGORY_DAMAGE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_CHAINING)
e1:SetCountLimit(1,101102075+EFFECT_COUNT_CODE_OATH)
e1:SetCondition(c101102075.condition)
e1:SetTarget(c101102075.target)
e1:SetOperation(c101102075.activate)
c:RegisterEffect(e1)
--act in set turn
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_TRAP_ACT_IN_SET_TURN)
e2:SetProperty(EFFECT_FLAG_SET_AVAILABLE)
e2:SetCondition(c101102075.actcon)
c:RegisterEffect(e2)
end
function c101102075.confilter(c)
return c:IsFaceup() and c:IsSetCard(0xb)
end
function c101102075.condition(e,tp,eg,ep,ev,re,r,rp)
if not Duel.IsExistingMatchingCard(c101102075.confilter,tp,LOCATION_MZONE,0,1,nil) then return end
return ep==1-tp and re:IsActiveType(TYPE_MONSTER) and Duel.IsChainDisablable(ev)
end
function c101102075.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DISABLE,eg,1,0,0)
end
function c101102075.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.NegateEffect(ev) and re:GetHandler():IsRelateToEffect(re) and re:GetHandler():IsLevelAbove(1) and Duel.SelectYesNo(tp,aux.Stringid(101102075,1)) then
Duel.BreakEffect()
Duel.Damage(1-tp,re:GetHandler():GetLevel()*100,REASON_EFFECT)
end
end
function c101102075.actcon(e)
return Duel.GetFieldGroupCount(e:GetHandlerPlayer(),LOCATION_HAND,0)==0
end
|
local tabler = require 'nelua.utils.tabler'
local class = require 'nelua.utils.class'
local sstream = require 'nelua.utils.sstream'
local traits = require 'nelua.utils.traits'
local console = require 'nelua.utils.console'
local types = require 'nelua.types'
local primtypes = require 'nelua.typedefs'.primtypes
local Attr = require 'nelua.attr'
local Symbol = class(Attr)
local config = require 'nelua.configer'.get()
Symbol._symbol = true
function Symbol.promote_attr(attr, node, name)
attr.node = node
if name then
attr.name = name
else
attr.anonymous = true
end
setmetatable(attr, Symbol)
return attr
end
function Symbol:clear_possible_types()
self.possibletypes = nil
self.fallbacktype = nil
self.unknownrefs = nil
self.refersitself = nil
end
function Symbol:add_possible_type(type, refnode)
if self.type then return end
if type then
if type.is_nilptr and not self.fallbacktype then
self.fallbacktype = primtypes.pointer
elseif type.is_niltype then
self.fallbacktype = primtypes.any
end
if type.is_nolvalue then return end
end
local unknownrefs = self.unknownrefs
if not type then
assert(refnode)
if not unknownrefs then
self.unknownrefs = {[refnode] = true}
else
unknownrefs[refnode] = true
end
return
elseif unknownrefs and unknownrefs[refnode] then
unknownrefs[refnode] = nil
if #unknownrefs == 0 then
self.unknownrefs = nil
end
end
if not self.possibletypes then
self.possibletypes = {[1] = type}
elseif not tabler.ifind(self.possibletypes, type) then
table.insert(self.possibletypes, type)
else
return
end
end
function Symbol:has_resolve_refsym(refsym, checkedsyms)
if self.unknownrefs then
if not checkedsyms then
checkedsyms = {[self] = true}
else
checkedsyms[self] = true
end
for refnode in pairs(self.unknownrefs) do
for sym in refnode:walk_symbols() do
if sym == refsym then
return true
elseif not checkedsyms[sym] and sym:has_resolve_refsym(refsym, checkedsyms) then
return true
end
end
end
end
return false
end
function Symbol:is_waiting_others_resolution()
if self.unknownrefs then
if self.refersitself == nil then
self.refersitself = self:has_resolve_refsym(self)
end
return not self.refersitself
end
return false
end
function Symbol:is_waiting_resolution()
if self:is_waiting_others_resolution() then
return true
end
if self.possibletypes and #self.possibletypes > 0 then
return true
end
return false
end
function Symbol:resolve_type(force)
if self.type then return false end -- type already resolved
if not force and self:is_waiting_others_resolution() then
-- ignore when other symbols need to be resolved first
return false
end
local resolvetype = types.find_common_type(self.possibletypes)
if resolvetype then
self.type = resolvetype
self:clear_possible_types()
elseif traits.is_type(force) then
self.type = force
elseif force and self.fallbacktype then
self.type = self.fallbacktype
else
return false
end
if config.debug_resolve then
console.info(self.node:format_message('info', "symbol '%s' resolved to type '%s'", self.name, self.type))
end
return true
end
function Symbol:link_node(node)
local attr = node.attr
if attr ~= self then
if next(attr) == nil then
node.attr = self
else
node.attr = self:merge(attr)
end
end
end
-- Mark that this symbol is used by another symbol (usually a function symbol).
function Symbol:add_use_by(funcsym)
if funcsym then
local usedby = self.usedby
if not usedby then
usedby = {[funcsym] = true}
self.usedby = usedby
else
usedby[funcsym] = true
end
else -- use on root scope
self.used = true
end
end
-- Returns whether the symbol is really used in the program.
-- Used for dead code elimination.
function Symbol:is_used(cache, checkedsyms)
local used = self.used
if used ~= nil then return used end
used = false
if self.cexport or self.entrypoint or self.volatile or self.nodce or self.ctopinit then
used = true
else
local usedby = self.usedby
if usedby then
if not checkedsyms then
checkedsyms = {}
end
checkedsyms[self] = true
for funcsym in next,usedby do
if not checkedsyms[funcsym] then
if funcsym:is_used(false, checkedsyms) then
used = true
break
end
end
end
end
end
if cache then
self.used = used
end
return used
end
-- Checks a symbol is directly accessible from a scope, without needing closures.
function Symbol:is_directly_accesible_from_scope(scope)
if self.staticstorage or -- symbol declared in the program static storage, thus always accessible
self.comptime or (self.type and self.type.is_comptime) then -- compile time symbols are always accessible
return true
end
if self.scope:get_up_function_scope() == scope:get_up_function_scope() then
-- the scope and symbol's scope are inside the same function
return true
end
return false
end
function Symbol:__tostring()
local ss = sstream()
ss:add(self.name or '<anonymous>')
local type = self.type
if type then
ss:addmany(': ', type)
end
local value = self.value
if value and not type.is_procedure then
ss:addmany(' = ', value)
end
return ss:tostring()
end
return Symbol
|
--[[
© 2013 GmodLive private project do not share
without permission of its author (Andrew Mensky vk.com/men232).
--]]
local greenCode = greenCode;
local math = math;
local PLUGIN = PLUGIN or greenCode.plugin:Loader();
ECONOMIC_TAX = 0;
PLUGIN.stored = PLUGIN.stored or {};
function PLUGIN:GetStatus()
return self.stored.status or 1;
end;
function PLUGIN:GetStock()
return self.stored.stock or 0;
end;
function PLUGIN:GetPrice( nAmount ) return math.Round( nAmount * (1 + (1 - self:GetStatus())*greenCode.config:Get("bank_agres"):Get(2)) ); end;
greenCode.datastream:Hook( "_RPEconomic", function( tData )
ECONOMIC_TAX = tData.tax or 0;
tData.tax = nil;
PLUGIN.stored = tData or {};
end); |
local Ans = select(2, ...);
local Utils = Ans.Utils;
local Config = Ans.Config;
local EventManager = Ans.EventManager;
EventManager:On("BAG_UPDATE_DELAYED",
function()
if (UnitIsDead("player") or InCombatLockdown()) then
return;
end
if (AnsDestroyWindow and Config.Crafting().autoShowDestroying) then
AnsDestroyWindow:Populate(true);
AnsDestroyWindow:Show();
end
end
); |
----------------------------------------------------------------------------------
--- Total RP 3
--- Prat plugin
--- ---------------------------------------------------------------------------
--- Copyright 2014-2019 Morgane "Ellypse" Parize <ellypse@totalrp3.info> @EllypseCelwe
---
--- Licensed under the Apache License, Version 2.0 (the "License");
--- you may not use this file except in compliance with the License.
--- You may obtain a copy of the License at
---
--- http://www.apache.org/licenses/LICENSE-2.0
---
--- Unless required by applicable law or agreed to in writing, software
--- distributed under the License is distributed on an "AS IS" BASIS,
--- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
--- See the License for the specific language governing permissions and
--- limitations under the License.
----------------------------------------------------------------------------------
if not Prat then
return;
end
---@type TRP3_API
local _, TRP3_API = ...;
Prat:AddModuleToLoad(function()
local PRAT_MODULE = Prat:RequestModuleName("Total RP 3")
local pratModule = Prat:NewModule(PRAT_MODULE);
local PL = pratModule.PL;
PL:AddLocale(PRAT_MODULE, "enUS", {
module_name = "Total RP 3",
module_desc = "Total RP 3 customizations for Prat",
});
Prat:SetModuleOptions(pratModule, {
name = "Total RP 3",
desc = "Total RP 3 customizations for Prat",
type = "group",
args = {
info = {
name = "Total RP 3 customizations for Prat",
type = "description",
}
}
});
-- Enable Total RP 3's module by default
Prat:SetModuleDefaults(pratModule.name, {
profile = {
on = true,
},
});
-- Runs before Prat add the message to the chat frames
function pratModule:Prat_PreAddMessage(_, message, _, event)
if TRP3_API.chat.disabledByOOC() then return end;
-- If the message has no GUID (system?) or an invalid GUID (WIM >:( ) we don't have anything to do with this
if not message.GUID or not C_PlayerInfo.GUIDIsPlayer(message.GUID) then return end;
-- Do not do any modification if the channel is not handled by TRP3 or customizations has been disabled
-- for that channel in the settings
if not TRP3_API.chat.isChannelHandled(event) or not TRP3_API.chat.configIsChannelUsed(event) then return end;
-- Retrieve all the player info from the message GUID
local _, _, _, _, _, name, realm = GetPlayerInfoByGUID(message.GUID);
-- Calling our unitInfoToID() function to get a "Player-Realm" formatted string (handles cases where realm is nil)
local unitID = TRP3_API.utils.str.unitInfoToID(name, realm);
local characterName = unitID;
--- Extract the color used by Prat so we use it by default
---@type ColorMixin
local characterColor = TRP3_API.utils.color.extractColorFromText(message.PLAYER);
-- Character name is without the server name is they are from the same realm or if the option to remove realm info is enabled
if realm == TRP3_API.globals.player_realm_id or TRP3_API.configuration.getValue("remove_realm") then
characterName = name;
end
-- Get the unit color and name
local customizedName = TRP3_API.chat.getFullnameForUnitUsingChatMethod(unitID);
if customizedName then
characterName = customizedName;
end
-- We retrieve the custom color if the option for custom colored names in chat is enabled
if TRP3_API.chat.configShowNameCustomColors() then
local customColor = TRP3_API.utils.color.getUnitCustomColor(unitID);
-- If we do have a custom
if customColor then
-- Check if the option to increase the color contrast is enabled
if AddOn_TotalRP3.Configuration.shouldDisplayIncreasedColorContrast() then
-- And lighten the color if it is
customColor:LightenColorUntilItIsReadable();
end
-- And finally, use the color
characterColor = customColor;
end
end
if characterColor then
-- If we have a valid color in the end, wrap the name around the color's code
characterName = characterColor:WrapTextInColorCode(characterName);
end
if TRP3_API.configuration.getValue("chat_show_icon") then
local info = TRP3_API.utils.getCharacterInfoTab(unitID);
if info and info.characteristics and info.characteristics.IC then
characterName = TRP3_API.utils.str.icon(info.characteristics.IC, 15) .. " " .. characterName;
end
end
-- Check if this message was flagged as containing a 's at the beggning.
-- To avoid having a space between the name of the player and the 's we previously removed the 's
-- from the message. We now need to insert it after the player's name, without a space.
if TRP3_API.chat.getOwnershipNameID() == message.GUID then
characterName = characterName .. "'s";
end
-- Replace the message player name with the colored character name
message.PLAYER = characterName
message.sS = nil
message.SERVER = nil
message.Ss = nil
end
function pratModule:OnModuleEnable()
Prat.RegisterChatEvent(pratModule, "Prat_PreAddMessage");
end
function pratModule:OnModuleDisable()
Prat.UnregisterChatEvent(pratModule, "Prat_PreAddMessage");
end
end);
|
local EventEmitter = require('colyseus.events').EventEmitter
local protocol = require('colyseus.protocol')
Room = {}
Room.__index = Room
function Room.create(client, name)
local room = EventEmitter:new({
id = nil,
state = {}
})
setmetatable(room, Room)
room:init(client, name)
return room
end
function Room:init(client, name)
self.client = client
self.name = name
-- remove all listeners on leave
self:on('leave', self.off)
end
function Room:leave()
if this.id >= 0 then
self.client.send({ protocol.LEAVE_ROOM, self.id })
end
end
function Room:send (data)
self.client:send({ protocol.ROOM_DATA, self.id, data })
end
return Room
|
--
-- Author: wangdi
-- Date: 2016-02-09 00:13:55
--
local GameManager = {}
buffVector = {}
enemyVector = {}
local buffPanel = nil
local attribution = {
specialWaveNum = 10,
maxBuffNum = 5,
maxBulletShootNum = 10,
maxBulletSplitNum = 10,
moreEnemiesDuration = 10,
specialBulletDuration = 10,
freeBulletDuration = 10,
bulletPower = 1,
coinRainValue = 5,
coinRainDuration = 8,
coinEnemySplitValue = 5,
coinEnemySplitNum = 8,
doubleScoreDuration = 10,
shootSpeed = 2
}
function GameManager.getAttr()
return attribution
end
function GameManager.setBuffPanel( _buffPanel )
buffPanel = _buffPanel
end
function GameManager.getBuffPanel()
return buffPanel
end
return GameManager |
local Root = script:FindFirstAncestor('MazeGeneratorPlugin')
local Plugin = Root.Plugin
local Roact = require(Root:WaitForChild('Roact'))
local M = require(Root.M)
local UICorner = require(Plugin.Components.UICorner)
local e = Roact.createElement
local materialIconsAsset = 'rbxassetid://3926305904'
local materialIconsAsset2 = 'rbxassetid://3926307971'
local Theme = require(Plugin.Components.Theme)
local MaterialIcons = {
close = {
Image = materialIconsAsset,
ImageRectOffset = Vector2.new(284, 4),
ImageRectSize = Vector2.new(24, 24),
},
inbox = {
Image = materialIconsAsset,
ImageRectOffset = Vector2.new(404, 484),
ImageRectSize = Vector2.new(36, 36),
},
shop = {
Image = materialIconsAsset2,
ImageRectOffset = Vector2.new(684, 44),
ImageRectSize = Vector2.new(36, 36),
},
}
local function RoundButton(props)
local image
local aspect
local size = UDim2.new(1, 0, 0, 50)
if props.icon then
size = UDim2.new(0.7, 0, 0.7, 0)
aspect = e('UIAspectRatioConstraint')
image = e(
'ImageButton',
M.extend(
{
Position = UDim2.new(0.5, 0, 0.5, 0),
AnchorPoint = Vector2.new(0.5, 0.5),
Size = UDim2.new(0, 25, 0, 25),
BackgroundTransparency = 1,
ZIndex = 2,
[Roact.Event.MouseButton1Click] = function()
props.onClicked()
end,
},
MaterialIcons[props.icon]
)
)
end
return Theme.with(function(theme)
return e(
'TextButton',
M.extend(
{
Font = theme.ButtonFont,
Size = size,
BackgroundColor3 = theme.Brand1,
TextColor3 = theme.TextOnAccent,
TextSize = 26,
Text = '',
[Roact.Event.MouseButton1Click] = function()
props.onClicked()
end,
},
M.omit(props, 'icon', 'onClicked')
),
{
UICorner = e(UICorner),
aspect,
image,
}
)
end)
end
return RoundButton |
GrailDatabasePlayer = {
["controlCompletedQuests"] = {
},
["spellsCast"] = {
[27] = 262144,
[2] = 1024,
[4605] = 2,
[1770] = 1,
[2130] = 262144,
[2170] = 4096,
[24] = 4096,
[5963] = 16384,
[5601] = 2048,
[95] = 8,
[159] = 671088640,
[1988] = 402653184,
[3716] = 512,
[82] = 262144,
[2228] = 2147483648,
[4756] = 2097152,
[2166] = 134217728,
[5544] = 1024,
[271] = 131072,
[1371] = 134217728,
[26] = 8,
[4774] = 8192,
[607] = 512,
[1667] = 64,
[30] = 2097152,
[46] = 67108864,
[4637] = 2048,
[5018] = 1048576,
[3741] = 805306368,
[2168] = 8192,
[202] = 12288,
[1319] = 8192,
[105] = 16,
[1746] = 2048,
[2163] = 2048,
[1817] = 8388608,
[155] = 212992,
},
["abandonedQuests"] = {
},
["buffsExperienced"] = {
[4637] = 2048,
[1915] = 16384,
[3737] = 67108864,
[1515] = 8388608,
[5963] = 16512,
[159] = 536870912,
[3716] = 512,
[4774] = 8192,
[1492] = 256,
[1090] = 256,
[4759] = 16384,
[1371] = 134217728,
[1558] = 2048,
[5825] = 32,
[24] = 32,
[673] = 33554432,
[279] = 128,
[3622] = 65536,
[5601] = 2048,
[2033] = 16777216,
[1102] = 33554432,
[3599] = 64,
[77] = 16384,
[0] = 65536,
[5002] = 256,
[4789] = 8388608,
},
["dailyGroups"] = {
},
["completedQuests"] = {
[824] = 805306368,
[763] = 25165824,
[1019] = 512,
[1021] = 1,
[840] = 118489088,
[968] = 3932384,
[844] = 284672,
[978] = 530432,
[24] = 80,
[919] = 8,
[984] = 50331666,
[986] = 4294934541,
[994] = 15724544,
[96] = 524288,
[874] = 671612960,
[756] = 4194304,
[1121] = 4096,
[865] = 65536,
[776] = 268959744,
[638] = 25165824,
[766] = 134220800,
[451] = 516489328,
[1083] = 65536,
[1020] = 4260364288,
[452] = 67108864,
[839] = 27262976,
[967] = 16777216,
[969] = 50331648,
[845] = 100663296,
[973] = 536870912,
[1241] = 1,
[198] = 251658240,
[26] = 268435457,
[918] = 16777216,
[1000] = 128,
[985] = 4160749568,
[987] = 511,
[767] = 32,
[991] = 79872,
[993] = 256,
[741] = 1048576,
[1231] = 1269760,
[999] = 2097152,
[347] = 16777216,
[818] = 6156,
[1112] = 1214447616,
[1242] = 8,
[996] = 480,
[23] = 86661312,
[764] = 1408,
},
["completedResettableQuests"] = {
[1122] = 50331648,
},
["actuallyCompletedQuests"] = {
[969] = 33554432,
},
["serverUpdated"] = "2015-11-17 20:36",
}
|
--[[
*******************************************************
* LASP - LUA AREA SCRIPTING PROJECT *
* License *
*******************************************************
This software is provided as free and open source by the
staff of The Lua Area Scripting Project, in accordance with
the AGPL license. This means we provide the software we have
created freely and it has been thoroughly tested to work for
the developers, but NO GUARANTEE is made it will work for you
as well. Please give credit where credit is due, if modifying,
redistributing and/or using this software. Thank you.
Area - Mulgore - Mobs.lua by Yerney
Report Bugs at www.lasp.forummotion.com
-- ]]
--Bael'dun Appraiser
function BaelApp_OnCombat(Unit, Event)
Unit:SendChatMessage(12, 0, "Gor eft mitta ta gor-skalf")
if Unit:GetHealthPct() < 15 then
Unit:FullCastSpell(2052)
end
end
function BaelApp_OnDead(Unit, Event)
Unit:RemoveEvents()
end
function BaelApp_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(2990, 1, "BaelApp_OnCombat")
RegisterUnitEvent(2990, 2, "BaelApp_LeaveCombat")
RegisterUnitEvent(2990, 4, "BaelApp_OnDead")
--Bristleback Battleboar
function Battleboar_OnCombat(pUnit, Event)
pUnit:FullCastSpell(3385)
end
function Battleboar_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent (2954, 1, "Battleboar_OnCombat")
RegisterUnitEvent (2954, 2, "Battleboar_LeaveCombat")
--Bristleback Interloper
function Bristleback_OnCombat(pUnit, Event)
pUnit:RegisterEvent("Bristleback_Spell", 3500, 0)
end
function Bristleback_Spell(pUnit, Event)
pUnit:FullCastSpellOnTarget(12166, pUnit:GetClosestPlayer())
end
RegisterUnitEvent (3566, 1, "Bristleback_OnCombat")
--Bristleback Shaman
function BristleSha_OnCombat(Unit, Event)
Unit:RegisterEvent("BristleSha_Spell", 3500, 0)
end
function BristleSha_Spell(pUnit, Event)
pUnit:FullCastSpellOnTarget(13482, pUnit:GetClosestPlayer())
end
function BristleSha_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(2953, 1, "BristleSha_OnCombat")
RegisterUnitEvent(2953, 2, "BristleSha_LeaveCombat")
--Galak Outrunner
function GalakOut_OnCombat(pUnit, Event)
pUnit:RegisterEvent("GalakOut_Spell", 3500, 0)
end
function GalakOut_Spell(pUnit, Event)
pUnit:FullCastSpellOnTarget(6660, pUnit:GetClosestPlayer())
end
function GalakOut_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(2968, 1, "GalakOut_OnCombat")
RegisterUnitEvent(2968, 2, "GalakOut_LeaveCombat")
--Mazzranach -> Elite
function Mazz_OnCombat(pUnit, Event)
pUnit:CastSpell(6268)
pUnit:RegisterEvent("Mazz_Spell", 5000, 1)
end
function Mazz_Spell(pUnit, Event)
pUnit:FullCastSpellOnTarget(3583, pUnit:GetClosestPlayer())
end
function Mazz_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(3068, 1, "Mazz_OnCombat")
RegisterUnitEvent(3068, 2, "Mazz_LeaveCombat")
--Palemane Poacher
function PalemanePoacher_OnCombat(pUnit, Event)
pUnit:RegisterEvent("PalemanePoacher_Shoot", 3500, 0)
pUnit:RegisterEvent("PalemanePoacher_Shot", 5000, 0)
end
function PalemanePoacher_Shoot(pUnit, Event)
pUnit:FullCastSpellOnTarget(6660, pUnit:GetClosestPlayer())
end
function PalemanePoacher_Shot(pUnit, Event)
pUnit:FullCastSpellOnTarget(1516, pUnit:GetClosestPlayer())
end
function PalemanePoacher_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(2951, 1, "PalemanePoacher_OnCombat")
RegisterUnitEvent(2951, 2, "PalemanePoacher_LeaveCombat")
--Palemane Skinner
function PalemaneSkinner_OnCombat(pUnit, Event)
local sayflip=math.random(1,2)
if sayflip==1 then
pUnit:SendChatMessage(12, 0, "Grr... fresh meat!")
elseif sayflip==2 then
pUnit:SendChatMessage(12, 0, "More bones to gnaw on...")
end
pUnit:RegisterEvent("PalemaneSkinner_Spell", 8000, 1)
end
function PalemaneSkinner_Spell(pUnit, Event)
pUnit:FullCastSpell(774)
end
function PalemaneSkinner_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(2950, 1, "PalemaneSkinner_OnCombat")
RegisterUnitEvent(2950, 2, "PalemaneSkinner_LeaveCombat")
--Palemane Tanner
function PalemaneTanner_OnCombat(pUnit, Event)
local sayflip=math.random(1,2)
if sayflip==1 then
pUnit:SendChatMessage(12, 0, "Grr... fresh meat!")
elseif sayflip==2 then
pUnit:SendChatMessage(12, 0, "More bones to gnaw on...")
end
pUnit:RegisterEvent("PalemaneTanner_Wrath", 3500, 0)
end
function PalemaneTanner_Wrath(pUnit, Event)
pUnit:FullCastSpellOnTarget(9739, pUnit:GetClosestPlayer())
end
function PalemaneTanner_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(2949, 1, "PalemaneTanner_OnCombat")
RegisterUnitEvent(2949, 2, "PalemaneTanner_LeaveCombat")
--Wolves
function Wolves_OnCombat(pUnit, Event)
pUnit:RegisterEvent("Wolves_Bite", 5000, 0)
pUnit:RegisterEvent("Wolves_Howl", 9000, 1)
end
function Wolves_Bite(pUnit, Event)
pUnit:FullCastSpellOnTarget(17255, pUnit:GetClosestPlayer())
end
function Wolves_Howl(pUnit, Event)
pUnit:FullCastSpellOnTarget(5781, pUnit:GetClosestPlayer())
end
function Wolves_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(2959, 1, "Wolves_OnCombat")
RegisterUnitEvent(2959, 2, "Wolves_LeaveCombat")
RegisterUnitEvent(2958, 1, "Wolves_OnCombat")
RegisterUnitEvent(2958, 2, "Wolves_LeaveCombat")
RegisterUnitEvent(2960, 1, "Wolves_OnCombat")
RegisterUnitEvent(2960, 2, "Wolves_LeaveCombat")
--SnaggleSpear -> Elite
function SnaggleSpear_OnCombat(pUnit, Event)
pUnit:RegisterEvent("SnaggleSpear_Net", 6000, 1)
end
function SnaggleSpear_Net(pUnit, Event)
pUnit:FullCastSpellOnTarget(12024, pUnit:GetClosestPlayer())
end
function SnaggleSpear_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(5786, 1, "SnaggleSpear_OnCombat")
RegisterUnitEvent(5786, 2, "SnaggleSpear_LeaveCombat")
--Swoop
function Swoop_OnCombat(pUnit, Event)
pUnit:RegisterEvent("Swoop_Swoop", 6000, 0)
end
function Swoop_Swoop(pUnit, Event)
pUnit:FullCastSpell(5708)
end
function Swoop_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(2969, 1, "Swoop_OnCombat")
RegisterUnitEvent(2969, 2, "Swoop_LeaveCombat")
RegisterUnitEvent(2970, 1, "Swoop_OnCombat")
RegisterUnitEvent(2970, 2, "Swoop_LeaveCombat")
RegisterUnitEvent(2971, 1, "Swoop_OnCombat")
RegisterUnitEvent(2971, 2, "Swoop_LeaveCombat")
--The Rake -> Elite
function Rake_OnCombat(pUnit, Event)
pUnit:RegisterEvent("Rake_Tear", 7000, 1)
end
function Rake_Tear(pUnit, Event)
pUnit:FullCastSpellOnTarget(12166, pUnit:GetClosestPlayer())
end
function Rake_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(5807, 1, "Rake_OnCombat")
RegisterUnitEvent(5807, 2, "Rake_LeaveCombat")
--Venture Co. Supervisor
function Supervisor_OnCombat(pUnit, Event)
pUnit:RegisterEvent("Supervisor_shout", 7000, 1)
end
function Supervisor_shout(pUnit, Event)
pUnit:FullCastSpell(6673)
end
function Supervisor_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(2979, 1, "Supervisor_OnCombat")
RegisterUnitEvent(2979, 2, "Supervisor_LeaveCombat")
--Windfury Matriach
function Matr_OnCombat(pUnit, Event)
pUnit:RegisterEvent("Matr_Wave", 12000, 1)
pUnit:RegisterEvent("Matr_Bolt", 3000, 0)
end
function Matr_Wave(Unit, Event)
Unit:FullCastSpell(332)
end
function Matr_Bolt(pUnit, Event)
pUnit:FullCastSpellOnTarget(9532, pUnit:GetClosestPlayer())
end
function Matr_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(2965, 1, "Matr_OnCombat")
RegisterUnitEvent(2965, 2, "Matr_LeaveCombat")
--Windfury Sorceress
function Sorceress_OnCombat(pUnit, Event)
pUnit:RegisterEvent("Sorcer_Bolt", 3000, 0)
end
function Sorcer_Bolt(pUnit, Event)
pUnit:FullCastSpellOnTarget(13322, pUnit:GetClosestPlayer())
end
function Sorceress_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(2964, 1, "Sorceress_OnCombat")
RegisterUnitEvent(2964, 2, "Sorceress_LeaveCombat")
--Windfury Wind Witch
function WindWitch_OnCombat(pUnit, Event)
pUnit:RegisterEvent("WindWitch_Wave", 12000, 1)
pUnit:RegisterEvent("Matr_Bolt", 3000, 0)
end
function WindWitch_Wave(pUnit, Event)
pUnit:FullCastSpell(6982)
end
function WindWitch_Bolt(pUnit, Event)
pUnit:FullCastSpellOnTarget(9532, pUnit:GetClosestPlayer())
end
function WindWitch_LeaveCombat(Unit, Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(2963, 1, "WindWitch_OnCombat")
RegisterUnitEvent(2963, 2, "WindWitch_LeaveCombat")
|
local MainMenu = {}
local crystalW = 226;
local crystalH = 512;
local maskExpansionTime = 350;
local popInTime = 550;
function MainMenu:new(rootGroup,contentGroup, context, returningFromGame)
local newMainMenu = {};
setmetatable(newMainMenu, self);
self.__index = self;
newMainMenu.rootGroup =rootGroup;
newMainMenu.contentGroup = contentGroup;
newMainMenu.context = context;
newMainMenu.uiConst = context.uiConst;
newMainMenu.bounds = context.displayBounds;
if(context.settings.language == nil) then
require("ui.main.LanguageSelector"):new(rootGroup, context,
function(langCode)
--print("TODO actually set the language!!")
context:setLanguage(langCode);
newMainMenu:init();
end);
else
newMainMenu:init(returningFromGame);
end
-- log event to analytics
context:analyticslogEvent("MainMenu");
return newMainMenu;
end
function MainMenu:init(returningFromGame)
-- add layers
self.g = display.newGroup(); -- main group
self.contentGroup:insert(self.g);
self.backLayer = display.newGroup();
self.g:insert(self.backLayer);
self.gameMapLayer = display.newGroup();
self.g:insert(self.gameMapLayer);
self.aboveGameMapLayer = display.newGroup();
self.g:insert(self.aboveGameMapLayer);
self.uiLayer = display.newGroup();
self.g:insert(self.uiLayer);
self.aboveUi = display.newGroup();
self.g:insert(self.aboveUi);
local showUI = true; -- turns ui on and off, useful for generating promo images
if(showUI)then
-- add game world map
self:addGameWorld();
-- add menu items
self:addMenuItems();
-- add
self:addSoundOptionsBtns()
end
-- add efects and animations
self.backAnim = require("ui.main.BackAnim"):new(self.backLayer,self.context);
--self.aboveGameMapLayer
self:frontEffects();
-- add touch/swipe input
-- touch/tap map events
if(showUI)then
local sideMargin = self.bounds.width*0.5;
local bounds = self.bounds;
local limits = {
minX = -(self.gameWorld.w-bounds.width+math.abs(bounds.minX)+sideMargin), maxX = bounds.minX+sideMargin,--sideMargin,
minY = 0, maxY=0,
minScale=1,1
};
self.playerInput = require("input.PlayerInput"):new(self.context, self.backLayer, self.gameMapLayer, nil, limits);
end
--display.newCircle(self.gameMapLayer, self.gameWorld.w, self.bounds.centerY, 5);
--display.newCircle(self.gameMapLayer, 0, self.bounds.centerY, 5);
self:startExpansionEffect()
self:popInContent();
-- decide whenewer show 'please rate me window...'
local settings = self.context.settings;
local rateMeWinShownsCount = settings.rateMeWinShownsCount;
if(rateMeWinShownsCount == nil) then
rateMeWinShownsCount = 0;
settings.rateMeWinShownsCount = 0;
elseif (rateMeWinShownsCount > 5) then
settings.canShowRateMeWin = false;
end
-- save settings to persistent memory
self.context.settingsIO:persistSettings();
if(returningFromGame and settings.runCount > 1 and settings.canShowRateMeWin) then
require("ui.win.RateMePane"):new(self.uiLayer, self.context);
end
end
function MainMenu:destroy()
--print("MainMenu:destroy()")
if(self.backAnim) then
self.backAnim:destroy();
self.backAnim = nil;
end
if(self.gameWorld) then
self.gameWorld:destroy();
self.gameWorld = nil;
end
if(self.g) then
self.g:removeSelf();
self.g = nil;
transition.cancel();
end
end
function MainMenu:popInContent()
--self.backLayer.alpha = 0;
--transition.to(self.backLayer, {alpha=1, time=popInTime, transition = easing.inOutSine});
self.gameMapLayer.alpha = 0;
transition.to(self.gameMapLayer, {alpha =1, time=popInTime, delay=maskExpansionTime, transition = easing.inOutSine});
self.uiLayer.alpha = 0;
transition.to(self.uiLayer, {alpha=1, time=popInTime, delay = maskExpansionTime, transition = easing.inOutSine});
end
function MainMenu:startExpansionEffect()
local bounds = self.bounds;
local startMask = graphics.newMask("img/comm/start_mask.png");
local maskSize = 128;
local overExpansionRatio = 1.6;
local maxScaleX = overExpansionRatio*bounds.width / maskSize;
local maxScaleY = maxScaleX--overExpansionRatio*bounds.height / maskSize;
local minSize = 100;
local minScale = minSize/maskSize;
self.rootGroup:setMask(startMask);
self.rootGroup.maskX = bounds.centerX;
self.rootGroup.maskY = bounds.centerY;
self.rootGroup.maskScaleX = minScale;
self.rootGroup.maskScaleY = minScale;
transition.to(self.rootGroup, {maskScaleX=maxScaleX, maskScaleY=maxScaleY, time=maskExpansionTime, onComplete =
function()
self.rootGroup:setMask(nil);
end
})
end
function MainMenu:addBackground()
local bounds = self.bounds;
self.backMargin = self.bounds.height*0.05;
local w = bounds.width-2*self.backMargin;
local h = bounds.height-2*self.backMargin;
local textureSize = 512;
display.setDefault( "textureWrapX", "repeat" )
display.setDefault( "textureWrapY", "repeat" )
--[[
local back = display.newPolygon(self.backLayer, bounds.centerX, bounds.centerY,
{isoGrid.minX, isoGrid.centerY, isoGrid.centerX, isoGrid.minY, isoGrid.maxX, isoGrid.centerY, isoGrid.centerX, isoGrid.maxY}
);
]]
local back = display.newRect(self.backLayer, bounds.centerX, bounds.centerY,w,h);
back.fill = {type="image", filename= "img/back.png"}
--back:setFillColor(0.5,0.5)
--local s = textureSize/isoGrid.width; print("W: " .. isoGrid.width .. ", S:" .. s .. "repeated:" .. 1/s .." times")
back.fill.scaleX = textureSize/w;
back.fill.scaleY = textureSize/h;
back.blendMode = "add";
back.alpha = self.uiConst.mapBackgroundAlpha;-- 0.4;
display.setDefault( "textureWrapX", "clampToEdge" )
display.setDefault( "textureWrapY", "clampToEdge" )
-- add crystal
local img = display.newImageRect(self.backLayer, "img/mm/crystal.png", crystalW, crystalH);
img.x = bounds.minX + 0.5*crystalW;
img.y = bounds.maxY - 0.5*crystalH;
end
--[[
function MainMenu:addGameLogo()
local layer = self.uiLayer;
local bounds = self.bounds;
local uiConst = self.uiConst;
local cy = bounds.minY + bounds.height*0.3*0.5;
local cx = bounds.centerX;
local label = display.newText{ -- game name
text= self.context.textSource:getText("mm.gameName"),
parent = layer,
x = cx,--left+margin,--cx,
y = cy,
--width = labelW,
height = 0,
font= uiConst.fontName,
fontSize = uiConst.hugeFontSize,
align = "center",
}
label:setFillColor(unpack(uiConst.highlightedFontColor));
end
]]
function MainMenu:addSoundOptionsBtns()
local g = display.newGroup();
self.uiLayer:insert(g);
local bounds = self.bounds;
local uiConst = self.uiConst;
local margin = uiConst.defaultMargin;
local soundSettings = self.context.settings.soundSettings;
local h = 64;
local x = bounds.minX;
local y = bounds.maxY - 0.5*h - margin;
local w = 36;
local disColor = {0.75,0.1,0.1}; --uiConst.defBtnFillColor.over
local m = math.max(w,h);
local cx = x + 0.5*m + margin;
local musicIcon = display.newImageRect(g,"img/ui/music.png", w, h);
musicIcon.x = cx;
musicIcon.y = y;
musicIcon:setFillColor(unpack(uiConst.defBtnFillColor.default))
musicIcon.blendMode = "add";
local musicDisabled = display.newImageRect(g,"img/ui/disabled.png", h, h);
musicDisabled.x = cx;
musicDisabled.y = y;
musicDisabled:setFillColor(unpack(disColor))
musicDisabled.blendMode = "add";
if(soundSettings.music) then musicDisabled.isVisible = false; end;
self.musicDisabledIcon = musicDisabled;
local musicBct = display.newRect(g, cx, y, m , m);
musicBct:addEventListener("tap", function() return self:onMusicOnOff() end);
musicBct.isVisible = false;
musicBct.isHitTestable = true;
x= x+ math.max(w,h) + margin;
w = 57;
m= math.max(w,h);
cx = x + 0.5*m + margin;
local soundIcon = display.newImageRect(g,"img/ui/sound.png", w, h);
soundIcon.x = cx;
soundIcon.y = y;
soundIcon:setFillColor(unpack(uiConst.defBtnFillColor.default))
soundIcon.blendMode = "add";
local soundDisabled = display.newImageRect(g,"img/ui/disabled.png", h, h);
soundDisabled.x = cx;
soundDisabled.y = y;
soundDisabled:setFillColor(unpack(disColor))
soundDisabled.blendMode = "add";
if(soundSettings.sound) then soundDisabled.isVisible = false; end;
self.soundDisabledIcon = soundDisabled;
local soundBtn = display.newRect(g, cx, y, m , m);
soundBtn:addEventListener("tap", function() return self:onSoundOnOff() end);
soundBtn.isVisible = false;
soundBtn.isHitTestable = true;
end
function MainMenu:onMusicOnOff()
local soundSettings = self.context.settings.soundSettings --{sound=true, soundVolume = 0.5, music=true, musicVolume=0.3};
local soundManager = self.context.soundManager;
if(soundSettings.music)then
-- turn music off
soundSettings.music = false;
soundManager:stopMusic();
self.musicDisabledIcon.isVisible = true;
else
-- turn music on
soundSettings.music = true;
soundManager:playMusic();
self.musicDisabledIcon.isVisible = false;
end
Runtime:dispatchEvent({name="soundrequest", type="button"}); -- play button sound
-- save settings to persistent memory
self.context.settingsIO:persistSettings();
return true;
end
function MainMenu:onSoundOnOff()
local soundSettings = self.context.settings.soundSettings --{sound=true, soundVolume = 0.5, music=true, musicVolume=0.3};
--local soundManager = self.context.soundManager;
if(soundSettings.sound)then
-- turn music off
soundSettings.sound = false;
--soundManager:stopMusic();
self.soundDisabledIcon.isVisible = true;
else
-- turn music on
soundSettings.sound = true;
--soundManager:playMusic();
self.soundDisabledIcon.isVisible = false;
end
Runtime:dispatchEvent({name="soundrequest", type="button"}); -- play button sound
-- save settings to persistent memory
self.context.settingsIO:persistSettings();
return true;
end
function MainMenu:addMenuItems()
local g = self.uiLayer;
local bounds = self.bounds;
local uiConst = self.uiConst;
local margin = uiConst.defaultMargin;
local textSource = self.context.textSource;
local btnH = uiConst.defaultSmallBtnHeight; --uiConst.defaultBigBtnHeight;
local btnW = 4*btnH;
local backH = btnH + 2*margin;
--local backW = bounds.width;
local cy = bounds.maxY - backH*0.5; --bounds.minY + bounds.height*0.4;
--local cx = bounds.centerX;
local w = bounds.width;-- - 2*self.backMargin;
local itemTexts = {"rateme.mmButtonText", "mm.about"}; --"mm.help"
local itemActions = {"onRateMeBtn", "onAboutBtn"};
local img = self.context.img;
--add backgound
--local uiUtils = require("ui.uiUtils");
--local back = uiUtils.newUiBackRect(g, cx, cy, backW, backH, self.context, 0, false);
--back.alpha = 0.4;
-- add top rim
--local backTop = bounds.maxY - backH;
--local rim = display.newLine(g, bounds.minX, backTop, bounds.maxX, backTop);
--rim.strokeWidth = 16;
--rim.stroke = {type="image", filename="img/comm/rim_stroke.png"}
--rim.blendMode ="multiply";
--local btnMargin = (w - #itemTexts*btnW)/;
local dx = btnW+2*margin--((w - #itemTexts*btnW) / (#itemTexts+1)) + btnW;
local btnX = bounds.maxX - #itemTexts*dx +0.5*btnW -margin --bounds.minX + margin + dx-0.5*btnW;
for i=1, #itemTexts do
-- creates new rounded rectangle shape button
-- params: {group=display group, top=um, left= num, cx=num, cy = num,
-- onAction=function(event), w= num, h=num, label=string, labelColor= see widgets docs, fontSize = optional font size}
-- either 'top' 'left' or 'cx' 'cy' has to be specified
-- w,h - optional width and height parameters, button is scaled according to size of default image if not supplied
img:newBtn
{
group=g, cx=btnX, cy = cy,
w= btnW, h=btnH,
label=textSource:getText(itemTexts[i]),
--labelColor= see widgets docs,
fontSize = uiConst.normalFontSize, lightness = 0.1,
onAction=function() self:onMenuItemAction(itemActions[i]) end
}
btnX = btnX + dx;
end
end
function MainMenu:onMenuItemAction(actionName)
Runtime:dispatchEvent({name="soundrequest", type="button"}); -- play button sound
if(actionName == "onAboutBtn") then
require("ui.main.About"):new(self.aboveUi, self.context);
elseif (actionName == "onRateMeBtn") then
require("ui.win.RateMePane"):new(self.uiLayer, self.context);
else
print("Unimplemented main menu item action: " .. tostring(actionName))
end
-- log event to analytics
self.context:analyticslogEvent(actionName);
end
function MainMenu:addGameWorld()
self.gameWorld = require("ui.main.map.GameWorld"):new(self.gameMapLayer, self.backLayer, self.context,
function(mapName) self:onPlay(mapName); end
);
end
function MainMenu:onPlay(mapName)
--print("MainMenu:onPlay(), mapIndex: " .. tostring(mapName));
Runtime:dispatchEvent({name="soundrequest", type="button"}); -- play button sound
-- remove main menu UI
self:destroy();
-- start new game ...
local game = require("game.game");
game:createGame(self.rootGroup, self.contentGroup,self.context, mapName);
game:startGame();
end
function MainMenu:frontEffects()
--print("TODO MainMenu:frontEffects()");
--ewMainMenu.context = context;
local uiConst = self.uiConst;
local bounds = self.bounds;
-- add front rectangle
local rect = display.newRect(self.aboveGameMapLayer, bounds.centerX, bounds.centerY, bounds.width, bounds.height);
rect.fill = {
type = "gradient",
color1 = { 0.5,0.3,0.3,1 },
color2 = { 0.1,0.1,0.5,1 },
direction = "down"
}
--rect.fill.rotation = 45;
--print(tostring(rect.fill));
--transition.to(rect.fill.color1)
rect.alpha = 0.2;
rect.blendMode = "add";
-- add vingnetation
--[[
local rectVig = display.newRect(self.aboveGameMapLayer, bounds.centerX, bounds.centerY, bounds.width, bounds.height);
--rectVig.alpha = 0.5;
rectVig:setFillColor(1, 0.0);
rectVig.fill.effect = "filter.vignette";
rectVig.fill.effect.radius = 0.1;
]]
end
return MainMenu;
|
cf.suffuse = function(pos)
minetest.add_particlespawner({
amount = 1,
time = 0.1,
minpos = {x=pos.x-0.2, y=pos.y-0.4, z=pos.z-0.2},
maxpos = {x=pos.x+0.2, y=pos.y-0.4, z=pos.z+0.2},
minvel = {x=0, y=0, z=0},
maxvel = {x=0, y=0.01, z=0},
minacc = {x=0, y=0, z=0},
maxacc = {x=0, y=1, z=0},
minexptime = 0.1,
maxexptime = 0.4,
minsize = 10,
maxsize = 30,
collisiondetection = false,
collision_removal = false,
vertical = true,
texture = "smash1.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 0.3},
{
type = "sheet_2d",
frames_w = 1,
frames_h = 18,
frame_length = 0.6,
},
glow = 4
})
end
cf.spark1 = function(pos)
local dest = minetest.find_node_near(pos,1,tm.."vestibule")
if dest then
local dist = vector.multiply(vector.direction(pos, dest),{x = 2, y = 1, z = 2})
minetest.add_particlespawner({
amount = 3,
time = 1,
minpos = {x=pos.x, y=pos.y + 0.06, z=pos.z},
maxpos = {x=pos.x, y=pos.y + 0.06, z=pos.z},
minvel = {x=0, y=0, z=0},
maxvel = dist,
minacc = {x=0, y=0, z=0},
maxacc = {x=0, y=1, z=0},
minexptime = 0.5,
maxexptime = 0.5,
minsize = 0.6,
maxsize = 1,
collisiondetection = false,
collision_removal = false,
vertical = true,
texture = "luxion_anim.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 0.8},
{
type = "sheet_2d",
frames_w = 1,
frames_h = 6,
frame_length = 0.6,
},
glow = 4
})
else end
end
cf.cone = function(pos,tex,r)
local x, z = pos.x, pos.z
for i = 1, 360, 4 do
local ang = i * math.pi / 180
local ptx, ptz = x + r * math.cos(ang), z + r * math.sin(ang)
minetest.add_particlespawner({
amount = 1,
time = 1,
minpos = {x=ptx, y=pos.y, z=ptz},
maxpos = {x=ptx, y=pos.y, z=ptz},
minvel = {x = 0, y =0.6, z = 0},
maxvel = {x = 0, y=1.0, z= 0},
minacc = {x = 0, y = 0.7, z = 0},
maxacc = {x=0, y=0, z=0},
minexptime = 0.6,
maxexptime = 1,
minsize = 0.8,
maxsize = 1.8,
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 0.8},
{
type = "sheet_2d",
frames_w = 1,
frames_h = 18,
frame_length = 0.8,
},
collisiondetection = true,
collision_removal = true,
vertical = true,
texture = tex,
glow = 8
})
end
end |
--[[
libs
--]]
--[[--
载入一个模块
import() 与 require() 功能相同,但具有一定程度的自动化特性。
假设我们有如下的目录结构:
~~~
app/
app/classes/
app/classes/MyClass.lua
app/classes/MyClassBase.lua
app/classes/data/Data1.lua
app/classes/data/Data2.lua
~~~
MyClass 中需要载入 MyClassBase 和 MyClassData。如果用 require(),MyClass 内的代码如下:
~~~ lua
local MyClassBase = require("app.classes.MyClassBase")
local MyClass = class("MyClass", MyClassBase)
local Data1 = require("app.classes.data.Data1")
local Data2 = require("app.classes.data.Data2")
~~~
假如我们将 MyClass 及其相关文件换一个目录存放,那么就必须修改 MyClass 中的 require() 命令,否则将找不到模块文件。
而使用 import(),我们只需要如下写:
~~~ lua
local MyClassBase = import(".MyClassBase")
local MyClass = class("MyClass", MyClassBase)
local Data1 = import(".data.Data1")
local Data2 = import(".data.Data2")
~~~
当在模块名前面有一个"." 时,import() 会从当前模块所在目录中查找其他模块。因此 MyClass 及其相关文件不管存放到什么目录里,我们都不再需要修改 MyClass 中的 import() 命令。这在开发一些重复使用的功能组件时,会非常方便。
我们可以在模块名前添加多个"." ,这样 import() 会从更上层的目录开始查找模块。
~
不过 import() 只有在模块级别调用(也就是没有将 import() 写在任何函数中)时,才能够自动得到当前模块名。如果需要在函数中调用 import(),那么就需要指定当前模块名:
~~~ lua
# MyClass.lua
# 这里的 ... 是隐藏参数,包含了当前模块的名字,所以最好将这行代码写在模块的第一行
local CURRENT_MODULE_NAME = ...
local function testLoad()
local MyClassBase = import(".MyClassBase", CURRENT_MODULE_NAME)
# 更多代码
end
~~~
@param string moduleName 要载入的模块的名字
@param [string currentModuleName] 当前模块名
@return module
]]
function import(moduleName, currentModuleName)
local currentModuleNameParts
local moduleFullName = moduleName
local offset = 1
while true do
if string.byte(moduleName, offset) ~= 46 then -- .
moduleFullName = string.sub(moduleName, offset)
if currentModuleNameParts and #currentModuleNameParts > 0 then
moduleFullName = table.concat(currentModuleNameParts, ".") .. "." .. moduleFullName
end
break
end
offset = offset + 1
if not currentModuleNameParts then
if not currentModuleName then
local n,v = debug.getlocal(3, 1)
currentModuleName = v
end
currentModuleNameParts = string.split(currentModuleName, ".")
end
table.remove(currentModuleNameParts, #currentModuleNameParts)
end
return require(moduleFullName)
end
require("libs.cocos.init")
require("libs.quick.framework.init")
require("libs.libzq.init")
|
require("firecast.lua");
local __o_rrpgObjs = require("rrpgObjs.lua");
require("rrpgGUI.lua");
require("rrpgDialogs.lua");
require("rrpgLFM.lua");
require("ndb.lua");
require("locale.lua");
local __o_Utils = require("utils.lua");
local function constructNew_frmFicha_HdA2_svg()
local obj = GUI.fromHandle(_obj_newObject("form"));
local self = obj;
local sheet = nil;
rawset(obj, "_oldSetNodeObjectFunction", rawget(obj, "setNodeObject"));
function obj:setNodeObject(nodeObject)
sheet = nodeObject;
self.sheet = nodeObject;
self:_oldSetNodeObjectFunction(nodeObject);
end;
function obj:setNodeDatabase(nodeObject)
self:setNodeObject(nodeObject);
end;
_gui_assignInitialParentForForm(obj.handle);
obj:beginUpdate();
obj:setName("frmFicha_HdA2_svg");
obj:setAlign("client");
obj:setTheme("light");
obj:setMargins({top=1});
obj.scrollBox1 = GUI.fromHandle(_obj_newObject("scrollBox"));
obj.scrollBox1:setParent(obj);
obj.scrollBox1:setAlign("client");
obj.scrollBox1:setName("scrollBox1");
obj.rectangle1 = GUI.fromHandle(_obj_newObject("rectangle"));
obj.rectangle1:setParent(obj.scrollBox1);
obj.rectangle1:setWidth(1077);
obj.rectangle1:setHeight(1474);
obj.rectangle1:setColor("white");
obj.rectangle1:setName("rectangle1");
obj.image1 = GUI.fromHandle(_obj_newObject("image"));
obj.image1:setParent(obj.rectangle1);
obj.image1:setLeft(0);
obj.image1:setTop(0);
obj.image1:setWidth(1077);
obj.image1:setHeight(1474);
obj.image1:setSRC("/Ficha_HdA/images/2.png");
obj.image1:setStyle("stretch");
obj.image1:setOptimize(true);
obj.image1:setName("image1");
obj.layout1 = GUI.fromHandle(_obj_newObject("layout"));
obj.layout1:setParent(obj.rectangle1);
obj.layout1:setLeft(75);
obj.layout1:setTop(119);
obj.layout1:setWidth(453);
obj.layout1:setHeight(748);
obj.layout1:setName("layout1");
obj.textEditor1 = GUI.fromHandle(_obj_newObject("textEditor"));
obj.textEditor1:setParent(obj.layout1);
obj.textEditor1:setLeft(0);
obj.textEditor1:setTop(0);
obj.textEditor1:setWidth(453);
obj.textEditor1:setHeight(748);
obj.textEditor1:setFontSize(18);
obj.textEditor1:setFontColor("#000000");
obj.textEditor1:setField("PERSONAGENS");
obj.textEditor1:setTransparent(true);
obj.textEditor1:setName("textEditor1");
obj.layout2 = GUI.fromHandle(_obj_newObject("layout"));
obj.layout2:setParent(obj.rectangle1);
obj.layout2:setLeft(561);
obj.layout2:setTop(119);
obj.layout2:setWidth(453);
obj.layout2:setHeight(348);
obj.layout2:setName("layout2");
obj.textEditor2 = GUI.fromHandle(_obj_newObject("textEditor"));
obj.textEditor2:setParent(obj.layout2);
obj.textEditor2:setLeft(0);
obj.textEditor2:setTop(0);
obj.textEditor2:setWidth(453);
obj.textEditor2:setHeight(348);
obj.textEditor2:setFontSize(18);
obj.textEditor2:setFontColor("#000000");
obj.textEditor2:setField("FEITICOS");
obj.textEditor2:setTransparent(true);
obj.textEditor2:setName("textEditor2");
obj.layout3 = GUI.fromHandle(_obj_newObject("layout"));
obj.layout3:setParent(obj.rectangle1);
obj.layout3:setLeft(562);
obj.layout3:setTop(547);
obj.layout3:setWidth(453);
obj.layout3:setHeight(317);
obj.layout3:setName("layout3");
obj.textEditor3 = GUI.fromHandle(_obj_newObject("textEditor"));
obj.textEditor3:setParent(obj.layout3);
obj.textEditor3:setLeft(0);
obj.textEditor3:setTop(0);
obj.textEditor3:setWidth(453);
obj.textEditor3:setHeight(317);
obj.textEditor3:setFontSize(18);
obj.textEditor3:setFontColor("#000000");
obj.textEditor3:setField("NOTAS");
obj.textEditor3:setTransparent(true);
obj.textEditor3:setName("textEditor3");
obj.layout4 = GUI.fromHandle(_obj_newObject("layout"));
obj.layout4:setParent(obj.rectangle1);
obj.layout4:setLeft(76);
obj.layout4:setTop(941);
obj.layout4:setWidth(942);
obj.layout4:setHeight(463);
obj.layout4:setName("layout4");
obj.textEditor4 = GUI.fromHandle(_obj_newObject("textEditor"));
obj.textEditor4:setParent(obj.layout4);
obj.textEditor4:setLeft(0);
obj.textEditor4:setTop(0);
obj.textEditor4:setWidth(942);
obj.textEditor4:setHeight(463);
obj.textEditor4:setFontSize(18);
obj.textEditor4:setFontColor("#000000");
obj.textEditor4:setField("DIARIO");
obj.textEditor4:setTransparent(true);
obj.textEditor4:setName("textEditor4");
function obj:_releaseEvents()
end;
obj._oldLFMDestroy = obj.destroy;
function obj:destroy()
self:_releaseEvents();
if (self.handle ~= 0) and (self.setNodeDatabase ~= nil) then
self:setNodeDatabase(nil);
end;
if self.textEditor3 ~= nil then self.textEditor3:destroy(); self.textEditor3 = nil; end;
if self.textEditor4 ~= nil then self.textEditor4:destroy(); self.textEditor4 = nil; end;
if self.layout3 ~= nil then self.layout3:destroy(); self.layout3 = nil; end;
if self.textEditor2 ~= nil then self.textEditor2:destroy(); self.textEditor2 = nil; end;
if self.layout1 ~= nil then self.layout1:destroy(); self.layout1 = nil; end;
if self.scrollBox1 ~= nil then self.scrollBox1:destroy(); self.scrollBox1 = nil; end;
if self.rectangle1 ~= nil then self.rectangle1:destroy(); self.rectangle1 = nil; end;
if self.layout2 ~= nil then self.layout2:destroy(); self.layout2 = nil; end;
if self.layout4 ~= nil then self.layout4:destroy(); self.layout4 = nil; end;
if self.textEditor1 ~= nil then self.textEditor1:destroy(); self.textEditor1 = nil; end;
if self.image1 ~= nil then self.image1:destroy(); self.image1 = nil; end;
self:_oldLFMDestroy();
end;
obj:endUpdate();
return obj;
end;
function newfrmFicha_HdA2_svg()
local retObj = nil;
__o_rrpgObjs.beginObjectsLoading();
__o_Utils.tryFinally(
function()
retObj = constructNew_frmFicha_HdA2_svg();
end,
function()
__o_rrpgObjs.endObjectsLoading();
end);
assert(retObj ~= nil);
return retObj;
end;
local _frmFicha_HdA2_svg = {
newEditor = newfrmFicha_HdA2_svg,
new = newfrmFicha_HdA2_svg,
name = "frmFicha_HdA2_svg",
dataType = "",
formType = "undefined",
formComponentName = "form",
title = "",
description=""};
frmFicha_HdA2_svg = _frmFicha_HdA2_svg;
Firecast.registrarForm(_frmFicha_HdA2_svg);
return _frmFicha_HdA2_svg;
|
if not MusicManager.playlist then
return
end
CustomSoundManager:CreateSourceHook("BeardLibCustomMenuTrackFix", function(name, source)
if name == "HUDLootScreen" or name == "cleanup" then
source:pre_hook("FixCustomTrack", function(event)
managers.music:attempt_play(nil, event)
end)
end
end)
function MusicManager:check_playlist(is_menu)
local playlist = is_menu and self:playlist_menu() or self:playlist()
local tracklist = is_menu and tweak_data.music.track_menu_list or tweak_data.music.track_list
for i, track in pairs(playlist) do
local exists
for _, v in pairs(tracklist) do
if v.track == track then
exists = true
end
end
if not exists then
playlist[i] = nil
managers.savefile:setting_changed()
end
end
if not is_menu then
self:check_playlist(true)
end
end
function MusicManager:stop_custom()
local source = self._xa_source
self._xa_source = nil
if source then
source:close()
end
if alive(self._player) then
self._player:parent():remove(self._player)
end
end
local orig_post = MusicManager.post_event
function MusicManager:post_event(name, ...)
if name and Global.music_manager.current_event ~= name then
if not self._skip_play then
if not self:attempt_play(nil, name, true) then
return orig_post(self, name, ...)
end
end
Global.music_manager.current_event = name
end
end
local orig_check = MusicManager.check_music_switch
function MusicManager:check_music_switch(...)
local switches = tweak_data.levels:get_music_switches()
if switches and #switches > 0 then
Global.music_manager.current_track = switches[math.random(#switches)]
if not self:attempt_play(Global.music_manager.current_track) then
return orig_check(self, ...)
end
end
end
local orig_stop = MusicManager.track_listen_stop
function MusicManager:track_listen_stop(...)
local current_event = self._current_event
local current_track = self._current_track
orig_stop(self, ...)
local success
if current_event then
self:stop_custom()
if Global.music_manager.current_event then
if self:attempt_play(nil, Global.music_manager.current_event) then
success = true
end
end
end
if current_track and Global.music_manager.current_track then
if self:attempt_play(Global.music_manager.current_track) then
success = true
end
end
if success then
Global.music_manager.source:stop()
end
end
local movie_ids = Idstring("movie")
function MusicManager:attempt_play(track, event, stop)
if event == "music_uno_fade_reset" then
return
end
if stop then
self:stop_custom()
end
local next_music
local next_event
if track and track ~= self._current_custom_track then
self._current_custom_track = nil
end
for id, music in pairs(BeardLib.MusicMods) do
if next_music then
break
end
if event == id or track == id or self._current_custom_track == id then
if music.source and (self._current_custom_track ~= id or id == event) then
next_music = music
self._current_custom_track = id
end
if music.events and event then
local event_tbl = music.events[string.split(event, "_")[3]]
if event_tbl then
next_music = music
next_event = event_tbl
self._current_custom_track = id
end
end
end
end
if next_music then
local next = next_event or next_music
local use_alt_source = next.alt_source and math.random() < next.alt_chance
local source = use_alt_source and (next.alt_start_source or next.start_source or next.alt_source) or next.start_source or next.source
if next_music.xaudio then
if not source then
BeardLib:Err("No buffer found to play for music '%s'", tostring(self._current_custom_track))
end
else
if not source or not DB:has(movie_ids, source:id()) then
BeardLib:Err("Source file '%s' is not loaded, music id '%s'", tostring(source), tostring(self._current_custom_track))
return true
end
end
local volume = next.volume or next_music.volume
self._switch_at_end = (next.start_source or next.alt_source) and {
source = (next.allow_switch or not use_alt_source) and next.source or next.alt_source,
alt_source = next.allow_switch and next.alt_source,
alt_chance = next.allow_switch and next.alt_chance,
xaudio = next_music.xaudio,
volume = volume
}
self:play(source, next_music.xaudio, volume)
return true
end
return next_music ~= nil
end
function MusicManager:play(src, use_xaudio, custom_volume)
self:stop_custom()
Global.music_manager.source:post_event("stop_all_music")
--Uncomment if unloading is ever needed
--[[if type(src) == "table" and src.module and self._last_module and self._last_module ~= src.module then
self._last_buffer.module:UnloadBuffers()
end]]
if use_xaudio then
if XAudio then
if type(src) == "table" and src.module then
if not src.buffer then
src.module:LoadBuffers()
end
if not src.buffer then
BeardLib:log("Something went wrong while trying to play the source")
return
end
src = src.buffer
self._last_module = src.module
else
self._last_module = nil
end
self._xa_source = XAudio.Source:new(src)
self._xa_source:set_type("music")
self._xa_source:set_relative(true)
self._xa_source:set_looping(not self._switch_at_end)
if custom_volume then
self._xa_source:set_volume(custom_volume)
end
else
BeardLib:log("XAduio was not found, cannot play music.")
end
elseif managers.menu_component._main_panel then
self._player = managers.menu_component._main_panel:video({
name = "music",
video = src,
visible = false,
loop = not self._switch_at_end,
})
self._player:set_volume_gain(Global.music_manager.volume)
end
end
function MusicManager:custom_update(t, dt, paused)
local gui_ply = alive(self._player) and self._player or nil
if gui_ply then
gui_ply:set_volume_gain(Global.music_manager.volume)
end
if paused then
--xaudio already pauses itself.
if gui_ply then
gui_ply:set_volume_gain(0)
gui_ply:goto_frame(gui_ply:current_frame()) --Force because the pause function is kinda broken :/
end
elseif self._switch_at_end then
if (self._xa_source and self._xa_source:is_closed()) or (gui_ply and gui_ply:current_frame() >= gui_ply:frames()) then
local switch = self._switch_at_end
self._switch_at_end = switch.alt_source and switch or nil
local source = switch.alt_source and math.random() < switch.alt_chance and switch.alt_source or switch.source
self:play(source, switch.xaudio, switch.volume)
end
end
end
--Hooks
Hooks:PostHook(MusicManager, "init", "BeardLibMusicManagerInit", function(self)
for id, music in pairs(BeardLib.MusicMods) do
if music.heist then
table.insert(tweak_data.music.track_list, {track = id})
end
if music.menu then
table.insert(tweak_data.music.track_menu_list, {track = id})
end
end
end)
Hooks:PostHook(MusicManager, "load_settings", "BeardLibMusicManagerLoadSettings", function(self)
self:check_playlist()
end)
Hooks:PostHook(MusicManager, "track_listen_start", "BeardLibMusicManagerTrackListenStart", function(self, event, track)
self:stop_custom()
local success
if track and self:attempt_play(track) then
success = true
end
if self:attempt_play(nil, event) then
success = true
end
if success then
Global.music_manager.source:stop()
end
end)
Hooks:PostHook(MusicManager, "set_volume", "BeardLibMusicManagerSetVolume", function(self, volume)
--xaudio sets its own volume
if alive(self._player) then
self._player:set_volume_gain(volume)
end
end)
Hooks:Add("MenuUpdate", "BeardLibMusicMenuUpdate", function(t, dt)
if managers.music then
managers.music:custom_update(t, dt)
end
end)
Hooks:Add("GameSetupUpdate", "BeardLibMusicUpdate", function(t, dt)
if managers.music then
managers.music:custom_update(t, dt)
end
end)
Hooks:Add("GameSetupPauseUpdate", "BeardLibMusicPausedUpdate", function(t, dt)
if managers.music then
managers.music:custom_update(t, dt, true)
end
end) |
local CreateClass = LibStub("Poncho-1.0");
TrackerHelperFrame = CreateClass("Frame", "TrackerHelperFrame", nil, nil, TrackerHelperBase);
local Frame = TrackerHelperFrame;
function Frame:OnCreate()
TrackerHelperBase.OnCreate(self);
local setWidth = self.SetWidth;
function self:SetWidth(width)
setWidth(self, width);
self.content:RefreshSize();
-- Re-anchor the frame to prevent sizing issues
self:SetPosition(self:GetPosition());
end
local setHeight = self.SetHeight;
function self:SetHeight(height)
if not self.maxHeight then
setHeight(self, self.content:GetFullHeight());
else
setHeight(self, math.min(self.content:GetFullHeight(), self.maxHeight));
end
-- Re-anchor the frame to prevent sizing issues
self:SetPosition(self:GetPosition());
self:_clampScroll();
end
local stopMovingOrSizing = self.StopMovingOrSizing;
function self:StopMovingOrSizing()
stopMovingOrSizing(self);
self:SetUserPlaced(false);
-- Re-anchor the frame to prevent sizing issues
self:SetPosition(self:GetPosition());
end
end
function Frame:OnAcquire()
self.locked = false;
self.background = TrackerHelperBackgroundFrame(self);
self:SetClipsChildren(true);
self:SetClampedToScreen(true);
self:SetFrameStrata("BACKGROUND");
self:SetSize(1, 1);
self:EnableMouseWheel(true);
self:SetMovable(true);
self:SetBackgroundColor({
r = 0.0,
g = 0.0,
b = 0.0,
a = 0.5
});
self:SetPosition(0, 400);
self:SetBackgroundVisibility(false);
self:SetLocked(false);
self:SetScript("OnMouseWheel", self.OnMouseWheel);
self:Clear();
self:SetWidth(200);
self:SetMaxHeight(500);
end
function Frame:Clear()
if self.content then
self.content:Release();
end
self.elements = {};
self.content = TrackerHelperContainer(self);
end
-- Element Creators
function Frame:Container(options)
options = options or {};
local container = TrackerHelperContainer(options.container or self.content);
container:SetMargin(options.margin);
container:SetBackgroundColor(options.backgroundColor);
if options.events then
for event, listener in pairs(options.events) do
container:AddListener(event, listener);
end
end
container:UpdateParentsHeight(container:GetFullHeight());
container:SetHidden(options.hidden);
container:SetMetadata(options.metadata);
return container;
end
function Frame:Font(options)
options = options or {};
local font = TrackerHelperFont(options.container or self.content);
font:SetMargin(options.margin);
font:SetColor(options.color);
font:SetHoverColor(options.hoverColor);
font:SetLabel(options.label);
font:SetSize(options.size or 12);
font:UpdateParentsHeight(font:GetFullHeight());
return font;
end
-- Getters & Setters
function Frame:UpdateSettings(settings)
if settings.maxHeight ~= nil then
self:SetMaxHeight(settings.maxHeight);
end
if settings.width ~= nil then
self:SetWidth(settings.width);
end
if settings.backgroundColor ~= nil then
self:SetBackgroundColor(settings.backgroundColor);
end
if settings.position ~= nil then
self:SetPosition(settings.position.x, settings.position.y);
end
if settings.backgroundVisible ~= nil then
self:SetBackgroundVisibility(settings.backgroundVisible);
end
if settings.locked ~= nil then
self:SetLocked(settings.locked);
end
end
function Frame:SetBackgroundVisibility(visible)
self.background:SetBackgroundVisibility(visible);
end
function Frame:SetBackgroundColor(backgroundColor)
self.background:SetBackgroundColor(backgroundColor);
end
function Frame:GetPosition()
local x = self:GetRight();
local y = self:GetTop();
local inversedX = x - GetScreenWidth();
local inversedY = y - GetScreenHeight();
return inversedX, inversedY;
end
function Frame:SetPosition(x, y)
if x == nil then
x = self.position.x;
end
if y == nil then
y = self.position.y;
end
self:ClearAllPoints();
self:SetPoint("TOPRIGHT", UIParent, "TOPRIGHT", x, y);
self.position = { x = x, y = y };
end
function Frame:SetMaxHeight(maxHeight)
self.maxHeight = maxHeight;
self:SetHeight(self:GetHeight());
end
function Frame:SetLocked(locked)
self.locked = locked;
if self.content then
self.content:SetLocked(locked);
end
end
-- Events
function Frame:OnMouseWheel(value)
local _, _, _, _, y = self.content:GetPoint("TOP");
self.content:SetPoint("TOP", self, 0, y + 10 * -value);
self:_clampScroll(self.content);
end
-- Helpers
function Frame:_clampScroll()
local parent = self.content:GetParent();
if self.content:GetTop() < parent:GetTop() then
self.content:SetPoint("TOP", parent, 0, 0);
elseif self.content:GetBottom() > parent:GetBottom() then
self.content:SetPoint("TOP", parent, 0, self.content:GetHeight() - parent:GetHeight());
end
end
|
CUSTOM_GOLD_PER_TICK = 2
CUSTOM_GOLD_TICK_TIME = 0.5
Gold = Gold or class({})
Events:Register("activate", function ()
GameRules:SetGoldPerTick(0)
GameRules:SetGoldTickTime(0)
GameRules:SetStartingGold(0)
GameRules:SetUseBaseGoldBountyOnHeroes(true)
end)
function Gold:UpdatePlayerGold(unitvar)
local playerId = UnitVarToPlayerID(unitvar)
if playerId and playerId > -1 then
PlayerResource:SetGold(playerId, 0, false)
PlayerTables:SetTableValue("gold", playerId, PLAYER_DATA[playerId].SavedGold)
end
end
function Gold:ClearGold(unitvar)
Gold:SetGold(unitvar, 0)
end
function Gold:SetGold(unitvar, gold)
local playerId = UnitVarToPlayerID(unitvar)
PLAYER_DATA[playerId].SavedGold = math.floor(gold)
Gold:UpdatePlayerGold(playerId)
end
function Gold:ModifyGold(unitvar, gold, bReliable, iReason)
if gold > 0 then
Gold:AddGold(unitvar, gold)
elseif gold < 0 then
Gold:RemoveGold(unitvar, -gold)
end
end
function Gold:RemoveGold(unitvar, gold)
local playerId = UnitVarToPlayerID(unitvar)
PLAYER_DATA[playerId].SavedGold = math.max((PLAYER_DATA[playerId].SavedGold or 0) - math.ceil(gold), 0)
Gold:UpdatePlayerGold(playerId)
end
function Gold:AddGold(unitvar, gold)
local playerId = UnitVarToPlayerID(unitvar)
PLAYER_DATA[playerId].SavedGold = (PLAYER_DATA[playerId].SavedGold or 0) + math.floor(gold)
Gold:UpdatePlayerGold(playerId)
end
function Gold:AddGoldWithMessage(unit, gold, optPlayerID)
local player = optPlayerID and PlayerResource:GetPlayer(optPlayerID) or PlayerResource:GetPlayer(UnitVarToPlayerID(unit))
SendOverheadEventMessage(player, OVERHEAD_ALERT_GOLD, unit, math.floor(gold), player)
Gold:AddGold(optPlayerID or unit, gold)
end
function Gold:GetGold(unitvar)
return math.floor(PLAYER_DATA[UnitVarToPlayerID(unitvar)].SavedGold or 0)
end
|
--
-- Created by IntelliJ IDEA.
-- User: nander
-- Date: 01/03/2019
-- Time: 20:57
-- To change this template use File | Settings | File Templates.
--
local renderTrain = function(from, to, travelPercentage)
local x = (from.x * (1 - travelPercentage) + to.x * (travelPercentage))
local y = (from.y * (1 - travelPercentage) + to.y * (travelPercentage))
love.graphics.circle("fill", x, y, 20)
love.graphics.setColor(1, 1, 1)
end
GETHOWFARONCURVE = function(d, x, T)
return d * (2 * math.pi * x - T * math.sin(2 * math.pi * x / T)) / (2 * T * math.pi)
end
return function()
return function(event)
for k, v in pairs(F.train) do
local route = TRAINGETROUTE(v.ID)
local from, to = GET(route.from), GET(route.to)
local length = 0
local prevPos = from.position
for k, v in ipairs(route.midpoints) do
local xd, yd = (prevPos.x - v.y), (prevPos.y - v.y)
length = length + math.sqrt(xd * xd + yd * yd)
prevPos = v
end
local xd, yd = (prevPos.x - to.position.y), (prevPos.y - to.position.y)
length = length + math.sqrt(xd * xd + yd * yd)
local d = length
local T = event.otime
local x = (event.otime - event.timeLeft)
local distTraveled = GETHOWFARONCURVE(d, x, T)
local prevPos = from.position
local legLength = 0
local early = false
local red, green, blue = math.sin(v.ID), math.sin(2 * v.ID), math.sin(3 * v.ID)
love.graphics.setColor(math.abs(red), math.abs(green), math.abs(blue))
if distTraveled < 0 then
renderTrain(from.position, from.position, 0)
else
for k, v in ipairs(route.midpoints) do
local xd, yd = (prevPos.x - v.y), (prevPos.y - v.y)
legLength = math.sqrt(xd * xd + yd * yd)
if legLength > distTraveled then
early = true
renderTrain(prevPos, v, distTraveled / legLength)
break
end
distTraveled = distTraveled - legLength
prevPos = v
end
if not early then
local v = to.position
local xd, yd = (prevPos.x - v.y), (prevPos.y - v.y)
legLength = math.sqrt(xd * xd + yd * yd)
renderTrain(prevPos, v, distTraveled / legLength)
end
end
end
end
end |
--------------------------------------------------------------------------------
-- Main Server Loader
--------------------------------------------------------------------------------
local serverTab = "Main"
setDefaultTab(serverTab)
Server = {}
Server.Extensions = {}
--------------------------------------------------------------------------------
-- Styles and Scripts to Load
--------------------------------------------------------------------------------
-- Styles - /Core/Bot/Server/Styles/
Server.Styles = {
"Main"
}
--------------------------------------------------------------------------------
-- Core - /Core/Bot/Server/
Server.Core = {
}
--------------------------------------------------------------------------------
-- Functions - /Core/Bot/Server/Functions/
Server.Functions = {
}
--------------------------------------------------------------------------------
-- Extensions - /Core/Bot/Server/Extensions/
Server.Extensions = {
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Local Loading Functions
--------------------------------------------------------------------------------
-- Load Styles
local function loadStyles(s)
return importStyle("/Core/Bot/Server/Styles/" .. s .. ".otui")
end
-- Load Core
local function loadCore(c)
return dofile("/Core/Bot/Server/" .. c .. ".lua")
end
-- Load Extensions
local function loadExtensions(e)
return dofile("/Core/Bot/Server/Extensions/" .. e .. ".lua")
end
-- Load Functions
local function loadFunctions(f)
return dofile("/Core/Bot/Server/Functions/" .. f .. ".lua")
end
--------------------------------------------------------------------------------
-- Load Styles, Core, Functions, Extensions and Main
--------------------------------------------------------------------------------
-- Load Styles
for i, s in ipairs(Server.Styles) do
loadStyles(s)
end
-- Load Core
for i, c in ipairs(Server.Core) do
loadCore(c)
end
-- Load Extensions
for i, e in ipairs(Server.Extensions) do
loadExtensions(e)
end
-- Load Functions
for i, f in ipairs(Server.Functions) do
loadFunctions(f)
end
-- Load Main (ALWAYS LOAD LAST)
loadCore("Main")
--------------------------------------------------------------------------------
|
local addonName, ns, _ = ...
local BNET_PREFIX = "(OQ)"
-- GLOBALS: BNFeaturesEnabledAndConnected, BNConnected, BNGetInfo, BNGetNumFriends, BNGetFriendInfo, BNSetCustomMessage, BNSendFriendInvite, BNGetFriendInfoByID
function ns.GetBnetFriendInfo(searchBattleTag)
searchBattleTag = searchBattleTag:lower()
for i = 1, BNGetNumFriends() do
local presenceID, _, battleTag, _, _, _, client, isOnline = BNGetFriendInfo(i)
if battleTag and battleTag:lower() == searchBattleTag then
return presenceID, isOnline, client == 'WoW'
end
end
end
-- battleTag or playerName, realmName or true to force sending to BNet, messageType, message, token, ttl
function ns.SendMessage(target, targetRealm, messageType, message, token, ttl)
if not target or not message then return end
local fullMessage = strjoin(',', 'OQ', ns.OQversion, token or ns.oq.GenerateToken('W'), ttl or ns.OQmaxPosts, messageType, message)
if targetRealm == true or (targetRealm ~= nil and targetRealm ~= ns.playerRealm) then
local presenceID
if type(target) == 'number' then
-- this is already the toon's id
presenceID = target
elseif target:find('#') then
-- get presenceID from battleTag
local isOnline, isWow
presenceID, isOnline, isWow = ns.GetBnetFriendInfo(target)
end
print('Sending message to', presenceID, target, "\n".._G.GRAY_FONT_COLOR_CODE..fullMessage.."|r")
if presenceID then
BNSendGameData(presenceID, 'OQ', fullMessage)
else
table.insert(ns.db.bntracking, { target, messageType, fullMessage })
BNSendFriendInvite(target, fullMessage)
end
else
SendAddonMessage('OQ', fullMessage, 'WHISPER', target)
end
end
local playerData
function ns.JoinQueue(leader, password)
if ns.db.queued[leader] and ns.db.queued[leader] > ns.const.status.NONE then
-- we already requested wait list slot
return
end
local target, targetRealm, battleTag = ns.oq.DecodeLeaderData(leader)
if targetRealm == ns.playerRealm then
if target == ns.playerName then return end
targetRealm = nil
else
target = battleTag
end
-- prepare message
if not playerData then
playerData = ns.oq.EncodeLeaderData(ns.playerName, ns.playerRealm, ns.playerBattleTag)
end
local premadeType = ns.db.premadeCache[leader].type
local playerStats = ns.EncodeStats(premadeType)
local password = ns.oq.EncodePassword(password)
local groupSize = 1 -- GetNumGroupMembers()
local message = strjoin(',', ns.db.premadeCache[leader].token, premadeType, groupSize, ns.oq.GenerateToken('Q', leader), playerData, playerStats, password)
-- send message
-- ns.SendMessage(target, targetRealm, 'ri', message, 'W1', 0)
ns.SendMessage(battleTag, true, 'ri', message, 'W1', 0)
ns.db.queued[leader] = ns.const.status.PENDING
ns.UpdateUI(true)
end
function ns.LeaveQueue(leader, announce)
local target, targetRealm, battleTag = ns.oq.DecodeLeaderData(leader)
if announce then
-- send message to get us out of queue
if targetRealm == ns.playerRealm then
if target == ns.playerName then return end
targetRealm = nil
else
target = battleTag
end
local message = strjoin(',', ns.db.premadeCache[leader].token, ns.db.tokens[leader])
ns.SendMessage(target, targetRealm, 'leave_waitlist', message, 'W1', 0)
else
ns.db.queued[leader] = nil
local presenceID = ns.GetBnetFriendInfo(battleTag)
if presenceID then
local presenceID, presenceName, battleTag, isBattleTagPresence, toonName, toonID, client, isOnline, lastOnline, isAFK, isDND, messageText, noteText, isRIDFriend = BNGetFriendInfoByID(presenceID)
if isBattleTagPresence and isRIDFriend and (noteText == 'OQ' or noteText == 'OQ,leader') then
BNRemoveFriend(presenceID) -- or toonID
end
end
end
end
|
#!/usr/bin/env tarantool
local fio = require('fio')
local log = require('log')
local rpc = require('cartridge.rpc')
local checks = require('checks')
local yaml = require('yaml')
local helpers = require('test.helper')
local t = require('luatest')
local g = t.group()
function g.setup()
g.server = t.Server:new({
command = helpers.entrypoint('srv_empty'),
workdir = fio.tempdir(),
net_box_port = 13301,
http_port = 8082,
net_box_credentials = {user = 'admin', password = ''},
})
g.server:start()
helpers.retrying({}, t.Server.connect_net_box, g.server)
g.server.net_box:eval([[
_G.test = require('test.unit.rpc_candidates_test')
]])
end
function g.teardown()
g.server:stop()
fio.rmtree(g.server.workdir)
end
local M = {}
local function test_remotely(fn_name, fn)
M[fn_name] = fn
g[fn_name] = function()
g.server.net_box:eval([[
local test = require('test.unit.rpc_candidates_test')
local ok, err = pcall(test[...])
if not ok then
error(err.message, 0)
end
]], {fn_name})
end
end
-------------------------------------------------------------------------------
local function apply_mocks(topology_draft)
local members = {}
local topology_cfg = {
failover = topology_draft.failover,
replicasets = {},
servers = {},
}
for _, rpl in ipairs(topology_draft) do
topology_cfg.replicasets[rpl.uuid] = {
master = rpl[rpl.leader].uuid,
roles = {
[rpl.role] = true,
}
}
for _, srv in ipairs(rpl) do
local uri = srv.uuid
topology_cfg.servers[srv.uuid] = {
uri = uri,
disabled = srv.disabled or false,
replicaset_uuid = rpl.uuid,
}
if srv.status == nil then
members[uri] = nil
else
members[uri] = {
uri = uri,
status = srv.status,
payload = {
uuid = srv.uuid,
state = srv.state,
}
}
end
end
end
local vars = require('cartridge.vars').new('cartridge.confapplier')
local ClusterwideConfig = require('cartridge.clusterwide-config')
vars.clusterwide_config = ClusterwideConfig.new({
['topology.yml'] = yaml.encode(topology_cfg)
}):lock()
local failover = require('cartridge.failover')
_G.box = {
cfg = function() end,
error = box.error,
info = {
cluster = {uuid = 'A'},
uuid = 'a1',
},
}
failover.cfg(vars.clusterwide_config)
package.loaded['membership'].get_member = function(uri)
return members[uri]
end
end
local function values(array)
if array == nil then
return nil
end
local ret = {}
for _, v in pairs(array) do
ret[v] = true
end
return ret
end
local function test_candidates(test_name, replicasets, opts, expected)
checks('string', 'table', 'table', 'nil|table')
apply_mocks(replicasets)
t.assert_equals(
values(rpc.get_candidates(unpack(opts))),
values(expected),
test_name
)
end
-------------------------------------------------------------------------------
local draft = {
[1] = {
uuid = 'A',
role = 'target-role',
leader = 1,
[1] = {
uuid = 'a1',
status = 'alive',
state = 'RolesConfigured',
},
[2] = {
uuid = 'a2',
status = 'alive',
state = 'RolesConfigured',
},
},
[2] = {
uuid = 'B',
leader = 1,
role = 'some-other-role',
[1] = {
uuid = 'b1',
status = 'alive',
state = 'RolesConfigured',
},
[2] = {
uuid = 'b2',
status = 'alive',
state = 'RolesConfigured',
},
}
}
test_remotely('test_all', function()
-------------------------------------------------------------------------------
log.info('all alive')
test_candidates('invalid-role',
draft, {'invalid-role'},
{}
)
test_candidates('-leader',
draft, {'target-role'},
{'a1', 'a2'}
)
test_candidates('+leader',
draft, {'target-role', {leader_only = true}},
{'a1'}
)
-------------------------------------------------------------------------------
draft[1][1].status = 'suspect'
log.info('a1 leader suspect')
test_candidates('-leader +healthy',
draft, {'target-role'},
{'a1', 'a2'}
)
test_candidates('+leader +healthy',
draft, {'target-role', {leader_only = true}},
{'a1'}
)
-------------------------------------------------------------------------------
draft[1][1].status = 'dead'
log.info('a1 leader died')
test_candidates('-leader -healthy',
draft, {'target-role', {healthy_only = false}},
{'a1', 'a2'}
)
test_candidates('-leader +healthy',
draft, {'target-role'},
{'a2'}
)
test_candidates('+leader -healthy',
draft, {'target-role', {leader_only = true, healthy_only = false}},
{'a1'}
)
test_candidates('+leader +healthy',
draft, {'target-role', {leader_only = true}},
{}
)
-------------------------------------------------------------------------------
draft.failover = true
log.info('failover enabled')
test_candidates('-leader -healthy',
draft, {'target-role', {healthy_only = false}},
{'a1', 'a2'}
)
test_candidates('-leader +healthy',
draft, {'target-role'},
{'a2'}
)
test_candidates('+leader -healthy',
draft, {'target-role', {leader_only = true, healthy_only = false}},
{'a2'}
)
test_candidates('+leader +healthy',
draft, {'target-role', {leader_only = true}},
{'a2'}
)
-------------------------------------------------------------------------------
draft.failover = false
log.info('failover disabled')
draft[1][1].status = 'alive'
log.info('a1 leader restored')
draft[2].role = 'target-role'
log.info('B target-role enabled')
test_candidates('-leader',
draft, {'target-role'},
{'a1', 'a2', 'b1', 'b2'}
)
test_candidates('+leader',
draft, {'target-role', {leader_only = true}},
{'a1', 'b1'}
)
-------------------------------------------------------------------------------
draft[2][1].state = 'BootError'
log.info('b1 has an error')
test_candidates('-leader -healthy',
draft, {'target-role', {healthy_only = false}},
{'a1', 'a2', 'b2', 'b1'}
)
test_candidates('-leader +healthy',
draft, {'target-role'},
{'a1', 'a2', 'b2'}
)
test_candidates('+leader -healthy',
draft, {'target-role', {leader_only = true, healthy_only = false}},
{'a1', 'b1'}
)
test_candidates('+leader +healthy',
draft, {'target-role', {leader_only = true}},
{'a1'}
)
-------------------------------------------------------------------------------
draft[1][1].disabled = true
log.info('a1 disabled')
test_candidates('-leader -healthy',
draft, {'target-role', {healthy_only = false}},
{'a2', 'b2', 'b1'}
)
test_candidates('-leader +healthy',
draft, {'target-role'},
{'a2', 'b2'}
)
test_candidates('+leader -healthy',
draft, {'target-role', {leader_only = true, healthy_only = false}},
{'b1'}
)
test_candidates('+leader +healthy',
draft, {'target-role', {leader_only = true}},
{}
)
end)
return M
|
local gift = {
{
Name = "封印",
Art = "war3mapImported\\icon_pas_Slow_Grey.blp",
_remarks = "[奇]字技,特别神奇且怪异的技能|n当前正处于封印状态",
_attr = nil,
},
{
Name = "无我",
Art = "war3mapImported\\icon_pas_Arcane_MindMastery.blp",
_attr = {
sight = "+500",
damage_reduction = "+200",
},
},
{
Name = "醍醐点化",
Art = "war3mapImported\\icon_pas_Holy_BlindingHeal.blp",
_attr = {
gold_ratio = "+50",
exp_ratio = "+50",
},
},
{
Name = "勿想冥念",
Art = "war3mapImported\\icon_pas_Arcane_StudentOfMagic.blp",
_attr = {
mana = "+1000",
int_green = "+200",
},
},
{
Name = "神的使者",
Art = "war3mapImported\\icon_pas_Holy_Absolution.blp",
_attr = {
e_god_attack = "+1",
e_god = "+30",
e_god_oppose = "+30",
},
},
}
local _used = _onItemUsed(function(evtData)
local triggerUnit = evtData.triggerUnit
local playerIndex = hplayer.index(hunit.getOwner(triggerUnit))
local hero = hhero.player_heroes[playerIndex][1] -- 兼容信使
if (hero == nil or his.deleted(hero)) then
return
end
local gt = "tao"
local fid = hslk.n2i("奇 - 封印")
if (hskill.has(hero, fid)) then
hskill.del(hero, fid)
end
if (game.playerData.gift[playerIndex][gt] ~= nil) then
hskill.del(hero, game.playerData.gift[playerIndex][gt])
end
local itemName = hitem.getName(evtData.triggerItem)
local abName = string.gsub(itemName, "秘笈:", "")
local triggerSkill = hslk.n2i(abName)
hskill.add(hero, triggerSkill)
game.playerData.gift[playerIndex][gt] = triggerSkill
heffect.toUnit("Abilities\\Spells\\Items\\AIem\\AIemTarget.mdl", hero)
echo("学会了[奇]技[" .. hcolor.green(abName) .. "]")
end)
for _, v in ipairs(gift) do
hslk_ability_empty({
Art = v.Art,
Name = "奇 - " .. v.Name,
Buttonpos_1 = 3,
Buttonpos_2 = 1,
race = "human",
_remarks = v._remarks,
_attr = v._attr,
})
end
for _, v in ipairs(gift) do
if (v._attr ~= nil) then
local _attr = table.clone(v._attr)
_attr.disabled = true
hslk_item({
Art = v.Art,
Name = "秘笈:奇 - " .. v.Name,
Ubertip = "使用习得[奇技]:" .. v.Name,
file = "Objects\\InventoryItems\\tomeBlue\\tomeBlue.mdl",
race = "human",
perishable = 1,
_type = "gift_tao",
_cooldown = 0,
_attr = _attr,
_onItemUsed = _used,
})
end
end
|
emu.keypost('RUN"CAS:"\n')
|
require("torch")
require("utils")
local tds = require("tds")
local class = require("class")
local comp = require 'pl.comprehension' . new()
local QPlayer = class("QPlayer")
function QPlayer:__init(opt)
opt = opt or {}
self.Q = tds.Hash({})
self.epsLearning = tonumber(opt.epsLearning) or 0.1
self.epsEvaluate = tonumber(opt.epsEvaluate) or 0.1
self.learningRate = tonumber(opt.learningRate) or 0.1
self.discount = tonumber(opt.discount) or 0.99
self.memorySize = tonumber(opt.memorySize) or 3
self.idxCrt = 1
self.oldStates =
comp 'table(y, "" for y)' (seq.copy(seq.range(1,self.memorySize)))
self.lastAction = nil
self.statesNo = 0
end
function QPlayer.getIndex(n, m)
return (n - 1) % m + 1
end
function QPlayer:selectAction(state, actions, isTraining)
if (not isTraining and math.random() >= self.epsEvaluate)
or (isTraining and math.random() >= self.epsLearning) then
return self:bestAction(state, actions)
else
return actions[torch.random(#actions)], 0
end
end
function QPlayer:bestAction(state, actions)
if self.memorySize > 1 then
for i = 1, self.memorySize - 1 do
for l in string.gmatch(self.oldStates[i], "%a") do
local pos = string.find(self.oldStates[i], l)
for j = i + 1, self.memorySize do
local pos2 = string.find(self.oldStates[j], l)
if pos2 and pos ~= pos2 and (string.sub(state,pos,pos) == ' '
or string.sub(state,pos2,pos2) == ' ') then
print(getString(pos, pos2))
print(self.oldStates)
return getString(pos, pos2), 0
end
end
end
end
end
local Qs = self.Q[state] or {}
local bestAction = nil
local bestQ
for a, q in pairs(Qs) do
if self.memorySize > 0 then
local ind = self.getIndex(self.idxCrt, self.memorySize)
if self.memorySize == 1 and
self.lastAction ~= getString(getNumbers(a)) then
do break end
end
else
if not bestQ or q > bestQ then
bestQ = q
bestAction = a
end
-- bestAction[1] = a
-- elseif q == bestQ then
-- bestAction[#bestAction] = a
-- end
end
end
if bestAction then
-- local ind = torch.random(#bestAction)
-- return bestAction[ind], bestQ
return bestAction, bestQ
else
return actions[torch.random(#actions)], 0
end
end
function QPlayer:getBestQ(state)
local bestQ = 0
for _, q in pairs(self.Q[state] or {}) do
if q > bestQ then
bestQ = q
end
end
return bestQ
end
function QPlayer:feedback(state, action, reward, nextState)
local ind = self.getIndex(self.idxCrt, self.memorySize)
local q = self:getBestQ(nextState)
if not self.Q[state] then
self.Q[state] = tds.Hash({})
self.statesNo = self.statesNo + 1
end
self.Q[state][action] = self.Q[state][action] or 0
self.Q[state][action] = self.Q[state][action] + self.learningRate *
(reward + self.discount * q - self.Q[state][action])
if self.memorySize >= 1 then
self.oldStates[ind] = nextState
self.lastAction = action
self.idxCrt = self.idxCrt + 1
end
end
function QPlayer:getStatesNo()
return self.statesNo
end
return QPlayer
|
local morsealphabet = {
["a"] = ".-",
["b"] = "-...",
["c"] = "-.-.",
["d"] = "-..",
["e"] = ".",
["f"] = "..-.",
["g"] = "--.",
["h"] = "....",
["i"] = "..",
["j"] = ".---",
["k"] = "-.-",
["l"] = ".-..",
["m"] = "--",
["n"] = "-.",
["o"] = "---",
["p"] = ".--.",
["q"] = "--.-",
["r"] = ".-.",
["s"] = "...",
["t"] = "-",
["u"] = "..-",
["v"] = "...-",
["w"] = ".--",
["x"] = "-..-",
["y"] = "-.--",
["z"] = "--..",
[" "] = "/"
}
local reversemorsealphabet = {}
for k,v in pairs(morsealphabet) do
reversemorsealphabet[v] = k
end
function morse.fromText(x)
x = string.lower(x)
local morsed = ""
for c in x:gmatch(".") do
if morsealphabet[c] then
morsed = morsed .. morsealphabet[c] .. " "
end
end
print(morsed)
end
function morse.toText(x)
local text = x:split(' ')
local demorsed = "";
for i = 1, #text do
local cache = reversemorsealphabet[text[i]]
if cache then
demorsed = demorsed .. cache
end
end
print(demorsed)
end
function morse.credits()
print("Original source: https://github.com/trfunk/lua/blob/master/dailyprogrammer%20%28reddit%29/%5B7%5Dmorsecode.lua")
end |
local _inspect_ = require "inspect"
local _M = {}
function _M.url_encode(s)
s = string.gsub(s, "([^%w%.%- ])", function(c) return string.format("%%%02X", string.byte(c)) end)
return string.gsub(s, " ", "+")
end
function _M.url_decode(s)
s = string.gsub(s, '%%(%x%x)', function(h) return string.char(tonumber(h, 16)) end)
return s
end
local _G_ENV = {
print = _G.print,
assert = _G.assert,
error = _G.error,
ipairs = _G.ipairs,
next = _G.next,
pairs = _G.pairs,
pcall = _G.pcall,
select = _G.select,
tonumber = _G.tonumber,
tostring = _G.tostring,
type = _G.type,
unpack = _G.unpack,
xpcall = _G.xpcall,
string = {
byte = string.byte,
char = string.char,
find = string.find,
format = string.format,
gmatch = string.gmatch,
gsub = string.gsub,
len = string.len,
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,
insert = table.insert,
concate = table.concate,
},
_inspect_ = _inspect_,
_cjson_decode_ = require('cjson').decode,
_cjson_encode_ = require('cjson').encode,
_url_encode_ = _M.url_encode,
_url_decode_ = _M.url_decode,
_log_ = function(e)
print(_inspect_(e))
ngx.log(ngx.ERR, _inspect_(e))
end,
}
function _M.sandbox_load(lua_file, local_env)
local f, message = loadfile(lua_file)
if not f then
return false, message
end
for k,v in pairs(_G_ENV) do
local_env[k] = v
end
setfenv(f, local_env)
return true, f
end
function _M.sandbox_exec(f)
return xpcall(f, function() ngx.log(ngx.ERR, debug.traceback()) end)
end
return _M
|
local Prop = {}
Prop.Name = "Nº731 Bairro Capitalista"
Prop.Cat = "House"
Prop.Price = 340
Prop.Doors = {
Vector(260, -7901, -3),
Vector(73, -7563, -2),
Vector(110, -7767, -3),
}
GM.Property:Register( Prop )
|
function update()
print("updated!")
end
|
local OnEvents = require("optpack.core.loader.event")
local OnFileTypes = {}
OnFileTypes.__index = OnFileTypes
function OnFileTypes.set(plugin_name, group_name, filetypes)
local events = vim.tbl_map(function(filetype)
return { "FileType", filetype }
end, filetypes)
OnEvents.set(plugin_name, group_name, events)
end
return OnFileTypes
|
require "date_format_europe";
require "serial_api_clock"
require "serial_api_open_weather"
require "blink"
require "scheduler"
require "credentials"
require "ram_watchdog"
function scmd.GFR()
collectgarbage()
sapi.send("RAM: " .. tostring(node.heap() / 1000))
end
local gtc = {
last_weather_sync_sec = -1,
ntpc_stat = nil,
owe_stat = nil,
text = "Initializing..... ",
update_count = 0,
last_gtc_call = -1,
print_debug = true
}
-- set debug level
function scmd.GDL(level)
if level == '0' then
log.change_level(false, false, false, false)
elseif level == '1' then
log.change_level(false, false, false, true)
elseif level == '2' then
log.change_level(false, false, true, true)
elseif level == '3' then
log.change_level(false, true, true, true)
elseif level == '4' then
log.change_level(true, true, true, true)
end
end
-- return short status for all modules.
function scmd.GSS()
local ntpc_stat = ntpc.status()
local owe_stat = owe.status()
local status = {}
if ntpc_stat == nil and owe_stat == nil then
table.insert(status, "OK")
else
if ntpc_stat ~= nil then
table.insert(status, " ")
end
if owe_stat ~= nil then
table.insert(status, owe_stat)
end
collectgarbage()
table.insert(status, "; RAM:")
table.insert(status, node.heap() / 1000)
table.insert(status, "kb")
end
sapi.send(table.concat(status))
end
-- return 1 if the text has been changed since last call, otherwise 0
function scmd.GTC()
local changed
if gtc.update_count == 0 then
changed = '1'
elseif gtc.last_gtc_call == gtc.update_count then
changed = '0'
else
changed = '1'
gtc.last_gtc_call = gtc.update_count
end
sapi.send(changed)
end
-- scrolling text for arduino
function scmd.GTX()
sapi.send(gtc.text)
end
local function generate_weather_text()
local text = {}
local ft = owe.forecast_text()
if ft ~= nil and ft:len() > 0 then
table.insert(text, ft)
end
local owe_stat = owe.status()
if owe_stat ~= nil then
table.insert(text, " >> ")
table.insert(text, owe_stat)
end
local ntpc_stat = ntpc.status()
if ntpc_stat ~= nil then
table.insert(text, " >> ")
table.insert(text, ntpc_stat)
end
if gtc.print_debug then
collectgarbage()
table.insert(text, ">> RAM:")
table.insert(text, node.heap() / 1000)
table.insert(text, "kb")
end
table.insert(text, " ")
return table.concat(text)
end
local function update_weather()
local ntpc_stat = ntpc.status()
local owe_stat = owe.status()
local last_weather_sync_sec = owe.last_sync_sec
if gtc.last_weather_sync_sec == last_weather_sync_sec and gtc.ntpc_stat == ntpc_stat and gtc.owe_stat == owe_stat then
return
end
gtc.last_weather_sync_sec = last_weather_sync_sec
gtc.ntpc_stat = ntpc_stat
gtc.owe_stat = owe_stat
local new_text = generate_weather_text()
if (new_text == gtc.text) then
if log.is_info then
log.info("INT Weather did not change")
end
else
gtc.update_count = gtc.update_count + 1
gtc.text = new_text
if log.is_info then
log.info("INT new weather:", gtc.text)
end
end
end
if log.is_info then log.info("Initializing....") end
owe.register_response_callback(update_weather)
wlan.setup(cred.ssid, cred.password)
sapi.start()
ntpc.start("pool.ntp.org")
owe.start()
blink.start()
rwd.start()
scheduler.start()
|
--------------------------------------------------
-- SneakerIdle
--------------------------
-- created: Mikko Mononen 21-6-2006
local Behavior = CreateAIBehavior("Cover2IdleST","HBaseIdle",
{
Constructor = function(self,entity)
--AI.LogEvent(entity:GetName().." Cover2Idle constructor");
entity:InitAIRelaxed();
-- set combat class
if ( entity.inventory:GetItemByClass("LAW") ) then
AI.ChangeParameter( entity.id, AIPARAM_COMBATCLASS, AICombatClasses.InfantryRPG );
else
AI.ChangeParameter( entity.id, AIPARAM_COMBATCLASS, AICombatClasses.Infantry );
end
if ( entity.AI and entity.AI.needsAlerted ) then
AI.SetBehaviorVariable(entity.id, "IncomingFire", true);
entity.AI.needsAlerted = nil;
end
-- entity:CheckWeaponAttachments();
-- entity:EnableLAMLaser(false);
end,
---------------------------------------------
OnQueryUseObject = function ( self, entity, sender, extraData )
end,
---------------------------------------------
OnEnemySeen = function( self, entity, fDistance, data )
entity:MakeAlerted();
entity:TriggerEvent(AIEVENT_DROPBEACON);
entity.AI.firstContact = true;
AI.SetBehaviorVariable(entity.id, "Attack", true);
AI_Utils:CommonEnemySeen(entity, data);
end,
---------------------------------------------
OnNoTarget = function(self,entity,sender)
end,
---------------------------------------------
OnTankSeen = function( self, entity, fDistance )
if( AI_Utils:HasRPGAttackSlot(entity) and entity.inventory:GetItemByClass("LAW")
and AIBehavior.Cover2RPGAttack.FindRPGSpot(self, entity) ~= nil) then
entity:Readibility("suppressing_fire",1,1,0.1,0.4);
AI.SetBehaviorVariable(entity.id, "RpgAttack", true);
else
entity:Readibility("explosion_imminent",1,1,0.1,0.4);
AI.SetBehaviorVariable(entity.id, "AvoidTank", true);
end
end,
---------------------------------------------
OnHeliSeen = function( self, entity, fDistance )
entity:Readibility("explosion_imminent",1,1,0.1,0.4);
AI.SetBehaviorVariable(entity.id, "AvoidTank", true);
end,
---------------------------------------------
OnTargetDead = function( self, entity )
-- called when the attention target died
entity:Readibility("target_down",1,1,0.3,0.5);
end,
--------------------------------------------------
OnNoHidingPlace = function( self, entity, sender,data )
end,
---------------------------------------------
OnBackOffFailed = function(self,entity,sender)
end,
---------------------------------------------
SEEK_KILLER = function(self, entity)
AI.SetBehaviorVariable(entity.id, "Threatened", true);
end,
---------------------------------------------
DRAW_GUN = function( self, entity )
if(not entity.inventory:GetCurrentItemId()) then
entity:HolsterItem(false);
end
end,
---------------------------------------------
OnEnemyMemory = function( self, entity )
-- called when the enemy can no longer see its foe, but remembers where it saw it last
end,
---------------------------------------------
OnSomethingSeen = function( self, entity )
-- called when the enemy sees a foe which is not a living player
entity:Readibility("idle_interest_see",1,1,0.6,1);
AI_Utils:CheckInterested(entity);
AI.SetBehaviorVariable(entity.id, "Interested", true);
AI.ModifySmartObjectStates(entity.id,"UseMountedWeaponInterested");
end,
---------------------------------------------
OnThreateningSeen = function( self, entity )
-- called when the enemy hears a scary sound
entity:Readibility("idle_interest_see",1,1,0.6,1);
entity:TriggerEvent(AIEVENT_DROPBEACON);
if(AI_Utils:IsTargetOutsideStandbyRange(entity) == 1) then
entity.AI.hurryInStandby = 0;
AI.SetBehaviorVariable(entity.id, "ThreatenedStandby", true);
else
AI.SetBehaviorVariable(entity.id, "Threatened", true);
end
AI.ModifySmartObjectStates(entity.id,"UseMountedWeaponInterested");
end,
---------------------------------------------
OnInterestingSoundHeard = function( self, entity )
-- check if we should check the sound or not.
entity:Readibility("idle_interest_hear",1,1,0.6,1);
AI_Utils:CheckInterested(entity);
AI.SetBehaviorVariable(entity.id, "Interested", true);
AI.ModifySmartObjectStates(entity.id,"UseMountedWeaponInterested");
end,
---------------------------------------------
OnThreateningSoundHeard = function( self, entity, fDistance )
-- called when the enemy hears a scary sound
entity:Readibility("idle_alert_threat_hear",1,1,0.6,1);
entity:TriggerEvent(AIEVENT_DROPBEACON);
if(AI_Utils:IsTargetOutsideStandbyRange(entity) == 1) then
entity.AI.hurryInStandby = 0;
AI.SetBehaviorVariable(entity.id, "ThreatenedStandby", true);
else
AI.SetBehaviorVariable(entity.id, "Threatened", true);
end
AI.ModifySmartObjectStates(entity.id,"UseMountedWeaponInterested");
end,
--------------------------------------------------
INVESTIGATE_BEACON = function (self, entity, sender)
entity:Readibility("ok_battle_state",1,1,0.6,1);
AI.SetBehaviorVariable(entity.id, "Threatened", true);
end,
--------------------------------------------------
OnCoverRequested = function ( self, entity, sender)
-- called when the enemy is damaged
end,
---------------------------------------------
OnDamage = function ( self, entity, sender)
-- called when the enemy is damaged
entity:Readibility("taking_fire",1,1,0.3,0.5);
entity:GettingAlerted();
end,
---------------------------------------------
OnEnemyDamage = function (self, entity, sender, data)
-- called when the enemy is damaged
entity:GettingAlerted();
entity:Readibility("taking_fire",1,1,0.3,0.5);
-- set the beacon to the enemy pos
local shooter = System.GetEntity(data.id);
if(shooter) then
AI.SetBeaconPosition(entity.id, shooter:GetPos());
else
entity:TriggerEvent(AIEVENT_DROPBEACON);
end
AI.SetBehaviorVariable(entity.id, "IncomingFire", true);
-- dummy call to this one, just to make sure that the initial position is checked correctly.
AI_Utils:IsTargetOutsideStandbyRange(entity);
AI.SetBehaviorVariable(entity.id, "Hide", true);
end,
---------------------------------------------
OnReload = function( self, entity )
-- entity:Readibility("reloading",1);
-- called when the enemy goes into automatic reload after its clip is empty
-- AI.LogEvent("OnReload()");
-- entity:SelectPipe(0,"cv_scramble");
end,
---------------------------------------------
OnBulletRain = function(self, entity, sender, data)
-- only react to hostile bullets.
-- AI.RecComment(entity.id, "hostile="..tostring(AI.Hostile(entity.id, sender.id)));
if(AI.Hostile(entity.id, sender.id)) then
entity:GettingAlerted();
if(AI.GetTargetType(entity.id)==AITARGET_NONE) then
local closestCover = AI.GetNearestHidespot(entity.id, 3, 15, sender:GetPos());
if(closestCover~=nil) then
AI.SetBeaconPosition(entity.id, closestCover);
else
AI.SetBeaconPosition(entity.id, sender:GetPos());
end
else
entity:TriggerEvent(AIEVENT_DROPBEACON);
end
entity:Readibility("bulletrain",1,1,0.1,0.4);
-- dummy call to this one, just to make sure that the initial position is checked correctly.
AI_Utils:IsTargetOutsideStandbyRange(entity);
AI.Signal(SIGNALFILTER_GROUPONLY_EXCEPT,1,"INCOMING_FIRE",entity.id);
AI.SetBehaviorVariable(entity.id, "Hide", true);
else
if(sender==g_localActor) then
entity:Readibility("friendly_fire",1,0.6,1);
entity:InsertSubpipe(AIGOALPIPE_NOTDUPLICATE,"look_at_player_5sec");
entity:InsertSubpipe(AIGOALPIPE_NOTDUPLICATE,"do_nothing"); -- make the timeout goal in previous subpipe restart if it was there already
end
end
end,
--------------------------------------------------
OnCollision = function(self,entity,sender,data)
if(AI.GetTargetType(entity.id) ~= AITARGET_ENEMY) then
if(AI.Hostile(entity.id,data.id)) then
--entity:ReadibilityContact();
entity:SelectPipe(0,"short_look_at_lastop",data.id);
end
end
end,
--------------------------------------------------
OnCloseContact = function ( self, entity, sender,data)
-- entity:InsertSubpipe(AIGOALPIPE_NOTDUPLICATE,"melee_close");
end,
---------------------------------------------
-- OnGroupMemberDied = function( self, entity, sender)
-- entity:GettingAlerted();
-- AI.Signal(SIGNALFILTER_SENDER,1,"TO_HIDE",entity.id);
-- end,
--------------------------------------------------
OnGroupMemberDied = function(self, entity, sender, data)
--AI.LogEvent(entity:GetName().." OnGroupMemberDied!");
entity:GettingAlerted();
AI.SetBehaviorVariable(entity.id, "Hide", true);
end,
--------------------------------------------------
COVER_NORMALATTACK = function (self, entity, sender)
-- entity:SelectPipe(0,"cv_scramble");
end,
--------------------------------------------------
INVESTIGATE_TARGET = function (self, entity, sender)
entity:SelectPipe(0,"cv_investigate_threat");
end,
---------------------------------------------
ENEMYSEEN_FIRST_CONTACT = function( self, entity )
if(AI.GetTargetType(entity.id) ~= AITARGET_ENEMY) then
entity:Readibility("idle_interest_see",1,1,0.6,1);
if(AI_Utils:IsTargetOutsideStandbyRange(entity) == 1) then
entity.AI.hurryInStandby = 1;
AI.SetBehaviorVariable(entity.id, "ThreatenedStandby", true);
else
AI.SetBehaviorVariable(entity.id, "Threatened", true);
end
end
end,
--------------------------------------------------
ENEMYSEEN_DURING_COMBAT = function (self, entity, sender)
entity:GettingAlerted();
if(AI.GetTargetType(entity.id) ~= AITARGET_ENEMY) then
AI.SetBehaviorVariable(entity.id, "Seek", true);
end
end,
---------------------------------------------
INCOMING_FIRE = function (self, entity, sender)
entity:GettingAlerted();
if(DistanceVectors(sender:GetPos(), entity:GetPos()) < 15.0) then
-- near to the guy who is being shot, hide!
AI.SetBehaviorVariable(entity.id, "Hide", true);
else
-- further away, threatened!
if(AI_Utils:IsTargetOutsideStandbyRange(entity) == 1) then
entity.AI.hurryInStandby = 1;
AI.SetBehaviorVariable(entity.id, "ThreatenedStandby", true);
else
AI.SetBehaviorVariable(entity.id, "Threatened", true);
end
end
end,
---------------------------------------------
TREE_DOWN = function (self, entity, sender)
entity:Readibility("bulletrain",1,1,0.1,0.4);
end,
-- OnVehicleDanger = function(self, entity, sender, signalData)
-- end,
--------------------------------------------------
OnLeaderReadabilitySeek = function(self, entity, sender)
entity:Readibility("signalMove",1,10);
end,
--------------------------------------------------
OnLeaderReadabilityAlarm = function(self, entity, sender)
entity:Readibility("signalGetDown",1,10);
end,
--------------------------------------------------
OnLeaderReadabilityAdvanceLeft = function(self, entity, sender)
entity:Readibility("signalAdvance",1,10);
end,
--------------------------------------------------
OnLeaderReadabilityAdvanceRight = function(self, entity, sender)
entity:Readibility("signalAdvance",1,10);
end,
--------------------------------------------------
OnLeaderReadabilityAdvanceForward = function(self, entity, sender)
entity:Readibility("signalAdvance",1,10);
end,
---------------------------------------------
OnFriendlyDamage = function ( self, entity, sender,data)
if(data.id==g_localActor.id) then
entity:Readibility("friendly_fire",1,1, 0.6,1);
if(entity:IsUsingPipe("stand_only")) then
entity:InsertSubpipe(AIGOALPIPE_NOTDUPLICATE,"look_at_player_5sec");
entity:InsertSubpipe(AIGOALPIPE_NOTDUPLICATE,"do_nothing"); -- make the timeout goal in previous subpipe restart if it was there already
end
end
end,
---------------------------------------------
SELECT_SEC_WEAPON = function (self, entity)
entity:SelectSecondaryWeapon();
end,
---------------------------------------------
SELECT_PRI_WEAPON = function (self, entity)
entity:SelectPrimaryWeapon();
end,
---------------------------------------------
ConstructorCover2 = function (self, entity)
entity.AI.target = {x=0, y=0, z=0};
entity.AI.targetFound = 0;
AI_Utils:SetupTerritory(entity);
AI_Utils:SetupStandby(entity);
end,
---------------------------------------------
ConstructorSneaker = function (self, entity)
entity.AI.target = {x=0, y=0, z=0};
entity.AI.targetFound = 0;
AI_Utils:SetupTerritory(entity);
AI_Utils:SetupStandby(entity);
end,
---------------------------------------------
ConstructorCamper = function (self, entity)
entity.AI.target = {x=0, y=0, z=0};
entity.AI.targetFound = 0;
AI_Utils:SetupTerritory(entity);
AI_Utils:SetupStandby(entity, true);
end,
---------------------------------------------
ConstructorLeader = function (self, entity)
entity.AI.target = {x=0, y=0, z=0};
entity.AI.targetFound = 0;
AI_Utils:SetupTerritory(entity);
AI_Utils:SetupStandby(entity);
end,
---------------------------------------------
OnShapeEnabled = function (self, entity, sender, data)
--Log(entity:GetName().."OnShapeEnabled");
if(data.iValue == AIAnchorTable.COMBAT_TERRITORY) then
AI_Utils:SetupTerritory(entity, false);
elseif(data.iValue == AIAnchorTable.ALERT_STANDBY_IN_RANGE) then
AI_Utils:SetupStandby(entity);
end
end,
---------------------------------------------
OnShapeDisabled = function (self, entity, sender, data)
--Log(entity:GetName().."OnShapeDisabled");
if(data.iValue == 1) then
-- refshape
AI_Utils:SetupStandby(entity);
elseif(data.iValue == 2) then
-- territory
AI_Utils:SetupTerritory(entity, false);
elseif(data.iValue == 3) then
-- refshape and territory
AI_Utils:SetupTerritory(entity, false);
AI_Utils:SetupStandby(entity);
end
end,
---------------------------------------------
SET_TERRITORY = function (self, entity, sender, data)
-- If the current standby area is the same as territory, clear the standby.
if(entity.AI.StandbyEqualsTerritory) then
entity.AI.StandbyShape = nil;
end
entity.AI.TerritoryShape = data.ObjectName;
newDist = AI.DistanceToGenericShape(entity:GetPos(), entity.AI.TerritoryShape, 0);
local curDist = 10000000.0;
if(entity.AI.StandbyShape) then
curDist = AI.DistanceToGenericShape(entity:GetPos(), entity.AI.StandbyShape, 0);
end
-- Log(" - curdist:"..tostring(curDist));
-- Log(" - newdist:"..tostring(newDist));
if(newDist < curDist) then
if(entity.AI.TerritoryShape) then
entity.AI.StandbyShape = entity.AI.TerritoryShape;
end
entity.AI.StandbyEqualsTerritory = true;
end
if(entity.AI.StandbyShape) then
entity.AI.StandbyValid = true;
AI.SetRefShapeName(entity.id, entity.AI.StandbyShape);
else
entity.AI.StandbyValid = false;
AI.SetRefShapeName(entity.id, "");
end
if(entity.AI.TerritoryShape) then
AI.SetTerritoryShapeName(entity.id, entity.AI.TerritoryShape);
else
AI.SetTerritoryShapeName(entity.id, "");
end
end,
---------------------------------------------
CLEAR_TERRITORY = function (self, entity, sender, data)
entity.AI.StandbyEqualsTerritory = false;
entity.AI.StandbyShape = nil;
entity.AI.TerritoryShape = nil;
AI.SetRefShapeName(entity.id, "");
AI.SetTerritoryShapeName(entity.id, "");
end,
--------------------------------------------------
OnCallReinforcements = function (self, entity, sender, data)
entity.AI.reinfSpotId = data.id;
entity.AI.reinfType = data.iValue;
-- AI.LogEvent(">>> "..entity:GetName().." OnCallReinforcements");
AI.SetBehaviorVariable(entity.id, "CallReinforcement", false);
end,
--------------------------------------------------
OnGroupChanged = function (self, entity)
-- TODO: goto the nearest group
if (AI.GetTargetType(entity.id)~=AITARGET_ENEMY) then
AI.BeginGoalPipe("cv_goto_beacon");
AI.PushGoal("locate",0,"beacon");
AI.PushGoal("approach",1,4,AILASTOPRES_USE,15,"",3);
AI.PushGoal("signal",1,1,"GROUP_REINF_DONE",0);
AI.EndGoalPipe();
entity:SelectPipe(0,"cv_goto_beacon");
end
end,
--------------------------------------------------
GROUP_REINF_DONE = function (self, entity)
AI_Utils:CommonContinueAfterReaction(entity);
end,
--------------------------------------------------
OnExposedToFlashBang = function (self, entity, sender, data)
if (data.iValue == 1) then
-- near
entity:SelectPipe(0,"sn_flashbang_reaction_flinch");
else
-- visible
entity:SelectPipe(0,"sn_flashbang_reaction");
end
end,
--------------------------------------------------
FLASHBANG_GONE = function (self, entity)
entity:SelectPipe(0,"do_nothing");
-- Choose proper action after being interrupted.
AI_Utils:CommonContinueAfterReaction(entity);
end,
--------------------------------------------------
OnExposedToSmoke = function (self, entity)
--System.Log(">>>>"..entity:GetName().." OnExposedToSmoke");
-- if (random(1,10) > 6) then
entity:Readibility("cough",1,115,0.1,4.5);
-- end
end,
---------------------------------------------
OnExposedToExplosion = function(self, entity, data)
if(data == nil)then
return;
end
self:OnCloseCollision(entity, data);
end,
---------------------------------------------
OnCloseCollision = function(self, entity, data)
AI_Utils:ChooseFlinchReaction(entity, data.point);
end,
---------------------------------------------
OnGroupMemberMutilated = function(self, entity)
-- System.Log(">>"..entity:GetName().." OnGroupMemberMutilated");
AI.SetBehaviorVariable(entity.id, "Panic", true);
end,
---------------------------------------------
OnTargetCloaked = function(self, entity)
entity:SelectPipe(0,"sn_target_cloak_reaction");
end,
---------------------------------------------
PANIC_DONE = function(self, entity)
AI.Signal(SIGNALFILTER_GROUPONLY_EXCEPT, 1, "ENEMYSEEN_FIRST_CONTACT",entity.id);
-- Choose proper action after being interrupted.
AI_Utils:CommonContinueAfterReaction(entity);
end,
--------------------------------------------------
OnOutOfAmmo = function (self,entity, sender)
entity:Readibility("reload",1,4,0.1,0.4);
if (entity.Reload == nil) then
--System.Log(" - no reload available");
do return end
end
entity:Reload();
end,
---------------------------------------------
SET_DEFEND_POS = function(self, entity, sender, data)
--System.Log(">>>>"..entity:GetName().." SET_DEFEND_POS");
if (data and data.point) then
AI.SetRefPointPosition(entity.id,data.point);
end
end,
---------------------------------------------
CLEAR_DEFEND_POS = function(self, entity, sender, data)
end,
---------------------------------------------
OnFallAndPlayWakeUp = function(self, entity, data)
-- System.Log(">>>>"..entity:GetName().." OnFallAndPlayWakeUp");
AI_Utils:CommonContinueAfterReaction(entity);
end,
})
|
--[[for i, prototype in pairs (data.raw["electric-pole"]) do
if (prototype.maximum_wire_distance >= 30 and prototype.supply_area_distance <= 5) then
prototype.max_health = 19999
end
end
for i, prototype in pairs (data.raw["straight-rail"]) do
prototype.max_health = 19999
end
for i, prototype in pairs (data.raw["curved-rail"]) do
prototype.max_health = 19999
end]]--
--[[for i, prototype in pairs (data.raw["rail-signal"]) do
prototype.max_health = 19999
end
for i, prototype in pairs (data.raw["rail-chain-signal"]) do
prototype.max_health = 19999
end]]-- |
local backgroundColor = Color(0, 0, 0, 66)
local PANEL = {}
AccessorFunc(PANEL, "maxWidth", "MaxWidth", FORCE_NUMBER)
function PANEL:Init()
self:SetWide(180)
self:Dock(LEFT)
self.maxWidth = ScrW() * 0.2
end
function PANEL:Paint(width, height)
surface.SetDrawColor(backgroundColor)
surface.DrawRect(0, 0, width, height)
end
function PANEL:SizeToContents()
local width = 0
for _, v in ipairs(self:GetChildren()) do
width = math.max(width, v:GetWide())
end
self:SetSize(math.max(32, math.min(width, self.maxWidth)), self:GetParent():GetTall())
end
vgui.Register("ixHelpMenuCategories", PANEL, "EditablePanel")
-- help menu
PANEL = {}
function PANEL:Init()
self:Dock(FILL)
self.categories = {}
self.categorySubpanels = {}
self.categoryPanel = self:Add("ixHelpMenuCategories")
self.canvasPanel = self:Add("EditablePanel")
self.canvasPanel:Dock(FILL)
self.idlePanel = self.canvasPanel:Add("Panel")
self.idlePanel:Dock(FILL)
self.idlePanel:DockMargin(8, 0, 0, 0)
self.idlePanel.Paint = function(_, width, height)
surface.SetDrawColor(backgroundColor)
surface.DrawRect(0, 0, width, height)
derma.SkinFunc("DrawHelixCurved", width * 0.5, height * 0.5, width * 0.25)
surface.SetFont("ixIntroSubtitleFont")
local text = L("helix"):lower()
local textWidth, textHeight = surface.GetTextSize(text)
surface.SetTextColor(color_white)
surface.SetTextPos(width * 0.5 - textWidth * 0.5, height * 0.5 - textHeight * 0.75)
surface.DrawText(text)
surface.SetFont("ixMediumLightFont")
text = L("helpIdle")
local infoWidth, _ = surface.GetTextSize(text)
surface.SetTextColor(color_white)
surface.SetTextPos(width * 0.5 - infoWidth * 0.5, height * 0.5 + textHeight * 0.25)
surface.DrawText(text)
end
local categories = {}
hook.Run("PopulateHelpMenu", categories)
for k, v in SortedPairs(categories) do
if (!isstring(k)) then
ErrorNoHalt("expected string for help menu key\n")
continue
elseif (!isfunction(v)) then
ErrorNoHalt(string.format("expected function for help menu entry '%s'\n", k))
continue
end
self:AddCategory(k)
self.categories[k] = v
end
self.categoryPanel:SizeToContents()
if (ix.gui.lastHelpMenuTab) then
self:OnCategorySelected(ix.gui.lastHelpMenuTab)
end
end
function PANEL:AddCategory(name)
local button = self.categoryPanel:Add("ixMenuButton")
button:SetText(L(name))
button:SizeToContents()
-- @todo don't hardcode this but it's the only panel that needs docking at the bottom so it'll do for now
button:Dock(name == "credits" and BOTTOM or TOP)
button.DoClick = function()
self:OnCategorySelected(name)
end
local panel = self.canvasPanel:Add("DScrollPanel")
panel:SetVisible(false)
panel:Dock(FILL)
panel:DockMargin(8, 0, 0, 0)
panel:GetCanvas():DockPadding(8, 8, 8, 8)
panel.Paint = function(_, width, height)
surface.SetDrawColor(backgroundColor)
surface.DrawRect(0, 0, width, height)
end
-- reverts functionality back to a standard panel in the case that a category will manage its own scrolling
panel.DisableScrolling = function()
panel:GetCanvas():SetVisible(false)
panel:GetVBar():SetVisible(false)
panel.OnChildAdded = function() end
end
self.categorySubpanels[name] = panel
end
function PANEL:OnCategorySelected(name)
local panel = self.categorySubpanels[name]
if (!IsValid(panel)) then
return
end
if (!panel.bPopulated) then
self.categories[name](panel)
panel.bPopulated = true
end
if (IsValid(self.activeCategory)) then
self.activeCategory:SetVisible(false)
end
panel:SetVisible(true)
self.idlePanel:SetVisible(false)
self.activeCategory = panel
ix.gui.lastHelpMenuTab = name
end
vgui.Register("ixHelpMenu", PANEL, "EditablePanel")
local function DrawHelix(width, height, color) -- luacheck: ignore 211
local segments = 76
local radius = math.min(width, height) * 0.375
surface.SetTexture(-1)
for i = 1, math.ceil(segments) do
local angle = math.rad((i / segments) * -360)
local x = width * 0.5 + math.sin(angle + math.pi * 2) * radius
local y = height * 0.5 + math.cos(angle + math.pi * 2) * radius
local barOffset = math.sin(SysTime() + i * 0.5)
local barHeight = barOffset * radius * 0.25
if (barOffset > 0) then
surface.SetDrawColor(color)
else
surface.SetDrawColor(color.r * 0.5, color.g * 0.5, color.b * 0.5, color.a)
end
surface.DrawTexturedRectRotated(x, y, 4, barHeight, math.deg(angle))
end
end
hook.Add("CreateMenuButtons", "ixHelpMenu", function(tabs)
tabs["help"] = function(container)
container:Add("ixHelpMenu")
end
end)
hook.Add("PopulateHelpMenu", "ixHelpMenu", function(tabs)
tabs["commands"] = function(container)
-- info text
local info = container:Add("DLabel")
info:SetFont("ixSmallFont")
info:SetText(L("helpCommands"))
info:SetContentAlignment(5)
info:SetTextColor(color_white)
info:SetExpensiveShadow(1, color_black)
info:Dock(TOP)
info:DockMargin(0, 0, 0, 8)
info:SizeToContents()
info:SetTall(info:GetTall() + 16)
info.Paint = function(_, width, height)
surface.SetDrawColor(ColorAlpha(derma.GetColor("Info", info), 160))
surface.DrawRect(0, 0, width, height)
end
-- commands
for uniqueID, command in SortedPairs(ix.command.list) do
if (command.OnCheckAccess and !command:OnCheckAccess(LocalPlayer())) then
continue
end
local bIsAlias = false
local aliasText = ""
-- we want to show aliases in the same entry for better readability
if (command.alias) then
local alias = istable(command.alias) and command.alias or {command.alias}
for _, v in ipairs(alias) do
if (v:lower() == uniqueID) then
bIsAlias = true
break
end
aliasText = aliasText .. ", /" .. v
end
if (bIsAlias) then
continue
end
end
-- command name
local title = container:Add("DLabel")
title:SetFont("ixMediumLightFont")
title:SetText("/" .. command.name .. aliasText)
title:Dock(TOP)
title:SetTextColor(ix.config.Get("color"))
title:SetExpensiveShadow(1, color_black)
title:SizeToContents()
-- syntax
local syntaxText = command.syntax
local syntax
if (syntaxText != "" and syntaxText != "[none]") then
syntax = container:Add("DLabel")
syntax:SetFont("ixMediumLightFont")
syntax:SetText(syntaxText)
syntax:Dock(TOP)
syntax:SetTextColor(color_white)
syntax:SetExpensiveShadow(1, color_black)
syntax:SetWrap(true)
syntax:SetAutoStretchVertical(true)
syntax:SizeToContents()
end
-- description
local descriptionText = command:GetDescription()
if (descriptionText != "") then
local description = container:Add("DLabel")
description:SetFont("ixSmallFont")
description:SetText(descriptionText)
description:Dock(TOP)
description:SetTextColor(color_white)
description:SetExpensiveShadow(1, color_black)
description:SetWrap(true)
description:SetAutoStretchVertical(true)
description:SizeToContents()
description:DockMargin(0, 0, 0, 8)
elseif (syntax) then
syntax:DockMargin(0, 0, 0, 8)
else
title:DockMargin(0, 0, 0, 8)
end
end
end
tabs["flags"] = function(container)
-- info text
local info = container:Add("DLabel")
info:SetFont("ixSmallFont")
info:SetText(L("helpFlags"))
info:SetContentAlignment(5)
info:SetTextColor(color_white)
info:SetExpensiveShadow(1, color_black)
info:Dock(TOP)
info:DockMargin(0, 0, 0, 8)
info:SizeToContents()
info:SetTall(info:GetTall() + 16)
info.Paint = function(_, width, height)
surface.SetDrawColor(ColorAlpha(derma.GetColor("Info", info), 160))
surface.DrawRect(0, 0, width, height)
end
-- flags
local curType = ""
for k, v in SortedPairsByMemberValue(ix.flag.list, "flagType") do
if(v.flagType != curType) then
local panel = container:Add("Panel")
panel:Dock(TOP)
panel:DockMargin(0, 0, 0, 8)
panel:DockPadding(4, 4, 4, 4)
panel.Paint = function(_, width, height)
derma.SkinFunc("DrawImportantBackground", 0, 0, width, height, Color(0,0,0,100))
end
local flag = panel:Add("DLabel")
flag:SetFont("ixMonoMediumFont")
flag:SetText(v.flagType)
flag:Dock(LEFT)
flag:SetTextColor(color_white)
flag:SetExpensiveShadow(1, color_black)
flag:SetTextInset(4, 0)
flag:SizeToContents()
flag:SetTall(flag:GetTall() + 8)
-- This string represents the start. We don't want a DockMargin at the top of this panel.
if(curType != "") then
panel:DockMargin(0, 0, 0, 8)
end
end
local background = ColorAlpha(
LocalPlayer():GetCharacter():HasFlags(k) and derma.GetColor("Success", info) or derma.GetColor("Error", info), 88
)
local panel = container:Add("Panel")
panel:Dock(TOP)
panel:DockMargin(0, 0, 0, 8)
panel:DockPadding(4, 4, 4, 4)
panel.Paint = function(_, width, height)
derma.SkinFunc("DrawImportantBackground", 0, 0, width, height, background)
end
local flag = panel:Add("DLabel")
flag:SetFont("ixMonoMediumFont")
flag:SetText(string.format("[%s]", k))
flag:Dock(LEFT)
flag:SetTextColor(color_white)
flag:SetExpensiveShadow(1, color_black)
flag:SetTextInset(4, 0)
flag:SizeToContents()
flag:SetTall(flag:GetTall() + 8)
local description = panel:Add("DLabel")
description:SetFont("ixMediumLightFont")
description:SetText(v.description)
description:Dock(FILL)
description:SetTextColor(color_white)
description:SetExpensiveShadow(1, color_black)
description:SetTextInset(8, 0)
description:SizeToContents()
description:SetTall(description:GetTall() + 8)
panel:SizeToChildren(false, true)
curType = v.flagType
end
end
tabs["plugins"] = function(container)
for _, v in SortedPairsByMemberValue(ix.plugin.list, "author") do
-- name
local title = container:Add("DLabel")
title:SetFont("ixMediumLightFont")
title:SetText(v.name or "Unknown")
title:Dock(TOP)
title:SetTextColor(ix.config.Get("color"))
title:SetExpensiveShadow(1, color_black)
title:SizeToContents()
-- author
local author = container:Add("DLabel")
author:SetFont("ixSmallFont")
author:SetText(string.format("%s: %s", L("author"), v.author))
author:Dock(TOP)
author:SetTextColor(color_white)
author:SetExpensiveShadow(1, color_black)
author:SetWrap(true)
author:SetAutoStretchVertical(true)
author:SizeToContents()
-- description
local descriptionText = v.description
if (descriptionText != "") then
local description = container:Add("DLabel")
description:SetFont("ixSmallFont")
description:SetText(descriptionText)
description:Dock(TOP)
description:SetTextColor(color_white)
description:SetExpensiveShadow(1, color_black)
description:SetWrap(true)
description:SetAutoStretchVertical(true)
description:SizeToContents()
description:DockMargin(0, 0, 0, 8)
else
author:DockMargin(0, 0, 0, 8)
end
end
end
end)
|
function execute(sender, commandName, ...)
Player(sender):addScriptOnce("cmd/disttocore.lua")
return 0, "", ""
end
function getDescription()
return "Display distance to galaxy core from current sector."
end
function getHelp()
return "Display distance to galaxy core from current sector. Usage: /disttocore"
end |
F = {}
local kutils = require ("kong.plugins.keystone.utils")
local unistd = require "posix.unistd"
local Chars = {}
for Loop = 0, 255 do
Chars[Loop+1] = string.char(Loop)
end
local String = table.concat(Chars)
local Built = {['.'] = Chars}
local AddLookup = function(CharSet)
local Substitute = string.gsub(String, '[^'..CharSet..']', '')
local Lookup = {}
for Loop = 1, string.len(Substitute) do
Lookup[Loop] = string.sub(Substitute, Loop, Loop)
end
Built[CharSet] = Lookup
return Lookup
end
function randomize(tstart, tend)
local number = tostring(os.clock())
if string.find(number,"%.") ~= nil then
number = string.sub(number, string.find(number,"%.")+1)
end
math.randomseed( tonumber(number))
number = number + math.random(1, 7)
math.randomseed( tonumber(number))
math.random(tstart, tend); math.random(tstart, tend); math.random(tstart, tend)
local result = math.random(tstart, tend)
return result
end
-- randomize function
function string.random(Length, CharSet)
-- Length (number)
-- CharSet (string, optional); e.g. %l%d for lower case letters and digits
local CharSet = CharSet or '.'
if CharSet == '' then
return ''
else
local Result = {}
local Lookup = Built[CharSet] or AddLookup(CharSet)
local Range = #Lookup
for Loop = 1,Length do
Result[Loop] = Lookup[randomize(1, Range)]
end
return table.concat(Result)
end
end
function crypt(password)
local rounds = kutils.config_from_dao().default_crypt_strength
-- calc checksum
local rounds = kutils.config_from_dao().default_crypt_strength
local salt = string.random(16, "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
local a = unistd.crypt(password, "$6$rounds=" .. rounds .. "$".. salt .."$")
local checksum = string.sub(a, -86)
local b = "$6$rounds=" .. rounds .. "$".. salt .."$" .. checksum
local result = unistd.crypt(password, b )
return result
end
function verify(password, hashed)
local rounds = kutils.config_from_dao().default_crypt_strength
local checksum = string.sub(hashed, -86)
local salt = string.sub(hashed, 17, -67)
--rounds = string.sub(hashed, 3, -13)
-- calc checksum
local b = "$6$rounds=" .. rounds .. "$".. salt .."$" .. checksum
local result = unistd.crypt(password, b)
return result == hashed
end
F.crypt = crypt
F.verify = verify
return F
|
package = "blunty666.nodes.gui"
imports = "blunty666.nodes.MasterNode"
class = "ScreenHandler"
local mainTerminalEvents = {
char = true,
key = true,
key_up = true,
mouse_click = true,
mouse_drag = true,
mouse_scroll = true,
mouse_up = true,
paste = true,
term_resize = true,
terminate = true,
}
variables = {
masterNode = false,
handler = false,
monitors = {},
timers = {},
clickTime = 0.05,
running = false,
}
methods = {
AddMonitor = function(self, monitorName, backgroundColour, scale)
if type(monitorName) == "string" and peripheral.getType(monitorName) == "monitor" then
local monitor = peripheral.wrap(monitorName)
monitor.setTextScale(scale)
local masterNode = MasterNode(monitor, backgroundColour)
local handler = GuiHandler(masterNode)
self.monitors[monitorName] = {
masterNode = masterNode,
handler = handler,
}
return masterNode
end
return false
end,
GetMonitorMasterNode = function(self, monitorName)
if self.monitors[monitorName] then
return self.monitors[monitorName].masterNode
end
return false
end,
GetMonitorHandler = function(self, monitorName)
if self.monitors[monitorName] then
return self.monitors[monitorName].handler
end
return false
end,
RemoveMonitor = function(self, monitorName)
if self.monitors[monitorName] then
self.monitors[monitorName] = nil
return true
end
return false
end,
HandleEvent = function(self, event)
if type(event) == "table" then
local eventType = event[1]
if mainTerminalEvents[eventType] then
-- pass event to mainTerminal
self.handler:HandleEvent(event)
elseif eventType == "monitor_touch" then
local monitorName = event[2]
local monitorData = self.monitors[monitorName]
if monitorData then
if monitorData.timer then -- check for previous monitor_touch
-- clear timer
self.timers[monitorData.timer] = nil
monitorData.timer = false
-- pass mouse_up event to monitor handler
if monitorData.handler then
monitorData.handler:HandleEvent({"mouse_up", 1, monitorData.lastX, monitorData.lastY})
end
monitorData.lastX, monitorData.lastY = false, false
end
-- pass mouse_click event to correct monitor
if monitorData.handler then
monitorData.handler:HandleEvent({"mouse_click", 1, event[3], event[4]})
monitorData.lastX, monitorData.lastY = event[3], event[4]
monitorData.timer = os.startTimer(self.clickTime)
self.timers[monitorData.timer] = monitorName
end
end
elseif eventType == "timer" then
local timer = event[2]
local monitorName = self.timers[timer]
if monitorName then
self.timers[timer] = nil
local monitorData = self.monitors[monitorName]
if monitorData then
monitorData.timer = false
if monitorData.handler then
monitorData.handler:HandleEvent({"mouse_up", 1, monitorData.lastX, monitorData.lastY})
end
monitorData.lastX, monitorData.lastY = false, false
end
end
end
end
return false
end,
Run = function(self)
self.running = true
local event
local terminated = false
while self.running do
-- push buffer updates to screens
self.masterNode:DrawChanges()
for _, monitorData in pairs(self.monitors) do
local monitorTerminal = monitorData.masterNode
if monitorTerminal then
monitorTerminal:DrawChanges()
end
end
-- handle event
event = {coroutine.yield()}
if event[1] == "terminate" then
self.running = false
terminated = true
end
self:HandleEvent(event)
end
-- push buffer updates to screens
self.masterNode:DrawChanges()
for _, monitorData in pairs(self.monitors) do
local monitorTerminal = monitorData.masterNode
if monitorTerminal then
monitorTerminal:DrawChanges()
end
end
return terminated
end,
Stop = function(self)
if self.running then
self.running = false
return true
end
return false
end,
}
constructor = function(self, mainTerminal, mainTerminalBackgroundColour)
local masterNode = MasterNode((type(mainTerminal) == "table" and mainTerminal) or term.current(), mainTerminalBackgroundColour)
local handler = GuiHandler(masterNode)
self.masterNode = masterNode
self.handler = handler
end
|
local json = require("json")
local path = require("path")
local patterns = require("sg.patterns")
local recognizers = require("sg.recognizers")
local shared = loadfile("shared.lua")()
local util = loadfile("util.lua")()
local indexer = "sourcegraph/lsif-typescript:autoindex"
local typescript_nmusl_command = "N_NODE_MIRROR=https://unofficial-builds.nodejs.org/download/release n --arch x64-musl auto"
local exclude_paths = patterns.path_combine(shared.exclude_paths, {
patterns.path_segment("node_modules"),
})
local check_lerna_file = function(root, contents_by_path)
local ancestors = path.ancestors(root)
for i = 1, #ancestors do
local payload = json.decode(contents_by_path[path.join(ancestors[i], "lerna.json")] or "")
if payload and payload["npmClient"] == "yarn" then
return true
end
end
return false
end
local can_derive_node_version = function(root, paths, contents_by_path)
local ancestors = path.ancestors(root)
for i = 1, #ancestors do
local payload = json.decode(contents_by_path[path.join(ancestors[i], "package.json")] or "")
if payload and payload["engines"]["node"] ~= "" then
return true
end
end
for i = 1, #ancestors do
local candidates = {
path.join(ancestors[i], ".nvmrc"),
path.join(ancestors[i], ".node-version"),
path.join(ancestors[i], ".n-node-version"),
}
if util.contains_any(paths, candidates) then
return true
end
end
return false
end
local infer_typescript_job = function(api, tsconfig_path, should_infer_config)
local root = path.dirname(tsconfig_path)
local reverse_ancestors = util.reverse(path.ancestors(tsconfig_path))
api:register(recognizers.path_recognizer {
patterns = {
-- To disambiguate installation steps
patterns.path_basename("yarn.lock"),
-- Try to determine version
patterns.path_basename(".n-node-version"),
patterns.path_basename(".node-version"),
patterns.path_basename(".nvmrc"),
-- To reinvoke simple cases with no other files
patterns.path_basename("tsconfig.json"),
patterns.path_exclude(exclude_paths),
},
patterns_for_content = {
-- To read explicitly configured engines and npm client
patterns.path_basename("package.json"),
patterns.path_basename("lerna.json"),
patterns.path_exclude(exclude_paths),
},
-- Invoked when any of the files listed in the patterns above exist.
generate = function(api, paths, contents_by_path)
local is_yarn = check_lerna_file(root, contents_by_path)
local docker_steps = {}
for i = 1, #reverse_ancestors do
if contents_by_path[path.join(reverse_ancestors[i], "package.json")] then
local install_command = ""
if is_yarn or util.contains(paths, path.join(reverse_ancestors[i], "yarn.lock")) then
install_command = "yarn --ignore-engines"
else
install_command = "npm install"
end
local install_command_suffix = ""
if should_infer_config then
install_command_suffix = " --ignore-scripts"
end
table.insert(docker_steps, {
root = reverse_ancestors[i],
image = indexer,
commands = { install_command .. install_command_suffix },
})
end
end
local local_steps = {}
if can_derive_node_version(root, paths, contents_by_path) then
for i = 1, #docker_steps do
-- Add `n` invocation command before each docker step
docker_steps[i].commands = util.with_new_head(docker_steps[i].commands, typescript_nmusl_command)
end
-- Add `n` invocation (in indexing container) before indexer runs
local_steps = { typescript_nmusl_command }
end
local args = { "lsif-typescript-autoindex", "index" }
if should_infer_config then
table.insert(args, "--infer-tsconfig")
end
return {
steps = docker_steps,
local_steps = local_steps,
root = root,
indexer = indexer,
indexer_args = args,
outfile = "",
}
end,
})
return {}
end
return recognizers.path_recognizer {
patterns = {
patterns.path_basename("package.json"),
patterns.path_basename("tsconfig.json"),
patterns.path_exclude(exclude_paths),
},
-- Invoked when package.json or tsconfig.json files exist
generate = function(api, paths)
local has_tsconfig = false
for i = 1, #paths do
if path.basename(paths[i]) == "tsconfig.json" then
-- Infer typescript jobs
infer_typescript_job(api, paths[i], false)
has_tsconfig = true
end
end
if not has_tsconfig then
-- Infer javascript jobs if there's no tsconfig.json found
infer_typescript_job(api, "tsconfig.json", true)
end
return {}
end,
}
|
local cbe = CraftBagExtended
local util = cbe.utility
local class = cbe.classes
local debug = false
class.TransferQueue = ZO_Object:Subclass()
function class.TransferQueue:New(...)
local controller = ZO_Object.New(self)
controller:Initialize(...)
return controller
end
function class.TransferQueue:Initialize(name, sourceBag, targetBag)
self.name = name or cbe.name .. "TransferQueue"
self.sourceBag = sourceBag or BAG_VIRTUAL
self.targetBag = targetBag or BAG_BACKPACK
self:Clear()
if self.targetBag ~= BAG_GUILDBANK then
self.emptySlotTracker = util.GetSingleton(class.EmptySlotTracker, self.targetBag)
end
if self.sourceBag ~= BAG_GUILDBANK then
self.sourceSlotTracker = util.GetSingleton(class.EmptySlotTracker, self.sourceBag)
end
end
function class.TransferQueue:Clear()
util.Debug(self.name..": Clear()")
if self.emptySlotTracker then
if self.itemsByTargetSlotIndex then
for targetSlotIndex, _ in pairs(self.itemsByTargetSlotIndex) do
self.emptySlotTracker:UnreserveSlot(targetSlotIndex)
end
end
self.emptySlotTracker:UnregisterStackArrivedCallback(self.name, util.OnStackArrived)
end
if self.sourceSlotTracker then
self.sourceSlotTracker:UnregisterStackRemovedCallback(self.name, util.OnStackRemoved)
end
self.itemCount = 0
self.items = {}
self.itemsByKey = {}
self.itemsByTargetSlotIndex = {}
self.itemsBySourceSlotIndex = {}
self.dequeuedItemsBySourceSlotIndex = {}
end
function class.TransferQueue:AddItem(item)
if item.itemId == 0 or not item.itemId then
util.Debug(self.name..": enqueue failed for item with itemId "..tostring(item.itemId), debug)
return
elseif self.targetBag == BAG_VIRTUAL then
if not cbe.hasCraftBagAccess then
ZO_Alert(UI_ALERT_CATEGORY_ERROR, SOUNDS.NEGATIVE_CLICK, SI_CRAFT_BAG_STATUS_LOCKED_DESCRIPTION)
return
elseif not CanItemBeVirtual(self.sourceBag, item.slotIndex) then
ZO_Alert(UI_ALERT_CATEGORY_ERROR, SOUNDS.NEGATIVE_CLICK, SI_CBE_CRAFTBAG_ITEM_INVALID)
return
else
item.targetSlotIndex = item.itemId
end
end
-- Don't allow items from the same stack to queue before previous transfers have all left the source bag
if item.location == cbe.constants.LOCATION.SOURCE_BAG
and self.itemsBySourceSlotIndex[item.slotIndex]
then
for _, queuedItem in ipairs(self.itemsBySourceSlotIndex[item.slotIndex]) do
if queuedItem.location == cbe.constants.LOCATION.SOURCE_BAG then
util.Debug(self.name..": enqueue disallowed due to duplicate queued item still in source bag for "
..item.itemLink.." id "..tostring(item.itemId).." bag "..tostring(item.bag).." slot "
..tostring(item.slotIndex).." qty "..tostring(item.quantity), debug)
return
end
end
end
if self.emptySlotTracker then
if item.targetSlotIndex == nil then
local targetSlotIndex = self.emptySlotTracker:ReserveSlot()
if not targetSlotIndex then
if self.targetBag == BAG_BANK and IsESOPlusSubscriber() then
item.targetBag = BAG_SUBSCRIBER_BANK
item.queue = util.GetTransferQueue(self.sourceBag, BAG_SUBSCRIBER_BANK)
return item.queue:AddItem(item)
end
util.Debug(self.name..": enqueue failed for "..item.itemLink.." id "..tostring(item.itemId)
.." bag "..tostring(item.bag).." slot "..tostring(item.slotIndex).." qty "
..tostring(item.quantity), debug)
return
end
item.targetSlotIndex = targetSlotIndex
end
if not self.itemsByTargetSlotIndex[item.targetSlotIndex] then
self.itemsByTargetSlotIndex[item.targetSlotIndex] = { item }
else
table.insert(self.itemsByTargetSlotIndex[item.targetSlotIndex], item)
end
end
local key = self:GetKey(item.itemId, item.quantity, self.targetBag)
if not self.itemsByKey[key] then
self.itemsByKey[key] = {}
end
table.insert(self.itemsByKey[key], item)
if not self.itemsBySourceSlotIndex[item.slotIndex] then
self.itemsBySourceSlotIndex[item.slotIndex] = { }
end
table.insert(self.itemsBySourceSlotIndex[item.slotIndex], item)
table.insert(self.items, item)
self.itemCount = self.itemCount + 1
if self.itemCount == 1 then
if self.emptySlotTracker then
self.emptySlotTracker:RegisterStackArrivedCallback(self.name, util.OnStackArrived)
end
if self.sourceSlotTracker then
self.sourceSlotTracker:RegisterStackRemovedCallback(self.name, util.OnStackRemoved)
end
end
if self.sourceBag == BAG_VIRTUAL and item.quantity ~= cbe.constants.QUANTITY_UNSPECIFIED then
item:StartUnqueueTimeout(cbe.constants.UNQUEUE_TIMEOUT_MS)
end
util.Debug(self.name..": enqueue succeeded for "..item.itemLink.." x"..tostring(item.quantity)
.." (id:"..tostring(item.itemId)..") source bag "..util.GetBagName(item.bag).." slot "
..tostring(item.slotIndex).." to target bag "..util.GetBagName(self.targetBag)
.." slot "..tostring(item.targetSlotIndex), debug)
return item
end
function class.TransferQueue:Dequeue(bag, slotIndex, quantity)
if quantity == nil then
if slotIndex == nil
or slotIndex == cbe.constants.QUANTITY_UNSPECIFIED
then
quantity = slotIndex
slotIndex = bag
bag = self.targetBag
end
end
if bag == self.targetBag and slotIndex and bag ~= BAG_GUILDBANK and bag ~= BAG_VIRTUAL then
return self:DequeueTargetSlotIndex(slotIndex)
end
local itemId = GetItemId(bag, slotIndex)
if (not quantity or quantity == 0) and bag ~= BAG_VIRTUAL then
local stackSize, maxStackSize = GetSlotStackSize(bag, slotIndex)
quantity = math.min(stackSize, maxStackSize)
local scope = util.GetTransferItemScope(self.sourceBag, self.targetBag)
local default = cbe.settings:GetTransferDefault(scope, itemId)
if default then
quantity = math.min(quantity, default)
end
end
local key = self:GetKey(itemId, quantity, self.targetBag)
if not self.itemsByKey[key] then
util.Debug(self.name..": dequeue failed for key "..tostring(key), debug)
return
end
local item = table.remove(self.itemsByKey[key], 1)
self:DequeueItem(item, key)
if not item.targetSlotIndex and bag == self.targetBag and slotIndex then
item.targetSlotIndex = slotIndex
end
return item
end
function class.TransferQueue:DequeueItem(item, key)
if not item then
return
end
item:CancelUnqueueTimeout()
if not util.RemoveValue(self.items, item) then
return
end
if self.emptySlotTracker and item.targetSlotIndex and item.targetSlotIndex > 0 then
self.emptySlotTracker:UnreserveSlot(item.targetSlotIndex)
end
if not key then
key = self:GetKey(item.itemId, item.quantity, self.targetBag)
if self.itemsByKey[key] then
util.RemoveValue(self.itemsByKey[key], item)
end
end
if self.itemsByKey[key] and #self.itemsByKey[key] < 1 then
self.itemsByKey[key] = nil
end
if item.targetSlotIndex and self.itemsByTargetSlotIndex[item.targetSlotIndex] then
util.RemoveValue(self.itemsByTargetSlotIndex[item.targetSlotIndex], item)
if #self.itemsByTargetSlotIndex[item.targetSlotIndex] < 1 then
self.itemsByTargetSlotIndex[item.targetSlotIndex] = nil
end
end
if self.itemsBySourceSlotIndex[item.slotIndex] then
util.RemoveValue(self.itemsBySourceSlotIndex[item.slotIndex], item)
if #self.itemsBySourceSlotIndex[item.slotIndex] < 1 then
self.itemsBySourceSlotIndex[item.slotIndex] = nil
end
end
if item.location == cbe.constants.LOCATION.SOURCE_BAG then
if not self.dequeuedItemsBySourceSlotIndex[item.slotIndex] then
self.dequeuedItemsBySourceSlotIndex[item.slotIndex] = {}
end
table.insert(self.dequeuedItemsBySourceSlotIndex[item.slotIndex], item)
end
self.itemCount = self.itemCount - 1
if self.itemCount < 1 then
if self.emptySlotTracker then
self.emptySlotTracker:UnregisterStackArrivedCallback(self.name, util.OnStackArrived)
end
if self.sourceSlotTracker and not next(self.dequeuedItemsBySourceSlotIndex) then
self.sourceSlotTracker:UnregisterStackRemovedCallback(self.name, util.OnStackRemoved)
end
end
item.location = cbe.constants.LOCATION.TARGET_BAG
util.Debug(self.name..": dequeue succeeded for "..item.itemLink.." x"..tostring(item.quantity).." (id:"..tostring(item.itemId)..") target bag "..util.GetBagName(item.targetBag).." slot "..tostring(item.targetSlotIndex).." from source bag "..util.GetBagName(item.bag).." slot "..tostring(item.slotIndex), debug)
end
function class.TransferQueue:DequeueTargetSlotIndex(targetSlotIndex)
local item
if self.itemsByTargetSlotIndex[targetSlotIndex] then
item = table.remove(self.itemsByTargetSlotIndex[targetSlotIndex], 1)
if #self.itemsByTargetSlotIndex[targetSlotIndex] < 1 then
self.itemsByTargetSlotIndex[targetSlotIndex] = nil
end
end
if not item then
util.Debug(self.name..": dequeue failed for target slot index "..tostring(targetSlotIndex), debug)
return
end
self:DequeueItem(item)
return item
end
function class.TransferQueue:Enqueue(slotIndex, quantity, callback, ...)
local item = class.TransferItem:New(self, slotIndex, quantity, callback, ...)
return self:AddItem(item)
end
function class.TransferQueue:GetKey(itemId, quantity, bag)
-- Match by id and quantity
return tostring(itemId).."-"..tostring(quantity)
end
function class.TransferQueue.GetName(sourceBag, destinationBag)
return cbe.name .. util.GetBagName(sourceBag) .. util.GetBagName(destinationBag) .. "Queue"
end
function class.TransferQueue:GetSourceBagItems()
local items = {}
for _, item in ipairs(self.items) do
if item.location == cbe.constants.LOCATION.SOURCE_BAG then
table.insert(items, item)
end
end
return items
end
function class.TransferQueue:HasItems()
return self.itemCount > 0
end
local function StowCallback(item)
cbe:Stow(item.targetSlotIndex, item.quantity)
end
function class.TransferQueue:ReturnToCraftBag()
if self.sourceBag ~= BAG_VIRTUAL then
return
end
util.Debug(self.name..":ReturnToCraftBag()", debug)
-- as soon as each item in the queue arrives in the backpack, stow it back in the craft bag
for _, item in ipairs(self.items) do
item.callback = StowCallback
end
end
function class.TransferQueue:TryMarkInTransitItem(bag, slotIndex, quantity)
if bag ~= self.sourceBag then
return
end
if self.dequeuedItemsBySourceSlotIndex[slotIndex] then
local item = table.remove(self.dequeuedItemsBySourceSlotIndex[slotIndex], 1)
if #self.dequeuedItemsBySourceSlotIndex[slotIndex] < 1 then
self.dequeuedItemsBySourceSlotIndex[slotIndex] = nil
if self.itemCount < 1 and self.sourceSlotTracker and not next(self.dequeuedItemsBySourceSlotIndex) then
self.sourceSlotTracker:UnregisterStackRemovedCallback(self.name, util.OnStackRemoved)
end
end
util.Debug(self.name..": transfer item has already arrived at target bag "
..util.GetBagName(item.targetBag).." slot "..tostring(item.targetSlotIndex), debug)
return true
elseif self.itemsBySourceSlotIndex[slotIndex] then
for _, item in ipairs(self.itemsBySourceSlotIndex[slotIndex]) do
if item.location == cbe.constants.LOCATION.SOURCE_BAG and item ~= cbe.transferDialogItem then
item.location = cbe.constants.LOCATION.IN_TRANSIT
util.Debug(self.name..": transfer item marked in-transit", debug)
return true
end
end
end
end
function class.TransferQueue:UpdateKey(item, oldKey, newKey)
if not self.itemsByKey[newKey] then
self.itemsByKey[newKey] = {}
end
if self.itemsByKey[oldKey] then
util.RemoveValue(self.itemsByKey[oldKey], item)
if #self.itemsByKey[oldKey] < 1 then
self.itemsByKey[oldKey] = nil
end
end
table.insert(self.itemsByKey[newKey], item)
end
function class.TransferQueue:UnqueueSourceBag()
for _, item in ipairs(self.items) do
if item:UnqueueSourceBag() then
return item
end
end
end |
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by Dylan Malandain.
--- DateTime: 27/02/2019 12:49
---
---@type table
UIProgressBarItem = setmetatable({}, UIProgressBarItem)
---@type table
UIProgressBarItem.__index = UIProgressBarItem
---@type table
UIProgressBarItem.__call = function()
return "UIProgressBarItem"
end
---New
---@param Text string
---@param X number
---@param Y number
---@param Heading number
---@param R number
---@param G number
---@param B number
---@param A number
function UIProgressBarItem.New(Text, X, Y, Heading, R, G, B, A)
local X, Y = tonumber(X) or 800, tonumber(Y) or 1030
if Heading ~= nil then
Heading = tonumber(Heading) or 0
else
Heading = 0
end
if R ~= nil then
R = tonumber(R) or 255
else
R = 255
end
if G ~= nil then
G = tonumber(G) or 255
else
G = 255
end
if B ~= nil then
B = tonumber(B) or 255
else
B = 255
end
if A ~= nil then
A = tonumber(A) or 100
else
A = 100
end
local _UIProgressBarItem = {
Background = UIResRectangle.New(0, 0, 350, 40, 0, 0, 0, 100),
Text = UIResText.New(Text or "N/A", 0, 0, 0.35, 255, 255, 255, 255, 0, "Centre"),
ProgressBar = UIResRectangle.New(0, 0, 0, 30, R, G, B, A),
Position = { X = X, Y = Y },
}
return setmetatable(_UIProgressBarItem, UIProgressBarItem)
end
---SetPercentage
---@param Number number
function UIProgressBarItem:SetPercentage(Number)
if (Number <= 100) then
self.ProgressBar.Width = Number * 3.4
else
self.ProgressBar.Width = 100 * 3.4
end
end
function UIProgressBarItem:GetPercentage()
return math.floor(self.ProgressBar.Width * 1 / 3.4)
end
---SetText
---@param String string
function UIProgressBarItem:SetText(String)
self.Text:Text(String)
end
---SetTextColors
---@param R number
---@param G number
---@param B number
---@param A number
function UIProgressBarItem:SetTextColor(R, G, B, A)
if R ~= nil then
R = tonumber(R) or 255
else
R = 255
end
if G ~= nil then
G = tonumber(G) or 255
else
G = 255
end
if B ~= nil then
B = tonumber(B) or 255
else
B = 255
end
if A ~= nil then
A = tonumber(A) or 255
else
A = 255
end
self.Text:Colour(R, G, B, A)
end
---SetBackgroundProgressColor
---@param R number
---@param G number
---@param B number
---@param A number
function UIProgressBarItem:SetBackgroundProgressColor(R, G, B, A)
if R ~= nil then
R = tonumber(R) or 0
else
R = 0
end
if G ~= nil then
G = tonumber(G) or 0
else
G = 0
end
if B ~= nil then
B = tonumber(B) or 0
else
B = 0
end
if A ~= nil then
A = tonumber(A) or 100
else
A = 100
end
self.Background:Colour(R, G, B, A)
end
---SetProgressColor
---@param R number
---@param G number
---@param B number
---@param A number
function UIProgressBarItem:SetProgressColor(R, G, B, A)
if R ~= nil then
R = tonumber(R) or 32
else
R = 32
end
if G ~= nil then
G = tonumber(G) or 120
else
G = 120
end
if B ~= nil then
B = tonumber(B) or 32
else
B = 32
end
if A ~= nil then
A = tonumber(A) or 150
else
A = 150
end
self.ProgressBar:Colour(R, G, B, A)
end
---Draw
function UIProgressBarItem:Draw()
self.Background:Position(self.Position.X, self.Position.Y)
self.Text:Position(self.Position.X + 170.0, self.Position.Y + 5)
self.ProgressBar:Position(self.Position.X + 5.0, self.Position.Y + 5)
self.Background:Draw()
self.Text:Draw()
self.ProgressBar:Draw()
end
|
--
-- Copyright (C) 2022 Masatoshi Fukunaga
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
local time = os.time
local find = string.find
local isa = require('isa')
local is_boolean = isa.boolean
local is_string = isa.string
local is_uint = isa.uint
local format = require('print').format
--- is_valid_key
--- @param key string
--- @return boolean ok
--- @return string err
local function is_valid_key(key)
if not is_string(key) or not find(key, '^[a-zA-Z0-9_%-]+$') then
return false, format('key must be string of %q', '^[a-zA-Z0-9_%-]+$')
end
return true
end
--- @class reflex.cache
--- @field data table
local Cache = {}
--- new
--- @return reflex.cache
function Cache:init()
self.data = {}
return self
end
--- set_item
--- @param key string
--- @param val any
--- @param ttl integer
--- @return boolean ok
--- @return string err
function Cache:set_item(key, val, ttl)
self.data[key] = {
val = val,
ttl = ttl,
exp = ttl and time() + ttl or nil,
}
return true
end
--- set
--- @param key string
--- @param val any
--- @param ttl integer
--- @return boolean ok
--- @return string err
function Cache:set(key, val, ttl)
local ok, err = is_valid_key(key)
if not ok then
return false, err
elseif val == nil then
return false, format('val must not be nil')
elseif ttl ~= nil and (not is_uint(ttl) or ttl < 1) then
return false, format('ttl must be integer greater than 0')
end
return self:set_item(key, val, ttl)
end
--- get_item
--- @param key string
--- @param touch boolean
--- @return string val
--- @return string err
function Cache:get_item(key, touch)
local item = self.data[key]
if not item then
return nil
elseif item.exp then
local t = time()
if item.exp <= t then
self.data[key] = nil
return nil
elseif touch then
item.exp = t + item.ttl
end
end
return item.val
end
--- get
--- @param key string
--- @param touch boolean
--- @return string val
--- @return string err
function Cache:get(key, touch)
local ok, err = is_valid_key(key)
if not ok then
return nil, err
elseif touch ~= nil and not is_boolean(touch) then
return nil, 'touch must be boolean'
end
return self:get_item(key, touch)
end
--- del_item
--- @param key string
--- @return boolean ok
--- @return string err
function Cache:del_item(key)
if self.data[key] ~= nil then
self.data[key] = nil
return true
end
return false
end
--- del
--- @param key string
--- @return boolean ok
--- @return string err
function Cache:del(key)
local ok, err = is_valid_key(key)
if not ok then
return false, err
end
return self:del_item(key)
end
return {
new = require('metamodule').new(Cache),
}
|
function SotSActionUI(iPlayerID, iUnitID, PlotX, PlotY) -- Core UI code of the Statue of the Seven
local pPlayer = Players[iPlayerID];
local pCity = Cities.GetCityInPlot(PlotX, PlotY);
local SotSRemainingHP = pPlayer:GetProperty("SotSHealCapability");
if SotSRemainingHP then
if (SotSRemainingHP >0 and pCity ~= nil) then
local pCityBuildings= pCity:GetBuildings();
local buildingSotS = GameInfo.Buildings["BUILDING_STATUE_OF_THE_SEVEN"];
if (pCityBuildings:HasBuilding(buildingSotS.Index)) then
local pUnit = UnitManager.GetUnit(iPlayerID, iUnitID);
if (pUnit ~= nil and pUnit:GetDamage() ~= 0) then
if (PlayersVisibility[Game.GetLocalPlayer()]:IsVisible(PlotX,PlotY)) then
UI.PlaySound("Play_Statue_of_The_Seven_Heal");
end
end
end
end
end
end
function OnUnitMoveComplete_SotSTriggerUI(iPlayerID, iUnitID, PlotX, PlotY)
SotSActionUI(iPlayerID, iUnitID, PlotX, PlotY);
end
function OnUnitSelectionChanged_SotSTriggerUI(iPlayerID, iUnitID, hexI, hexJ, hexK, bSelected, bEditable)
local pUnit = UnitManager.GetUnit(iPlayerID, iUnitID); -- Heal unit selected
if (bSelected) then
SotSActionUI(iPlayerID, iUnitID, pUnit:GetX(), pUnit:GetY());
end
end
Events.UnitMoveComplete.Add(OnUnitMoveComplete_SotSTriggerUI);
Events.UnitSelectionChanged.Add(OnUnitSelectionChanged_SotSTriggerUI); |
----------------------------------------------------------------------------------------------------
-- localized Spanish (database module) strings
--
--get the add-on engine
local AddOnName = ...;
--Spanish or Latin America Spanish
local L = LibStub("AceLocale-3.0"):NewLocale(AddOnName, "esES")
if not L then
L = LibStub("AceLocale-3.0"):NewLocale(AddOnName, "esMX");
if not L then
return;
end
end
L["DATABASE_MYTHIC_PLUS"] = "Miticas +"
L["DATABASE_CUSTOM"] = "Personalizadas"
L["DATABASE_CUSTOM_ENTRY"] = "Personalizada " |
local url_count = 0
local tries = 0
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
if verdict and string.match(url, "webcache%.googleusercontent%.com") then
return false
elseif verdict and string.match(url, "data:image/") then
return false
else
return verdict
end
end
wget.callbacks.httploop_result = function(url, err, http_stat)
local status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. ": " .. status_code .. " " .. url["url"] .. "\n")
io.stdout:flush()
if status_code == 0 or status_code >= 500 or
(status_code >= 400 and status_code ~= 404) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 2 and (
(string.match(url["url"], 'googleusercontent') and status_code == 403) or
(status_code == 0)
) then
tries = 0
io.stdout:write("\nI can't seem to download this file. Ignoring it.\n")
io.stdout:flush()
return wget.actions.EXIT
elseif tries >= 20 then
io.stdout:write("\nI give up... Please report this item to the admins.\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
local sleep_time = math.random(100, 2000) / 1000.0
if string.match(url["host"], "googleusercontent") or
string.match(url["host"], "googleapis") or
string.match(url["path"], "%.jpg") or
string.match(url["path"], "%.png") or
string.match(url["path"], "%.js") or
string.match(url["path"], "%.css")
then
-- We should be able to go fast on images since that's what a web browser does
sleep_time = 0
end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
-- Copyright (c) 2021 Kirazy
-- Part of Artisanal Reskins: Bob's Mods
--
-- See LICENSE in the project directory for license information.
-- Check to see if reskinning needs to be done.
if not (reskins.bobs and reskins.bobs.triggers.logistics.entities) then return end
if reskins.lib.setting("bobmods-logistics-trains") == false then return end
-- Set input parameters
local inputs = {
type = "fluid-wagon",
icon_name = "fluid-wagon",
base_entity = "fluid-wagon",
mod = "bobs",
group = "logistics",
particles = {["small"] = 3},
}
local tier_map = {
["fluid-wagon"] = {1, 2},
["bob-fluid-wagon-2"] = {2, 3},
["bob-fluid-wagon-3"] = {3, 4},
["bob-armoured-fluid-wagon"] = {1, 4},
["bob-armoured-fluid-wagon-2"] = {2, 5},
}
-- Reskin entities, create and assign extra details
for name, map in pairs(tier_map) do
-- Fetch entity
local entity = data.raw[inputs.type][name]
-- Check if entity exists, if not, skip this iteration
if not entity then goto continue end
-- Parse map
local tier = map[1]
if reskins.lib.setting("reskins-lib-tier-mapping") == "progression-map" then
tier = map[2]
end
-- Determine what tint we're using
inputs.tint = reskins.lib.tint_index[tier]
-- Setup icon details
if string.find(name, "armoured") then
inputs.icon_extras = {
{
icon = reskins.bobs.directory.."/graphics/icons/logistics/locomotive/armored-train-symbol.png"
},
{
icon = reskins.bobs.directory.."/graphics/icons/logistics/locomotive/armored-train-symbol.png",
tint = reskins.lib.adjust_alpha(reskins.lib.tint_index[tier], 0.75)
}
}
else
inputs.icon_extras = nil
end
reskins.lib.setup_standard_entity(name, tier, inputs)
-- TODO: Reskin remnants?
-- TODO: Reskin entity?
-- Label to skip to next iteration
::continue::
end |
return {'abactis','abacus','abandon','abandonnement','abandonneren','abattoir','abaja','abaci','abactissen','abandonneert','abattoirs','abandonneerde','abajas'} |
--[[
This sets up the LeaderStats and non-LeaderStats data that is relayed to the players.
]]
local ReplicatedPlayerData = require(game.ReplicatedStorage.ReplicatedPlayerData)
local PlayerData = require(game.ServerScriptService.PlayerData)
local PlayerUtils = require(game.ServerScriptService.PlayerUtils)
local Utils = require(game.ReplicatedStorage.Utils)
PlayerUtils.Register_onPlayerAdded(function(player)
local data = PlayerData:get(player)
-- create the two folders
local fld_leaderstats = Utils.GetOrCreate(player, "leaderstats", "Folder")
local fld_stats = Utils.GetOrCreate(player, "stats", "Folder")
-- populate the stats folder
for name, x in pairs(ReplicatedPlayerData.items) do
if x.inst ~= nil then
local vv = Instance.new(x.inst)
vv.Name = name
if x.inst ~= "Folder" and x.inst ~= "ObjectValue" then
vv.Value = data:Get(name)
end
vv.Parent = fld_stats
-- set the update function
data:OnUpdate(name, function(newval)
vv.Value = newval
end)
end
end
-- populate the leaderstat folder
for _, x in ipairs(ReplicatedPlayerData.leaderstats) do
local vv = Instance.new(x.inst)
local dsvar = x.dsvar or x.name
vv.Name = x.name
vv.Parent = fld_leaderstats
local function updatefield(newval)
if x.func ~= nil then
vv.Value = x.func(newval)
else
vv.Value = newval
end
end
-- set the update function
data:OnUpdate(dsvar, updatefield)
updatefield(data:Get(dsvar))
end
-- note that we have loaded everything and the splash screen can go away
Utils.AddBoolValue(player, "PlayerDataLoaded", true)
end)
|
local TextHandler = require("api.gui.TextHandler")
local Ui = require("api.Ui")
local Gui = require("api.Gui")
local IInput = require("api.gui.IInput")
local IUiLayer = require("api.gui.IUiLayer")
local InputHandler = require("api.gui.InputHandler")
local UiTextEditor = require("mod.ui_console.api.gui.UiTextEditor")
local StyledConsoleRenderer = require("mod.ui_console.api.gui.StyledConsoleRenderer")
local TextEditorPrompt = class.class("TextEditorPrompt", IUiLayer)
TextEditorPrompt:delegate("input", IInput)
function TextEditorPrompt:init(text)
text = text or ""
self.editor = UiTextEditor:new(text, 16, StyledConsoleRenderer:new())
self.input = InputHandler:new(TextHandler:new())
self.input:bind_keys(self:make_keymap())
self.input:forward_to(self.editor)
self.input:halt_input()
end
function TextEditorPrompt:make_keymap()
return {
escape = function() self.canceled = true end,
text_canceled = function() self.canceled = true end,
}
end
function TextEditorPrompt:on_query()
Gui.play_sound("base.pop2")
end
function TextEditorPrompt:relayout(x, y, width, height)
self.width = 400
self.height = 500
self.x, self.y, self.width, self.height = Ui.params_centered(self.width, self.height)
self.editor:relayout(self.x, self.y, self.width, self.height)
end
function TextEditorPrompt:draw()
self.editor:draw()
end
function TextEditorPrompt:update(dt)
local canceled = self.canceled
self.canceled = false
self.editor:update(dt)
if canceled then
return self.editor:merge_lines(), nil
end
end
return TextEditorPrompt
|
local cmp = require("cmp")
local luasnip = require("luasnip")
local check_back_space = function()
local col = vim.fn.col(".") - 1
return col == 0 or vim.fn.getline("."):sub(col, col):match("%s")
end
local t = function(str)
return vim.api.nvim_replace_termcodes(str, true, true, true)
end
local function config()
cmp.setup {
formatting = {
format = function(entry, vim_item)
local icons = require("lsp.kind").icons
vim_item.kind = icons[vim_item.kind]
vim_item.menu = ({
nvim_lsp = "[LSP]",
nvim_lua = "[Lua]",
path = "[Path]",
luasnip = "[Snippet]",
buffer = "[Buffer]"
})[entry.source.name]
vim_item.dup = ({buffer = 1, path = 1, nvim_lsp = 0})[entry.source.name] or 0
return vim_item
end
},
snippet = {
expand = function(args)
require("luasnip").lsp_expand(args.body)
end
},
documentation = {
border = {"╭", "─", "╮", "│", "╯", "─", "╰", "│"},
winhighlight = "NormalFloat:CmpDocumentation,FloatBorder:CmpDocumentationBorder"
},
sources = cmp.config.sources(
{
{name = "nvim_lsp"},
{ name = 'luasnip' }, -- For luasnip users.
{name = "path"},
{name = "nvim-lua"},
}, {{name = "buffer"}}),
mapping = {
["<C-y>"] = cmp.config.disable,
["<C-p>"] = cmp.mapping.select_prev_item(),
["<C-n>"] = cmp.mapping.select_next_item(),
["<C-d>"] = cmp.mapping(cmp.mapping.scroll_docs(-4), {"i", "c"}),
["<C-u>"] = cmp.mapping(cmp.mapping.scroll_docs(4), {"i", "c"}),
["<Tab>"] = function(fallback)
if vim.fn.pumvisible() == 1 then
vim.fn.feedkeys(t("<C-n>"), "n")
elseif check_back_space() then
vim.fn.feedkeys(t("<Tab>"), "n")
elseif luasnip.expand_or_jumpable() then
vim.fn.feedkeys(t("<Plug>luasnip-expand-or-jump"), "")
else
fallback()
end
end,
["<S-Tab>"] = function(fallback)
if vim.fn.pumvisible() == 1 then
vim.fn.feedkeys(t("<C-p>"), "n")
elseif check_back_space() then
vim.fn.feedkeys(t("<C-h>"), "n")
elseif luasnip.jumpable(-1) then
vim.fn.feedkeys(t("<Plug>luasnip-jump-prev"), "")
else
fallback()
end
end,
["<C-Space>"] = cmp.mapping(cmp.mapping.complete(), {"i", "c"}),
["<C-e>"] = cmp.mapping({i = cmp.mapping.abort(), c = cmp.mapping.close()}),
["<CR>"] = cmp.mapping.confirm {behavior = cmp.ConfirmBehavior.Replace, select = true}
}
}
end
return {config = config}
|
--[[
Project: SA Memory (Available from https://blast.hk/)
Developers: LUCHARE, FYP
Special thanks:
plugin-sdk (https://github.com/DK22Pac/plugin-sdk) for the structures and addresses.
Copyright (c) 2018 BlastHack.
]]
local shared = require 'SAMemory.shared'
shared.require 'vector3d'
shared.ffi.cdef[[
typedef struct CWeaponEffects
{
bool bActive;
char _pad01[3];
int nTimeWhenToDeactivate;
vector3d vPosn;
unsigned int uiColor;
float fSize;
int field_1C;
int field_20;
float fRotation;
char field_28;
char _pad29[3];
} CWeaponEffects;
]]
shared.validate_size('CWeaponEffects', 0x2C)
|
-- Valid town id list
app.Custom.ValidTownList = {1,2,3,4}
-- Valid vocation id list
app.Custom.ValidVocationList = {1, 2, 3, 4}
-- New character values
app.Custom.NewCharacterValues = {
[1] = { -- no voc (vocation ID -1)
level = 1,
experience = 0,
health = 150,
healthmax = 150,
mana = 0,
manamax = 0,
cap = 435,
soul = 0
},
[2] = { -- sorc
level = 8,
experience = 4200,
health = 185,
healthmax = 185,
mana = 35,
manamax = 35,
cap = 470,
soul = 100,
-- extra = {["maglevel"] = 45, ["skill_shielding"] = 20}
-- NOTE: the keys in extra ( ["key"] = value ) must be valid column names in your players table.
},
[3] = { -- druid
inherit_from = 2 -- remove this line if you want to use custom values
},
[4] = { -- paladin
inherit_from = 2
},
[5] = { -- knight
inherit_from = 2
}
}
|
configuration "macosx"
-- OS X frameworks need the extension to be handled properly
links { "Cocoa.framework", "OpenGL.framework", "IOKit.framework" }
defines { "PLATFORM_MAC" }
configuration "windows"
defines { "PLATFORM_WINDOWS" }
debugdir "$(SolutionDir)" --> Set working dir for VS to root folder
workspace "GameEngine"
configurations { "Debug", "Release", "Dist" }
startproject "EngineTests"
architecture "x64"
systemversion "latest"
targetdir "bin/"
objdir "bin/obj/"
staticruntime "On" --> Sets <RuntimeLibrary> to "MultiThreaded" in VS
filter "configurations:Debug"
defines { "DEBUG" }
flags { "MultiProcessorCompile" }
symbols "On"
filter "configurations:Release"
defines { "RELEASE" }
flags { "MultiProcessorCompile", "FatalWarnings" }
optimize "On"
filter "configurations:Dist"
defines { "DIST" }
flags { "MultiProcessorCompile", "FatalWarnings" }
optimize "Speed"
group "Vendor"
project "Glad"
kind "StaticLib"
language "C"
location "vendor"
targetdir "bin/obj/%{cfg.buildcfg}"
files {
"vendor/glad/**.c",
}
includedirs {
"vendor/glad",
}
project "GLFW"
kind "StaticLib"
language "C"
targetdir "bin/obj/%{cfg.buildcfg}"
location "vendor"
files {
"vendor/glfw/src/internal.h",
"vendor/glfw/src/mappings.h",
"vendor/glfw/src/glfw_config.h",
"vendor/glfw/include/GLFW/glfw3.h",
"vendor/glfw/include/GLFW/glfw3native.h",
"vendor/glfw/src/context.c",
"vendor/glfw/src/init.c",
"vendor/glfw/src/input.c",
"vendor/glfw/src/monitor.c",
"vendor/glfw/src/vulkan.c",
"vendor/glfw/src/window.c"
}
filter "system:macosx"
files {
"vendor/glfw/src/cocoa_init.m",
"vendor/glfw/src/cocoa_joystick.m",
"vendor/glfw/src/cocoa_monitor.m",
"vendor/glfw/src/cocoa_window.m",
"vendor/glfw/src/cocoa_time.c",
"vendor/glfw/src/posix_thread.c",
"vendor/glfw/src/nsgl_context.m",
"vendor/glfw/src/egl_context.c",
"vendor/glfw/src/osmesa_context.c",
}
defines {
"_GLFW_COCOA"
}
filter "system:linux"
pic "On"
files {
"vendor/glfw/src/x11_init.c",
"vendor/glfw/src/x11_monitor.c",
"vendor/glfw/src/x11_window.c",
"vendor/glfw/src/xkb_unicode.c",
"vendor/glfw/src/posix_time.c",
"vendor/glfw/src/posix_thread.c",
"vendor/glfw/src/glx_context.c",
"vendor/glfw/src/egl_context.c",
"vendor/glfw/src/osmesa_context.c",
"vendor/glfw/src/linux_joystick.c"
}
defines {
"_GLFW_X11"
}
filter "system:windows"
files {
"vendor/glfw/src/win32_init.c",
"vendor/glfw/src/win32_joystick.c",
"vendor/glfw/src/win32_monitor.c",
"vendor/glfw/src/win32_time.c",
"vendor/glfw/src/win32_thread.c",
"vendor/glfw/src/win32_window.c",
"vendor/glfw/src/wgl_context.c",
"vendor/glfw/src/egl_context.c",
"vendor/glfw/src/osmesa_context.c"
}
defines {
"_GLFW_WIN32",
"_CRT_SECURE_NO_WARNINGS"
}
project "ImGui"
kind "StaticLib"
language "C++"
location "vendor"
targetdir "bin/obj/%{cfg.buildcfg}"
files {
"vendor/imgui/*.cpp",
"vendor/imgui/examples/imgui_impl_opengl3.cpp",
}
includedirs {
"vendor/glfw/include",
"vendor/glad",
"vendor/imgui",
}
project "Utils"
kind "StaticLib"
language "C++"
location "vendor"
targetdir "bin/obj/%{cfg.buildcfg}"
files {
"vendor/stb/**.cpp",
}
includedirs {
"vendor/stb"
}
group ""
project "Engine"
kind "StaticLib"
location "Engine"
language "C++"
cppdialect "C++17"
buildoptions { "-Wall" }
targetdir "bin/obj/%{cfg.buildcfg}"
pchheader "EngineCommon.h"
pchsource "Engine/EngineCommon.cpp"
files {
"Engine/**.h*",
"Engine/**.cpp",
}
includedirs {
"Engine",
"vendor/spdlog/include",
"vendor/glfw/include",
"vendor/glad",
"vendor/imgui",
"vendor/glm",
"vendor/stb"
}
project "EngineTests"
kind "ConsoleApp"
location "EngineTests"
language "C++"
cppdialect "C++17"
buildoptions { "-Wall" }
files {
"EngineTests/**.h*",
"EngineTests/**.cpp",
}
includedirs {
"Engine",
"EngineTests",
"vendor/spdlog/include",
"vendor/imgui",
"vendor/glm",
}
links { "Engine", "GLFW", "Glad", "ImGui", "Utils" }
|
local Board = require "src.board"
local Sidebar = require "src.ui.sidebar"
local Settings = require "src.settings"
local class = require "lib.middleclass"
--- @class Game
--- @field new fun(self: Game)
local Game = class("Game")
function Game:initialize()
self.start_time = 0
self.time = 0
self.level = 0
self.score = 0
self.back_to_back = 0
self.lines_cleared = 0
self.dropping = false
self.step_interval_time = 20
self.move_interval = 0.1
self.move_interval_time = 0
self.sidebar = Sidebar:new(
NUM_COLS * CELL_SIZE,
NUM_COLS * CELL_SIZE + STATS_WIDTH
)
self.board = Board:new(self, NUM_COLS, NUM_ROWS, CELL_SIZE)
self.settings = Settings:new()
end
--- Updates score and back-to-back count depending on number of lines cleared.
--- Also updates level if the required lines are reached.
--- @param num_lines integer @ The number of lines cleared.
function Game:onLinesCleared(num_lines)
-- Update back-to-back tetris count
if num_lines >= 4 then
self.back_to_back = self.back_to_back + 1
else
self.back_to_back = 0
end
-- Score 100 per line, plus 100 per back-to-back tetris
local added_score = num_lines * 100 + self.back_to_back * 100
self.score = self.score + added_score
self.lines_cleared = self.lines_cleared + num_lines
if self.lines_cleared >= self.level * 10 + 10 then self.level = self.level + 1 end
end
--- Returns the time a piece spends in one single row
--- @return number @ The time a piece spends in one row
function Game:stepInterval()
local regularInterval = ((0.8 - self.level * 0.007) ^ self.level)
return self.dropping and math.min(0.05, regularInterval) or regularInterval
end
-- Returns the time between sideways movements of a piece
--- @return number @ The time between sideways movements
function Game:moveInterval()
return math.min(0.05, self:stepInterval())
end
--- Resets the game
--- @return Game @ The reset game
function Game:reset()
self = Game:new()
return self
end
return Game
|
-- Copyright (C) 2017-2018 by chrono
-- modify response headers
ngx.header["Host-Name"] = ngx.var.hostname
-- we should set content-length for keep alive
-- send headers must before say or print
ngx.send_headers()
assert(ngx.headers_sent)
-- send response body data
ngx.say("openresty test req params\n")
ngx.say("nginx : ", ngx.config.nginx_version)
ngx.say("openresty : ", ngx.config.ngx_lua_version)
ngx.say("jit : ", jit.os, ",", jit.arch, ",", jit.version)
ngx.say("")
local method = ngx.req.get_method()
ngx.say("method = ", method)
local uri = ngx.var.request_uri
ngx.say("uri = ", uri)
ngx.say("http = ", ngx.req.http_version())
ngx.say("")
local headers = ngx.req.get_headers()
local count = 0
ngx.say("req headers are : ")
for k, v in pairs(headers) do
ngx.say("\t", k, " : ", v)
count = count + 1
end
ngx.say("total ", count, " headers")
-- finish body data
ngx.eof()
|
isMinigolfGamemodeActive = function()
local gm = gmod.GetGamemode()
return gm and gm.IsMinigolf == true
end
hook.Add("OnGamemodeLoaded", "Minigolf.OnlyLoadDevKitAfterGamemode", function()
if(isMinigolfGamemodeActive())then
print("Minigolf DevKit not loading: Minigolf gamemode is active!")
return
end
if(not game.GetMap():StartWith("golf_"))then
print("Minigolf DevKit not loading: not on a golf map!")
return
end
print("Minigolf DevKit loading!")
-- Load the entities
ENT = {}
if CLIENT then
include("golf_entities/minigolf_ball/cl_init.lua")
else
include("golf_entities/minigolf_ball/init.lua")
end
scripted_ents.Register(ENT, "minigolf_ball")
ENT = {}
if CLIENT then
include("golf_entities/minigolf_hole_start/cl_init.lua")
else
include("golf_entities/minigolf_hole_start/init.lua")
end
scripted_ents.Register(ENT, "minigolf_hole_start")
ENT = {}
if CLIENT then
include("golf_entities/minigolf_hole_end/cl_init.lua")
else
include("golf_entities/minigolf_hole_end/init.lua")
end
scripted_ents.Register(ENT, "minigolf_hole_end")
ENT = {}
if CLIENT then
include("golf_entities/minigolf_hole_flag/cl_init.lua")
else
include("golf_entities/minigolf_hole_flag/init.lua")
end
scripted_ents.Register(ENT, "minigolf_hole_flag")
ENT = {}
if SERVER then
include("golf_entities/minigolf_trigger_oob/init.lua")
end
scripted_ents.Register(ENT, "minigolf_trigger_oob")
-- Ensure that players don't collide with balls
hook.Add("ShouldCollide", "Minigolf.StopPlayerCollisionWithBalls", function(ent1, ent2)
if(IsValid(ent1) and IsValid(ent2)
and (ent1:IsPlayer() or ent2:IsPlayer()) and (ent1:GetClass() == "minigolf_ball" or ent2:GetClass() == "minigolf_ball")) then
return false
end
end)
if(SERVER)then
hook.Add("KeyPress", "Minigolf.AllowUseBall", function( golfer, key )
if( key == IN_USE )then
local tr = golfer:GetEyeTraceNoCursor()
for _, ent in ipairs(ents.FindInSphere(tr.HitPos, 128))do
if(IsValid(ent) and ent:GetClass() == "minigolf_ball")then
ent:OnUse(golfer)
end
end
end
end)
elseif(CLIENT)then
local HideDefaultHUDElements = {
CHudHealth = true,
CHudBattery = true,
CHudAmmo = true,
CHudDamageIndicator = true,
CHudWeaponSelection = true,
}
hook.Add("HUDShouldDraw", "Minigolf.HideDefaultHUD", function(name)
if(HideDefaultHUDElements[name]) then
return false
end
end)
hook.Add("PreDrawHalos", "Minigolf.AddSentHalos", function()
halo.Add( ents.FindByClass( "minigolf_*" ), Color( 255, 0, 0 ), 5, 5, 2 )
end)
local devKitLogo = Material("minigolf/devkit/logo_compact.png")
local logoW, logoH = 256, 256
local PADDING = 5
hook.Add("HUDPaint", "Minigolf.DrawDebugUI", function()
-- Draw indicators that devkit dev is running
surface.SetDrawColor(255, 255, 255, 25)
surface.SetMaterial(devKitLogo)
local logoX = ScrW() - logoW
surface.DrawTexturedRect(logoX, PADDING, logoW, logoH)
surface.SetTextColor(255, 255, 255, 25)
surface.SetFont("Trebuchet24")
local textW = select(1, surface.GetTextSize("Minigolf DevKit Active"))
surface.SetTextPos(logoX + (logoW * .5) - (textW * .5) - 25, PADDING + logoH - 30) -- -25 because the logo is off-center due to the flag / -30 because there's a lot of whitespace around the logo
surface.DrawText("Minigolf DevKit Active")
-- Draw start info
for k,v in pairs(ents.FindByClass( "minigolf_hole_start" )) do
local vPos = v:GetPos():ToScreen()
local currentY = vPos.y
surface.SetTextColor(255, 255, 255, 200)
surface.SetFont("Trebuchet24")
local textH = select(2, surface.GetTextSize("Doesn't matter for the height"))
surface.SetTextPos(vPos.x, currentY)
surface.DrawText("Start of the hole: '" .. v:GetHoleName() .. "'")
currentY = currentY + PADDING + textH
surface.SetTextPos(vPos.x, currentY)
surface.DrawText("Par: " .. v:GetPar())
currentY = currentY + PADDING + textH
surface.SetTextPos(vPos.x, currentY)
surface.DrawText("Maximum tries of: " .. v:GetMaxStrokes() .. " strokes")
currentY = currentY + PADDING + textH
surface.SetTextPos(vPos.x, currentY)
surface.DrawText("Max. Pitch: " .. v:GetMaxPitch() .. " degrees")
currentY = currentY + PADDING + textH
surface.SetTextPos(vPos.x, currentY)
surface.DrawText("Time Limit: " .. v:GetLimit() .. " seconds")
currentY = currentY + PADDING + textH
surface.SetTextPos(vPos.x, currentY)
surface.DrawText("Optional Description: '" .. v:GetDescription() .. "'")
currentY = currentY + PADDING + textH
end
-- Draw ball info
for k,v in pairs(ents.FindByClass( "minigolf_ball" )) do
local vPos = v:GetPos():ToScreen()
local currentY = vPos.y
surface.SetTextColor(255, 255, 255, 200)
surface.SetFont("Trebuchet24")
local textH = select(2, surface.GetTextSize("asd"))
surface.SetTextPos(vPos.x, currentY)
surface.DrawText("Ball of golfer:" .. v:GetNWString("GolferName"))
end
end)
end
end) |
-- Constructors
-- Patterns have the following, optional fields:
--
-- - type: the pattern type. ~1 to 1 correspondance with the pattern constructors
-- described in the LPeg documentation.
-- - pattern: the one subpattern held by the pattern, like most captures, or
-- `#pt`, `-pt` and `pt^n`.
-- - aux: any other type of data associated to the pattern. Like the string of a
-- `P"string"`, the range of an `R`, or the list of subpatterns of a `+` or
-- `*` pattern. In some cases, the data is pre-processed. in that case,
-- the `as_is` field holds the data as passed to the constructor.
-- - as_is: see aux.
-- - meta: A table holding meta information about patterns, like their
-- minimal and maximal width, the form they can take when compiled,
-- whether they are terminal or not (no V patterns), and so on.
local getmetatable, ipairs, newproxy, print, setmetatable
= getmetatable, ipairs, newproxy, print, setmetatable
local t, u, compat
= require"table", require"util", require"compat"
--[[DBG]] local debug = require"debug"
local t_concat = t.concat
local copy, getuniqueid, id, map
, weakkey, weakval
= u.copy, u.getuniqueid, u.id, u.map
, u.weakkey, u.weakval
local _ENV = u.noglobals() ----------------------------------------------------
--- The type of cache for each kind of pattern:
--
-- Patterns are memoized using different strategies, depending on what kind of
-- data is associated with them.
local patternwith = {
constant = {
"Cp", "true", "false"
},
-- only aux
aux = {
"string", "any",
"char", "range", "set",
"ref", "sequence", "choice",
"Carg", "Cb"
},
-- only sub pattern
subpt = {
"unm", "lookahead", "C", "Cf",
"Cg", "Cs", "Ct", "/zero"
},
-- both
both = {
"behind", "at least", "at most", "Clb", "Cmt",
"div_string", "div_number", "div_table", "div_function"
},
none = "grammar", "Cc"
}
-------------------------------------------------------------------------------
return function(Builder, LL) --- module wrapper.
--
local S_tostring = Builder.set.tostring
-------------------------------------------------------------------------------
--- Base pattern constructor
--
local newpattern, pattmt
-- This deals with the Lua 5.1/5.2 compatibility, and restricted
-- environements without access to newproxy and/or debug.setmetatable.
-- Augment a pattern with unique identifier.
local next_pattern_id = 1
if compat.proxies and not compat.lua52_len then
-- Lua 5.1 / LuaJIT without compat.
local proxycache = weakkey{}
local __index_LL = {__index = LL}
local baseproxy = newproxy(true)
pattmt = getmetatable(baseproxy)
Builder.proxymt = pattmt
function pattmt:__index(k)
return proxycache[self][k]
end
function pattmt:__newindex(k, v)
proxycache[self][k] = v
end
function LL.getdirect(p) return proxycache[p] end
function newpattern(cons)
local pt = newproxy(baseproxy)
setmetatable(cons, __index_LL)
proxycache[pt]=cons
pt.id = "__ptid" .. next_pattern_id
next_pattern_id = next_pattern_id + 1
return pt
end
else
-- Fallback if neither __len(table) nor newproxy work
-- for example in restricted sandboxes.
if LL.warnings and not compat.lua52_len then
print("Warning: The `__len` metamethod won't work with patterns, "
.."use `LL.L(pattern)` for lookaheads.")
end
pattmt = LL
function LL.getdirect (p) return p end
function newpattern(pt)
pt.id = "__ptid" .. next_pattern_id
next_pattern_id = next_pattern_id + 1
return setmetatable(pt,LL)
end
end
Builder.newpattern = newpattern
local
function LL_ispattern(pt) return getmetatable(pt) == pattmt end
LL.ispattern = LL_ispattern
function LL.type(pt)
if LL_ispattern(pt) then
return "pattern"
else
return nil
end
end
-------------------------------------------------------------------------------
--- The caches
--
local ptcache, meta
local
function resetcache()
ptcache, meta = {}, weakkey{}
Builder.ptcache = ptcache
-- Patterns with aux only.
for _, p in ipairs(patternwith.aux) do
ptcache[p] = weakval{}
end
-- Patterns with only one sub-pattern.
for _, p in ipairs(patternwith.subpt) do
ptcache[p] = weakval{}
end
-- Patterns with both
for _, p in ipairs(patternwith.both) do
ptcache[p] = {}
end
return ptcache
end
LL.resetptcache = resetcache
resetcache()
-------------------------------------------------------------------------------
--- Individual pattern constructor
--
local constructors = {}
Builder.constructors = constructors
constructors["constant"] = {
truept = newpattern{ pkind = "true" },
falsept = newpattern{ pkind = "false" },
Cppt = newpattern{ pkind = "Cp" }
}
-- data manglers that produce cache keys for each aux type.
-- `id()` for unspecified cases.
local getauxkey = {
string = function(aux, as_is) return as_is end,
table = copy,
set = function(aux, as_is)
return S_tostring(aux)
end,
range = function(aux, as_is)
return t_concat(as_is, "|")
end,
sequence = function(aux, as_is)
return t_concat(map(getuniqueid, aux),"|")
end
}
getauxkey.choice = getauxkey.sequence
constructors["aux"] = function(typ, aux, as_is)
-- dprint("CONS: ", typ, pt, aux, as_is)
local cache = ptcache[typ]
local key = (getauxkey[typ] or id)(aux, as_is)
local res_pt = cache[key]
if not res_pt then
res_pt = newpattern{
pkind = typ,
aux = aux,
as_is = as_is
}
cache[key] = res_pt
end
return res_pt
end
-- no cache for grammars
constructors["none"] = function(typ, aux)
-- [[DBG]] print("CONS: ", typ, _, aux)
-- [[DBG]] print(debug.traceback(1))
return newpattern{
pkind = typ,
aux = aux
}
end
constructors["subpt"] = function(typ, pt)
-- [[DP]]print("CONS: ", typ, pt, aux)
local cache = ptcache[typ]
local res_pt = cache[pt.id]
if not res_pt then
res_pt = newpattern{
pkind = typ,
pattern = pt
}
cache[pt.id] = res_pt
end
return res_pt
end
constructors["both"] = function(typ, pt, aux)
-- [[DBG]] print("CONS: ", typ, pt, aux)
local cache = ptcache[typ][aux]
if not cache then
ptcache[typ][aux] = weakval{}
cache = ptcache[typ][aux]
end
local res_pt = cache[pt.id]
if not res_pt then
res_pt = newpattern{
pkind = typ,
pattern = pt,
aux = aux,
cache = cache -- needed to keep the cache as long as the pattern exists.
}
cache[pt.id] = res_pt
end
return res_pt
end
constructors["binary"] = function(typ, a, b)
-- [[DBG]] print("CONS: ", typ, pt, aux)
return newpattern{
a, b;
pkind = typ,
}
end
end -- module wrapper
-- The Romantic WTF public license.
-- --------------------------------
-- a.k.a. version "<3" or simply v3
--
--
-- Dear user,
--
-- The LuLPeg library
--
-- \
-- '.,__
-- \ /
-- '/,__
-- /
-- /
-- /
-- has been / released
-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
-- under the Romantic WTF Public License.
-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~`,´ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
-- I hereby grant you an irrevocable license to
-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
-- do what the gentle caress you want to
-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
-- with this lovely
-- ~ ~ ~ ~ ~ ~ ~ ~
-- / thing...
-- / ~ ~ ~ ~
-- / Love,
-- # / '.'
-- ####### ·
-- #####
-- ###
-- #
--
-- -- Pierre-Yves
--
--
-- P.S.: Even though I poured my heart into this work,
-- I _cannot_ provide any warranty regarding
-- its fitness for _any_ purpose. You
-- acknowledge that I will not be held liable
-- for any damage its use could incur.
|
local config = require("aerial.config")
describe("config", function()
before_each(function()
pcall(vim.api.nvim_del_var, "aerial")
end)
it("falls back to default options", function()
assert.equals(config.close_behavior, "auto")
end)
it("reads options from g:aerial dict var", function()
vim.g.aerial = {
close_behavior = "persist",
}
assert.equals(config.close_behavior, "persist")
end)
it("reads options from g:aerial_<name> vars", function()
vim.g.aerial_close_behavior = "persist"
assert.equals(config.close_behavior, "persist")
vim.api.nvim_del_var("aerial_close_behavior")
end)
it("merges nested options with g:aerial dict", function()
vim.g.aerial = {
float = {
row = 10,
},
}
assert.equals(config["float.row"], 10)
assert.equals(config.float.row, 10)
assert.equals(config["float.col"], 0)
assert.equals(config.float.col, 0)
end)
it("merges nested options with g:aerial_<name> vars", function()
vim.g.aerial_float_row = 10
assert.equals(config["float.row"], 10)
assert.equals(config.float.row, 10)
vim.api.nvim_del_var("aerial_float_row")
end)
-- Filetype maps
it("reads the default value for filetype map option", function()
assert.equals(config.open_automatic(), false)
end)
it("reads the filetype default value for filetype map option", function()
vim.g.aerial = {
open_automatic = {
["_"] = 1,
},
}
assert.equals(config.open_automatic(), true)
end)
it("reads the filetype value for filetype map option", function()
vim.g.aerial = {
open_automatic = {
fake_ft = 1,
},
}
vim.api.nvim_buf_set_option(0, "filetype", "fake_ft")
assert.equals(config.open_automatic(), true)
end)
-- Filter kind
it("reads the filter_kind option", function()
vim.g.aerial = {
filter_kind = { "Function" },
}
local fk = config.get_filter_kind_map("foo")
assert.equals(nil, fk.Class)
assert.equals(true, fk.Function)
end)
it("reads the filter_kind option from filetype map", function()
vim.g.aerial = {
filter_kind = { foo = { "Function" } },
}
local fk = config.get_filter_kind_map("foo")
assert.equals(nil, fk.Class)
assert.equals(true, fk.Function)
end)
it("recognizes when filter_kind is false", function()
vim.g.aerial = {
filter_kind = { foo = 0 },
}
local fk = config.get_filter_kind_map("foo")
assert.equals(true, fk.Class)
assert.equals(true, fk.Function)
end)
-- Icons
it("reads icons from the default table", function()
vim.g.aerial = {
nerd_font = true,
}
assert.equals("", config._get_icons()["Function"])
end)
it("reads icons from g:aerial dict var", function()
vim.g.aerial = {
nerd_font = true,
icons = {
Function = "*",
},
}
assert.equals("*", config._get_icons()["Function"])
assert.equals("", config._get_icons()["Method"])
end)
-- This is for backwards compatibility with lsp options that used to be in the
-- global namespace
it("reads lsp_ options from g:aerial dict var", function()
assert.equals(config["lsp.update_when_errors"], true)
vim.g.aerial = {
update_when_errors = false,
}
assert.equals(config["lsp.update_when_errors"], false)
assert.equals(config.lsp.update_when_errors, false)
end)
it("reads lsp_ options from g:aerial_<name> vars", function()
assert.equals(config["lsp.update_when_errors"], true)
vim.g.aerial_update_when_errors = false
assert.equals(config["lsp.update_when_errors"], false)
assert.equals(config.lsp.update_when_errors, false)
vim.api.nvim_del_var("aerial_update_when_errors")
end)
end)
|
local M = {}
function M.get(cp)
return {
NeogitBranch = { fg = cp.pink },
NeogitRemote = { fg = cp.pink },
NeogitHunkHeader = { bg = cp.blue, fg = cp.white },
NeogitHunkHeaderHighlight = { bg = cp.black4, fg = cp.blue },
NeogitDiffContextHighlight = { bg = cp.gray2, fg = cp.green },
NeogitDiffDeleteHighlight = { fg = cp.red, bg = cp.black2 },
NeogitDiffAddHighlight = { fg = cp.blue, bg = cp.black2 },
}
end
return M
|
local playsession = {
{"Olekplane1", {71483}},
{"vad7ik", {9561}},
{"Jemlinski", {663}},
{"kajkaj123", {2975}},
{"dr_evil", {32283}},
{"Gerkiz", {20383}},
{"Diangeres", {19556}}
}
return playsession |
function switch(c)
local swtbl = {
casevar = c,
caseof = function (self, code)
local f
if (self.casevar) then
f = code[self.casevar] or code.default
else
f = code.missing or code.default
end
if f then
if type(f)=="function" then
return f(self.casevar,self)
else
error("case "..tostring(self.casevar).." not a function")
end
end
end
}
return swtbl
end
c = 1
switch(c) : caseof {
[1] = function (x) print(x,"one") end,
[2] = function (x) print(x,"two") end,
[3] = 12345, -- this is an invalid case stmt
default = function (x) print(x,"default") end,
missing = function (x) print(x,"missing") end,
}
print("expect to see 468: ".. 123 +
switch(2):caseof{
[1] = function(x) return 234 end,
[2] = function(x) return 345 end
})
|
local self = ...
local ud = u(self)
local p = ud.parent
return ud.shown and (not p or m(p, 'IsVisible'))
|
--------------------------------------------------
-- DIRETIDE Roshan AI
--------------------------------------------------
-- Author: zimberzimber
-- Date: 30.8.2017
if imba_roshan_ai_diretide == nil then imba_roshan_ai_diretide = class({}) end
LinkLuaModifier("modifier_imba_roshan_ai_diretide", "components/modifiers/diretide/roshan_diretide", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_roshan_ai_beg", "components/modifiers/diretide/roshan_diretide", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_roshan_ai_eat", "components/modifiers/diretide/roshan_diretide", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_roshan_eaten_candy", "components/modifiers/diretide/roshan_diretide", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_roshan_acceleration", "components/modifiers/diretide/roshan_diretide", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_imba_roshan_death_buff", "components/modifiers/diretide/roshan_diretide", LUA_MODIFIER_MOTION_NONE)
function imba_roshan_ai_diretide:GetIntrinsicModifierName()
return "modifier_imba_roshan_ai_diretide" end
------------------------------------------
-- Modifiers --
------------------------------------------
if modifier_imba_roshan_ai_diretide == nil then modifier_imba_roshan_ai_diretide = class({}) end
function modifier_imba_roshan_ai_diretide:GetAttributes() return MODIFIER_ATTRIBUTE_PERMANENT + MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE end
function modifier_imba_roshan_ai_diretide:IsPurgeException() return false end
function modifier_imba_roshan_ai_diretide:IsPurgable() return false end
function modifier_imba_roshan_ai_diretide:IsDebuff() return false end
function modifier_imba_roshan_ai_diretide:IsHidden() return true end
-- GENERAL
function modifier_imba_roshan_ai_diretide:GetPriority()
return MODIFIER_PRIORITY_SUPER_ULTRA end
function modifier_imba_roshan_ai_diretide:GetModifierProvidesFOWVision()
-- if self:GetStackCount() == 3 then
-- return 0
-- else
return 1
-- end
end
function modifier_imba_roshan_ai_diretide:GetActivityTranslationModifiers()
if self:GetStackCount() == 3 then
return "sugarrush"
else return nil end
end
function modifier_imba_roshan_ai_diretide:DeclareFunctions()
return { MODIFIER_PROPERTY_TRANSLATE_ACTIVITY_MODIFIERS,
MODIFIER_PROPERTY_PROVIDES_FOW_POSITION,
MODIFIER_EVENT_ON_ATTACK_LANDED,
MODIFIER_EVENT_ON_ATTACK_START,
MODIFIER_EVENT_ON_TAKEDAMAGE }
end
function modifier_imba_roshan_ai_diretide:CheckState()
local state = {}
if self:GetStackCount() == 1 then
state = {
[MODIFIER_STATE_ATTACK_IMMUNE] = true,
[MODIFIER_STATE_INVULNERABLE] = true,
[MODIFIER_STATE_MAGIC_IMMUNE] = true,
[MODIFIER_STATE_CANNOT_MISS] = true,
[MODIFIER_STATE_ROOTED] = true,
[MODIFIER_STATE_DISARMED] = true,
[MODIFIER_STATE_SILENCED] = false,
[MODIFIER_STATE_MUTED] = false,
[MODIFIER_STATE_STUNNED] = false,
[MODIFIER_STATE_HEXED] = false,
[MODIFIER_STATE_INVISIBLE] = false,
[MODIFIER_STATE_UNSELECTABLE] = true }
elseif self:GetStackCount() == 2 then
state = {
[MODIFIER_STATE_ATTACK_IMMUNE] = true,
[MODIFIER_STATE_INVULNERABLE] = true,
[MODIFIER_STATE_MAGIC_IMMUNE] = true,
[MODIFIER_STATE_CANNOT_MISS] = true,
[MODIFIER_STATE_ROOTED] = false,
[MODIFIER_STATE_DISARMED] = false,
[MODIFIER_STATE_SILENCED] = false,
[MODIFIER_STATE_MUTED] = false,
[MODIFIER_STATE_STUNNED] = false,
[MODIFIER_STATE_HEXED] = false,
[MODIFIER_STATE_INVISIBLE] = false, }
if self.isEatingCandy then
state[MODIFIER_STATE_UNSELECTABLE] = true
state[MODIFIER_STATE_DISARMED] = true
state[MODIFIER_STATE_ROOTED] = true
elseif self.begState == 1 then
state[MODIFIER_STATE_DISARMED] = true
state[MODIFIER_STATE_ROOTED] = true
end
elseif self:GetStackCount() == 3 then
if self.isTransitioning then
state = { [MODIFIER_STATE_INVULNERABLE] = true,
[MODIFIER_STATE_UNSELECTABLE] = true,
[MODIFIER_STATE_DISARMED] = true,
[MODIFIER_STATE_ATTACK_IMMUNE] = true, }
if self.atStartPoint then
state[MODIFIER_STATE_ROOTED] = true
end
elseif self.returningToLeash then
state[MODIFIER_STATE_FLYING_FOR_PATHING_PURPOSES_ONLY] = true -- Because fuck those Overused Dildos and their Astral Prisons
end
end
-- Always phased, and hidden health bar
state[MODIFIER_STATE_NO_UNIT_COLLISION] = true -- Obvious reasons
state[MODIFIER_STATE_NO_HEALTH_BAR] = true -- Either not needed, or shown in the HUD
return state
end
function modifier_imba_roshan_ai_diretide:OnCreated()
if IsServer() then
-- common keys
local ability = self:GetAbility()
self.roshan = self:GetParent() -- Roshans entity for easier handling
self.AItarget = nil -- Targeted hero
-- phase 2 keys
self.targetTeam = math.random(DOTA_TEAM_GOODGUYS, DOTA_TEAM_BADGUYS) -- Team Roshan is currently targeting
self.begState = 0 -- 0 = not begged | 1 = begging | anything else = has begged
self.isEatingCandy = false -- Is Roshan eating a candy right now?
self.begDistance = ability:GetSpecialValueFor("beg_distance") -- Distance from target to start begging
-- phase 3 keys
self.isTransitioning = false -- Is Roshan playing the transition animation?
self.atStartPoint = false -- Has Roshan reached the start point?
self.acquisition_range = ability:GetSpecialValueFor("acquisition_range") -- Acquisition range for phase 3
self.leashPoint = nil -- Phase 3 arena mid point (defined in phase 3 thinking function)
self.leashDistance = ability:GetSpecialValueFor("leash_distance") -- How far is Roshan allowed to walk away from the starting point
self.leashHealPcnt = ability:GetSpecialValueFor("leash_heal_pcnt") -- Percent of max health Roshan will heal should he get leashed
self.isDead = false -- Is Roshan 'dead'?
self.deathPoint = Vector(0,0,0) -- Roshans last death point to which he will return upon respawn
self.deathCounter = 0 -- Times Roshan died
self.refreshed_heroes = false
-- Sound delays to sync with animation
self.candyBeg = 0.5
self.candyEat = 0.15
self.candySniff = 3.33
self.candyRoar = 5.9
self.pumpkinDrop = 0.3
self.candyGobble = 0.5
self.gobbleRoar = 4.7
self.deathRoar = 1.9
-- Aimation durations
self.animBeg = 5
self.animGobble = 6
self.animDeath = 10
-- Ability handlers
self.forceWave = self.roshan:FindAbilityByName("roshan_deafening_blast")
self.roshlings = self.roshan:FindAbilityByName("imba_roshan_diretide_summon_roshlings")
self.breath = self.roshan:FindAbilityByName("creature_fire_breath")
self.apocalypse = self.roshan:FindAbilityByName("imba_roshan_diretide_apocalypse")
self.fireBall = self.roshan:FindAbilityByName("imba_roshan_diretide_fireball")
self.toss = self.roshan:FindAbilityByName("tiny_toss")
-- Passive effect KVs
self.bashChance = ability:GetSpecialValueFor("bash_chance") * 0.01
self.bashDamage = ability:GetSpecialValueFor("bash_damage")
self.bashDistance = ability:GetSpecialValueFor("bash_distance")
self.bashDuration = ability:GetSpecialValueFor("bash_duration")
-- Create a dummy for global vision
AddFOWViewer(self.roshan:GetTeamNumber(), Vector(0,0,0), 250000, 999999, false)
-- Turn on brain
self.targetTeam = DOTA_TEAM_GOODGUYS
self:SetStackCount(1)
end
end
function modifier_imba_roshan_ai_diretide:OnStackCountChanged(stacks)
if IsServer() then
-- Get new stacks, and start thinking if its 2 or 3, or become idle if its 1 or anything else
local stacks = self:GetStackCount()
if stacks < 1 then
stacks = 1
end
self:StartPhase(stacks)
end
end
function modifier_imba_roshan_ai_diretide:OnIntervalThink()
local stacks = self:GetStackCount()
if self.roshan:IsAlive() then
-- When back from the dead, respawns Rosh at his death point
if self.isDead then
self.isDead = false
end
if stacks == 2 and not self.isEatingCandy then
if self.targetTeam ~= DOTA_TEAM_GOODGUYS and self.targetTeam ~= DOTA_TEAM_BADGUYS then
self.targetTeam = math.random(DOTA_TEAM_GOODGUYS, DOTA_TEAM_BADGUYS)
end
self:ThinkPhase2(self.roshan)
elseif stacks == 3 then
self:ThinkPhase3(self.roshan)
end
else
-- Spawn death particle, start the respawn timer, index death point
if not self.isDead then
self.deathPoint = self.roshan:GetAbsOrigin()
self.isDead = true
self.deathCounter = self.deathCounter + 1
Diretide.DIRETIDE_REINCARNATING = true
-- Play sounds
self.roshan:EmitSound("Diretide.RoshanDeathLava")
self.roshan:EmitSound("Diretide.RoshanDeath1")
Timers:CreateTimer(self.deathRoar, function()
self.roshan:EmitSound("Diretide.RoshanDeath2")
end)
-- Play particle
local deathParticle = ParticleManager:CreateParticle("particles/hw_fx/hw_roshan_death.vpcf", PATTACH_CUSTOMORIGIN, nil)
ParticleManager:SetParticleControl(deathParticle, 0, self.roshan:GetAbsOrigin())
ParticleManager:ReleaseParticleIndex(deathParticle)
Timers:CreateTimer(self.animDeath, function()
if self.isDead then
self.roshan:RespawnUnit()
self.roshan:CreatureLevelUp(1)
Diretide.nCOUNTDOWNTIMER = Diretide.nCOUNTDOWNTIMER + 30.0
self.refreshed_heroes = false
if self.forceWave then self.forceWave:EndCooldown() end
if self.roshlings then self.roshlings:EndCooldown() end
if self.breath then self.breath:EndCooldown() end
if self.apocalypse then self.apocalypse:EndCooldown() end
if self.fireBall then self.fireBall:EndCooldown() end
if self.toss then self.toss:EndCooldown() end
local deathMod = self.roshan:FindModifierByName("modifier_imba_roshan_death_buff")
if not deathMod then
deathMod = self.roshan:AddNewModifier(self.roshan, self:GetAbility(), "modifier_imba_roshan_death_buff", {})
end
if deathMod then
deathMod:SetStackCount(self.deathCounter)
else
print("ERROR - DEATH COUNTING MODIFIER MISSING AND FAILED TO APPLY TO ROSHAN")
end
Diretide.DIRETIDE_REINCARNATING = false
end
end)
end
end
end
function modifier_imba_roshan_ai_diretide:StartPhase(phase)
-- Reset values
self.begState = 0
self.AItarget = nil
self.targetTeam = 0
self.isEatingCandy = false
self.isTransitioning = false
self.atStartPoint = false
self.wait = 0
self.leashPoint = nil
self.deathPoint = self.roshan:GetAbsOrigin()
self.deathCounter = 0
if self.isDead then
self.isDead = false
self.roshan:RespawnUnit()
end
if phase == 4 then return end
-- Reset behavior
self.roshan:SetAcquisitionRange(-1000)
self.roshan:SetForceAttackTarget(nil)
self.roshan:Interrupt()
self.roshan:SetHealth(self.roshan:GetMaxHealth())
-- Destroy candy eaten count
local candyMod = self.roshan:FindModifierByName("modifier_imba_roshan_eaten_candy")
if candyMod then candyMod:Destroy() end
-- Destroy all fury swipe modifiers
local units = FindUnitsInRadius(self.roshan:GetTeamNumber(), Vector(0,0,0), nil, FIND_UNITS_EVERYWHERE, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES + DOTA_UNIT_TARGET_FLAG_INVULNERABLE + DOTA_UNIT_TARGET_FLAG_OUT_OF_WORLD, FIND_CLOSEST, false)
for _, unit in ipairs(units) do
local swipesModifier = unit:FindModifierByName("modifier_imba_roshan_fury_swipes")
if swipesModifier then swipesModifier:Destroy() end
end
-- Destroy acceleration modifier
local accelerationMod = self.roshan:FindModifierByName("modifier_imba_roshan_acceleration")
if accelerationMod then accelerationMod:Destroy() end
if phase == 1 then -- Halts thinking, and become unrespawnable
self.roshan:SetUnitCanRespawn(false)
self:StartIntervalThink(-1)
else -- Starts thinking, and become respawnable
self.roshan:SetUnitCanRespawn(true)
if phase == 2 then
EmitGlobalSound("diretide_eventstart_Stinger")
self.roshan:AddNewModifier(self.roshan, self:GetAbility(), "modifier_imba_roshan_eaten_candy", {})
Timers:CreateTimer(5.8, function() -- Timer so music ends first
self:StartIntervalThink(0.1)
end)
elseif phase == 3 then
EmitGlobalSound("diretide_sugarrush_Stinger")
self.isTransitioning = true
self:StartIntervalThink(0.1)
UpdateRoshanBar(self.roshan, FrameTime() * 2)
end
end
end
-- PHASE II
function modifier_imba_roshan_ai_diretide:ThinkPhase2(roshan)
if not self.AItarget then -- If no target
local heroes = FindUnitsInRadius(roshan:GetTeamNumber(), roshan:GetAbsOrigin(), nil, FIND_UNITS_EVERYWHERE, DOTA_UNIT_TARGET_TEAM_BOTH, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES + DOTA_UNIT_TARGET_FLAG_INVULNERABLE + DOTA_UNIT_TARGET_FLAG_PLAYER_CONTROLLED + DOTA_UNIT_TARGET_FLAG_NOT_ILLUSIONS + DOTA_UNIT_TARGET_FLAG_OUT_OF_WORLD, FIND_ANY_ORDER, false)
for _, hero in ipairs(heroes) do
if hero:GetTeamNumber() == self.targetTeam then
if hero:IsAlive() then
self.AItarget = hero
self.roshan:SetForceAttackTarget(hero)
roshan:AddNewModifier(roshan, self:GetAbility(), "modifier_imba_roshan_acceleration", {})
EmitSoundOnClient("diretide_select_target_Stinger", hero:GetPlayerOwner())
CustomGameEventManager:Send_ServerToAllClients("roshan_target", {target = hero:GetUnitName(), team_target = hero:GetTeamNumber()})
break
end
end
end
else
local disconnected = true
if self.AItarget.GetPlayerID then
if PlayerResource:GetConnectionState(self.AItarget:GetPlayerID()) ~= 3 then
disconnected = false
end
-- else
-- disconnected = true
end
if self.AItarget and self.AItarget:IsAlive() and not self.AItarget:HasModifier("modifier_fountain_invulnerable") and disconnected == false then
if not self.roshan:IsAttackingEntity(self.AItarget) then
self.roshan:SetForceAttackTarget(self.AItarget)
end
else
self:ChangeTarget(self.roshan)
end
if self.begState == 0 then -- If haven't begged
if CalcDistanceBetweenEntityOBB(roshan, self.AItarget) <= self.begDistance then
self.begState = 1
roshan:AddNewModifier(roshan, nil, "modifier_imba_roshan_ai_beg", {duration = self.animBeg})
-- sound
Timers:CreateTimer(self.candyBeg, function()
roshan:EmitSound("Diretide.RoshanBeg")
end)
end
elseif self.begState == 1 then
else -- If has begged
end
end
end
function modifier_imba_roshan_ai_diretide:Candy(roshan)
self.isEatingCandy = true
roshan:SetForceAttackTarget(nil)
roshan:Interrupt()
local begMod = roshan:FindModifierByName("modifier_imba_roshan_ai_beg")
if begMod then begMod:DestroyNoAggro() end
-- Timer because if an animation modifying modifier gets removed and another gets added at the same moment, the new animation will not apply
Timers:CreateTimer(FrameTime(), function()
roshan:AddNewModifier(roshan, nil, "modifier_imba_roshan_ai_eat", {duration = 7})
Diretide:Announcer("Diretide.Announcer.Roshan.Fed")
print("ROSHAN ATE CANDY")
-- Sounds
Timers:CreateTimer(self.candyEat, function()
roshan:EmitSound("Diretide.RoshanEatCandy")
end)
Timers:CreateTimer(self.candySniff, function()
roshan:EmitSound("Diretide.RoshanSniff")
end)
Timers:CreateTimer(self.candyRoar, function()
roshan:EmitSound("Diretide.RoshanRoar")
end)
end)
local candyMod = roshan:FindModifierByName("modifier_imba_roshan_eaten_candy")
if not candyMod then
candyMod = roshan:AddNewModifier(roshan, self:GetAbility(), "modifier_imba_roshan_eaten_candy", {})
end
candyMod:IncrementStackCount()
end
function modifier_imba_roshan_ai_diretide:ChangeTarget(roshan)
self.AItarget = nil
self.begState = 0
self.isEatingCandy = false
roshan:SetForceAttackTarget(nil)
roshan:Interrupt()
-- Destroy all fury swipe modifiers
local units = FindUnitsInRadius(roshan:GetTeamNumber(), Vector(0,0,0), nil, FIND_UNITS_EVERYWHERE, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES + DOTA_UNIT_TARGET_FLAG_INVULNERABLE + DOTA_UNIT_TARGET_FLAG_OUT_OF_WORLD, FIND_CLOSEST, false)
for _, unit in ipairs(units) do
local swipesModifier = unit:FindModifierByName("modifier_imba_roshan_fury_swipes")
if swipesModifier then swipesModifier:Destroy() end
end
-- Destroy acceleration modifier
local accelerationMod = roshan:FindModifierByName("modifier_imba_roshan_acceleration")
if accelerationMod then accelerationMod:Destroy() end
local begMod = roshan:FindModifierByName("modifier_imba_roshan_ai_beg")
if begMod then begMod:DestroyNoAggro() end
if self.targetTeam == DOTA_TEAM_GOODGUYS then
self.targetTeam = DOTA_TEAM_BADGUYS
print("ROSHAN TARGET DIRE")
Diretide:Announcer("diretide", "roshan_target_bad")
else
print("ROSHAN TARGET RADIANT")
Diretide:Announcer("diretide", "roshan_target_good")
self.targetTeam = DOTA_TEAM_GOODGUYS
end
end
-- PHASE III
function modifier_imba_roshan_ai_diretide:ThinkPhase3(roshan)
-- Don't think while being stunned, hexed, or casting spells
if roshan:IsStunned() or roshan:IsHexed() or roshan:IsChanneling() or roshan:GetCurrentActiveAbility() then return end
-- Wait. No reason to decrement negative values
if self.wait < 0 then
return
elseif self.wait > 0 then
self.wait = self.wait - 1
return
end
if not self.leashPoint then
self.leashPoint = Entities:FindByName(nil, "good_healer_7"):GetAbsOrigin() -- Pick arena based on phase 2 winner
end
-- Transitioning from Phase 2 to 3
if self.isTransitioning then
if self.atStartPoint then return end
local distanceFromLeash = (roshan:GetAbsOrigin() - self.leashPoint):Length2D()
if distanceFromLeash > 100 then
roshan:SetForceAttackTarget(nil)
roshan:MoveToPosition(self.leashPoint)
if distanceFromLeash < 250 then
Entities:FindByName(nil, "good_healer_7"):ForceKill(false)
end
else
self.atStartPoint = true
EmitSoundOnLocationWithCaster(roshan:GetAbsOrigin(), "RoshanDT.", roshan)
roshan:SetForceAttackTarget(nil)
roshan:Interrupt()
roshan:StartGesture(ACT_TRANSITION)
Timers:CreateTimer(self.pumpkinDrop, function()
roshan:EmitSound("Diretide.RoshanBucketDrop")
end)
Timers:CreateTimer(self.candyGobble, function()
roshan:EmitSound("Diretide.RoshanGobble")
end)
Timers:CreateTimer(self.gobbleRoar, function()
roshan:EmitSound("Diretide.RoshanRoar2")
end)
Timers:CreateTimer(self.animGobble, function()
self.atStartPoint = false
self.isTransitioning = false
roshan:RemoveGesture(ACT_TRANSITION)
roshan:SetAcquisitionRange(self.acquisition_range)
Diretide:EndRoshanCamera()
end)
end
return
end
if Diretide.COUNT_DOWN and Diretide.COUNT_DOWN == false then
local heroDetector = FindUnitsInRadius(roshan:GetTeamNumber(), roshan:GetAbsOrigin(), nil, 700, DOTA_UNIT_TARGET_TEAM_BOTH, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NONE, FIND_CLOSEST, false)
if #heroDetector > 0 then
-- EnableCountdown(true)
else
self.wait = 5
return
end
end
-- Check if Roshan too far away from the leashing point
local distanceFromLeash = (roshan:GetAbsOrigin() - self.leashPoint):Length2D()
if not self.returningToLeash and distanceFromLeash >= self.leashDistance then
self.returningToLeash = true
roshan:SetHealth(roshan:GetHealth() + roshan:GetMaxHealth() * (self.leashHealPcnt * 0.01)) -- To bypass shit like AAs ult or Malediction healing reduction
elseif self.returningToLeash and distanceFromLeash < 100 then
roshan:Interrupt()
self.returningToLeash = false
end
-- Return to the leashing point if he should
if self.returningToLeash then
roshan:SetForceAttackTarget(nil)
roshan:MoveToPosition(self.leashPoint)
-- Destroy trees for dramatic effect because he has flying movement while being leashed
GridNav:DestroyTreesAroundPoint(roshan:GetAbsOrigin(), 150, false)
return
end
if self.refreshed_heroes == false then
if roshan:GetHealthPercent() <= 50 then
self.refreshed_heroes = true
for _, hero in pairs(HeroList:GetAllHeroes()) do
for i=0, 23, 1 do --The maximum number of abilities a unit can have is currently 16.
local current_ability = hero:GetAbilityByIndex(i)
if current_ability ~= nil then
current_ability:EndCooldown()
end
end
for i=0, 8, 1 do
local current_item = hero:GetItemInSlot(i)
if current_item ~= nil then
if current_item:GetName() ~= "item_refresher_datadriven" then --Refresher Orb does not refresh itself.
current_item:EndCooldown()
end
end
end
ParticleManager:SetParticleControlEnt(ParticleManager:CreateParticle("particles/items2_fx/refresher.vpcf", PATTACH_ABSORIGIN_FOLLOW, hero), 0, hero, PATTACH_POINT_FOLLOW, "attach_hitloc", hero:GetAbsOrigin(), true)
end
roshan:EmitSound("DOTA_Item.Refresher.Activate")
end
end
local ability_count = roshan:GetAbilityCount()
for ability_index = 0, ability_count - 1 do
local ability = roshan:GetAbilityByIndex( ability_index )
if ability and ability:IsInAbilityPhase() then
-- print("Cast Time:", ability:GetCastPoint())
if not roshan:HasModifier("modifier_black_king_bar_immune") then
roshan:EmitSound("DOTA_Item.BlackKingBar.Activate")
else
roshan:RemoveModifierByName("modifier_black_king_bar_immune")
end
roshan:AddNewModifier(roshan, self.ability, "modifier_black_king_bar_immune", {duration=0.2})
end
end
-- Don't attempt casting spells if Silenced
if not roshan:IsSilenced() then
-- If can summon Roshlings, summon them and keep thinking
if self.roshlings and self.roshlings:IsCooldownReady() then
local foundRoshling = false
local units = FindUnitsInRadius(roshan:GetTeamNumber(), roshan:GetAbsOrigin(), nil, FIND_UNITS_EVERYWHERE, DOTA_UNIT_TARGET_TEAM_FRIENDLY, DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_INVULNERABLE + DOTA_UNIT_TARGET_FLAG_OUT_OF_WORLD, FIND_CLOSEST, false)
for _, unit in ipairs(units) do
if unit:GetUnitLabel() == "npc_imba_roshling" then
foundRoshling = true
break
end
end
if foundRoshling then
self.roshlings:StartCooldown(self.roshlings:GetSpecialValueFor("spawn_think_cooldown"))
else
roshan:CastAbilityNoTarget(self.roshlings, 1)
end
end
-- Cast Force Wave if its available
if self.forceWave and self.forceWave:IsCooldownReady() then
local radius = self.forceWave:GetSpecialValueFor("travel_distance")
local nearbyHeroes = FindUnitsInRadius(roshan:GetTeamNumber(), roshan:GetAbsOrigin(), nil, radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NONE, FIND_CLOSEST, false)
if #nearbyHeroes >= 1 then
roshan:CastAbilityNoTarget(self.forceWave, 1)
return
end
end
-- Cast apocalypse if its available
if self.apocalypse and self.apocalypse:IsCooldownReady() then
local maxRange = self.apocalypse:GetSpecialValueFor("max_range")
local minRange = self.apocalypse:GetSpecialValueFor("min_range")
local minTargets = self.apocalypse:GetSpecialValueFor("min_targets")
local inRange = 0
local nearbyHeroes = FindUnitsInRadius(roshan:GetTeamNumber(), roshan:GetAbsOrigin(), nil, maxRange, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, FIND_CLOSEST, false)
for _, hero in ipairs(nearbyHeroes) do
if CalcDistanceBetweenEntityOBB(roshan, hero) >= minRange then
inRange = inRange + 1
end
end
if inRange >= minTargets then
roshan:CastAbilityNoTarget(self.apocalypse, 1)
return
end
end
-- Cast Fire Breath if its available
if self.breath and self.breath:IsCooldownReady() then
local searchRange = self.breath:GetSpecialValueFor("search_range")
local nearbyHeroes = FindUnitsInRadius(roshan:GetTeamNumber(), roshan:GetAbsOrigin(), nil, searchRange, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NONE, FIND_CLOSEST, false)
for _, hero in ipairs(nearbyHeroes) do
roshan:CastAbilityOnPosition(hero:GetAbsOrigin(), self.breath, 1)
return
end
end
-- Cast Fire Ball if its available
if self.fireBall and self.fireBall:IsCooldownReady() then
local range = self.fireBall:GetSpecialValueFor("range")
local minTargets = self.fireBall:GetSpecialValueFor("min_targets")
local nearbyHeroes = FindUnitsInRadius(roshan:GetTeamNumber(), roshan:GetAbsOrigin(), nil, range, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NONE, FIND_CLOSEST, false)
if #nearbyHeroes >= minTargets then
roshan:CastAbilityNoTarget(self.fireBall, 1)
return
end
end
-- Cast Toss if its available
if self.toss and self.toss:IsCooldownReady() then
local maxRange = self.toss:GetSpecialValueFor("tooltip_range")
local pickupRadius = self.toss:GetSpecialValueFor("grab_radius")
local pickupUnit = nil
local throwTarget = nil
local units = FindUnitsInRadius(roshan:GetTeamNumber(), roshan:GetAbsOrigin(), nil, pickupRadius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_BASIC + DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES + DOTA_UNIT_TARGET_FLAG_NOT_ILLUSIONS, FIND_CLOSEST, false)
for _, unit in ipairs(units) do
if unit and unit:IsAlive() and not unit:IsAncient() then
pickupUnit = unit
break
end
end
if pickupUnit then
units = FindUnitsInRadius(roshan:GetTeamNumber(), roshan:GetAbsOrigin(), nil, maxRange, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_BASIC + DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES + DOTA_UNIT_TARGET_FLAG_NOT_ILLUSIONS, FIND_FARTHEST, false)
for _, unit in ipairs(units) do
if unit and unit:IsAlive() then
throwTarget = unit
break
end
end
if throwTarget then
roshan:CastAbilityOnTarget(throwTarget, self.toss, 1)
return
end
end
end
end
end
function modifier_imba_roshan_ai_diretide:OnTakeDamage(keys)
if IsServer() then
local unit = keys.unit
local attacker = keys.attacker
-- Only apply if the unit taking damage is the caster
if unit == self.roshan then
-- If the damage came from ourselves (e.g. Rot, Double Edge), do nothing
if attacker == unit then
return nil
end
if unit.CAN_START_COUNTDOWN == true and Diretide.COUNT_DOWN == false then
Diretide.COUNT_DOWN = true
print("PHASE 3")
Diretide:Announcer("diretide", "phase_3")
end
end
end
end
-- SPECIAL EFFECTS + ATTACK SOUND + ILLUSION KILLER
function modifier_imba_roshan_ai_diretide:OnAttackLanded(keys)
if IsServer() then
local roshan = self:GetParent()
local target = keys.target
local attacker = keys.attacker
if roshan == target then
-- Instantly kill attacking illusions
if attacker:IsIllusion() then attacker:ForceKill(true) end
elseif roshan == attacker then
-- Emit hit sound
target:EmitSound("Roshan.Attack")
target:EmitSound("Roshan.Attack.Post")
-- Deal fury swipes increased damage
local furySwipesModifier = target:FindModifierByName("modifier_imba_roshan_fury_swipes")
if furySwipesModifier then
local damageTable = { victim = target,attacker = roshan, damage_type = DAMAGE_TYPE_PURE, -- armor 2 stronk
damage = furySwipesModifier:GetStackCount() * self.furyswipeDamage, }
-- Increase fury swipe damage based on times Roshan died
if self:GetStackCount() == 3 then
local deathMod = roshan:FindModifierByName("modifier_imba_roshan_death_buff")
if deathMod then
damageTable.damage = damageTable.damage + deathMod:GetStackCount() * self.furyswipeIncreasePerDeath
end
end
ApplyDamage(damageTable)
furySwipesModifier:IncrementStackCount()
else
-- Does not wear off on phase 2
if self:GetStackCount() == 2 then
furySwipesModifier = target:AddNewModifier(roshan, self:GetAbility(), "modifier_imba_roshan_fury_swipes", {duration = math.huge})
if furySwipesModifier then furySwipesModifier:SetStackCount(1) end
elseif self:GetStackCount() == 3 then
furySwipesModifier = target:AddNewModifier(roshan, self:GetAbility(), "modifier_imba_roshan_fury_swipes", {duration = self.furyswipeDuration})
if furySwipesModifier then furySwipesModifier:SetStackCount(1) end
end
end
-- Bash only in phase 3
if self:GetStackCount() == 3 then
-- check bash chance
if math.random() <= self.bashChance then
local knockback = { center_x = target.x,
center_y = target.y,
center_z = target.z,
duration = self.bashDuration,
knockback_distance = 200,
knockback_height = self.bashDistance,
knockback_duration = self.bashDuration * 0.67, }
target:AddNewModifier(roshan, self:GetAbility(), "modifier_knockback", knockback)
target:EmitSound("Roshan.Bash")
end
end
end
end
end
-- PREATTACK SOUND
function modifier_imba_roshan_ai_diretide:OnAttackStart(keys)
if IsServer() then
local roshan = self:GetParent()
if roshan == keys.attacker then
roshan:EmitSound("Roshan.PreAttack")
roshan:EmitSound("Roshan.Grunt")
end
end
end
---------- Roshans Fury Swipes modifier
if modifier_imba_roshan_fury_swipes == nil then modifier_imba_roshan_fury_swipes = class({}) end
function modifier_imba_roshan_fury_swipes:IsPurgeException() return false end
function modifier_imba_roshan_fury_swipes:IsPurgable() return false end
function modifier_imba_roshan_fury_swipes:IsHidden() return false end
function modifier_imba_roshan_fury_swipes:IsDebuff() return true end
function modifier_imba_roshan_fury_swipes:GetEffectName()
return "particles/units/heroes/hero_ursa/ursa_fury_swipes_debuff.vpcf" end
function modifier_imba_roshan_fury_swipes:GetTexture()
return "roshan_bash" end
function modifier_imba_roshan_fury_swipes:GetEffectAttachType()
return PATTACH_OVERHEAD_FOLLOW end
---------- Roshans acceleration modifier
if modifier_imba_roshan_acceleration == nil then modifier_imba_roshan_acceleration = class({}) end
function modifier_imba_roshan_acceleration:GetAttributes() return MODIFIER_ATTRIBUTE_PERMANENT + MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE end
function modifier_imba_roshan_acceleration:IsPurgeException() return false end
function modifier_imba_roshan_acceleration:IsPurgable() return false end
function modifier_imba_roshan_acceleration:IsDebuff() return false end
function modifier_imba_roshan_acceleration:IsHidden() return true end
function modifier_imba_roshan_acceleration:DeclareFunctions()
return { MODIFIER_PROPERTY_MOVESPEED_BONUS_CONSTANT, MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT} end
function modifier_imba_roshan_acceleration:OnCreated()
local ability = self:GetAbility()
self.speedIncrease = ability:GetSpecialValueFor("speedup_increase")
self.asIncrease = ability:GetSpecialValueFor("speedup_as_increase")
if IsServer() then
self:StartIntervalThink(ability:GetSpecialValueFor("speedup_interval"))
end
end
function modifier_imba_roshan_acceleration:OnIntervalThink()
self:IncrementStackCount() end
function modifier_imba_roshan_acceleration:GetModifierMoveSpeedBonus_Constant()
return self.speedIncrease * self:GetStackCount() end
function modifier_imba_roshan_acceleration:GetModifierAttackSpeedBonus_Constant()
return self.asIncrease * self:GetStackCount() end
---------- Roshans death buff
if modifier_imba_roshan_death_buff == nil then modifier_imba_roshan_death_buff = class({}) end
function modifier_imba_roshan_death_buff:GetAttributes() return MODIFIER_ATTRIBUTE_PERMANENT + MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE end
function modifier_imba_roshan_death_buff:IsPurgeException() return false end
function modifier_imba_roshan_death_buff:IsPurgable() return false end
function modifier_imba_roshan_death_buff:IsHidden() return true end
function modifier_imba_roshan_death_buff:IsDebuff() return false end
function modifier_imba_roshan_death_buff:DeclareFunctions()
return {
MODIFIER_PROPERTY_SPELL_AMPLIFY_PERCENTAGE,
MODIFIER_PROPERTY_EXTRA_HEALTH_BONUS,
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE,
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS,
MODIFIER_PROPERTY_MAGICAL_RESISTANCE_BONUS,
MODIFIER_PROPERTY_STATUS_RESISTANCE_STACKING
}
end
function modifier_imba_roshan_death_buff:GetModifierExtraHealthBonus()
return self:GetAbility():GetSpecialValueFor("health_per_death") * self:GetStackCount()
end
function modifier_imba_roshan_death_buff:GetModifierSpellAmplify_Percentage()
return self:GetAbility():GetSpecialValueFor("spellamp_per_death") * self:GetStackCount()
end
function modifier_imba_roshan_death_buff:GetModifierPreAttack_BonusDamage()
return self:GetAbility():GetSpecialValueFor("damage_per_death") * self:GetStackCount()
end
function modifier_imba_roshan_death_buff:GetModifierAttackSpeedBonus_Constant()
return self:GetAbility():GetSpecialValueFor("attackspeed_per_death") * self:GetStackCount()
end
function modifier_imba_roshan_death_buff:GetModifierPhysicalArmorBonus()
return self:GetAbility():GetSpecialValueFor("armor_per_death") * self:GetStackCount()
end
function modifier_imba_roshan_death_buff:GetModifierMagicalResistanceBonus()
return self:GetAbility():GetSpecialValueFor("resist_per_death") * self:GetStackCount()
end
function modifier_imba_roshan_death_buff:GetModifierStatusResistanceStacking()
return self:GetAbility():GetSpecialValueFor("tenacity_per_death") * self:GetStackCount()
end
---------- Modifier for handling begging
if modifier_imba_roshan_ai_beg == nil then modifier_imba_roshan_ai_beg = class({}) end
function modifier_imba_roshan_ai_beg:GetAttributes() return MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE end
function modifier_imba_roshan_ai_beg:IsPurgeException() return false end
function modifier_imba_roshan_ai_beg:IsPurgable() return false end
function modifier_imba_roshan_ai_beg:IsDebuff() return false end
function modifier_imba_roshan_ai_beg:IsHidden() return true end
function modifier_imba_roshan_ai_beg:GetEffectName()
return "particles/generic_gameplay/generic_has_quest.vpcf"
end
function modifier_imba_roshan_ai_beg:GetEffectAttachType()
return PATTACH_OVERHEAD_FOLLOW end
function modifier_imba_roshan_ai_beg:OnDestroy()
if IsServer() then
if not self.noAggro then -- Go ape shit if the modifier expired on its own (not by candy-ing Roshan or through 'ChangeTarget)
local roshan = self:GetParent()
local AImod = roshan:FindModifierByName("modifier_imba_roshan_ai_diretide")
if AImod then
AImod.begState = 2
end
end
end
end
function modifier_imba_roshan_ai_beg:DestroyNoAggro()
self.noAggro = true
self:Destroy()
end
function modifier_imba_roshan_ai_beg:DeclareFunctions()
return { MODIFIER_PROPERTY_OVERRIDE_ANIMATION,
MODIFIER_PROPERTY_OVERRIDE_ANIMATION_WEIGHT,}
end
function modifier_imba_roshan_ai_beg:GetOverrideAnimation()
return ACT_DOTA_CHANNEL_ABILITY_5 end
function modifier_imba_roshan_ai_beg:GetOverrideAnimationWeight()
return 100 end
---------- Modifier for when eating a candy
if modifier_imba_roshan_ai_eat == nil then modifier_imba_roshan_ai_eat = class({}) end
function modifier_imba_roshan_ai_eat:GetAttributes() return MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE end
function modifier_imba_roshan_ai_eat:IsPurgeException() return false end
function modifier_imba_roshan_ai_eat:IsPurgable() return false end
function modifier_imba_roshan_ai_eat:IsDebuff() return false end
function modifier_imba_roshan_ai_eat:IsHidden() return true end
function modifier_imba_roshan_ai_eat:GetEffectName()
return "particles/hw_fx/candy_fed.vpcf"
end
function modifier_imba_roshan_ai_eat:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW
end
function modifier_imba_roshan_ai_eat:OnDestroy()
if IsServer() then
local roshan = self:GetParent()
local AImod = roshan:FindModifierByName("modifier_imba_roshan_ai_diretide")
if AImod then
AImod:ChangeTarget(roshan)
end
end
end
function modifier_imba_roshan_ai_eat:DeclareFunctions()
return { MODIFIER_PROPERTY_OVERRIDE_ANIMATION,
MODIFIER_PROPERTY_OVERRIDE_ANIMATION_WEIGHT,}
end
function modifier_imba_roshan_ai_eat:GetOverrideAnimation()
return ACT_DOTA_CHANNEL_ABILITY_6 end
function modifier_imba_roshan_ai_eat:GetOverrideAnimationWeight()
return 1000 end
---------- Candy modifier
if modifier_imba_roshan_eaten_candy == nil then modifier_imba_roshan_eaten_candy = class({}) end
function modifier_imba_roshan_eaten_candy:GetAttributes() return MODIFIER_ATTRIBUTE_PERMANENT + MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE end
function modifier_imba_roshan_eaten_candy:IsPurgeException() return false end
function modifier_imba_roshan_eaten_candy:IsPurgable() return false end
function modifier_imba_roshan_eaten_candy:IsDebuff() return false end
function modifier_imba_roshan_eaten_candy:IsHidden() return false end
function modifier_imba_roshan_eaten_candy:GetTexture()
return "item_halloween_candy_corn" end
function modifier_imba_roshan_eaten_candy:DeclareFunctions()
return { MODIFIER_PROPERTY_MOVESPEED_MAX,
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE,
MODIFIER_PROPERTY_MOVESPEED_BONUS_CONSTANT, }
end
function modifier_imba_roshan_eaten_candy:OnCreated()
local ability = self:GetAbility()
if not ability then
print("ERROR - NO ABILITY FOR CANDY MODIFIER!")
self:Destroy()
return
end
self.speedPerCandy = ability:GetSpecialValueFor("speed_per_candy")
self.damagePerCandy = ability:GetSpecialValueFor("damage_per_candy")
end
function modifier_imba_roshan_eaten_candy:GetModifierPreAttack_BonusDamage()
return self.speedPerCandy * self:GetStackCount() end
function modifier_imba_roshan_eaten_candy:GetModifierMoveSpeedBonus_Constant()
return self.damagePerCandy * self:GetStackCount() end
function modifier_imba_roshan_eaten_candy:GetModifierMoveSpeed_Max()
return 99999 end
------------------------------------------
-- APOCALYPSE --
------------------------------------------
if imba_roshan_diretide_apocalypse == nil then imba_roshan_diretide_apocalypse = class({}) end
function imba_roshan_diretide_apocalypse:GetCastAnimation()
return ACT_DOTA_CAST_ABILITY_1 end
function imba_roshan_diretide_apocalypse:OnSpellStart()
local roshan = self:GetCaster()
local minRange = self:GetSpecialValueFor("min_range")
local maxRange = self:GetSpecialValueFor("max_range")
local delay = self:GetSpecialValueFor("delay")
local damage = self:GetSpecialValueFor("damage")
local radius = self:GetSpecialValueFor("radius")
local positions = {}
local heroes = FindUnitsInRadius(roshan:GetTeamNumber(), roshan:GetAbsOrigin(), nil, maxRange, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, FIND_CLOSEST, false)
for _, hero in ipairs(heroes) do
if CalcDistanceBetweenEntityOBB(roshan, hero) >= minRange then
local pos = hero:GetAbsOrigin()
table.insert(positions, pos)
EmitSoundOnLocationWithCaster(pos, "Hero_Invoker.SunStrike.Charge", roshan)
local particle = ParticleManager:CreateParticle("particles/econ/items/invoker/invoker_apex/invoker_sun_strike_team_immortal1.vpcf", PATTACH_CUSTOMORIGIN, roshan)
ParticleManager:SetParticleControl(particle, 0, pos)
ParticleManager:ReleaseParticleIndex(particle)
end
end
Timers:CreateTimer(delay, function()
-- loop through the positions and deal damage to all units caught in the explosions AoE
for _, position in ipairs(positions) do
local units = FindUnitsInRadius(roshan:GetTeamNumber(), position, nil, radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_BASIC + DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, FIND_CLOSEST, false)
local damageTable = {victim = nil, attacker = roshan, damage = damage / #units, damage_type = DAMAGE_TYPE_PURE}
for _, unit in ipairs(units) do
damageTable.victim = unit
ApplyDamage(damageTable)
end
EmitSoundOnLocationWithCaster(position, "Hero_Invoker.SunStrike.Ignite", roshan)
local particle = ParticleManager:CreateParticle("particles/econ/items/invoker/invoker_apex/invoker_sun_strike_immortal1.vpcf", PATTACH_CUSTOMORIGIN, roshan)
ParticleManager:SetParticleControl(particle, 0, position)
ParticleManager:ReleaseParticleIndex(particle)
end
end)
end
--------------------------------------
-- Wave of Force --
--------------------------------------
if imba_roshan_diretide_force_wave == nil then imba_roshan_diretide_force_wave = class({}) end
function imba_roshan_diretide_force_wave:GetBehavior()
return DOTA_ABILITY_BEHAVIOR_NO_TARGET end
function imba_roshan_diretide_force_wave:GetCastAnimation()
return ACT_DOTA_CAST_ABILITY_2 end
function imba_roshan_diretide_force_wave:OnSpellStart() -- Parameters
local roshan = self:GetCaster()
local castPoint = roshan:GetAbsOrigin()
local waveDistance = self:GetSpecialValueFor("radius")
local waveRadius = 200
local waveSpeed = self:GetSpecialValueFor("speed")
local waves = 8
local angleStep = 360 / waves
local hitUnits = {}
roshan:EmitSound("RoshanDT.WaveOfForce.Cast")
print(waveSpeed)
print(angleStep)
-- Base projectile information
local waveProjectile = {
Ability = self,
EffectName = "particles/units/heroes/hero_invoker/invoker_deafening_blast.vpcf",
vSpawnOrigin = castPoint + Vector(0, 0, 50),
fDistance = waveDistance,
fStartRadius = waveRadius,
fEndRadius = waveRadius,
Source = roshan,
bHasFrontalCone = true,
bReplaceExisting = false,
iUnitTargetTeam = DOTA_UNIT_TARGET_TEAM_ENEMY,
iUnitTargetFlags = DOTA_UNIT_TARGET_FLAG_NONE,
iUnitTargetType = DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC,
bDeleteOnHit = false,
vVelocity = roshan:GetForwardVector() * waveSpeed,
bProvidesVision = false,
iVisionRadius = 0,
iVisionTeamNumber = roshan:GetTeamNumber(),
}
for i = 1, waves do
waveProjectile.vVelocity = roshan:GetForwardVector() + angleStep
waveProjectile.vVelocity.z = 0 -- So it doesn't move upwards
ProjectileManager:CreateLinearProjectile(waveProjectile)
end
end
function imba_roshan_diretide_force_wave:OnProjectileHit(unit, unitPos)
print("Target hit!")
end
------------------------------------------
-- ROSHLINGS --
------------------------------------------
if imba_roshan_diretide_summon_roshlings == nil then imba_roshan_diretide_summon_roshlings = class({}) end
function imba_roshan_diretide_summon_roshlings:OnSpellStart()
local roshan = self:GetCaster()
local roshanPos = roshan:GetAbsOrigin()
local summonCount = self:GetSpecialValueFor("summon_count")
local summon = "npc_imba_roshling"
local summonAbilities = { "imba_roshling_bash", "imba_roshling_aura" }
local deathMod = roshan:FindModifierByName("modifier_imba_roshan_death_buff")
if deathMod then
summonCount = summonCount + deathMod:GetStackCount() * self:GetSpecialValueFor("extra_per_death")
end
local roshling = nil
GridNav:DestroyTreesAroundPoint(roshanPos, 250, false)
for i = 1, summonCount do
roshling = CreateUnitByName(summon, roshanPos, true, roshan, roshan, roshan:GetTeam())
roshling:SetForwardVector(roshan:GetForwardVector())
for _, abilityName in ipairs(summonAbilities) do
local ability = roshling:FindAbilityByName(abilityName)
if ability then ability:SetLevel(1) end
end
end
end |
local csv = require("csv")
local inspect = require("inspect")
local argparse = require("argparse")
local sia = require("sia")
local parser = argparse("download_sia_vac_all", "Download all VAC of french AD from SIA.")
parser:option("-i --input", "Input file (France.cup).", "France.cup")
local args = parser:parse()
local f = csv.open(args.input, {
separator = ',',
header = false,
})
local pattern = "LF[A-Z][A-Z]"
for fields in f:lines() do
-- print(inspect(fields))
if string.match(fields[2], pattern) then
local icao_code = fields[2]
local status, err = pcall(sia.download_sia_vac, icao_code)
if not status then
print("error with " .. icao_code .. " " .. err)
end
end
end
|
return Def.ActorFrame {
Def.Quad {
InitCommand = function(self)
self
:xy(SCREEN_CENTER_X, SCREEN_TOP)
:vertalign(bottom)
:diffuse(color("#000000"))
:zoomto(SCREEN_WIDTH, SCREEN_HEIGHT)
end,
BeginCommand = function(self)
self
:zwrite(1)
:z(1)
:blend("BlendMode_NoEffect")
end,
OffCommand = function(self)
self
:accelerate(0.4)
:y(SCREEN_BOTTOM)
end
},
Def.BitmapText {
Font = "_venacti bold 24px",
InitCommand = function(self)
self
:xy(SCREEN_CENTER_X, SCREEN_CENTER_Y + 40)
:horizalign(center)
:shadowlength(0)
:wrapwidthpixels(500)
:strokecolor(color("#a200ff"))
:settext(THEME:GetString("ScreenCaution", "CautionText"))
end,
BeginCommand = function(self)
self:ztest(1)
end
}
}
|
return {'username','usernames'} |
--[[
Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com>
This code is licensed under the MIT. See LICENSE for details.
]]
local translate = {}
local mattata = require('mattata')
local https = require('ssl.https')
local url = require('socket.url')
local json = require('dkjson')
function translate:init()
translate.commands = mattata.commands(
self.info.username
):command('translate')
:command('tl').table
translate.help = [[/translate [locale] <text> - If a locale is given, the given text is translated into the said locale's language. If no locale is given then the given text is translated into the bot's configured language. If the command is used in reply to a message containing text, then the replied-to text is translated and the translation is returned. Alias: /tl.]]
end
function translate:on_inline_query(inline_query, configuration)
local input = mattata.input(inline_query.query)
if not input then
return
end
local lang
if not mattata.get_word(input) or mattata.get_word(input):len() > 2 then
lang = configuration.language
else
lang = mattata.get_word(input)
end
local jstr, res = https.request('https://translate.yandex.net/api/v1.5/tr.json/translate?key=' .. configuration.keys.translate .. '&lang=' .. lang .. '&text=' .. url.escape(input:gsub(lang .. ' ', '')))
if res ~= 200 then
return
end
local jdat = json.decode(jstr)
return mattata.answer_inline_query(
inline_query.id,
json.encode(
{
{
['type'] = 'article',
['id'] = '1',
['title'] = jdat.text[1],
['description'] = 'Click to send your translation.',
['input_message_content'] = {
['message_text'] = jdat.text[1]
}
}
}
)
)
end
function translate:on_message(message, configuration, language)
local input = mattata.input(message.text)
local lang = configuration['language']
if message.reply
then
lang = input
or lang
input = message.reply.text
elseif not input
then
return mattata.send_reply(
message,
translate.help
)
elseif input:match('^%a%a .-$')
then
lang, input = input:match('^(%a%a) (.-)$')
end
local jstr, res = https.request('https://translate.yandex.net/api/v1.5/tr.json/translate?key=' .. configuration['keys']['translate'] .. '&lang=' .. lang .. '&text=' .. url.escape(input))
if res ~= 200
then
return mattata.send_reply(
message,
'An error occured. Are you sure you specified a valid locale?'
)
end
local jdat = json.decode(jstr)
return mattata.send_message(
message.chat.id,
'<b>Translation (from ' .. jdat.lang:gsub('%-', ' to ') .. '):</b>\n' .. mattata.escape_html(jdat.text[1]),
'html'
)
end
return translate |
local BTConnection = bt.Class("BTConnection")
bt.BTConnection = BTConnection
function BTConnection:ctor()
self.id = 0
self.name = "BTConnection"
self.sourceNode = nil
self.targetNode = nil
self.isDisabled = false
self.status = bt.Status.Resting
end
function BTConnection:setActive(flag)
if not self.isDisabled and not flag then
self:reset(true)
end
self.isDisabled = not flag
end
function BTConnection:isActive()
return not self.isDisabled
end
function BTConnection:create(id,source,target,isDisabled)
if source == nil or target == nil then
print("Can't Create a Connection without providing Source and Target Nodes")
return nil
end
self.id = id
self.isDisabled = isDisabled
self.sourceNode = source
self.targetNode = target
end
function BTConnection:execute(agent,blackboard)
if not self:isActive() then
return bt.Status.Resting
end
self.status = self.targetNode:execute(agent,blackboard)
return self.status
end
function BTConnection:reset(recursively)
if self.status == bt.Status.Resting then
return
end
self.status = bt.Status.Resting
if recursively then
self.targetNode:reset(recursively)
end
end |
local spy = require "luassert.spy"
local lspconfig = require "lspconfig"
local configs = require "lspconfig.configs"
local servers = require "nvim-lsp-installer.servers"
describe("automatic_installation_exclude", function()
it(
"should install servers set up via lspconfig",
async_test(function()
local server1_installer_spy = spy.new()
local server2_installer_spy = spy.new()
local server1 = ServerGenerator {
name = "automatic_installation_exclude1",
installer = function()
server1_installer_spy()
end,
}
local server2 = ServerGenerator {
name = "automatic_installation_exclude2",
installer = function()
server2_installer_spy()
end,
}
servers.register(server1)
servers.register(server2)
configs[server1.name] = { default_config = {} }
configs[server2.name] = { default_config = {} }
require("nvim-lsp-installer").setup {
automatic_installation = { exclude = { server2.name } },
}
lspconfig[server1.name].setup {}
lspconfig[server2.name].setup {}
assert.wait_for(function()
assert.spy(server1_installer_spy).was_called(1)
assert.spy(server2_installer_spy).was_called(0)
end)
end)
)
end)
|
local ADJUST_SOUND = SoundDuration("npc/metropolice/pain1.wav") > 0
and ""
or "../../hl2/sound/"
-- Emits sounds one after the other from an entity.
function nut.util.emitQueuedSounds(
entity,
sounds,
delay,
spacing,
volume,
pitch
)
-- Let there be a delay before any sound is played.
delay = delay or 0
spacing = spacing or 0.1
-- Loop through all of the sounds.
for k, v in ipairs(sounds) do
local postSet, preSet = 0, 0
-- Determine if this sound has special time offsets.
if (istable(v)) then
postSet, preSet = v[2] or 0, v[3] or 0
v = v[1]
end
-- Get the length of the sound.
local length = SoundDuration(ADJUST_SOUND..v)
-- If the sound has a pause before it is played, add it here.
delay = delay + preSet
-- Have the sound play in the future.
timer.Simple(delay, function()
-- Check if the entity still exists and play the sound.
if (IsValid(entity)) then
entity:EmitSound(v, volume, pitch)
end
end)
-- Add the delay for the next sound.
delay = delay + length + postSet + spacing
end
-- Return how long it took for the whole thing.
return delay
end
|
msg_min = "minuta"
msg_hour = "časa"
|
require 'astronauta.keymap'
local nnoremap = vim.keymap.nnoremap
nnoremap { '<F5>', '<Cmd>update|mkview|edit|TSBufEnable highlight<Cr>' }
|
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by Administrator.
--- DateTime: 2021/2/23 17:51
---
extConf = {}
extConf.placeTextWithPlayerJoining="KspTooi"
extConf.placeTextWithPlayerSpawn = {
text1= "欢迎加入KspTooi服务器",
text2= "欢迎",
text3= "回家"
}
--显示版本
extConf.displayVersion="开发版本:1.39-E"
--是否允许玩家加入主团队
extConf.enableMainTeam=false
--Discord
extConf.serverInfoDiscordText = "discord.gg/trnpcen"
--QQGroup
extConf.serverInfoQQGroupText = "QQ群:860179317"
--服务器公告
extConf.serverNews =
extConf.displayVersion.." 大规模更新\n"..
"更新内容:\n"..
"* 修复一个因NPE造成的服务端内存泄露问题\n"..
"* 商店中的商品价格与数量进行了调整\n"..
"* 玩家列表中现在可以查看所有在线玩家的现金\n"..
"* 新增服务器公告\n"..
"* 增加传送功能(一次200现金) 用法: /tpa 玩家名 例: /tpa ksptooi\n\n"..
"* 平衡性修正 - 虫巢\n"..
"** 虫巢整体抗性加成 37.5%\n"..
--[[ "** 虫巢激光抗性加成 98%\n"..
"** 蜘蛛对虫巢的伤害降低 95%\n"..
"** 所有类型的炮塔与无人机对虫巢的伤害降低 95%\n"..]]
"* 平衡性修正 - 玩家\n"..
"** 所有动能武器伤害加成 62.5%\n\n"..
"*新版本规划\n"..
"**优化现有的旧地图,移除一些长期不上线的玩家基地\n\n"..
"*游戏机制改版规划:\n"..
"**为服务器增加RPG系统\n"..
"**去除现有的玩家基地机制,所有玩家将在同一个重生点重生\n"..
"玩家需要自己去寻找合适的位置建立基地发展\n"..
"**完全关闭玩家之间的PVP\n"..
" \n\n\n"
return extConf
|
local wezterm = require 'wezterm';
return {
launch_menu = {
{
args = {"top"},
},
{
args = {"source", "/Users/gongyu/Workspace/python-venvs/env-zeus/bin/activate", ";", "nvim"},
},
},
enable_scroll_bar = true,
-- How many lines of scrollback you want to retain per tab
scrollback_lines = 10000,
-- Fonts
font = wezterm.font_with_fallback({
"Fira Code",
"MesloLGS NF",
}),
dpi = 144.0,
font_size = 13.0,
line_height = 1.2,
-- https://wezfurlong.org/wezterm/colorschemes/index.html
-- The last color scheme in the following least takes effect
color_scheme = "Violet Dark",
--color_scheme = "Relaxed",
--color_scheme = "Ayu Mirage",
--color_scheme = "Batman",
--color_scheme = "Blue Matrix",
color_scheme = "matrix",
--color_scheme = "Darkside",
--color_scheme = "Doom Peacock",
--color_scheme = "Dracula",
--color_scheme = "Unikitty",
--color_scheme = "GitHub Dark",
--color_scheme = "Molokai",
--color_scheme = "Monokai Remastered",
--color_scheme = "Monokai Vivid",
--color_scheme = "Github",
--color_scheme = "Grape",
--color_scheme = "Grass",
--color_scheme = "jubi",
--color_scheme = "Laser",
--color_scheme = "MaterialOcean",
--color_scheme = "Mirage",
--color_scheme = "AlienBlood",
--color_scheme = "Afterglow",
--color_scheme = "AdventureTime",
--color_scheme = "Abernathy",
--color_scheme = "Blazer",
--color_scheme = "BlueDolphin",
--color_scheme = "Borland",
--color_scheme = "Night Owlish Light",
--color_scheme = "Novel",
--color_scheme = "Obsidian",
--color_scheme = "Ocean",
--color_scheme = "Pandora",
--color_scheme = "Spacedust",
--color_scheme = "Treehouse",
--color_scheme = "UltraViolent",
--color_scheme = "Violet Light",
--color_scheme = "Wez",
-- Window
window_decorations = "RESIZE",
window_padding = {
left = "1%",
right = "0",
top = "0.5%",
bottom = "0.5%",
},
window_background_opacity = 1.0,
window_background_image = "/Users/gongyu/Pictures/jinx3.jpg",
window_background_image_hsb = {
-- Darken the background image by reducing it to 1/3rd
brightness = 0.3,
-- You can adjust the hue by scaling its value.
-- a multiplier of 1.0 leaves the value unchanged.
hue = 1.0,
-- You can adjust the saturation also.
saturation = 1.0,
},
text_background_opacity = 1.0,
window_close_confirmation = "AlwaysPrompt",
inactive_pane_hsb = {
saturation = 0.9,
brightness = 0.8,
},
keys = {
-- this will show the launcher in the current tab
-- {key=";", mods="CTRL|SHIFT|ALT", action="ShowLauncher"},
{key=";", mods="CTRL|SHIFT|ALT", action=wezterm.action{ShowLauncherArgs={
flags="LAUNCH_MENU_ITEMS"
}}},
{key="l", mods="CTRL|SHIFT|ALT", action=wezterm.action{ShowLauncherArgs={
flags="WORKSPACES|TABS"
}}},
{key="d", mods="CTRL|SHIFT|ALT", action=wezterm.action{ShowLauncherArgs={
flags="DOMAINS"
}}},
{key="k", mods="CTRL|SHIFT|ALT", action=wezterm.action{ShowLauncherArgs={
flags="FUZZY|KEY_ASSIGNMENTS"
}}},
-- This will create a new split and run the program inside "args", e.g., args={"top"}
{key="_", mods="CTRL|SHIFT|ALT", action=wezterm.action{SplitVertical={
args={}, domain="CurrentPaneDomain",
}}},
{key="|", mods="CTRL|SHIFT|ALT", action=wezterm.action{SplitHorizontal={
args={}, domain="CurrentPaneDomain",
}}},
{key="w", mods="CMD",
action=wezterm.action{CloseCurrentPane={confirm=true}}}
},
-- Tabs
-- set to false to disable the tab bar completely
enable_tab_bar = true,
-- set to true to hide the tab bar when there is only
-- a single tab in the window
hide_tab_bar_if_only_one_tab = true,
colors = {
tab_bar = {
-- The color of the strip that goes along the top of the window
background = "#0b0022",
-- The active tab is the one that has focus in the window
active_tab = {
-- The color of the background area for the tab
bg_color = "#2b2042",
-- The color of the text for the tab
fg_color = "#c0c0c0",
-- Specify whether you want "Half", "Normal" or "Bold" intensity for the
-- label shown for this tab.
-- The default is "Normal"
intensity = "Normal",
-- Specify whether you want "None", "Single" or "Double" underline for
-- label shown for this tab.
-- The default is "None"
underline = "None",
-- Specify whether you want the text to be italic (true) or not (false)
-- for this tab. The default is false.
italic = false,
-- Specify whether you want the text to be rendered with strikethrough (true)
-- or not for this tab. The default is false.
strikethrough = false,
},
-- Inactive tabs are the tabs that do not have focus
inactive_tab = {
bg_color = "#1b1032",
fg_color = "#808080",
-- The same options that were listed under the `active_tab` section above
-- can also be used for `inactive_tab`.
},
-- You can configure some alternate styling when the mouse pointer
-- moves over inactive tabs
inactive_tab_hover = {
bg_color = "#3b3052",
fg_color = "#909090",
italic = true,
-- The same options that were listed under the `active_tab` section above
-- can also be used for `inactive_tab_hover`.
},
-- The new tab button that let you create new tabs
new_tab = {
bg_color = "#1b1032",
fg_color = "#808080",
-- The same options that were listed under the `active_tab` section above
-- can also be used for `new_tab`.
},
-- You can configure some alternate styling when the mouse pointer
-- moves over the new tab button
new_tab_hover = {
bg_color = "#3b3052",
fg_color = "#909090",
italic = true,
-- The same options that were listed under the `active_tab` section above
-- can also be used for `new_tab_hover`.
}
}
}
}
|
local luasnip = require "luasnip"
local s = luasnip.snippet
local sn = luasnip.snippet_node
local t = luasnip.text_node
local i = luasnip.insert_node
local c = luasnip.choice_node
luasnip.snippets = {
all = {},
lua = {
s("module", {
t "local M = {}",
t { "", "", "" },
t "function M.",
i(1),
t "(",
i(2),
t ")",
t { "", "\t" },
i(0),
t { "", "end" },
t { "", "", "" },
t "return M",
}),
},
java = {
s("class", {
c(1, {
t "public ",
t "private ",
}),
t "class ",
i(2),
t " ",
c(3, {
t "{",
sn(nil, {
t "extends ",
i(1),
t " {",
}),
sn(nil, {
t "implements ",
i(1),
t " {",
}),
}),
t { "", "\t" },
i(0),
t { "", "}" },
}),
s("class-allman", {
c(1, {
t "public ",
t "private ",
}),
t "class ",
i(2),
t " ",
c(3, {
t "",
sn(nil, {
t "extends ",
i(1),
}),
sn(nil, {
t "implements ",
i(1),
}),
}),
t { "", "{" },
t { "", "\t" },
i(0),
t { "", "}" },
}),
s("fn", {
c(1, {
t "public ",
t "private ",
}),
c(2, {
t "void",
i(nil, { "" }),
t "String",
t "char",
t "int",
t "double",
t "boolean",
}),
t " ",
i(3),
t "(",
i(4),
t ")",
c(5, {
t "",
sn(nil, {
t { "", " throws " },
i(1),
}),
}),
t { " {", "\t" },
i(0),
t { "", "}" },
}),
s("fn-allman", {
c(1, {
t "public ",
t "private ",
}),
c(2, {
t "void",
i(nil, { "" }),
t "String",
t "char",
t "int",
t "double",
t "boolean",
}),
t " ",
i(3),
t "(",
i(4),
t ")",
c(5, {
t "",
sn(nil, {
t { "", " throws " },
i(1),
}),
}),
t { "", " {", "", "\t" },
i(0),
t { "", "}" },
}),
},
}
|
return {
["com.github.thetaepsilon.minetest.libmt_node_network"] = {
search_dirs = {
"nodenetwork",
},
},
}
|
describe('contains', function()
it('errors when its parent errors', function()
expect(Rx.Observable.throw():contains(1)).to.produce.error()
end)
it('returns false if the source Observable produces no values', function()
expect(Rx.Observable.empty():contains(3)).to.produce(false)
end)
it('returns true if the value is nil and the Observable produces an empty value', function()
local observable = Rx.Observable.create(function(observer)
observer:onNext(nil)
observer:onCompleted()
end)
expect(observable:contains(nil)).to.produce(true)
end)
it('returns true if the source Observable produces the specified value', function()
local observable = Rx.Observable.fromRange(5)
expect(observable:contains(3)).to.produce(true)
end)
it('supports multiple values', function()
local observable = Rx.Observable.fromRange(6):wrap(3)
expect(observable).to.produce({{1, 2, 3}, {4, 5, 6}})
expect(observable:contains(5)).to.produce(true)
end)
end)
|
--[[-------------------------------------------------------------------------
WARDEN v2.1.0
by: Silhouhat (http://steamcommunity.com/id/Silhouhat/)
---------------------------------------------------------------------------]]
WARDEN = WARDEN or {}
WARDEN.Config = WARDEN.Config or {}
WARDEN.API_KEY = WARDEN.API_KEY or false
WARDEN.CACHE = WARDEN.CACHE or {}
-------------------
-- Configuration --
-------------------
-- Logs various events in the console.
WARDEN.Config.Log = true
-- Used for debugging, you probably don't need this set to true.
WARDEN.Config.Debug = true
-- How long before we should clear the cache, in seconds.
WARDEN.Config.CacheTimer = 86400
--should we kick proxies?
WARDEN.Config.KickProxy = false
-- IP Addresses that we don't bother to check.
WARDEN.Config.NoCheck = {
"loopback",
"localhost",
"127.0.0.1"
}
-- Groups & clients that are trusted enough to not check.
-- Careful, if a malicious person gets access to a client or group on this list
-- it can spell more trouble if they are using a proxy.
WARDEN.Config.Exceptions = {
Groups = {
"superadmin",
"admin",
},
SteamIDs = {
--"STEAM_0:1:56142649",
--"STEAM_0:0:28681590",
},
}
-- The kick messages to be displayed.
WARDEN.Config.KickMessages = {
["Invalid IP"] = "Unable to verify IP address",
["Proxy IP"] = "Unable to validate IP address",
}
---------------------
-- Local Functions --
---------------------
--[[-------------------------------------------------------------------------
WARDEN_LOG( message, type )
Just a pretty and branded print()
ARGUMENTS:
[string] message
The message you would like to log to the console.
[int] type
The type of the message.
0 = Information
1 = Warning
2 = Log
3 = Debug
---------------------------------------------------------------------------]]
local function WARDEN_Log( type, msg )
local textcolor, prefix = Color( 255, 255, 255 ), ""
if type == 1 then
textcolor, prefix = Color( 255, 100, 100 ), "ERROR: "
end
if type == 2 then
if not WARDEN.Config.Log then return end
textcolor, prefix = Color( 255, 255, 100 ), "LOG: "
end
if type == 3 then
if not WARDEN.Config.Debug then return end
textcolor, prefix = Color( 255, 125, 50 ), "DEBUG: "
end
MsgC( Color( 255, 255, 255 ), "[", Color( 51, 126, 254 ), "WARDEN", Color( 255, 255, 255 ), "] ", textcolor, prefix, msg, "\n" )
end
----------------------
-- Global Functions --
----------------------
--[[-------------------------------------------------------------------------
WARDEN.CheckIP( ip, function )
Checks the IP address to see if it is a proxy.
ARGUMENTS:
[string] ip
The IP to check.
[function] callback( proxyInfo )
The callback to run when the IP verification is finished.
PARAMETERS:
[string/bool] proxyInfo
The return value from the IP check. False if connection failed.
POSSIBLE VALUES:
Given an IP address, the system will return a probabilistic value (between a value of 0 and 1)
of how likely the IP is a VPN / proxy / hosting / bad IP.
A value of 1 means that IP is explicitly banned (a web host, VPN, or TOR node) by their dynamic lists.
Otherwise, the output will return a real number value between 0 and 1, of how likely
the IP is bad / VPN / proxy, which is inferred through machine learning & probability theory
techniques using dynamic checks with large datasets. Billions of new records are parsed
each month to ensure the datasets have the latest information and old records automatically expire.
The system is designed to be efficient, fast, simple, and accurate.
[boolean] useCache = true
Whether or not you would like to attempt to use the cache.
---------------------------------------------------------------------------]]
function WARDEN.CheckIP( ip, callback, useCache )
-- If the port is included, we throw it out.
if string.find( ip, ":" ) then
ip = string.Explode( ":", ip )[1]
end
-- Prevent the server host from getting kicked.
if table.HasValue( WARDEN.Config.NoCheck, ip ) then
WARDEN_Log( 2, "Preventing the check of the IP address \""..ip.."\" because it is in the no-check list.")
return
end
-- P2P servers don't work with IP addresses.
if string.find( ip, "p2p" ) then
WARDEN_Log( 1, "Warden does not work on P2P servers!" )
return
end
useCache = useCache or true
if useCache and table.HasValue( table.GetKeys( WARDEN.CACHE ), ip ) then
WARDEN_Log( 3, "Using cache to get the verification for \""..ip.."\".")
callback( WARDEN.CACHE[ip], "CACHE" )
return
end
http.Fetch( "http://check.getipintel.net/check.php?ip=" .. ip.. "&contact=fagfagas39@gmail.com",
function( info )
callback( info )
-- Add result to cache
WARDEN.CACHE[ip] = info
end
)
end
--[[-------------------------------------------------------------------------
WARDEN.SetupCache()
Sets up a new instance of the cache table.
Also clears any existing cache and starts a timer to clear
the cache after a set amount of time set in the config.
---------------------------------------------------------------------------]]
function WARDEN.SetupCache()
WARDEN_Log( 2, "Clearing cache..." )
table.Empty( WARDEN.CACHE )
-- We use this and timer.Create() instead of just timer.Simple() in order to not have multiple timers running at once.
if timer.Exists( "WARDEN_CacheTimer" ) then
timer.Remove( "WARDEN_CacheTimer" )
end
-- Clear the cache after a set period of time.
timer.Create( "WARDEN_CacheTimer", WARDEN.Config.CacheTimer, 1, function()
WARDEN.SetupCache()
end )
WARDEN_Log( 2, "Cache cleared." )
end
-----------
-- Hooks --
-----------
-- Prevent people from joining w/ an untrusted IP address.
local function WARDEN_PlayerInitialSpawn( ply )
if table.HasValue( WARDEN.Config.Exceptions.Groups, ply:GetUserGroup() ) or table.HasValue( WARDEN.Config.Exceptions.SteamIDs, ply:SteamID() ) then
WARDEN_Log( 2, "Ignoring verifying the IP of "..ply:Nick().." as their SteamID or usergroup is in the exceptions list.")
WARDEN_Log( 3, "SteamID: "..ply:SteamID().." | Usergroup: "..ply:GetUserGroup() )
return
end
WARDEN_Log( 2, "Verifying the IP address of "..ply:Nick().."..." )
WARDEN.CheckIP( ply:IPAddress(), function( isProxy )
if tonumber(isProxy) >= 0.995 then
local proxy = true
if WARDEN.Config.KickProxy then
WARDEN_Log( 2, "The IP address of "..ply:Nick().." was marked as a proxy. Kicking player..." )
ply:Kick( WARDEN.Config.KickMessages["Proxy IP"] )
else
local proxy = false
WARDEN_Log( 2, "The IP address of "..ply:Nick().." was marked as a proxy.")
end
elseif tonumber(isProxy) <= 0.80 then
WARDEN_Log( 2, "The IP address of "..ply:Nick().." is clean." )
end
end )
end
hook.Add( "PlayerInitialSpawn", "WARDEN_PlayerInitialSpawn", WARDEN_PlayerInitialSpawn)
-----------------
-- Concommands --
-----------------
-- Debug concommands.
if WARDEN.Config.Debug then
-- Checks the IP you input outright via WARDEN.CheckIP().
concommand.Add( "warden_checkip", function( ply, cmd, args )
if not args or table.Count( args ) != 1 then
WARDEN_Log( 1, "Invalid arguments! Use \"warden_checkip [ip address]\"")
return
end
WARDEN.CheckIP( args[1], function( isProxy )
WARDEN_Log( 0, args[1].." is"..((tonumber(isProxy) >= 0.995) and " NOT" or "").." a proxy IP address." )
end )
end )
end
|
local __exports = LibStub:NewLibrary("ovale/Spells", 80000)
if not __exports then return end
local __class = LibStub:GetLibrary("tslib").newClass
local __Debug = LibStub:GetLibrary("ovale/Debug")
local OvaleDebug = __Debug.OvaleDebug
local __Profiler = LibStub:GetLibrary("ovale/Profiler")
local OvaleProfiler = __Profiler.OvaleProfiler
local __Ovale = LibStub:GetLibrary("ovale/Ovale")
local Ovale = __Ovale.Ovale
local __Requirement = LibStub:GetLibrary("ovale/Requirement")
local RegisterRequirement = __Requirement.RegisterRequirement
local UnregisterRequirement = __Requirement.UnregisterRequirement
local aceEvent = LibStub:GetLibrary("AceEvent-3.0", true)
local tonumber = tonumber
local GetSpellCount = GetSpellCount
local IsSpellInRange = IsSpellInRange
local IsUsableItem = IsUsableItem
local IsUsableSpell = IsUsableSpell
local UnitIsFriend = UnitIsFriend
local __State = LibStub:GetLibrary("ovale/State")
local OvaleState = __State.OvaleState
local __Data = LibStub:GetLibrary("ovale/Data")
local OvaleData = __Data.OvaleData
local __Power = LibStub:GetLibrary("ovale/Power")
local OvalePower = __Power.OvalePower
local __SpellBook = LibStub:GetLibrary("ovale/SpellBook")
local OvaleSpellBook = __SpellBook.OvaleSpellBook
local WARRIOR_INCERCEPT_SPELLID = 198304
local WARRIOR_HEROICTHROW_SPELLID = 57755
local OvaleSpellsBase = OvaleProfiler:RegisterProfiling(OvaleDebug:RegisterDebugging(Ovale:NewModule("OvaleSpells", aceEvent)))
local OvaleSpellsClass = __class(OvaleSpellsBase, {
OnInitialize = function(self)
RegisterRequirement("spellcount_min", self.RequireSpellCountHandler)
RegisterRequirement("spellcount_max", self.RequireSpellCountHandler)
end,
OnDisable = function(self)
UnregisterRequirement("spellcount_max")
UnregisterRequirement("spellcount_min")
end,
GetCastTime = function(self, spellId)
if spellId then
local name, _, _, castTime = OvaleSpellBook:GetSpellInfo(spellId)
if name then
if castTime then
castTime = castTime / 1000
else
castTime = 0
end
else
castTime = nil
end
return castTime
end
end,
GetSpellCount = function(self, spellId)
local index, bookType = OvaleSpellBook:GetSpellBookIndex(spellId)
if index and bookType then
local spellCount = GetSpellCount(index, bookType)
self:Debug("GetSpellCount: index=%s bookType=%s for spellId=%s ==> spellCount=%s", index, bookType, spellId, spellCount)
return spellCount
else
local spellName = OvaleSpellBook:GetSpellName(spellId)
local spellCount = GetSpellCount(spellName)
self:Debug("GetSpellCount: spellName=%s for spellId=%s ==> spellCount=%s", spellName, spellId, spellCount)
return spellCount
end
end,
IsSpellInRange = function(self, spellId, unitId)
local index, bookType = OvaleSpellBook:GetSpellBookIndex(spellId)
local returnValue = nil
if index and bookType then
returnValue = IsSpellInRange(index, bookType, unitId)
elseif OvaleSpellBook:IsKnownSpell(spellId) then
local name = OvaleSpellBook:GetSpellName(spellId)
returnValue = IsSpellInRange(name, unitId)
end
if (returnValue == 1 and spellId == WARRIOR_INCERCEPT_SPELLID) then
return (UnitIsFriend("player", unitId) or __exports.OvaleSpells:IsSpellInRange(WARRIOR_HEROICTHROW_SPELLID, unitId))
end
return (returnValue == 1 and true) or (returnValue == 0 and false) or (returnValue == nil and nil)
end,
CleanState = function(self)
end,
InitializeState = function(self)
end,
ResetState = function(self)
end,
IsUsableItem = function(self, itemId, atTime)
__exports.OvaleSpells:StartProfiling("OvaleSpellBook_state_IsUsableItem")
local isUsable = IsUsableItem(itemId)
local ii = OvaleData:ItemInfo(itemId)
if ii then
if isUsable then
local unusable = OvaleData:GetItemInfoProperty(itemId, atTime, "unusable")
if unusable and unusable > 0 then
__exports.OvaleSpells:Log("Item ID '%s' is flagged as unusable.", itemId)
isUsable = false
end
end
end
__exports.OvaleSpells:StopProfiling("OvaleSpellBook_state_IsUsableItem")
return isUsable
end,
IsUsableSpell = function(self, spellId, atTime, targetGUID)
__exports.OvaleSpells:StartProfiling("OvaleSpellBook_state_IsUsableSpell")
local isUsable = OvaleSpellBook:IsKnownSpell(spellId)
local noMana = false
local si = OvaleData.spellInfo[spellId]
local requirement
if si then
if isUsable then
local unusable = OvaleData:GetSpellInfoProperty(spellId, atTime, "unusable", targetGUID)
if unusable and unusable > 0 then
__exports.OvaleSpells:Log("Spell ID '%s' is flagged as unusable.", spellId)
isUsable = false
end
end
if isUsable then
isUsable, requirement = OvaleData:CheckSpellInfo(spellId, atTime, targetGUID)
if not isUsable then
noMana = OvalePower.PRIMARY_POWER[requirement]
if noMana then
__exports.OvaleSpells:Log("Spell ID '%s' does not have enough %s.", spellId, requirement)
else
__exports.OvaleSpells:Log("Spell ID '%s' failed '%s' requirements.", spellId, requirement)
end
end
end
else
local index, bookType = OvaleSpellBook:GetSpellBookIndex(spellId)
if index and bookType then
return IsUsableSpell(index, bookType)
elseif OvaleSpellBook:IsKnownSpell(spellId) then
local name = OvaleSpellBook:GetSpellName(spellId)
return IsUsableSpell(name)
end
end
__exports.OvaleSpells:StopProfiling("OvaleSpellBook_state_IsUsableSpell")
return isUsable, noMana
end,
constructor = function(self, ...)
OvaleSpellsBase.constructor(self, ...)
self.RequireSpellCountHandler = function(spellId, atTime, requirement, tokens, index, targetGUID)
local verified = false
local countString
if index then
countString = tokens[index]
index = index + 1
end
if countString then
local count = tonumber(countString) or 1
local actualCount = __exports.OvaleSpells:GetSpellCount(spellId)
verified = (requirement == "spellcount_min" and count <= actualCount) or (requirement == "spellcount_max" and count >= actualCount)
else
Ovale:OneTimeMessage("Warning: requirement '%s' is missing a count argument.", requirement)
end
return verified, requirement, index
end
end
})
__exports.OvaleSpells = OvaleSpellsClass()
OvaleState:RegisterState(__exports.OvaleSpells)
|
local events = require("__flib__.event")
local tables = require("__flib__.table")
local MAX_KEEP = 60 * 60 * 60 * 24 -- ticks * seconds * minutes * hours
local function clear_older_force(force_index, older_than)
-- local old_size = table_size(global.history)
global.history = tables.filter(global.history, function(v)
return v.force_index ~= force_index or v.last_change >= older_than
end, true)
-- game.print("Clear older " .. old_size .. " => " .. table_size(global.history) .. " for force " .. force_index)
end
local function clear_older(player_index, older_than)
local force_index = game.players[player_index].force.index
clear_older_force(force_index, older_than)
end
local function new_current(train)
return {
-- Required because front_stock might not be valid later
force_index = train.front_stock.force.index,
train = train,
started_at = game.tick,
last_change = game.tick,
contents = {},
events = {}
}
end
local function diff(old_values, new_values)
local result = {}
if old_values then
for k, v in pairs(old_values) do
result[k] = -v
end
end
if new_values then
for k, v in pairs(new_values) do
local old_value = result[k] or 0
result[k] = old_value + v
end
end
return result
end
local function get_train_data(train, train_id)
if not global.trains[train_id] then
global.trains[train_id] = new_current(train)
end
return global.trains[train_id]
end
local function get_logs(force)
return tables.filter(global.trains, function(train_data)
return train_data.force_index == force.index
end)
end
local function add_log(train_data, log_event)
train_data.last_change = game.tick
table.insert(train_data.events, log_event)
end
local function finish_current_log(train, train_id, train_data)
table.insert(global.history, train_data)
local new_data = new_current(train)
global.trains[train_id] = new_data
clear_older_force(new_data.force_index, game.tick - MAX_KEEP)
end
events.on_train_schedule_changed(function(event)
local train = event.train
local train_id = train.id
local train_data = get_train_data(train, train_id)
add_log(train_data, {
tick = game.tick,
schedule = train.schedule,
changed_by = event.player_index
})
end)
local interesting_states = {
[defines.train_state.path_lost] = true,
[defines.train_state.no_schedule] = true,
[defines.train_state.no_path] = true,
[defines.train_state.wait_signal] = false, -- TODO: Add wait at signal info later
[defines.train_state.wait_station] = true,
[defines.train_state.manual_control_stop] = true,
[defines.train_state.manual_control] = true,
[defines.train_state.destination_full] = true
}
local function read_contents(train)
return {
items = train.get_contents(),
fluids = train.get_fluid_contents()
}
end
events.on_train_changed_state(function(event)
local train = event.train
local train_id = train.id
local train_data = get_train_data(train, train_id)
local new_state = train.state
local interesting_event = interesting_states[event.old_state] or interesting_states[new_state]
if not interesting_event then
return
end
--if event.old_state == defines.train_state.wait_station and new_state == defines.train_state.arrive_station then
-- Temporary stop at the same position as a station (common with LTN)
-- return
--end
local log = {
tick = game.tick,
old_state = event.old_state,
state = train.state
}
if event.old_state == defines.train_state.wait_station then
local diff_items = diff(train_data.contents.items, train.get_contents())
local diff_fluids = diff(train_data.contents.fluids, train.get_fluid_contents())
train_data.contents = read_contents(train)
log.diff = {
items = diff_items,
fluids = diff_fluids
}
-- end old entry, but save timestamp somewhere
end
if new_state == defines.train_state.wait_station then
-- create new entry
-- train_data.contents_on_enter = ...
-- always log position
log.position = train.front_stock.position
if train.station then
train_data.contents = read_contents(train)
log.contents = train_data.contents.items
log.fluids = train_data.contents.fluids
log.station = train.station
end
end
-- Show train, time since last station, station name, entered with contents, and content diff
-- Save waiting for signals, start and end in the same
-- time waited at signal, signal entity + position
-- Save waiting at temporary stop, as long as it doesn't change from wait_station to arrive_station
-- Save waiting at train station
add_log(train_data, log)
if train.state == defines.train_state.wait_station and train.schedule.current == 1 then
finish_current_log(train, train_id, train_data)
end
end)
return {
clear_older = clear_older,
get_logs = get_logs
}
|
require("marks").setup()
|
C_ChallengeMode = {}
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.CanUseKeystoneInCurrentMap)
---@param itemLocation ItemLocationMixin
---@return boolean canUse
function C_ChallengeMode.CanUseKeystoneInCurrentMap(itemLocation) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.ClearKeystone)
function C_ChallengeMode.ClearKeystone() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.CloseKeystoneFrame)
function C_ChallengeMode.CloseKeystoneFrame() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.GetActiveChallengeMapID)
---@return number? mapChallengeModeID
function C_ChallengeMode.GetActiveChallengeMapID() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.GetActiveKeystoneInfo)
---@return number activeKeystoneLevel
---@return number[] activeAffixIDs
---@return boolean wasActiveKeystoneCharged
function C_ChallengeMode.GetActiveKeystoneInfo() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.GetAffixInfo)
---@param affixID number
---@return string name
---@return string description
---@return number filedataid
function C_ChallengeMode.GetAffixInfo(affixID) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.GetCompletionInfo)
---@return number mapChallengeModeID
---@return number level
---@return number time
---@return boolean onTime
---@return number keystoneUpgradeLevels
---@return boolean practiceRun
---@return number? oldOverallDungeonScore
---@return number? newOverallDungeonScore
---@return boolean IsMapRecord
---@return boolean IsAffixRecord
---@return number PrimaryAffix
---@return boolean isEligibleForScore
---@return ChallengeModeCompletionMemberInfo[] members
function C_ChallengeMode.GetCompletionInfo() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.GetDeathCount)
---@return number numDeaths
---@return number timeLost
function C_ChallengeMode.GetDeathCount() end
---Returns a color value from the passed in overall season M+ rating.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.GetDungeonScoreRarityColor)
---@param dungeonScore number
---@return ColorMixin scoreColor
function C_ChallengeMode.GetDungeonScoreRarityColor(dungeonScore) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.GetGuildLeaders)
---@return ChallengeModeGuildTopAttempt[] topAttempt
function C_ChallengeMode.GetGuildLeaders() end
---Returns a color value from the passed in keystone level.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.GetKeystoneLevelRarityColor)
---@param level number
---@return ColorMixin levelScore
function C_ChallengeMode.GetKeystoneLevelRarityColor(level) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.GetMapScoreInfo)
---@return MythicPlusRatingLinkInfo[] displayScores
function C_ChallengeMode.GetMapScoreInfo() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.GetMapTable)
---@return number[] mapChallengeModeIDs
function C_ChallengeMode.GetMapTable() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.GetMapUIInfo)
---@param mapChallengeModeID number
---@return string name
---@return number id
---@return number timeLimit
---@return number? texture
---@return number backgroundTexture
function C_ChallengeMode.GetMapUIInfo(mapChallengeModeID) end
---Gets the overall season mythic+ rating for the player.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.GetOverallDungeonScore)
---@return number overallDungeonScore
function C_ChallengeMode.GetOverallDungeonScore() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.GetPowerLevelDamageHealthMod)
---@param powerLevel number
---@return number damageMod
---@return number healthMod
function C_ChallengeMode.GetPowerLevelDamageHealthMod(powerLevel) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.GetSlottedKeystoneInfo)
---@return number mapChallengeModeID
---@return number[] affixIDs
---@return number keystoneLevel
function C_ChallengeMode.GetSlottedKeystoneInfo() end
---Returns a color value from the passed in mythic+ rating from the combined affix scores for a specific dungeon
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.GetSpecificDungeonOverallScoreRarityColor)
---@param specificDungeonOverallScore number
---@return ColorMixin specificDungeonOverallScoreColor
function C_ChallengeMode.GetSpecificDungeonOverallScoreRarityColor(specificDungeonOverallScore) end
---Returns a color value from the passed in mythic+ rating for a specific dungeon.
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.GetSpecificDungeonScoreRarityColor)
---@param specificDungeonScore number
---@return ColorMixin specificDungeonScoreColor
function C_ChallengeMode.GetSpecificDungeonScoreRarityColor(specificDungeonScore) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.HasSlottedKeystone)
---@return boolean hasSlottedKeystone
function C_ChallengeMode.HasSlottedKeystone() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.IsChallengeModeActive)
---@return boolean challengeModeActive
function C_ChallengeMode.IsChallengeModeActive() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.RemoveKeystone)
---@return boolean removalSuccessful
function C_ChallengeMode.RemoveKeystone() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.RequestLeaders)
---@param mapChallengeModeID number
function C_ChallengeMode.RequestLeaders(mapChallengeModeID) end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.Reset)
function C_ChallengeMode.Reset() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.SetKeystoneTooltip)
function C_ChallengeMode.SetKeystoneTooltip() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.SlotKeystone)
function C_ChallengeMode.SlotKeystone() end
---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ChallengeMode.StartChallengeMode)
---@return boolean success
function C_ChallengeMode.StartChallengeMode() end
---@class ChallengeModeCompletionMemberInfo
---@field memberGUID string
---@field name string
---@class ChallengeModeGuildAttemptMember
---@field name string
---@field classFileName string
---@class ChallengeModeGuildTopAttempt
---@field name string
---@field classFileName string
---@field keystoneLevel number
---@field mapChallengeModeID number
---@field isYou boolean
---@field members ChallengeModeGuildAttemptMember[]
|
--[[
TheNexusAvenger
Registers commands on the client.
--]]
local Registry = require(script.Parent:WaitForChild("Common"):WaitForChild("Registry"))
local ClientRegistry = Registry:Extend()
ClientRegistry:SetClassName("ClientRegistry")
--[[
Creates the client registry.
--]]
function ClientRegistry:__new(Cmdr,Authorization,Messages,NexusAdminRemotes)
self:InitializeSuper(Authorization,Messages)
self.Cmdr = Cmdr
--Set up the events.
local RegistryEvents = NexusAdminRemotes:WaitForChild("RegistryEvents")
local GetRegisteredCommands = RegistryEvents:WaitForChild("GetRegisteredCommands")
self.GetRegisteredCommands = GetRegisteredCommands
local CommandRegistered = RegistryEvents:WaitForChild("CommandRegistered")
CommandRegistered.OnClientEvent:Connect(function(Data)
self:LoadCommand(Data)
end)
--Register the BeforeRun hook for verifying admin levels.
self.Cmdr.Registry:RegisterHook("BeforeRun",function(CommandContext)
--Return if a result exists from the common function.
local BeforeRunResult = self:PerformBeforeRun(CommandContext)
if BeforeRunResult then
return BeforeRunResult
end
end)
end
--[[
Loads a command.
--]]
function ClientRegistry:LoadCommand(CommandData)
self.super:LoadCommand(CommandData)
--Register the command.
local CmdrCommandData = self:GetReplicatableCmdrData(CommandData)
local ExistingCommand = self.Cmdr.Registry.Commands[CmdrCommandData.Name]
if CommandData.OnInvoke or CommandData.Run then
CmdrCommandData.ClientRun = self:CreateRunMethod(CommandData)
elseif ExistingCommand then
CmdrCommandData.ClientRun = ExistingCommand.ClientRun
end
self.Cmdr.Registry:RegisterCommandObject(CmdrCommandData)
end
--[[
Loads the current commands from the server.
--]]
function ClientRegistry:LoadServerCommands()
for _,Command in pairs(self.GetRegisteredCommands:InvokeServer()) do
self:LoadCommand(Command)
end
end
return ClientRegistry |
local cmds = require('commands')
local getopt = require('getopt')
local lib14a = require('read14a')
local utils = require('utils')
local pre = require('precalc')
local toys = require('default_toys')
local lsh = bit32.lshift
local rsh = bit32.rshift
local bor = bit32.bor
local band = bit32.band
example =[[
script run tnp3clone
script run tnp3clone -h
script run tnp3clone -l
script run tnp3clone -t aa00 -s 0030
]]
author = "Iceman"
usage = "script run tnp3clone -t <toytype> -s <subtype>"
desc =[[
This script will try making a barebone clone of a tnp3 tag on to a magic generation1 card.
Arguments:
-h : this help
-l : list all known toy tokens
-t <data> : toytype id, 4hex symbols
-s <data> : subtype id, 4hex symbols
For fun, try the following subtype id:
0612 - Lightcore
0118 - Series 1
0138 - Series 2
0234 - Special
023c - Special
0020 - Swapforce
]]
-- This is only meant to be used when errors occur
function oops(err)
print("ERROR: ",err)
end
-- Usage help
function help()
print(desc)
print("Example usage")
print(example)
end
local function waitCmd()
local response = core.WaitForResponseTimeout(cmds.CMD_ACK,2000)
if response then
local count,cmd,arg0 = bin.unpack('LL',response)
if(arg0==1) then
local count,arg1,arg2,data = bin.unpack('LLH511',response,count)
return data:sub(1,32)
else
return nil, "Couldn't read block."
end
end
return nil, "No response from device"
end
local function readblock( blocknum, keyA )
-- Read block 0
cmd = Command:new{cmd = cmds.CMD_MIFARE_READBL, arg1 = blocknum, arg2 = 0, arg3 = 0, data = keyA}
err = core.SendCommand(cmd:getBytes())
if err then return nil, err end
local block0, err = waitCmd()
if err then return nil, err end
return block0
end
local function readmagicblock( blocknum )
-- Read block 0
local CSETBLOCK_SINGLE_OPERATION = 0x1F
cmd = Command:new{cmd = cmds.CMD_MIFARE_CGETBLOCK, arg1 = CSETBLOCK_SINGLE_OPERATION, arg2 = 0, arg3 = blocknum}
err = core.SendCommand(cmd:getBytes())
if err then return nil, err end
local block0, err = waitCmd()
if err then return nil, err end
return block0
end
local function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
local numBlocks = 64
local cset = 'hf mf csetbl '
local csetuid = 'hf mf csetuid '
local cget = 'hf mf cgetbl '
local empty = '00000000000000000000000000000000'
local AccAndKeyB = '7F078869000000000000'
-- Defaults to Gusto
local toytype = 'C201'
local subtype = '0030'
local DEBUG = true
-- Arguments for the script
for o, a in getopt.getopt(args, 'ht:s:l') do
if o == "h" then return help() end
if o == "t" then toytype = a end
if o == "s" then subtype = a end
if o == "l" then return toys.List() end
end
if #toytype ~= 4 then return oops('Wrong size - toytype. (4hex symbols)') end
if #subtype ~= 4 then return oops('Wrong size - subtype. (4hex symbols)') end
-- look up type, find & validate types
local item = toys.Find( toytype, subtype)
if item then
print( (' Looking up input: Found %s - %s (%s)'):format(item[6],item[5], item[4]) )
else
print('Didn\'t find item type. If you are sure about it, report it in')
end
--15,16
--13-14
-- find tag
result, err = lib14a.read14443a(false, true)
if not result then return oops(err) end
-- load keys
local akeys = pre.GetAll(result.uid)
local keyA = akeys:sub(1, 12 )
local b0 = readblock(0,keyA)
if not b0 then
print('failed reading block with factorydefault key. Trying chinese magic read.')
b0, err = readmagicblock(0)
if not b0 then
oops(err)
return oops('failed reading block with chinese magic command. quitting...')
end
end
-- wipe card.
local cmd = (csetuid..'%s 0004 08 w'):format(result.uid)
core.console(cmd)
local b1 = toytype..string.rep('00',10)..subtype
local calc = utils.Crc16(b0..b1)
local calcEndian = bor(rsh(calc,8), lsh(band(calc, 0xff), 8))
local cmd = (cset..'1 %s%04x'):format( b1, calcEndian)
core.console(cmd)
local pos, key
for blockNo = 2, numBlocks-1, 1 do
pos = (math.floor( blockNo / 4 ) * 12)+1
key = akeys:sub(pos, pos + 11 )
if blockNo%4 == 3 then
cmd = ('%s %d %s%s'):format(cset,blockNo,key,AccAndKeyB)
core.console(cmd)
end
end
core.clearCommandBuffer()
end
main(args) |
--[[
flyboy
By Haxmeister
]]
flyboy.UI = flyboy.UI or {}
flyboy.UI.Display = flyboy.UI.Display or {}
flyboy.UI.NotifyTimer = Timer()
flyboy.UI.Init = function()
if (flyboy.UI.NotifyHolder==nil) then
flyboy.UI.NotifyHolder = iup.vbox { margin="8x4", expand="YES", alignment="ALEFT" }
flyboy.UI.NotifyHolder2 = iup.vbox {
visible="NO",
iup.fill { size="%80" },
iup.hbox {
iup.fill {},
iup.hudrightframe {
border="2 2 2 2",
iup.vbox {
expand="NO",
iup.hudrightframe {
border="0 0 0 0",
iup.hbox {
flyboy.UI.NotifyHolder,
},
},
},
},
iup.fill {},
},
iup.fill {},
alignment="ACENTER",
gap=2
}
iup.Append(HUD.pluginlayer, flyboy.UI.NotifyHolder2)
end
-- warranty status window
flyboy.Notifier.UpdateNotifyDisplayTimer:SetTimeout(1500, flyboy.Notifier.UpdateNotifyDisplay)
end
-- list window
flyboy.List = flyboy.List or {}
local alpha, selalpha = ListColors.Alpha, ListColors.SelectedAlpha
local even, odd, sel = ListColors[0], ListColors[1], ListColors[2]
flyboy.List.bg = {
[0] = even.." "..alpha,
[1] = odd.." "..alpha,
[2] = sel.." "..selalpha
}
flyboy.List.List = flyboy.List.List or iup.pdasubsubmatrix {
numcol=3,
expand='YES',
edit_mode='NO',
bgcolor='0 0 0 128 *',
edition_cb = function()
return iup.IGNORE
end,
enteritem_cb = function(self, line, col)
self:setattribute("BGCOLOR", line, -1, flyboy.List.bg[2])
end,
leaveitem_cb = function(self, line, col)
self:setattribute("BGCOLOR", line, -1, flyboy.List.bg[math.fmod(line,2)])
end
--
--click_cb = function(self, line, col)
--if line == 0 then
---- Click on header
--if sortd == -1 then
--sortd = 1
--elseif sortd == 1 then
--sortd = -1
--end
--flyboy.List.Sort(flyboy.List.List,col,sortd)
--else
---- Not header - select a line
--end
--end
}
flyboy.List.List['0:1'] = 'Sector'
flyboy.List.List['0:2'] = 'Roids'
flyboy.List.List['0:3'] = 'Max'
flyboy.List.List['ALIGNMENT1'] = 'ALEFT'
flyboy.List.List['ALIGNMENT3'] = 'ARIGHT'
flyboy.List.List['WIDTH'.. 1]='100'
flyboy.List.List['WIDTH'.. 2]='50'
flyboy.List.List['WIDTH'.. 3]='50'
flyboy.List.closeBtn = flyboy.List.closeBtn or iup.stationbutton {
title = "Close",
ALIGNMENT="ACENTER",
EXPAND="NO",
action = function(self)
HideDialog(flyboy.List.ListWindow)
end
}
flyboy.List.ListWindow = flyboy.List.ListWindow or iup.dialog{
iup.hbox {
iup.fill {},
iup.vbox {
iup.fill {},
iup.stationhighopacityframe{
expand="NO",
size="x500",
iup.stationhighopacityframebg{
iup.vbox { margin="15x15",
iup.hbox {
iup.fill{}, iup.label { title="Ores Found", font=Font.H3 }, iup.fill{},
},
iup.fill { size="15" },
iup.hbox {
flyboy.List.List,
},
iup.fill { size="15" },
iup.hbox {
iup.fill {},
flyboy.List.closeBtn,
iup.fill {},
},
},
},
},
iup.fill {},
},
iup.fill {},
},
border="NO",menubox="NO",resize="NO",
defaultesc=flyboy.List.closeBtn,
topmost="YES",
modal="YES",
alignment="ACENTER",
bgcolor="0 0 0 92 *",
fullscreen="YES"
}
flyboy.List.ListWindow:map()
--RegisterEvent(flyboy.Notifier.TargetChanged, "TARGET_CHANGED")
|
-- vscode theme configuration
vim.g.vscode_style = "dark"
vim.g.vscode_italic_comment = 1
-- vim.g.vscode_transparent = 1
|
teal_item =
{
codename = "excalibur",
name = "Excalibur",
description = "Legendary Sword",
level = 1,
icon = ":/game/items/swords/broadsword_fire",
map_offset = { x = 12, y = -3 },
components =
{
damage_modifier =
{
attack =
{
fire = 150
},
resistance =
{
neutral = 6,
fire = 18
}
},
equippable =
{
bodypart = "Hands",
use_both_hands = false,
skill_id = "item_excalibur"
}
}
}
|
function new_world()
local w={}
w.score=0
w.spawn_t=2000
w.spawn_dt=1000
w.ball={x=309/2-12, y=96, dx=0, dy=0}
set_ball_image(w)
w.ball.lethalt=0
w.bonuses={}
w.plrbonus=0
if debug then w.plrbonus=10 end
w.shifters={}
w.spawners={}
for i=1,5 do
local sx,sy=grid*i+1,309/2-grid+grid*i+1
ins(w.shifters,{x=sx,y=sy})
ins(w.shifters,{x=309-sx-43,y=sy})
end
w.shouts={}
w.particles={}
w.rp={i=1}
w.t=0
return w
end
function reset(w,noresettime)
w=w or main_wld
w.score=0
w.ball.x=309/2-12; w.ball.y=96; w.ball.dx=0; w.ball.dy=0; w.ball.bonus=nil
w.plrbonus=0
if debug then w.plrbonus=10 end
w.bonuses={}
w.spawn_t=2000
w.spawn_dt=1000
w.shifters={}
w.spawners={}
for i=1,5 do
local sx,sy=grid*i+1,309/2-grid+grid*i+1
ins(w.shifters,{x=sx,y=sy})
--prep_spec(w.shifters[#w.shifters],w)
ins(w.shifters,{x=309-sx-43,y=sy})
--prep_spec(w.shifters[#w.shifters],w)
end
if w.mode=='Chaotic' then
ins(w.shifters,{x=grid*0+1,y=309/2-grid+grid*0+1})
prep_spec(w.shifters[#w.shifters],w,false,true)
w.shifters[#w.shifters].myspawn={}
ins(w.shifters,{x=309-grid*0+1-43-1-1,y=309/2-grid+grid*0+1+1-1})
prep_spec(w.shifters[#w.shifters],w,false,true)
w.shifters[#w.shifters].myspawn={}
end
w.shouts={}
w.particles={}
if love.update~=replay and love.update~=rp_gallery and love.update~=rp_zoom then
w.rp={i=1}
love.update=update
end
if not noresettime then
w.t=0
end
end
function set_ball_image(w)
w.ball.img=lg.newCanvas(26,26)
lg.setCanvas(w.ball.img)
fg(0xa0/255.0,0xa0/255.0,0xa0/255.0)
circ('fill',13,13,13)
fg(0xf0/255.0,0xf0/255.0,0xf0/255.0)
circ('fill',13,13,12.8)
lg.setCanvas()
w.ball.imgdata=w.ball.img:newImageData()
end |
-- ref:
-- https://www.lua.org/pil/1.2.html
-- https://love2d.org/wiki/love.graphics
leftx = 0
lefty = 0
rightx = love.graphics.getWidth() - 20
righty = 0
movement = 10
-- ref:
-- https://love2d.org/wiki/love.load
-- https://love2d.org/wiki/love.graphics
function love.load()
background = love.graphics.newImage("background.png")
end
-- ref:
-- https://love2d.org/wiki/love.draw
-- https://love2d.org/wiki/love.graphics
function love.draw()
love.graphics.draw(background, 0, 0)
love.graphics.rectangle("fill", leftx, lefty, 20, 60)
love.graphics.rectangle("fill", rightx, righty, 20, 60)
end
-- We are changing how we are dealing with keys
-- You might have been a bit annoyed with not being able to hold
-- down keys to move the paddles. To change that we will start
-- using the love.update function when dealing with keys.
-- ref:
-- https://love2d.org/wiki/love.keyboard
-- https://love2d.org/wiki/love.update
-- https://www.lua.org/pil/4.3.1.html
function love.update(dt)
-- left side paddle
if love.keyboard.isDown("s") then
lefty = lefty - movement
end
if love.keyboard.isDown("x") then
lefty = lefty + movement
end
-- right side paddle
if love.keyboard.isDown("up") then
righty = righty - movement
end
if love.keyboard.isDown("down") then
righty = righty + movement
end
end
|
name = "Balloons 2 Wes"
description = [[
EN:
Wes character remake made by Ophaneom.
Customizable mod.
- STATUS:
* Maximum life increased from 113 to 150.
* Maximum hunger increased from 113 to 150.
* Hunger multiplier changed from 1.25x to 1x.
* Damage multiplier changed from 0.75x to 1x.
- BALLOONS:
* New crafting tab.
* Explosive Balloon: Damage a small area after a few seconds.
* Pig Balloon: Spawns a temporary pig king and his followers.
* Spider Balloon: Spawns 3 spider dens around the balloon.
* Beefalo balloon: Spawns 1 baby beefalo.
PT-BR:
Remake do personagem Wes feito por Ophaneom.
Mod customizável.
- STATUS:
* Vida máxima aumentada de 113 para 150.
* Fome máxima aumentada de 113 para 150.
* Multiplicador de fome alterado de 1.25x para 1x.
* Multiplicador de dano alterado de 0.75x para 1x.
- BALÕES:
* Nova aba de crafting.
* Balão Explosivo: Dá um pequeno dano em área após alguns segundos.
* Balão de Porco: Spawna um rei porco temporário e seus súditos.
* Balão de Aranha: Spawna de 3 casulos em volta do balão.
* Balão de Beefalo: Spawna de 1 bebê beefalo.
]]
author = "Ophaneom"
version = "1.0.2c"
forumthread = ""
api_version = 10
priority = -20
dont_starve_compatible = true
reign_of_giants_compatible = true
dst_compatible = true
hamlet_compatible = true
all_clients_require_mod = true
client_only_mod = false
server_only_mod = false
icon_atlas = "icone.xml"
icon = "icone.tex"
local never = {{description = "", data = false}}
local function Breaker(title, hover)
return {
name = title,
hover = hover,
options = never,
default = false
}
end
configuration_options =
{
Breaker("Language Settings"),
{
name = "LINGUAGEM",
label = "Language",
options = {
{description = "English", data = "EN"},
{description = "Portuguese-BR", data = "BR"},
},
default = "EN",
},
Breaker("Wes Status Settings"),
{
name = "HEALTH",
label = "Health",
options = {
{description = "1", data = "1"},{description = "5", data = "5"},{description = "10", data = "10"},{description = "20", data = "20"},{description = "30", data = "30"},
{description = "40", data = "40"},{description = "50", data = "50"},{description = "60", data = "60"},{description = "70", data = "70"},{description = "80", data = "80"},
{description = "90", data = "90"},{description = "100", data = "100"},{description = "110", data = "110"},{description = "113 - Vanilla", data = "113"},{description = "120", data = "120"},
{description = "130", data = "130"},{description = "140", data = "140"},{description = "150 - Default", data = "150"},{description = "160", data = "160"},{description = "170", data = "170"},
{description = "180", data = "180"},{description = "190", data = "190"},{description = "200", data = "200"},{description = "210", data = "210"},{description = "220", data = "220"},
{description = "230", data = "230"},{description = "240", data = "240"},{description = "250", data = "250"},{description = "260", data = "260"},{description = "270", data = "270"},
{description = "280", data = "280"},{description = "290", data = "290"},{description = "300", data = "300"},{description = "400", data = "400"},{description = "500", data = "500"},
{description = "600", data = "600"},{description = "700", data = "700"},{description = "800", data = "800"},{description = "900", data = "900"},{description = "1000", data = "1000"},
},
default = "150",
},
{
name = "SANITY",
label = "Sanity",
options = {
{description = "1", data = "1"},{description = "5", data = "5"},{description = "10", data = "10"},{description = "20", data = "20"},{description = "30", data = "30"},
{description = "40", data = "40"},{description = "50", data = "50"},{description = "60", data = "60"},{description = "70", data = "70"},{description = "80", data = "80"},
{description = "90", data = "90"},{description = "100", data = "100"},{description = "110", data = "110"},{description = "113 - Vanilla", data = "113"},{description = "120", data = "120"},
{description = "130", data = "130"},{description = "140", data = "140"},{description = "150 - Default", data = "150"},{description = "160", data = "160"},{description = "170", data = "170"},
{description = "180", data = "180"},{description = "190", data = "190"},{description = "200", data = "200"},{description = "210", data = "210"},{description = "220", data = "220"},
{description = "230", data = "230"},{description = "240", data = "240"},{description = "250", data = "250"},{description = "260", data = "260"},{description = "270", data = "270"},
{description = "280", data = "280"},{description = "290", data = "290"},{description = "300", data = "300"},{description = "400", data = "400"},{description = "500", data = "500"},
{description = "600", data = "600"},{description = "700", data = "700"},{description = "800", data = "800"},{description = "900", data = "900"},{description = "1000", data = "1000"},
},
default = "150",
},
{
name = "HUNGER",
label = "Hunger",
options = {
{description = "1", data = "1"},{description = "5", data = "5"},{description = "10", data = "10"},{description = "20", data = "20"},{description = "30", data = "30"},
{description = "40", data = "40"},{description = "50", data = "50"},{description = "60", data = "60"},{description = "70", data = "70"},{description = "80", data = "80"},
{description = "90", data = "90"},{description = "100", data = "100"},{description = "110", data = "110"},{description = "113 - Vanilla", data = "113"},{description = "120", data = "120"},
{description = "130", data = "130"},{description = "140", data = "140"},{description = "150 - Default", data = "150"},{description = "160", data = "160"},{description = "170", data = "170"},
{description = "180", data = "180"},{description = "190", data = "190"},{description = "200", data = "200"},{description = "210", data = "210"},{description = "220", data = "220"},
{description = "230", data = "230"},{description = "240", data = "240"},{description = "250", data = "250"},{description = "260", data = "260"},{description = "270", data = "270"},
{description = "280", data = "280"},{description = "290", data = "290"},{description = "300", data = "300"},{description = "400", data = "400"},{description = "500", data = "500"},
{description = "600", data = "600"},{description = "700", data = "700"},{description = "800", data = "800"},{description = "900", data = "900"},{description = "1000", data = "1000"},
},
default = "150",
},
{
name = "HUNGER_RATE",
label = "Hunger Rate",
options = {
{description = "0.10x", data = "0.10"},{description = "0.15x", data = "0.15"},
{description = "0.20x", data = "0.20"},{description = "0.25x", data = "0.25"},
{description = "0.30x", data = "0.30"},{description = "0.35x", data = "0.35"},
{description = "0.40x", data = "0.40"},{description = "0.45x", data = "0.45"},
{description = "0.50x", data = "0.50"},{description = "0.55x", data = "0.55"},
{description = "0.60x", data = "0.60"},{description = "0.65x", data = "0.65"},
{description = "0.70x", data = "0.70"},{description = "0.75x", data = "0.75"},
{description = "0.80x", data = "0.80"},{description = "0.85x", data = "0.85"},
{description = "0.90x", data = "0.90"},{description = "0.95x", data = "0.95"},
{description = "1.00x - Default", data = "1.00"},{description = "1.05x", data = "1.05"},
{description = "1.10x", data = "1.10"},{description = "1.15x", data = "1.15"},
{description = "1.20x", data = "1.20"},{description = "1.25x - Vanilla", data = "1.25"},
{description = "1.30x", data = "1.30"},{description = "1.35x", data = "1.35"},
{description = "1.40x", data = "1.40"},{description = "1.45x", data = "1.45"},
{description = "1.50x", data = "1.50"},{description = "1.55x", data = "1.55"},
{description = "1.60x", data = "1.60"},{description = "1.65x", data = "1.65"},
{description = "1.70x", data = "1.70"},{description = "1.75x", data = "1.75"},
{description = "1.80x", data = "1.80"},{description = "1.85x", data = "1.85"},
{description = "1.90x", data = "1.90"},{description = "1.95x", data = "1.95"},
{description = "2.00x", data = "2.00"},{description = "2.05x", data = "2.05"},
{description = "2.10x", data = "2.10"},{description = "2.15x", data = "2.15"},
{description = "2.20x", data = "2.20"},{description = "2.25x", data = "2.25"},
{description = "2.30x", data = "2.30"},{description = "2.35x", data = "2.35"},
{description = "2.40x", data = "2.40"},{description = "2.45x", data = "2.45"},
{description = "2.50x", data = "2.50"},{description = "2.55x", data = "2.55"},
{description = "2.60x", data = "2.60"},{description = "2.65x", data = "2.65"},
{description = "2.70x", data = "2.70"},{description = "2.75x", data = "2.75"},
{description = "2.80x", data = "2.80"},{description = "2.85x", data = "2.85"},
{description = "2.90x", data = "2.90"},{description = "2.95x", data = "2.95"},
{description = "3.00x", data = "3.00"},
},
default = "1.00",
},
{
name = "DAMAGE_MULT",
label = "Damage Multiplier",
options = {
{description = "0.10x", data = "0.10"},{description = "0.15x", data = "0.15"},
{description = "0.20x", data = "0.20"},{description = "0.25x", data = "0.25"},
{description = "0.30x", data = "0.30"},{description = "0.35x", data = "0.35"},
{description = "0.40x", data = "0.40"},{description = "0.45x", data = "0.45"},
{description = "0.50x", data = "0.50"},{description = "0.55x", data = "0.55"},
{description = "0.60x", data = "0.60"},{description = "0.65x", data = "0.65"},
{description = "0.70x", data = "0.70"},{description = "0.75x - Vanilla", data = "0.75"},
{description = "0.80x", data = "0.80"},{description = "0.85x", data = "0.85"},
{description = "0.90x", data = "0.90"},{description = "0.95x", data = "0.95"},
{description = "1.00x - Default", data = "1.00"},{description = "1.05x", data = "1.05"},
{description = "1.10x", data = "1.10"},{description = "1.15x", data = "1.15"},
{description = "1.20x", data = "1.20"},{description = "1.25x", data = "1.25"},
{description = "1.30x", data = "1.30"},{description = "1.35x", data = "1.35"},
{description = "1.40x", data = "1.40"},{description = "1.45x", data = "1.45"},
{description = "1.50x", data = "1.50"},{description = "1.55x", data = "1.55"},
{description = "1.60x", data = "1.60"},{description = "1.65x", data = "1.65"},
{description = "1.70x", data = "1.70"},{description = "1.75x", data = "1.75"},
{description = "1.80x", data = "1.80"},{description = "1.85x", data = "1.85"},
{description = "1.90x", data = "1.90"},{description = "1.95x", data = "1.95"},
{description = "2.00x", data = "2.00"},{description = "2.05x", data = "2.05"},
{description = "2.10x", data = "2.10"},{description = "2.15x", data = "2.15"},
{description = "2.20x", data = "2.20"},{description = "2.25x", data = "2.25"},
{description = "2.30x", data = "2.30"},{description = "2.35x", data = "2.35"},
{description = "2.40x", data = "2.40"},{description = "2.45x", data = "2.45"},
{description = "2.50x", data = "2.50"},{description = "2.55x", data = "2.55"},
{description = "2.60x", data = "2.60"},{description = "2.65x", data = "2.65"},
{description = "2.70x", data = "2.70"},{description = "2.75x", data = "2.75"},
{description = "2.80x", data = "2.80"},{description = "2.85x", data = "2.85"},
{description = "2.90x", data = "2.90"},{description = "2.95x", data = "2.95"},
{description = "3.00x", data = "3.00"},
},
default = "1.00",
},
{
name = "WALK_SPEED",
label = "Walk Speed",
options = {
{description = "1", data = "1"},{description = "2", data = "2"},{description = "3", data = "3"},{description = "4 - Vanilla", data = "4"},{description = "5", data = "5"},
{description = "6", data = "6"},{description = "7", data = "7"},{description = "8", data = "8"},{description = "9", data = "9"},{description = "10", data = "10"},
{description = "11", data = "11"},{description = "12", data = "12"},{description = "13", data = "13"},{description = "14", data = "14"},{description = "15", data = "15"},
{description = "16", data = "16"},{description = "17", data = "17"},{description = "18", data = "18"},{description = "19", data = "19"},{description = "20", data = "20"},
},
default = "4",
},
{
name = "RUN_SPEED",
label = "Run Speed",
options = {
{description = "1", data = "1"},{description = "2", data = "2"},{description = "3", data = "3"},{description = "4", data = "4"},{description = "5", data = "5"},
{description = "6 - Vanilla", data = "6"},{description = "7", data = "7"},{description = "8", data = "8"},{description = "9", data = "9"},{description = "10", data = "10"},
{description = "11", data = "11"},{description = "12", data = "12"},{description = "13", data = "13"},{description = "14", data = "14"},{description = "15", data = "15"},
{description = "16", data = "16"},{description = "17", data = "17"},{description = "18", data = "18"},{description = "19", data = "19"},{description = "20", data = "20"},
},
default = "6",
},
Breaker("Balloon Delay Settings"),
{
name = "DELAY_EXPLOSIVE",
label = "Delay Explosive Balloon",
options = {
{description = "1s", data = "1"},{description = "2s", data = "2"},{description = "3s", data = "3"},{description = "4s", data = "4"},{description = "5s", data = "5"},
{description = "6s", data = "6"},{description = "7s", data = "7"},{description = "8s", data = "8"},{description = "9s", data = "9"},{description = "10s", data = "10"},
{description = "11s", data = "11"},{description = "12s", data = "12"},{description = "13s", data = "13"},{description = "14s", data = "14"},{description = "15s", data = "15"},
{description = "16s", data = "16"},{description = "17s", data = "17"},{description = "18s", data = "18"},{description = "19s", data = "19"},{description = "20s", data = "20"},
},
default = "1",
},
{
name = "DELAY_PIG",
label = "Delay Pig Balloon",
options = {
{description = "1s", data = "1"},{description = "2s", data = "2"},{description = "3s", data = "3"},{description = "4s", data = "4"},{description = "5s", data = "5"},
{description = "6s", data = "6"},{description = "7s", data = "7"},{description = "8s", data = "8"},{description = "9s", data = "9"},{description = "10s", data = "10"},
{description = "11s", data = "11"},{description = "12s", data = "12"},{description = "13s", data = "13"},{description = "14s", data = "14"},{description = "15s", data = "15"},
{description = "16s", data = "16"},{description = "17s", data = "17"},{description = "18s", data = "18"},{description = "19s", data = "19"},{description = "20s", data = "20"},
},
default = "1",
},
{
name = "DELAY_SPIDER",
label = "Delay Spider Balloon",
options = {
{description = "1s", data = "1"},{description = "2s", data = "2"},{description = "3s", data = "3"},{description = "4s", data = "4"},{description = "5s", data = "5"},
{description = "6s", data = "6"},{description = "7s", data = "7"},{description = "8s", data = "8"},{description = "9s", data = "9"},{description = "10s", data = "10"},
{description = "11s", data = "11"},{description = "12s", data = "12"},{description = "13s", data = "13"},{description = "14s", data = "14"},{description = "15s", data = "15"},
{description = "16s", data = "16"},{description = "17s", data = "17"},{description = "18s", data = "18"},{description = "19s", data = "19"},{description = "20s", data = "20"},
},
default = "1",
},
{
name = "DELAY_BEEFALO",
label = "Delay Beefalo Balloon",
options = {
{description = "1s", data = "1"},{description = "2s", data = "2"},{description = "3s", data = "3"},{description = "4s", data = "4"},{description = "5s", data = "5"},
{description = "6s", data = "6"},{description = "7s", data = "7"},{description = "8s", data = "8"},{description = "9s", data = "9"},{description = "10s", data = "10"},
{description = "11s", data = "11"},{description = "12s", data = "12"},{description = "13s", data = "13"},{description = "14s", data = "14"},{description = "15s", data = "15"},
{description = "16s", data = "16"},{description = "17s", data = "17"},{description = "18s", data = "18"},{description = "19s", data = "19"},{description = "20s", data = "20"},
},
default = "1",
},
Breaker("Pig King Settings"),
{
name = "PIGKING_DURATION",
label = "Pig King Duration",
options = {
{description = "1", data = "1"},{description = "5", data = "5"},{description = "10", data = "10"},{description = "20", data = "20"},{description = "30", data = "30"},
{description = "40", data = "40"},{description = "50", data = "50"},{description = "60", data = "60"},{description = "70", data = "70"},{description = "80", data = "80"},
{description = "90", data = "90"},{description = "100", data = "100"},{description = "110", data = "110"},{description = "120", data = "120"},{description = "130", data = "130"},
{description = "140", data = "140"},{description = "150", data = "150"},{description = "160", data = "160"},{description = "170", data = "170"},{description = "180", data = "180"},
{description = "190", data = "190"},{description = "200", data = "200"},{description = "210", data = "210"},{description = "220", data = "220"},{description = "230", data = "230"},
{description = "240", data = "240"},{description = "250", data = "250"},{description = "260", data = "260"},{description = "270", data = "270"},{description = "280", data = "280"},
{description = "290", data = "290"},{description = "300", data = "300"},
},
default = "60",
},
{
name = "PIGMAN_DURATION",
label = "Pigmans Duration",
options = {
{description = "1", data = "1"},{description = "5", data = "5"},{description = "10", data = "10"},{description = "20", data = "20"},{description = "30", data = "30"},
{description = "40", data = "40"},{description = "50", data = "50"},{description = "60", data = "60"},{description = "70", data = "70"},{description = "80", data = "80"},
{description = "90", data = "90"},{description = "100", data = "100"},{description = "110", data = "110"},{description = "120", data = "120"},{description = "130", data = "130"},
{description = "140", data = "140"},{description = "150", data = "150"},{description = "160", data = "160"},{description = "170", data = "170"},{description = "180", data = "180"},
{description = "190", data = "190"},{description = "200", data = "200"},{description = "210", data = "210"},{description = "220", data = "220"},{description = "230", data = "230"},
{description = "240", data = "240"},{description = "250", data = "250"},{description = "260", data = "260"},{description = "270", data = "270"},{description = "280", data = "280"},
{description = "290", data = "290"},{description = "300", data = "300"},
},
default = "60",
},
Breaker("Spider Settings"),
{
name = "SPIDERDEN_QNT",
label = "Spiderden Quantity",
options = {
{description = "1", data = "1"},{description = "2", data = "2"},{description = "3", data = "3"},{description = "4", data = "4"},{description = "5", data = "5"},
{description = "6", data = "6"},{description = "7", data = "7"},{description = "8", data = "8"},{description = "9", data = "9"},{description = "10", data = "10"},
{description = "11", data = "11"},{description = "12", data = "12"},{description = "13", data = "13"},{description = "14", data = "14"},{description = "15", data = "15"},
{description = "16", data = "16"},{description = "17", data = "17"},{description = "18", data = "18"},{description = "19", data = "19"},{description = "20", data = "20"},
},
default = "3",
},
{
name = "SPIDERDEN_RANGE",
label = "Spiderden Range",
options = {
{description = "1", data = "1"},{description = "2", data = "2"},{description = "3", data = "3"},{description = "4", data = "4"},{description = "5", data = "5"},
{description = "6", data = "6"},{description = "7", data = "7"},{description = "8", data = "8"},{description = "9", data = "9"},{description = "10", data = "10"},
{description = "11", data = "11"},{description = "12", data = "12"},{description = "13", data = "13"},{description = "14", data = "14"},{description = "15", data = "15"},
},
default = "7",
},
Breaker("Beefalo Settings"),
{
name = "BEEFALO_QNT",
label = "Beefalo Quantity",
options = {
{description = "1", data = "1"},{description = "2", data = "2"},{description = "3", data = "3"},{description = "4", data = "4"},{description = "5", data = "5"},
{description = "6", data = "6"},{description = "7", data = "7"},{description = "8", data = "8"},{description = "9", data = "9"},{description = "10", data = "10"},
{description = "11", data = "11"},{description = "12", data = "12"},{description = "13", data = "13"},{description = "14", data = "14"},{description = "15", data = "15"},
{description = "16", data = "16"},{description = "17", data = "17"},{description = "18", data = "18"},{description = "19", data = "19"},{description = "20", data = "20"},
},
default = "1",
},
{
name = "BEEFALO_RANGE",
label = "Beefalo Range",
options = {
{description = "1", data = "1"},{description = "2", data = "2"},{description = "3", data = "3"},{description = "4", data = "4"},{description = "5", data = "5"},
{description = "6", data = "6"},{description = "7", data = "7"},{description = "8", data = "8"},{description = "9", data = "9"},{description = "10", data = "10"},
{description = "11", data = "11"},{description = "12", data = "12"},{description = "13", data = "13"},{description = "14", data = "14"},{description = "15", data = "15"},
},
default = "2",
},
Breaker("Pigman Settings"),
{
name = "PIGMAN_QNT",
label = "Pigmans Quantity",
options = {
{description = "1", data = "1"},{description = "2", data = "2"},{description = "3", data = "3"},{description = "4", data = "4"},{description = "5", data = "5"},
{description = "6", data = "6"},{description = "7", data = "7"},{description = "8", data = "8"},{description = "9", data = "9"},{description = "10", data = "10"},
{description = "11", data = "11"},{description = "12", data = "12"},{description = "13", data = "13"},{description = "14", data = "14"},{description = "15", data = "15"},
{description = "16", data = "16"},{description = "17", data = "17"},{description = "18", data = "18"},{description = "19", data = "19"},{description = "20", data = "20"},
},
default = "3",
},
{
name = "PIGMAN_RANGE",
label = "Pigmans Range",
options = {
{description = "1", data = "1"},{description = "2", data = "2"},{description = "3", data = "3"},{description = "4", data = "4"},{description = "5", data = "5"},
{description = "6", data = "6"},{description = "7", data = "7"},{description = "8", data = "8"},{description = "9", data = "9"},{description = "10", data = "10"},
{description = "11", data = "11"},{description = "12", data = "12"},{description = "13", data = "13"},{description = "14", data = "14"},{description = "15", data = "15"},
},
default = "5",
},
{
name = "PIGMAN_HEALTH",
label = "Pigmans Health",
options = {
{description = "1", data = "1"},{description = "5", data = "5"},{description = "10", data = "10"},{description = "20", data = "20"},{description = "30", data = "30"},
{description = "40", data = "40"},{description = "50", data = "50"},{description = "60", data = "60"},{description = "70", data = "70"},{description = "80", data = "80"},
{description = "90", data = "90"},{description = "100", data = "100"},{description = "110", data = "110"},{description = "120", data = "120"},{description = "130", data = "130"},
{description = "140", data = "140"},{description = "150", data = "150"},{description = "160", data = "160"},{description = "170", data = "170"},{description = "180", data = "180"},
{description = "190", data = "190"},{description = "200", data = "200"},{description = "210", data = "210"},{description = "220", data = "220"},{description = "230", data = "230"},
{description = "240", data = "240"},{description = "250", data = "250"},{description = "260", data = "260"},{description = "270", data = "270"},{description = "280", data = "280"},
{description = "290", data = "290"},{description = "300", data = "300"},{description = "400", data = "400"},{description = "500", data = "500"},{description = "600", data = "600"},
{description = "700", data = "700"},{description = "800", data = "800"},{description = "900", data = "900"},{description = "1000", data = "1000"},
},
default = "400",
},
{
name = "PIGMAN_DAMAGE",
label = "Pigmans Damage",
options = {
{description = "1", data = "1"},{description = "5", data = "5"},{description = "10", data = "10"},{description = "20", data = "20"},{description = "30", data = "30"},{description = "33", data = "33"},
{description = "40", data = "40"},{description = "50", data = "50"},{description = "60", data = "60"},{description = "70", data = "70"},{description = "80", data = "80"},
{description = "90", data = "90"},{description = "100", data = "100"},{description = "110", data = "110"},{description = "120", data = "120"},{description = "130", data = "130"},
{description = "140", data = "140"},{description = "150", data = "150"},{description = "160", data = "160"},{description = "170", data = "170"},{description = "180", data = "180"},
{description = "190", data = "190"},{description = "200", data = "200"},{description = "210", data = "210"},{description = "220", data = "220"},{description = "230", data = "230"},
{description = "240", data = "240"},{description = "250", data = "250"},{description = "260", data = "260"},{description = "270", data = "270"},{description = "280", data = "280"},
{description = "290", data = "290"},{description = "300", data = "300"},{description = "400", data = "400"},{description = "500", data = "500"},{description = "600", data = "600"},
{description = "700", data = "700"},{description = "800", data = "800"},{description = "900", data = "900"},{description = "1000", data = "1000"},
},
default = "33",
},
{
name = "PIGMAN_ATTACKSPEED",
label = "Pigmans Attack Speed",
options = {
{description = "1", data = "1"},{description = "2", data = "2"},{description = "3", data = "3"},{description = "4", data = "4"},{description = "5", data = "5"},
{description = "6", data = "6"},{description = "7", data = "7"},{description = "8", data = "8"},{description = "9", data = "9"},{description = "10", data = "10"},
{description = "11", data = "11"},{description = "12", data = "12"},{description = "13", data = "13"},{description = "14", data = "14"},{description = "15", data = "15"},
},
default = "3",
},
{
name = "PIGMAN_RUNSPEED",
label = "Pigmans Run Speed",
options = {
{description = "1", data = "1"},{description = "2", data = "2"},{description = "3", data = "3"},{description = "4", data = "4"},{description = "5", data = "5"},
{description = "6", data = "6"},{description = "7", data = "7"},{description = "8", data = "8"},{description = "9", data = "9"},{description = "10", data = "10"},
{description = "11", data = "11"},{description = "12", data = "12"},{description = "13", data = "13"},{description = "14", data = "14"},{description = "15", data = "15"},
},
default = "5",
},
{
name = "PIGMAN_WALKSPEED",
label = "Pigmans Walk Speed",
options = {
{description = "1", data = "1"},{description = "2", data = "2"},{description = "3", data = "3"},{description = "4", data = "4"},{description = "5", data = "5"},
{description = "6", data = "6"},{description = "7", data = "7"},{description = "8", data = "8"},{description = "9", data = "9"},{description = "10", data = "10"},
{description = "11", data = "11"},{description = "12", data = "12"},{description = "13", data = "13"},{description = "14", data = "14"},{description = "15", data = "15"},
},
default = "3",
},
}
|
function Teleporting_onUse1 (pUnit, Event, pMisc)
pMisc:Teleport (0,1934.19,2124.14,141.566)
end
RegisterGameObjectEvent (5000000, 4, "Teleporting_onUse1")
|
--ヴァンパイア・デザイア
--Script by nekrozar
function c100408008.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,100408008+EFFECT_COUNT_CODE_OATH)
e1:SetTarget(c100408008.target)
e1:SetOperation(c100408008.activate)
c:RegisterEffect(e1)
end
function c100408008.tgfilter1(c,tp)
local lv=c:GetLevel()
return lv>0 and c:IsFaceup()
and Duel.IsExistingMatchingCard(c100408008.tgfilter2,tp,LOCATION_DECK,0,1,nil,lv)
end
function c100408008.tgfilter2(c,lv)
return c:IsSetCard(0x8e) and c:IsLevelAbove(0) and not c:IsLevel(lv) and c:IsAbleToGrave()
end
function c100408008.spfilter1(c,tp)
return c:IsAbleToGrave() and Duel.GetMZoneCount(tp,c)>0
end
function c100408008.spfilter2(c,e,tp)
return c:IsSetCard(0x8e) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c100408008.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then
if e:GetLabel()==0 then
return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c100408008.tgfilter1(chkc,tp)
else
return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c100408008.spfilter2(chkc,e,tp)
end
end
local b1=Duel.IsExistingTarget(c100408008.tgfilter1,tp,LOCATION_MZONE,0,1,nil,tp)
local b2=Duel.IsExistingMatchingCard(c100408008.spfilter1,tp,LOCATION_MZONE,0,1,nil,tp)
and Duel.IsExistingTarget(c100408008.spfilter2,tp,LOCATION_GRAVE,0,1,nil,e,tp)
if chk==0 then return b1 or b2 end
local op=0
if b1 and b2 then
op=Duel.SelectOption(tp,aux.Stringid(100408008,0),aux.Stringid(100408008,1))
elseif b1 then
op=Duel.SelectOption(tp,aux.Stringid(100408008,0))
else
op=Duel.SelectOption(tp,aux.Stringid(100408008,1))+1
end
e:SetLabel(op)
if op==0 then
e:SetCategory(CATEGORY_TOGRAVE)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,c100408008.tgfilter1,tp,LOCATION_MZONE,0,1,1,nil,tp)
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_DECK)
else
e:SetCategory(CATEGORY_TOGRAVE+CATEGORY_SPECIAL_SUMMON)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c100408008.spfilter2,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_MZONE)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
end
function c100408008.activate(e,tp,eg,ep,ev,re,r,rp)
if e:GetLabel()==0 then
local tc=Duel.GetFirstTarget()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c100408008.tgfilter2,tp,LOCATION_DECK,0,1,1,nil,tc:GetLevel())
if g:GetCount()>0 and Duel.SendtoGrave(g,REASON_EFFECT)~=0 and g:GetFirst():IsLocation(LOCATION_GRAVE)
and tc:IsRelateToEffect(e) and tc:IsFaceup() then
local lv=g:GetFirst():GetLevel()
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LEVEL)
e1:SetValue(lv)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
end
else
local tc=Duel.GetFirstTarget()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local tg=Duel.SelectMatchingCard(tp,c100408008.spfilter1,tp,LOCATION_MZONE,0,1,1,nil,tp)
if tg:GetCount()>0 and Duel.SendtoGrave(tg,REASON_EFFECT)~=0 and tg:GetFirst():IsLocation(LOCATION_GRAVE)
and tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
end
|
LinkLuaModifier("modifier_ardm", "modifiers/modifier_ardm.lua", LUA_MODIFIER_MOTION_NONE )
modifier_ardm = class(ModifierBaseClass)
-- START IF SERVER
if IsServer() then
function modifier_ardm:ReplaceHero ()
-- this is not the total gold, this is only the gold on the hero...
local parent = self:GetParent()
local playerId = parent:GetPlayerID()
local currentDotaGold = PlayerResource:GetGold(playerId)
local items = {}
-- Reset cooldown for items
for i = DOTA_ITEM_SLOT_1, DOTA_ITEM_SLOT_9 do
local item = parent:GetItemInSlot(i)
items[i] = item
end
Debug:EnableDebugging()
local heroXp = parent:GetCurrentXP()
--local heroLevel = parent:GetLevel()
--DebugPrint('Hero was level ' .. heroLevel .. ' with xp ' .. heroXp)
Timers:CreateTimer(0, function()
PlayerResource:ReplaceHeroWith(playerId, self.hero, currentDotaGold, heroXp)
local newHero = PlayerResource:GetSelectedHeroEntity(playerId)
-- while newHero:GetLevel() < heroLevel do
-- newHero:HeroLevelUp(false)
-- local level = newHero:GetLevel()
-- AbilityLevels:CheckAbilityLevels({
-- level = level,
-- player = PlayerResource:GetPlayer(playerId):entindex(),
-- selectedEntity = newHero:entindex()
-- })
-- HeroProgression:ReduceStatGain(newHero, level)
-- HeroProgression:ProcessAbilityPointGain(newHero, level)
-- end
--newHero:AddExperience(heroXp, DOTA_ModifyXP_Unspecified, false, true)
-- for i = DOTA_ITEM_SLOT_1, DOTA_ITEM_SLOT_9 do
-- local item = newHero:GetItemInSlot(i)
-- if item then
-- newHero:RemoveItem(item)
-- end
-- end
for i = DOTA_ITEM_SLOT_1, DOTA_ITEM_SLOT_9 do
local item = items[i]
if item then
newHero:AddItem(item)
end
end
--UTIL_Remove(parent)
end)
end
function modifier_ardm:DeclareFunctions ()
return {
MODIFIER_EVENT_ON_RESPAWN
}
end
function modifier_ardm:OnRespawn()
if self.hero then
-- run next frame
self:ReplaceHero()
end
end
-- END IF SERVER
end
function modifier_ardm:IsHidden()
return true
end
function modifier_ardm:IsDebuff()
return false
end
function modifier_ardm:IsPurgable()
return false
end
function modifier_ardm:IsPurgeException()
return false
end
function modifier_ardm:IsPermanent()
return true
end
function modifier_ardm:RemoveOnDeath()
return false
end
|
if SERVER then
AddCSLuaFile("shared.lua")
end
if CLIENT then
SWEP.ViewModelFlip = false
SWEP.PrintName = "FAMAS"
SWEP.IconLetter = "v"
SWEP.Slot = 4
SWEP.Slotpos = 2
end
SWEP.HoldType = "ar2"
SWEP.Base = "rad_base"
SWEP.ViewModel = "models/weapons/v_rif_famas.mdl"
SWEP.WorldModel = "models/weapons/w_rif_famas.mdl"
SWEP.SprintPos = Vector(4.9288, -2.4157, 2.2032)
SWEP.SprintAng = Vector(0.8736, 40.1165, 28.0526)
SWEP.IsSniper = false
SWEP.AmmoType = "Rifle"
SWEP.Primary.Sound = Sound( "Weapon_famas.Single" )
SWEP.Primary.Recoil = 7.5
SWEP.Primary.Damage = 45
SWEP.Primary.NumShots = 1
SWEP.Primary.Cone = 0.035
SWEP.Primary.Delay = 0.100
SWEP.Primary.ClipSize = 25
SWEP.Primary.Automatic = true
|
-----------------------------------
-- Area: Alzadaal Undersea Ruins
-- NPC: ??? (Spawn Armed Gears(ZNM T3))
-- !pos -42 -4 -169 72
-----------------------------------
local ID = require("scripts/zones/Alzadaal_Undersea_Ruins/IDs")
require("scripts/globals/npc_util")
-----------------------------------
function onTrade(player, npc, trade)
if npcUtil.tradeHas(trade, 2574) and npcUtil.popFromQM(player, npc, ID.mob.ARMED_GEARS) then -- Trade Ferrite
player:confirmTrade()
end
end
function onTrigger(player, npc)
player:messageSpecial(ID.text.NOTHING_HAPPENS)
end
|
object_tangible_saga_system_rewards_frn_fireplace = object_tangible_saga_system_rewards_shared_frn_fireplace:new {
}
ObjectTemplates:addTemplate(object_tangible_saga_system_rewards_frn_fireplace, "object/tangible/saga_system/rewards/frn_fireplace.iff")
|
local moduleName = "mcunode"
local M = {}
_G[moduleName] = M
local handlers = {}
local files = {}
--plugin
function ls()
local l = file.list()
for k,v in pairs(l) do
print("name:"..k..", size:"..v)
end
end
function cat(filename)
local line
file.open(filename, "r")
while 1 do
line = file.readline()
if line == nil then
break
end
line = string.gsub(line, "\n", "")
print(line)
end
file.close()
end
local function urlDecode(str)
if str == nil then
return nil
end
str = string.gsub(str, '+', ' ')
str = string.gsub(str, '%%(%x%x)', function(h) return string.char(tonumber(h, 16)) end)
return str
end
-- 解析request请求参数
local function parseRequest(data)
--print("data"..data)
local req = {}
local param = nil
req.parameter = {}
req.method = 'GET'
req.protocol = 'http'
-- 解析请求路径及请求参数
_,_,req.path,param = string.find(data,"([^%?]+)%??([^%s]*)") --1 16 gpio pin=1&val=0 path ="gpio?pin=1&val=0"
--print("param"..param)
if param ~= nil then --解析请求参数
--print(param.."not nil")
for key,value in string.gmatch(param,"([^%?%&]+)=([^%?%&]+)") do
--print(key..value)
req.parameter[key] = urlDecode(value) --pin 1 , val 0 param ="gpio?pin=1&val=0"
end
param = nil
end
--print("request path : " .. req.path)
data = nil
req.getParam = function(name) --获取请求参数
if(name == nil) then
return req.parameter
end
return req.parameter[name] --"farry"
end
return req
end
-- tabel to string
local function renderString(subs)
local content = ""
for k,v in pairs(subs) do
content = content.. k .."=" .. v ..","
end
if ( #content == 0 ) then
return nil
end
return string.sub(content,1,#content -1)
end
-- 渲染返回数据
local function render(conn,res)
local body = nil
local attr = res.attribute
html=""
if res.file then
--print("file")
file.open(res.file,"r")
--print("response file : " .. res.file)
while true do
local line = file.readline()
if line == nil then
break
end
if attr then
for k, v in pairs(attr) do
line= string.gsub(line, '{{'..k..'}}', v)
end
end
--html=html..line
conn:send(line)
line=""
end
file.close()
elseif res.body then
--print("body")
body = res.body
if attr then
for k, v in pairs(attr) do
body = string.gsub(body, '{{'..k..'}}', v)
end
end
--print(body)
html=body
conn:send(html)
elseif attr then
--print("attr")
body = renderString(attr)
if body then
html=body
conn:send(html)
end
end
--print("send"..html)
html=nil
res = nil
body = nil
attr = nil
end
local function receive(conn,data)
local s = tmr.now() -- start time
local req = parseRequest(data)
local func = handlers["/"..req.path]
local response = {}
response.attribute = {} --当file或body不为nil时,做变量置换,否则body为attribute解析之后的结果
response.body = nil --响应体
response.file = nil -- 静态文件
response.setAttribute = function(k,v)
if(type(k) == "table") then
for key,val in pairs(k) do
response.attribute[key] = val
end
else
response.attribute[k] = v
end
end
response.getAttribute = function(k)
if(k == nil) then
return response.attribute
end
return response.attribute[k]
end
tmr.wdclr()
if func == nil then -- 没有匹配路径
node.input(data)
function s_output(str)
if (conn~=nil and str~='') then
conn:send(str)
end
end
node.output(s_output,1)
elseif func == "file" then
response.file = req.path
else
response = func(req,response)
end
req = nil
if response then
render(conn,response)
end
response = nil
local e = tmr.now() -- end time
--print("heap:" .. node.heap() .. "bytes, start_time : ".. s .. "us,end_time:".. e .."us,total_time : " .. (e-s) .."us")
collectgarbage("collect")
--node.output(nil)
end
function M.handle(path, func)
handlers[path] = func
end
function M.connect( id , host , ssid , pwd )
conn = net.createConnection(net.TCP, 0)
conn:on("connection", function(sk, c)
sk:send(id)
tmr.alarm(2, 10000, 1, function() sk:send('<h1></h1>') end)
end)
conn:on('receive', receive)
if (ssid~=nil) then
wifi.setmode(wifi.STATION)
wifi.sta.config(ssid,tostring(pwd or "")) --set your ap info !!!!!!
wifi.sta.autoconnect(1)
tmr.alarm(1, 1000, 1, function()
if wifi.sta.getip()==nil then
print("Connect AP, Waiting...")
else
tmr.stop(1)
conn:connect(8001,host)
print("Mcunode Terminal and web proxy is running !\nId is " .. id.." host is "..host)
local l = file.list()
for k,v in pairs (l) do
if not string.find(k,".lc") then
handlers["/"..k] = "file"
end
end
l = nil
for k,v in pairs (handlers) do
print("path:" .. k)
end
--collectgarbage("collect")
--tmr.delay(100000)
print("localhost ip : "..wifi.sta.getip())
end
end)
end
end
return M |
cloud2 = class:new()
function cloud2:init(y)
self.x = math.random()*100
self.y = 120+y
self.i = math.random(2)
self.speed = -500
end
function cloud2:update(dt)
self.y = self.y + self.speed*dt
if self.y < -20 then
self.y = self.y+140
self.x = math.random()*100
self.i = math.random(2)
end
end
function cloud2:draw()
draw(_G["cloud" .. self.i .. "img"], self.x, self.y, 0, 1, 1, 15)
end |
local tokens_key = KEYS[1]
local timestamp_key = KEYS[2]
--redis.log(redis.LOG_WARNING, "tokens_key " .. tokens_key)
local rate = tonumber(ARGV[1])
local capacity = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local requested = tonumber(ARGV[4])
local fill_time = capacity/rate
local ttl = math.floor(fill_time*2)
-- Get the current amount of token. if nil then set to capacity (ARG 2)
local last_tokens = tonumber(redis.call("get", tokens_key))
if last_tokens == nil then
last_tokens = capacity
end
--redis.log(redis.LOG_WARNING, "last_tokens " .. last_tokens)
local last_refreshed = tonumber(redis.call("get", timestamp_key))
if last_refreshed == nil then
last_refreshed = 0
end
--redis.log(redis.LOG_WARNING, "last_refreshed " .. last_refreshed)
local delta = math.max(0, now-last_refreshed)
local filled_tokens = math.min(capacity, last_tokens+(delta*rate))
local allowed = filled_tokens >= requested
local new_tokens = filled_tokens
local allowed_num = 0
if allowed then
new_tokens = filled_tokens - requested
allowed_num = 1
end
--redis.log(redis.LOG_WARNING, "delta " .. delta)
if ttl > 0 then
redis.call("setex", tokens_key, ttl, new_tokens)
redis.call("setex", timestamp_key, ttl, now)
end
-- return { allowed_num, new_tokens, capacity, filled_tokens, requested, new_tokens }
return { allowed_num, new_tokens, ttl } |
--------------------------------------------------------------------------------
-- Class used by the Server entity to control communication between components.
--
-- The communication channel should be configured using the three ports:
-- - com_port: Used to broadcast message to Client entities.
-- - set_port: Used by Clients to send messages to the Server entity.
-- - res_port: Used by the Servery entity to respond to a Client request.
--------------------------------------------------------------------------------
local bus_server = {}
local zmq = require('lzmq')
local json = require('json')
--------------------------------------------------------------------------------
-- Default Configuration
--------------------------------------------------------------------------------
local HOST = '127.0.0.1'
local COM_PORT = 5556
local SET_PORT = 5557 -- clients send to this port
local RES_PORT = 5558 -- clients get on this port
--------------------------------------------------------------------------------
--- Creates a new Bus Server instance.
--
-- @param opt An object that contains the configuration for this Bus Server. If
-- not provided, the default configurations will be set. eg: {id="My
-- Server", host="localhost", com_port=1, set_port=2, res_port=3}
-- @return table The new Bus Server instance.
function bus_server:new(opt)
local self = {}
setmetatable(self, {__index=bus_server})
opt = opt or {}
self.id = opt.id or 'server_id'
self.host = opt.host or HOST
self.com_port = opt.com_port or COM_PORT
self.set_port = opt.set_port or SET_PORT
self.res_port = opt.res_port or RES_PORT
return self
end
--- Prepares this Bus Server to be used.
-- Before sending/receiving messages, the method setup() should be called to
-- properly setup the socket configurations.
--
-- @return table The instance itself.
function bus_server:setup()
self.context = zmq.context()
self.pub_socket, err = self.context:socket(zmq.PUB)
zmq.assert(self.pub_socket, err)
self.pub_socket:bind('tcp://'..self.host..':'..self.com_port)
self.set_socket, err = self.context:socket(zmq.PAIR)
zmq.assert(self.set_socket, err)
self.set_socket:bind('tcp://'..self.host..':'..self.set_port)
return self
end
--- Distribute a message to all Clients.
-- When called, the message will be distributed to all Clientes connected in
-- this communication channel, using the 'com_port'.
--
-- @param msg A table containing the message.
-- eg: {sender="Me", type="hello", data="from server"}
-- @return table The instance itself.
function bus_server:distribute(msg)
if not msg then return end
self.pub_socket:send(msg.sender .. ' ' .. json.encode(msg))
print('distribute:',msg.sender .. ' ' .. json.encode(msg))
return self
end
--- Receives a message from the communication channel.
-- Tryies to get a message from the communication channel, checking the
-- 'set_port' for new messages.
--
-- @param noblocking If true, the method will check if there is a message and
-- then return the message, if it exists, or 'nil' if no message was
-- received. If false, the method will block the interpreter until a new
-- message arrives, which then is returned.
-- @return string The message, if exists, or nil, if no message was received.
function bus_server:getMessage(noblocking)
local msg = self.set_socket:recv(noblocking and zmq.NOBLOCK)
if not msg then return nil end
return json.decode(msg)
end
--- Respond to a Client request.
-- When a Client has requested (ie. sent a message with type='get'), it will be
-- wainting for a response through the 'res_port'. This method uses the
-- 'res_port' to respond to a client request directly.
--
-- @param msg A table containing the message.
-- eg: {sender="Me", type="get", data="user_list"}
-- @return table The instance itself.
function bus_server:sendResponse(msg)
local res_socket, err = self.context:socket(zmq.PAIR)
zmq.assert(res_socket, err)
res_socket:connect('tcp://'..self.host..':'..self.res_port)
res_socket:send(json.encode(msg))
res_socket:close()
return self
end
return bus_server
|
return {
summary = 'Enable or disable the Joint.',
description = 'Enable or disable the Joint.',
arguments = {
{
name = 'enabled',
type = 'boolean',
description = 'Whether the Joint should be enabled.'
}
},
returns = {}
}
|
-- Version Checking down here, better don't touch this
local CurrentVersion = '2.3.1'
local GithubResourceName = 'DeathScreen'
PerformHttpRequest('https://raw.githubusercontent.com/Flatracer/FiveM_Resources/master/' .. GithubResourceName .. '/VERSION', function(Error, NewestVersion, Header)
PerformHttpRequest('https://raw.githubusercontent.com/Flatracer/FiveM_Resources/master/' .. GithubResourceName .. '/CHANGES', function(Error, Changes, Header)
print('\n')
print('##############')
print('## ' .. GithubResourceName)
print('##')
print('## Current Version: ' .. CurrentVersion)
print('## Newest Version: ' .. NewestVersion)
print('##')
if CurrentVersion ~= NewestVersion then
print('## Outdated')
print('## Check the Topic')
print('## For the newest Version!')
print('##############')
print('CHANGES: ' .. Changes)
else
print('## Up to date!')
print('##############')
end
print('\n')
end)
end)
--Update Check
-- Client to Client Communication
RegisterServerEvent(GetCurrentResourceName() .. ':SendDeathMessage')
AddEventHandler(GetCurrentResourceName() .. ':SendDeathMessage', function(Victim, Killer, DeathReasonVictim, DeathReasonOthers, DeathReasonKiller) --Sends the Death Message to every client
TriggerClientEvent(GetCurrentResourceName() .. ':PrintDeathMessage', -1, Victim, Killer, DeathReasonVictim, DeathReasonOthers, DeathReasonKiller)
end)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.