repo_name stringlengths 6 78 | path stringlengths 4 206 | copies stringclasses 281
values | size stringlengths 4 7 | content stringlengths 625 1.05M | license stringclasses 15
values |
|---|---|---|---|---|---|
Victek/wrt1900ac-aa | veriksystems/luci-0.11/applications/luci-pbx-voicemail/luasrc/model/cbi/pbx-voicemail.lua | 29 | 6708 | --[[
Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com>
This file is part of luci-pbx-voicemail.
luci-pbx-voicemail is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
luci-pbx-voicemail is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with luci-pbx-voicemail. If not, see <http://www.gnu.org/licenses/>.
]]--
if nixio.fs.access("/etc/init.d/asterisk") then
server = "asterisk"
elseif nixio.fs.access("/etc/init.d/freeswitch") then
server = "freeswitch"
else
server = ""
end
modulename = "pbx-voicemail"
vmlogfile = "/tmp/last_sent_voicemail.log"
m = Map (modulename, translate("Voicemail Setup"),
translate("Here you can configure a global voicemail for this PBX. Since this system is \
intended to run on embedded systems like routers, there is no local storage of voicemail - \
it must be sent out by email. Therefore you need to configure an outgoing mail (SMTP) server \
(for example your ISP's, Google's, or Yahoo's SMTP server), and provide a list of \
addresses that receive recorded voicemail."))
-- Recreate the config, and restart services after changes are commited to the configuration.
function m.on_after_commit(self)
luci.sys.call("/etc/init.d/pbx-" .. server .. " restart 1\>/dev/null 2\>/dev/null")
luci.sys.call("/etc/init.d/" .. server .. " restart 1\>/dev/null 2\>/dev/null")
end
----------------------------------------------------------------------------------------------------
s = m:section(NamedSection, "global_voicemail", "voicemail", translate("Global Voicemail Setup"),
translate("When you enable voicemail, you will have the opportunity to specify \
email addresses that receive recorded voicemail. You must also set up an SMTP server below."))
s.anonymous = true
enable = s:option(ListValue, "enabled", translate("Enable Voicemail"))
enable:value("yes", translate("Yes"))
enable:value("no", translate("No"))
enable.default = "no"
emails = s:option(DynamicList, "global_email_addresses",
translate("Email Addresses that Receive Voicemail"))
emails:depends("enabled", "yes")
savepath = s:option(Value, "global_save_path", translate("Local Storage Directory"),
translate("You can also retain copies of voicemail messages on the device running \
your PBX. The path specified here will be created if it doesn't exist. \
Beware of limited space on embedded devices like routers, and enable this \
option only if you know what you are doing."))
savepath.optional = true
if nixio.fs.access("/etc/pbx-voicemail/greeting.WAV") then
m1 = s:option(DummyValue, "_m1")
m1:depends("enabled", "yes")
m1.default = "NOTE: Found a voicemail greeting. To check or change your voicemail greeting, dial *789 \
and the system will play your current message. You have 5 seconds to hangup, otherwise a \
new recording will begin and your old message will be overwritten. Hang up or press # to \
stop recording. When you press #, the system will play back the new recording."
else
m1 = s:option(DummyValue, "_m1")
m1:depends("enabled", "yes")
m1.default = "WARNING: Could not find voicemail greeting. Callers will hear only a beep before \
recording starts. To record a greeting, dial *789 and record a greeting after the beep. \
Hang up or press # to stop recording. When # is pressed the system will play back the \
recording."
end
----------------------------------------------------------------------------------------------------
s = m:section(NamedSection, "voicemail_smtp", "voicemail", translate("Outgoing mail (SMTP) Server"),
translate("In order for this PBX to send emails containing voicemail recordings, you need to \
set up an SMTP server here. Your ISP usually provides an SMTP server for that purpose. \
You can also set up a third party SMTP server such as the one provided by Google or Yahoo."))
s.anonymous = true
serv = s:option(Value, "smtp_server", translate("SMTP Server Hostname or IP Address"))
serv.datatype = "host"
port = s:option(Value, "smtp_port", translate("SMTP Port Number"))
port.datatype = "port"
port.default = "25"
tls = s:option(ListValue, "smtp_tls", translate("Secure Connection Using TLS"))
tls:value("on", translate("Yes"))
tls:value("off", translate("No"))
tls.default = "on"
auth = s:option(ListValue, "smtp_auth", translate("SMTP Server Authentication"))
auth:value("on", translate("Yes"))
auth:value("off", translate("No"))
auth.default = "off"
user = s:option(Value, "smtp_user", translate("SMTP User Name"))
user:depends("smtp_auth", "on")
pwd = s:option(Value, "smtp_password", translate("SMTP Password"),
translate("Your real SMTP password is not shown for your protection. It will be changed \
only when you change the value in this box."))
pwd.password = true
pwd:depends("smtp_auth", "on")
-- We skip reading off the saved value and return nothing.
function pwd.cfgvalue(self, section)
return "Password Not Displayed"
end
-- We check the entered value against the saved one, and only write if the entered value is
-- something other than the empty string, and it differes from the saved value.
function pwd.write(self, section, value)
local orig_pwd = m:get(section, self.option)
if value == "Password Not Displayed" then value = "" end
if value and #value > 0 and orig_pwd ~= value then
Value.write(self, section, value)
end
end
----------------------------------------------------------------------------------------------------
s = m:section(NamedSection, "voicemail_log", "voicemail", translate("Last Sent Voicemail Log"))
s.anonymous = true
s:option (DummyValue, "vmlog")
sts = s:option(DummyValue, "_sts")
sts.template = "cbi/tvalue"
sts.rows = 5
function sts.cfgvalue(self, section)
log = nixio.fs.readfile(vmlogfile)
if log == nil or log == "" then
log = "No errors or messages reported."
end
return log
end
return m
| gpl-2.0 |
Xaedblade/Trtl_Mineshaft | Trtl_Mineshaft.lua | 1 | 2833 | x=0; z=0; y=0
direction = 0
-----------------------------------------------------
-- This section is for general movement functions
-- These functions keeps track of the direction
-- and location of the turtle
-----------------------------------------------------
-- updates the direction of the turtle regardless
-- of how many turns by mod 4
function updateDirection(change)
direction = (direction + change)% 4
end
-- updates the coordinates of the turtle after
-- moving based on the direction
function updateCoords(_direction)
if direction == 0 then
x=x+1
elseif direction == 1 then
z=z+1
elseif direction == 2 then
x=x-1
else
z=z-1
end
end
-- updates the turtle's y coordinate by number
-- provided
function updateHeight(change)
y=y+change
end
-----------------------------------------------------
--
--
-----------------------------------------------------
-- This function takes one paramater and will
-- move the turtle forward x blocks and clear
-- blocks in front of it and attack entities
-- in front of it
function forward(times)
for i=1,times do
--turtle.forward() do -- can't move
--forward so make a check for a block
while not true do
print("Blocked")
-- there is not a block must
-- be an entity there for attack
if turtle.detect() then
print("Attacking entity")
turtle.attack()
end
end
updateCoords(direction)
end
end
function turn(direction,times)
for i=1,times do
if direction=="left" then
--turtle.turnLeft()
updateDirection(-1)
else
--turtle.turnRight()
updateDirection(1)
end
end
end
function down(times)
times = times * -1
updateHeight(times)
end
function up(times)
updateHeight(times)
end
function makeShaft()
end
-----------------------------------------------------
-- Tests
-----------------------------------------------------
function test3()
print("Test 3")
print("Starting fr: d="..direction.." | x="..
x.." | z="..z.." | y="..y)
up(2)
print("update height: 2")
print("updating to: d="..direction.." | x="..
x.." | z="..z.." | y="..y)
down(2)
print("update height: -2")
print("updating to: d="..direction.." | x="..
x.." | z="..z.." | y="..y)
down(5)
print("update height: -5")
print("updating to: d="..direction.." | x="..
x.." | z="..z.." | y="..y)
print(" ")
print("Expected Results")
y=0
print("Starting fr: d="..direction.." | x="..
x.." | z="..z.." | y="..y)
updateHeight(2)
print("update height: 2")
print("updating to: d="..direction.." | x="..
x.." | z="..z.." | y="..y)
updateHeight(-2)
print("update height: -2")
print("updating to: d="..direction.." | x="..
x.." | z="..z.." | y="..y)
updateHeight(-5)
print("update height: -5")
print("updating to: d="..direction.." | x="..
x.." | z="..z.." | y="..y)
end
function test2()
end
function test1()
end
test3()
| gpl-3.0 |
jshackley/darkstar | scripts/globals/items/prominence_axe.lua | 42 | 1450 | -----------------------------------------
-- ID: 18220
-- Item: Prominence Axe
-- Additional Effect: Fire Damage
-- Enchantment: Enfire
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 5;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(3,10);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_FIRE, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_FIRE,0);
dmg = adjustForTarget(target,dmg,ELE_FIRE);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_FIRE,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_FIRE_DAMAGE,message,dmg;
end
end;
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
return 0;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
local effect = EFFECT_ENFIRE;
doEnspell(target,target,nil,effect);
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/weaponskills/starburst.lua | 30 | 1304 | -----------------------------------
-- Starburst
-- Staff weapon skill
-- Skill Level: 100
-- Deals light or darkness elemental damage. Damage varies with TP.
-- Aligned with the Shadow Gorget & Aqua Gorget.
-- Aligned with the Shadow Belt & Aqua Belt.
-- Element: Light/Dark (Random)
-- Modifiers: : STR:40% MND:40%
-- 100%TP 200%TP 300%TP
-- 1.00 2.00 2.50
-----------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.ftp100 = 1; params.ftp200 = 2; params.ftp300 = 2.5;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.ele = ELE_DARK; params.ele = ELE_LIGHT
params.skill = SKILL_STF;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.4; params.mnd_wsc = 0.4;
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
LiberatorUSA/GUCEF | tests/gucefCOM_TestApp/premake4.lua | 2 | 1980 | --------------------------------------------------------------------
-- This file was automatically generated by ProjectGenerator
-- which is tooling part the build system designed for GUCEF
-- (Galaxy Unlimited Framework)
-- For the latest info, see http://www.VanvelzenSoftware.com/
--
-- The contents of this file are placed in the public domain. Feel
-- free to make use of it in any way you like.
--------------------------------------------------------------------
--
-- Configuration for module: gucefCOM_TestApp
project( "gucefCOM_TestApp" )
configuration( {} )
location( os.getenv( "PM4OUTPUTDIR" ) )
configuration( {} )
targetdir( os.getenv( "PM4TARGETDIR" ) )
configuration( {} )
language( "C++" )
configuration( { "WIN32" } )
configuration( { WIN32 } )
kind( "WindowedApp" )
configuration( { "NOT WIN32" } )
configuration( {} )
kind( "ConsoleApp" )
configuration( {} )
links( { "gucefCOM", "gucefCOMCORE", "gucefCORE", "gucefMT" } )
links( { "gucefCOM", "gucefCOMCORE", "gucefCORE", "gucefMT" } )
configuration( {} )
vpaths { ["Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"include/TestCode_CHTTPClient.h",
"include/TestCode_CHTTPServer.h"
} )
configuration( {} )
vpaths { ["Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/gucefCOM_TestApp_main.cpp",
"src/TestCode_CHTTPClient.cpp",
"src/TestCode_CHTTPServer.cpp"
} )
configuration( {} )
includedirs( { "../../common/include", "../../gucefCOM/include", "../../gucefCOMCORE/include", "../../gucefCORE/include", "../../gucefMT/include", "include" } )
configuration( { "ANDROID" } )
includedirs( { "../../gucefCORE/include/android" } )
configuration( { "LINUX" } )
includedirs( { "../../gucefCORE/include/linux" } )
configuration( { "WIN32" } )
includedirs( { "../../gucefCOMCORE/include/mswin", "../../gucefCORE/include/mswin" } )
configuration( { "WIN64" } )
includedirs( { "../../gucefCOMCORE/include/mswin", "../../gucefCORE/include/mswin" } )
| apache-2.0 |
jshackley/darkstar | scripts/globals/items/kusamochi.lua | 47 | 2084 | -----------------------------------------
-- ID: 6262
-- Item: kusamochi
-- Food Effect: 30 Min, All Races
-----------------------------------------
-- HP + 20 (Pet & Master)
-- Vitality + 3 (Pet & Master)
-- Attack + 20% Cap: 72 (Pet & Master) Pet Cap: 113
-- Ranged Attack + 20% Cap: 72 (Pet & Master) Pet Cap: 113
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD)) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,6262);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 20)
target:addMod(MOD_VIT, 3)
target:addMod(MOD_FOOD_ATTP, 20)
target:addMod(MOD_FOOD_ATT_CAP, 72)
target:addMod(MOD_FOOD_RATTP, 20)
target:addMod(MOD_FOOD_RATT_CAP, 72)
target:addPetMod(MOD_HP, 20)
target:addPetMod(MOD_VIT, 3)
target:addPetMod(MOD_FOOD_ATTP, 20)
target:addPetMod(MOD_FOOD_ATT_CAP, 113)
target:addPetMod(MOD_FOOD_RATTP, 20)
target:addPetMod(MOD_FOOD_RATT_CAP, 113)
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 20)
target:delMod(MOD_VIT, 3)
target:delMod(MOD_FOOD_ATTP, 20)
target:delMod(MOD_FOOD_ATT_CAP, 72)
target:delMod(MOD_FOOD_RATTP, 20)
target:delMod(MOD_FOOD_RATT_CAP, 72)
target:delPetMod(MOD_HP, 20)
target:delPetMod(MOD_VIT, 3)
target:delPetMod(MOD_FOOD_ATTP, 20)
target:delPetMod(MOD_FOOD_ATT_CAP, 113)
target:delPetMod(MOD_FOOD_RATTP, 20)
target:delPetMod(MOD_FOOD_RATT_CAP, 113)
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/AlTaieu/npcs/qm2.lua | 26 | 1476 | -----------------------------------
-- Area: Al'Taieu
-- NPC: ??? (Jailer of Justice Spawn)
-- Allows players to spawn the Jailer of Justice by trading the Second Virtue, Deed of Moderation, and HQ Xzomit Organ to a ???.
-- @pos , -278 0 -463
-----------------------------------
package.loaded["scripts/zones/AlTaieu/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/AlTaieu/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Trade the Second Virtue, Deed of Moderation, and HQ Xzomit Organ
--[[if (GetMobAction(16912839) == 0 and trade:hasItemQty(1853,1) and trade:hasItemQty(1854,1) and trade:hasItemQty(1785,1) and
trade:getItemCount() == 3) then
player:tradeComplete();
SpawnMob(16912839,900):updateClaim(player); -- Spawn Jailer of Justice
end]]
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("onUpdate CSID: %u",csid);
--printf("onUpdate RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
end; | gpl-3.0 |
DipColor/mehrabon3 | plugins/anti-bot.lua | 369 | 3064 |
local function isBotAllowed (userId, chatId)
local hash = 'anti-bot:allowed:'..chatId..':'..userId
local banned = redis:get(hash)
return banned
end
local function allowBot (userId, chatId)
local hash = 'anti-bot:allowed:'..chatId..':'..userId
redis:set(hash, true)
end
local function disallowBot (userId, chatId)
local hash = 'anti-bot:allowed:'..chatId..':'..userId
redis:del(hash)
end
-- Is anti-bot enabled on chat
local function isAntiBotEnabled (chatId)
local hash = 'anti-bot:enabled:'..chatId
local enabled = redis:get(hash)
return enabled
end
local function enableAntiBot (chatId)
local hash = 'anti-bot:enabled:'..chatId
redis:set(hash, true)
end
local function disableAntiBot (chatId)
local hash = 'anti-bot:enabled:'..chatId
redis:del(hash)
end
local function isABot (user)
-- Flag its a bot 0001000000000000
local binFlagIsBot = 4096
local result = bit32.band(user.flags, binFlagIsBot)
return result == binFlagIsBot
end
local function kickUser(userId, chatId)
local chat = 'chat#id'..chatId
local user = 'user#id'..userId
chat_del_user(chat, user, function (data, success, result)
if success ~= 1 then
print('I can\'t kick '..data.user..' but should be kicked')
end
end, {chat=chat, user=user})
end
local function run (msg, matches)
-- We wont return text if is a service msg
if matches[1] ~= 'chat_add_user' and matches[1] ~= 'chat_add_user_link' then
if msg.to.type ~= 'chat' then
return 'Anti-flood works only on channels'
end
end
local chatId = msg.to.id
if matches[1] == 'enable' then
enableAntiBot(chatId)
return 'Anti-bot enabled on this chat'
end
if matches[1] == 'disable' then
disableAntiBot(chatId)
return 'Anti-bot disabled on this chat'
end
if matches[1] == 'allow' then
local userId = matches[2]
allowBot(userId, chatId)
return 'Bot '..userId..' allowed'
end
if matches[1] == 'disallow' then
local userId = matches[2]
disallowBot(userId, chatId)
return 'Bot '..userId..' disallowed'
end
if matches[1] == 'chat_add_user' or matches[1] == 'chat_add_user_link' then
local user = msg.action.user or msg.from
if isABot(user) then
print('It\'s a bot!')
if isAntiBotEnabled(chatId) then
print('Anti bot is enabled')
local userId = user.id
if not isBotAllowed(userId, chatId) then
kickUser(userId, chatId)
else
print('This bot is allowed')
end
end
end
end
end
return {
description = 'When bot enters group kick it.',
usage = {
'!antibot enable: Enable Anti-bot on current chat',
'!antibot disable: Disable Anti-bot on current chat',
'!antibot allow <botId>: Allow <botId> on this chat',
'!antibot disallow <botId>: Disallow <botId> on this chat'
},
patterns = {
'^!antibot (allow) (%d+)$',
'^!antibot (disallow) (%d+)$',
'^!antibot (enable)$',
'^!antibot (disable)$',
'^!!tgservice (chat_add_user)$',
'^!!tgservice (chat_add_user_link)$'
},
run = run
}
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Al_Zahbi/npcs/Gadalar.lua | 38 | 1028 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Gadalar
-- Type: Fireserpent General
-- @zone: 48
-- @pos -105.979 -7 39.692
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x010a);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Selbina/npcs/Gabwaleid.lua | 17 | 1508 | -----------------------------------
-- Area: Selbina
-- NPC: Gabwaleid
-- Involved in Quest: Riding on the Clouds
-- @pos -17 -7 11 248
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_3") == 4) then
if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_3",0);
player:tradeComplete();
player:addKeyItem(SOMBER_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SOMBER_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0258);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Sea_Serpent_Grotto/npcs/relic.lua | 42 | 1858 | -----------------------------------
-- Area: Sea Serpent Grotto
-- NPC: <this space intentionally left blank>
-- @pos -356 14 -102 176
-----------------------------------
package.loaded["scripts/zones/Sea_Serpent_Grotto/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Sea_Serpent_Grotto/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Working on correct relic, 4 items, Stage 4 item, Shard, Necropsyche, currencypiece
if (player:getVar("RELIC_IN_PROGRESS") == 18311 and trade:getItemCount() == 4 and trade:hasItemQty(18311,1) and
trade:hasItemQty(1579,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1457,1)) then
player:startEvent(11,18312);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 11) then
if (player:getFreeSlotsCount() < 2) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18312);
player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1456);
else
player:tradeComplete();
player:addItem(18312);
player:addItem(1456,30);
player:messageSpecial(ITEM_OBTAINED,18312);
player:messageSpecial(ITEMS_OBTAINED,1456,30);
player:setVar("RELIC_IN_PROGRESS",0);
end
end
end; | gpl-3.0 |
adminmagma/telegood | plugins/yoda.lua | 642 | 1199 | local ltn12 = require "ltn12"
local https = require "ssl.https"
-- Edit data/mashape.lua with your Mashape API key
-- http://docs.mashape.com/api-keys
local mashape = load_from_file('data/mashape.lua', {
api_key = ''
})
local function request(text)
local api = "https://yoda.p.mashape.com/yoda?"
text = string.gsub(text, " ", "+")
local parameters = "sentence="..(text or "")
local url = api..parameters
local api_key = mashape.api_key
if api_key:isempty() then
return 'Configure your Mashape API Key'
end
local headers = {
["X-Mashape-Key"] = api_key,
["Accept"] = "text/plain"
}
local respbody = {}
local body, code = https.request{
url = url,
method = "GET",
headers = headers,
sink = ltn12.sink.table(respbody),
protocol = "tlsv1"
}
if code ~= 200 then return code end
local body = table.concat(respbody)
return body
end
local function run(msg, matches)
return request(matches[1])
end
return {
description = "Listen to Yoda and learn from his words!",
usage = "!yoda You will learn how to speak like me someday.",
patterns = {
"^![y|Y]oda (.*)$"
},
run = run
}
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Northern_San_dOria/npcs/Kuu_Mohzolhi.lua | 37 | 3233 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Kuu Mohzolhi
-- Starts and Finishes Quest: Growing Flowers
-- @zone 231
-- @pos -123 0 80
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
count = trade:getItemCount();
gil = trade:getGil();
itemQuality = 0;
if (trade:getItemCount() == 1 and trade:getGil() == 0) then
if (trade:hasItemQty(958,1)) then -- Marguerite
itemQuality = 2;
elseif (trade:hasItemQty(957,1) or -- Amaryllis
trade:hasItemQty(2554,1) or -- Asphodel
trade:hasItemQty(948,1) or -- Carnation
trade:hasItemQty(1120,1) or -- Casablanca
trade:hasItemQty(1413,1) or -- Cattleya
trade:hasItemQty(636,1) or -- Chamomile
trade:hasItemQty(959,1) or -- Dahlia
trade:hasItemQty(835,1) or -- Flax Flower
trade:hasItemQty(956,1) or -- Lilac
trade:hasItemQty(2507,1) or -- Lycopodium Flower
trade:hasItemQty(1412,1) or -- Olive Flower
trade:hasItemQty(938,1) or -- Papaka Grass
trade:hasItemQty(1411,1) or -- Phalaenopsis
trade:hasItemQty(949,1) or -- Rain Lily
trade:hasItemQty(941,1) or -- Red Rose
trade:hasItemQty(1725,1) or -- Snow Lily
trade:hasItemQty(1410,1) or -- Sweet William
trade:hasItemQty(950,1) or -- Tahrongi Cactus
trade:hasItemQty(2960,1) or -- Water Lily
trade:hasItemQty(951,1)) then -- Wijnruit
itemQuality = 1;
end
end
GrowingFlowers = player:getQuestStatus(SANDORIA,GROWING_FLOWERS);
if (itemQuality == 2) then
if (GrowingFlowers == QUEST_COMPLETED) then
player:startEvent(0x025d, 0, 231, 4);
else
player:startEvent(0x025d, 0, 231, 2);
end
elseif (itemQuality == 1) then
if (GrowingFlowers == QUEST_ACCEPTED) then
player:startEvent(0x025d, 0, 231, 3);
else
player:startEvent(0x025d, 0, 231, 1);
end
else
player:startEvent(0x025d, 0, 231, 0);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x025d, 0, 231, 10);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x025d and option == 1002) then
player:tradeComplete();
player:completeQuest(SANDORIA,GROWING_FLOWERS);
player:addFame(SANDORIA,SAN_FAME*120);
player:moghouseFlag(1);
player:messageSpecial(MOGHOUSE_EXIT);
elseif (csid == 0x025d and option == 1) then
player:tradeComplete();
player:addQuest(SANDORIA,GROWING_FLOWERS);
end
end; | gpl-3.0 |
VincentGong/chess | cocos2d-x/tests/lua-tests/src/CocoStudioTest/CocoStudioTest.lua | 3 | 2976 | require "src/CocoStudioTest/CocoStudioGUITest/CocoStudioGUITest"
require "src/CocoStudioTest/CocoStudioSceneTest/CocoStudioSceneTest"
require "src/CocoStudioTest/CocoStudioArmatureTest/CocoStudioArmatureTest"
local LINE_SPACE = 40
local ITEM_TAG_BASIC = 1000
local cocoStudioTestItemNames =
{
{
itemTitle = "CocoStudioArmatureTest",
testScene = function ()
runArmatureTestScene()
end
},
{
itemTitle = "CocoStudioGUITest",
testScene = function ()
runCocosGUITestScene()
end
},
{
itemTitle = "CocoStudioSceneTest",
testScene = function ()
runCocosSceneTestScene()
end
},
}
local CocoStudioTestScene = class("CocoStudioTestScene")
CocoStudioTestScene.__index = CocoStudioTestScene
function CocoStudioTestScene.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, CocoStudioTestScene)
return target
end
function CocoStudioTestScene:runThisTest()
--armatureSceneIdx = ArmatureTestIndex.TEST_COCOSTUDIO_WITH_SKELETON
--self:addChild(restartArmatureTest())
end
function CocoStudioTestScene.create()
local scene = CocoStudioTestScene.extend(cc.Scene:create())
return scene
end
local CocoStudioTestLayer = class("CocoStudioTestLayer")
CocoStudioTestLayer.__index = CocoStudioTestLayer
function CocoStudioTestLayer.extend(target)
local t = tolua.getpeer(target)
if not t then
t = {}
tolua.setpeer(target, t)
end
setmetatable(t, CocoStudioTestLayer)
return target
end
function CocoStudioTestLayer.onMenuCallback(tag,sender)
local index = sender:getLocalZOrder() - ITEM_TAG_BASIC
cocoStudioTestItemNames[index].testScene()
end
function CocoStudioTestLayer:createMenu()
local winSize = cc.Director:getInstance():getWinSize()
local menu = cc.Menu:create()
menu:setPosition(cc.p(0,0))
cc.MenuItemFont:setFontName("Arial")
cc.MenuItemFont:setFontSize(24)
for i = 1, table.getn(cocoStudioTestItemNames) do
local menuItem = cc.MenuItemFont:create(cocoStudioTestItemNames[i].itemTitle)
menuItem:setPosition(cc.p(winSize.width / 2, winSize.height - (i + 1) * LINE_SPACE))
menuItem:registerScriptTapHandler(CocoStudioTestLayer.onMenuCallback)
menu:addChild(menuItem, ITEM_TAG_BASIC + i)
end
self:addChild(menu)
end
function CocoStudioTestLayer.create()
local layer = CocoStudioTestLayer.extend(cc.Layer:create())
if nil ~= layer then
layer:createMenu()
end
return layer
end
-------------------------------------
--CocoStudio Test
-------------------------------------
function CocoStudioTestMain()
local newScene = CocoStudioTestScene.create()
newScene:addChild(CreateBackMenuItem())
newScene:addChild(CocoStudioTestLayer.create())
newScene:runThisTest()
return newScene
end
| mit |
LiberatorUSA/GUCEF | projects/premake5/targets/GUCEF_exe_gucefVFS_TestApp/premake5.lua | 1 | 4453 | --------------------------------------------------------------------
-- This file was automatically generated by ProjectGenerator
-- which is tooling part the build system designed for GUCEF
-- (Galaxy Unlimited Framework)
-- For the latest info, see http://www.VanvelzenSoftware.com/
--
-- The contents of this file are placed in the public domain. Feel
-- free to make use of it in any way you like.
--------------------------------------------------------------------
--
workspace( "GUCEF_exe_gucefVFS_TestApp" )
platforms( { "ALL", "LINUX32", "LINUX64", "WIN32", "WIN64" } )
location( "projects\premake5\targets" )
--
-- Includes for all modules in the solution:
--
filter "ALL"
include( "dependencies/DVPACKSYS" )
include( "dependencies/aws-c-common" )
include( "dependencies/aws-c-event-stream" )
include( "dependencies/aws-checksums" )
include( "dependencies/aws-cpp-sdk-core" )
include( "dependencies/aws-cpp-sdk-s3" )
include( "dependencies/curl" )
include( "dependencies/zziplib" )
include( "platform/gucefCORE" )
include( "platform/gucefMT" )
include( "platform/gucefVFS" )
include( "plugins/SHARED/pluginglueAWSSDK" )
include( "plugins/VFS/vfspluginAWSS3" )
include( "plugins/VFS/vfspluginDVP" )
include( "plugins/VFS/vfspluginITV" )
include( "plugins/VFS/vfspluginVP" )
include( "plugins/VFS/vfspluginZIP" )
include( "tests/gucefVFS_TestApp" )
filter "LINUX32"
include( "dependencies/DVPACKSYS" )
include( "dependencies/aws-c-common" )
include( "dependencies/aws-c-event-stream" )
include( "dependencies/aws-checksums" )
include( "dependencies/aws-cpp-sdk-core" )
include( "dependencies/aws-cpp-sdk-s3" )
include( "dependencies/curl" )
include( "dependencies/zlib" )
include( "dependencies/zziplib" )
include( "platform/gucefCORE" )
include( "platform/gucefMT" )
include( "platform/gucefVFS" )
include( "plugins/SHARED/pluginglueAWSSDK" )
include( "plugins/VFS/vfspluginAWSS3" )
include( "plugins/VFS/vfspluginDVP" )
include( "plugins/VFS/vfspluginITV" )
include( "plugins/VFS/vfspluginVP" )
include( "plugins/VFS/vfspluginZIP" )
include( "tests/gucefVFS_TestApp" )
filter "LINUX64"
include( "dependencies/DVPACKSYS" )
include( "dependencies/aws-c-common" )
include( "dependencies/aws-c-event-stream" )
include( "dependencies/aws-checksums" )
include( "dependencies/aws-cpp-sdk-core" )
include( "dependencies/aws-cpp-sdk-s3" )
include( "dependencies/curl" )
include( "dependencies/zlib" )
include( "dependencies/zziplib" )
include( "platform/gucefCORE" )
include( "platform/gucefMT" )
include( "platform/gucefVFS" )
include( "plugins/SHARED/pluginglueAWSSDK" )
include( "plugins/VFS/vfspluginAWSS3" )
include( "plugins/VFS/vfspluginDVP" )
include( "plugins/VFS/vfspluginITV" )
include( "plugins/VFS/vfspluginVP" )
include( "plugins/VFS/vfspluginZIP" )
include( "tests/gucefVFS_TestApp" )
filter "WIN32"
include( "dependencies/DVPACKSYS" )
include( "dependencies/aws-c-common" )
include( "dependencies/aws-c-event-stream" )
include( "dependencies/aws-checksums" )
include( "dependencies/aws-cpp-sdk-core" )
include( "dependencies/aws-cpp-sdk-s3" )
include( "dependencies/curl" )
include( "dependencies/zlib" )
include( "dependencies/zziplib" )
include( "platform/gucefCORE" )
include( "platform/gucefMT" )
include( "platform/gucefVFS" )
include( "plugins/SHARED/pluginglueAWSSDK" )
include( "plugins/VFS/vfspluginAWSS3" )
include( "plugins/VFS/vfspluginDVP" )
include( "plugins/VFS/vfspluginITV" )
include( "plugins/VFS/vfspluginVP" )
include( "plugins/VFS/vfspluginZIP" )
include( "tests/gucefVFS_TestApp" )
filter "WIN64"
include( "dependencies/DVPACKSYS" )
include( "dependencies/aws-c-common" )
include( "dependencies/aws-c-event-stream" )
include( "dependencies/aws-checksums" )
include( "dependencies/aws-cpp-sdk-core" )
include( "dependencies/aws-cpp-sdk-s3" )
include( "dependencies/curl" )
include( "dependencies/zlib" )
include( "dependencies/zziplib" )
include( "platform/gucefCORE" )
include( "platform/gucefMT" )
include( "platform/gucefVFS" )
include( "plugins/SHARED/pluginglueAWSSDK" )
include( "plugins/VFS/vfspluginAWSS3" )
include( "plugins/VFS/vfspluginDVP" )
include( "plugins/VFS/vfspluginITV" )
include( "plugins/VFS/vfspluginVP" )
include( "plugins/VFS/vfspluginZIP" )
include( "tests/gucefVFS_TestApp" )
| apache-2.0 |
vasilish/torch-draw | models/draw.lua | 1 | 20857 | require('nn')
require('nngraph')
require('dpnn')
local lstm_factory = require('../modules/lstm')
local model_utils = require('models/model_utils')
require('../modules/FilterGrid')
require('../modules/MeanGrid')
require('../modules/GaussianSampler')
require('../modules/Num2Tensor')
require('../modules/ExpandAsTensor')
local M = {}
local Draw = torch.class('Draw', M)
function Draw:__init(options)
self.options = options
self.use_attention = options.use_attention == 'true'
self:create_model(options)
self:initConstTensors(options)
self.model_folder = options.model_folder
self.T = options.num_glimpses
-- Unroll the model in time
if options.verbose then
print('=====> Cloning Network...')
end
local clones = model_utils.clone_model(self.draw, self.T)
if options.verbose then
print('=====> Finished cloning Network...')
end
self.unrolled_model = clones
-- Add the learned bias to the model
self.unrolled_model[1], self.learnedParams =
model_utils.addLearnedBias(options, self.unrolled_model[1], 'training')
-- Restore the model from stored files
if options.restore then
self:load_model(options)
end
self.sharedContainer = model_utils.create_shared_container(self.unrolled_model)
self.sharedContainer = model_utils.convert_model(options, self.sharedContainer)
self.encoder = model_utils.convert_model(options, self.encoder)
self.decoder = model_utils.convert_model(options, self.decoder)
nngraph.setDebug(options.debug == 'true')
end
function Draw:getParameters()
-- Get the flattened parameter tensors.
local params, gradParams = self.sharedContainer:getParameters()
-- Get the parameters of the full model
local model_params, _ = self.sharedContainer:parameters()
local enc_params, _ = self.encoder:parameters()
local dec_params, _ = self.decoder:parameters()
local learnedBias_params, _ = self.learnedParams:parameters()
for i = 1, #learnedBias_params do
learnedBias_params[i]:set(model_params[i])
end
local encoder_offset = #learnedBias_params
for i = 1, #enc_params do
enc_params[i]:set(model_params[i + encoder_offset])
end
-- The offset for the decoder parameter tensors
-- The number 4 is the number of tensors used for the
-- parameters of the linear layers that calculate the mean
-- and the variance for the latent variable sampling.
local dec_offset = #learnedBias_params + #enc_params + 4
for i = 1, #dec_params do
dec_params[i]:set(model_params[i + dec_offset])
end
return params, gradParams
end
function Draw:initConstTensors(options)
keys = {'canvas', 'h_enc', 'c_enc', 'h_dec', 'c_dec'}
-- The initial states of the recurrent networks
local startTensors = {}
local img_size = options.img_size
local batch_size = options.batch_size
local hidden_size = options.hidden_size
local use_cuda = options.backend == 'cuda' or options.backend == 'cudnn'
startTensors[keys[1]] = torch.Tensor(batch_size, table.unpack(img_size:totable()))
for i = 2, #keys do
startTensors[keys[i]] = torch.Tensor(batch_size, hidden_size):zero()
end
if use_cuda then
for key, val in pairs(startTensors) do
startTensors[key] = startTensors[key]:cuda()
end
end
self.startTensors = startTensors
local gradKeys = {'h_enc', 'c_enc', 'h_dec', 'c_dec'}
local gradTensors = {}
for i = 1, #gradKeys do
gradTensors[i] = torch.Tensor(batch_size, hidden_size):zero()
end
-- Will be passed to the attention paramters in the backward pass.
gradTensors[#gradTensors + 1] = torch.Tensor(batch_size, 4):zero()
gradTensors[#gradKeys + 2] = torch.Tensor():resizeAs(gradTensors[#gradKeys + 1])
gradTensors[#gradKeys + 2]:copy(gradTensors[#gradKeys + 1])
if use_cuda then
for i = 1, #gradTensors do
gradTensors[i] = gradTensors[i]:cuda()
end
end
gradTensors[#gradTensors - 1] = torch.split(gradTensors[#gradTensors - 1], 1, 2)
gradTensors[#gradTensors] = torch.split(gradTensors[#gradTensors], 1, 2)
self.gradTensors = gradTensors
return
end
function Draw:forward(batch)
local canvas = {[0] = self.startTensors['canvas']}
local h_enc = {[0] = self.startTensors['h_enc']}
local c_enc = {[0] = self.startTensors['c_enc']}
local h_dec = {[0] = self.startTensors['h_dec']}
local c_dec = {[0] = self.startTensors['c_dec']}
local read_att_params, write_att_params
if self.use_attention then
read_att_params = {}
write_att_params = {}
end
local mu = {}
local logvar = {}
for t = 1, self.T do
local inputs = {batch, canvas[t - 1], h_enc[t - 1], c_enc[t - 1],
h_dec[t - 1], c_dec[t - 1]}
if self.use_attention then
canvas[t], h_enc[t], c_enc[t], h_dec[t], c_dec[t], mu[t], logvar[t],
read_att_params[t], write_att_params[t] =
table.unpack(self.unrolled_model[t]:forward(inputs))
else
canvas[t], h_enc[t], c_enc[t], h_dec[t], c_dec[t], mu[t], logvar[t] =
table.unpack(self.unrolled_model[t]:forward(inputs))
end
end
return {canvas, h_enc, c_enc, h_dec, c_dec, mu, logvar}, read_att_params, write_att_params
end
function Draw:backward(batch, gradLossX, output)
canvas, h_enc, c_enc, h_dec, c_dec, mu, logvar = table.unpack(output)
local numBatchElements = batch:nElement()
local gradLossZ = {}
local dh_enc = {[self.T] = self.gradTensors[1]}
local dc_enc = {[self.T] = self.gradTensors[2]}
local dh_dec = {[self.T] = self.gradTensors[3]}
local dc_dec = {[self.T] = self.gradTensors[4]}
local gradCanvas = {[self.T] = gradLossX}
local gradMu = {[self.T] = mu[self.T] / numBatchElements}
local gradVar = {[self.T] = 0.5 * (torch.exp(logvar[self.T]) - 1) / numBatchElements}
for t = self.T, 1, -1 do
local inputs = {batch, canvas[t - 1], h_dec[t - 1], c_dec[t - 1],
h_dec[t - 1], c_dec[t - 1]}
local gradOutput = {gradCanvas[t], dh_enc[t], dc_enc[t], dh_dec[t], dc_dec[t],
gradMu[t], gradVar[t]}
if self.use_attention then
gradOutput[#gradOutput + 1] = self.gradTensors[5]
gradOutput[#gradOutput + 1] = self.gradTensors[6]
end
_, gradCanvas[t - 1], dh_enc[t - 1], dc_enc[t - 1], dh_dec[t - 1], dc_dec[t - 1] =
table.unpack(self.unrolled_model[t]:backward(inputs, gradOutput))
if t > 1 then
gradMu[t - 1] = mu[t - 1] / numBatchElements
gradVar[t - 1] = 0.5 * (torch.exp(logvar[t - 1]) - 1) / numBatchElements
end
end
end
function Draw:load_model(options)
local model_folder = paths.concat(self.model_folder, self.use_attention
and 'attention' or 'no_attention')
local draw_path = paths.concat(model_folder, 'draw_t0.t7')
print('===> Loading DRAW model from file...')
local stored_model = torch.load(draw_path)
local storedParams, _ = stored_model:parameters()
local modelParams, _ = self.unrolled_model[1]:parameters()
for i = 1, #storedParams do
modelParams[i]:copy(storedParams[i])
end
print('===> Finished loading the model...')
return
end
function Draw:save_model(options)
local params, _ = self.unrolled_model[1]:parameters()
local model_folder = paths.concat(options.model_folder, self.use_attention
and 'attention' or 'no_attention')
if not paths.dirp(model_folder) and not paths.mkdir(model_folder) then
cmd:error('Error: Unable to create model directory: ' .. model_folder '\n')
end
print('====> Saving DRAW model')
local draw_path = paths.concat(model_folder, 'draw_t0.t7')
torch.save(draw_path, self.unrolled_model[1])
local learnedInitStates, _ = self.learnedParams:parameters()
print('====> Saving the initial canvas...')
local canvas0Path = paths.concat(model_folder, 'canvas0.t7')
torch.save(canvas0Path, learnedInitStates[1])
print('====> Saving the initial decoder state...')
local hDec0 = paths.concat(model_folder, 'hDec0.t7')
torch.save(hDec0, learnedInitStates[3])
print('====> Saving decoder...')
local decoder_path = paths.concat(model_folder, 'decoder.t7')
torch.save(decoder_path, self.decoder)
end
function Draw:create_model(options)
-- Constant initialization
local read_size = options.read_size
local write_size = options.write_size
local hidden_size = options.hidden_size
local latent_size = options.latent_size
-- The size of each image
local img_size = options.img_size
-- The number of elements in each image
local input_size = options.input_size
local height = img_size[#img_size - 1]
local width = img_size[#img_size]
-- ####### The model #######
-- The input image
local x = nn.Identity()()
local canvas = nn.Identity()()
local h_enc = nn.Identity()()
local c_enc = nn.Identity()()
local h_dec = nn.Identity()()
local c_dec = nn.Identity()()
local encoder = self:create_encoder(options)
local encoder_out = encoder({x, canvas, h_enc, c_enc, h_dec})
local next_h_enc = nn.SelectTable(1)(encoder_out)
local next_c_enc = nn.SelectTable(2)(encoder_out)
local read_att_params
if self.use_attention then
read_att_params = nn.SelectTable(3)(encoder_out)
end
local sample = self:Sampler(hidden_size, latent_size)(next_h_enc):annotate{
name = 'Sampler'}
local z = nn.SelectTable(1)(sample)
local mu_z = nn.SelectTable(2)(sample)
local log_sigma_z = nn.SelectTable(3)(sample)
-- Decoder
-- Forward the information through the decoder
local decoder = self:create_decoder(options)
local decoder_out = decoder({z, canvas, h_dec, c_dec})
local new_canvas = nn.SelectTable(1)(decoder_out)
local next_h_dec = nn.SelectTable(2)(decoder_out)
local next_c_dec = nn.SelectTable(3)(decoder_out)
local write_att_params
if self.use_attention then
write_att_params = nn.SelectTable(4)(decoder_out)
end
local draw_inputs = {x, canvas, h_enc, c_enc, h_dec, c_dec}
local draw_outputs = {new_canvas, next_h_enc, next_c_enc, next_h_dec, next_c_dec,
mu_z, log_sigma_z}
if self.use_attention then
draw_outputs[#draw_outputs + 1] = read_att_params
draw_outputs[#draw_outputs + 1] = write_att_params
end
local draw = nn.gModule(draw_inputs, draw_outputs)
self.draw = draw
self.encoder = encoder
self.decoder = decoder
return
end
function Draw:create_encoder(options)
-- Constant initialization
local read_size = options.read_size
local hidden_size = options.hidden_size
-- The size of each image
local img_size = options.img_size
local height = img_size[#img_size - 1]
local width = img_size[#img_size]
local enc_input_size = hidden_size
if self.use_attention then
enc_input_size = enc_input_size + 2 * read_size * read_size
else
enc_input_size = enc_input_size + 2 * height * width
end
local encoder_rnn = lstm_factory.create_lstm(options, enc_input_size, hidden_size)
-- Encoder Graph Module Construction
local x = nn.Identity()()
local canvas = nn.Identity()()
local h_enc = nn.Identity()()
local c_enc = nn.Identity()()
local h_dec = nn.Identity()()
local encoder_inputs = {x, canvas, h_enc, c_enc, h_dec}
local xHat = self:ErrorImage()({x, canvas}):annotate{name = 'Error Image'}
local read, read_node
local read_node = self:read(options, img_size, read_size)
if self.use_attention then
read = read_node({x, xHat, h_dec})
else
read = read_node({x, xHat})
end
read:annotate{name = 'Read'}
-- Read Head finished
-- Forward the information through the encoder
local enc_input
if self.use_attention then
enc_input = nn.JoinTable(1, 1)
(
{
nn.View(-1, read_size ^ 2)(nn.SelectTable(1)(read)),
nn.View(-1, read_size ^ 2)(nn.SelectTable(2)(read)),
nn.View(-1, hidden_size)(h_dec)
}
)
else
enc_input = nn.JoinTable(1, 1)
(
{
nn.View(-1, height * width)(nn.SelectTable(1)(read)),
nn.View(-1, height * width)(nn.SelectTable(2)(read)),
nn.View(-1, hidden_size)(h_dec)
}
)
end
local next_state = encoder_rnn({enc_input, h_enc, c_enc})
local next_h_enc = nn.SelectTable(1)(next_state)
local next_c_enc = nn.SelectTable(2)(next_state)
local encoder_outputs = {next_h_enc, next_c_enc}
local att_params
if self.use_attention then
att_params = nn.NarrowTable(3, 4)(read)
encoder_outputs[#encoder_outputs + 1] = att_params
end
return nn.gModule(encoder_inputs, encoder_outputs)
end
function Draw:create_decoder(options)
-- Constant initialization
local write_size = options.write_size
local hidden_size = options.hidden_size
local latent_size = options.latent_size
-- The size of each image
local img_size = options.img_size
-- The number of elements in each image
local input_size = options.input_size
local height = img_size[#img_size - 1]
local width = img_size[#img_size]
local decoder_rnn = lstm_factory.create_lstm(options, latent_size, hidden_size)
-- Decoder Graph Module Construction
-- The latent variable
local z = nn.Identity()()
local canvas = nn.Identity()()
-- The previous hidden and cell state of the decoder rnn
local h_dec = nn.Identity()()
local c_dec = nn.Identity()()
local decoder_input = {z, canvas, h_dec, c_dec}
-- Calculate the next step of the decoder
local next_dec_state = decoder_rnn({z, h_dec, c_dec}):annotate{name = 'Decoder'}
next_h_dec = nn.SelectTable(1)(next_dec_state)
next_c_dec = nn.SelectTable(2)(next_dec_state)
-- Find the write patch
local write = self:write(options, img_size, write_size)(next_h_dec):annotate{
name = 'Write'}
-- Write/Add the result to the canvas
local wt
if self.use_attention then
wt = nn.SelectTable(1)(write)
else
wt = write
end
wt:annotate{name = 'Write value at time t'}
local new_canvas = nn.CAddTable()
(
{
canvas,
wt
}
)
local att_params
local decoder_output = {new_canvas, next_h_dec, next_c_dec}
if self.use_attention then
att_params = nn.NarrowTable(2, 4)(write)
decoder_output[#decoder_output + 1] = att_params
end
return nn.gModule(decoder_input, decoder_output)
end
function Draw:Sampler(hidden_size, latent_size)
local h_enc = nn.Identity()()
-- Sample from the distribution
local mu_z = nn.Linear(hidden_size, latent_size)(h_enc)
local log_sigma_z = nn.Linear(hidden_size, latent_size)(h_enc)
local sigma_z = nn.MulConstant(0.5)(log_sigma_z)
- nn.Exp()
local e = nn.GaussianSampler(0, 1)(sigma_z)
local e_sigma = nn.CMulTable()({e, sigma_z})
-- Apply the reparameterization trick to sample from the latent distribution
local z = nn.CAddTable()({mu_z, e_sigma})
return nn.gModule({h_enc}, {z, mu_z, log_sigma_z})
end
function Draw:ErrorImage()
local x = nn.Identity()()
local prev_canvas = nn.Identity()()
local output = nn.CSubTable()({x, nn.Sigmoid()(prev_canvas)})
return nn.gModule({x, prev_canvas}, {output})
end
function Draw:read(options, img_size, N)
local x = nn.Identity()()
local xHat = nn.Identity()()
local h_dec_prev = nn.Identity()()
local height = img_size[#img_size - 1]
local width = img_size[#img_size]
local read_input
local read_output
if self.use_attention then
read_input = {x, xHat, h_dec_prev}
local width_indices = nn.Constant(torch.range(1, width))(x)
local height_indices = nn.Constant(torch.range(1, height))(x)
local read_att_params = self:attention_parameters(options, width, height, N)(h_dec_prev)
local gx = nn.SelectTable(1)(read_att_params)
local gy = nn.SelectTable(2)(read_att_params)
local var = nn.SelectTable(3)(read_att_params)
local delta = nn.SelectTable(4)(read_att_params)
local gamma = nn.SelectTable(5)(read_att_params)
local fx = self:create_filterbank(options, width, N)({gx, delta, var, width_indices})
local fy = self:create_filterbank(options, height, N)({gy, delta, var, height_indices})
local gamma_mat = nn.Replicate(N * N, 1, 1)(gamma)
- nn.Copy(nil, nil, true)
- nn.View(-1, N, N)
local read_patch_y = nn.MM(false, false)({fy, x})
local read_patch_xy = nn.MM(false, true)({read_patch_y, fx})
local x_patch = nn.CMulTable()({read_patch_xy, gamma_mat})
local error_patch_y = nn.MM(false, false)({fy, xHat})
local error_patch_xy = nn.MM(false, true)({error_patch_y, fx})
local error_patch = nn.CMulTable()({error_patch_xy, gamma_mat})
read_output = {x_patch, error_patch, gx, gy, var, delta}
else
read_input = {x, xHat}
read_output = {nn.Identity()(x), nn.Identity()(xHat)}
end
return nn.gModule(read_input, read_output)
end
function Draw:write(options, img_size, N)
local h_dec = nn.Identity()()
local height = img_size[#img_size - 1]
local width = img_size[#img_size]
local write_input = {h_dec}
local write_output
if self.use_attention then
local width_indices = nn.Constant(torch.range(1, width))(h_dec)
local height_indices = nn.Constant(torch.range(1, height))(h_dec)
local write_att_params = self:attention_parameters(options, width, height, N)(h_dec)
local gx = nn.SelectTable(1)(write_att_params)
local gy = nn.SelectTable(2)(write_att_params)
local var = nn.SelectTable(3)(write_att_params)
local delta = nn.SelectTable(4)(write_att_params)
local gamma = nn.SelectTable(5)(write_att_params)
local fx = self:create_filterbank(options, width, N)({gx, delta, var, width_indices})
local fy = self:create_filterbank(options, height, N)({gy, delta, var, height_indices})
local gamma_mat = nn.Replicate(width * height, 1, 1)(gamma)
- nn.Copy(nil, nil, true)
- nn.View(-1, height, width)
local wt = nn.Linear(options.hidden_size, N * N)(h_dec)
- nn.View(-1, N, N)
local write_patch_y = nn.MM(true, false)({fy, wt})
local write_patch_xy = nn.MM(false, false)({write_patch_y, fx})
local write_result = nn.CDivTable()({write_patch_xy, gamma_mat})
write_output = {write_result, gx, gy, var, delta}
else
local wt = nn.Linear(options.hidden_size, height * width)(h_dec)
- nn.View(-1, height, width)
write_output = {wt}
end
return nn.gModule(write_input, write_output)
end
function Draw:attention_parameters(options, width, height, N)
local h_dec = nn.Identity()()
local hidden_size = options.hidden_size
local gx_bar = nn.Linear(hidden_size, 1)(h_dec)
local gy_bar = nn.Linear(hidden_size, 1)(h_dec)
local log_var = nn.Linear(hidden_size, 1)(h_dec)
local log_delta = nn.Linear(hidden_size, 1)(h_dec)
local log_gamma = nn.Linear(hidden_size, 1)(h_dec)
local gx = nn.AddConstant(1)(gx_bar)
- nn.MulConstant((width + 1) / 2)
local gy = nn.AddConstant(1)(gy_bar)
- nn.MulConstant((height + 1) / 2)
local delta = nn.Exp()(log_delta)
- nn.MulConstant((math.max(height, width) - 1) / (N - 1))
local var = nn.Exp()(log_var)
local gamma = nn.Exp()(log_gamma)
return nn.gModule({h_dec}, {gx, gy, var, delta, gamma})
end
function Draw:create_filterbank(options, dim_size, N)
local batch_size = options.batch_size
-- The inputs to the filter bank function
local g = nn.Identity()()
local var = nn.Identity()()
local delta = nn.Identity()()
local idx = nn.Identity()()
local function mean_row(i, dim_size, N)
-- Calculates the mean for the current row
-- and replicates the value dim_size times
local g = nn.Identity()()
local delta = nn.Identity()()
local mu = nn.CAddTable()(
{
g,
nn.MulConstant(i - N / 2 - 0.5)(delta)
}
)
- nn.Replicate(dim_size, 1, 1)
- nn.Copy(nil, nil, true)
- nn.View(dim_size)
local mean = nn.gModule({g, delta}, {mu})
return mean
end
local function filter_row(i, dim_size, N, batch_size)
-- The current grid center coordinate
local g = nn.Identity()()
-- The variance of the attention filter
local var = nn.Identity()()
-- The size of the attention window
local delta = nn.Identity()()
-- An extra parameters used to pass a constant Tensor of
-- indices in order to perform the calculations
local idx = nn.Identity()()
-- Calculates the numerator of the exponent
local num = nn.CSubTable()
(
{
nn.Replicate(batch_size, 1, 2)(idx),
-- Create the array holding the mean for the current row
mean_row(i, dim_size, N)({g, delta})
}
)
-- Calculate the exponent of the filter
local exponent = nn.CDivTable()
(
{
nn.Power(2)(num) - nn.MulConstant(-1),
nn.Replicate(dim_size, 1, 1)(var) - nn.MulConstant(2)
}
)
local filter = nn.Exp()(exponent)
- nn.Normalize(1)
- nn.Unsqueeze(1, 1)
return nn.gModule({g, delta, var, idx}, {filter})
end
local filters = {}
for i = 1, N do
filters[i] = filter_row(i, dim_size, N, batch_size)({g, delta, var, idx})
end
local filter_mat = nn.JoinTable(1, 2)(filters)
return nn.gModule({g, delta, var, idx}, {filter_mat})
end
return M.Draw
| mit |
jshackley/darkstar | scripts/zones/Bastok_Mines/npcs/Goraow.lua | 34 | 2470 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Goraow
-- Starts Quests: Vengeful Wrath
-- @pos 38 .1 14 234
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local Vengeful = player:getQuestStatus(BASTOK, VENGEFUL_WRATH);
if (Vengeful ~= QUEST_AVAILABLE) then
QuadavHelm = trade:hasItemQty(501,1);
if (QuadavHelm == true and trade:getItemCount() == 1) then
player:startEvent(0x006b);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local Vengeful = player:getQuestStatus(BASTOK,VENGEFUL_WRATH);
local Fame = player:getFameLevel(BASTOK);
local WildcatBastok = player:getVar("WildcatBastok");
if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,16) == false) then
player:startEvent(0x01fa);
elseif (Vengeful == QUEST_AVAILABLE and Fame >= 3) then
player:startEvent(0x006a);
else
player:startEvent(0x0069);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x006a) then
player:addQuest(BASTOK, VENGEFUL_WRATH);
elseif (csid == 0x006b) then
Vengeful = player:getQuestStatus(BASTOK, VENGEFUL_WRATH);
if (Vengeful == QUEST_ACCEPTED) then
player:addTitle(95);
player:addFame(BASTOK,BAS_FAME*120);
else
player:addFame(BASTOK,BAS_FAME*8);
end
player:tradeComplete();
player:addGil(GIL_RATE*900);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*900);
player:completeQuest(BASTOK, VENGEFUL_WRATH); -- for save fame
elseif (csid == 0x01fa) then
player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",16,true);
end
end;
| gpl-3.0 |
bigdogmat/gmod_whitelist | lua/whitelist/sv_init.lua | 1 | 4070 | -- Base server-side file
-- Global server-side table
Whitelist = Whitelist or {
lookup = {},
count = 0,
kickreason = "You're not whitelisted!",
ranks = {["admin"] = true, ["superadmin"] = true},
}
-- Include all server-side a/////////////////ssets and
-- add client assets to download list
include "sv_manifest.lua"
-- Now lets create all of our global helper functions
-- Save
-- Args: !
-- Description: Saves whitelist in JSON format
-- Notes: Auto runs on shutdown or map change
function Whitelist.Save()
file.Write("bigdogmat_whitelist/whitelist.txt", util.TableToJSON(Whitelist))
end
hook.Add("ShutDown", "bigdogmat_whitelist_save", Whitelist.Save)
-- Reload
-- Args: !
-- Description: Loads the whitelist
-- Notes: Auto loads on Initialize
function Whitelist.Reload()
if not file.Exists("bigdogmat_whitelist", "DATA") then
file.CreateDir "bigdogmat_whitelist"
Whitelist.Save()
elseif file.Exists("bigdogmat_whitelist/whitelist.txt", "DATA") then
local json = file.Read("bigdogmat_whitelist/whitelist.txt", "DATA")
-- "json" can't be nil here as for the file.Exist check
-- so we just need to check if it's empty
if json ~= '' then
local jsontable = util.JSONToTable(json)
if jsontable then
for k, v in pairs(jsontable) do
Whitelist[k] = v
end
else
MsgN "Whitelist: Malformed whitelist file!"
MsgN "Whitelist: Send file to addon creator if you want a chance to back it up. It's located in data/bigdogmat_whitelist"
MsgN "Whitelist: Be sure to save backup of file before changing the whitelist as once changed it will overwrite bad file"
end
end
end
MsgN "Whitelist loaded!"
MsgN("Whitelist: ", Whitelist.count, " player(s) whitelisted")
end
hook.Add("Initialize", "bigdogmat_whitelist_load", Whitelist.Reload)
-- Add
-- Args: SteamID:string
-- Description: Adds a SteamID to the whitelist
-- Notes: !
function Whitelist.Add(SteamID)
if SteamID == '' then return end
if Whitelist.lookup[SteamID] then return end
Whitelist.lookup[SteamID] = true
Whitelist.count = Whitelist.count + 1
end
-- Remove
-- Args: SteamID:string
-- Description: Removes a SteamID from the whitelist
-- Notes: !
function Whitelist.Remove(SteamID)
if SteamID == '' then return end
if not Whitelist.lookup[SteamID] then return end
Whitelist.lookup[SteamID] = nil
Whitelist.count = Whitelist.count - 1
end
-- Menu
-- Args: Player:entity
-- Description: Send whitelist data to client and
-- opens whitelist menu
-- Notes: I'll probably change the way this function
-- sends data
util.AddNetworkString "bigdogmat_whitelist_open"
function Whitelist.Menu(caller)
net.Start "bigdogmat_whitelist_open"
net.WriteString(Whitelist.kickreason)
local list = ''
if Whitelist.count > 0 then
for id in pairs(Whitelist.lookup) do
list = list .. id
end
list = util.Compress(list)
end
net.WriteUInt(#list, 16)
net.WriteData(list, #list)
net.Send(caller)
end
-- RankList
-- Args: !
-- Description: Returns a formatted string of all
-- usergroups allowed to make whitelist changes
-- Notes: !
function Whitelist.RankList()
local str = ''
for k, _ in pairs(Whitelist.ranks) do
str = str .. k .. ", "
end
return str:sub(1, -3)
end
-- Allowed
-- Args: Player:entity
-- Description: Returns true if player is allowed to
-- make changes to the whitelist, false if not
-- Notes: Returns true for console
function Whitelist.Allowed(ply)
if game.SinglePlayer() then return true end
if not IsValid(ply) then return true end
return Whitelist.ranks[ply:GetUserGroup()] == true
end
-- Now here is the actual hook that checks to see if
-- a connecting player is on the whitelist
hook.Add("CheckPassword", "bigdogmat_whitelist_kick", function(steamID)
if not (Whitelist.lookup[util.SteamIDFrom64(steamID)] or game.SinglePlayer()) and Whitelist.count > 0 then
return false, Whitelist.kickreason
end
end)
-- And with that I believe we're done here :D
| apache-2.0 |
jshackley/darkstar | scripts/zones/The_Eldieme_Necropolis/npcs/_5fn.lua | 34 | 2569 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: North Plate
-- @pos 180 -34 71 195
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local state0 = 8;
local state1 = 9;
local DoorOffset = npc:getID() - 22; -- _5f1
if (npc:getAnimation() == 8) then
state0 = 9;
state1 = 8;
end
-- Gates
-- Shiva's Gate
GetNPCByID(DoorOffset):setAnimation(state0);
GetNPCByID(DoorOffset+1):setAnimation(state0);
GetNPCByID(DoorOffset+2):setAnimation(state0);
GetNPCByID(DoorOffset+3):setAnimation(state0);
GetNPCByID(DoorOffset+4):setAnimation(state0);
-- Odin's Gate
GetNPCByID(DoorOffset+5):setAnimation(state1);
GetNPCByID(DoorOffset+6):setAnimation(state1);
GetNPCByID(DoorOffset+7):setAnimation(state1);
GetNPCByID(DoorOffset+8):setAnimation(state1);
GetNPCByID(DoorOffset+9):setAnimation(state1);
-- Leviathan's Gate
GetNPCByID(DoorOffset+10):setAnimation(state0);
GetNPCByID(DoorOffset+11):setAnimation(state0);
GetNPCByID(DoorOffset+12):setAnimation(state0);
GetNPCByID(DoorOffset+13):setAnimation(state0);
GetNPCByID(DoorOffset+14):setAnimation(state0);
-- Titan's Gate
GetNPCByID(DoorOffset+15):setAnimation(state1);
GetNPCByID(DoorOffset+16):setAnimation(state1);
GetNPCByID(DoorOffset+17):setAnimation(state1);
GetNPCByID(DoorOffset+18):setAnimation(state1);
GetNPCByID(DoorOffset+19):setAnimation(state1);
-- Plates
-- East Plate
GetNPCByID(DoorOffset+20):setAnimation(state0);
GetNPCByID(DoorOffset+21):setAnimation(state0);
-- North Plate
GetNPCByID(DoorOffset+22):setAnimation(state0);
GetNPCByID(DoorOffset+23):setAnimation(state0);
-- West Plate
GetNPCByID(DoorOffset+24):setAnimation(state0);
GetNPCByID(DoorOffset+25):setAnimation(state0);
-- South Plate
GetNPCByID(DoorOffset+26):setAnimation(state0);
GetNPCByID(DoorOffset+27):setAnimation(state0);
return 0;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
Th2Evil/SuperPlus | plugins/writer.lua | 15 | 15445 | local function mohammed(msg, matches)
if #matches < 2 then
return "اكتب الامر /write ثم ضع فاصلة واكتب الجملة وستظهر لك نتائج الزخرفة " end
if string.len(matches[2]) > 20 then
return "متاح لك 20 حرف انكليزي فقط لايمكنك وضع حروف اكثر ❤️😐 @"..msg.from.username..'\n'
end--@TH3BOSS
local font_base = "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,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,0,9,8,7,6,5,4,3,2,1,.,_"
local font_hash = "z,y,x,w,v,u,t,s,r,q,p,o,n,m,l,k,j,i,h,g,f,e,d,c,b,a,Z,Y,X,W,V,U,T,S,R,Q,P,O,N,M,L,K,J,I,H,G,F,E,D,C,B,A,0,1,2,3,4,5,6,7,8,9,.,_"
local fonts = {
"ⓐ,ⓑ,ⓒ,ⓓ,ⓔ,ⓕ,ⓖ,ⓗ,ⓘ,ⓙ,ⓚ,ⓛ,ⓜ,ⓝ,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,ⓣ,ⓤ,ⓥ,ⓦ,ⓧ,ⓨ,ⓩ,ⓐ,ⓑ,ⓒ,ⓓ,ⓔ,ⓕ,ⓖ,ⓗ,ⓘ,ⓙ,ⓚ,ⓛ,ⓜ,ⓝ,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,ⓣ,ⓤ,ⓥ,ⓦ,ⓧ,ⓨ,ⓩ,⓪,➈,➇,➆,➅,➄,➃,➂,➁,➀,●,_",
"⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⓪,⑼,⑻,⑺,⑹,⑸,⑷,⑶,⑵,⑴,.,_",
"α,в,c,∂,є,ƒ,g,н,ι,נ,к,ℓ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,χ,у,z,α,в,c,∂,є,ƒ,g,н,ι,נ,к,ℓ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,χ,у,z,0,9,8,7,6,5,4,3,2,1,.,_",
"α,в,c,d,e,ғ,ɢ,н,ι,j,ĸ,l,м,ɴ,o,p,q,r,ѕ,т,υ,v,w,х,y,z,α,в,c,d,e,ғ,ɢ,н,ι,j,ĸ,l,м,ɴ,o,p,q,r,ѕ,т,υ,v,w,х,y,z,0,9,8,7,6,5,4,3,2,1,.,_",
"α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ą,ҍ,ç,ժ,ҽ,ƒ,ց,հ,ì,ʝ,ҟ,Ӏ,ʍ,ղ,օ,ք,զ,ɾ,ʂ,է,մ,ѵ,ա,×,վ,Հ,ą,ҍ,ç,ժ,ҽ,ƒ,ց,հ,ì,ʝ,ҟ,Ӏ,ʍ,ղ,օ,ք,զ,ɾ,ʂ,է,մ,ѵ,ա,×,վ,Հ,⊘,९,𝟠,7,Ϭ,Ƽ,५,Ӡ,ϩ,𝟙,.,_", "ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,0,9,8,7,6,5,4,3,2,1,.,_",
"α,ß,ς,d,ε,ƒ,g,h,ï,յ,κ,レ,m,η,⊕,p,Ω,r,š,†,u,∀,ω,x,ψ,z,α,ß,ς,d,ε,ƒ,g,h,ï,յ,κ,レ,m,η,⊕,p,Ω,r,š,†,u,∀,ω,x,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ム,乃,ζ,Ð,乇,キ,Ǥ,ん,ノ,フ,ズ,レ,ᄊ,刀,Ծ,ア,Q,尺,ㄎ,イ,Ц,Џ,Щ,メ,リ,乙,ム,乃,ζ,Ð,乇,キ,Ǥ,ん,ノ,フ,ズ,レ,ᄊ,刀,Ծ,ア,q,尺,ㄎ,イ,Ц,Џ,Щ,メ,リ,乙,ᅙ,9,8,ᆨ,6,5,4,3,ᆯ,1,.,_",
"α,β,c,δ,ε,Ŧ,ĝ,h,ι,j,κ,l,ʍ,π,ø,ρ,φ,Ʀ,$,†,u,υ,ω,χ,ψ,z,α,β,c,δ,ε,Ŧ,ĝ,h,ι,j,κ,l,ʍ,π,ø,ρ,φ,Ʀ,$,†,u,υ,ω,χ,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ձ,ъ,ƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,ձ,ъ,ƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,0,9,8,7,6,5,4,3,2,1,.,_",
"Λ,ɓ,¢,Ɗ,£,ƒ,ɢ,ɦ,ĩ,ʝ,Қ,Ł,ɱ,ה,ø,Ṗ,Ҩ,Ŕ,Ş,Ŧ,Ū,Ɣ,ω,Ж,¥,Ẑ,Λ,ɓ,¢,Ɗ,£,ƒ,ɢ,ɦ,ĩ,ʝ,Қ,Ł,ɱ,ה,ø,Ṗ,Ҩ,Ŕ,Ş,Ŧ,Ū,Ɣ,ω,Ж,¥,Ẑ,0,9,8,7,6,5,4,3,2,1,.,_",
"Λ,Б,Ͼ,Ð,Ξ,Ŧ,G,H,ł,J,К,Ł,M,Л,Ф,P,Ǫ,Я,S,T,U,V,Ш,Ж,Џ,Z,Λ,Б,Ͼ,Ð,Ξ,Ŧ,g,h,ł,j,К,Ł,m,Л,Ф,p,Ǫ,Я,s,t,u,v,Ш,Ж,Џ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"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̴,̴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̴,̴0̴,̴9̴,̴8̴,̴7̴,̴6̴,̴5̴,̴4̴,̴3̴,̴2̴,̴1̴,̴.̴,̴_̴",
"ⓐ,ⓑ,ⓒ,ⓓ,ⓔ,ⓕ,ⓖ,ⓗ,ⓘ,ⓙ,ⓚ,ⓛ,ⓜ,ⓝ,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,ⓣ,ⓤ,ⓥ,ⓦ,ⓧ,ⓨ,ⓩ,ⓐ,ⓑ,ⓒ,ⓓ,ⓔ,ⓕ,ⓖ,ⓗ,ⓘ,ⓙ,ⓚ,ⓛ,ⓜ,ⓝ,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,ⓣ,ⓤ,ⓥ,ⓦ,ⓧ,ⓨ,ⓩ,⓪,➈,➇,➆,➅,➄,➃,➂,➁,➀,●,_",
"⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⓪,⑼,⑻,⑺,⑹,⑸,⑷,⑶,⑵,⑴,.,_",
"α,в,c,∂,є,ƒ,g,н,ι,נ,к,ℓ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,χ,у,z,α,в,c,∂,є,ƒ,g,н,ι,נ,к,ℓ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,χ,у,z,0,9,8,7,6,5,4,3,2,1,.,_",
"α,в,c,ɗ,є,f,g,н,ι,נ,к,Ɩ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,x,у,z,α,в,c,ɗ,є,f,g,н,ι,נ,к,Ɩ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,x,у,z,0,9,8,7,6,5,4,3,2,1,.,_",
"α,в,c,d,e,ғ,ɢ,н,ι,j,ĸ,l,м,ɴ,o,p,q,r,ѕ,т,υ,v,w,х,y,z,α,в,c,d,e,ғ,ɢ,н,ι,j,ĸ,l,м,ɴ,o,p,q,r,ѕ,т,υ,v,w,х,y,z,0,9,8,7,6,5,4,3,2,1,.,_",
"α,Ⴆ,ƈ,ԃ,ҽ,ϝ,ɠ,ԋ,ι,ʝ,ƙ,ʅ,ɱ,ɳ,σ,ρ,ϙ,ɾ,ʂ,ƚ,υ,ʋ,ɯ,x,ყ,ȥ,α,Ⴆ,ƈ,ԃ,ҽ,ϝ,ɠ,ԋ,ι,ʝ,ƙ,ʅ,ɱ,ɳ,σ,ρ,ϙ,ɾ,ʂ,ƚ,υ,ʋ,ɯ,x,ყ,ȥ,0,9,8,7,6,5,4,3,2,1,.,_",
"α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ą,ɓ,ƈ,đ,ε,∱,ɠ,ɧ,ï,ʆ,ҡ,ℓ,ɱ,ŋ,σ,þ,ҩ,ŗ,ş,ŧ,ų,√,щ,х,γ,ẕ,ą,ɓ,ƈ,đ,ε,∱,ɠ,ɧ,ï,ʆ,ҡ,ℓ,ɱ,ŋ,σ,þ,ҩ,ŗ,ş,ŧ,ų,√,щ,х,γ,ẕ,0,9,8,7,6,5,4,3,2,1,.,_",
"ą,ҍ,ç,ժ,ҽ,ƒ,ց,հ,ì,ʝ,ҟ,Ӏ,ʍ,ղ,օ,ք,զ,ɾ,ʂ,է,մ,ѵ,ա,×,վ,Հ,ą,ҍ,ç,ժ,ҽ,ƒ,ց,հ,ì,ʝ,ҟ,Ӏ,ʍ,ղ,օ,ք,զ,ɾ,ʂ,է,մ,ѵ,ա,×,վ,Հ,⊘,९,𝟠,7,Ϭ,Ƽ,५,Ӡ,ϩ,𝟙,.,_",
"მ,ჩ,ƈ,ძ,ε,բ,ց,հ,ἶ,ʝ,ƙ,l,ო,ղ,օ,ր,գ,ɾ,ʂ,է,մ,ν,ω,ჯ,ყ,z,მ,ჩ,ƈ,ძ,ε,բ,ց,հ,ἶ,ʝ,ƙ,l,ო,ղ,օ,ր,գ,ɾ,ʂ,է,մ,ν,ω,ჯ,ყ,z,0,Գ,Ց,Դ,6,5,Վ,Յ,Զ,1,.,_",
"ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,0,9,8,7,6,5,4,3,2,1,.,_",
"α,ß,ς,d,ε,ƒ,g,h,ï,յ,κ,レ,m,η,⊕,p,Ω,r,š,†,u,∀,ω,x,ψ,z,α,ß,ς,d,ε,ƒ,g,h,ï,յ,κ,レ,m,η,⊕,p,Ω,r,š,†,u,∀,ω,x,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ª,b,¢,Þ,È,F,૬,ɧ,Î,j,Κ,Ļ,м,η,◊,Ƿ,ƍ,r,S,⊥,µ,√,w,×,ý,z,ª,b,¢,Þ,È,F,૬,ɧ,Î,j,Κ,Ļ,м,η,◊,Ƿ,ƍ,r,S,⊥,µ,√,w,×,ý,z,0,9,8,7,6,5,4,3,2,1,.,_",
"Δ,Ɓ,C,D,Σ,F,G,H,I,J,Ƙ,L,Μ,∏,Θ,Ƥ,Ⴓ,Γ,Ѕ,Ƭ,Ʊ,Ʋ,Ш,Ж,Ψ,Z,λ,ϐ,ς,d,ε,ғ,ɢ,н,ι,ϳ,κ,l,ϻ,π,σ,ρ,φ,г,s,τ,υ,v,ш,ϰ,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"Λ,ß,Ƈ,D,Ɛ,F,Ɠ,Ĥ,Ī,Ĵ,Ҡ,Ŀ,M,И,♡,Ṗ,Ҩ,Ŕ,S,Ƭ,Ʊ,Ѵ,Ѡ,Ӿ,Y,Z,Λ,ß,Ƈ,D,Ɛ,F,Ɠ,Ĥ,Ī,Ĵ,Ҡ,Ŀ,M,И,♡,Ṗ,Ҩ,Ŕ,S,Ƭ,Ʊ,Ѵ,Ѡ,Ӿ,Y,Z,0,9,8,7,6,5,4,3,2,1,.,_",
"ム,乃,ζ,Ð,乇,キ,Ǥ,ん,ノ,フ,ズ,レ,ᄊ,刀,Ծ,ア,Q,尺,ㄎ,イ,Ц,Џ,Щ,メ,リ,乙,ム,乃,ζ,Ð,乇,キ,Ǥ,ん,ノ,フ,ズ,レ,ᄊ,刀,Ծ,ア,q,尺,ㄎ,イ,Ц,Џ,Щ,メ,リ,乙,ᅙ,9,8,ᆨ,6,5,4,3,ᆯ,1,.,_",
"α,β,c,δ,ε,Ŧ,ĝ,h,ι,j,κ,l,ʍ,π,ø,ρ,φ,Ʀ,$,†,u,υ,ω,χ,ψ,z,α,β,c,δ,ε,Ŧ,ĝ,h,ι,j,κ,l,ʍ,π,ø,ρ,φ,Ʀ,$,†,u,υ,ω,χ,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ค,๖,¢,໓,ē,f,ງ,h,i,ว,k,l,๓,ຖ,໐,p,๑,r,Ş,t,น,ง,ຟ,x,ฯ,ຊ,ค,๖,¢,໓,ē,f,ງ,h,i,ว,k,l,๓,ຖ,໐,p,๑,r,Ş,t,น,ง,ຟ,x,ฯ,ຊ,0,9,8,7,6,5,4,3,2,1,.,_",
"ձ,ъ,ƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,ձ,ъ,ƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,0,9,8,7,6,5,4,3,2,1,.,_",
"Â,ß,Ĉ,Ð,Є,Ŧ,Ǥ,Ħ,Ī,ʖ,Қ,Ŀ,♏,И,Ø,P,Ҩ,R,$,ƚ,Ц,V,Щ,X,¥,Ẕ,Â,ß,Ĉ,Ð,Є,Ŧ,Ǥ,Ħ,Ī,ʖ,Қ,Ŀ,♏,И,Ø,P,Ҩ,R,$,ƚ,Ц,V,Щ,X,¥,Ẕ,0,9,8,7,6,5,4,3,2,1,.,_",
"Λ,ɓ,¢,Ɗ,£,ƒ,ɢ,ɦ,ĩ,ʝ,Қ,Ł,ɱ,ה,ø,Ṗ,Ҩ,Ŕ,Ş,Ŧ,Ū,Ɣ,ω,Ж,¥,Ẑ,Λ,ɓ,¢,Ɗ,£,ƒ,ɢ,ɦ,ĩ,ʝ,Қ,Ł,ɱ,ה,ø,Ṗ,Ҩ,Ŕ,Ş,Ŧ,Ū,Ɣ,ω,Ж,¥,Ẑ,0,9,8,7,6,5,4,3,2,1,.,_",
"Λ,Б,Ͼ,Ð,Ξ,Ŧ,G,H,ł,J,К,Ł,M,Л,Ф,P,Ǫ,Я,S,T,U,V,Ш,Ж,Џ,Z,Λ,Б,Ͼ,Ð,Ξ,Ŧ,g,h,ł,j,К,Ł,m,Л,Ф,p,Ǫ,Я,s,t,u,v,Ш,Ж,Џ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"Թ,Յ,Շ,Ժ,ȝ,Բ,Գ,ɧ,ɿ,ʝ,ƙ,ʅ,ʍ,Ռ,Ծ,ρ,φ,Ր,Տ,Ե,Մ,ע,ա,Ճ,Վ,Հ,Թ,Յ,Շ,Ժ,ȝ,Բ,Գ,ɧ,ɿ,ʝ,ƙ,ʅ,ʍ,Ռ,Ծ,ρ,φ,Ր,Տ,Ե,Մ,ע,ա,Ճ,Վ,Հ,0,9,8,7,6,5,4,3,2,1,.,_",
"Æ,þ,©,Ð,E,F,ζ,Ħ,Ї,¿,ズ,ᄂ,M,Ñ,Θ,Ƿ,Ø,Ґ,Š,τ,υ,¥,w,χ,y,շ,Æ,þ,©,Ð,E,F,ζ,Ħ,Ї,¿,ズ,ᄂ,M,Ñ,Θ,Ƿ,Ø,Ґ,Š,τ,υ,¥,w,χ,y,շ,0,9,8,7,6,5,4,3,2,1,.,_",
"ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"4,8,C,D,3,F,9,H,!,J,K,1,M,N,0,P,Q,R,5,7,U,V,W,X,Y,2,4,8,C,D,3,F,9,H,!,J,K,1,M,N,0,P,Q,R,5,7,U,V,W,X,Y,2,0,9,8,7,6,5,4,3,2,1,.,_",
"Λ,M,X,ʎ,Z,ɐ,q,ɔ,p,ǝ,ɟ,ƃ,ɥ,ı,ɾ,ʞ,l,ա,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,Λ,M,X,ʎ,Z,ɐ,q,ɔ,p,ǝ,ɟ,ƃ,ɥ,ı,ɾ,ʞ,l,ա,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,0,9,8,7,6,5,4,3,2,1,.,‾",
"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̴,̴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̴,̴0̴,̴9̴,̴8̴,̴7̴,̴6̴,̴5̴,̴4̴,̴3̴,̴2̴,̴1̴,̴.̴,̴_̴",
"A̱,̱Ḇ,̱C̱,̱Ḏ,̱E̱,̱F̱,̱G̱,̱H̱,̱I̱,̱J̱,̱Ḵ,̱Ḻ,̱M̱,̱Ṉ,̱O̱,̱P̱,̱Q̱,̱Ṟ,̱S̱,̱Ṯ,̱U̱,̱V̱,̱W̱,̱X̱,̱Y̱,̱Ẕ,̱a̱,̱ḇ,̱c̱,̱ḏ,̱e̱,̱f̱,̱g̱,̱ẖ,̱i̱,̱j̱,̱ḵ,̱ḻ,̱m̱,̱ṉ,̱o̱,̱p̱,̱q̱,̱ṟ,̱s̱,̱ṯ,̱u̱,̱v̱,̱w̱,̱x̱,̱y̱,̱ẕ,̱0̱,̱9̱,̱8̱,̱7̱,̱6̱,̱5̱,̱4̱,̱3̱,̱2̱,̱1̱,̱.̱,̱_̱",
"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̲,̲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̲,̲0̲,̲9̲,̲8̲,̲7̲,̲6̲,̲5̲,̲4̲,̲3̲,̲2̲,̲1̲,̲.̲,̲_̲",
"Ā,̄B̄,̄C̄,̄D̄,̄Ē,̄F̄,̄Ḡ,̄H̄,̄Ī,̄J̄,̄K̄,̄L̄,̄M̄,̄N̄,̄Ō,̄P̄,̄Q̄,̄R̄,̄S̄,̄T̄,̄Ū,̄V̄,̄W̄,̄X̄,̄Ȳ,̄Z̄,̄ā,̄b̄,̄c̄,̄d̄,̄ē,̄f̄,̄ḡ,̄h̄,̄ī,̄j̄,̄k̄,̄l̄,̄m̄,̄n̄,̄ō,̄p̄,̄q̄,̄r̄,̄s̄,̄t̄,̄ū,̄v̄,̄w̄,̄x̄,̄ȳ,̄z̄,̄0̄,̄9̄,̄8̄,̄7̄,̄6̄,̄5̄,̄4̄,̄3̄,̄2̄,̄1̄,̄.̄,̄_̄",
"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,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,0,9,8,7,6,5,4,3,2,1,.,_",
"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,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,0,9,8,7,6,5,4,3,2,1,.,_",
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
local result = {}
i=0
for k=1,#fonts do
i=i+1
local tar_font = fonts[i]:split(",")
local text = matches[2]
local text = text:gsub("A",tar_font[1])
local text = text:gsub("B",tar_font[2])
local text = text:gsub("C",tar_font[3])
local text = text:gsub("D",tar_font[4])
local text = text:gsub("E",tar_font[5])
local text = text:gsub("F",tar_font[6])
local text = text:gsub("G",tar_font[7])
local text = text:gsub("H",tar_font[8])
local text = text:gsub("I",tar_font[9])
local text = text:gsub("J",tar_font[10])
local text = text:gsub("K",tar_font[11])
local text = text:gsub("L",tar_font[12])
local text = text:gsub("M",tar_font[13])
local text = text:gsub("N",tar_font[14])
local text = text:gsub("O",tar_font[15])
local text = text:gsub("P",tar_font[16])
local text = text:gsub("Q",tar_font[17])
local text = text:gsub("R",tar_font[18])
local text = text:gsub("S",tar_font[19])
local text = text:gsub("T",tar_font[20])
local text = text:gsub("U",tar_font[21])
local text = text:gsub("V",tar_font[22])
local text = text:gsub("W",tar_font[23])
local text = text:gsub("X",tar_font[24])
local text = text:gsub("Y",tar_font[25])
local text = text:gsub("Z",tar_font[26])
local text = text:gsub("a",tar_font[27])
local text = text:gsub("b",tar_font[28])
local text = text:gsub("c",tar_font[29])
local text = text:gsub("d",tar_font[30])
local text = text:gsub("e",tar_font[31])
local text = text:gsub("f",tar_font[32])
local text = text:gsub("g",tar_font[33])
local text = text:gsub("h",tar_font[34])
local text = text:gsub("i",tar_font[35])
local text = text:gsub("j",tar_font[36])
local text = text:gsub("k",tar_font[37])
local text = text:gsub("l",tar_font[38])
local text = text:gsub("m",tar_font[39])
local text = text:gsub("n",tar_font[40])
local text = text:gsub("o",tar_font[41])
local text = text:gsub("p",tar_font[42])
local text = text:gsub("q",tar_font[43])
local text = text:gsub("r",tar_font[44])
local text = text:gsub("s",tar_font[45])
local text = text:gsub("t",tar_font[46])
local text = text:gsub("u",tar_font[47])
local text = text:gsub("v",tar_font[48])
local text = text:gsub("w",tar_font[49])
local text = text:gsub("x",tar_font[50])
local text = text:gsub("y",tar_font[51])
local text = text:gsub("z",tar_font[52])
local text = text:gsub("0",tar_font[53])
local text = text:gsub("9",tar_font[54])
local text = text:gsub("8",tar_font[55])
local text = text:gsub("7",tar_font[56])
local text = text:gsub("6",tar_font[57])
local text = text:gsub("5",tar_font[58])
local text = text:gsub("4",tar_font[59])
local text = text:gsub("3",tar_font[60])
local text = text:gsub("2",tar_font[61])
local text = text:gsub("1",tar_font[62])
table.insert(result, text)
end--@TH3BOSS
local result_text = "زخرفة كلمة : "..matches[2].."\nتطبيق اكثر من "..tostring(#fonts).." نوع من الخطوط : \n🃏〰〰〰〰〰〰〰〰〰🃏\n"
a=0
for v=1,#result do
a=a+1
result_text = result_text..a.."- "..result[a].."\n\n"
end
return result_text.."🃏〰〰〰〰〰〰〰〰〰🃏\n💯-Đєⱴ💀: @TH3BOSS\n💯-Đєⱴ ฿๏ͳ💀: @ll60Kllbot\n💯-Đєⱴ Ϲḫ₳ͷͷєℓ💀: @llDEV1ll"end
return {
description = "Fantasy Writer",
usagehtm = '<tr><td align="center">write </td><td align="right">ملف زخرفة للكلمات الانكليزية ملف يحتوي على اكثر من 50 نوع من الخطوط للزخرفة وتحصل على زخارف رائعة يمكنك وضع 20 حرف انكليزي فقط لايمكنك وضع اكثر</td></tr>',
usage = {"write [text] : ",},
patterns = {
"^(write) (.*)",
"^(Write) (.*)",
},
run = mohammed
} | gpl-2.0 |
jshackley/darkstar | scripts/zones/PsoXja/npcs/_097.lua | 17 | 1614 | -----------------------------------
-- Area: Pso'Xja
-- NPC: _097 (Stone Gate)
-- Notes: Spawns Gargoyle when triggered
-- @pos -330.000 14.074 -261.600 9
-----------------------------------
package.loaded["scripts/zones/PsoXja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/PsoXja/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
local Z=player:getZPos();
if (npc:getAnimation() == 9) then
if (Z <= -82) then
if (GetMobAction(16814088) == 0) then
local Rand = math.random(1,10);
if (Rand <=9) then -- Spawn Gargoyle
player:messageSpecial(TRAP_ACTIVATED);
SpawnMob(16814088,120):updateClaim(player); -- Gargoyle
else
player:messageSpecial(TRAP_FAILS);
npc:openDoor(30);
end
else
player:messageSpecial(DOOR_LOCKED);
end
elseif (Z >= -81) then
player:startEvent(0x001A);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == 0x001A and option == 1) then
player:setPos(260,-0.25,-20,254,111);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Northern_San_dOria/npcs/Nouveil.lua | 17 | 2121 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Nouveil
-- Type: General
-- @zone: 231
-- @pos 123 0 106
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) == true and trade:getItemCount() == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
if (player:getQuestStatus(SANDORIA,WATER_OF_THE_CHEVAL) == QUEST_ACCEPTED) then
if (trade:getGil() >= 10) then
player:startEvent(0x023b);
end;
end;
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(SANDORIA,WATER_OF_THE_CHEVAL) == QUEST_ACCEPTED) then
if (player:hasItem(603) == true) then
player:startEvent(0x023d);
elseif (player:hasItem(602) == true) then
player:startEvent(0x023c);
else
player:startEvent(0x023f);
end;
else
player:startEvent(0x023e);
end;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
-- Waters of the Cheval, recieve blessed waterskin
if (csid == 0x023b) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 602);
else
player:delGil(10);
player:addItem(602);
player:messageSpecial(ITEM_OBTAINED, 602);
end;
end;
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Ghelsba_Outpost/bcnms/holy_crest.lua | 19 | 2119 | -----------------------------------
-- Area: Ghelsba Outpost
-- Name: Holy Crest - DRG flag quest
-- @pos -162 -11 78 140
-----------------------------------
package.loaded["scripts/zones/Ghelsba_Outpost/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/pets");
require("scripts/zones/Ghelsba_Outpost/TextIDs");
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print(leave code ..leavecode);
if (leavecode == 2) then --play end CS. Need time and battle id for record keeping + storage
if (player:getQuestStatus(SANDORIA,THE_HOLY_CREST) == QUEST_ACCEPTED) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,1);
end
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print(bc update csid ..csid.. and option ..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid: "..csid.."and option: "..option);
if (csid == 0x7d01 and option ~= 0 and player:hasKeyItem(DRAGON_CURSE_REMEDY) == true) then
player:addTitle(HEIR_TO_THE_HOLY_CREST);
player:delKeyItem(DRAGON_CURSE_REMEDY);
player:unlockJob(14);
player:messageSpecial(YOU_CAN_NOW_BECOME_A_DRAGOON);
player:setVar("TheHolyCrest_Event",0);
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA,THE_HOLY_CREST);
player:setPetName(PETTYPE_WYVERN,option);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Riverne-Site_B01/Zone.lua | 17 | 1801 | -----------------------------------
--
-- Zone: Riverne-Site_B01
--
-----------------------------------
package.loaded["scripts/zones/Riverne-Site_B01/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Riverne-Site_B01/TextIDs");
require("scripts/globals/status");
require("scripts/globals/settings");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(729.749,-20.319,407.153,90); -- {R}
end
-- ZONE LEVEL RESTRICTION
if (ENABLE_COP_ZONE_CAP == 1) then
player:addStatusEffect(EFFECT_LEVEL_RESTRICTION,50,0,0);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/items/betta.lua | 18 | 1254 | -----------------------------------------
-- ID: 5139
-- Item: Betta
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 3
-- Mind -5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:getRace() ~= 7) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5139);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 3);
target:addMod(MOD_MND, -5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 3);
target:delMod(MOD_MND, -5);
end;
| gpl-3.0 |
VincentGong/chess | cocos2d-x/cocos/scripting/lua-bindings/auto/api/lua_cocos2dx_studio_auto_api.lua | 6 | 4735 | --------------------------------
-- @module ccs
--------------------------------------------------------
-- the ccs ActionObject
-- @field [parent=#ccs] ActionObject#ActionObject ActionObject preloaded module
--------------------------------------------------------
-- the ccs ActionManagerEx
-- @field [parent=#ccs] ActionManagerEx#ActionManagerEx ActionManagerEx preloaded module
--------------------------------------------------------
-- the ccs BaseData
-- @field [parent=#ccs] BaseData#BaseData BaseData preloaded module
--------------------------------------------------------
-- the ccs DisplayData
-- @field [parent=#ccs] DisplayData#DisplayData DisplayData preloaded module
--------------------------------------------------------
-- the ccs SpriteDisplayData
-- @field [parent=#ccs] SpriteDisplayData#SpriteDisplayData SpriteDisplayData preloaded module
--------------------------------------------------------
-- the ccs ArmatureDisplayData
-- @field [parent=#ccs] ArmatureDisplayData#ArmatureDisplayData ArmatureDisplayData preloaded module
--------------------------------------------------------
-- the ccs ParticleDisplayData
-- @field [parent=#ccs] ParticleDisplayData#ParticleDisplayData ParticleDisplayData preloaded module
--------------------------------------------------------
-- the ccs BoneData
-- @field [parent=#ccs] BoneData#BoneData BoneData preloaded module
--------------------------------------------------------
-- the ccs ArmatureData
-- @field [parent=#ccs] ArmatureData#ArmatureData ArmatureData preloaded module
--------------------------------------------------------
-- the ccs FrameData
-- @field [parent=#ccs] FrameData#FrameData FrameData preloaded module
--------------------------------------------------------
-- the ccs MovementBoneData
-- @field [parent=#ccs] MovementBoneData#MovementBoneData MovementBoneData preloaded module
--------------------------------------------------------
-- the ccs MovementData
-- @field [parent=#ccs] MovementData#MovementData MovementData preloaded module
--------------------------------------------------------
-- the ccs AnimationData
-- @field [parent=#ccs] AnimationData#AnimationData AnimationData preloaded module
--------------------------------------------------------
-- the ccs ContourData
-- @field [parent=#ccs] ContourData#ContourData ContourData preloaded module
--------------------------------------------------------
-- the ccs TextureData
-- @field [parent=#ccs] TextureData#TextureData TextureData preloaded module
--------------------------------------------------------
-- the ccs Tween
-- @field [parent=#ccs] Tween#Tween Tween preloaded module
--------------------------------------------------------
-- the ccs DisplayManager
-- @field [parent=#ccs] DisplayManager#DisplayManager DisplayManager preloaded module
--------------------------------------------------------
-- the ccs Bone
-- @field [parent=#ccs] Bone#Bone Bone preloaded module
--------------------------------------------------------
-- the ccs BatchNode
-- @field [parent=#ccs] BatchNode#BatchNode BatchNode preloaded module
--------------------------------------------------------
-- the ccs ArmatureAnimation
-- @field [parent=#ccs] ArmatureAnimation#ArmatureAnimation ArmatureAnimation preloaded module
--------------------------------------------------------
-- the ccs ArmatureDataManager
-- @field [parent=#ccs] ArmatureDataManager#ArmatureDataManager ArmatureDataManager preloaded module
--------------------------------------------------------
-- the ccs Armature
-- @field [parent=#ccs] Armature#Armature Armature preloaded module
--------------------------------------------------------
-- the ccs Skin
-- @field [parent=#ccs] Skin#Skin Skin preloaded module
--------------------------------------------------------
-- the ccs ComAttribute
-- @field [parent=#ccs] ComAttribute#ComAttribute ComAttribute preloaded module
--------------------------------------------------------
-- the ccs ComAudio
-- @field [parent=#ccs] ComAudio#ComAudio ComAudio preloaded module
--------------------------------------------------------
-- the ccs ComController
-- @field [parent=#ccs] ComController#ComController ComController preloaded module
--------------------------------------------------------
-- the ccs ComRender
-- @field [parent=#ccs] ComRender#ComRender ComRender preloaded module
--------------------------------------------------------
-- the ccs GUIReader
-- @field [parent=#ccs] GUIReader#GUIReader GUIReader preloaded module
--------------------------------------------------------
-- the ccs SceneReader
-- @field [parent=#ccs] SceneReader#SceneReader SceneReader preloaded module
return nil
| mit |
VincentGong/chess | cocos2d-x/cocos/scripting/lua-bindings/auto/api/ComAttribute.lua | 6 | 2261 |
--------------------------------
-- @module ComAttribute
-- @extend Component
--------------------------------
-- @function [parent=#ComAttribute] getFloat
-- @param self
-- @param #string str
-- @param #float float
-- @return float#float ret (return value: float)
--------------------------------
-- @function [parent=#ComAttribute] getString
-- @param self
-- @param #string str
-- @param #string str
-- @return string#string ret (return value: string)
--------------------------------
-- @function [parent=#ComAttribute] setFloat
-- @param self
-- @param #string str
-- @param #float float
--------------------------------
-- @function [parent=#ComAttribute] setString
-- @param self
-- @param #string str
-- @param #string str
--------------------------------
-- @function [parent=#ComAttribute] getBool
-- @param self
-- @param #string str
-- @param #bool bool
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#ComAttribute] setInt
-- @param self
-- @param #string str
-- @param #int int
--------------------------------
-- @function [parent=#ComAttribute] parse
-- @param self
-- @param #string str
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#ComAttribute] getInt
-- @param self
-- @param #string str
-- @param #int int
-- @return int#int ret (return value: int)
--------------------------------
-- @function [parent=#ComAttribute] setBool
-- @param self
-- @param #string str
-- @param #bool bool
--------------------------------
-- @function [parent=#ComAttribute] create
-- @param self
-- @return ComAttribute#ComAttribute ret (return value: ccs.ComAttribute)
--------------------------------
-- @function [parent=#ComAttribute] createInstance
-- @param self
-- @return Ref#Ref ret (return value: cc.Ref)
--------------------------------
-- @function [parent=#ComAttribute] init
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#ComAttribute] serialize
-- @param self
-- @param #void void
-- @return bool#bool ret (return value: bool)
return nil
| mit |
tridge/ardupilot | libraries/AP_Scripting/examples/Aerobatics/Via_Switch/10_loops-and-immelman.lua | 8 | 11279 | -- loops and returns on switch
TRICK_NUMBER = 10 -- selector number recognized to execute trick, change as desired
-- number of loops controlled by AERO_RPT_COUNT, if 0 it will do an immelman instead, trick returns control after executing even if trick id remains 10
local target_vel -- trick specific global variables
local loop_stage
-------------------------------------------------------------------
-- do not change anything unless noted
local running = false
local not_bound = true
local initial_yaw_deg = 0
local initial_height = 0
local repeat_count
-- constrain a value between limits
function constrain(v, vmin, vmax)
if v < vmin then
v = vmin
end
if v > vmax then
v = vmax
end
return v
end
function wrap_360(angle) --function returns positive angle modulo360, -710 in returns 10, -10 returns +350
local res = math.fmod(angle, 360.0)
if res < 0 then
res = res + 360.0
end
return res
end
function wrap_180(angle)
local res = wrap_360(angle)
if res > 180 then
res = res - 360
end
return res
end
-- roll angle error 180 wrap to cope with errors while in inverted segments
function roll_angle_error_wrap(roll_angle_error)
if math.abs(roll_angle_error) > 180 then
if roll_angle_error > 0 then
roll_angle_error = roll_angle_error - 360
else
roll_angle_error= roll_angle_error +360
end
end
return roll_angle_error
end
--roll controller to keep wings level in earth frame. if arg is 0 then level is at only 0 deg, otherwise its at 180/-180 roll also for loops
function earth_frame_wings_level(arg)
local roll_deg = math.deg(ahrs:get_roll())
local roll_angle_error = 0.0
if (roll_deg > 90 or roll_deg < -90) and arg ~= 0 then
roll_angle_error = 180 - roll_deg
else
roll_angle_error = - roll_deg
end
return roll_angle_error_wrap(roll_angle_error)/(RLL2SRV_TCONST:get())
end
-- constrain rates to rate controller call
function _set_target_throttle_rate_rpy(throttle,roll_rate, pitch_rate, yaw_rate)
local r_rate = constrain(roll_rate,-RATE_MAX:get(),RATE_MAX:get())
local p_rate = constrain(pitch_rate,-RATE_MAX:get(),RATE_MAX:get())
vehicle:set_target_throttle_rate_rpy(throttle, r_rate, p_rate, yaw_rate)
end
-- a PI controller implemented as a Lua object
local function PI_controller(kP,kI,iMax)
-- the new instance. You can put public variables inside this self
-- declaration if you want to
local self = {}
-- private fields as locals
local _kP = kP or 0.0
local _kI = kI or 0.0
local _kD = kD or 0.0
local _iMax = iMax
local _last_t = nil
local _I = 0
local _P = 0
local _total = 0
local _counter = 0
local _target = 0
local _current = 0
-- update the controller.
function self.update(target, current)
local now = millis():tofloat() * 0.001
if not _last_t then
_last_t = now
end
local dt = now - _last_t
_last_t = now
local err = target - current
_counter = _counter + 1
local P = _kP * err
_I = _I + _kI * err * dt
if _iMax then
_I = constrain(_I, -_iMax, iMax)
end
local I = _I
local ret = P + I
_target = target
_current = current
_P = P
_total = ret
return ret
end
-- reset integrator to an initial value
function self.reset(integrator)
_I = integrator
end
function self.set_I(I)
_kI = I
end
function self.set_P(P)
_kP = P
end
function self.set_Imax(Imax)
_iMax = Imax
end
-- log the controller internals
function self.log(name, add_total)
-- allow for an external addition to total
logger.write(name,'Targ,Curr,P,I,Total,Add','ffffff',_target,_current,_P,_I,_total,add_total)
end
-- return the instance
return self
end
local function height_controller(kP_param,kI_param,KnifeEdge_param,Imax)
local self = {}
local kP = kP_param
local kI = kI_param
local KnifeEdge = KnifeEdge_param
local PI = PI_controller(kP:get(), kI:get(), Imax)
function self.update(target)
local target_pitch = PI.update(initial_height, ahrs:get_position():alt()*0.01)
local roll_rad = ahrs:get_roll()
local ke_add = math.abs(math.sin(roll_rad)) * KnifeEdge:get()
target_pitch = target_pitch + ke_add
PI.log("HPI", ke_add)
return constrain(target_pitch,-45,45)
end
function self.reset()
PI.reset(math.max(math.deg(ahrs:get_pitch()), 3.0))
PI.set_P(kP:get())
PI.set_I(kI:get())
end
return self
end
-- a controller to target a zero pitch angle and zero heading change, used in a roll
-- output is a body frame pitch rate, with convergence over time tconst in seconds
function pitch_controller(target_pitch_deg, target_yaw_deg, tconst)
local roll_deg = math.deg(ahrs:get_roll())
local pitch_deg = math.deg(ahrs:get_pitch())
local yaw_deg = math.deg(ahrs:get_yaw())
-- get earth frame pitch and yaw rates
local ef_pitch_rate = (target_pitch_deg - pitch_deg) / tconst
local ef_yaw_rate = wrap_180(target_yaw_deg - yaw_deg) / tconst
local bf_pitch_rate = math.sin(math.rad(roll_deg)) * ef_yaw_rate + math.cos(math.rad(roll_deg)) * ef_pitch_rate
local bf_yaw_rate = math.cos(math.rad(roll_deg)) * ef_yaw_rate - math.sin(math.rad(roll_deg)) * ef_pitch_rate
return bf_pitch_rate, bf_yaw_rate
end
-- a controller for throttle to account for pitch
function throttle_controller()
local pitch_rad = ahrs:get_pitch()
local thr_ff = THR_PIT_FF:get()
local throttle = TRIM_THROTTLE:get() + math.sin(pitch_rad) * thr_ff
return constrain(throttle, TRIM_THROTTLE:get(), 100.0)
end
function bind_param(name)
local p = Parameter()
if p:init(name) then
not_bound = false
return p
else
not_bound = true
end
end
-- recover entry altitude
function recover_alt()
local target_pitch = height_PI.update(initial_height)
local pitch_rate, yaw_rate = pitch_controller(target_pitch, initial_yaw_deg, PITCH_TCONST:get())
throttle = throttle_controller()
return throttle, pitch_rate, yaw_rate
end
----------------------------------------------------------------------------------------------
--every trick needs an init, change as needed...to bind the AERO params it uses(which will depend on the trick), and setup PID controllers used by script
function init()
HGT_P = bind_param("AERO_HGT_P") -- height P gain, required for height controller
HGT_I = bind_param("AERO_HGT_I") -- height I gain, required for height controller
HGT_KE_BIAS = bind_param("AERO_HGT_KE_BIAS") -- height knifeedge addition for pitch
THR_PIT_FF = bind_param("AERO_THR_PIT_FF") -- throttle FF from pitch
TRIM_THROTTLE = bind_param("TRIM_THROTTLE") --usually required for any trick
TRIM_ARSPD_CM = bind_param("TRIM_ARSPD_CM") --usually required for any trick
RATE_MAX = bind_param("AERO_RATE_MAX")
RLL2SRV_TCONST = bind_param("RLL2SRV_TCONST") --usually required for any trick
PITCH_TCONST = bind_param("PTCH2SRV_TCONST") --usually required for any trick
TRICK_ID = bind_param("AERO_TRICK_ID") --- required for any trick
TRICK_RAT = bind_param("AERO_TRICK_RAT") --usually required for any trick
RPT_COUNT = bind_param("AERO_RPT_COUNT") --repeat count for trick
if not_bound then
gcs:send_text(0,string.format("Not bound yet"))
return init, 100
else
gcs:send_text(0,string.format("Params bound,Trick %.0f loaded", TRICK_NUMBER))
height_PI = height_controller(HGT_P, HGT_I, HGT_KE_BIAS, 20.0) -- this trick needs this height PID controller setup to hold height during the trick
loop_stage = 0
return update, 50
end
end
-----------------------------------------------------------------------------------------------
--every trick will have its own do_trick function to perform the trick...this will change totally for each different trick
function do_loop(arg1)
-- do one loop with controllable pitch rate arg1 is pitch rate, arg2 number of loops, 0 indicates 1/2 cuban8 reversa
local throttle = throttle_controller()
local pitch_deg = math.deg(ahrs:get_pitch())
local roll_deg = math.deg(ahrs:get_roll())
local vel = ahrs:get_velocity_NED():length()
local pitch_rate = arg1
local yaw_rate = 0
pitch_rate = pitch_rate * (1+ 2*((vel/target_vel)-1)) --increase/decrease rate based on velocity to round loop
pitch_rate = constrain(pitch_rate,.5 * arg1, 3 * arg1)
if loop_stage == 0 then
if pitch_deg > 60 then
loop_stage = 1
end
elseif loop_stage == 1 then
if (math.abs(roll_deg) < 90 and pitch_deg > -5 and pitch_deg < 5 and repeat_count > 0) then
-- we're done with loop
gcs:send_text(0, string.format("Finished loop p=%.1f", pitch_deg))
loop_stage = 2 --now recover stage
repeat_count = repeat_count - 1
elseif (math.abs(roll_deg) > 90 and pitch_deg > -5 and pitch_deg < 5 and repeat_count <= 0) then
gcs:send_text(0, string.format("Finished return p=%.1f", pitch_deg))
loop_stage = 2 --now recover stage
repeat_count = repeat_count - 1
initial_yaw_deg = math.deg(ahrs:get_yaw())
end
elseif loop_stage == 2 then
-- recover alt if above or below start and terminate
if repeat_count > 0 then
--yaw_rate = 0
loop_stage = 0
elseif math.abs(ahrs:get_position():alt()*0.01 - initial_height) > 3 then
throttle, pitch_rate, yaw_rate = recover_alt()
else
running = false
gcs:send_text(0, string.format("Recovered entry alt"))
TRICK_ID:set(0)
return
end
end
throttle = throttle_controller()
if loop_stage == 2 or loop_stage == 0 then level_type = 0 else level_type = 1 end
if math.abs(pitch_deg) > 85 and math.abs(pitch_deg) < 95 then
roll_rate = 0
else
roll_rate = earth_frame_wings_level(level_type)
end
_set_target_throttle_rate_rpy(throttle, roll_rate, pitch_rate, yaw_rate)
end
-------------------------------------------------------------------------------------------
--trick should noramlly only have to change the notification text in this routine,initialize trick specific variables, and any parameters needing to be passed to do_trick(..)
function update()
if (TRICK_ID:get() == TRICK_NUMBER) then
local current_mode = vehicle:get_mode()
if arming:is_armed() and running == false then
if not vehicle:nav_scripting_enable(current_mode) then
return update, 50
end
running = true
initial_height = ahrs:get_position():alt()*0.01
initial_yaw_deg = math.deg(ahrs:get_yaw())
height_PI.reset()
repeat_count = RPT_COUNT:get()
-----------------------------------------------trick specific
loop_stage = 0
target_vel = ahrs:get_velocity_NED():length()
gcs:send_text(0, string.format("Loop/Return")) --change announcement as appropriate for trick
-------------------------------------------------------
elseif running == true then
do_loop(TRICK_RAT:get()) -- change arguments as appropriate for trick
end
else
running = false
end
return update, 50
end
return init,1000
| gpl-3.0 |
Victek/wrt1900ac-aa | feeds/xwrt/webif-iw-lua/files/usr/lib/lua/lua-xwrt/xwrt/translator.lua | 26 | 1471 | --------------------------------------------------------------------------------
-- translator.lua
--
-- Description:
-- to translate text ...
-- before this script must be load some files functions and set some VARS
--
-- Author(s) [in order of work date]:
-- Fabián Omar Franzotti .
--
-- Configuration files referenced:
--
--------------------------------------------------------------------------------
__tr = {}
--util = require("lua-xwrt.util")
function tr_load()
local lang = uci.get("webif","general","lang") or "en"
if lang == "en" then return end
local file = "/usr/lib/webif/lang/"..lang.."/common.txt"
local data, len = util.file_load(file)
if len then
data = string.gsub(data," "," ")
for line in string.gmatch(data,"[^\n]+") do
_, _, key, val = string.find(line, "(.+)[=][>]%s*(.*)")
if key then
key = string.trim(key)
-- val = string.trim(val)
__tr[key] = val
end
end
end
end
function tr(k)
local str = ""
local u, text = unpack(string.split(k,"#"))
-- print(v,u,text,"<BR>")
if text == nil then text = u end
mytr = string.trim(__tr[u])
-- print (u,mytr,"<br>")
if mytr == nil or mytr == "" then mytr = text end
str = str .. mytr
return str
end
function trsh(linea)
local ret=""
linea = string.gsub(linea,"@TR<<","}{")
linea = string.gsub(linea,">>","}{").."}"
for v in string.gmatch(linea,"%b{}") do
ret = ret .. tr(string.gsub("@aa"..v, "@(%a+){(.-)}", "%2")).." "
end
return ret
end
| gpl-2.0 |
Ombridride/minetest-minetestforfun-server | mods/WorldEdit/worldedit/common.lua | 25 | 2824 | --- Common functions [INTERNAL]. All of these functions are internal!
-- @module worldedit.common
--- Copies and modifies positions `pos1` and `pos2` so that each component of
-- `pos1` is less than or equal to the corresponding component of `pos2`.
-- Returns the new positions.
function worldedit.sort_pos(pos1, pos2)
pos1 = {x=pos1.x, y=pos1.y, z=pos1.z}
pos2 = {x=pos2.x, y=pos2.y, z=pos2.z}
if pos1.x > pos2.x then
pos2.x, pos1.x = pos1.x, pos2.x
end
if pos1.y > pos2.y then
pos2.y, pos1.y = pos1.y, pos2.y
end
if pos1.z > pos2.z then
pos2.z, pos1.z = pos1.z, pos2.z
end
return pos1, pos2
end
--- Determines the volume of the region defined by positions `pos1` and `pos2`.
-- @return The volume.
function worldedit.volume(pos1, pos2)
local pos1, pos2 = worldedit.sort_pos(pos1, pos2)
return (pos2.x - pos1.x + 1) *
(pos2.y - pos1.y + 1) *
(pos2.z - pos1.z + 1)
end
--- Gets other axes given an axis.
-- @raise Axis must be x, y, or z!
function worldedit.get_axis_others(axis)
if axis == "x" then
return "y", "z"
elseif axis == "y" then
return "x", "z"
elseif axis == "z" then
return "x", "y"
else
error("Axis must be x, y, or z!")
end
end
function worldedit.keep_loaded(pos1, pos2)
local manip = minetest.get_voxel_manip()
manip:read_from_map(pos1, pos2)
end
local mh = {}
worldedit.manip_helpers = mh
--- Generates an empty VoxelManip data table for an area.
-- @return The empty data table.
function mh.get_empty_data(area)
-- Fill emerged area with ignore so that blocks in the area that are
-- only partially modified aren't overwriten.
local data = {}
local c_ignore = minetest.get_content_id("ignore")
for i = 1, worldedit.volume(area.MinEdge, area.MaxEdge) do
data[i] = c_ignore
end
return data
end
function mh.init(pos1, pos2)
local manip = minetest.get_voxel_manip()
local emerged_pos1, emerged_pos2 = manip:read_from_map(pos1, pos2)
local area = VoxelArea:new({MinEdge=emerged_pos1, MaxEdge=emerged_pos2})
return manip, area
end
function mh.init_radius(pos, radius)
local pos1 = vector.subtract(pos, radius)
local pos2 = vector.add(pos, radius)
return mh.init(pos1, pos2)
end
function mh.init_axis_radius(base_pos, axis, radius)
return mh.init_axis_radius_length(base_pos, axis, radius, radius)
end
function mh.init_axis_radius_length(base_pos, axis, radius, length)
local other1, other2 = worldedit.get_axis_others(axis)
local pos1 = {
[axis] = base_pos[axis],
[other1] = base_pos[other1] - radius,
[other2] = base_pos[other2] - radius
}
local pos2 = {
[axis] = base_pos[axis] + length,
[other1] = base_pos[other1] + radius,
[other2] = base_pos[other2] + radius
}
return mh.init(pos1, pos2)
end
function mh.finish(manip, data)
-- Update map
manip:set_data(data)
manip:write_to_map()
manip:update_map()
end
| unlicense |
jshackley/darkstar | scripts/zones/Cloister_of_Gales/Zone.lua | 32 | 1656 | -----------------------------------
--
-- Zone: Cloister_of_Gales (201)
--
-----------------------------------
package.loaded["scripts/zones/Cloister_of_Gales/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Cloister_of_Gales/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-399.541,-1.697,-420,252);
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
Ombridride/minetest-minetestforfun-server | mods/unified_inventory/callbacks.lua | 5 | 7411 | local function default_refill(stack)
stack:set_count(stack:get_stack_max())
local itemdef = minetest.registered_items[stack:get_name()]
if itemdef
and (itemdef.wear_represents or "mechanical_wear") == "mechanical_wear"
and stack:get_wear() ~= 0 then
stack:set_wear(0)
end
return stack
end
minetest.register_on_joinplayer(function(player)
local player_name = player:get_player_name()
unified_inventory.players[player_name] = {}
unified_inventory.current_index[player_name] = 1
unified_inventory.filtered_items_list[player_name] =
unified_inventory.items_list
unified_inventory.activefilter[player_name] = ""
unified_inventory.active_search_direction[player_name] = "nochange"
unified_inventory.apply_filter(player, "", "nochange")
unified_inventory.current_searchbox[player_name] = ""
unified_inventory.alternate[player_name] = 1
unified_inventory.current_item[player_name] = nil
unified_inventory.current_craft_direction[player_name] = "recipe"
unified_inventory.set_inventory_formspec(player,
unified_inventory.default)
-- Refill slot
local refill = minetest.create_detached_inventory(player_name.."refill", {
allow_put = function(inv, listname, index, stack, player)
local player_name = player:get_player_name()
if unified_inventory.is_creative(player_name) then
return stack:get_count()
else
return 0
end
end,
on_put = function(inv, listname, index, stack, player)
local player_name = player:get_player_name()
local handle_refill = (minetest.registered_items[stack:get_name()] or {}).on_refill or default_refill
stack = handle_refill(stack)
inv:set_stack(listname, index, stack)
minetest.sound_play("electricity",
{to_player=player_name, gain = 1.0})
end,
})
refill:set_size("main", 1)
end)
minetest.register_on_player_receive_fields(function(player, formname, fields)
local player_name = player:get_player_name()
local ui_peruser,draw_lite_mode = unified_inventory.get_per_player_formspec(player_name)
if formname ~= "" then
return
end
if fields.hidebutton then --MFF crabman(29/11/2015) hide guide, textfield bug
if not unified_inventory.hidden_guide[player_name] then
unified_inventory.hidden_guide[player_name] = true
else
unified_inventory.hidden_guide[player_name] = false
end
unified_inventory.set_inventory_formspec(player, unified_inventory.current_page[player_name])
return
end
-- always take new search text, even if not searching on it yet
if fields.searchbox
and fields.searchbox ~= unified_inventory.current_searchbox[player_name] then
unified_inventory.current_searchbox[player_name] = fields.searchbox
unified_inventory.set_inventory_formspec(player, unified_inventory.current_page[player_name])
end
for i, def in pairs(unified_inventory.buttons) do
if fields[def.name] then
def.action(player)
minetest.sound_play("click",
{to_player=player_name, gain = 0.1})
return
end
end
-- Inventory page controls
local start = math.floor(
unified_inventory.current_index[player_name] / ui_peruser.items_per_page + 1)
local start_i = start
local pagemax = math.floor(
(#unified_inventory.filtered_items_list[player_name] - 1)
/ (ui_peruser.items_per_page) + 1)
if fields.start_list then
start_i = 1
end
if fields.rewind1 then
start_i = start_i - 1
end
if fields.forward1 then
start_i = start_i + 1
end
if fields.rewind3 then
start_i = start_i - 3
end
if fields.forward3 then
start_i = start_i + 3
end
if fields.end_list then
start_i = pagemax
end
if start_i < 1 then
start_i = 1
end
if start_i > pagemax then
start_i = pagemax
end
if start_i ~= start then
minetest.sound_play("paperflip1",
{to_player=player_name, gain = 1.0})
unified_inventory.current_index[player_name] = (start_i - 1) * ui_peruser.items_per_page + 1
unified_inventory.set_inventory_formspec(player,
unified_inventory.current_page[player_name])
end
local clicked_item
for name, value in pairs(fields) do
if string.sub(name, 1, 12) == "item_button_" then
local new_dir, mangled_item = string.match(name, "^item_button_([a-z]+)_(.*)$")
clicked_item = unified_inventory.demangle_for_formspec(mangled_item)
if string.sub(clicked_item, 1, 6) == "group:" then
minetest.sound_play("click", {to_player=player_name, gain = 0.1})
unified_inventory.apply_filter(player, clicked_item, new_dir)
unified_inventory.current_searchbox[player_name] = clicked_item
unified_inventory.set_inventory_formspec(player,
unified_inventory.current_page[player_name])
return
end
if new_dir == "recipe"
or new_dir == "usage" then
unified_inventory.current_craft_direction[player_name] = new_dir
end
break
end
end
if clicked_item then
minetest.sound_play("click",
{to_player=player_name, gain = 0.1})
local page = unified_inventory.current_page[player_name]
local player_creative = unified_inventory.is_creative(player_name)
if not player_creative then
page = "craftguide"
end
if page == "craftguide" then
unified_inventory.current_item[player_name] = clicked_item
unified_inventory.alternate[player_name] = 1
unified_inventory.set_inventory_formspec(player, "craftguide")
elseif player_creative then
local inv = player:get_inventory()
local stack = ItemStack(clicked_item)
stack:set_count(stack:get_stack_max())
if inv:room_for_item("main", stack) then
inv:add_item("main", stack)
end
end
end
if fields.searchbutton or fields.key_enter_field == "searchbox" then
unified_inventory.apply_filter(player, unified_inventory.current_searchbox[player_name], "nochange")
unified_inventory.set_inventory_formspec(player,
unified_inventory.current_page[player_name])
minetest.sound_play("paperflip2",
{to_player=player_name, gain = 1.0})
elseif fields.searchresetbutton then
unified_inventory.apply_filter(player, "", "nochange")
unified_inventory.current_searchbox[player_name] = ""
unified_inventory.set_inventory_formspec(player,
unified_inventory.current_page[player_name])
minetest.sound_play("click",
{to_player=player_name, gain = 0.1})
end
-- alternate buttons
if not (fields.alternate or fields.alternate_prev) then
return
end
minetest.sound_play("click",
{to_player=player_name, gain = 0.1})
local item_name = unified_inventory.current_item[player_name]
if not item_name then
return
end
local crafts = unified_inventory.crafts_for[unified_inventory.current_craft_direction[player_name]][item_name]
if not crafts then
return
end
local alternates = #crafts
if alternates <= 1 then
return
end
local alternate
if fields.alternate then
alternate = unified_inventory.alternate[player_name] + 1
if alternate > alternates then
alternate = 1
end
elseif fields.alternate_prev then
alternate = unified_inventory.alternate[player_name] - 1
if alternate < 1 then
alternate = alternates
end
end
unified_inventory.alternate[player_name] = alternate
unified_inventory.set_inventory_formspec(player,
unified_inventory.current_page[player_name])
end)
if minetest.delete_detached_inventory then
minetest.register_on_leaveplayer(function(player)
local player_name = player:get_player_name()
minetest.delete_detached_inventory(player_name.."_bags")
minetest.delete_detached_inventory(player_name.."craftrecipe")
minetest.delete_detached_inventory(player_name.."refill")
end)
end
| unlicense |
jshackley/darkstar | scripts/zones/Windurst_Waters/npcs/Kirarara.lua | 36 | 1420 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Kirarara
-- Involved in Quest: Making the Grade
-- Working 100%
-- @zone = 238
-- @pos = 132 -7 172
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(WINDURST,MAKING_THE_GRADE) == QUEST_ACCEPTED) then
player:startEvent(0x01bf); -- During Making the GRADE
else
player:startEvent(0x01a9); -- Standard conversation
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/globals/weaponskills/sanguine_blade.lua | 3 | 1660 | -----------------------------------
-- Sanguine Blade
-- Sword weapon skill
-- Skill Level: 300
-- Drains a percentage of damage dealt to HP varies with TP.
-- Will not stack with Sneak Attack.
-- Not aligned with any "elemental gorgets" or "elemental belts" due to it's absence of Skillchain properties.
-- Element: Dark
-- Modifiers: STR:30% ; MND:50%
-- 100%TP 200%TP 300%TP
-- 2.75 2.75 2.75
-- HP Drained by TP:
-- 100%TP 200%TP 300%TP
-- 50% 75% 100%
-----------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local tp = player:getTP();
local drain = 0;
if (tp >= 100 and tp <=199) then
drain = 50;
elseif (tp >= 200 and tp <= 299) then
drain = 75;
elseif (tp == 300) then
drain = 100;
end
local params = {};
params.ftp100 = 2.75; params.ftp200 = 2.75; params.ftp300 = 2.75;
params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.5; params.chr_wsc = 0.0;
params.ele = ELE_DARK;
params.skill = SKILL_SWD;
params.includemab = true;
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
if (target:isUndead() == false) then
player:addHP((damage/100) * drain);
end
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
jshackley/darkstar | scripts/globals/items/plate_of_dorado_sushi.lua | 14 | 1749 | -----------------------------------------
-- ID: 5178
-- Item: plate_of_dorado_sushi
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Dexterity 5
-- Accuracy % 15
-- Accuracy Cap 72
-- Ranged ACC % 15
-- Ranged ACC Cap 72
-- Sleep Resist 5
-- Enmity 4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5178);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_ENMITY, 4);
target:addMod(MOD_DEX, 5);
target:addMod(MOD_FOOD_ACCP, 15);
target:addMod(MOD_FOOD_ACC_CAP, 72);
target:addMod(MOD_FOOD_RACCP, 15);
target:addMod(MOD_FOOD_RACC_CAP, 72);
target:addMod(MOD_SLEEPRES, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_ENMITY, 4);
target:delMod(MOD_DEX, 5);
target:delMod(MOD_FOOD_ACCP, 15);
target:delMod(MOD_FOOD_ACC_CAP, 72);
target:delMod(MOD_FOOD_RACCP, 15);
target:delMod(MOD_FOOD_RACC_CAP, 72);
target:delMod(MOD_SLEEPRES, 5);
end;
| gpl-3.0 |
gemini-project/contrib | ingress/controllers/nginx/lua/trie.lua | 56 | 1428 | -- Simple trie for URLs
local _M = {}
local mt = {
__index = _M
}
-- http://lua-users.org/wiki/SplitJoin
local strfind, tinsert, strsub = string.find, table.insert, string.sub
function _M.strsplit(delimiter, text)
local list = {}
local pos = 1
while 1 do
local first, last = strfind(text, delimiter, pos)
if first then -- found?
tinsert(list, strsub(text, pos, first-1))
pos = last+1
else
tinsert(list, strsub(text, pos))
break
end
end
return list
end
local strsplit = _M.strsplit
function _M.new()
local t = { }
return setmetatable(t, mt)
end
function _M.add(t, key, val)
local parts = {}
-- hack for just /
if key == "/" then
parts = { "" }
else
parts = strsplit("/", key)
end
local l = t
for i = 1, #parts do
local p = parts[i]
if not l[p] then
l[p] = {}
end
l = l[p]
end
l.__value = val
end
function _M.get(t, key)
local parts = strsplit("/", key)
local l = t
-- this may be nil
local val = t.__value
for i = 1, #parts do
local p = parts[i]
if l[p] then
l = l[p]
local v = l.__value
if v then
val = v
end
else
break
end
end
-- may be nil
return val
end
return _M
| apache-2.0 |
Victek/wrt1900ac-aa | veriksystems/luci-0.11/applications/luci-minidlna/luasrc/model/cbi/minidlna.lua | 87 | 5720 | --[[
LuCI - Lua Configuration Interface - miniDLNA support
Copyright 2012 Gabor Juhos <juhosg@openwrt.org>
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
$Id$
]]--
local m, s, o
m = Map("minidlna", translate("miniDLNA"),
translate("MiniDLNA is server software with the aim of being fully compliant with DLNA/UPnP-AV clients."))
m:section(SimpleSection).template = "minidlna_status"
s = m:section(TypedSection, "minidlna", "miniDLNA Settings")
s.addremove = false
s.anonymous = true
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
o = s:taboption("general", Flag, "enabled", translate("Enable:"))
o.rmempty = false
function o.cfgvalue(self, section)
return luci.sys.init.enabled("minidlna") and self.enabled or self.disabled
end
function o.write(self, section, value)
if value == "1" then
luci.sys.init.enable("minidlna")
luci.sys.call("/etc/init.d/minidlna start >/dev/null")
else
luci.sys.call("/etc/init.d/minidlna stop >/dev/null")
luci.sys.init.disable("minidlna")
end
return Flag.write(self, section, value)
end
o = s:taboption("general", Value, "port", translate("Port:"),
translate("Port for HTTP (descriptions, SOAP, media transfer) traffic."))
o.datatype = "port"
o.default = 8200
o = s:taboption("general", Value, "interface", translate("Interfaces:"),
translate("Network interfaces to serve."))
o.template = "cbi/network_ifacelist"
o.widget = "checkbox"
o.nocreate = true
function o.cfgvalue(self, section)
local rv = { }
local val = Value.cfgvalue(self, section)
if val then
local ifc
for ifc in val:gmatch("[^,%s]+") do
rv[#rv+1] = ifc
end
end
return rv
end
function o.write(self, section, value)
local rv = { }
local ifc
for ifc in luci.util.imatch(value) do
rv[#rv+1] = ifc
end
Value.write(self, section, table.concat(rv, ","))
end
o = s:taboption("general", Value, "friendly_name", translate("Friendly name:"),
translate("Set this if you want to customize the name that shows up on your clients."))
o.rmempty = true
o.placeholder = "OpenWrt DLNA Server"
o = s:taboption("advanced", Value, "db_dir", translate("Database directory:"),
translate("Set this if you would like to specify the directory where you want MiniDLNA to store its database and album art cache."))
o.rmempty = true
o.placeholder = "/var/cache/minidlna"
o = s:taboption("advanced", Value, "log_dir", translate("Log directory:"),
translate("Set this if you would like to specify the directory where you want MiniDLNA to store its log file."))
o.rmempty = true
o.placeholder = "/var/log"
s:taboption("advanced", Flag, "inotify", translate("Enable inotify:"),
translate("Set this to enable inotify monitoring to automatically discover new files."))
s:taboption("advanced", Flag, "enable_tivo", translate("Enable TIVO:"),
translate("Set this to enable support for streaming .jpg and .mp3 files to a TiVo supporting HMO."))
o.rmempty = true
o = s:taboption("advanced", Flag, "strict_dlna", translate("Strict to DLNA standard:"),
translate("Set this to strictly adhere to DLNA standards. This will allow server-side downscaling of very large JPEG images, which may hurt JPEG serving performance on (at least) Sony DLNA products."))
o.rmempty = true
o = s:taboption("advanced", Value, "presentation_url", translate("Presentation URL:"))
o.rmempty = true
o.placeholder = "http://192.168.1.1/"
o = s:taboption("advanced", Value, "notify_interval", translate("Notify interval:"),
translate("Notify interval in seconds."))
o.datatype = "uinteger"
o.placeholder = 900
o = s:taboption("advanced", Value, "serial", translate("Announced serial number:"),
translate("Serial number the miniDLNA daemon will report to clients in its XML description."))
o.placeholder = "12345678"
s:taboption("advanced", Value, "model_number", translate("Announced model number:"),
translate("Model number the miniDLNA daemon will report to clients in its XML description."))
o.placholder = "1"
o = s:taboption("advanced", Value, "minissdpsocket", translate("miniSSDP socket:"),
translate("Specify the path to the MiniSSDPd socket."))
o.rmempty = true
o.placeholder = "/var/run/minissdpd.sock"
o = s:taboption("general", ListValue, "root_container", translate("Root container:"))
o:value(".", translate("Standard container"))
o:value("B", translate("Browse directory"))
o:value("M", translate("Music"))
o:value("V", translate("Video"))
o:value("P", translate("Pictures"))
s:taboption("general", DynamicList, "media_dir", translate("Media directories:"),
translate("Set this to the directory you want scanned. If you want to restrict the directory to a specific content type, you can prepend the type ('A' for audio, 'V' for video, 'P' for images), followed by a comma, to the directory (eg. media_dir=A,/mnt/media/Music). Multiple directories can be specified."))
o = s:taboption("general", DynamicList, "album_art_names", translate("Album art names:"),
translate("This is a list of file names to check for when searching for album art."))
o.rmempty = true
o.placeholder = "Cover.jpg"
function o.cfgvalue(self, section)
local rv = { }
local val = Value.cfgvalue(self, section)
if type(val) == "table" then
val = table.concat(val, "/")
elseif not val then
val = ""
end
local file
for file in val:gmatch("[^/%s]+") do
rv[#rv+1] = file
end
return rv
end
function o.write(self, section, value)
local rv = { }
local file
for file in luci.util.imatch(value) do
rv[#rv+1] = file
end
Value.write(self, section, table.concat(rv, "/"))
end
return m
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Port_Jeuno/npcs/Raging_Lion.lua | 17 | 1316 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Raging Lion
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
require("scripts/zones/Port_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local vHour = VanadielHour();
local vMin = VanadielMinute();
while vHour >= 3 do
vHour = vHour - 6;
end
if ( vHour == -3) then vHour = 3;
elseif ( vHour == -2) then vHour = 4;
elseif ( vHour == -1) then vHour = 5;
end
local seconds = math.floor(2.4 * ((vHour * 60) + vMin));
player:startEvent( 0x0011, seconds, 0, 0, 0, 0, 0, 0, 0);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
danomatika/joyosc | prj/premake4.lua | 2 | 2900 | --[[ A solution contains projects, and defines the available configurations
http://industriousone.com/premake/user-guide
example: http://opende.svn.sourceforge.net/viewvc/opende/trunk/build/premake4.lua?revision=1708&view=markup
http://bitbucket.org/anders/lightweight/src/tip/premake4.lua
]]
solution "joyosc"
configurations { "Debug", "Release" }
objdir "./obj"
-- joyosc executable
project "joyosc"
kind "ConsoleApp"
language "C++"
targetdir "../src/joyosc"
files { "../src/joyosc/**.h", "../src/joyosc/**.cpp" }
includedirs { "../src",
"../lib/lopack/src",
"../lib/tinyobject/src",
"../lib/cpphelpers",
"../lib/cpphelpers/tclap" }
--libdirs { "../lib/lopack/src/lopack", "../lib/tinyobject/src/tinyobject" }
--links { "lopack", "tinyobject" }
linkoptions { "$(PROJECT_DIR)/../lib/lopack/src/lopack/.libs/liblopack.a",
"$(PROJECT_DIR)/../lib/tinyobject/src/tinyobject/.libs/libtinyobject.a" }
configuration "linux"
buildoptions { "`pkg-config --cflags sdl2`", "`pkg-config --cflags liblo`", "`pkg-config --cflags tinyxml2`", "-DHAVE_CONFIG_H" }
linkoptions { "`pkg-config --libs sdl2`", "`pkg-config --libs liblo`", "`pkg-config --libs tinyxml2`" }
configuration 'macosx'
-- Homebrew & Macports
includedirs { "/usr/local/include", "/usr/local/include/SDL2", "/opt/local/include", "/opt/local/include/SDL2" }
libdirs { "/usr/local/lib", "/opt/local/lib" }
links { "lo", "tinyxml2", "pthread", "SDL2" }
buildoptions { "-DHAVE_CONFIG_H"}
linkoptions { "-Wl,-framework,Cocoa", "-Wl,-framework,OpenGL",
"-Wl,-framework,ApplicationServices",
"-Wl,-framework,Carbon", "-Wl,-framework,AudioToolbox",
"-Wl,-framework,AudioUnit", "-Wl,-framework,IOKit" }
configuration "Debug"
defines { "DEBUG" }
flags { "Symbols" }
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize" }
-- lsjs executable
project "lsjs"
kind "ConsoleApp"
language "C++"
targetdir "../src/lsjs"
files { "../src/lsjs/**.h", "../src/lsjs/**.cpp" }
includedirs { "../src",
"../lib/cpphelpers",
"../lib/cpphelpers/tclap" }
configuration "linux"
buildoptions { "`pkg-config --cflags sdl2`", "-DHAVE_CONFIG_H" }
linkoptions { "`pkg-config --libs sdl2`" }
configuration 'macosx'
-- Homebrew & Macports
includedirs { "/usr/local/include", "/usr/local/include/SDL2", "/opt/local/include", "/usr/local/include/SDL2" }
libdirs { "/usr/local/lib", "/opt/local/lib" }
links { "SDL2" }
buildoptions { "-DHAVE_CONFIG_H" }
linkoptions { "-Wl,-framework,Cocoa", "-Wl,-framework,OpenGL",
"-Wl,-framework,ApplicationServices",
"-Wl,-framework,Carbon", "-Wl,-framework,AudioToolbox",
"-Wl,-framework,AudioUnit", "-Wl,-framework,IOKit" }
configuration "Debug"
defines { "DEBUG" }
flags { "Symbols" }
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize" }
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Upper_Jeuno/npcs/Finnela.lua | 38 | 1027 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Finnela
-- Type: Standard NPC
-- @zone: 244
-- @pos -51.880 -1 106.486
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x278d);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
bartslinger/paparazzi | sw/extras/chdk/pictuav.lua | 87 | 5350 | --[[
@title PictUAV
@param d Display off frame 0=never
@default d 0
--]]
-- Developed on IXUS 230 HS. Other cameras should work as well, but some errors or crashes are possible
-- also considering that some firmwares still have CHDK bugs.
--
-- Other settings in the camera that you should try to manipulate to reduce the time between taking pictures:
-- CHDK menu
-- Extra Photo overrides
-- Disable overrides : Off
-- Do not override shutter speed ( I allow the camera to determine exposure time, but feel free to experiment)
-- ND filter state: Out (removes ND filter to allow more light to fall on the sensor )
-- Override subj. dist. value: 65535. (good to keep it there)
-- Do not save RAW images, they take longer
--
-- Camera menu
-- Use P mode, certainly not automatic
-- If you can hardset the focus, do this towards infinity
-- Play around with aperture. Smaller apertures are better for more sharpness, but not every camera allows you to.
-- (Some cameras have really bad behaviour on larger apertures that allow more light through, especially at edges).
-- Disable IS (plane vibrations mess up its function and increases the chance of blur)
-- Take Large images with Fine resolution.
-- Turn "Review" mode off.
-- Consider hard-setting ISO, but consider local weather. If set too high, shutter time goes up, which causes blur.
-- Blur can then also occur in areas where there is little light reflection from the earth.
--
-- How to use the script:
-- Load this on the card under "CHDK/SCRIPTS"
-- Enter the CHDK menu through your "ALT" button
-- Under scripts, select the script and specify "Autostart: on"
--
-- As the camera starts up, this also loads. with the shutter button pressed, you can interrupt the script
-- Then press the "ALT" button to disable the scripting actuator.
-- Press the shutter button to extend the lens
-- Press "ALT" again to bring up the scripting actuator.
-- Press the shutter button to reinitiate the script.
-- If you have a IXUS 230HS like me, the focus can't be set automatically. Point the camera at a distant object while the script
-- is starting. It should say "Focused", after which it's ready for use.
--
-- Example paparazzi airframe configuration:
--
-- <section name="DIGITAL_CAMERA" prefix="DC_">
-- <define name="AUTOSHOOT_QUARTERSEC_PERIOD" value="8" unit="quarter_second"/>
-- <define name="AUTOSHOOT_METER_GRID" value="60" unit="meter"/>
-- <define name="SHUTTER_DELAY" value="0" unit="quarter_second"/>
-- <define name="POWER_OFF_DELAY" value="3" unit="quarter_second"/>
-- </section>
--
-- <load name="digital_cam.xml" >
-- <define name="DC_SHUTTER_LED" value="4"/>
-- <define name="DC_POWER_OFF_LED" value="4"/>
-- <define name="DC_RELEASE" value="LED_ON" />
-- <define name="DC_PUSH" value="LED_OFF" />
-- </load>
--
print( "PictUAV Started " )
function print_status (frame)
local free = get_jpg_count()
print("#" .. frame )
end
-- switch to autofocus mode, pre-focus, then go to manual focus mode (locking focus there).
-- this helps to reduce the delay between the signal and taking the picture.
function pre_focus()
local focused = false
local try = 1
while not focused and try <= 5 do
print("Pre-focus attempt " .. try)
press("shoot_half")
sleep(2000)
if get_prop(18) > 0 then
print("Focused")
focused = true
set_aflock(1)
end
release("shoot_half")
sleep(500)
try = try + 1
end
return focused
end
-- set aperture/shooting mode to landscape
set_prop(6,3)
ap = get_prop(6)
print ("AF(3=inf,4=MF) "..ap)
-- Turn IS off
set_prop(145, 3)
-- set P mode
set_capture_mode(2)
sleep(1000)
-- Get focusing mode
p = get_prop(6)
if (p==3) then
print "Inf set."
else
-- on ixus230hs, no explicit MF.
-- so set to infinity (3)
while (p ~= 3) do
press "left"
release "left"
p = get_prop (6)
end
print "Focus set to infinity"
end
-- on ixus230hs set focus doesn't fail, but doesn't do anything.
set_focus(100)
print "set_focus 100"
sleep(2000)
f = get_focus
-- on ixus230hs set focus doesn't fail, but doesn't do anything.
set_focus( 65535 )
print "set_focus 65535"
sleep( 2000)
g = get_focus
if (f==g) then
print "set_focus inop"
-- if focusing until here didn't work, pre-focus using a different method.
pre_focus()
else
-- set_aflock(1) fails when the camera isn't knowingly focused.
print( "Setting aflock 1" )
sleep(1000)
set_aflock( 1 )
end
-- measuring the pulse on CHDK isn't necessarily that accurate, they can easily vary by 40ms.
-- Since I'm using a 100ms wait here, the variance for a shoot is around 140ms.
-- If the pulse is 250ms, then I should allow for anything down to 110.
-- For Paparazzi, taking a single picture using the button may not work because the timing may be very off
-- considering the 4Hz loop (this requires a change in the cam module for paparazzi).
print( "PictUAV loop " )
a = -1
repeat
a = get_usb_power(0)
-- a pulse is detected longer than ~610ms.
if (a>61) then
print( "shutting down " )
shut_down()
sleep(1500)
break
end
-- a pulse longer than ~100ms is detected.
if (a>10) then
frame = 1
shoot()
frame = frame + 1
end
sleep(100)
until ( false )
print( "PictUAV ended " )
| gpl-2.0 |
josetaas/YokiRaidCursor | Libs/Ace3/AceGUI-3.0/widgets/AceGUIWidget-Slider.lua | 9 | 8424 | --[[-----------------------------------------------------------------------------
Slider Widget
Graphical Slider, like, for Range values.
-------------------------------------------------------------------------------]]
local Type, Version = "Slider", 21
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local min, max, floor = math.min, math.max, math.floor
local tonumber, pairs = tonumber, pairs
-- WoW APIs
local PlaySound = PlaySound
local CreateFrame, UIParent = CreateFrame, UIParent
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: GameFontHighlightSmall
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
local function UpdateText(self)
local value = self.value or 0
if self.ispercent then
self.editbox:SetText(("%s%%"):format(floor(value * 1000 + 0.5) / 10))
else
self.editbox:SetText(floor(value * 100 + 0.5) / 100)
end
end
local function UpdateLabels(self)
local min, max = (self.min or 0), (self.max or 100)
if self.ispercent then
self.lowtext:SetFormattedText("%s%%", (min * 100))
self.hightext:SetFormattedText("%s%%", (max * 100))
else
self.lowtext:SetText(min)
self.hightext:SetText(max)
end
end
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function Control_OnEnter(frame)
frame.obj:Fire("OnEnter")
end
local function Control_OnLeave(frame)
frame.obj:Fire("OnLeave")
end
local function Frame_OnMouseDown(frame)
frame.obj.slider:EnableMouseWheel(true)
AceGUI:ClearFocus()
end
local function Slider_OnValueChanged(frame)
local self = frame.obj
if not frame.setup then
local newvalue = frame:GetValue()
if self.step and self.step > 0 then
local min_value = self.min or 0
newvalue = floor((newvalue - min_value) / self.step + 0.5) * self.step + min_value
end
if newvalue ~= self.value and not self.disabled then
self.value = newvalue
self:Fire("OnValueChanged", newvalue)
end
if self.value then
UpdateText(self)
end
end
end
local function Slider_OnMouseUp(frame)
local self = frame.obj
self:Fire("OnMouseUp", self.value)
end
local function Slider_OnMouseWheel(frame, v)
local self = frame.obj
if not self.disabled then
local value = self.value
if v > 0 then
value = min(value + (self.step or 1), self.max)
else
value = max(value - (self.step or 1), self.min)
end
self.slider:SetValue(value)
end
end
local function EditBox_OnEscapePressed(frame)
frame:ClearFocus()
end
local function EditBox_OnEnterPressed(frame)
local self = frame.obj
local value = frame:GetText()
if self.ispercent then
value = value:gsub('%%', '')
value = tonumber(value) / 100
else
value = tonumber(value)
end
if value then
PlaySound("igMainMenuOptionCheckBoxOn")
self.slider:SetValue(value)
self:Fire("OnMouseUp", value)
end
end
local function EditBox_OnEnter(frame)
frame:SetBackdropBorderColor(0.5, 0.5, 0.5, 1)
end
local function EditBox_OnLeave(frame)
frame:SetBackdropBorderColor(0.3, 0.3, 0.3, 0.8)
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self:SetWidth(200)
self:SetHeight(44)
self:SetDisabled(false)
self:SetIsPercent(nil)
self:SetSliderValues(0,100,1)
self:SetValue(0)
self.slider:EnableMouseWheel(false)
end,
-- ["OnRelease"] = nil,
["SetDisabled"] = function(self, disabled)
self.disabled = disabled
if disabled then
self.slider:EnableMouse(false)
self.label:SetTextColor(.5, .5, .5)
self.hightext:SetTextColor(.5, .5, .5)
self.lowtext:SetTextColor(.5, .5, .5)
--self.valuetext:SetTextColor(.5, .5, .5)
self.editbox:SetTextColor(.5, .5, .5)
self.editbox:EnableMouse(false)
self.editbox:ClearFocus()
else
self.slider:EnableMouse(true)
self.label:SetTextColor(1, .82, 0)
self.hightext:SetTextColor(1, 1, 1)
self.lowtext:SetTextColor(1, 1, 1)
--self.valuetext:SetTextColor(1, 1, 1)
self.editbox:SetTextColor(1, 1, 1)
self.editbox:EnableMouse(true)
end
end,
["SetValue"] = function(self, value)
self.slider.setup = true
self.slider:SetValue(value)
self.value = value
UpdateText(self)
self.slider.setup = nil
end,
["GetValue"] = function(self)
return self.value
end,
["SetLabel"] = function(self, text)
self.label:SetText(text)
end,
["SetSliderValues"] = function(self, min, max, step)
local frame = self.slider
frame.setup = true
self.min = min
self.max = max
self.step = step
frame:SetMinMaxValues(min or 0,max or 100)
UpdateLabels(self)
frame:SetValueStep(step or 1)
if self.value then
frame:SetValue(self.value)
end
frame.setup = nil
end,
["SetIsPercent"] = function(self, value)
self.ispercent = value
UpdateLabels(self)
UpdateText(self)
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local SliderBackdrop = {
bgFile = "Interface\\Buttons\\UI-SliderBar-Background",
edgeFile = "Interface\\Buttons\\UI-SliderBar-Border",
tile = true, tileSize = 8, edgeSize = 8,
insets = { left = 3, right = 3, top = 6, bottom = 6 }
}
local ManualBackdrop = {
bgFile = "Interface\\ChatFrame\\ChatFrameBackground",
edgeFile = "Interface\\ChatFrame\\ChatFrameBackground",
tile = true, edgeSize = 1, tileSize = 5,
}
local function Constructor()
local frame = CreateFrame("Frame", nil, UIParent)
frame:EnableMouse(true)
frame:SetScript("OnMouseDown", Frame_OnMouseDown)
local label = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
label:SetPoint("TOPLEFT")
label:SetPoint("TOPRIGHT")
label:SetJustifyH("CENTER")
label:SetHeight(15)
local slider = CreateFrame("Slider", nil, frame)
slider:SetOrientation("HORIZONTAL")
slider:SetHeight(15)
slider:SetHitRectInsets(0, 0, -10, 0)
slider:SetBackdrop(SliderBackdrop)
slider:SetThumbTexture("Interface\\Buttons\\UI-SliderBar-Button-Horizontal")
slider:SetPoint("TOP", label, "BOTTOM")
slider:SetPoint("LEFT", 3, 0)
slider:SetPoint("RIGHT", -3, 0)
slider:SetValue(0)
slider:SetScript("OnValueChanged",Slider_OnValueChanged)
slider:SetScript("OnEnter", Control_OnEnter)
slider:SetScript("OnLeave", Control_OnLeave)
slider:SetScript("OnMouseUp", Slider_OnMouseUp)
slider:SetScript("OnMouseWheel", Slider_OnMouseWheel)
local lowtext = slider:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
lowtext:SetPoint("TOPLEFT", slider, "BOTTOMLEFT", 2, 3)
local hightext = slider:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
hightext:SetPoint("TOPRIGHT", slider, "BOTTOMRIGHT", -2, 3)
local editbox = CreateFrame("EditBox", nil, frame)
editbox:SetAutoFocus(false)
editbox:SetFontObject(GameFontHighlightSmall)
editbox:SetPoint("TOP", slider, "BOTTOM")
editbox:SetHeight(14)
editbox:SetWidth(70)
editbox:SetJustifyH("CENTER")
editbox:EnableMouse(true)
editbox:SetBackdrop(ManualBackdrop)
editbox:SetBackdropColor(0, 0, 0, 0.5)
editbox:SetBackdropBorderColor(0.3, 0.3, 0.30, 0.80)
editbox:SetScript("OnEnter", EditBox_OnEnter)
editbox:SetScript("OnLeave", EditBox_OnLeave)
editbox:SetScript("OnEnterPressed", EditBox_OnEnterPressed)
editbox:SetScript("OnEscapePressed", EditBox_OnEscapePressed)
local widget = {
label = label,
slider = slider,
lowtext = lowtext,
hightext = hightext,
editbox = editbox,
alignoffset = 25,
frame = frame,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
slider.obj, editbox.obj = widget, widget
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type,Constructor,Version)
| mit |
jshackley/darkstar | scripts/globals/items/head_of_isleracea.lua | 36 | 1149 | -----------------------------------------
-- ID: 5965
-- Item: Head of Isleracea
-- Food Effect: 5 Min, All Races
-----------------------------------------
-- Agility 2
-- Vitality -4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5965);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 2);
target:addMod(MOD_VIT, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 2);
target:delMod(MOD_VIT, -4);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Dynamis-Xarcabard/mobs/Duke_Gomory.lua | 1 | 1255 | -----------------------------------
-- Area: Dynamis Xarcabard
-- MOB: Duke Gomory
-----------------------------------
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Xarcabard/TextIDs");
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer,ally)
local Animate_Trigger = GetServerVariable("[DynaXarcabard]Boss_Trigger");
if (mob:isInBattlefieldList() == false) then
mob:addInBattlefieldList();
Animate_Trigger = Animate_Trigger + 2;
SetServerVariable("[DynaXarcabard]Boss_Trigger",Animate_Trigger);
if (Animate_Trigger == 32767) then
SpawnMob(17330911); -- 142
SpawnMob(17330912); -- 143
SpawnMob(17330183); -- 177
SpawnMob(17330184); -- 178
activateAnimatedWeapon(); -- Change subanim of all animated weapon
end
end
if (Animate_Trigger == 32767) then
ally:messageSpecial(PRISON_OF_SOULS_HAS_SET_FREE);
end
end; | gpl-3.0 |
saeeidbeygi/Mrbot | plugins/youtube.lua | 644 | 1722 | do
local google_config = load_from_file('data/google.lua')
local function httpsRequest(url)
print(url)
local res,code = https.request(url)
if code ~= 200 then return nil end
return json:decode(res)
end
function get_yt_data (yt_code)
local url = 'https://www.googleapis.com/youtube/v3/videos?'
url = url .. 'id=' .. URL.escape(yt_code) .. '&part=snippet'
if google_config.api_keys then
local i = math.random(#google_config.api_keys)
local api_key = google_config.api_keys[i]
if api_key then
url = url.."&key="..api_key
end
end
return httpsRequest(url)
end
function send_youtube_data(data, receiver)
local title = data.title
local description = data.description
local uploader = data.channelTitle
local text = title..' ('..uploader..')\n'..description
local image_url = data.thumbnails.high.url or data.thumbnails.default.url
local cb_extra = {
receiver = receiver,
url = image_url
}
send_msg(receiver, text, send_photo_from_url_callback, cb_extra)
end
function run(msg, matches)
local yt_code = matches[1]
local data = get_yt_data(yt_code)
if data == nil or #data.items == 0 then
return "I didn't find info about that video."
end
local senddata = data.items[1].snippet
local receiver = get_receiver(msg)
send_youtube_data(senddata, receiver)
end
return {
description = "Sends YouTube info and image.",
usage = "",
patterns = {
"youtu.be/([_A-Za-z0-9-]+)",
"youtube.com/watch%?v=([_A-Za-z0-9-]+)",
},
run = run
}
end
| gpl-2.0 |
sugiartocokrowibowo/Algorithm-Implementations | Depth_First_Search/Lua/Yonaba/handlers/gridmap_handler.lua | 182 | 2356 | -- A grid map handler
-- Supports 4-directions and 8-directions moves
-- This handler is devised for 2d bounded grid where nodes are indexed
-- with a pair of (x, y) coordinates. It features straight (4-directions)
-- and diagonal (8-directions) moves.
local PATH = (...):gsub('handlers.gridmap_handler$','')
local Node = require (PATH .. '.utils.node')
-- Implements Node class (from node.lua)
function Node:initialize(x, y) self.x, self.y = x, y end
function Node:toString() return ('Node: x = %d, y = %d'):format(self.x, self.y) end
function Node:isEqualTo(n) return self.x == n.x and self.y == n.y end
-- Direction vectors for straight moves
local orthogonal = {
{x = 0, y = -1},
{x = -1, y = 0},
{x = 1, y = 0},
{x = 0, y = 1},
}
-- Direction vectors for diagonal moves
local diagonal = {
{x = -1, y = -1},
{x = 1, y = -1},
{x = -1, y = 1},
{x = 1, y = 1}
}
-- Checks of a given location is walkable on the grid.
-- Assumes 0 is walkable, any other value is unwalkable.
local function isWalkable(map, x, y) return map[y] and map[y][x] and map[y][x] == 0 end
local nodes = {}
-- Handler implementation
local handler = {}
-- Inits the search space
function handler.init(map)
handler.map = map
nodes = {}
for y, line in ipairs(map) do
for x in ipairs(line) do
table.insert(nodes, Node(x, y))
end
end
end
-- Returns an array of all nodes in the graph
function handler.getAllNodes() return nodes end
-- Returns a Node
function handler.getNode(x, y)
local h, w = #handler.map, #handler.map[1]
local k = (y - 1) * w + (x%w == 0 and w or x)
return nodes[k]
end
-- Returns manhattan distance between node a and node b
function handler.distance(a, b)
local dx, dy = a.x - b.x, a.y - b.y
return math.abs(dx) + math.abs(dy)
end
-- Returns an array of neighbors of node n
function handler.getNeighbors(n)
local neighbors = {}
for _, axis in ipairs(orthogonal) do
local x, y = n.x + axis.x, n.y + axis.y
if isWalkable(handler.map, x, y) then
table.insert(neighbors, handler.getNode(x, y))
end
end
if handler.diagonal then
for _, axis in ipairs(diagonal) do
local x, y = n.x + axis.x, n.y + axis.y
if isWalkable(handler.map, x, y) then
table.insert(neighbors, handler.getNode(x,y))
end
end
end
return neighbors
end
return handler
| mit |
jshackley/darkstar | scripts/zones/Abyssea-Konschtat/npcs/qm18.lua | 17 | 1737 | -----------------------------------
-- Zone: Abyssea-Konschtat
-- NPC: ???
-- Spawns: Kukulkan
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--[[
if (GetMobAction(16838872) == ACTION_NONE) then -- NM not already spawned from this
if (player:hasKeyItem(TATTERED_HIPPOGRYPH_WING) and player:hasKeyItem(CRACKED_WIVRE_HORN)
and player:hasKeyItem(MUCID_AHRIMAN_EYEBALL)) then -- I broke it into 3 lines at the 'and' because it was so long.
player:startEvent(1020, TATTERED_HIPPOGRYPH_WING, CRACKED_WIVRE_HORN, MUCID_AHRIMAN_EYEBALL); -- Ask if player wants to use KIs
else
player:startEvent(1021, TATTERED_HIPPOGRYPH_WING, CRACKED_WIVRE_HORN, MUCID_AHRIMAN_EYEBALL); -- Do not ask, because player is missing at least 1.
end
end
]]
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 1020 and option == 1) then
SpawnMob(16838872):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:delKeyItem(TATTERED_HIPPOGRYPH_WING);
player:delKeyItem(CRACKED_WIVRE_HORN);
player:delKeyItem(MUCID_AHRIMAN_EYEBALL);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Tahrongi_Canyon/Zone.lua | 17 | 4501 | -----------------------------------
--
-- Zone: Tahrongi_Canyon (117)
--
-----------------------------------
package.loaded["scripts/zones/Tahrongi_Canyon/TextIDs"] = nil;
package.loaded["scripts/globals/chocobo_digging"] = nil;
-----------------------------------
require("scripts/zones/Tahrongi_Canyon/TextIDs");
require("scripts/globals/icanheararainbow");
require("scripts/globals/zone");
require("scripts/globals/chocobo_digging");
-----------------------------------
-- Chocobo Digging vars
-----------------------------------
local itemMap = {
-- itemid, abundance, requirement
{ 880, 224, DIGREQ_NONE },
{ 887, 39, DIGREQ_NONE },
{ 645, 14, DIGREQ_NONE },
{ 893, 105, DIGREQ_NONE },
{ 737, 17, DIGREQ_NONE },
{ 643, 64, DIGREQ_NONE },
{ 17296, 122, DIGREQ_NONE },
{ 942, 6, DIGREQ_NONE },
{ 642, 58, DIGREQ_NONE },
{ 864, 22, DIGREQ_NONE },
{ 843, 4, DIGREQ_NONE },
{ 4096, 100, DIGREQ_NONE }, -- all crystals
{ 656, 95, DIGREQ_BURROW },
{ 749, 26, DIGREQ_BURROW },
{ 751, 33, DIGREQ_BURROW },
{ 750, 89, DIGREQ_BURROW },
{ 902, 6, DIGREQ_BORE },
{ 886, 3, DIGREQ_BORE },
{ 867, 3, DIGREQ_BORE },
{ 1587, 19, DIGREQ_BORE },
{ 888, 25, DIGREQ_BORE },
{ 1586, 8, DIGREQ_BORE },
{ 885, 10, DIGREQ_BORE },
{ 866, 3, DIGREQ_BORE },
{ 4570, 10, DIGREQ_MODIFIER },
{ 4487, 11, DIGREQ_MODIFIER },
{ 4409, 12, DIGREQ_MODIFIER },
{ 1188, 10, DIGREQ_MODIFIER },
{ 4532, 12, DIGREQ_MODIFIER },
};
local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED };
-----------------------------------
-- onChocoboDig
-----------------------------------
function onChocoboDig(player, precheck)
return chocoboDig(player, itemMap, precheck, messageArray);
end;
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local manuals = {17257075,17257076,17257077};
SetFieldManual(manuals);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn( player, prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos( 442.781, -1.641, -40.144, 160);
end
if (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow
cs = 0x0023;
elseif (player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1) then
cs = 0x0025;
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter( player, region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate( player, csid, option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0023) then
lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow
elseif (csid == 0x0025) then
if (player:getPreviousZone() == 116 or player:getPreviousZone() == 118) then
player:updateEvent(0,0,0,0,0,7);
elseif (player:getPreviousZone() == 198) then
player:updateEvent(0,0,0,0,0,6);
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish( player, csid, option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0023) then
lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow
end
end; | gpl-3.0 |
Mizugola/MeltingSaga | engine/Lib/Extlibs/binser.lua | 5 | 25566 | -- binser.lua
--[[
Copyright (c) 2016 Calvin Rose
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 assert = assert
local error = error
local select = select
local pairs = pairs
local getmetatable = getmetatable
local setmetatable = setmetatable
local type = type
local loadstring = loadstring or load
local concat = table.concat
local char = string.char
local byte = string.byte
local format = string.format
local sub = string.sub
local dump = string.dump
local floor = math.floor
local frexp = math.frexp
local unpack = unpack or table.unpack
-- Lua 5.3 frexp polyfill
-- From https://github.com/excessive/cpml/blob/master/modules/utils.lua
if not frexp then
local log, abs, floor = math.log, math.abs, math.floor
local log2 = log(2)
frexp = function(x)
if x == 0 then return 0, 0 end
local e = floor(log(abs(x)) / log2 + 1)
return x / 2 ^ e, e
end
end
local function pack(...)
return {...}, select("#", ...)
end
local function not_array_index(x, len)
return type(x) ~= "number" or x < 1 or x > len or x ~= floor(x)
end
local function type_check(x, tp, name)
assert(type(x) == tp,
format("Expected parameter %q to be of type %q.", name, tp))
end
local bigIntSupport = false
local isInteger
if math.type then -- Detect Lua 5.3
local mtype = math.type
bigIntSupport = loadstring[[
local char = string.char
return function(n)
local nn = n < 0 and -(n + 1) or n
local b1 = nn // 0x100000000000000
local b2 = nn // 0x1000000000000 % 0x100
local b3 = nn // 0x10000000000 % 0x100
local b4 = nn // 0x100000000 % 0x100
local b5 = nn // 0x1000000 % 0x100
local b6 = nn // 0x10000 % 0x100
local b7 = nn // 0x100 % 0x100
local b8 = nn % 0x100
if n < 0 then
b1, b2, b3, b4 = 0xFF - b1, 0xFF - b2, 0xFF - b3, 0xFF - b4
b5, b6, b7, b8 = 0xFF - b5, 0xFF - b6, 0xFF - b7, 0xFF - b8
end
return char(212, b1, b2, b3, b4, b5, b6, b7, b8)
end]]()
isInteger = function(x)
return mtype(x) == 'integer'
end
else
isInteger = function(x)
return floor(x) == x
end
end
-- Copyright (C) 2012-2015 Francois Perrad.
-- number serialization code modified from https://github.com/fperrad/lua-MessagePack
-- Encode a number as a big-endian ieee-754 double, big-endian signed 64 bit integer, or a small integer
local function number_to_str(n)
if isInteger(n) then -- int
if n <= 100 and n >= -27 then -- 1 byte, 7 bits of data
return char(n + 27)
elseif n <= 8191 and n >= -8192 then -- 2 bytes, 14 bits of data
n = n + 8192
return char(128 + (floor(n / 0x100) % 0x100), n % 0x100)
elseif bigIntSupport then
return bigIntSupport(n)
end
end
local sign = 0
if n < 0.0 then
sign = 0x80
n = -n
end
local m, e = frexp(n) -- mantissa, exponent
if m ~= m then
return char(203, 0xFF, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
elseif m == 1/0 then
if sign == 0 then
return char(203, 0x7F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
else
return char(203, 0xFF, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
end
end
e = e + 0x3FE
if e < 1 then -- denormalized numbers
m = m * 2 ^ (52 + e)
e = 0
else
m = (m * 2 - 1) * 2 ^ 52
end
return char(203,
sign + floor(e / 0x10),
(e % 0x10) * 0x10 + floor(m / 0x1000000000000),
floor(m / 0x10000000000) % 0x100,
floor(m / 0x100000000) % 0x100,
floor(m / 0x1000000) % 0x100,
floor(m / 0x10000) % 0x100,
floor(m / 0x100) % 0x100,
m % 0x100)
end
-- Copyright (C) 2012-2015 Francois Perrad.
-- number deserialization code also modified from https://github.com/fperrad/lua-MessagePack
local function number_from_str(str, index)
local b = byte(str, index)
if not b then error("Expected more bytes of input.") end
if b < 128 then
return b - 27, index + 1
elseif b < 192 then
local b2 = byte(str, index + 1)
if not b2 then error("Expected more bytes of input.") end
return b2 + 0x100 * (b - 128) - 8192, index + 2
end
local b1, b2, b3, b4, b5, b6, b7, b8 = byte(str, index + 1, index + 8)
if (not b1) or (not b2) or (not b3) or (not b4) or
(not b5) or (not b6) or (not b7) or (not b8) then
error("Expected more bytes of input.")
end
if b == 212 then
local flip = b1 >= 128
if flip then -- negative
b1, b2, b3, b4 = 0xFF - b1, 0xFF - b2, 0xFF - b3, 0xFF - b4
b5, b6, b7, b8 = 0xFF - b5, 0xFF - b6, 0xFF - b7, 0xFF - b8
end
local n = ((((((b1 * 0x100 + b2) * 0x100 + b3) * 0x100 + b4) *
0x100 + b5) * 0x100 + b6) * 0x100 + b7) * 0x100 + b8
if flip then
return (-n) - 1, index + 9
else
return n, index + 9
end
end
if b ~= 203 then
error("Expected number")
end
local sign = b1 > 0x7F and -1 or 1
local e = (b1 % 0x80) * 0x10 + floor(b2 / 0x10)
local m = ((((((b2 % 0x10) * 0x100 + b3) * 0x100 + b4) * 0x100 + b5) * 0x100 + b6) * 0x100 + b7) * 0x100 + b8
local n
if e == 0 then
if m == 0 then
n = sign * 0.0
else
n = sign * (m / 2 ^ 52) * 2 ^ -1022
end
elseif e == 0x7FF then
if m == 0 then
n = sign * (1/0)
else
n = 0.0/0.0
end
else
n = sign * (1.0 + m / 2 ^ 52) * 2 ^ (e - 0x3FF)
end
return n, index + 9
end
local function newbinser()
-- unique table key for getting next value
local NEXT = {}
local CTORSTACK = {}
-- NIL = 202
-- FLOAT = 203
-- TRUE = 204
-- FALSE = 205
-- STRING = 206
-- TABLE = 207
-- REFERENCE = 208
-- CONSTRUCTOR = 209
-- FUNCTION = 210
-- RESOURCE = 211
-- INT64 = 212
-- TABLE WITH META = 213
local mts = {}
local ids = {}
local serializers = {}
local deserializers = {}
local resources = {}
local resources_by_name = {}
local types = {}
types["nil"] = function(x, visited, accum)
accum[#accum + 1] = "\202"
end
function types.number(x, visited, accum)
accum[#accum + 1] = number_to_str(x)
end
function types.boolean(x, visited, accum)
accum[#accum + 1] = x and "\204" or "\205"
end
function types.string(x, visited, accum)
local alen = #accum
if visited[x] then
accum[alen + 1] = "\208"
accum[alen + 2] = number_to_str(visited[x])
else
visited[x] = visited[NEXT]
visited[NEXT] = visited[NEXT] + 1
accum[alen + 1] = "\206"
accum[alen + 2] = number_to_str(#x)
accum[alen + 3] = x
end
end
local function check_custom_type(x, visited, accum)
local res = resources[x]
if res then
accum[#accum + 1] = "\211"
types[type(res)](res, visited, accum)
return true
end
local mt = getmetatable(x)
local id = mt and ids[mt]
if id then
local constructing = visited[CTORSTACK]
if constructing[x] then
error("Infinite loop in constructor.")
end
constructing[x] = true
accum[#accum + 1] = "\209"
types[type(id)](id, visited, accum)
local args, len = pack(serializers[id](x))
accum[#accum + 1] = number_to_str(len)
for i = 1, len do
local arg = args[i]
types[type(arg)](arg, visited, accum)
end
visited[x] = visited[NEXT]
visited[NEXT] = visited[NEXT] + 1
-- We finished constructing
constructing[x] = nil
return true
end
end
function types.userdata(x, visited, accum)
if visited[x] then
accum[#accum + 1] = "\208"
accum[#accum + 1] = number_to_str(visited[x])
else
if check_custom_type(x, visited, accum) then return end
error("Cannot serialize this userdata.")
end
end
function types.table(x, visited, accum)
if visited[x] then
accum[#accum + 1] = "\208"
accum[#accum + 1] = number_to_str(visited[x])
else
if check_custom_type(x, visited, accum) then return end
visited[x] = visited[NEXT]
visited[NEXT] = visited[NEXT] + 1
local xlen = #x
local mt = getmetatable(x)
if mt then
accum[#accum + 1] = "\213"
types.table(mt, visited, accum)
else
accum[#accum + 1] = "\207"
end
accum[#accum + 1] = number_to_str(xlen)
for i = 1, xlen do
local v = x[i]
types[type(v)](v, visited, accum)
end
local key_count = 0
for k in pairs(x) do
if not_array_index(k, xlen) then
key_count = key_count + 1
end
end
accum[#accum + 1] = number_to_str(key_count)
for k, v in pairs(x) do
if not_array_index(k, xlen) then
types[type(k)](k, visited, accum)
types[type(v)](v, visited, accum)
end
end
end
end
types["function"] = function(x, visited, accum)
if visited[x] then
accum[#accum + 1] = "\208"
accum[#accum + 1] = number_to_str(visited[x])
else
if check_custom_type(x, visited, accum) then return end
visited[x] = visited[NEXT]
visited[NEXT] = visited[NEXT] + 1
local str = dump(x)
accum[#accum + 1] = "\210"
accum[#accum + 1] = number_to_str(#str)
accum[#accum + 1] = str
end
end
types.cdata = function(x, visited, accum)
if visited[x] then
accum[#accum + 1] = "\208"
accum[#accum + 1] = number_to_str(visited[x])
else
if check_custom_type(x, visited, #accum) then return end
error("Cannot serialize this cdata.")
end
end
types.thread = function() error("Cannot serialize threads.") end
local function deserialize_value(str, index, visited)
local t = byte(str, index)
if not t then return nil, index end
if t < 128 then
return t - 27, index + 1
elseif t < 192 then
local b2 = byte(str, index + 1)
if not b2 then error("Expected more bytes of input.") end
return b2 + 0x100 * (t - 128) - 8192, index + 2
elseif t == 202 then
return nil, index + 1
elseif t == 203 or t == 212 then
return number_from_str(str, index)
elseif t == 204 then
return true, index + 1
elseif t == 205 then
return false, index + 1
elseif t == 206 then
local length, dataindex = number_from_str(str, index + 1)
local nextindex = dataindex + length
if not (length >= 0) then error("Bad string length") end
if #str < nextindex - 1 then error("Expected more bytes of string") end
local substr = sub(str, dataindex, nextindex - 1)
visited[#visited + 1] = substr
return substr, nextindex
elseif t == 207 or t == 213 then
local mt, count, nextindex
local ret = {}
visited[#visited + 1] = ret
nextindex = index + 1
if t == 213 then
mt, nextindex = deserialize_value(str, nextindex, visited)
if type(mt) ~= "table" then error("Expected table metatable") end
end
count, nextindex = number_from_str(str, nextindex)
for i = 1, count do
local oldindex = nextindex
ret[i], nextindex = deserialize_value(str, nextindex, visited)
if nextindex == oldindex then error("Expected more bytes of input.") end
end
count, nextindex = number_from_str(str, nextindex)
for i = 1, count do
local k, v
local oldindex = nextindex
k, nextindex = deserialize_value(str, nextindex, visited)
if nextindex == oldindex then error("Expected more bytes of input.") end
oldindex = nextindex
v, nextindex = deserialize_value(str, nextindex, visited)
if nextindex == oldindex then error("Expected more bytes of input.") end
if k == nil then error("Can't have nil table keys") end
ret[k] = v
end
if mt then setmetatable(ret, mt) end
return ret, nextindex
elseif t == 208 then
local ref, nextindex = number_from_str(str, index + 1)
return visited[ref], nextindex
elseif t == 209 then
local count
local name, nextindex = deserialize_value(str, index + 1, visited)
count, nextindex = number_from_str(str, nextindex)
local args = {}
for i = 1, count do
local oldindex = nextindex
args[i], nextindex = deserialize_value(str, nextindex, visited)
if nextindex == oldindex then error("Expected more bytes of input.") end
end
if not name or not deserializers[name] then
error(("Cannot deserialize class '%s'"):format(tostring(name)))
end
local ret = deserializers[name](unpack(args))
visited[#visited + 1] = ret
return ret, nextindex
elseif t == 210 then
local length, dataindex = number_from_str(str, index + 1)
local nextindex = dataindex + length
if not (length >= 0) then error("Bad string length") end
if #str < nextindex - 1 then error("Expected more bytes of string") end
local ret = loadstring(sub(str, dataindex, nextindex - 1))
visited[#visited + 1] = ret
return ret, nextindex
elseif t == 211 then
local resname, nextindex = deserialize_value(str, index + 1, visited)
if resname == nil then error("Got nil resource name") end
local res = resources_by_name[resname]
if res == nil then
error(("No resources found for name '%s'"):format(tostring(resname)))
end
return res, nextindex
else
error("Could not deserialize type byte " .. t .. ".")
end
end
local function serialize(...)
local visited = {[NEXT] = 1, [CTORSTACK] = {}}
local accum = {}
for i = 1, select("#", ...) do
local x = select(i, ...)
types[type(x)](x, visited, accum)
end
return concat(accum)
end
local function make_file_writer(file)
return setmetatable({}, {
__newindex = function(_, _, v)
file:write(v)
end
})
end
local function serialize_to_file(path, mode, ...)
local file, err = io.open(path, mode)
assert(file, err)
local visited = {[NEXT] = 1, [CTORSTACK] = {}}
local accum = make_file_writer(file)
for i = 1, select("#", ...) do
local x = select(i, ...)
types[type(x)](x, visited, accum)
end
-- flush the writer
file:flush()
file:close()
end
local function writeFile(path, ...)
return serialize_to_file(path, "wb", ...)
end
local function appendFile(path, ...)
return serialize_to_file(path, "ab", ...)
end
local function deserialize(str, index)
assert(type(str) == "string", "Expected string to deserialize.")
local vals = {}
index = index or 1
local visited = {}
local len = 0
local val
while true do
local nextindex
val, nextindex = deserialize_value(str, index, visited)
if nextindex > index then
len = len + 1
vals[len] = val
index = nextindex
else
break
end
end
return vals, len
end
local function deserializeN(str, n, index)
assert(type(str) == "string", "Expected string to deserialize.")
n = n or 1
assert(type(n) == "number", "Expected a number for parameter n.")
assert(n > 0 and floor(n) == n, "N must be a poitive integer.")
local vals = {}
index = index or 1
local visited = {}
local len = 0
local val
while len < n do
local nextindex
val, nextindex = deserialize_value(str, index, visited)
if nextindex > index then
len = len + 1
vals[len] = val
index = nextindex
else
break
end
end
vals[len + 1] = index
return unpack(vals, 1, n + 1)
end
local function readFile(path)
local file, err = io.open(path, "rb")
assert(file, err)
local str = file:read("*all")
file:close()
return deserialize(str)
end
-- Resources
local function registerResource(resource, name)
type_check(name, "string", "name")
assert(not resources[resource],
"Resource already registered.")
assert(not resources_by_name[name],
format("Resource %q already exists.", name))
resources_by_name[name] = resource
resources[resource] = name
return resource
end
local function unregisterResource(name)
type_check(name, "string", "name")
assert(resources_by_name[name], format("Resource %q does not exist.", name))
local resource = resources_by_name[name]
resources_by_name[name] = nil
resources[resource] = nil
return resource
end
-- Templating
local function normalize_template(template)
local ret = {}
for i = 1, #template do
ret[i] = template[i]
end
local non_array_part = {}
-- The non-array part of the template (nested templates) have to be deterministic, so they are sorted.
-- This means that inherently non deterministicly sortable keys (tables, functions) should NOT be used
-- in templates. Looking for way around this.
for k in pairs(template) do
if not_array_index(k, #template) then
non_array_part[#non_array_part + 1] = k
end
end
table.sort(non_array_part)
for i = 1, #non_array_part do
local name = non_array_part[i]
ret[#ret + 1] = {name, normalize_template(template[name])}
end
return ret
end
local function templatepart_serialize(part, argaccum, x, len)
local extras = {}
local extracount = 0
for k, v in pairs(x) do
extras[k] = v
extracount = extracount + 1
end
for i = 1, #part do
local name
if type(part[i]) == "table" then
name = part[i][1]
len = templatepart_serialize(part[i][2], argaccum, x[name], len)
else
name = part[i]
len = len + 1
argaccum[len] = x[part[i]]
end
if extras[name] ~= nil then
extracount = extracount - 1
extras[name] = nil
end
end
if extracount > 0 then
argaccum[len + 1] = extras
else
argaccum[len + 1] = nil
end
return len + 1
end
local function templatepart_deserialize(ret, part, values, vindex)
for i = 1, #part do
local name = part[i]
if type(name) == "table" then
local newret = {}
ret[name[1]] = newret
vindex = templatepart_deserialize(newret, name[2], values, vindex)
else
ret[name] = values[vindex]
vindex = vindex + 1
end
end
local extras = values[vindex]
if extras then
for k, v in pairs(extras) do
ret[k] = v
end
end
return vindex + 1
end
local function template_serializer_and_deserializer(metatable, template)
return function(x)
local argaccum = {}
local len = templatepart_serialize(template, argaccum, x, 0)
return unpack(argaccum, 1, len)
end, function(...)
local ret = {}
local args = {...}
templatepart_deserialize(ret, template, args, 1)
return setmetatable(ret, metatable)
end
end
-- Used to serialize classes withh custom serializers and deserializers.
-- If no _serialize or _deserialize (or no _template) value is found in the
-- metatable, then the metatable is registered as a resources.
local function register(metatable, name, serialize, deserialize)
if type(metatable) == "table" then
name = name or metatable.name
serialize = serialize or metatable._serialize
deserialize = deserialize or metatable._deserialize
if (not serialize) or (not deserialize) then
if metatable._template then
-- Register as template
local t = normalize_template(metatable._template)
serialize, deserialize = template_serializer_and_deserializer(metatable, t)
else
-- Register the metatable as a resource. This is semantically
-- similar and more flexible (handles cycles).
registerResource(metatable, name)
return
end
end
elseif type(metatable) == "string" then
name = name or metatable
end
type_check(name, "string", "name")
type_check(serialize, "function", "serialize")
type_check(deserialize, "function", "deserialize")
assert((not ids[metatable]) and (not resources[metatable]),
"Metatable already registered.")
assert((not mts[name]) and (not resources_by_name[name]),
("Name %q already registered."):format(name))
mts[name] = metatable
ids[metatable] = name
serializers[name] = serialize
deserializers[name] = deserialize
return metatable
end
local function unregister(item)
local name, metatable
if type(item) == "string" then -- assume name
name, metatable = item, mts[item]
else -- assume metatable
name, metatable = ids[item], item
end
type_check(name, "string", "name")
mts[name] = nil
if (metatable) then
resources[metatable] = nil
ids[metatable] = nil
end
serializers[name] = nil
deserializers[name] = nil
resources_by_name[name] = nil;
return metatable
end
local function registerClass(class, name)
name = name or class.name
if class.__instanceDict then -- middleclass
register(class.__instanceDict, name)
else -- assume 30log or similar library
register(class, name)
end
return class
end
return {
-- aliases
s = serialize,
d = deserialize,
dn = deserializeN,
r = readFile,
w = writeFile,
a = appendFile,
serialize = serialize,
deserialize = deserialize,
deserializeN = deserializeN,
readFile = readFile,
writeFile = writeFile,
appendFile = appendFile,
register = register,
unregister = unregister,
registerResource = registerResource,
unregisterResource = unregisterResource,
registerClass = registerClass,
newbinser = newbinser
}
end
return newbinser()
| mit |
Victek/wrt1900ac-aa | veriksystems/luci-0.11/modules/admin-mini/luasrc/model/cbi/mini/luci.lua | 11 | 1381 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
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
$Id: luci.lua 5813 2010-03-13 20:13:41Z acinonyx $
]]--
require "luci.config"
local fs = require "nixio.fs"
m = Map("luci", translate("Web <abbr title=\"User Interface\">UI</abbr>"), translate("Here you can customize the settings and the functionality of <abbr title=\"Lua Configuration Interface\">LuCI</abbr>."))
-- force reload of global luci config namespace to reflect the changes
function m.commit_handler(self)
package.loaded["luci.config"] = nil
require "luci.config"
end
c = m:section(NamedSection, "main", "core", translate("General"))
l = c:option(ListValue, "lang", translate("Language"))
l:value("auto")
local i18ndir = luci.i18n.i18ndir .. "base."
for k, v in luci.util.kspairs(luci.config.languages) do
local file = i18ndir .. k:gsub("_", "-")
if k:sub(1, 1) ~= "." and fs.access(file .. ".lmo") then
l:value(k, v)
end
end
t = c:option(ListValue, "mediaurlbase", translate("Design"))
for k, v in pairs(luci.config.themes) do
if k:sub(1, 1) ~= "." then
t:value(v, k)
end
end
return m
| gpl-2.0 |
Shrike78/Shilke2D | Samples/movieclip.lua | 1 | 3012 | -- uncomment to debug touch and keyboard callbacks. works with Mobdebug
--__DEBUG_CALLBACKS__ = true
--By default (0,0) is topleft point and y is from top to bottom. Defining this allows to
--set (0,0) as bottomleft point and having y from bottom to top.
--__USE_SIMULATION_COORDS__ = true
--include Shilke2D lib
require("Shilke2D/include")
local WIDTH,HEIGHT = 1024,680
local FPS = 60
--the working dir of the application
IO.setWorkingDir("Assets")
--Setup is called once at the beginning of the application, just after Shilke2D initialization phase
--here everything should be set up for the following execution
function setup()
local shilke = Shilke2D.current
--the stage is the base displayObjContainer of the scene. Everything need to be connected to the
--stage to be displayed. The stage is a particular displayObjContainer because it can't be moved,scaled
--or anyway transformed geometrically.
local stage = shilke.stage
--show as overlay fps and memory allocation
shilke:showStats(true)
--if not set, the default color is (0,0,0)
stage:setBackgroundColor(128,128,128)
--the juggler is the animator of all the animated objs, like
--movieclips, tweens or other jugglers too.
juggler = shilke.juggler
--it's possible to load an image and automatically create sub regions if the regions
--have all the same size and the margin and spacign between the regions are known
--it's also possible to specify a prefix and a padding to format the textures name
local atlas = TextureAtlas.fromTexture("numbers.png",32,32,0,0,"numbers_",2)
--MovieClip inherits from Image and is the most simple way to put an animated obj, with a fixed frametime,
--into the screen. It's initialized with the sequence of textures that will compose the animation and with
--the animation fps value. Must be added to a juggler to be player and can be played starting from
--a frame by choice and for an option number of times. negative values (like in the example) means
--"infinite loop"
mc = MovieClip(atlas:getTextures(),12)
mc:setPosition(WIDTH/2,HEIGHT/2)
stage:addChild(mc)
juggler:add(mc)
mc:play(1,-1)
end
--update is called once per frame and allows to logically update status of objects
function update(elapsedTime)
end
--called when no hittable object is hit by the current touch. By default each object added to the stage
--is hittable. a displayObjContainer by default forward the hit test to the children, unless is requested to handle
--the hit test directly. If a displayObjContainer is set as "not touchable" all his children will not be touchable.
--Therefore if the stage is set as not touchable every touch is redirected here
function touched(touch)
if touch.state == Touch.BEGAN then
--the order of frames is inverted each time the screen is 'touched'
mc:stop()
mc:invertFrames()
mc:play(1,-1)
end
end
--shilke2D initialization. it requires width, height and fps. Optional a scale value for x / y.
shilke2D = Shilke2D(WIDTH,HEIGHT,FPS)
shilke2D:start() | mit |
Ombridride/minetest-minetestforfun-server | mods/homedecor_modpack/homedecor/bathroom_sanitation.lua | 7 | 8096 | local S = homedecor.gettext
local toilet_sbox = {
type = "fixed",
fixed = { -6/16, -8/16, -8/16, 6/16, 9/16, 8/16 },
}
local toilet_cbox = {
type = "fixed",
fixed = {
{-6/16, -8/16, -8/16, 6/16, 1/16, 8/16 },
{-6/16, -8/16, 4/16, 6/16, 9/16, 8/16 }
}
}
homedecor.register("toilet", {
description = S("Toilet"),
mesh = "homedecor_toilet_closed.obj",
tiles = {
"homedecor_marble.png^[colorize:#ffffff:175",
"homedecor_marble.png^[colorize:#ffffff:175",
"homedecor_marble.png^[colorize:#ffffff:175",
"homedecor_generic_metal_black.png^[brighten"
},
selection_box = toilet_sbox,
node_box = toilet_cbox,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
on_punch = function (pos, node, puncher)
node.name = "homedecor:toilet_open"
minetest.set_node(pos, node)
end
})
homedecor.register("toilet_open", {
mesh = "homedecor_toilet_open.obj",
tiles = {
"homedecor_marble.png^[colorize:#ffffff:175",
"homedecor_marble.png^[colorize:#ffffff:175",
"homedecor_marble.png^[colorize:#ffffff:175",
"default_water.png",
"homedecor_generic_metal_black.png^[brighten"
},
selection_box = toilet_sbox,
collision_box = toilet_cbox,
drop = "homedecor:toilet",
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
on_punch = function (pos, node, puncher)
node.name = "homedecor:toilet"
minetest.set_node(pos, node)
minetest.sound_play("homedecor_toilet_flush", {
pos=pos,
max_hear_distance = 5,
gain = 1,
})
end
})
-- toilet paper :-)
local tp_cbox = {
type = "fixed",
fixed = { -0.25, 0.125, 0.0625, 0.1875, 0.4375, 0.5 }
}
homedecor.register("toilet_paper", {
description = S("Toilet paper"),
mesh = "homedecor_toilet_paper.obj",
tiles = {
"homedecor_generic_quilted_paper.png",
"default_wood.png"
},
inventory_image = "homedecor_toilet_paper_inv.png",
selection_box = tp_cbox,
walkable = false,
groups = {snappy=3,oddly_breakable_by_hand=3},
sounds = default.node_sound_defaults(),
})
--Sink
local sink_cbox = {
type = "fixed",
fixed = { -5/16, -8/16, 1/16, 5/16, 8/16, 8/16 }
}
homedecor.register("sink", {
description = S("Bathroom Sink"),
mesh = "homedecor_bathroom_sink.obj",
tiles = {
"homedecor_marble.png^[colorize:#ffffff:175",
"homedecor_marble.png",
"default_water.png"
},
inventory_image="homedecor_bathroom_sink_inv.png",
selection_box = sink_cbox,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
node_box = {
type = "fixed",
fixed = {
{ -5/16, 5/16, 1/16, -4/16, 8/16, 8/16 },
{ 5/16, 5/16, 1/16, 4/16, 8/16, 8/16 },
{ -5/16, 5/16, 1/16, 5/16, 8/16, 2/16 },
{ -5/16, 5/16, 6/16, 5/16, 8/16, 8/16 },
{ -4/16, -8/16, 1/16, 4/16, 5/16, 6/16 }
}
},
on_destruct = function(pos)
homedecor.stop_particle_spawner({x=pos.x, y=pos.y+1, z=pos.z})
end
})
--Taps
local function taps_on_rightclick(pos, node, clicker)
local below = minetest.get_node_or_nil({x=pos.x, y=pos.y-1, z=pos.z})
if below and
below.name == "homedecor:shower_tray" or
below.name == "homedecor:sink" or
below.name == "homedecor:kitchen_cabinet_with_sink" then
local particledef = {
outlet = { x = 0, y = -0.44, z = 0.28 },
velocity_x = { min = -0.1, max = 0.1 },
velocity_y = -0.3,
velocity_z = { min = -0.1, max = 0 },
spread = 0
}
homedecor.start_particle_spawner(pos, node, particledef, "homedecor_faucet")
end
end
homedecor.register("taps", {
description = S("Bathroom taps/faucet"),
mesh = "homedecor_bathroom_faucet.obj",
tiles = {
"homedecor_generic_metal_black.png^[brighten",
"homedecor_generic_metal_bright.png",
"homedecor_generic_metal_black.png^[colorize:#ffffff:200",
"homedecor_generic_metal_bright.png"
},
inventory_image = "3dforniture_taps_inv.png",
wield_image = "3dforniture_taps_inv.png",
selection_box = {
type = "fixed",
fixed = { -4/16, -7/16, 4/16, 4/16, -4/16, 8/16 },
},
walkable = false,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
on_rightclick = taps_on_rightclick,
on_destruct = homedecor.stop_particle_spawner,
on_rotate = screwdriver.disallow
})
homedecor.register("taps_brass", {
description = S("Bathroom taps/faucet (brass)"),
mesh = "homedecor_bathroom_faucet.obj",
tiles = {
"homedecor_generic_metal_brass.png",
"homedecor_generic_metal_brass.png",
"homedecor_generic_metal_black.png^[colorize:#ffffff:200",
"homedecor_generic_metal_brass.png"
},
inventory_image = "3dforniture_taps_brass_inv.png",
wield_image = "3dforniture_taps_brass_inv.png",
selection_box = {
type = "fixed",
fixed = { -4/16, -7/16, 4/16, 4/16, -4/16, 8/16 },
},
walkable = false,
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
on_rightclick = taps_on_rightclick,
on_destruct = homedecor.stop_particle_spawner,
on_rotate = screwdriver.disallow
})
--Shower Tray
homedecor.register("shower_tray", {
description = S("Shower Tray"),
tiles = {
"forniture_marble_base_ducha_top.png",
"homedecor_marble.png"
},
node_box = {
type = "fixed",
fixed = {
{ -0.5, -0.5, -0.5, 0.5, -0.45, 0.5 },
{ -0.5, -0.45, -0.5, 0.5, -0.4, -0.45 },
{ -0.5, -0.45, 0.45, 0.5, -0.4, 0.5 },
{ -0.5, -0.45, -0.45, -0.45, -0.4, 0.45 },
{ 0.45, -0.45, -0.45, 0.5, -0.4, 0.45 }
},
},
selection_box = homedecor.nodebox.slab_y(0.1),
groups = {cracky=2},
sounds = default.node_sound_stone_defaults(),
on_destruct = function(pos)
homedecor.stop_particle_spawner({x=pos.x, y=pos.y+2, z=pos.z}) -- the showerhead
homedecor.stop_particle_spawner({x=pos.x, y=pos.y+1, z=pos.z}) -- the taps, if any
end
})
--Shower Head
local sh_cbox = {
type = "fixed",
fixed = { -0.2, -0.4, -0.05, 0.2, 0.1, 0.5 }
}
homedecor.register("shower_head", {
drawtype = "mesh",
mesh = "homedecor_shower_head.obj",
tiles = {
"homedecor_generic_metal_black.png^[brighten",
"homedecor_shower_head.png"
},
inventory_image = "homedecor_shower_head_inv.png",
description = "Shower Head",
groups = {snappy=3},
selection_box = sh_cbox,
walkable = false,
on_rotate = screwdriver.disallow,
on_rightclick = function (pos, node, clicker)
local below = minetest.get_node_or_nil({x=pos.x, y=pos.y-2.0, z=pos.z})
if below and below.name == "homedecor:shower_tray" then
local particledef = {
outlet = { x = 0, y = -0.42, z = 0.1 },
velocity_x = { min = -0.15, max = 0.15 },
velocity_y = -2,
velocity_z = { min = -0.3, max = 0.1 },
spread = 0.12
}
homedecor.start_particle_spawner(pos, node, particledef, "homedecor_shower")
end
end,
on_destruct = function(pos)
homedecor.stop_particle_spawner(pos)
end
})
local bs_cbox = {
type = "fixed",
fixed = { -8/16, -8/16, 1/16, 8/16, 8/16, 8/16 }
}
homedecor.register("bathroom_set", {
drawtype = "mesh",
mesh = "homedecor_bathroom_set.obj",
tiles = {
"homedecor_bathroom_set_mirror.png",
"homedecor_bathroom_set_tray.png",
"homedecor_bathroom_set_toothbrush.png",
"homedecor_bathroom_set_cup.png",
"homedecor_bathroom_set_toothpaste.png",
},
inventory_image = "homedecor_bathroom_set_inv.png",
description = "Bathroom sundries set",
groups = {snappy=3},
selection_box = bs_cbox,
walkable = false,
sounds = default.node_sound_glass_defaults(),
})
minetest.register_alias("3dforniture:toilet", "homedecor:toilet")
minetest.register_alias("3dforniture:toilet_open", "homedecor:toilet_open")
minetest.register_alias("3dforniture:sink", "homedecor:sink")
minetest.register_alias("3dforniture:taps", "homedecor:taps")
minetest.register_alias("3dforniture:shower_tray", "homedecor:shower_tray")
minetest.register_alias("3dforniture:shower_head", "homedecor:shower_head")
minetest.register_alias("3dforniture:table_lamp", "homedecor:table_lamp_off")
minetest.register_alias("toilet", "homedecor:toilet")
minetest.register_alias("sink", "homedecor:sink")
minetest.register_alias("taps", "homedecor:taps")
minetest.register_alias("shower_tray", "homedecor:shower_tray")
minetest.register_alias("shower_head", "homedecor:shower_head")
minetest.register_alias("table_lamp", "homedecor:table_lamp_off")
| unlicense |
opentibia/server | data/scripts/examples/movecreature_example.lua | 3 | 1120 | local movecreature_example = {}
local count_steps = {}
function movecreature_example.move_callback(event)
local c = count_steps[event.creature:getID()]
if c then
c.steps = c.steps + 1
if c.steps > 100 then
stopListener(c.listener)
count_steps[event.creature:getID()] = nil
return
end
end
wait(200)
local field = createItem(1488)
event.toTile:addItem(field)
field:startDecaying()
wait(5000)
if #field then
field:destroy()
end
end
function movecreature_example.stepIn_callback(event)
local c = count_steps[event.creature:getID()]
if c and c.steps > 0 then
c.steps = 0
return
end
count_steps[event.creature:getID()] =
{
steps = 0,
listener = registerOnCreatureMove(event.creature, movecreature_example.move_callback)
}
end
function movecreature_example.registerHandler()
if movecreature_example.stepInCreature_listener then
stopListener(movecreature_example.stepInCreature_listener)
end
movecreature_example.stepInCreature_listener =
registerOnAnyCreatureMoveIn("itemid", 420, movecreature_example.stepIn_callback)
end
movecreature_example.registerHandler()
| gpl-2.0 |
VincentGong/chess | cocos2d-x/cocos/scripting/lua-bindings/auto/api/Lens3D.lua | 3 | 1271 |
--------------------------------
-- @module Lens3D
-- @extend Grid3DAction
--------------------------------
-- @function [parent=#Lens3D] setPosition
-- @param self
-- @param #cc.Vec2 vec2
--------------------------------
-- @function [parent=#Lens3D] setConcave
-- @param self
-- @param #bool bool
--------------------------------
-- @function [parent=#Lens3D] setLensEffect
-- @param self
-- @param #float float
--------------------------------
-- @function [parent=#Lens3D] getPosition
-- @param self
-- @return Vec2#Vec2 ret (return value: cc.Vec2)
--------------------------------
-- @function [parent=#Lens3D] getLensEffect
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
-- @function [parent=#Lens3D] create
-- @param self
-- @param #float float
-- @param #size_table size
-- @param #cc.Vec2 vec2
-- @param #float float
-- @return Lens3D#Lens3D ret (return value: cc.Lens3D)
--------------------------------
-- @function [parent=#Lens3D] clone
-- @param self
-- @return Lens3D#Lens3D ret (return value: cc.Lens3D)
--------------------------------
-- @function [parent=#Lens3D] update
-- @param self
-- @param #float float
return nil
| mit |
jshackley/darkstar | scripts/globals/weaponskills/garland_of_bliss.lua | 18 | 4785 | -----------------------------------
-- Garland Of Bliss
-- Staff weapon skill
-- Skill level: N/A
-- Lowers target's defense. Duration of effect varies with TP. Nirvana: Aftermath effect varies with TP.
-- Reduces enemy's defense by 12.5%.
-- Available only after completing the Unlocking a Myth (Summoner) quest.
-- Aligned with the Flame Gorget, Light Gorget & Aqua Gorget.
-- Aligned with the Flame Belt, Light Belt & Aqua Belt.
-- Element: Light
-- Modifiers: MND:40%
-- 100%TP 200%TP 300%TP
-- 2.00 2.00 2.00
-----------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.ftp100 = 2; params.ftp200 = 2; params.ftp300 = 2;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.4; params.chr_wsc = 0.0;
params.ele = ELE_LIGHT;
params.skill = SKILL_STF;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 2.25; params.ftp200 = 2.25; params.ftp300 = 2.25;
params.str_wsc = 0.3; params.mnd_wsc = 0.7;
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params);
if damage > 0 then
local tp = player:getTP();
local duration = (tp/100 * 30) + 30;
if (target:hasStatusEffect(EFFECT_DEFENSE_DOWN) == false) then
target:addStatusEffect(EFFECT_DEFENSE_DOWN, 12.5, 0, duration);
end
end
if ((player:getEquipID(SLOT_MAIN) == 19005) and (player:getMainJob() == JOB_SMN)) then
if (damage > 0) then
-- AFTERMATH LV1
if ((player:getTP() >= 100) and (player:getTP() <= 110)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 10, 0, 180, 0, 1);
elseif ((player:getTP() >= 111) and (player:getTP() <= 120)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 11, 0, 180, 0, 1);
elseif ((player:getTP() >= 121) and (player:getTP() <= 130)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 12, 0, 180, 0, 1);
elseif ((player:getTP() >= 131) and (player:getTP() <= 140)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 13, 0, 180, 0, 1);
elseif ((player:getTP() >= 141) and (player:getTP() <= 150)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 14, 0, 180, 0, 1);
elseif ((player:getTP() >= 151) and (player:getTP() <= 160)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 15, 0, 180, 0, 1);
elseif ((player:getTP() >= 161) and (player:getTP() <= 170)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 16, 0, 180, 0, 1);
elseif ((player:getTP() >= 171) and (player:getTP() <= 180)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 17, 0, 180, 0, 1);
elseif ((player:getTP() >= 181) and (player:getTP() <= 190)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 18, 0, 180, 0, 1);
elseif ((player:getTP() >= 191) and (player:getTP() <= 199)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 19, 0, 180, 0, 1);
-- AFTERMATH LV2
elseif ((player:getTP() >= 200) and (player:getTP() <= 210)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 24, 0, 180, 0, 1);
elseif ((player:getTP() >= 211) and (player:getTP() <= 219)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 28, 0, 180, 0, 1);
elseif ((player:getTP() >= 221) and (player:getTP() <= 229)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 32, 0, 180, 0, 1);
elseif ((player:getTP() >= 231) and (player:getTP() <= 239)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 36, 0, 180, 0, 1);
elseif ((player:getTP() >= 241) and (player:getTP() <= 249)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 40, 0, 180, 0, 1);
elseif ((player:getTP() >= 251) and (player:getTP() <= 259)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 44, 0, 180, 0, 1);
elseif ((player:getTP() >= 261) and (player:getTP() <= 269)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 48, 0, 180, 0, 1);
elseif ((player:getTP() >= 271) and (player:getTP() <= 279)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 52, 0, 180, 0, 1);
elseif ((player:getTP() >= 281) and (player:getTP() <= 289)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 56, 0, 180, 0, 1);
elseif ((player:getTP() >= 291) and (player:getTP() <= 299)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 59, 0, 180, 0, 1);
-- AFTERMATH LV3
elseif ((player:getTP() == 300)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV3, 45, 0, 120, 0, 1);
end
end
end
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Bastok_Markets_[S]/npcs/HomePoint#1.lua | 17 | 1277 | -----------------------------------
-- Area: Bastok_Markets_[S]
-- NPC: HomePoint#1
-- @pos -293.048 -10.000 -102.558 87
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets_[S]/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Bastok_Markets_[S]/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 69);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Maze_of_Shakhrami/npcs/Excavation_Point.lua | 17 | 1628 | -----------------------------------
-- Area: Maze of Shakhrami
-- NPC: Excavation Point
-- Used in Quest: The Holy Crest
-- @pos 234 0.1 -110 198
-----------------------------------
package.loaded["scripts/zones/Maze_of_Shakhrami/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/excavation");
require("scripts/zones/Maze_of_Shakhrami/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getVar("TheHolyCrest_Event") == 3 and player:hasItem(1159) == false) then
if (trade:hasItemQty(605,1) and trade:getItemCount() == 1) then
if (player:getFreeSlotsCount(0) >= 1) then
player:tradeComplete();
player:addItem(1159);
player:messageSpecial(ITEM_OBTAINED, 1159); -- Wyvern Egg
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1159); -- Wyvern Egg
end
end
else
startExcavation(player,player:getZoneID(),npc,trade,0x003C);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(MINING_IS_POSSIBLE_HERE,605);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Promyvion-Holla/npcs/qm6.lua | 17 | 1088 | -----------------------------------
-- Area: Promyvion holla
-- ??? map acquisition
-----------------------------------
package.loaded["scripts/zones/Promyvion-Holla/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Promyvion-Holla/TextIDs");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(1720,1) and trade:getItemCount() == 1 and player:hasKeyItem(436)==false) then
player:addKeyItem(436); --add map
player:tradeComplete();
player:messageSpecial(KEYITEM_OBTAINED,436);
else
player:messageSpecial(NOTHING_HAPPENS);
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
JoMiro/arcemu | src/scripts/lua/LuaBridge/0Misc/0LCF_Includes/LCF_Creature.lua | 13 | 9679 | --[[
* ArcEmu MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008-2010 <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*]]
assert( include("LCF.lua") )
local CREATURE = LCF.CreatureMethods
assert(CREATURE)
local function alias(LHAname, LBname)
CREATURE[LHAname] = function(self, ...)
return self[LBname](self, ...);
end
end
local function aialias(LHAname, LBname)
CREATURE[LHAname] = function(self, ...)
return self:GetAIInterface()[LBname](self:GetAIInterface(), ...);
end
end
-- Some shorcuts to getting the ai interface.
CREATURE.AI = function(self) return self:GetAIInterface() end
CREATURE.ai = CREATURE.AI
function CREATURE:SetUnselectable()
if(self:HasFlag(LCF.UNIT_FIELD_FLAGS, LCF.UNIT_FLAG_NOT_SELECTABLE) == false) then
self:SetUInt32Value(LCF.UNIT_FIELD_FLAGS,bit_or(self:GetUInt32Value(LCF.UNIT_FIELD_FLAGS),LCF.UNIT_FLAG_NOT_SELECTABLE))
end
end
function CREATURE:SetSelectable()
if(self:HasFlag(LCF.UNIT_FIELD_FLAGS,LCF.UNIT_FLAG_NOT_SELECTABLE)) then
self:RemoveFlag(LCF.UNIT_FIELD_FLAGS,LCF.UNIT_FLAG_NOT_SELECTABLE)
end
end
function CREATURE:SetUnattackable()
if(self:HasFlag(LCF.UNIT_FIELD_FLAGS,LCF.UNIT_FLAG_NOT_ATTACKABLE_9) == false) then
self:SetUInt32Value(LCF.UNIT_FIELD_FLAGS,bit_or(self:GetUInt32Value(LCF.UNIT_FIELD_FLAGS),LCF.UNIT_FLAG_NOT_ATTACKABLE_9))
end
end
function CREATURE:SetAttackable()
if(self:HasFlag(LCF.UNIT_FIELD_FLAGS,LCF.UNIT_FLAG_NOT_ATTACKABLE_9) ) then
self:RemoveFlag(LCF.UNIT_FIELD_FLAGS,LCF.UNIT_FLAG_NOT_ATTACKABLE_9)
end
if(self:HasFlag(LCF.UNIT_FIELD_FLAGS,LCF.UNIT_FLAG_NOT_ATTACKABLE_2) ) then
self:RemoveFlag(LCF.UNIT_FIELD_FLAGS,LCF.UNIT_FLAG_NOT_ATTACKABLE_2)
end
end
function CREATURE:MonsterYell(msg)
self:SendChatMessage( LCF.CHAT_MSG_MONSTER_YELL, LCF.LANG_UNIVERSAL, msg, 0)
end
function CREATURE:MonsterSay(msg)
self:SendChatMessage(LCF.CHAT_MSG_MONSTER_SAY,LCF.LANG_UNIVERSAL,msg, 0)
end
function CREATURE:MonsterEmote(msg)
self:SendChatMessage(LCF.CHAT_MSG_MONSTER_EMOTE,LCF.LANG_UNIVERSAL,msg, 0)
end
function CREATURE:MonsterWhisper(msg)
self:SendChatMessage(LCF.CHAT_MSG_MONSTER_WHISPER,LCF.LANG_UNIVERSAL,msg, 0)
end
function CREATURE:MonsterYellToPlayer(plr,msg)
self:SendChatMessageToPlayer(LCF.CHAT_MSG_MONSTER_YELL,LCF.LANG_UNIVERSAL,msg,plr)
end
function CREATURE:MonsterSayToPlayer(plr,msg)
self:SendChatMessageToPlayer(LCF.CHAT_MSG_MONSTER_SAY,LCF.LANG_UNIVERSAL,msg,plr)
end
function CREATURE:MonsterWhisperToPlayer(plr,msg)
self:SendChatMessageToPlayer(LCF.CHAT_MSG_MONSTER_WHISPER,LCF.LANG_UNIVERSAL,msg,plr)
end
function CREATURE:BossRaidEmote(msg)
self:SendChatMessage(LCF.CHAT_MSG_RAID_BOSS_EMOTE,LCF.LANG_UNIVERSAL,msg, 0)
end
function CREATURE:MoveToUnit(target)
local x,y,z = target:GetLocation()
self:MoveTo(x,y,z,self:GetO())
end
function CREATURE:RegisterAIUpdateEvent( interval)
self:GetScript():RegisterAIUpdateEvent(interval)
end
function CREATURE:ModifyAIUpdateEvent( nInterval)
self:GetScript():ModifyAIUpdateEvent(nInterval)
end
function CREATURE:RemoveAIUpdateEvent()
self:GetScript():RemoveAIUpdateEvent()
end
CREATURE.GetName = function(self) return self:GetCreatureInfo().Name end
CREATURE.Name = CREATURE.GetName
CREATURE.name = CREATURE.Name
function CREATURE:Type()
return self:GetCreatureInfo().Type
end
function CREATURE:WipeThreatList()
self:GetAIInterface():WipeHateList()
end
function CREATURE:WipeHateList() self:GetAIInterface():WipeHateList() end
function CREATURE:DisableCombat( bewl)
self:GetAIInterface().disable_combat = bewl
end
function CREATURE:DisableMelee( bewl)
self:GetAIInterface().disable_melee = bewl
end
function CREATURE:DisableSpells( bewl)
self:GetAIInterface().disable_spell = bewl
end
function CREATURE:DisableTargeting( bewl)
self:GetAIInterface().disable_targeting = bewl
end
function CREATURE:DisableRanged( bewl)
self:GetAIInterface().m_canRangedAttack = bewl
end
function CREATURE:SetCombatCapable( bewl)
self:GetAIInterface().disable_combat = not bewl
end
function CREATURE:SetCombatMeleeCapable( bewl)
self:GetAIInterface().disable_melee = not bewl
end
function CREATURE:SetCombatSpellCapable( bewl)
self:GetAIInterface().disable_spell = not bewl
end
function CREATURE:SetCombatTargetingCapable( bewl)
self:GetAIInterface().disable_targeting = not bewl
end
function CREATURE:SetCombatRangedCapable( bewl)
self:GetAIInterface().m_canRangedAttack = not bewl
end
CREATURE.DisableRespawn = function (self, bewl) self:GetAIInterface().m_noRespawn = bewl end
CREATURE.NoRespawn = CREATURE.DisableRespawn
function CREATURE:CallForHelpHp( hp)
self:GetAIInterface().m_CallForHelpHealth = hp
end
function CREATURE:CanCallForHelp( bewl)
self:GetAIInterface().m_canCallForHelp = bewl
end
function CREATURE:RemoveThreat(target)
self:GetAIInterface():RemoveThreatByPtr( target)
end
function CREATURE:WipeCurrentTarget()
local target = self:GetAIInterface():getNextTarget()
if( target ~= nil) then
self:GetAIInterface():RemoveThreatByPtr(target)
end
self:GetAIInterface():setNextTarget( nil)
end
aialias("GetNextTarget", "getNextTarget")
function CREATURE:SetNextTarget(target) self:GetAIInterface():setNextTarget( target) end
CREATURE.GetMostHated = function(self) return self:GetAIInterface():GetMostHated() end
CREATURE.GetMainTank = CREATURE.GetMostHated
CREATURE.GetSecondHated = function(self) return self:GetAIInterface():GetSecondHated() end
CREATURE.GetAddTank = CREATURE.GetSecondHated
function CREATURE:MoveTo(...) self:GetAIInterface():MoveTo(...) end
function CREATURE:EventCastSpell(target, spell, delay, repeats)
assert( target and spell)
local function dospell(self, target, spell)
self:FullCastSpellOnTarget(spell, target)
end
self:RegisterEvent( dospell, delay, repeats, target, spell)
end
function CREATURE:SetEquippedItem(slot, id)
self:SetUInt32Value(LCF.UNIT_VIRTUAL_ITEM_SLOT_ID+slot, id)
end
function CREATURE:Attack(target)
self:GetAIInterface():WipeTargetList()
self:GetAIInterface():taunt(target, true)
return true
end
aialias("ChangeTarget", "setNextTarget")
aialias("ClearThreatList", "ClearHateList")
function CREATURE:CreateWaypoint(x,y,z,o,waittime,flags,model)
model = model or 0
local way = Waypoint()
way.x = x; way.y = y; way.z = z; way.o = o; way.waittime = waittime; way.flags = flags;
way.backwardskinid = model; way.forwardskinid = model;
self:GetAIInterface():addWayPoint(way);
return way;
end
alias("CreateCustomWaypoint", "CreateWaypoint")
function CREATURE:CreatureHasQuest(id) return self:HasQuest(id, 0xFFFFFFFF); end
aialias("DeleteWaypoint", "deleteWaypoint")
aialias("DeleteWaypoints", "deleteWaypoints")
function CREATURE:EventCastSpell(tar, id, delay, repeats)
self:RegisterEvent(function() self:CastSpell(tar, id, true); end, delay, repeats);
end
aialias("GetAIState", "getAIState")
aialias("GetAITargetsCount", "GetAITargetsCount")
aialias("GetCurrentWaypoint", "getCurrentWaypoint")
aialias("GetMoveType", "getMoveType")
aialias("GetSoulLinkedWith", "getSoullinkedWith")
aialias("GetTauntedBy", "getTauntedBy")
aialias("GetThreat", "getThreatByPtr")
aialias("GetUnitToFollow", "getUnitToFollow")
aialias("IsFlying", "IsFlying")
aialias("ModThreat", "modThreatByPtr")
function CREATURE:ModifyFlySpeed(value) self.flyspeed = value; end
function CREATURE:ModifyRunSpeed(value) self.runspeed = value; end
function CREATURE:ModifyWalkSpeed(value) self.walkspeed = value; end
function CREATURE:MoveToWaypoint(id)
self:GetAIInterface():setMoveType(3);
self:GetAIInterface():setWaypointToMove(id)
end
aialias("RemoveThreatByPtr", "RemoveThreatByPtr")
function CREATURE:ReturnToSpawnPoint()
local x,y,z,o = self:GetSpawnLocation()
self:MoveTo(x,y,z,o)
end
aialias("SetAIState", "SetAIState")
aialias("SetMoveRunFlag", "setMoveRunFlag")
aialias("SetMovementType", "setMoveType")
aialias("SetOutOfCombatRange", "setOutOfCombatRange")
aialias("SetPetOwner", "SetPetOwner")
aialias("SetSoulLinkedWith", "SetSoullinkedWith")
aialias("SetTauntedBy", "taunt")
function CREATURE:SetUnitToFollow(unit, dist)
self:GetAIInterface():SetUnitToFollow(unit)
self:GetAIInterface():SetFollowDistance(dist)
end
aialias("StopMovement", "StopMovement")
aialias("WipeThreatList", "WipeHateList")
function CREATURE:GetObjectType() return "Unit"; end
function CREATURE:AddAssistTargets(friend)
if (isFriendly(self, friend)) then
self:GetAIInterface():addAssistTargets(friend)
end
end
aialias("AttackReaction", "AttackReaction")
function CREATURE:AggroWithInRangeFriends()
if (not self.CombatStatus:IsInCombat()) then return; end
local pTarget = self:GetAIInterface():getNextTarget();
if (not pTarget) then return; end
for k,v in pairs(self:getInRangeSameFactions()) do
if (not v:IsDead() and v:IsCreature()) then
if (self:CalcDistanceToObject(v) < 10) then
v:GetAIInterface():setNextTarget(pTarget)
v:GetAIInterface():AttackReaction(pTarget, 1, 0)
end
end
end
end | agpl-3.0 |
yagop/telegram-bot | plugins/giphy.lua | 633 | 1796 | -- Idea by https://github.com/asdofindia/telegram-bot/
-- See http://api.giphy.com/
do
local BASE_URL = 'http://api.giphy.com/v1'
local API_KEY = 'dc6zaTOxFJmzC' -- public beta key
local function get_image(response)
local images = json:decode(response).data
if #images == 0 then return nil end -- No images
local i = math.random(#images)
local image = images[i] -- A random one
if image.images.downsized then
return image.images.downsized.url
end
if image.images.original then
return image.original.url
end
return nil
end
local function get_random_top()
local url = BASE_URL.."/gifs/trending?api_key="..API_KEY
local response, code = http.request(url)
if code ~= 200 then return nil end
return get_image(response)
end
local function search(text)
text = URL.escape(text)
local url = BASE_URL.."/gifs/search?q="..text.."&api_key="..API_KEY
local response, code = http.request(url)
if code ~= 200 then return nil end
return get_image(response)
end
local function run(msg, matches)
local gif_url = nil
-- If no search data, a random trending GIF will be sent
if matches[1] == "!gif" or matches[1] == "!giphy" then
gif_url = get_random_top()
else
gif_url = search(matches[1])
end
if not gif_url then
return "Error: GIF not found"
end
local receiver = get_receiver(msg)
print("GIF URL"..gif_url)
send_document_from_url(receiver, gif_url)
end
return {
description = "GIFs from telegram with Giphy API",
usage = {
"!gif (term): Search and sends GIF from Giphy. If no param, sends a trending GIF.",
"!giphy (term): Search and sends GIF from Giphy. If no param, sends a trending GIF."
},
patterns = {
"^!gif$",
"^!gif (.*)",
"^!giphy (.*)",
"^!giphy$"
},
run = run
}
end
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Port_Windurst/npcs/Kucha_Malkobhi.lua | 36 | 1528 | -----------------------------------
-- Area: Port Windurst
-- NPC: Kucha Malkobhi
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,KUCHAMALKOBHI_SHOP_DIALOG);
stock = {
0x315b, 273, --Tarutaru Kaftan
0x31d4, 163, --Tarutaru Mitts
0x3256, 236, --Tarutaru Braccae
0x32cf, 163, --Tarutaru Clomps
0x315c, 273, --Mithran Separates
0x31d5, 163, --Mithran Gauntlets
0x3257, 236, --Mithran Loincloth
0x32d0, 163 --Mithran Gaiters
}
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
sugiartocokrowibowo/Algorithm-Implementations | A_Star_Search/Lua/Yonaba/handlers/point_graph_handler.lua | 182 | 2492 | -- A point graph handler
-- This handler is devised for waypoints graphs.
-- Waypoints are locations represented via labelled nodes
-- and are connected with edges having a positive weight.
-- It assumes edges are symmetric, that is if an edge exists
-- between a and b, weight(a -> b) == weight(b -> a)
local PATH = (...):gsub('handlers.point_graph_handler$','')
local Node = require (PATH .. '.utils.node')
-- Implements Node class (from node.lua)
function Node:initialize(name) self.name = name end
function Node:toString() return ('Node: %s'):format(self.name) end
function Node:isEqualTo(n) return self.name == n.name end
-- Internal graph data
local graph = {nodes = {}, edges = {}}
-- Looks for an edge between a and b.
local function find_edge(edges_list, a, b)
for _, edge in ipairs(edges_list) do
if (edge.from == a and edge.to == b)
or (edge.from == b and edge.to == a)
then
return edge
end
end
end
-- Collects values from a map-table to an array
local function collect(map)
local array = {}
for _, element in pairs(map) do table.insert(array, element) end
return array
end
-- Handler implementation
local handler = {}
-- Returns an array of all nodes in the graph
function handler.getAllNodes() return collect(graph.nodes) end
-- Returns a Node
function handler.getNode(name) return graph.nodes[name] end
-- Returns the distance between node a and node b.
-- The distance should be the weight of the edge between the nodes
-- if existing, otherwise 0 (I could not figure anything better here).
function handler.distance(a, b)
local e = find_edge(graph.edges, a, b)
return e and e.weight or 0
end
-- Adds a new node labelled with name
function handler.addNode(name) graph.nodes[name] = Node(name) end
-- Adds a new edge between nodes labelled from and to
function handler.addEdge(from, to, weight)
table.insert(graph.edges,
{from = graph.nodes[from], to = graph.nodes[to], weight = weight or 0})
end
-- Sets the weight of edge from -> to
function handler.setEdgeWeight(from, to, weight)
local e = find_edge(graph.edges, graph.nodes[from], graph.nodes[to])
if e then e.weight = weight end
end
-- Returns an array of neighbors of node n
function handler.getNeighbors(n)
local neighbors = {}
for _, edge in ipairs(graph.edges) do
if edge.from == n then
table.insert(neighbors, edge.to)
elseif edge.to == n then
table.insert(neighbors, edge.from)
end
end
return neighbors
end
return handler
| mit |
sugiartocokrowibowo/Algorithm-Implementations | Dijkstra_Search/Lua/Yonaba/handlers/point_graph_handler.lua | 182 | 2492 | -- A point graph handler
-- This handler is devised for waypoints graphs.
-- Waypoints are locations represented via labelled nodes
-- and are connected with edges having a positive weight.
-- It assumes edges are symmetric, that is if an edge exists
-- between a and b, weight(a -> b) == weight(b -> a)
local PATH = (...):gsub('handlers.point_graph_handler$','')
local Node = require (PATH .. '.utils.node')
-- Implements Node class (from node.lua)
function Node:initialize(name) self.name = name end
function Node:toString() return ('Node: %s'):format(self.name) end
function Node:isEqualTo(n) return self.name == n.name end
-- Internal graph data
local graph = {nodes = {}, edges = {}}
-- Looks for an edge between a and b.
local function find_edge(edges_list, a, b)
for _, edge in ipairs(edges_list) do
if (edge.from == a and edge.to == b)
or (edge.from == b and edge.to == a)
then
return edge
end
end
end
-- Collects values from a map-table to an array
local function collect(map)
local array = {}
for _, element in pairs(map) do table.insert(array, element) end
return array
end
-- Handler implementation
local handler = {}
-- Returns an array of all nodes in the graph
function handler.getAllNodes() return collect(graph.nodes) end
-- Returns a Node
function handler.getNode(name) return graph.nodes[name] end
-- Returns the distance between node a and node b.
-- The distance should be the weight of the edge between the nodes
-- if existing, otherwise 0 (I could not figure anything better here).
function handler.distance(a, b)
local e = find_edge(graph.edges, a, b)
return e and e.weight or 0
end
-- Adds a new node labelled with name
function handler.addNode(name) graph.nodes[name] = Node(name) end
-- Adds a new edge between nodes labelled from and to
function handler.addEdge(from, to, weight)
table.insert(graph.edges,
{from = graph.nodes[from], to = graph.nodes[to], weight = weight or 0})
end
-- Sets the weight of edge from -> to
function handler.setEdgeWeight(from, to, weight)
local e = find_edge(graph.edges, graph.nodes[from], graph.nodes[to])
if e then e.weight = weight end
end
-- Returns an array of neighbors of node n
function handler.getNeighbors(n)
local neighbors = {}
for _, edge in ipairs(graph.edges) do
if edge.from == n then
table.insert(neighbors, edge.to)
elseif edge.to == n then
table.insert(neighbors, edge.from)
end
end
return neighbors
end
return handler
| mit |
sugiartocokrowibowo/Algorithm-Implementations | Depth_Limited_Search/Lua/Yonaba/handlers/point_graph_handler.lua | 182 | 2492 | -- A point graph handler
-- This handler is devised for waypoints graphs.
-- Waypoints are locations represented via labelled nodes
-- and are connected with edges having a positive weight.
-- It assumes edges are symmetric, that is if an edge exists
-- between a and b, weight(a -> b) == weight(b -> a)
local PATH = (...):gsub('handlers.point_graph_handler$','')
local Node = require (PATH .. '.utils.node')
-- Implements Node class (from node.lua)
function Node:initialize(name) self.name = name end
function Node:toString() return ('Node: %s'):format(self.name) end
function Node:isEqualTo(n) return self.name == n.name end
-- Internal graph data
local graph = {nodes = {}, edges = {}}
-- Looks for an edge between a and b.
local function find_edge(edges_list, a, b)
for _, edge in ipairs(edges_list) do
if (edge.from == a and edge.to == b)
or (edge.from == b and edge.to == a)
then
return edge
end
end
end
-- Collects values from a map-table to an array
local function collect(map)
local array = {}
for _, element in pairs(map) do table.insert(array, element) end
return array
end
-- Handler implementation
local handler = {}
-- Returns an array of all nodes in the graph
function handler.getAllNodes() return collect(graph.nodes) end
-- Returns a Node
function handler.getNode(name) return graph.nodes[name] end
-- Returns the distance between node a and node b.
-- The distance should be the weight of the edge between the nodes
-- if existing, otherwise 0 (I could not figure anything better here).
function handler.distance(a, b)
local e = find_edge(graph.edges, a, b)
return e and e.weight or 0
end
-- Adds a new node labelled with name
function handler.addNode(name) graph.nodes[name] = Node(name) end
-- Adds a new edge between nodes labelled from and to
function handler.addEdge(from, to, weight)
table.insert(graph.edges,
{from = graph.nodes[from], to = graph.nodes[to], weight = weight or 0})
end
-- Sets the weight of edge from -> to
function handler.setEdgeWeight(from, to, weight)
local e = find_edge(graph.edges, graph.nodes[from], graph.nodes[to])
if e then e.weight = weight end
end
-- Returns an array of neighbors of node n
function handler.getNeighbors(n)
local neighbors = {}
for _, edge in ipairs(graph.edges) do
if edge.from == n then
table.insert(neighbors, edge.to)
elseif edge.to == n then
table.insert(neighbors, edge.from)
end
end
return neighbors
end
return handler
| mit |
LuaDist2/luadbg | init.lua | 3 | 39924 |
--{{{
--Usage:
-- require('debugger') --load the debug library
-- pause(message) --start/resume a debug session
--An assert() failure will also invoke the debugger.
--}}}
local IsWindows = string.find(string.lower(os.getenv('OS') or ''),'^windows')
local coro_debugger
local events = { BREAK = 1, WATCH = 2, STEP = 3, SET = 4 }
local breakpoints = {}
local watches = {}
local step_into = false
local step_over = false
local step_lines = 0
local step_level = {main=0}
local stack_level = {main=0}
local trace_level = {main=0}
local trace_calls = false
local trace_returns = false
local trace_lines = false
local ret_file, ret_line, ret_name
local current_thread = 'main'
local started = false
local pause_off = false
local _g = _G
local cocreate, cowrap = coroutine.create, coroutine.wrap
local pausemsg = 'pause'
--{{{ make Lua 5.2 compatible
if not setfenv then -- Lua 5.2
--[[
As far as I can see, the only missing detail of these functions (except
for occasional bugs) to achieve 100% compatibility is the case of
'getfenv' over a function that does not have an _ENV variable (that is,
it uses no globals).
We could use a weak table to keep the environments of these functions
when set by setfenv, but that still misses the case of a function
without _ENV that was not subjected to setfenv.
-- Roberto
]]--
setfenv = setfenv or function(f, t)
f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func)
local name
local up = 0
repeat
up = up + 1
name = debug.getupvalue(f, up)
until name == '_ENV' or name == nil
if name then
debug.upvaluejoin(f, up, function() return name end, 1) -- use unique upvalue
debug.setupvalue(f, up, t)
end
end
getfenv = getfenv or function(f)
f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func)
local name, val
local up = 0
repeat
up = up + 1
name, val = debug.getupvalue(f, up)
until name == '_ENV' or name == nil
return val
end
end
--}}}
--{{{ local hints -- command help
--The format in here is name=summary|description
local hints = {
pause = [[
pause(msg[,lines][,force]) -- start/resume a debugger session|
This can only be used in your code or from the console as a means to
start/resume a debug session.
If msg is given that is shown when the session starts/resumes. Useful to
give a context if you've instrumented your code with pause() statements.
If lines is given, the script pauses after that many lines, else it pauses
immediately.
If force is true, the pause function is honoured even if poff has been used.
This is useful when in an interactive console session to regain debugger
control.
]],
poff = [[
poff -- turn off pause() command|
This causes all pause() commands to be ignored. This is useful if you have
instrumented your code in a busy loop and want to continue normal execution
with no further interruption.
]],
pon = [[
pon -- turn on pause() command|
This re-instates honouring the pause() commands you may have instrumented
your code with.
]],
setb = [[
setb | b [line file] -- set a breakpoint to line/file|, line 0 means 'any'
If file is omitted or is "-" the breakpoint is set at the file for the
currently set level (see "set"). Execution pauses when this line is about
to be executed and the debugger session is re-activated.
The file can be given as the fully qualified name, partially qualified or
just the file name. E.g. if file is set as "myfile.lua", then whenever
execution reaches any file that ends with "myfile.lua" it will pause. If
no extension is given, any extension will do.
If the line is given as 0, then reaching any line in the file will do.
]],
delb = [[
delb | del [line file] -- removes a breakpoint|
If file is omitted or is "-" the breakpoint is removed for the file of the
currently set level (see "set").
]],
delallb = [[
delallb -- removes all breakpoints|
]],
setw = [[
setw <exp> -- adds a new watch expression|
The expression is evaluated before each line is executed. If the expression
yields true then execution is paused and the debugger session re-activated.
The expression is executed in the context of the line about to be executed.
]],
delw = [[
delw <index> -- removes the watch expression at index|
The index is that returned when the watch expression was set by setw.
]],
delallw = [[
delallw -- removes all watch expressions|
]],
run = [[
run | r | c -- run until next breakpoint or watch expression|
]],
step = [[
step | s [N] -- run next N lines, stepping into function calls|
If N is omitted, use 1.
]],
over = [[
over | next [N] -- run next N lines, stepping over function calls|
If N is omitted, use 1.
]],
out = [[
out [N] -- run lines until stepped out of N functions|
If N is omitted, use 1.
If you are inside a function, using "out 1" will run until you return
from that function to the caller.
]],
gotoo = [[
gotoo [line file] -- step to line in file|
This is equivalent to 'setb line file', followed by 'run', followed
by 'delb line file'.
]],
listb = [[
listb -- lists breakpoints|
]],
listw = [[
listw -- lists watch expressions|
]],
set = [[
set [level] -- set context to stack level, omitted=show|
If level is omitted it just prints the current level set.
This sets the current context to the level given. This affects the
context used for several other functions (e.g. vars). The possible
levels are those shown by trace.
]],
vars = [[
vars [depth] -- list context locals to depth, omitted=1|
If depth is omitted then uses 1.
Use a depth of 0 for the maximum.
Lists all non-nil local variables and all non-nil upvalues in the
currently set context. For variables that are tables, lists all fields
to the given depth.
]],
fenv = [[
fenv [depth] -- list context function env to depth, omitted=1|
If depth is omitted then uses 1.
Use a depth of 0 for the maximum.
Lists all function environment variables in the currently set context.
For variables that are tables, lists all fields to the given depth.
]],
glob = [[
glob [depth] -- list globals to depth, omitted=1|
If depth is omitted then uses 1.
Use a depth of 0 for the maximum.
Lists all global variables.
For variables that are tables, lists all fields to the given depth.
]],
ups = [[
ups -- list all the upvalue names|
These names will also be in the "vars" list unless their value is nil.
This provides a means to identify which vars are upvalues and which are
locals. If a name is both an upvalue and a local, the local value takes
precedance.
]],
locs = [[
locs -- list all the locals names|
These names will also be in the "vars" list unless their value is nil.
This provides a means to identify which vars are upvalues and which are
locals. If a name is both an upvalue and a local, the local value takes
precedance.
]],
dump = [[
dump <var> [depth] -- dump all fields of variable to depth|
If depth is omitted then uses 1.
Use a depth of 0 for the maximum.
Prints the value of <var> in the currently set context level. If <var>
is a table, lists all fields to the given depth. <var> can be just a
name, or name.field or name.# to any depth, e.g. t.1.f accesses field
'f' in array element 1 in table 't'.
Can also be called from a script as dump(var,depth).
]],
tron = [[
tron [crl] -- turn trace on for (c)alls, (r)etuns, (l)lines|
If no parameter is given then tracing is turned off.
When tracing is turned on a line is printed to the console for each
debug 'event' selected. c=function calls, r=function returns, l=lines.
]],
trace = [[
trace -- dumps a stack trace|
Format is [level] = file,line,name
The level is a candidate for use by the 'set' command.
]],
info = [[
info -- dumps the complete debug info captured|
Only useful as a diagnostic aid for the debugger itself. This information
can be HUGE as it dumps all variables to the maximum depth, so be careful.
]],
show = [[
show | list line file X Y -- show X lines before and Y after line in file|
If line is omitted or is '-' then the current set context line is used.
If file is omitted or is '-' then the current set context file is used.
If file is not fully qualified and cannot be opened as specified, then
a search for the file in the package[path] is performed using the usual
"require" searching rules. If no file extension is given, .lua is used.
Prints the lines from the source file around the given line.
]],
exit = [[
exit -- exits debugger, re-start it using pause()|
]],
help = [[
help | h [command] -- show this list or help for command|
]],
["<statement>"] = [[
<statement> -- execute a statement in the current context|
The statement can be anything that is legal in the context, including
assignments. Such assignments affect the context and will be in force
immediately. Any results returned are printed. Use '=' as a short-hand
for 'return', e.g. "=func(arg)" will call 'func' with 'arg' and print
the results, and "=var" will just print the value of 'var'.
]],
what = [[
what <func> -- show where <func> is defined (if known)|
]],
}
--}}}
--{{{ local function getinfo(level,field)
--like debug.getinfo but copes with no activation record at the given level
--and knows how to get 'field'. 'field' can be the name of any of the
--activation record fields or any of the 'what' names or nil for everything.
--only valid when using the stack level to get info, not a function name.
local function getinfo(level,field)
level = level + 1 --to get to the same relative level as the caller
if not field then return debug.getinfo(level) end
local what
if field == 'name' or field == 'namewhat' then
what = 'n'
elseif field == 'what' or field == 'source' or field == 'linedefined' or field == 'lastlinedefined' or field == 'short_src' then
what = 'S'
elseif field == 'currentline' then
what = 'l'
elseif field == 'nups' then
what = 'u'
elseif field == 'func' then
what = 'f'
else
return debug.getinfo(level,field)
end
local ar = debug.getinfo(level,what)
if ar then return ar[field] else return nil end
end
--}}}
--{{{ local function indented( level, ... )
local function indented( level, ... )
io.write( string.rep(' ',level), table.concat({...}), '\n' )
end
--}}}
--{{{ local function dumpval( level, name, value, limit )
local dumpvisited
local function dumpval( level, name, value, limit )
local index
if type(name) == 'number' then
index = string.format('[%d] = ',name)
elseif type(name) == 'string'
and (name == '__VARSLEVEL__' or name == '__ENVIRONMENT__' or name == '__GLOBALS__' or name == '__UPVALUES__' or name == '__LOCALS__') then
--ignore these, they are debugger generated
return
elseif type(name) == 'string' and string.find(name,'^[_%a][_.%w]*$') then
index = name ..' = '
else
index = string.format('[%q] = ',tostring(name))
end
if type(value) == 'table' then
if dumpvisited[value] then
indented( level, index, string.format('ref%q;',dumpvisited[value]) )
else
dumpvisited[value] = tostring(value)
if (limit or 0) > 0 and level+1 >= limit then
indented( level, index, dumpvisited[value] )
else
indented( level, index, '{ -- ', dumpvisited[value] )
for n,v in pairs(value) do
dumpval( level+1, n, v, limit )
end
indented( level, '};' )
end
end
else
if type(value) == 'string' then
if string.len(value) > 40 then
indented( level, index, '[[', value, ']];' )
else
indented( level, index, string.format('%q',value), ';' )
end
else
indented( level, index, tostring(value), ';' )
end
end
end
--}}}
--{{{ local function dumpvar( value, limit, name )
local function dumpvar( value, limit, name )
dumpvisited = {}
dumpval( 0, name or tostring(value), value, limit )
end
--}}}
--{{{ local function show(file,line,before,after)
--show +/-N lines of a file around line M
local function show(file,line,before,after)
line = tonumber(line or 1)
before = tonumber(before or 10)
after = tonumber(after or before)
if not string.find(file,'%.') then file = file..'.lua' end
local f = io.open(file,'r')
if not f then
--{{{ try to find the file in the path
--
-- looks for a file in the package path
--
local path = package.path or LUA_PATH or ''
for c in string.gmatch (path, "[^;]+") do
local c = string.gsub (c, "%?%.lua", file)
f = io.open (c,'r')
if f then
break
end
end
--}}}
if not f then
io.write('Cannot find '..file..'\n')
return
end
end
local i = 0
for l in f:lines() do
i = i + 1
if i >= (line-before) then
if i > (line+after) then break end
if i == line then
io.write(i..'***\t'..l..'\n')
else
io.write(i..'\t'..l..'\n')
end
end
end
f:close()
end
--}}}
--{{{ local function tracestack(l)
local function gi( i )
return function() i=i+1 return debug.getinfo(i),i end
end
local function gl( level, j )
return function() j=j+1 return debug.getlocal( level, j ) end
end
local function gu( func, k )
return function() k=k+1 return debug.getupvalue( func, k ) end
end
local traceinfo
local function tracestack(l)
local l = l + 1 --NB: +1 to get level relative to caller
traceinfo = {}
traceinfo.pausemsg = pausemsg
for ar,i in gi(l) do
table.insert( traceinfo, ar )
if ar.what ~= 'C' then
local names = {}
local values = {}
for n,v in gl(i,0) do
if string.sub(n,1,1) ~= '(' then --ignore internal control variables
table.insert( names, n )
table.insert( values, v )
end
end
if #names > 0 then
ar.lnames = names
ar.lvalues = values
end
end
if ar.func then
local names = {}
local values = {}
for n,v in gu(ar.func,0) do
if string.sub(n,1,1) ~= '(' then --ignore internal control variables
table.insert( names, n )
table.insert( values, v )
end
end
if #names > 0 then
ar.unames = names
ar.uvalues = values
end
end
end
end
--}}}
--{{{ local function trace()
local function trace(set)
local mark
for level,ar in ipairs(traceinfo) do
if level == set then
mark = '***'
else
mark = ''
end
io.write('['..level..']'..mark..'\t'..(ar.name or ar.what)..' in '..ar.short_src..':'..ar.currentline..'\n')
end
end
--}}}
--{{{ local function info()
local function info() dumpvar( traceinfo, 0, 'traceinfo' ) end
--}}}
--{{{ local function set_breakpoint(file, line, once)
local function set_breakpoint(file, line, once)
if not breakpoints[line] then
breakpoints[line] = {}
end
if once then
breakpoints[line][file] = 1
else
breakpoints[line][file] = true
end
end
--}}}
--{{{ local function remove_breakpoint(file, line)
local function remove_breakpoint(file, line)
if breakpoints[line] then
breakpoints[line][file] = nil
end
end
--}}}
--{{{ local function has_breakpoint(file, line)
--allow for 'sloppy' file names
--search for file and all variations walking up its directory hierachy
--ditto for the file with no extension
--a breakpoint can be permenant or once only, if once only its removed
--after detection here, these are used for temporary breakpoints in the
--debugger loop when executing the 'gotoo' command
--a breakpoint on line 0 of a file means any line in that file
local function has_breakpoint(file, line)
local isLine = breakpoints[line]
local isZero = breakpoints[0]
if not isLine and not isZero then return false end
local noext = string.gsub(file,"(%..-)$",'',1)
if noext == file then noext = nil end
while file do
if isLine and isLine[file] then
if isLine[file] == 1 then isLine[file] = nil end
return true
end
if isZero and isZero[file] then
if isZero[file] == 1 then isZero[file] = nil end
return true
end
if IsWindows then
file = string.match(file,"[:/\\](.+)$")
else
file = string.match(file,"[:/](.+)$")
end
end
while noext do
if isLine and isLine[noext] then
if isLine[noext] == 1 then isLine[noext] = nil end
return true
end
if isZero and isZero[noext] then
if isZero[noext] == 1 then isZero[noext] = nil end
return true
end
if IsWindows then
noext = string.match(noext,"[:/\\](.+)$")
else
noext = string.match(noext,"[:/](.+)$")
end
end
return false
end
--}}}
--{{{ local function capture_vars(ref,level,line)
local function capture_vars(ref,level,line)
--get vars, file and line for the given level relative to debug_hook offset by ref
local lvl = ref + level --NB: This includes an offset of +1 for the call to here
--{{{ capture variables
local ar = debug.getinfo(lvl, "f")
if not ar then return {},'?',0 end
local vars = {__UPVALUES__={}, __LOCALS__={}}
local i
local func = ar.func
if func then
i = 1
while true do
local name, value = debug.getupvalue(func, i)
if not name then break end
if string.sub(name,1,1) ~= '(' then --NB: ignoring internal control variables
vars[name] = value
vars.__UPVALUES__[i] = name
end
i = i + 1
end
vars.__ENVIRONMENT__ = getfenv(func)
end
vars.__GLOBALS__ = getfenv(0)
i = 1
while true do
local name, value = debug.getlocal(lvl, i)
if not name then break end
if string.sub(name,1,1) ~= '(' then --NB: ignoring internal control variables
vars[name] = value
vars.__LOCALS__[i] = name
end
i = i + 1
end
vars.__VARSLEVEL__ = level
if func then
--NB: Do not do this until finished filling the vars table
setmetatable(vars, { __index = getfenv(func), __newindex = getfenv(func) })
end
--NB: Do not read or write the vars table anymore else the metatable functions will get invoked!
--}}}
local file = getinfo(lvl, "source")
if string.find(file, "@") == 1 then
file = string.sub(file, 2)
end
if IsWindows then file = string.lower(file) end
if not line then
line = getinfo(lvl, "currentline")
end
return vars,file,line
end
--}}}
--{{{ local function restore_vars(ref,vars)
local function restore_vars(ref,vars)
if type(vars) ~= 'table' then return end
local level = vars.__VARSLEVEL__ --NB: This level is relative to debug_hook offset by ref
if not level then return end
level = level + ref --NB: This includes an offset of +1 for the call to here
local i
local written_vars = {}
i = 1
while true do
local name, value = debug.getlocal(level, i)
if not name then break end
if vars[name] and string.sub(name,1,1) ~= '(' then --NB: ignoring internal control variables
debug.setlocal(level, i, vars[name])
written_vars[name] = true
end
i = i + 1
end
local ar = debug.getinfo(level, "f")
if not ar then return end
local func = ar.func
if func then
i = 1
while true do
local name, value = debug.getupvalue(func, i)
if not name then break end
if vars[name] and string.sub(name,1,1) ~= '(' then --NB: ignoring internal control variables
if not written_vars[name] then
debug.setupvalue(func, i, vars[name])
end
written_vars[name] = true
end
i = i + 1
end
end
end
--}}}
--{{{ local function trace_event(event, line, level)
local function print_trace(level,depth,event,file,line,name)
--NB: level here is relative to the caller of trace_event, so offset by 2 to get to there
level = level + 2
local file = file or getinfo(level,'short_src')
local line = line or getinfo(level,'currentline')
local name = name or getinfo(level,'name')
local prefix = ''
if current_thread ~= 'main' then prefix = '['..tostring(current_thread)..'] ' end
io.write(prefix..
string.format('%08.2f:%02i.',os.clock(),depth)..
string.rep('.',depth%32)..
(file or '')..' ('..(line or '')..') '..
(name or '')..
' ('..event..')\n')
end
local function trace_event(event, line, level)
if event == 'return' and trace_returns then
--note the line info for later
ret_file = getinfo(level+1,'short_src')
ret_line = getinfo(level+1,'currentline')
ret_name = getinfo(level+1,'name')
end
if event ~= 'line' then return end
local slevel = stack_level[current_thread]
local tlevel = trace_level[current_thread]
if trace_calls and slevel > tlevel then
--we are now in the function called, so look back 1 level further to find the calling file and line
print_trace(level+1,slevel-1,'c',nil,nil,getinfo(level+1,'name'))
end
if trace_returns and slevel < tlevel then
print_trace(level,slevel,'r',ret_file,ret_line,ret_name)
end
if trace_lines then
print_trace(level,slevel,'l')
end
trace_level[current_thread] = stack_level[current_thread]
end
--}}}
--{{{ local function report(ev, vars, file, line, idx_watch)
local function report(ev, vars, file, line, idx_watch)
local vars = vars or {}
local file = file or '?'
local line = line or 0
local prefix = ''
if current_thread ~= 'main' then prefix = '['..tostring(current_thread)..'] ' end
if ev == events.STEP then
io.write(prefix.."Paused at file "..file.." line "..line..' ('..stack_level[current_thread]..')\n')
elseif ev == events.BREAK then
io.write(prefix.."Paused at file "..file.." line "..line..' ('..stack_level[current_thread]..') (breakpoint)\n')
elseif ev == events.WATCH then
io.write(prefix.."Paused at file "..file.." line "..line..' ('..stack_level[current_thread]..')'.." (watch expression "..idx_watch.. ": ["..watches[idx_watch].exp.."])\n")
elseif ev == events.SET then
--do nothing
else
io.write(prefix.."Error in application: "..file.." line "..line.."\n")
end
if ev ~= events.SET then
if pausemsg and pausemsg ~= '' then io.write('Message: '..pausemsg..'\n') end
pausemsg = ''
end
return vars, file, line
end
--}}}
--{{{ local function debugger_loop(ev, vars, file, line, idx_watch)
local function debugger_loop(ev, vars, file, line, idx_watch)
local eval_env = vars or {}
local breakfile = file or '?'
local breakline = line or 0
local command, args
--{{{ local function getargs(spec)
--get command arguments according to the given spec from the args string
--the spec has a single character for each argument, arguments are separated
--by white space, the spec characters can be one of:
-- F for a filename (defaults to breakfile if - given in args)
-- L for a line number (defaults to breakline if - given in args)
-- N for a number
-- V for a variable name
-- S for a string
local function getargs(spec)
local res={}
local char,arg
local ptr=1
for i=1,string.len(spec) do
char = string.sub(spec,i,i)
if char == 'F' then
_,ptr,arg = string.find(args..' ',"%s*([%w%p]*)%s*",ptr)
if not arg or arg == '' then arg = '-' end
if arg == '-' then arg = breakfile end
elseif char == 'L' then
_,ptr,arg = string.find(args..' ',"%s*([%w%p]*)%s*",ptr)
if not arg or arg == '' then arg = '-' end
if arg == '-' then arg = breakline end
arg = tonumber(arg) or 0
elseif char == 'N' then
_,ptr,arg = string.find(args..' ',"%s*([%w%p]*)%s*",ptr)
if not arg or arg == '' then arg = '0' end
arg = tonumber(arg) or 0
elseif char == 'V' then
_,ptr,arg = string.find(args..' ',"%s*([%w%p]*)%s*",ptr)
if not arg or arg == '' then arg = '' end
elseif char == 'S' then
_,ptr,arg = string.find(args..' ',"%s*([%w%p]*)%s*",ptr)
if not arg or arg == '' then arg = '' end
else
arg = ''
end
table.insert(res,arg or '')
end
return unpack(res)
end
--}}}
while true do
io.write("[LDB]> ")
local line = io.read("*line")
if line == nil then io.write('\n'); line = 'exit' end
if string.find(line, "^[a-z]+") then
command = string.sub(line, string.find(line, "^[a-z]+"))
args = string.gsub(line,"^[a-z]+%s*",'',1) --strip command off line
else
command = ''
end
if (command == "setb" or command == "b") then
--{{{ set breakpoint
local line, filename = getargs('LF')
if filename ~= '' and line ~= '' then
set_breakpoint(filename,line)
io.write("Breakpoint set in file "..filename..' line '..line..'\n')
else
io.write("Bad request\n")
end
--}}}
elseif (command == "delb" or command == "del") then
--{{{ delete breakpoint
local line, filename = getargs('LF')
if filename ~= '' and line ~= '' then
remove_breakpoint(filename, line)
io.write("Breakpoint deleted from file "..filename..' line '..line.."\n")
else
io.write("Bad request\n")
end
--}}}
elseif command == "delallb" then
--{{{ delete all breakpoints
breakpoints = {}
io.write('All breakpoints deleted\n')
--}}}
elseif command == "listb" then
--{{{ list breakpoints
for i, v in pairs(breakpoints) do
for ii, vv in pairs(v) do
io.write("Break at: "..i..' in '..ii..'\n')
end
end
--}}}
elseif command == "setw" then
--{{{ set watch expression
if args and args ~= '' then
local func = loadstring("return(" .. args .. ")")
local newidx = #watches + 1
watches[newidx] = {func = func, exp = args}
io.write("Set watch exp no. " .. newidx..'\n')
else
io.write("Bad request\n")
end
--}}}
elseif command == "delw" then
--{{{ delete watch expression
local index = tonumber(args)
if index then
watches[index] = nil
io.write("Watch expression deleted\n")
else
io.write("Bad request\n")
end
--}}}
elseif command == "delallw" then
--{{{ delete all watch expressions
watches = {}
io.write('All watch expressions deleted\n')
--}}}
elseif command == "listw" then
--{{{ list watch expressions
for i, v in pairs(watches) do
io.write("Watch exp. " .. i .. ": " .. v.exp..'\n')
end
--}}}
elseif (command == "run" or command == "r" or command == "c") then
--{{{ run until breakpoint
step_into = false
step_over = false
return 'cont'
--}}}
elseif (command == "step" or command == "s") then
--{{{ step N lines (into functions)
local N = tonumber(args) or 1
step_over = false
step_into = true
step_lines = tonumber(N or 1)
return 'cont'
--}}}
elseif (command == "over" or command == "next") then
--{{{ step N lines (over functions)
local N = tonumber(args) or 1
step_into = false
step_over = true
step_lines = tonumber(N or 1)
step_level[current_thread] = stack_level[current_thread]
return 'cont'
--}}}
elseif command == "out" then
--{{{ step N lines (out of functions)
local N = tonumber(args) or 1
step_into = false
step_over = true
step_lines = 1
step_level[current_thread] = stack_level[current_thread] - tonumber(N or 1)
return 'cont'
--}}}
elseif command == "gotoo" then
--{{{ step until reach line
local line, filename = getargs('LF')
if line ~= '' then
step_over = false
step_into = false
if has_breakpoint(filename,line) then
return 'cont'
else
set_breakpoint(filename,line,true)
return 'cont'
end
else
io.write("Bad request\n")
end
--}}}
elseif command == "set" then
--{{{ set/show context level
local level = args
if level and level == '' then level = nil end
if level then return level end
--}}}
elseif command == "vars" then
--{{{ list context variables
local depth = args
if depth and depth == '' then depth = nil end
depth = tonumber(depth) or 1
dumpvar(eval_env, depth+1, 'variables')
--}}}
elseif command == "glob" then
--{{{ list global variables
local depth = args
if depth and depth == '' then depth = nil end
depth = tonumber(depth) or 1
dumpvar(eval_env.__GLOBALS__,depth+1,'globals')
--}}}
elseif command == "fenv" then
--{{{ list function environment variables
local depth = args
if depth and depth == '' then depth = nil end
depth = tonumber(depth) or 1
dumpvar(eval_env.__ENVIRONMENT__,depth+1,'environment')
--}}}
elseif command == "ups" then
--{{{ list upvalue names
dumpvar(eval_env.__UPVALUES__,2,'upvalues')
--}}}
elseif command == "locs" then
--{{{ list locals names
dumpvar(eval_env.__LOCALS__,2,'upvalues')
--}}}
elseif command == "what" then
--{{{ show where a function is defined
if args and args ~= '' then
local v = eval_env
local n = nil
for w in string.gmatch(args,"[%w_]+") do
v = v[w]
if n then n = n..'.'..w else n = w end
if not v then break end
end
if type(v) == 'function' then
local def = debug.getinfo(v,'S')
if def then
io.write(def.what..' in '..def.short_src..' '..def.linedefined..'..'..def.lastlinedefined..'\n')
else
io.write('Cannot get info for '..v..'\n')
end
else
io.write(v..' is not a function\n')
end
else
io.write("Bad request\n")
end
--}}}
elseif command == "dump" then
--{{{ dump a variable
local name, depth = getargs('VN')
if name ~= '' then
if depth == '' or depth == 0 then depth = nil end
depth = tonumber(depth or 1)
local v = eval_env
local n = nil
for w in string.gmatch(name,"[^%.]+") do --get everything between dots
if tonumber(w) then
v = v[tonumber(w)]
else
v = v[w]
end
if n then n = n..'.'..w else n = w end
if not v then break end
end
dumpvar(v,depth+1,n)
else
io.write("Bad request\n")
end
--}}}
elseif (command == "show" or command == "list") then
--{{{ show file around a line or the current breakpoint
local line, file, before, after = getargs('LFNN')
if before == 0 then before = 10 end
if after == 0 then after = before end
if file ~= '' and file ~= "=stdin" then
show(file,line,before,after)
else
io.write('Nothing to show\n')
end
--}}}
elseif command == "poff" then
--{{{ turn pause command off
pause_off = true
--}}}
elseif command == "pon" then
--{{{ turn pause command on
pause_off = false
--}}}
elseif command == "tron" then
--{{{ turn tracing on/off
local option = getargs('S')
trace_calls = false
trace_returns = false
trace_lines = false
if string.find(option,'c') then trace_calls = true end
if string.find(option,'r') then trace_returns = true end
if string.find(option,'l') then trace_lines = true end
--}}}
elseif command == "trace" then
--{{{ dump a stack trace
trace(eval_env.__VARSLEVEL__)
--}}}
elseif command == "info" then
--{{{ dump all debug info captured
info()
--}}}
elseif command == "pause" then
--{{{ not allowed in here
io.write('pause() should only be used in the script you are debugging\n')
--}}}
elseif (command == "help" or command == "h") then
--{{{ help
local command = getargs('S')
if command ~= '' and hints[command] then
io.write(hints[command]..'\n')
else
for _,v in pairs(hints) do
local _,_,h = string.find(v,"(.+)|")
io.write(h..'\n')
end
end
--}}}
elseif command == "exit" then
--{{{ exit debugger
return 'stop'
--}}}
elseif line ~= '' then
--{{{ just execute whatever it is in the current context
--map line starting with "=..." to "return ..."
if string.sub(line,1,1) == '=' then line = string.gsub(line,'=','return ',1) end
local ok, func = pcall(loadstring,line)
if func == nil then --Michael.Bringmann@lsi.com
io.write("Compile error: "..line..'\n')
elseif not ok then
io.write("Compile error: "..func..'\n')
else
setfenv(func, eval_env)
local res = {pcall(func)}
if res[1] then
if res[2] then
table.remove(res,1)
for _,v in ipairs(res) do
io.write(tostring(v))
io.write('\t')
end
io.write('\n')
end
--update in the context
return 0
else
io.write("Run error: "..res[2]..'\n')
end
end
--}}}
end
end
end
--}}}
--{{{ local function debug_hook(event, line, level, thread)
local function debug_hook(event, line, level, thread)
if not started then debug.sethook(); coro_debugger = nil; return end
current_thread = thread or 'main'
local level = level or 2
trace_event(event,line,level)
if event == "call" then
stack_level[current_thread] = stack_level[current_thread] + 1
elseif event == "return" then
stack_level[current_thread] = stack_level[current_thread] - 1
if stack_level[current_thread] < 0 then stack_level[current_thread] = 0 end
else
local vars,file,line = capture_vars(level,1,line)
local stop, ev, idx = false, events.STEP, 0
while true do
for index, value in pairs(watches) do
setfenv(value.func, vars)
local status, res = pcall(value.func)
if status and res then
ev, idx = events.WATCH, index
stop = true
break
end
end
if stop then break end
if (step_into)
or (step_over and (stack_level[current_thread] <= step_level[current_thread] or stack_level[current_thread] == 0)) then
step_lines = step_lines - 1
if step_lines < 1 then
ev, idx = events.STEP, 0
break
end
end
if has_breakpoint(file, line) then
ev, idx = events.BREAK, 0
break
end
return
end
if not coro_debugger then
io.write("Lua Debugger\n")
vars, file, line = report(ev, vars, file, line, idx)
io.write("Type 'help' for commands\n")
coro_debugger = true
else
vars, file, line = report(ev, vars, file, line, idx)
end
tracestack(level)
local last_next = 1
local next = 'ask'
local silent = false
while true do
if next == 'ask' then
next = debugger_loop(ev, vars, file, line, idx)
elseif next == 'cont' then
return
elseif next == 'stop' then
started = false
debug.sethook()
coro_debugger = nil
return
elseif tonumber(next) then --get vars for given level or last level
next = tonumber(next)
if next == 0 then silent = true; next = last_next else silent = false end
last_next = next
restore_vars(level,vars)
vars, file, line = capture_vars(level,next)
if not silent then
if vars and vars.__VARSLEVEL__ then
io.write('Level: '..vars.__VARSLEVEL__..'\n')
else
io.write('No level set\n')
end
end
ev = events.SET
next = 'ask'
else
io.write('Unknown command from debugger_loop: '..tostring(next)..'\n')
io.write('Stopping debugger\n')
next = 'stop'
end
end
end
end
--}}}
--{{{ coroutine.create
--This function overrides the built-in for the purposes of propagating
--the debug hook settings from the creator into the created coroutine.
_G.coroutine.create = function(f)
local thread
local hook, mask, count = debug.gethook()
if hook then
local function thread_hook(event,line)
hook(event,line,3,thread)
end
thread = cocreate(function(...)
stack_level[thread] = 0
trace_level[thread] = 0
step_level [thread] = 0
debug.sethook(thread_hook,mask,count)
return f(...)
end)
return thread
else
return cocreate(f)
end
end
--}}}
--{{{ coroutine.wrap
--This function overrides the built-in for the purposes of propagating
--the debug hook settings from the creator into the created coroutine.
_G.coroutine.wrap = function(f)
local thread
local hook, mask, count = debug.gethook()
if hook then
local function thread_hook(event,line)
hook(event,line,3,thread)
end
thread = cowrap(function(...)
stack_level[thread] = 0
trace_level[thread] = 0
step_level [thread] = 0
debug.sethook(thread_hook,mask,count)
return f(...)
end)
return thread
else
return cowrap(f)
end
end
--}}}
--{{{ function pause(x,l,f)
--
-- Starts/resumes a debug session
--
function pause(x,l,f)
if not f and pause_off then return end --being told to ignore pauses
pausemsg = x or 'pause'
local lines
local src = getinfo(2,'short_src')
if l then
lines = l --being told when to stop
elseif src == "stdin" then
lines = 1 --if in a console session, stop now
else
lines = 2 --if in a script, stop when get out of pause()
end
if started then
--we'll stop now 'cos the existing debug hook will grab us
step_lines = lines
step_into = true
debug.sethook(debug_hook, "crl") --reset it in case some external agent fiddled with it
else
--set to stop when get out of pause()
trace_level[current_thread] = 0
step_level [current_thread] = 0
stack_level[current_thread] = 1
step_lines = lines
step_into = true
started = true
debug.sethook(debug_hook, "crl") --NB: this will cause an immediate entry to the debugger_loop
end
end
--}}}
--{{{ function dump(v,depth)
--shows the value of the given variable, only really useful
--when the variable is a table
--see dump debug command hints for full semantics
function dump(v,depth)
dumpvar(v,(depth or 1)+1,tostring(v))
end
--}}}
--{{{ function debug.traceback(x)
local _traceback = debug.traceback --note original function
--override standard function
debug.traceback = function(x)
local assertmsg = _traceback(x) --do original function
pause(x) --let user have a look at stuff
return assertmsg --carry on
end
_TRACEBACK = debug.traceback --Lua 5.0 function
--}}}
return {
pause = pause
}
| lgpl-3.0 |
shagu/pfQuest | compat/pfUI.lua | 1 | 11572 | -- Initialize pfUI core table for non-pfUI environments
if not pfUI then
pfUI = {
["api"] = {},
["cache"] = {},
["backdrop"] = {
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true, tileSize = 16, edgeSize = 16,
insets = { left = 3, right = 3, top = 3, bottom = 3 }
},
["backdrop_small"] = {
bgFile = "Interface\\BUTTONS\\WHITE8X8", tile = false, tileSize = 0,
edgeFile = "Interface\\BUTTONS\\WHITE8X8", edgeSize = 1,
insets = {left = 0, right = 0, top = 0, bottom = 0},
},
["font_default"] = STANDARD_TEXT_FONT,
}
pfUI_config = {
["appearance"] = {
["border"] = {
["default"] = "3",
}
},
["global"] = {
["font_size"] = 12
},
-- fix for old questie releases
["disabled"] = {
["minimap"] = "1"
}
}
end
-- Add API support non-pfUI environments and for old pfUI versions:
-- strsplit, SanitizePattern, CreateBackdrop, SkinButton, CreateScrollFrame, CreateScrollChild
if pfUI.api and pfUI.api.strsplit and pfUI.api.CreateBackdrop and
pfUI.api.SkinButton and pfUI.api.CreateScrollFrame and
pfUI.api.CreateScrollChild and pfUI.api.SanitizePattern then
return
end
pfUI.api.emulated = true
function pfUI.api.strsplit(delimiter, subject)
if not subject then return nil end
local delimiter, fields = delimiter or ":", {}
local pattern = string.format("([^%s]+)", delimiter)
string.gsub(subject, pattern, function(c) fields[table.getn(fields)+1] = c end)
return unpack(fields)
end
local sanitize_cache = {}
function pfUI.api.SanitizePattern(pattern, dbg)
if not sanitize_cache[pattern] then
local ret = pattern
-- escape magic characters
ret = gsub(ret, "([%+%-%*%(%)%?%[%]%^])", "%%%1")
-- remove capture indexes
ret = gsub(ret, "%d%$","")
-- catch all characters
ret = gsub(ret, "(%%%a)","%(%1+%)")
-- convert all %s to .+
ret = gsub(ret, "%%s%+",".+")
-- set priority to numbers over strings
ret = gsub(ret, "%(.%+%)%(%%d%+%)","%(.-%)%(%%d%+%)")
-- cache it
sanitize_cache[pattern] = ret
end
return sanitize_cache[pattern]
end
local er, eg, eb, ea = .4,.4,.4,1
local br, bg, bb, ba = 0,0,0,1
function pfUI.api.CreateBackdrop(f, inset, legacy, transp)
-- exit if now frame was given
if not f then return end
-- use default inset if nothing is given
local border = inset
if not border then
border = tonumber(pfUI_config.appearance.border.default)
end
if transp then ba = transp end
-- use legacy backdrop handling
if legacy then
f:SetBackdrop(pfUI.backdrop)
f:SetBackdropColor(br, bg, bb, ba)
f:SetBackdropBorderColor(er, eg, eb , ea)
return
end
-- increase clickable area if available
if f.SetHitRectInsets then
f:SetHitRectInsets(-border,-border,-border,-border)
end
-- use new backdrop behaviour
if not f.backdrop then
f:SetBackdrop(nil)
local border = tonumber(border) - 1
local backdrop = pfUI.backdrop
if border < 1 then backdrop = pfUI.backdrop_small end
local b = CreateFrame("Frame", nil, f)
b:SetPoint("TOPLEFT", f, "TOPLEFT", -border, border)
b:SetPoint("BOTTOMRIGHT", f, "BOTTOMRIGHT", border, -border)
local level = f:GetFrameLevel()
if level < 1 then
--f:SetFrameLevel(level + 1)
b:SetFrameLevel(level)
else
b:SetFrameLevel(level - 1)
end
f.backdrop = b
b:SetBackdrop(backdrop)
end
local b = f.backdrop
b:SetBackdropColor(br, bg, bb, ba)
b:SetBackdropBorderColor(er, eg, eb , ea)
end
function pfUI.api.SkinButton(button, cr, cg, cb)
local b = getglobal(button)
if not b then b = button end
if not b then return end
if not cr or not cg or not cb then
_, class = UnitClass("player")
local color = RAID_CLASS_COLORS[class]
cr, cg, cb = color.r , color.g, color.b
end
pfUI.api.CreateBackdrop(b, nil, true)
b:SetNormalTexture(nil)
b:SetHighlightTexture(nil)
b:SetPushedTexture(nil)
b:SetDisabledTexture(nil)
local funce = b:GetScript("OnEnter")
local funcl = b:GetScript("OnLeave")
b:SetScript("OnEnter", function()
if funce then funce() end
pfUI.api.CreateBackdrop(b, nil, true)
b:SetBackdropBorderColor(cr,cg,cb,1)
end)
b:SetScript("OnLeave", function()
if funcl then funcl() end
pfUI.api.CreateBackdrop(b, nil, true)
end)
b:SetFont(pfUI.font_default, pfUI_config.global.font_size, "OUTLINE")
end
function pfUI.api.CreateScrollFrame(name, parent)
local f = CreateFrame("ScrollFrame", name, parent)
-- create slider
f.slider = CreateFrame("Slider", nil, f)
f.slider:SetOrientation('VERTICAL')
f.slider:SetPoint("TOPLEFT", f, "TOPRIGHT", -7, 0)
f.slider:SetPoint("BOTTOMRIGHT", 0, 0)
f.slider:SetThumbTexture("Interface\\BUTTONS\\WHITE8X8")
f.slider.thumb = f.slider:GetThumbTexture()
f.slider.thumb:SetHeight(50)
f.slider.thumb:SetTexture(.3,1,.8,.5)
f.slider:SetScript("OnValueChanged", function()
f:SetVerticalScroll(this:GetValue())
f.UpdateScrollState()
end)
f.UpdateScrollState = function()
f.slider:SetMinMaxValues(0, f:GetVerticalScrollRange())
f.slider:SetValue(f:GetVerticalScroll())
local m = f:GetHeight()+f:GetVerticalScrollRange()
local v = f:GetHeight()
local ratio = v / m
if ratio < 1 then
local size = math.floor(v * ratio)
f.slider.thumb:SetHeight(size)
f.slider:Show()
else
f.slider:Hide()
end
end
f.Scroll = function(self, step)
local step = step or 0
local current = f:GetVerticalScroll()
local max = f:GetVerticalScrollRange()
local new = current - step
if new >= max then
f:SetVerticalScroll(max)
elseif new <= 0 then
f:SetVerticalScroll(0)
else
f:SetVerticalScroll(new)
end
f:UpdateScrollState()
end
f:EnableMouseWheel(1)
f:SetScript("OnMouseWheel", function()
this:Scroll(arg1*10)
end)
return f
end
function pfUI.api.CreateScrollChild(name, parent)
local f = CreateFrame("Frame", name, parent)
-- dummy values required
f:SetWidth(1)
f:SetHeight(1)
f:SetAllPoints(parent)
parent:SetScrollChild(f)
f:SetScript("OnUpdate", function()
this:GetParent():UpdateScrollState()
end)
return f
end
-- [ round ]
-- Rounds a float number into specified places after comma.
-- 'input' [float] the number that should be rounded.
-- 'places' [int] amount of places after the comma.
-- returns: [float] rounded number.
function pfUI.api.round(input, places)
if not places then places = 0 end
if type(input) == "number" and type(places) == "number" then
local pow = 1
for i = 1, places do pow = pow * 10 end
return floor(input * pow + 0.5) / pow
end
end
-- [ rgbhex ]
-- Returns color format from color info
-- 'r' [table or number] color table or r color component
-- 'g' [number] optional g color component
-- 'b' [number] optional b color component
-- 'a' [number] optional alpha component
-- returns color string in the form of '|caaxxyyzz'
local hexcolor_cache = {}
function pfUI.api.rgbhex(r, g, b, a)
local key
if type(r)=="table" then
local _r,_g,_b,_a
if r.r then
_r,_g,_b,_a = r.r, r.g, r.b, r.a or 1
elseif table.getn(r) >= 3 then
_r,_g,_b,_a = r[1], r[2], r[3], r[4] or 1
end
if _r and _g and _b and _a then
key = string.format("%s%s%s%s",_r,_g,_b,_a)
if hexcolor_cache[key] == nil then
hexcolor_cache[key] = string.format("|c%02x%02x%02x%02x", _a*255, _r*255, _g*255, _b*255)
end
end
elseif tonumber(r) and g and b then
a = a or 1
key = string.format("%s%s%s%s",r,g,b,a)
if hexcolor_cache[key] == nil then
hexcolor_cache[key] = string.format("|c%02x%02x%02x%02x", a*255, r*255, g*255, b*255)
end
end
return hexcolor_cache[key] or ""
end
-- [ GetColorGradient ] --
-- 'perc' percentage (0-1)
-- return r,g,b and hexcolor
local gradientcolors = {}
function pfUI.api.GetColorGradient(perc)
perc = perc > 1 and 1 or perc
perc = perc < 0 and 0 or perc
perc = floor(perc*100)/100
local index = perc
if not gradientcolors[index] then
local r1, g1, b1, r2, g2, b2
if perc <= 0.5 then
perc = perc * 2
r1, g1, b1 = 1, 0, 0
r2, g2, b2 = 1, 1, 0
else
perc = perc * 2 - 1
r1, g1, b1 = 1, 1, 0
r2, g2, b2 = 0, 1, 0
end
local r = pfUI.api.round(r1 + (r2 - r1) * perc, 4)
local g = pfUI.api.round(g1 + (g2 - g1) * perc, 4)
local b = pfUI.api.round(b1 + (b2 - b1) * perc, 4)
local h = pfUI.api.rgbhex(r,g,b)
gradientcolors[index] = {}
gradientcolors[index].r = r
gradientcolors[index].g = g
gradientcolors[index].b = b
gradientcolors[index].h = h
end
return gradientcolors[index].r,
gradientcolors[index].g,
gradientcolors[index].b,
gradientcolors[index].h
end
-- [ GetBestAnchor ]
-- Returns the best anchor of a frame, based on its position
-- 'self' [frame] the frame that should be checked
-- returns: [string] the name of the best anchor
function pfUI.api.GetBestAnchor(self)
local scale = self:GetScale()
local x, y = self:GetCenter()
local a = GetScreenWidth() / scale / 3
local b = GetScreenWidth() / scale / 3 * 2
local c = GetScreenHeight() / scale / 3 * 2
local d = GetScreenHeight() / scale / 3
if not x or not y then return end
if x < a and y > c then
return "TOPLEFT"
elseif x > a and x < b and y > c then
return "TOP"
elseif x > b and y > c then
return "TOPRIGHT"
elseif x < a and y > d and y < c then
return "LEFT"
elseif x > a and x < b and y > d and y < c then
return "CENTER"
elseif x > b and y > d and y < c then
return "RIGHT"
elseif x < a and y < d then
return "BOTTOMLEFT"
elseif x > a and x < b and y < d then
return "BOTTOM"
elseif x > b and y < d then
return "BOTTOMRIGHT"
end
end
-- [ ConvertFrameAnchor ]
-- Converts a frame anchor into another one while preserving the frame position
-- 'self' [frame] the frame that should get another anchor.
-- 'anchor' [string] the new anchor that shall be used
-- returns: anchor, x, y can directly be used in SetPoint()
function pfUI.api.ConvertFrameAnchor(self, anchor)
local scale, x, y, _ = self:GetScale(), nil, nil, nil
if anchor == "CENTER" then
x, y = self:GetCenter()
x, y = x - GetScreenWidth()/2/scale, y - GetScreenHeight()/2/scale
elseif anchor == "TOPLEFT" then
x, y = self:GetLeft(), self:GetTop() - GetScreenHeight()/scale
elseif anchor == "TOP" then
x, _ = self:GetCenter()
x, y = x - GetScreenWidth()/2/scale, self:GetTop() - GetScreenHeight()/scale
elseif anchor == "TOPRIGHT" then
x, y = self:GetRight() - GetScreenWidth()/scale, self:GetTop() - GetScreenHeight()/scale
elseif anchor == "RIGHT" then
_, y = self:GetCenter()
x, y = self:GetRight() - GetScreenWidth()/scale, y - GetScreenHeight()/2/scale
elseif anchor == "BOTTOMRIGHT" then
x, y = self:GetRight() - GetScreenWidth()/scale, self:GetBottom()
elseif anchor == "BOTTOM" then
x, _ = self:GetCenter()
x, y = x - GetScreenWidth()/2/scale, self:GetBottom()
elseif anchor == "BOTTOMLEFT" then
x, y = self:GetLeft(), self:GetBottom()
elseif anchor == "LEFT" then
_, y = self:GetCenter()
x, y = self:GetLeft(), y - GetScreenHeight()/2/scale
end
return anchor, pfUI.api.round(x, 2), pfUI.api.round(y, 2)
end
| mit |
ByteFun/Starbound_mods | smount/tech/mech/mount62/mount62.lua | 7 | 34312 | function checkCollision(position)
local boundBox = mcontroller.boundBox()
boundBox[1] = boundBox[1] - mcontroller.position()[1] + position[1]
boundBox[2] = boundBox[2] - mcontroller.position()[2] + position[2]
boundBox[3] = boundBox[3] - mcontroller.position()[1] + position[1]
boundBox[4] = boundBox[4] - mcontroller.position()[2] + position[2]
return not world.rectCollision(boundBox)
end
function randomProjectileLine(startPoint, endPoint, stepSize, projectile, chanceToSpawn)
local dist = math.distance(startPoint, endPoint)
local steps = math.floor(dist / stepSize)
local normX = (endPoint[1] - startPoint[1]) / dist
local normY = (endPoint[2] - startPoint[2]) / dist
for i = 0, steps do
local p1 = { normX * i * stepSize + startPoint[1], normY * i * stepSize + startPoint[2]}
local p2 = { normX * (i + 1) * stepSize + startPoint[1] + math.random(-1, 1), normY * (i + 1) * stepSize + startPoint[2] + math.random(-1, 1)}
if math.random() <= chanceToSpawn then
world.spawnProjectile(projectile, math.midPoint(p1, p2), entity.id(), {normX, normY}, false)
end
end
return endPoint
end
function blinkAdjust(position, doPathCheck, doCollisionCheck, doLiquidCheck, doStandCheck)
local blinkCollisionCheckDiameter = tech.parameter("blinkCollisionCheckDiameter")
local blinkVerticalGroundCheck = tech.parameter("blinkVerticalGroundCheck")
local blinkFootOffset = tech.parameter("blinkFootOffset")
if doPathCheck then
local collisionBlocks = world.collisionBlocksAlongLine(mcontroller.position(), position, true, 1)
if #collisionBlocks ~= 0 then
local diff = world.distance(position, mcontroller.position())
diff[1] = diff[1] / math.abs(diff[1])
diff[2] = diff[2] / math.abs(diff[2])
position = {collisionBlocks[1][1] - diff[1], collisionBlocks[1][2] - diff[2]}
end
end
if doCollisionCheck and not checkCollision(position) then
local spaceFound = false
for i = 1, blinkCollisionCheckDiameter * 2 do
if checkCollision({position[1] + i / 2, position[2] + i / 2}) then
position = {position[1] + i / 2, position[2] + i / 2}
spaceFound = true
break
end
if checkCollision({position[1] - i / 2, position[2] + i / 2}) then
position = {position[1] - i / 2, position[2] + i / 2}
spaceFound = true
break
end
if checkCollision({position[1] + i / 2, position[2] - i / 2}) then
position = {position[1] + i / 2, position[2] - i / 2}
spaceFound = true
break
end
if checkCollision({position[1] - i / 2, position[2] - i / 2}) then
position = {position[1] - i / 2, position[2] - i / 2}
spaceFound = true
break
end
end
if not spaceFound then
return nil
end
end
if doStandCheck then
local groundFound = false
for i = 1, blinkVerticalGroundCheck * 2 do
local checkPosition = {position[1], position[2] - i / 2}
if world.pointCollision(checkPosition, false) then
groundFound = true
position = {checkPosition[1], checkPosition[2] + 0.5 - blinkFootOffset}
break
end
end
if not groundFound then
return nil
end
end
if doLiquidCheck and (world.liquidAt(position) or world.liquidAt({position[1], position[2] + blinkFootOffset})) then
return nil
end
if doCollisionCheck and not checkCollision(position) then
return nil
end
return position
end
function findRandomBlinkLocation(doCollisionCheck, doLiquidCheck, doStandCheck)
local randomBlinkTries = tech.parameter("randomBlinkTries")
local randomBlinkDiameter = tech.parameter("randomBlinkDiameter")
for i=1,randomBlinkTries do
local position = mcontroller.position()
position[1] = position[1] + (math.random() * 2 - 1) * randomBlinkDiameter
position[2] = position[2] + (math.random() * 2 - 1) * randomBlinkDiameter
local position = blinkAdjust(position, false, doCollisionCheck, doLiquidCheck, doStandCheck)
if position then
return position
end
end
return nil
end
function init()
self.level = tech.parameter("mechLevel", 6)
self.mechState = "off"
self.mechStateTimer = 0
self.specialLast = false
self.active = false
self.fireTimer = 0
tech.setVisible(false)
tech.rotateGroup("guns", 0, true)
self.multiJumps = 0
self.lastJump = false
self.mode = "none"
self.timer = 0
self.targetPosition = nil
self.grabbed = false
self.holdingJump = false
self.ranOut = false
self.airDashing = false
self.dashTimer = 0
self.dashDirection = 0
self.dashLastInput = 0
self.dashTapLast = 0
self.dashTapTimer = 0
self.dashAttackfireTimer = 0
self.dashAttackTimer = 0
self.dashAttackDirection = 0
self.dashAttackLastInput = 0
self.dashAttackTapLast = 0
self.dashAttackTapTimer = 0
self.holdingUp = false
self.holdingDown = false
self.holdingLeft = false
self.holdingRight = false
self.speedMultiplier = 1.1
self.levitateActivated = false
self.mechTimer = 0
end
function uninit()
if self.active then
local mechTransformPositionChange = tech.parameter("mechTransformPositionChange")
mcontroller.translate({-mechTransformPositionChange[1], -mechTransformPositionChange[2]})
tech.setParentOffset({0, 0})
self.active = false
tech.setVisible(false)
tech.setParentState()
tech.setToolUsageSuppressed(false)
mcontroller.controlFace(nil)
end
end
function input(args)
if self.dashTimer > 0 then
return nil
end
local maximumDoubleTapTime = tech.parameter("maximumDoubleTapTime")
if self.dashTapTimer > 0 then
self.dashTapTimer = self.dashTapTimer - args.dt
end
if args.moves["right"] and self.active then
if self.dashLastInput ~= 1 then
if self.dashTapLast == 1 and self.dashTapTimer > 0 then
self.dashTapLast = 0
self.dashTapTimer = 0
return "dashRight"
else
self.dashTapLast = 1
self.dashTapTimer = maximumDoubleTapTime
end
end
self.dashLastInput = 1
elseif args.moves["left"] and self.active then
if self.dashLastInput ~= -1 then
if self.dashTapLast == -1 and self.dashTapTimer > 0 then
self.dashTapLast = 0
self.dashTapTimer = 0
return "dashLeft"
else
self.dashTapLast = -1
self.dashTapTimer = maximumDoubleTapTime
end
end
self.dashLastInput = -1
else
self.dashLastInput = 0
end
if args.moves["jump"] and mcontroller.jumping() then
self.holdingJump = true
elseif not args.moves["jump"] then
self.holdingJump = false
end
if args.moves["special"] == 1 then
if self.active then
return "mechDeactivate"
else
return "mechActivate"
end
elseif args.moves[""] == 2 and self.active then
return "blink"
elseif args.moves[""] and args.moves[""] and args.moves[""] and not self.levitateActivated and self.active then
return "grab"
elseif args.moves["down"] and args.moves["right"] and not self.levitateActivated and self.active then
return "dashAttackRight"
elseif args.moves["down"] and args.moves["left"] and not self.levitateActivated and self.active then
return "dashAttackLeft"
elseif args.moves["primaryFire"] and self.active then
return "mechFire"
elseif args.moves[""] and self.active then
return "mechAltFire"
elseif args.moves[""] and args.moves[""] and self.active then
return "mechSecFire"
elseif args.moves[""] and not mcontroller.canJump() and not self.holdingJump and self.active then
return "jetpack"
elseif args.moves[""] and not mcontroller.jumping() and not mcontroller.canJump() and not self.lastJump then
self.lastJump = true
return "multiJump"
else
self.lastJump = args.moves["jump"]
end
self.specialLast = args.moves["special"] == 1
--RedOrb
-- if args.moves["left"] then
-- self.holdingLeft = true
-- elseif not args.moves["left"] then
-- self.holdingLeft = false
-- end
-- if args.moves["right"] then
-- self.holdingRight = true
-- elseif not args.moves["right"] then
-- self.holdingRight = false
-- end
-- if args.moves["up"] then
-- self.holdingUp = true
-- elseif not args.moves["up"] then
-- self.holdingUp = false
-- end
-- if args.moves["down"] then
-- self.holdingDown = true
-- elseif not args.moves["down"] then
-- self.holdingDown = false
-- end
-- if not args.moves["jump"] and not args.moves["left"]and not args.moves["right"]and not args.moves["up"]and not args.moves["down"] and not tech.canJump() and not self.holdingJump and self.levitateActivated then
-- return "levitatehover"
-- elseif args.moves["jump"] and not tech.canJump() and not self.holdingJump then
-- return "levitate"
-- elseif args.moves["left"] and args.moves["right"] and not tech.canJump() and self.levitateActivated then
-- return "levitatehover"
-- elseif args.moves["up"] and args.moves["down"] and not tech.canJump() and self.levitateActivated then
-- return "levitatehover"
-- elseif (args.moves["jump"] or args.moves["up"]) and args.moves["left"] and not tech.canJump() and not self.holdingRight and self.levitateActivated then
-- return "levitateleftup"
-- elseif (args.moves["jump"] or args.moves["up"]) and args.moves["right"] and not tech.canJump() and not self.holdingLeft and self.levitateActivated then
-- return "levitaterightup"
-- elseif args.moves["down"] and args.moves["left"] and not tech.canJump() and not self.holdingRight and self.levitateActivated then
-- return "levitateleftdown"
-- elseif args.moves["down"] and args.moves["right"] and not tech.canJump() and not self.holdingLeft and self.levitateActivated then
-- return "levitaterightdown"
-- elseif args.moves["left"] and not tech.canJump() and not self.holdingRight and self.levitateActivated then
-- return "levitateleft"
-- elseif args.moves["right"] and not tech.canJump() and not self.holdingLeft and self.levitateActivated then
-- return "levitateright"
-- elseif args.moves["up"] and not tech.canJump() and not self.holdingDown and self.levitateActivated then
-- return "levitateup"
-- elseif args.moves["down"] and not tech.canJump() and not self.holdingUp and self.levitateActivated then
-- return "levitatedown"
-- else
-- return nil
-- end
--RedOrbEnd
end
function update(args)
if self.mechTimer > 0 then
self.mechTimer = self.mechTimer - args.dt
end
local dashControlForce = tech.parameter("dashControlForce")
local dashSpeed = tech.parameter("dashSpeed")
local dashDuration = tech.parameter("dashDuration")
local energyUsageDash = tech.parameter("energyUsageDash")
local usedEnergy = 0
if args.actions["dashRight"] and self.dashTimer <= 0 and status.resource("energy") > energyUsageDash then
self.dashTimer = dashDuration
self.dashDirection = 1
usedEnergy = energyUsageDash
self.airDashing = not mcontroller.onGround()
return tech.consumeTechEnergy(energyUsageDash)
elseif args.actions["dashLeft"] and self.dashTimer <= 0 and status.resource("energy") > energyUsageDash then
self.dashTimer = dashDuration
self.dashDirection = -1
usedEnergy = energyUsageDash
self.airDashing = not mcontroller.onGround()
return tech.consumeTechEnergy(energyUsageDash)
end
if self.dashTimer > 0 then
mcontroller.controlApproachXVelocity(dashSpeed * self.dashDirection, dashControlForce, true)
if self.airDashing then
mcontroller.controlParameters({gravityEnabled = false})
mcontroller.controlApproachYVelocity(0, dashControlForce, true)
end
if self.dashDirection == -1 then
mcontroller.controlFace(-1)
tech.setFlipped(true)
else
mcontroller.controlFace(1)
tech.setFlipped(false)
end
tech.setAnimationState("dashing", "on")
tech.setParticleEmitterActive("dashParticles", true)
self.dashTimer = self.dashTimer - args.dt
else
tech.setAnimationState("dashing", "off")
tech.setParticleEmitterActive("dashParticles", false)
end
local dashAttackControlForce = tech.parameter("dashAttackControlForce")
local dashAttackSpeed = tech.parameter("dashAttackSpeed")
local dashAttackDuration = tech.parameter("dashAttackDuration")
local energyUsageDashAttack = tech.parameter("energyUsageDashAttack")
local diffDash = world.distance(tech.aimPosition(), mcontroller.position())
local aimAngleDash = math.atan(diffDash[2], diffDash[1])
local mechDashFireCycle = tech.parameter("mechDashFireCycle")
local mechDashProjectile = tech.parameter("mechDashProjectile")
local mechDashProjectileConfig = tech.parameter("mechDashProjectileConfig")
local flipDash = aimAngleDash > math.pi / 2 or aimAngleDash < -math.pi / 2
if flipDash then
tech.setFlipped(false)
mcontroller.controlFace(-1)
self.dashAttackDirection = -1
else
tech.setFlipped(true)
mcontroller.controlFace(1)
self.dashAttackDirection = 1
end
if status.resource("energy") > energyUsageDashAttack and args.actions["dashAttackLeft"] or args.actions["dashAttackRight"] then
if self.dashAttackTimer <= 0 then
world.spawnProjectile(mechDashProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontDashGun", "firePoint")), entity.id(), {math.cos(0), math.sin(0)}, false, mechDashProjectileConfig)
self.dashAttackTimer = self.dashAttackTimer + mechDashFireCycle
else
self.dashAttackTimer = self.dashAttackTimer - args.dt
end
mcontroller.controlApproachXVelocity(dashAttackSpeed * self.dashAttackDirection, dashAttackControlForce, true)
tech.setAnimationState("dashingAttack", "on")
tech.setParticleEmitterActive("dashAttackParticles", true)
else
tech.setAnimationState("dashingAttack", "off")
tech.setParticleEmitterActive("dashAttackParticles", false)
end
local energyUsageBlink = tech.parameter("energyUsageBlink")
local blinkMode = tech.parameter("blinkMode")
local blinkOutTime = tech.parameter("blinkOutTime")
local blinkInTime = tech.parameter("blinkInTime")
if args.actions["blink"] and self.mode == "none" and status.resource("energy") > energyUsageBlink then
local blinkPosition = nil
if blinkMode == "random" then
local randomBlinkAvoidCollision = tech.parameter("randomBlinkAvoidCollision")
local randomBlinkAvoidMidair = tech.parameter("randomBlinkAvoidMidair")
local randomBlinkAvoidLiquid = tech.parameter("randomBlinkAvoidLiquid")
blinkPosition =
findRandomBlinkLocation(randomBlinkAvoidCollision, randomBlinkAvoidMidair, randomBlinkAvoidLiquid) or
findRandomBlinkLocation(randomBlinkAvoidCollision, randomBlinkAvoidMidair, false) or
findRandomBlinkLocation(randomBlinkAvoidCollision, false, false)
elseif blinkMode == "cursor" then
blinkPosition = blinkAdjust(tech.aimPosition(), true, true, false, false)
elseif blinkMode == "cursorPenetrate" then
blinkPosition = blinkAdjust(tech.aimPosition(), false, true, false, false)
end
if blinkPosition then
self.targetPosition = blinkPosition
self.mode = "start"
else
-- Make some kind of error noise
end
end
if self.mode == "start" then
mcontroller.setVelocity({0, 0})
self.mode = "out"
self.timer = 0
return tech.consumeTechEnergy(energyUsageBlink)
elseif self.mode == "out" then
tech.setParentDirectives("?multiply=00000000")
tech.setVisible(false)
tech.setAnimationState("blinking", "out")
mcontroller.setVelocity({0, 0})
self.timer = self.timer + args.dt
if self.timer > blinkOutTime then
mcontroller.setPosition(self.targetPosition)
self.mode = "in"
self.timer = 0
end
return 0
elseif self.mode == "in" then
tech.setParentDirectives()
tech.setVisible(true)
tech.setAnimationState("blinking", "in")
mcontroller.setVelocity({0, 0})
self.timer = self.timer + args.dt
if self.timer > blinkInTime then
self.mode = "none"
end
return 0
end
local energyUsageJump = tech.parameter("energyUsageJump")
local multiJumpCount = tech.parameter("multiJumpCount")
if args.actions["multiJump"] and self.multiJumps < multiJumpCount and status.resource("energy") > energyUsageJump then
mcontroller.controlJump(true)
self.multiJumps = self.multiJumps + 1
tech.burstParticleEmitter("multiJumpParticles")
tech.playSound("sound")
return tech.consumeTechEnergy(energyUsageJump)
else
if mcontroller.onGround() or mcontroller.liquidMovement() then
self.multiJumps = 0
end
end
local energyCostPerSecond = tech.parameter("energyCostPerSecond")
local energyCostPerSecondPrim = tech.parameter("energyCostPerSecondPrim")
local energyCostPerSecondSec = tech.parameter("energyCostPerSecondSec")
local energyCostPerSecondAlt = tech.parameter("energyCostPerSecondAlt")
local mechCustomMovementParameters = tech.parameter("mechCustomMovementParameters")
local mechTransformPositionChange = tech.parameter("mechTransformPositionChange")
local parentOffset = tech.parameter("parentOffset")
local mechCollisionTest = tech.parameter("mechCollisionTest")
local mechAimLimit = tech.parameter("mechAimLimit") * math.pi / 180
local mechFrontRotationPoint = tech.parameter("mechFrontRotationPoint")
local mechFrontFirePosition = tech.parameter("mechFrontFirePosition")
local mechBackRotationPoint = tech.parameter("mechBackRotationPoint")
local mechBackFirePosition = tech.parameter("mechBackFirePosition")
local mechFireCycle = tech.parameter("mechFireCycle")
local mechProjectile = tech.parameter("mechProjectile")
local mechProjectileConfig = tech.parameter("mechProjectileConfig")
local mechAltFireCycle = tech.parameter("mechAltFireCycle")
local mechAltProjectile = tech.parameter("mechAltProjectile")
local mechAltProjectileConfig = tech.parameter("mechAltProjectileConfig")
local mechSecFireCycle = tech.parameter("mechSecFireCycle")
local mechSecProjectile = tech.parameter("mechSecProjectile")
local mechSecProjectileConfig = tech.parameter("mechSecProjectileConfig")
local mechGunBeamMaxRange = tech.parameter("mechGunBeamMaxRange")
local mechGunBeamStep = tech.parameter("mechGunBeamStep")
local mechGunBeamSmokeProkectile = tech.parameter("mechGunBeamSmokeProkectile")
local mechGunBeamEndProjectile = tech.parameter("mechGunBeamEndProjectile")
local mechGunBeamUpdateTime = tech.parameter("mechGunBeamUpdateTime")
local mechTransform = tech.parameter("mechTransform")
local mechActiveSide = nil
if tech.setFlipped(true) then
mechActiveSide = "left"
elseif tech.setFlipped(false) then
mechActiveSide = "right"
end
local mechStartupTime = tech.parameter("mechStartupTime")
local mechShutdownTime = tech.parameter("mechShutdownTime")
if not self.active and args.actions["mechActivate"] and self.mechState == "off" then
mechCollisionTest[1] = mechCollisionTest[1] + mcontroller.position()[1]
mechCollisionTest[2] = mechCollisionTest[2] + mcontroller.position()[2]
mechCollisionTest[3] = mechCollisionTest[3] + mcontroller.position()[1]
mechCollisionTest[4] = mechCollisionTest[4] + mcontroller.position()[2]
if not world.rectCollision(mechCollisionTest) then
tech.burstParticleEmitter("mechActivateParticles")
mcontroller.translate(mechTransformPositionChange)
tech.setVisible(true)
tech.setAnimationState("transform", "in")
-- status.modifyResource("health", status.stat("maxHealth") / 20)
tech.setParentState("sit")
tech.setToolUsageSuppressed(true)
self.mechState = "turningOn"
self.mechStateTimer = mechStartupTime
self.active = true
else
-- Make some kind of error noise
end
elseif self.mechState == "turningOn" and self.mechStateTimer <= 0 then
tech.setParentState("sit")
self.mechState = "on"
self.mechStateTimer = 0
elseif (self.active and (args.actions["mechDeactivate"] and self.mechState == "on" or (energyCostPerSecond * args.dt > status.resource("energy")) and self.mechState == "on")) then
self.mechState = "turningOff"
tech.setAnimationState("transform", "out")
self.mechStateTimer = mechShutdownTime
elseif self.mechState == "turningOff" and self.mechStateTimer <= 0 then
tech.burstParticleEmitter("mechDeactivateParticles")
mcontroller.translate({-mechTransformPositionChange[1], -mechTransformPositionChange[2]})
tech.setVisible(false)
tech.setParentState()
tech.setToolUsageSuppressed(false)
tech.setParentOffset({0, 0})
self.mechState = "off"
self.mechStateTimer = 0
self.active = false
end
mcontroller.controlFace(nil)
if self.mechStateTimer > 0 then
self.mechStateTimer = self.mechStateTimer - args.dt
end
if self.active then
local diff = world.distance(tech.aimPosition(), mcontroller.position())
local aimAngle = math.atan(diff[2], diff[1])
local flip = aimAngle > math.pi / 2 or aimAngle < -math.pi / 2
mcontroller.controlParameters(mechCustomMovementParameters)
if flip then
tech.setFlipped(false)
local nudge = tech.transformedPosition({0, 0})
tech.setParentOffset({-parentOffset[1] - nudge[1], parentOffset[2] + nudge[2]})
mcontroller.controlFace(-1)
if aimAngle > 0 then
aimAngle = math.max(aimAngle, math.pi - mechAimLimit)
else
aimAngle = math.min(aimAngle, -math.pi + mechAimLimit)
end
tech.rotateGroup("guns", math.pi + aimAngle)
else
tech.setFlipped(true)
local nudge = tech.transformedPosition({0, 0})
tech.setParentOffset({parentOffset[1] + nudge[1], parentOffset[2] + nudge[2]})
mcontroller.controlFace(1)
if aimAngle > 0 then
aimAngle = math.min(aimAngle, mechAimLimit)
else
aimAngle = math.max(aimAngle, -mechAimLimit)
end
tech.rotateGroup("guns", -aimAngle)
end
if not mcontroller.onGround() then
if mcontroller.velocity()[2] > 0 then
if args.actions["mechFire"] then
tech.setAnimationState("movement", "jumpAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "jumpAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "jumpAttack")
else
tech.setAnimationState("movement", "jump")
end
else
if args.actions["mechFire"] then
tech.setAnimationState("movement", "fallAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "fallAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "fallAttack")
else
tech.setAnimationState("movement", "fall")
end
end
elseif mcontroller.walking() or mcontroller.running() then
if flip and mcontroller.movingDirection() == 1 or not flip and mcontroller.movingDirection() == -1 then
if args.actions["mechFire"] then
tech.setAnimationState("movement", "backWalkAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "backWalkAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "backWalkAttack")
elseif args.actions["dashAttackRight"] then
tech.setAnimationState("movement", "backWalkDash")
elseif args.actions["dashAttackLeft"] then
tech.setAnimationState("movement", "backWalkDash")
else
tech.setAnimationState("movement", "backWalk")
end
else
if args.actions["mechFire"] then
tech.setAnimationState("movement", "walkAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "walkAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "walkAttack")
elseif args.actions["dashAttackRight"] then
tech.setAnimationState("movement", "walkDash")
elseif args.actions["dashAttackLeft"] then
tech.setAnimationState("movement", "walkDash")
else
tech.setAnimationState("movement", "walk")
end
end
else
if args.actions["mechFire"] then
tech.setAnimationState("movement", "idleAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "idleAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "idleAttack")
else
tech.setAnimationState("movement", "idle")
end
end
local telekinesisProjectile = tech.parameter("telekinesisProjectile")
local telekinesisProjectileConfig = tech.parameter("telekinesisProjectileConfig")
local telekinesisFireCycle = tech.parameter("telekinesisFireCycle")
local energyUsagePerSecondTelekinesis = tech.parameter("energyUsagePerSecondTelekinesis")
local energyUsageTelekinesis = energyUsagePerSecondTelekinesis * args.dt
if self.active and args.actions["grab"] and not self.grabbed then
local monsterIds = world.monsterQuery(tech.aimPosition(), 5)
for i,v in pairs(monsterIds) do
--world.spawnNpc( tech.aimPosition(), "glitch", "lonesurvivor_positionnpc", 2, 1)
world.monsterQuery(tech.aimPosition(),5, { callScript = "lonesurvivor_grab", callScriptArgs = { tech.aimPosition() } })
break
end
self.grabbed = true
elseif self.grabbed and not args.actions["grab"] then
--world.spawnNpc( tech.aimPosition(), "glitch", "lonesurvivor_positionnpc", 3, 1)
world.monsterQuery(tech.aimPosition(),30, { callScript = "lonesurvivor_release", callScriptArgs = { tech.aimPosition() } })
self.grabbed = false
elseif self.active and self.grabbed then
--world.spawnNpc( tech.aimPosition(), "glitch", "lonesurvivor_positionnpc", 1, 1)
world.monsterQuery(tech.aimPosition(),15, { callScript = "lonesurvivor_move", callScriptArgs = { tech.aimPosition() } })
end
if args.actions["grab"] and status.resource("energy") > energyUsageTelekinesis then
if self.fireTimer <= 0 then
world.spawnProjectile(telekinesisProjectile, tech.aimPosition(), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, telekinesisProjectileConfig)
self.fireTimer = self.fireTimer + telekinesisFireCycle
tech.setAnimationState("telekinesis", "telekinesisOn")
else
local oldFireTimer = self.fireTimer
self.fireTimer = self.fireTimer - args.dt
if oldFireTimer > telekinesisFireCycle / 2 and self.fireTimer <= telekinesisFireCycle / 2 then
end
end
return tech.consumeTechEnergy(energyUsageTelekinesis)
end
if args.actions["mechFire"] and status.resource("energy") > energyCostPerSecondPrim then
if self.fireTimer <= 0 then
world.spawnProjectile(mechProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontGun", "firePoint")), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechProjectileConfig)
self.fireTimer = self.fireTimer + mechFireCycle
tech.setAnimationState("frontFiring", "fire")
--tech.setParticleEmitterActive("jetpackParticles3", true)
-- local startPoint = vec2.add(mcontroller.position(), tech.partPoint("frontGun", "firePoint"))
-- local endPoint = vec_add(mcontroller.position(), {tech.partPoint("frontDashGun", "firePoint")[1] + mechGunBeamMaxRange * math.cos(aimAngle), tech.partPoint("frontDashGun", "firePoint")[2] + mechGunBeamMaxRange * math.sin(aimAngle) })
-- local beamCollision = progressiveLineCollision(startPoint, endPoint, mechGunBeamStep)
-- randomProjectileLine(startPoint, beamCollision, mechGunBeamStep, mechGunBeamSmokeProkectile, 0.08)
else
local oldFireTimer = self.fireTimer
self.fireTimer = self.fireTimer - args.dt
if oldFireTimer > mechFireCycle / 2 and self.fireTimer <= mechFireCycle / 2 then
end
end
return tech.consumeTechEnergy(energyCostPerSecondPrim)
end
if not args.actions["mechFire"] then
--tech.setParticleEmitterActive("jetpackParticles3", false)
end
if args.actions["mechAltFire"] and status.resource("energy") > energyCostPerSecondAlt then
if self.fireTimer <= 0 then
world.spawnProjectile(mechAltProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontAltGun", "firePoint")), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechAltProjectileConfig)
self.fireTimer = self.fireTimer + mechAltFireCycle
tech.setAnimationState("frontAltFiring", "fireAlt")
else
local oldFireTimer = self.fireTimer
self.fireTimer = self.fireTimer - args.dt
if oldFireTimer > mechAltFireCycle / 2 and self.fireTimer <= mechAltFireCycle / 2 then
end
end
return tech.consumeTechEnergy(energyCostPerSecondAlt)
end
if args.actions["mechSecFire"] and status.resource("energy") > energyCostPerSecondSec then
if self.fireTimer <= 0 then
world.spawnProjectile(mechSecProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontSecGun", "firePoint")), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechAltProjectileConfig)
self.fireTimer = self.fireTimer + mechSecFireCycle
tech.setAnimationState("frontSecFiring", "fireSec")
else
local oldFireTimer = self.fireTimer
self.fireTimer = self.fireTimer - args.dt
if oldFireTimer > mechSecFireCycle / 2 and self.fireTimer <= mechSecFireCycle / 2 then
end
end
return tech.consumeTechEnergy(energyCostPerSecondSec)
end
local jetpackSpeed = tech.parameter("jetpackSpeed")
local jetpackControlForce = tech.parameter("jetpackControlForce")
local energyUsagePerSecond = tech.parameter("energyUsagePerSecond")
local energyUsage = energyUsagePerSecond * args.dt
if status.resource("energy") < energyUsage then
self.ranOut = true
elseif mcontroller.onGround() or mcontroller.liquidMovement() then
self.ranOut = false
end
if args.actions["jetpack"] and not self.ranOut then
tech.setAnimationState("jetpack", "on")
mcontroller.controlApproachYVelocity(jetpackSpeed, jetpackControlForce, true)
return tech.consumeTechEnergy(energyUsage)
else
tech.setAnimationState("jetpack", "off")
return 0
end
-- local levitateSpeed = tech.parameter("levitateSpeed")
-- local levitateControlForce = tech.parameter("levitateControlForce")
-- local energyUsagePerSecondLevitate = tech.parameter("energyUsagePerSecondLevitate")
-- local energyUsagelevitate = energyUsagePerSecondLevitate * args.dt
-- if args.availableEnergy < energyUsagelevitate then
-- self.ranOut = true
-- elseif mcontroller.onGround() or mcontroller.liquidMovement() then
-- self.ranOut = false
-- end
-- if args.actions["levitate"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true)
-- self.levitateActivated = true
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitatehover"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(0, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(0, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateleft"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(0, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(-(levitateSpeed*self.speedMultiplier), levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateleftup"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(-(levitateSpeed*self.speedMultiplier), levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateleftdown"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(-(levitateSpeed)*0.5, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(-(levitateSpeed*self.speedMultiplier), levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateright"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(0, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(levitateSpeed*self.speedMultiplier, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitaterightup"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(levitateSpeed*self.speedMultiplier, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitaterightdown"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(-(levitateSpeed)*0,5, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(levitateSpeed*self.speedMultiplier, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateup"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(0, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitatedown"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(-(levitateSpeed)*0.5, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(0, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- else
-- self.levitateActivated = false
-- tech.setAnimationState("levitate", "off")
-- return 0
-- end
--return energyCostPerSecond * args.dt
end
return 0
end
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Selbina/npcs/Nomad_Moogle.lua | 34 | 1104 | -----------------------------------
--
-- Nomad Moogle
--
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,NOMAD_MOOGLE_DIALOG);
player:sendMenu(1);
end;
-----------------------------------
-- onEventUpdate Action
-----------------------------------
function onEventUpdate(player,csid,option)
--print("onEventUpdate");
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--print("onEventFinish");
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/The_Garden_of_RuHmet/bcnms/when_angels_fall.lua | 17 | 2249 | -----------------------------------
-- Area: The_Garden_of_RuHmet
-- Name: when_angels_fall
-----------------------------------
package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/zones/The_Garden_of_RuHmet/TextIDs");
-----------------------------------
-- EXAMPLE SCRIPT
--
-- What should go here:
-- giving key items, playing ENDING cutscenes
--
-- What should NOT go here:
-- Handling of "battlefield" status, spawning of monsters,
-- putting loot into treasure pool,
-- enforcing ANY rules (SJ/number of people/etc), moving
-- chars around, playing entrance CSes (entrance CSes go in bcnm.lua)
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus")==4) then
player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,0);
player:setVar("PromathiaStatus",5);
else
player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,1); --
end
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
--printf("leavecode: %u",leavecode);
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if (csid== 0x7d01) then
player:setPos(420,0,445,192);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Dynamis-Buburimu/mobs/Apocalyptic_Beast.lua | 1 | 1495 | -----------------------------------
-- Area: Dynamis Buburimu
-- MOB: Apocalyptic_Beast
-----------------------------------
package.loaded["scripts/zones/Dynamis-Buburimu/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Buburimu/TextIDs");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
if (GetServerVariable("[DynaBuburimu]Boss_Trigger")==0) then
--spwan additional mob :
for additionalmob = 16941489, 16941665, 1 do
if (additionalmob ~= 16941666 or additionalmob ~= 16941576 or additionalmob ~= 16941552 or additionalmob ~= 16941520) then
SpawnMob(additionalmob);
end
end
SetServerVariable("[DynaBuburimu]Boss_Trigger",1);
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer,ally)
if (ally:hasKeyItem(DYNAMIS_BUBURIMU_SLIVER ) == false) then
ally:addKeyItem(DYNAMIS_BUBURIMU_SLIVER);
ally:messageSpecial(KEYITEM_OBTAINED,DYNAMIS_BUBURIMU_SLIVER);
end
ally:addTitle(DYNAMISBUBURIMU_INTERLOPER);
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/items/bowl_of_adamantoise_soup.lua | 35 | 1607 | -----------------------------------------
-- ID: 5210
-- Item: Bowl of Adamantoise Soup
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Strength -7
-- Dexterity -7
-- Agility -7
-- Vitality -7
-- Intelligence -7
-- Mind -7
-- Charisma -7
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5210);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, -7);
target:addMod(MOD_DEX, -7);
target:addMod(MOD_AGI, -7);
target:addMod(MOD_VIT, -7);
target:addMod(MOD_INT, -7);
target:addMod(MOD_MND, -7);
target:addMod(MOD_CHR, -7);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, -7);
target:delMod(MOD_DEX, -7);
target:delMod(MOD_AGI, -7);
target:delMod(MOD_VIT, -7);
target:delMod(MOD_INT, -7);
target:delMod(MOD_MND, -7);
target:delMod(MOD_CHR, -7);
end;
| gpl-3.0 |
botmohammad12344888/bot-888338888 | plugins/azan.lua | 2 | 3156 | do
function run_bash(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
return result
end
local api_key = nil
local base_api = "https://maps.googleapis.com/maps/api"
function get_latlong(area)
local api = base_api .. "/geocode/json?"
local parameters = "address=".. (URL.escape(area) or "")
if api_key ~= nil then
parameters = parameters .. "&key="..api_key
end
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
lat = data.results[1].geometry.location.lat
lng = data.results[1].geometry.location.lng
acc = data.results[1].geometry.location_type
types= data.results[1].types
return lat,lng,acc,types
end
end
function get_staticmap(area)
local api = base_api .. "/staticmap?"
local lat,lng,acc,types = get_latlong(area)
local scale = types[1]
if scale=="locality" then zoom=8
elseif scale=="country" then zoom=4
else zoom = 13 end
local parameters =
"size=600x300" ..
"&zoom=" .. zoom ..
"¢er=" .. URL.escape(area) ..
"&markers=color:red"..URL.escape("|"..area)
if api_key ~=nil and api_key ~= "" then
parameters = parameters .. "&key="..api_key
end
return lat, lng, api..parameters
end
function run(msg, matches)
local hash = 'usecommands:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
local receiver = get_receiver(msg)
local city = matches[1]
if matches[1] == 'praytime' then
city = 'Tehran'
end
local lat,lng,url = get_staticmap(city)
local dumptime = run_bash('date +%s')
local code = http.request('http://api.aladhan.com/timings/'..dumptime..'?latitude='..lat..'&longitude='..lng..'&timezonestring=Asia/Tehran&method=7')
local jdat = json:decode(code)
local data = jdat.data.timings
local text = 'شهر: '..city
text = text..'\nاذان صبح: '..data.Fajr
text = text..'\nطلوع آفتاب: '..data.Sunrise
text = text..'\nاذان ظهر: '..data.Dhuhr
text = text..'\nغروب آفتاب: '..data.Sunset
text = text..'\nاذان مغرب: '..data.Maghrib
text = text..'\nعشاء : '..data.Isha
text = text..'\n\n@kingpowerobot ch:@kingpowerch'
if string.match(text, '0') then text = string.gsub(text, '0', '۰') end
if string.match(text, '1') then text = string.gsub(text, '1', '۱') end
if string.match(text, '2') then text = string.gsub(text, '2', '۲') end
if string.match(text, '3') then text = string.gsub(text, '3', '۳') end
if string.match(text, '4') then text = string.gsub(text, '4', '۴') end
if string.match(text, '5') then text = string.gsub(text, '5', '۵') end
if string.match(text, '6') then text = string.gsub(text, '6', '۶') end
if string.match(text, '7') then text = string.gsub(text, '7', '۷') end
if string.match(text, '8') then text = string.gsub(text, '8', '۸') end
if string.match(text, '9') then text = string.gsub(text, '9', '۹') end
return text
end
return {
patterns = {
"^اوقات شرقی (.*)$",
"^(اوقات شرقی)$"
},
run = run
}
end
| gpl-2.0 |
SpRoXx/GTW-RPG | [resources]/GTWtramdriver/tram_s.lua | 1 | 8453 | --[[
********************************************************************************
Project owner: RageQuit community
Project name: GTW-RPG
Developers: Mr_Moose
Source code: https://github.com/GTWCode/GTW-RPG/
Bugtracker: http://forum.404rq.com/bug-reports/
Suggestions: http://forum.404rq.com/mta-servers-development/
Version: Open source
License: BSD 2-Clause
Status: Stable release
********************************************************************************
]]--
-- Globally accessible tables
local tram_payment_timers = { }
--[[ Find and return the ID of nearest station ]]--
function find_nearest_station(plr, route)
if not plr or not isElement(plr) or getElementType(plr) ~= "player" then return 1 end
local x,y,z = getElementPosition(plr)
local ID,total_dist = 1,9999
for k=1, #tram_routes[route] do
local dist = getDistanceBetweenPoints3D(tram_routes[route][k][1],tram_routes[route][k][2],tram_routes[route][k][3], x,y,z)
if dist < total_dist then
total_dist = dist
ID = k
end
end
return ID
end
--[[ Calculate the ID for next tramstation and inform the passengers ]]--
function create_new_tram_station(plr, ID)
-- There must be a route at this point
if not plr or not getElementData(plr, "GTWtramdriver.currentRoute") then return end
-- Did we reach the end of the line yet? if so then restart the same route
if #tram_routes[getElementData(plr, "GTWtramdriver.currentRoute")] < ID then
ID = 1;
setElementData(plr, "GTWtramdriver.currentstation", 1)
end
-- Get the coordinates of the next station from our table
local x,y,z = tram_routes[getElementData(plr, "GTWtramdriver.currentRoute")][ID][1],
tram_routes[getElementData(plr, "GTWtramdriver.currentRoute")][ID][2],
tram_routes[getElementData(plr, "GTWtramdriver.currentRoute")][ID][3]
-- Tell the client to make a marker and a blip for the tramdriver
triggerClientEvent(plr, "GTWtramdriver.createtramstation", plr, x,y,z)
-- Get the tram object and check for passengers in it
local veh = getPedOccupiedVehicle(plr)
if not veh then return end
local passengers = getVehicleOccupants(veh)
if not passengers then return end
-- Alright, we got some passengers, let's tell them where we're going
for k,pa in pairs(passengers) do
setTimer(delayed_message, 10000, 1, "Next station: "..getZoneName(x,y,z)..
" in "..getZoneName(x,y,z, true), pa, 55,200, 0)
end
-- Save the station ID
setElementData(plr, "GTWtramdriver.currentstation", ID)
end
--[[ Drivers get's a route asigned while passengers has to pay when entering the tram ]]--
function on_tram_enter(plr, seat, jacked)
-- Make sure the vehicle is a tram
if not tram_vehicles[getElementModel(source)] then return end
if getElementType(plr) ~= "player" then return end
-- Start the payment timer for passengers entering the tram
if seat > 0 then
driver = getVehicleOccupant(source, 0)
if driver and getElementType(driver) == "player" and getPlayerTeam(driver) and
getPlayerTeam(driver) == getTeamFromName( "Civilians" ) and
getElementData(driver, "Occupation") == "Tram Driver" then
-- Initial payment
pay_for_the_ride(driver, plr)
-- Kill the timer if it exist and make a new one
if isTimer( tram_payment_timers[plr] ) then
killTimer( tram_payment_timers[plr] )
end
tram_payment_timers[plr] = setTimer(pay_for_the_ride, 30000, 0, driver, plr)
end
end
-- Whoever entered the tram is a tramdriver
if getPlayerTeam(plr) and getPlayerTeam(plr) == getTeamFromName("Civilians") and
getElementData(plr, "Occupation") == "Tram Driver" and
seat == 0 and tram_vehicles[getElementModel(source )] then
-- Let him choose a route to drive
triggerClientEvent(plr, "GTWtramdriver.selectRoute", plr)
end
end
addEventHandler("onVehicleEnter", root, on_tram_enter)
--[[ A new route has been selected, load it's data ]]--
function start_new_route(route)
setElementData(client, "GTWtramdriver.currentRoute", route)
if not getElementData(client, "GTWtramdriver.currentstation") then
local first_station = find_nearest_station(client, route)
create_new_tram_station(client, first_station)
else
create_new_tram_station(client, getElementData(client, "GTWtramdriver.currentstation"))
end
exports.GTWtopbar:dm("Drive your tram to the first station to start your route", client, 0, 255, 0)
end
addEvent("GTWtramdriver.selectRouteReceive", true)
addEventHandler("GTWtramdriver.selectRouteReceive", root, start_new_route)
--[[ Handles payments in trams ]]--
function pay_for_the_ride(driver, passenger, first)
-- Make sure that both the driver and passenger are players
if not driver or not isElement(driver) or getElementType(driver) ~= "player" then return end
if not passenger or not isElement(passenger) or getElementType(passenger) ~= "player" then return end
-- Make sure the passenger is still inside the tram
local veh = getPedOccupiedVehicle(driver)
if getVehicleOccupant(veh, 0) == driver and getElementData(driver, "Occupation") == "Tram Driver" then
-- First payment are more expensive
if first then
takePlayerMoney( passenger, 25 )
givePlayerMoney( driver, 25 )
else
takePlayerMoney( passenger, 5 )
givePlayerMoney( driver, 5 )
end
else
-- Throw the passenger out if he can't pay for the ride any more
removePedFromVehicle ( passenger )
if isElement(tram_payment_timers[passenger]) then
killTimer(tram_payment_timers[passenger])
end
exports.GTWtopbar:dm( "You can't afford this tram ride anymore!", passenger, 255, 0, 0 )
end
end
--[[ station the payment timer when a passenger exit the tram ]]--
function vehicle_exit(plr, seat, jacked)
if isTimer(tram_payment_timers[plr]) then
killTimer(tram_payment_timers[plr])
end
end
addEventHandler("onVehicleExit", root, vehicle_exit)
--[[ Calculate the next station ]]--
function calculate_next_station(td_payment)
-- Make sure the player is driving a tram
if not isPedInVehicle(client) then return end
if not tram_vehicles[getElementModel(getPedOccupiedVehicle(client))] then return end
-- Calculate the payment minus charges for damage
local fine = math.floor(td_payment -
(td_payment*(1-(getElementHealth(getPedOccupiedVehicle(client))/1000))))
-- Increase stats by 1
local playeraccount = getPlayerAccount(client)
local tram_stations = (getAccountData(playeraccount, "acorp_stats_tram_stations") or 0) + 1
setAccountData(playeraccount, "acorp_stats_tram_stations", tram_stations)
-- Pay the driver
givePlayerMoney(client, fine + math.floor(tram_stations/4))
-- Notify about the payment reduce if the tram is damaged
if math.floor(td_payment - fine) > 1 then
takePlayerMoney(client, math.floor(td_payment - fine))
exports.GTWtopbar:dm("Removed $"..tostring(math.floor(td_payment - fine)).." due to damage on your tram!",
client, 255, 0, 0)
end
-- Get the next station on the list
if #tram_routes[getElementData(client, "GTWtramdriver.currentRoute")] ==
tonumber(getElementData(client, "GTWtramdriver.currentstation")) then
setElementData( client, "GTWtramdriver.currentstation", 1)
else
setElementData(client, "GTWtramdriver.currentstation", tonumber(
getElementData(client, "GTWtramdriver.currentstation" ))+1)
end
-- Force the client to create markers and blips for the next station
create_new_tram_station(client, tonumber(getElementData(client, "GTWtramdriver.currentstation")))
end
addEvent("GTWtramdriver.paytramDriver", true)
addEventHandler("GTWtramdriver.paytramDriver", resourceRoot, calculate_next_station)
--[[ A little hack for developers to manually change the route ID ]]--
function set_manual_station(plr, cmd, ID)
local is_staff = exports.GTWstaff:isStaff(plr)
if not is_staff then return end
setElementData(plr, "GTWtramdriver.currentstation", tonumber(ID) or 1)
create_new_tram_station(plr, tonumber(ID) or 1)
end
addCommandHandler("settramstation", set_manual_station)
--[[ Display a delayed message securely ]]--
function delayed_message(text, plr, r,g,b, color_coded)
if not plr or not isElement(plr) or getElementType(plr) ~= "player" then return end
if not getPlayerTeam(plr) or getPlayerTeam(plr) ~= getTeamFromName("Civilians") or
getElementData(plr, "Occupation") ~= "Tram Driver" then return end
if not getPedOccupiedVehicle(plr) or not tram_vehicles[getElementModel(getPedOccupiedVehicle(plr))] then return end
exports.GTWtopbar:dm(text, plr, r,g,b, color_coded)
end
| bsd-2-clause |
Keithenneu/Dota2-FullOverwrite | abilityUse/abilityUse_viper.lua | 1 | 10629 | -------------------------------------------------------------------------------
--- AUTHOR: Nostrademous
--- GITHUB REPO: https://github.com/Nostrademous/Dota2-FullOverwrite
-------------------------------------------------------------------------------
BotsInit = require( "game/botsinit" )
local viperAbility = BotsInit.CreateGeneric()
require( GetScriptDirectory().."/fight_simul" )
require( GetScriptDirectory().."/modifiers" )
local utils = require( GetScriptDirectory().."/utility" )
local gHeroVar = require( GetScriptDirectory().."/global_hero_data" )
function setHeroVar(var, value)
gHeroVar.SetVar(GetBot():GetPlayerID(), var, value)
end
function getHeroVar(var)
return gHeroVar.GetVar(GetBot():GetPlayerID(), var)
end
local Abilities ={
"viper_poison_attack",
"viper_nethertoxin",
"viper_corrosive_skin",
"viper_viper_strike"
}
local abilityQ = ""
local abilityW = ""
local abilityE = ""
local abilityR = ""
local DoTdpsQ = 0
local DoTdpsUlt = 0
local AttackRange = 0
local ManaPerc = 0
local modeName = nil
function viperAbility:nukeDamage( bot, enemy )
if not utils.ValidTarget(enemy) then return 0, {}, 0, 0, 0 end
local comboQueue = {}
local manaAvailable = bot:GetMana()
local dmgTotal = 0
local castTime = 0
local stunTime = 0
local slowTime = 0
local engageDist = bot:GetAttackRange()+bot:GetBoundingRadius()
local magicImmune = utils.IsTargetMagicImmune(enemy)
local baseRightClickDmg = CalcRightClickDmg(bot, enemy)
-- Check Viper Strike
if abilityR:IsFullyCastable() then
local manaCostR = abilityR:GetManaCost()
if manaCostR <= manaAvailable then
if not magicImmune then
manaAvailable = manaAvailable - manaCostR
dmgTotal = dmgTotal + enemy:GetActualIncomingDamage(abilityR:GetAbilityDamage(), DAMAGE_TYPE_MAGICAL)
castTime = castTime + abilityR:GetCastPoint()
slowTime = slowTime + 5.1
engageDist = Min(engageDist, abilityR:GetCastRange())
table.insert(comboQueue, abilityR)
end
end
end
-- Check Poison Attack
if abilityQ:IsFullyCastable() then
if not magicImmune then
local manaCostQ = abilityQ:GetManaCost()
local numCasts = Min(bot:GetLevel(), 4)
if abilityR:IsFullyCastable() then
numCasts = math.ceil(5.1/bot:GetSecondsPerAttack())
end
for i = 1, numCasts, 1 do
if manaCostQ <= manaAvailable then
manaAvailable = manaAvailable - manaCostQ
dmgTotal = dmgTotal + baseRightClickDmg + enemy:GetActualIncomingDamage(DoTdpsQ, DAMAGE_TYPE_MAGICAL)
castTime = castTime + bot:GetAttackPoint()
slowTime = slowTime + 2.0
table.insert(comboQueue, abilityQ)
end
end
end
end
return dmgTotal, comboQueue, castTime, stunTime, slowTime, engageDist
end
function viperAbility:queueNuke(bot, enemy, castQueue, engageDist)
if not utils.ValidTarget(enemy) then return false end
local dist = GetUnitToUnitDistance(bot, enemy)
-- if out of range, attack move for one hit to get in range
if dist < engageDist then
bot:Action_ClearActions(false)
utils.AllChat("Killing "..utils.GetHeroName(enemy).." softly with my song")
utils.myPrint("Queue Nuke Damage: ", utils.GetHeroName(enemy))
for i = #castQueue, 1, -1 do
local skill = castQueue[i]
if skill:GetName() == Abilities[1] then
gHeroVar.HeroPushUseAbilityOnEntity(bot, skill, enemy)
elseif skill:GetName() == Abilities[4] then
gHeroVar.HeroPushUseAbilityOnEntity(bot, skill, enemy)
end
end
return true
end
return false
end
function CalcRightClickDmg(bot, target)
if not utils.ValidTarget(target) then return 0 end
local bonusDmg = 0
if abilityW ~= nil and abilityW:GetLevel() > 0 then
bonusDmg = abilityW:GetSpecialValueFloat("bonus_damage")
local tgtHealthPrct = target:GetHealth()/target:GetMaxHealth()
local healthRank = math.ceil(tgtHealthPrct/20)
bonusDmg = bonusDmg * math.pow(2, 5-healthRank)
end
local rightClickDmg = bot:GetAttackDamage() + bonusDmg
local actualDmg = target:GetActualIncomingDamage(rightClickDmg, DAMAGE_TYPE_PHYSICAL)
return actualDmg
end
function ComboDmg(bot, target)
if not utils.ValidTarget(target) then return 0 end
local dmg, castQueue, castTime, stunTime, slowTime, engageDist = viperAbility:nukeDamage( bot, target )
local rightClickTime = stunTime + slowTime -- in Viper's case we don't discount the slow as he can cast it indefinitely (mana providing)
DoTdpsQ = target:GetActualIncomingDamage(abilityQ:GetSpecialValueInt("damage"), DAMAGE_TYPE_MAGICAL)
DoTdpsR = abilityR:GetSpecialValueInt("damage")
if bot:GetLevel() >= 25 then
local unique2 = bot:GetAbilityByName("special_bonus_unique_viper_2")
if unique2 and unique2:GetLevel() >= 1 then
DoTdpsR = DoTdpsR + 80
end
end
DoTdpsR = target:GetActualIncomingDamage(DoTdpsR, DAMAGE_TYPE_MAGICAL)
local totalDmgPerSec = (CalcRightClickDmg(bot, target) + DoTdpsR + DoTdpsQ)/bot:GetSecondsPerAttack()
return totalDmgPerSec*rightClickTime
end
function viperAbility:AbilityUsageThink(bot)
if utils.IsBusy(bot) then return true end
if utils.IsUnableToCast(bot) then return false end
if abilityQ == "" then abilityQ = bot:GetAbilityByName( Abilities[1] ) end
if abilityW == "" then abilityW = bot:GetAbilityByName( Abilities[2] ) end
if abilityE == "" then abilityE = bot:GetAbilityByName( Abilities[3] ) end
if abilityR == "" then abilityR = bot:GetAbilityByName( Abilities[4] ) end
AttackRange = bot:GetAttackRange() + bot:GetBoundingRadius()
ManaPerc = bot:GetMana()/bot:GetMaxMana()
modeName = bot.SelfRef:getCurrentMode():GetName()
-- Consider using each ability
local castQDesire, castQTarget = ConsiderQ()
local castRDesire, castRTarget = ConsiderR()
if castRDesire > 0 then
gHeroVar.HeroUseAbilityOnEntity(bot, abilityR, castRTarget)
return true
end
if castQDesire > 0 then
gHeroVar.HeroUseAbilityOnEntity(bot, abilityQ, castQTarget)
return true
end
return false
end
function ConsiderQ()
local bot = GetBot()
if not abilityQ:IsFullyCastable() then
return BOT_ACTION_DESIRE_NONE, nil
end
if modeName ~= "retreat" or (modeName == "retreat" and bot.SelfRef:getCurrentModeValue() < BOT_MODE_DESIRE_VERYHIGH) then
local WeakestEnemy, HeroHealth = utils.GetWeakestHero(bot, AttackRange + 100)
if utils.ValidTarget(WeakestEnemy) then
if not utils.IsTargetMagicImmune(WeakestEnemy) and not utils.IsCrowdControlled(WeakestEnemy) then
if HeroHealth <= WeakestEnemy:GetActualIncomingDamage(ComboDmg(bot, WeakestEnemy), DAMAGE_TYPE_PHYSICAL) then
return BOT_ACTION_DESIRE_HIGH, WeakestEnemy
end
end
end
end
-- If we're going after someone
if modeName == "roam" or modeName == "defendally" or modeName == "fight" then
local npcEnemy = getHeroVar("RoamTarget")
if npcEnemy == nil then npcEnemy = getHeroVar("Target") end
if utils.ValidTarget(npcEnemy) then
if not utils.IsTargetMagicImmune(npcEnemy) and not utils.IsCrowdControlled(npcEnemy) and
GetUnitToUnitDistance(bot, npcEnemy) < (AttackRange + 75*#gHeroVar.GetNearbyAllies(bot,1200)) then
return BOT_ACTION_DESIRE_MODERATE, npcEnemy
end
end
end
-- If we are pushing a lane and have our level 25 building unique talent
if modeName == "pushlane" and ManaPerc > 0.25 then
local unique1 = bot:GetAbilityByName("special_bonus_unique_viper_1")
if unique1 and unique1:GetLevel() >= 1 then
local at = bot:GetAttackTarget()
if utils.NotNilOrDead(at) and at:IsBuilding() then
return BOT_ACTION_DESIRE_MODERATE, at
end
end
end
-- laning harassment
if modeName == "laning" and ManaPerc > 0.4 then
local WeakestEnemy, HeroHealth = utils.GetWeakestHero(bot, AttackRange)
if utils.ValidTarget(WeakestEnemy) then
if not utils.IsTargetMagicImmune(WeakestEnemy) and not utils.IsCrowdControlled(WeakestEnemy) then
return BOT_ACTION_DESIRE_LOW, WeakestEnemy
end
end
end
-- jungling
if modeName == "jungling" and ManaPerc > 0.25 then
local neutralCreeps = gHeroVar.GetNearbyEnemyCreep(bot, AttackRange)
for _, creep in pairs(neutralCreeps) do
if not creep:HasModifier("modifier_viper_poison_attack_slow") and not creep:IsAncientCreep() then
return BOT_ACTION_DESIRE_LOW, creep
end
end
end
return BOT_ACTION_DESIRE_NONE, nil
end
function ConsiderR()
local bot = GetBot()
if not abilityR:IsFullyCastable() then
return BOT_ACTION_DESIRE_NONE, nil
end
if modeName ~= "retreat" or (modeName == "retreat" and bot.SelfRef:getCurrentModeValue() < BOT_MODE_DESIRE_VERYHIGH) then
local WeakestEnemy, HeroHealth = utils.GetWeakestHero(bot, AttackRange + 100)
if utils.ValidTarget(WeakestEnemy) then
if not utils.IsTargetMagicImmune(WeakestEnemy) and not utils.IsCrowdControlled(WeakestEnemy) then
if HeroHealth <= WeakestEnemy:GetActualIncomingDamage(ComboDmg(bot, WeakestEnemy), DAMAGE_TYPE_PHYSICAL) then
return BOT_ACTION_DESIRE_HIGH, WeakestEnemy
end
end
end
end
-- If we're going after someone
if modeName == "roam" or modeName == "defendally" or modeName == "fight" then
local npcEnemy = getHeroVar("RoamTarget")
if npcEnemy == nil then npcEnemy = getHeroVar("Target") end
if utils.ValidTarget(npcEnemy) then
if not utils.IsTargetMagicImmune(npcEnemy) and not utils.IsCrowdControlled(npcEnemy) and
GetUnitToUnitDistance(bot, npcEnemy) < (AttackRange + 75*#gHeroVar.GetNearbyAllies(bot,1200)) then
return BOT_ACTION_DESIRE_MODERATE, npcEnemy
end
end
end
return BOT_ACTION_DESIRE_NONE, nil
end
return viperAbility
| gpl-3.0 |
VincentGong/chess | cocos2d-x/cocos/scripting/lua-bindings/auto/api/LinearLayoutParameter.lua | 4 | 1258 |
--------------------------------
-- @module LinearLayoutParameter
-- @extend LayoutParameter
--------------------------------
-- @function [parent=#LinearLayoutParameter] setGravity
-- @param self
-- @param #ccui.LinearLayoutParameter::LinearGravity lineargravity
--------------------------------
-- @function [parent=#LinearLayoutParameter] getGravity
-- @param self
-- @return LinearLayoutParameter::LinearGravity#LinearLayoutParameter::LinearGravity ret (return value: ccui.LinearLayoutParameter::LinearGravity)
--------------------------------
-- @function [parent=#LinearLayoutParameter] create
-- @param self
-- @return LinearLayoutParameter#LinearLayoutParameter ret (return value: ccui.LinearLayoutParameter)
--------------------------------
-- @function [parent=#LinearLayoutParameter] createCloneInstance
-- @param self
-- @return LayoutParameter#LayoutParameter ret (return value: ccui.LayoutParameter)
--------------------------------
-- @function [parent=#LinearLayoutParameter] copyProperties
-- @param self
-- @param #ccui.LayoutParameter layoutparameter
--------------------------------
-- @function [parent=#LinearLayoutParameter] LinearLayoutParameter
-- @param self
return nil
| mit |
jshackley/darkstar | scripts/zones/Kazham/npcs/HomePoint#1.lua | 17 | 1239 | -----------------------------------
-- Area: Kazham
-- NPC: HomePoint#1
-- @pos 77.654 -13.000 -94.457 250
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Kazham/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 39);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Windurst_Walls/npcs/Selulu.lua | 38 | 1029 | ----------------------------------
-- Area: Windurst Walls
-- NPC: Selulu
-- Type: Item Deliverer
-- @zone: 239
-- @pos 58.027 -2.5 -60.548
--
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
require("scripts/zones/Windurst_Walls/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, ITEM_DELIVERY_DIALOG);
player:openSendBox();
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/globals/items/timbre_timbers_taco.lua | 35 | 1566 | -----------------------------------------
-- ID: 5173
-- Item: timbre_timbers_taco
-- Food Effect: 1hour, All Races
-----------------------------------------
-- MP 20
-- Vitality -1
-- Agility 5
-- MP Recovered While Healing 3
-- Ranged Accuracy % 8 (cap 15)
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5173);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 20);
target:addMod(MOD_VIT, -1);
target:addMod(MOD_AGI, 5);
target:addMod(MOD_MPHEAL, 3);
target:addMod(MOD_FOOD_RACCP, 8);
target:addMod(MOD_FOOD_RACC_CAP, 15);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 20);
target:delMod(MOD_VIT, -1);
target:delMod(MOD_AGI, 5);
target:delMod(MOD_MPHEAL, 3);
target:delMod(MOD_FOOD_RACCP, 8);
target:delMod(MOD_FOOD_RACC_CAP, 15);
end;
| gpl-3.0 |
ByteFun/Starbound_mods | smount/tech/mech/mount38/mount38.lua | 7 | 34280 | function checkCollision(position)
local boundBox = mcontroller.boundBox()
boundBox[1] = boundBox[1] - mcontroller.position()[1] + position[1]
boundBox[2] = boundBox[2] - mcontroller.position()[2] + position[2]
boundBox[3] = boundBox[3] - mcontroller.position()[1] + position[1]
boundBox[4] = boundBox[4] - mcontroller.position()[2] + position[2]
return not world.rectCollision(boundBox)
end
function randomProjectileLine(startPoint, endPoint, stepSize, projectile, chanceToSpawn)
local dist = math.distance(startPoint, endPoint)
local steps = math.floor(dist / stepSize)
local normX = (endPoint[1] - startPoint[1]) / dist
local normY = (endPoint[2] - startPoint[2]) / dist
for i = 0, steps do
local p1 = { normX * i * stepSize + startPoint[1], normY * i * stepSize + startPoint[2]}
local p2 = { normX * (i + 1) * stepSize + startPoint[1] + math.random(-1, 1), normY * (i + 1) * stepSize + startPoint[2] + math.random(-1, 1)}
if math.random() <= chanceToSpawn then
world.spawnProjectile(projectile, math.midPoint(p1, p2), entity.id(), {normX, normY}, false)
end
end
return endPoint
end
function blinkAdjust(position, doPathCheck, doCollisionCheck, doLiquidCheck, doStandCheck)
local blinkCollisionCheckDiameter = tech.parameter("blinkCollisionCheckDiameter")
local blinkVerticalGroundCheck = tech.parameter("blinkVerticalGroundCheck")
local blinkFootOffset = tech.parameter("blinkFootOffset")
if doPathCheck then
local collisionBlocks = world.collisionBlocksAlongLine(mcontroller.position(), position, true, 1)
if #collisionBlocks ~= 0 then
local diff = world.distance(position, mcontroller.position())
diff[1] = diff[1] / math.abs(diff[1])
diff[2] = diff[2] / math.abs(diff[2])
position = {collisionBlocks[1][1] - diff[1], collisionBlocks[1][2] - diff[2]}
end
end
if doCollisionCheck and not checkCollision(position) then
local spaceFound = false
for i = 1, blinkCollisionCheckDiameter * 2 do
if checkCollision({position[1] + i / 2, position[2] + i / 2}) then
position = {position[1] + i / 2, position[2] + i / 2}
spaceFound = true
break
end
if checkCollision({position[1] - i / 2, position[2] + i / 2}) then
position = {position[1] - i / 2, position[2] + i / 2}
spaceFound = true
break
end
if checkCollision({position[1] + i / 2, position[2] - i / 2}) then
position = {position[1] + i / 2, position[2] - i / 2}
spaceFound = true
break
end
if checkCollision({position[1] - i / 2, position[2] - i / 2}) then
position = {position[1] - i / 2, position[2] - i / 2}
spaceFound = true
break
end
end
if not spaceFound then
return nil
end
end
if doStandCheck then
local groundFound = false
for i = 1, blinkVerticalGroundCheck * 2 do
local checkPosition = {position[1], position[2] - i / 2}
if world.pointCollision(checkPosition, false) then
groundFound = true
position = {checkPosition[1], checkPosition[2] + 0.5 - blinkFootOffset}
break
end
end
if not groundFound then
return nil
end
end
if doLiquidCheck and (world.liquidAt(position) or world.liquidAt({position[1], position[2] + blinkFootOffset})) then
return nil
end
if doCollisionCheck and not checkCollision(position) then
return nil
end
return position
end
function findRandomBlinkLocation(doCollisionCheck, doLiquidCheck, doStandCheck)
local randomBlinkTries = tech.parameter("randomBlinkTries")
local randomBlinkDiameter = tech.parameter("randomBlinkDiameter")
for i=1,randomBlinkTries do
local position = mcontroller.position()
position[1] = position[1] + (math.random() * 2 - 1) * randomBlinkDiameter
position[2] = position[2] + (math.random() * 2 - 1) * randomBlinkDiameter
local position = blinkAdjust(position, false, doCollisionCheck, doLiquidCheck, doStandCheck)
if position then
return position
end
end
return nil
end
function init()
self.level = tech.parameter("mechLevel", 6)
self.mechState = "off"
self.mechStateTimer = 0
self.specialLast = false
self.active = false
self.fireTimer = 0
tech.setVisible(false)
tech.rotateGroup("guns", 0, true)
self.multiJumps = 0
self.lastJump = false
self.mode = "none"
self.timer = 0
self.targetPosition = nil
self.grabbed = false
self.holdingJump = false
self.ranOut = false
self.airDashing = false
self.dashTimer = 0
self.dashDirection = 0
self.dashLastInput = 0
self.dashTapLast = 0
self.dashTapTimer = 0
self.dashAttackfireTimer = 0
self.dashAttackTimer = 0
self.dashAttackDirection = 0
self.dashAttackLastInput = 0
self.dashAttackTapLast = 0
self.dashAttackTapTimer = 0
self.holdingUp = false
self.holdingDown = false
self.holdingLeft = false
self.holdingRight = false
self.speedMultiplier = 1.1
self.levitateActivated = false
self.mechTimer = 0
end
function uninit()
if self.active then
local mechTransformPositionChange = tech.parameter("mechTransformPositionChange")
mcontroller.translate({-mechTransformPositionChange[1], -mechTransformPositionChange[2]})
tech.setParentOffset({0, 0})
self.active = false
tech.setVisible(false)
tech.setParentState()
tech.setToolUsageSuppressed(false)
mcontroller.controlFace(nil)
end
end
function input(args)
if self.dashTimer > 0 then
return nil
end
local maximumDoubleTapTime = tech.parameter("maximumDoubleTapTime")
if self.dashTapTimer > 0 then
self.dashTapTimer = self.dashTapTimer - args.dt
end
if args.moves[""] and self.active then
if self.dashLastInput ~= 1 then
if self.dashTapLast == 1 and self.dashTapTimer > 0 then
self.dashTapLast = 0
self.dashTapTimer = 0
return "dashRight"
else
self.dashTapLast = 1
self.dashTapTimer = maximumDoubleTapTime
end
end
self.dashLastInput = 1
elseif args.moves[""] and self.active then
if self.dashLastInput ~= -1 then
if self.dashTapLast == -1 and self.dashTapTimer > 0 then
self.dashTapLast = 0
self.dashTapTimer = 0
return "dashLeft"
else
self.dashTapLast = -1
self.dashTapTimer = maximumDoubleTapTime
end
end
self.dashLastInput = -1
else
self.dashLastInput = 0
end
if args.moves["jump"] and mcontroller.jumping() then
self.holdingJump = true
elseif not args.moves["jump"] then
self.holdingJump = false
end
if args.moves["special"] == 1 then
if self.active then
return "mechDeactivate"
else
return "mechActivate"
end
elseif args.moves[""] == 2 and self.active then
return "blink"
elseif args.moves[""] and args.moves[""] and args.moves[""] and not self.levitateActivated and self.active then
return "grab"
elseif args.moves["down"] and args.moves["right"] and not self.levitateActivated and self.active then
return "dashAttackRight"
elseif args.moves["down"] and args.moves["left"] and not self.levitateActivated and self.active then
return "dashAttackLeft"
elseif args.moves[""] and self.active then
return "mechFire"
elseif args.moves[""] and self.active then
return "mechAltFire"
elseif args.moves[""] and args.moves[""] and self.active then
return "mechSecFire"
elseif args.moves[""] and not mcontroller.canJump() and not self.holdingJump and self.active then
return "jetpack"
elseif args.moves[""] and not mcontroller.jumping() and not mcontroller.canJump() and not self.lastJump then
self.lastJump = true
return "multiJump"
else
self.lastJump = args.moves["jump"]
end
self.specialLast = args.moves["special"] == 1
--RedOrb
-- if args.moves["left"] then
-- self.holdingLeft = true
-- elseif not args.moves["left"] then
-- self.holdingLeft = false
-- end
-- if args.moves["right"] then
-- self.holdingRight = true
-- elseif not args.moves["right"] then
-- self.holdingRight = false
-- end
-- if args.moves["up"] then
-- self.holdingUp = true
-- elseif not args.moves["up"] then
-- self.holdingUp = false
-- end
-- if args.moves["down"] then
-- self.holdingDown = true
-- elseif not args.moves["down"] then
-- self.holdingDown = false
-- end
-- if not args.moves["jump"] and not args.moves["left"]and not args.moves["right"]and not args.moves["up"]and not args.moves["down"] and not tech.canJump() and not self.holdingJump and self.levitateActivated then
-- return "levitatehover"
-- elseif args.moves["jump"] and not tech.canJump() and not self.holdingJump then
-- return "levitate"
-- elseif args.moves["left"] and args.moves["right"] and not tech.canJump() and self.levitateActivated then
-- return "levitatehover"
-- elseif args.moves["up"] and args.moves["down"] and not tech.canJump() and self.levitateActivated then
-- return "levitatehover"
-- elseif (args.moves["jump"] or args.moves["up"]) and args.moves["left"] and not tech.canJump() and not self.holdingRight and self.levitateActivated then
-- return "levitateleftup"
-- elseif (args.moves["jump"] or args.moves["up"]) and args.moves["right"] and not tech.canJump() and not self.holdingLeft and self.levitateActivated then
-- return "levitaterightup"
-- elseif args.moves["down"] and args.moves["left"] and not tech.canJump() and not self.holdingRight and self.levitateActivated then
-- return "levitateleftdown"
-- elseif args.moves["down"] and args.moves["right"] and not tech.canJump() and not self.holdingLeft and self.levitateActivated then
-- return "levitaterightdown"
-- elseif args.moves["left"] and not tech.canJump() and not self.holdingRight and self.levitateActivated then
-- return "levitateleft"
-- elseif args.moves["right"] and not tech.canJump() and not self.holdingLeft and self.levitateActivated then
-- return "levitateright"
-- elseif args.moves["up"] and not tech.canJump() and not self.holdingDown and self.levitateActivated then
-- return "levitateup"
-- elseif args.moves["down"] and not tech.canJump() and not self.holdingUp and self.levitateActivated then
-- return "levitatedown"
-- else
-- return nil
-- end
--RedOrbEnd
end
function update(args)
if self.mechTimer > 0 then
self.mechTimer = self.mechTimer - args.dt
end
local dashControlForce = tech.parameter("dashControlForce")
local dashSpeed = tech.parameter("dashSpeed")
local dashDuration = tech.parameter("dashDuration")
local energyUsageDash = tech.parameter("energyUsageDash")
local usedEnergy = 0
if args.actions["dashRight"] and self.dashTimer <= 0 and status.resource("energy") > energyUsageDash then
self.dashTimer = dashDuration
self.dashDirection = 1
usedEnergy = energyUsageDash
self.airDashing = not mcontroller.onGround()
return tech.consumeTechEnergy(energyUsageDash)
elseif args.actions["dashLeft"] and self.dashTimer <= 0 and status.resource("energy") > energyUsageDash then
self.dashTimer = dashDuration
self.dashDirection = -1
usedEnergy = energyUsageDash
self.airDashing = not mcontroller.onGround()
return tech.consumeTechEnergy(energyUsageDash)
end
if self.dashTimer > 0 then
mcontroller.controlApproachXVelocity(dashSpeed * self.dashDirection, dashControlForce, true)
if self.airDashing then
mcontroller.controlParameters({gravityEnabled = false})
mcontroller.controlApproachYVelocity(0, dashControlForce, true)
end
if self.dashDirection == -1 then
mcontroller.controlFace(-1)
tech.setFlipped(true)
else
mcontroller.controlFace(1)
tech.setFlipped(false)
end
tech.setAnimationState("dashing", "on")
tech.setParticleEmitterActive("dashParticles", true)
self.dashTimer = self.dashTimer - args.dt
else
tech.setAnimationState("dashing", "off")
tech.setParticleEmitterActive("dashParticles", false)
end
local dashAttackControlForce = tech.parameter("dashAttackControlForce")
local dashAttackSpeed = tech.parameter("dashAttackSpeed")
local dashAttackDuration = tech.parameter("dashAttackDuration")
local energyUsageDashAttack = tech.parameter("energyUsageDashAttack")
local diffDash = world.distance(tech.aimPosition(), mcontroller.position())
local aimAngleDash = math.atan(diffDash[2], diffDash[1])
local mechDashFireCycle = tech.parameter("mechDashFireCycle")
local mechDashProjectile = tech.parameter("mechDashProjectile")
local mechDashProjectileConfig = tech.parameter("mechDashProjectileConfig")
local flipDash = aimAngleDash > math.pi / 2 or aimAngleDash < -math.pi / 2
if flipDash then
tech.setFlipped(false)
mcontroller.controlFace(-1)
self.dashAttackDirection = -1
else
tech.setFlipped(true)
mcontroller.controlFace(1)
self.dashAttackDirection = 1
end
if status.resource("energy") > energyUsageDashAttack and args.actions["dashAttackLeft"] or args.actions["dashAttackRight"] then
if self.dashAttackTimer <= 0 then
world.spawnProjectile(mechDashProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontDashGun", "firePoint")), entity.id(), {math.cos(0), math.sin(0)}, false, mechDashProjectileConfig)
self.dashAttackTimer = self.dashAttackTimer + mechDashFireCycle
else
self.dashAttackTimer = self.dashAttackTimer - args.dt
end
mcontroller.controlApproachXVelocity(dashAttackSpeed * self.dashAttackDirection, dashAttackControlForce, true)
tech.setAnimationState("dashingAttack", "on")
tech.setParticleEmitterActive("dashAttackParticles", true)
else
tech.setAnimationState("dashingAttack", "off")
tech.setParticleEmitterActive("dashAttackParticles", false)
end
local energyUsageBlink = tech.parameter("energyUsageBlink")
local blinkMode = tech.parameter("blinkMode")
local blinkOutTime = tech.parameter("blinkOutTime")
local blinkInTime = tech.parameter("blinkInTime")
if args.actions["blink"] and self.mode == "none" and status.resource("energy") > energyUsageBlink then
local blinkPosition = nil
if blinkMode == "random" then
local randomBlinkAvoidCollision = tech.parameter("randomBlinkAvoidCollision")
local randomBlinkAvoidMidair = tech.parameter("randomBlinkAvoidMidair")
local randomBlinkAvoidLiquid = tech.parameter("randomBlinkAvoidLiquid")
blinkPosition =
findRandomBlinkLocation(randomBlinkAvoidCollision, randomBlinkAvoidMidair, randomBlinkAvoidLiquid) or
findRandomBlinkLocation(randomBlinkAvoidCollision, randomBlinkAvoidMidair, false) or
findRandomBlinkLocation(randomBlinkAvoidCollision, false, false)
elseif blinkMode == "cursor" then
blinkPosition = blinkAdjust(tech.aimPosition(), true, true, false, false)
elseif blinkMode == "cursorPenetrate" then
blinkPosition = blinkAdjust(tech.aimPosition(), false, true, false, false)
end
if blinkPosition then
self.targetPosition = blinkPosition
self.mode = "start"
else
-- Make some kind of error noise
end
end
if self.mode == "start" then
mcontroller.setVelocity({0, 0})
self.mode = "out"
self.timer = 0
return tech.consumeTechEnergy(energyUsageBlink)
elseif self.mode == "out" then
tech.setParentDirectives("?multiply=00000000")
tech.setVisible(false)
tech.setAnimationState("blinking", "out")
mcontroller.setVelocity({0, 0})
self.timer = self.timer + args.dt
if self.timer > blinkOutTime then
mcontroller.setPosition(self.targetPosition)
self.mode = "in"
self.timer = 0
end
return 0
elseif self.mode == "in" then
tech.setParentDirectives()
tech.setVisible(true)
tech.setAnimationState("blinking", "in")
mcontroller.setVelocity({0, 0})
self.timer = self.timer + args.dt
if self.timer > blinkInTime then
self.mode = "none"
end
return 0
end
local energyUsageJump = tech.parameter("energyUsageJump")
local multiJumpCount = tech.parameter("multiJumpCount")
if args.actions["multiJump"] and self.multiJumps < multiJumpCount and status.resource("energy") > energyUsageJump then
mcontroller.controlJump(true)
self.multiJumps = self.multiJumps + 1
tech.burstParticleEmitter("multiJumpParticles")
tech.playSound("sound")
return tech.consumeTechEnergy(energyUsageJump)
else
if mcontroller.onGround() or mcontroller.liquidMovement() then
self.multiJumps = 0
end
end
local energyCostPerSecond = tech.parameter("energyCostPerSecond")
local energyCostPerSecondPrim = tech.parameter("energyCostPerSecondPrim")
local energyCostPerSecondSec = tech.parameter("energyCostPerSecondSec")
local energyCostPerSecondAlt = tech.parameter("energyCostPerSecondAlt")
local mechCustomMovementParameters = tech.parameter("mechCustomMovementParameters")
local mechTransformPositionChange = tech.parameter("mechTransformPositionChange")
local parentOffset = tech.parameter("parentOffset")
local mechCollisionTest = tech.parameter("mechCollisionTest")
local mechAimLimit = tech.parameter("mechAimLimit") * math.pi / 180
local mechFrontRotationPoint = tech.parameter("mechFrontRotationPoint")
local mechFrontFirePosition = tech.parameter("mechFrontFirePosition")
local mechBackRotationPoint = tech.parameter("mechBackRotationPoint")
local mechBackFirePosition = tech.parameter("mechBackFirePosition")
local mechFireCycle = tech.parameter("mechFireCycle")
local mechProjectile = tech.parameter("mechProjectile")
local mechProjectileConfig = tech.parameter("mechProjectileConfig")
local mechAltFireCycle = tech.parameter("mechAltFireCycle")
local mechAltProjectile = tech.parameter("mechAltProjectile")
local mechAltProjectileConfig = tech.parameter("mechAltProjectileConfig")
local mechSecFireCycle = tech.parameter("mechSecFireCycle")
local mechSecProjectile = tech.parameter("mechSecProjectile")
local mechSecProjectileConfig = tech.parameter("mechSecProjectileConfig")
local mechGunBeamMaxRange = tech.parameter("mechGunBeamMaxRange")
local mechGunBeamStep = tech.parameter("mechGunBeamStep")
local mechGunBeamSmokeProkectile = tech.parameter("mechGunBeamSmokeProkectile")
local mechGunBeamEndProjectile = tech.parameter("mechGunBeamEndProjectile")
local mechGunBeamUpdateTime = tech.parameter("mechGunBeamUpdateTime")
local mechTransform = tech.parameter("mechTransform")
local mechActiveSide = nil
if tech.setFlipped(true) then
mechActiveSide = "left"
elseif tech.setFlipped(false) then
mechActiveSide = "right"
end
local mechStartupTime = tech.parameter("mechStartupTime")
local mechShutdownTime = tech.parameter("mechShutdownTime")
if not self.active and args.actions["mechActivate"] and self.mechState == "off" then
mechCollisionTest[1] = mechCollisionTest[1] + mcontroller.position()[1]
mechCollisionTest[2] = mechCollisionTest[2] + mcontroller.position()[2]
mechCollisionTest[3] = mechCollisionTest[3] + mcontroller.position()[1]
mechCollisionTest[4] = mechCollisionTest[4] + mcontroller.position()[2]
if not world.rectCollision(mechCollisionTest) then
tech.burstParticleEmitter("mechActivateParticles")
mcontroller.translate(mechTransformPositionChange)
tech.setVisible(true)
tech.setAnimationState("transform", "in")
-- status.modifyResource("health", status.stat("maxHealth") / 20)
tech.setParentState("sit")
tech.setToolUsageSuppressed(true)
self.mechState = "turningOn"
self.mechStateTimer = mechStartupTime
self.active = true
else
-- Make some kind of error noise
end
elseif self.mechState == "turningOn" and self.mechStateTimer <= 0 then
tech.setParentState("sit")
self.mechState = "on"
self.mechStateTimer = 0
elseif (self.active and (args.actions["mechDeactivate"] and self.mechState == "on" or (energyCostPerSecond * args.dt > status.resource("energy")) and self.mechState == "on")) then
self.mechState = "turningOff"
tech.setAnimationState("transform", "out")
self.mechStateTimer = mechShutdownTime
elseif self.mechState == "turningOff" and self.mechStateTimer <= 0 then
tech.burstParticleEmitter("mechDeactivateParticles")
mcontroller.translate({-mechTransformPositionChange[1], -mechTransformPositionChange[2]})
tech.setVisible(false)
tech.setParentState()
tech.setToolUsageSuppressed(false)
tech.setParentOffset({0, 0})
self.mechState = "off"
self.mechStateTimer = 0
self.active = false
end
mcontroller.controlFace(nil)
if self.mechStateTimer > 0 then
self.mechStateTimer = self.mechStateTimer - args.dt
end
if self.active then
local diff = world.distance(tech.aimPosition(), mcontroller.position())
local aimAngle = math.atan(diff[2], diff[1])
local flip = aimAngle > math.pi / 2 or aimAngle < -math.pi / 2
mcontroller.controlParameters(mechCustomMovementParameters)
if flip then
tech.setFlipped(false)
local nudge = tech.transformedPosition({0, 0})
tech.setParentOffset({-parentOffset[1] - nudge[1], parentOffset[2] + nudge[2]})
mcontroller.controlFace(-1)
if aimAngle > 0 then
aimAngle = math.max(aimAngle, math.pi - mechAimLimit)
else
aimAngle = math.min(aimAngle, -math.pi + mechAimLimit)
end
tech.rotateGroup("guns", math.pi + aimAngle)
else
tech.setFlipped(true)
local nudge = tech.transformedPosition({0, 0})
tech.setParentOffset({parentOffset[1] + nudge[1], parentOffset[2] + nudge[2]})
mcontroller.controlFace(1)
if aimAngle > 0 then
aimAngle = math.min(aimAngle, mechAimLimit)
else
aimAngle = math.max(aimAngle, -mechAimLimit)
end
tech.rotateGroup("guns", -aimAngle)
end
if not mcontroller.onGround() then
if mcontroller.velocity()[2] > 0 then
if args.actions["mechFire"] then
tech.setAnimationState("movement", "jumpAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "jumpAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "jumpAttack")
else
tech.setAnimationState("movement", "jump")
end
else
if args.actions["mechFire"] then
tech.setAnimationState("movement", "fallAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "fallAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "fallAttack")
else
tech.setAnimationState("movement", "fall")
end
end
elseif mcontroller.walking() or mcontroller.running() then
if flip and mcontroller.movingDirection() == 1 or not flip and mcontroller.movingDirection() == -1 then
if args.actions["mechFire"] then
tech.setAnimationState("movement", "backWalkAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "backWalkAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "backWalkAttack")
elseif args.actions["dashAttackRight"] then
tech.setAnimationState("movement", "backWalkDash")
elseif args.actions["dashAttackLeft"] then
tech.setAnimationState("movement", "backWalkDash")
else
tech.setAnimationState("movement", "backWalk")
end
else
if args.actions["mechFire"] then
tech.setAnimationState("movement", "walkAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "walkAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "walkAttack")
elseif args.actions["dashAttackRight"] then
tech.setAnimationState("movement", "walkDash")
elseif args.actions["dashAttackLeft"] then
tech.setAnimationState("movement", "walkDash")
else
tech.setAnimationState("movement", "walk")
end
end
else
if args.actions["mechFire"] then
tech.setAnimationState("movement", "idleAttack")
elseif args.actions["mechAltFire"] then
tech.setAnimationState("movement", "idleAttack")
elseif args.actions["mechSecFire"] then
tech.setAnimationState("movement", "idleAttack")
else
tech.setAnimationState("movement", "idle")
end
end
local telekinesisProjectile = tech.parameter("telekinesisProjectile")
local telekinesisProjectileConfig = tech.parameter("telekinesisProjectileConfig")
local telekinesisFireCycle = tech.parameter("telekinesisFireCycle")
local energyUsagePerSecondTelekinesis = tech.parameter("energyUsagePerSecondTelekinesis")
local energyUsageTelekinesis = energyUsagePerSecondTelekinesis * args.dt
if self.active and args.actions["grab"] and not self.grabbed then
local monsterIds = world.monsterQuery(tech.aimPosition(), 5)
for i,v in pairs(monsterIds) do
--world.spawnNpc( tech.aimPosition(), "glitch", "lonesurvivor_positionnpc", 2, 1)
world.monsterQuery(tech.aimPosition(),5, { callScript = "lonesurvivor_grab", callScriptArgs = { tech.aimPosition() } })
break
end
self.grabbed = true
elseif self.grabbed and not args.actions["grab"] then
--world.spawnNpc( tech.aimPosition(), "glitch", "lonesurvivor_positionnpc", 3, 1)
world.monsterQuery(tech.aimPosition(),30, { callScript = "lonesurvivor_release", callScriptArgs = { tech.aimPosition() } })
self.grabbed = false
elseif self.active and self.grabbed then
--world.spawnNpc( tech.aimPosition(), "glitch", "lonesurvivor_positionnpc", 1, 1)
world.monsterQuery(tech.aimPosition(),15, { callScript = "lonesurvivor_move", callScriptArgs = { tech.aimPosition() } })
end
if args.actions["grab"] and status.resource("energy") > energyUsageTelekinesis then
if self.fireTimer <= 0 then
world.spawnProjectile(telekinesisProjectile, tech.aimPosition(), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, telekinesisProjectileConfig)
self.fireTimer = self.fireTimer + telekinesisFireCycle
tech.setAnimationState("telekinesis", "telekinesisOn")
else
local oldFireTimer = self.fireTimer
self.fireTimer = self.fireTimer - args.dt
if oldFireTimer > telekinesisFireCycle / 2 and self.fireTimer <= telekinesisFireCycle / 2 then
end
end
return tech.consumeTechEnergy(energyUsageTelekinesis)
end
if args.actions["mechFire"] and status.resource("energy") > energyCostPerSecondPrim then
if self.fireTimer <= 0 then
world.spawnProjectile(mechProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontGun", "firePoint")), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechProjectileConfig)
self.fireTimer = self.fireTimer + mechFireCycle
tech.setAnimationState("frontFiring", "fire")
--tech.setParticleEmitterActive("jetpackParticles3", true)
local startPoint = vec2.add(mcontroller.position(), tech.partPoint("frontGun", "firePoint"))
local endPoint = vec_add(mcontroller.position(), {tech.partPoint("frontDashGun", "firePoint")[1] + mechGunBeamMaxRange * math.cos(aimAngle), tech.partPoint("frontDashGun", "firePoint")[2] + mechGunBeamMaxRange * math.sin(aimAngle) })
local beamCollision = progressiveLineCollision(startPoint, endPoint, mechGunBeamStep)
randomProjectileLine(startPoint, beamCollision, mechGunBeamStep, mechGunBeamSmokeProkectile, 0.08)
else
local oldFireTimer = self.fireTimer
self.fireTimer = self.fireTimer - args.dt
if oldFireTimer > mechFireCycle / 2 and self.fireTimer <= mechFireCycle / 2 then
end
end
return tech.consumeTechEnergy(energyCostPerSecondPrim)
end
if not args.actions["mechFire"] then
--tech.setParticleEmitterActive("jetpackParticles3", false)
end
if args.actions["mechAltFire"] and status.resource("energy") > energyCostPerSecondAlt then
if self.fireTimer <= 0 then
world.spawnProjectile(mechAltProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontAltGun", "firePoint")), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechAltProjectileConfig)
self.fireTimer = self.fireTimer + mechAltFireCycle
tech.setAnimationState("frontAltFiring", "fireAlt")
else
local oldFireTimer = self.fireTimer
self.fireTimer = self.fireTimer - args.dt
if oldFireTimer > mechAltFireCycle / 2 and self.fireTimer <= mechAltFireCycle / 2 then
end
end
return tech.consumeTechEnergy(energyCostPerSecondAlt)
end
if args.actions["mechSecFire"] and status.resource("energy") > energyCostPerSecondSec then
if self.fireTimer <= 0 then
world.spawnProjectile(mechSecProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontSecGun", "firePoint")), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechAltProjectileConfig)
self.fireTimer = self.fireTimer + mechSecFireCycle
tech.setAnimationState("frontSecFiring", "fireSec")
else
local oldFireTimer = self.fireTimer
self.fireTimer = self.fireTimer - args.dt
if oldFireTimer > mechSecFireCycle / 2 and self.fireTimer <= mechSecFireCycle / 2 then
end
end
return tech.consumeTechEnergy(energyCostPerSecondSec)
end
local jetpackSpeed = tech.parameter("jetpackSpeed")
local jetpackControlForce = tech.parameter("jetpackControlForce")
local energyUsagePerSecond = tech.parameter("energyUsagePerSecond")
local energyUsage = energyUsagePerSecond * args.dt
if status.resource("energy") < energyUsage then
self.ranOut = true
elseif mcontroller.onGround() or mcontroller.liquidMovement() then
self.ranOut = false
end
if args.actions["jetpack"] and not self.ranOut then
tech.setAnimationState("jetpack", "on")
mcontroller.controlApproachYVelocity(jetpackSpeed, jetpackControlForce, true)
return tech.consumeTechEnergy(energyUsage)
else
tech.setAnimationState("jetpack", "off")
return 0
end
-- local levitateSpeed = tech.parameter("levitateSpeed")
-- local levitateControlForce = tech.parameter("levitateControlForce")
-- local energyUsagePerSecondLevitate = tech.parameter("energyUsagePerSecondLevitate")
-- local energyUsagelevitate = energyUsagePerSecondLevitate * args.dt
-- if args.availableEnergy < energyUsagelevitate then
-- self.ranOut = true
-- elseif mcontroller.onGround() or mcontroller.liquidMovement() then
-- self.ranOut = false
-- end
-- if args.actions["levitate"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true)
-- self.levitateActivated = true
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitatehover"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(0, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(0, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateleft"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(0, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(-(levitateSpeed*self.speedMultiplier), levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateleftup"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(-(levitateSpeed*self.speedMultiplier), levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateleftdown"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(-(levitateSpeed)*0.5, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(-(levitateSpeed*self.speedMultiplier), levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateright"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(0, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(levitateSpeed*self.speedMultiplier, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitaterightup"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(levitateSpeed*self.speedMultiplier, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitaterightdown"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(-(levitateSpeed)*0,5, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(levitateSpeed*self.speedMultiplier, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitateup"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(0, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- elseif args.actions["levitatedown"] and not self.ranOut then
-- tech.setAnimationState("levitate", "on")
-- mcontroller.controlApproachYVelocity(-(levitateSpeed)*0.5, levitateControlForce, true)
-- mcontroller.controlApproachXVelocity(0, levitateControlForce, true)
-- return tech.consumeTechEnergy(energyUsagelevitate)
-- else
-- self.levitateActivated = false
-- tech.setAnimationState("levitate", "off")
-- return 0
-- end
--return energyCostPerSecond * args.dt
end
return 0
end
| gpl-2.0 |
jshackley/darkstar | scripts/globals/items/sacred_maul.lua | 42 | 1457 | -----------------------------------------
-- ID: 18392
-- Item: Sacred Maul
-- Additional Effect: Light Damage
-- Enchantment: "Enlight"
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 5;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(7,21);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_LIGHT, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_LIGHT,0);
dmg = adjustForTarget(target,dmg,ELE_LIGHT);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHT,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_LIGHT_DAMAGE,message,dmg;
end
end;
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
return 0;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
local effect = EFFECT_ENLIGHT;
doEnspell(target,target,nil,effect);
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Norg/npcs/Jirokichi.lua | 19 | 1260 | -----------------------------------
-- Area: Norg
-- NPC: Jirokichi
-- Type: Tenshodo Merchant
-- @pos -1.463 0.000 18.846 252
-----------------------------------
package.loaded["scripts/zones/Norg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/keyitems");
require("scripts/zones/Norg/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(TENSHODO_MEMBERS_CARD)) then
if (player:sendGuild(60423,9,23,7)) then
player:showText(npc, JIROKICHI_SHOP_DIALOG);
end
else
-- player:startEvent(0x0096);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
Keithenneu/Dota2-FullOverwrite | ability_usage_antimage.lua | 2 | 4113 | -------------------------------------------------------------------------------
--- AUTHOR: Nostrademous
--- GITHUB REPO: https://github.com/Nostrademous/Dota2-FullOverwrite
-------------------------------------------------------------------------------
_G._savedEnv = getfenv()
module( "ability_usage_antimage", package.seeall )
local gHeroVar = require( GetScriptDirectory().."/global_hero_data" )
local utils = require( GetScriptDirectory().."/utility" )
function setHeroVar(var, value)
local bot = bot or GetBot()
gHeroVar.SetVar(bot:GetPlayerID(), var, value)
end
function getHeroVar(var)
local bot = bot or GetBot()
return gHeroVar.GetVar(bot:GetPlayerID(), var)
end
function AbilityUsageThink(nearbyEnemyHeroes, nearbyAlliedHeroes, nearbyEnemyCreep, nearbyAlliedCreep, nearbyEnemyTowers, nearbyAlliedTowers)
if ( GetGameState() ~= GAME_STATE_GAME_IN_PROGRESS and GetGameState() ~= GAME_STATE_PRE_GAME ) then return false end
local bot = GetBot()
if not bot:IsAlive() then return false end
-- Check if we're already using an ability
if bot:IsCastingAbility() or bot:IsChanneling() then return false end
if #nearbyEnemyHeroes == 0 then return false end
abilityMV = bot:GetAbilityByName( "antimage_mana_void" )
-- Consider using each ability
castMVDesire, castMVTarget = ConsiderManaVoid( abilityMV )
if castMVDesire > 0 then
gHeroVar.HeroUseAbilityOnEntity(bot, abilityMV, castMVTarget )
return true
end
return false
end
----------------------------------------------------------------------------------------------------
function CanCastManaVoidOnTarget( npcTarget )
return npcTarget:CanBeSeen() and not utils.IsTargetMagicImmune( npcTarget )
end
----------------------------------------------------------------------------------------------------
function ConsiderManaVoid(abilityMV, nearbyEnemyHeroes)
local bot = GetBot()
-- Make sure it's castable
if not abilityMV:IsFullyCastable() then
return BOT_ACTION_DESIRE_NONE, 0;
end
-- Get some of its values
local nRadius = abilityMV:GetSpecialValueInt( "mana_void_aoe_radius" )
local nDmgPerMana = abilityMV:GetSpecialValueFloat( "mana_void_damage_per_mana" )
local nCastRange = abilityMV:GetCastRange()
--------------------------------------
-- Global high-priorty usage
--------------------------------------
local channelingHero = nil
local lowestManaHero = nil
local highestManaDiff = 0
for _,npcEnemy in pairs( nearbyEnemyHeroes ) do
if GetUnitToUnitDistance( bot, npcEnemy ) < nCastRange and npcEnemy:IsChanneling() then
channelingHero = npcEnemy
end
local manaDiff = npcEnemy:GetMaxMana() - npcEnemy:GetMana()
if GetUnitToUnitDistance( bot, npcEnemy ) < nCastRange and manaDiff > highestManaDiff then
lowestManaHero = npcEnemy
highestManaDiff = manaDiff
end
end
if lowestManaHero == nil then return BOT_ACTION_DESIRE_NONE, nil end
local aoeDmg = highestManaDiff * nDmgPerMana
local actualDmgLowest = lowestManaHero:GetActualIncomingDamage( aoeDmg, DAMAGE_TYPE_MAGICAL )
if channelingHero ~= nil and channelingHero:GetHealth() < channelingHero:GetActualIncomingDamage( aoeDmg, DAMAGE_TYPE_MAGICAL )
and GetUnitToUnitDistance(channelingHero, lowestManaHero) < nRadius then
return BOT_ACTION_DESIRE_HIGH, lowestManaHero
elseif lowestManaHero:GetHealth() < actualDmgLowest then
--FIXME: Figure out how many deaths ulting each hero would result in - pick greatest # if above 0
return BOT_ACTION_DESIRE_HIGH, lowestManaHero
end
--------------------------------------
-- Mode based usage
--------------------------------------
-- If we're going after someone
local npcTarget = getHeroVar("Target")
if utils.ValidTarget(npcTarget) then
local manaDiff = npcTarget.Obj:GetMaxMana() - npcTarget.Obj:GetMana()
aoeDmg = manaDiff * nDmgPerMana
if CanCastManaVoidOnTarget( npcTarget.Obj ) and (npcTarget.Obj:IsChanneling() or npcTarget.Obj:GetHealth() < aoeDmg) then
return BOT_ACTION_DESIRE_HIGH, npcTarget.Obj
end
end
return BOT_ACTION_DESIRE_NONE, nil
end
for k,v in pairs( ability_usage_antimage ) do _G._savedEnv[k] = v end | gpl-3.0 |
jshackley/darkstar | scripts/zones/Meriphataud_Mountains/npcs/qm1.lua | 17 | 1385 | -----------------------------------
-- Area: Meriphataud Mountains
-- NPC: qm1 (???)
-- Involved in Quest: The Holy Crest
-- @pos 641 -15 7 119
-----------------------------------
package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Meriphataud_Mountains/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(1159,1) and trade:getItemCount() == 1) then
if (player:getVar("TheHolyCrest_Event") == 4) then
player:startEvent(0x0038);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_FOUND);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0038) then
player:tradeComplete();
player:setVar("TheHolyCrest_Event",5);
player:startEvent(0x0021);
end
end; | gpl-3.0 |
luastoned/turbo | turbo/hash.lua | 12 | 4411 | --- Turbo.lua Hash module
-- Wrappers for OpenSSL crypto.
--
-- Copyright 2011, 2012, 2013 John Abrahamsen
--
-- 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 _G.TURBO_SSL then
return setmetatable({},
{
__index = function(t, k)
error("TURBO_SSL is not defined and you are trying to use hash functions.")
end,
__call = function(t, k)
error("TURBO_SSL is not defined and you are trying to use hash functions.")
end
})
end
local ffi = require "ffi"
local buffer = require "turbo.structs.buffer"
require "turbo.cdef"
local lssl = ffi.load(os.getenv("TURBO_LIBSSL") or "ssl")
-- Buffers
local hexstr = buffer()
local hash = {} -- hash namespace
hash.SHA_DIGEST_LENGTH = 20
hash.SHA1 = class("SHA1")
--- Create a SHA1 object. Pass a Lua string with the initializer to digest
-- it.
-- @param str (String)
function hash.SHA1:initialize(str)
if type(str) == "string" then
self.md = ffi.new("unsigned char[?]", hash.SHA_DIGEST_LENGTH)
lssl.SHA1(str, str:len(), self.md)
self.final = true
else
self.ctx = ffi.new("SHA_CTX")
assert(lssl.SHA1_Init(self.ctx) == 1, "Could not init SHA_CTX.")
end
end
--- Update SHA1 context with more data.
-- @param str (String)
function hash.SHA1:update(str)
assert(self.ctx, "No SHA_CTX in object.")
assert(not self.final,
"SHA_CTX already finalized. Please create a new context.")
assert(lssl.SHA1_Update(self.ctx, str, str:len()) == 1,
"Could not update SHA_CTX")
end
--- Finalize SHA1 context.
-- @return (char*) Message digest.
function hash.SHA1:finalize()
if self.final == true then
return self.md
end
self.final = true
assert(self.ctx, "No SHA_CTX in object.")
self.md = ffi.new("unsigned char[?]", hash.SHA_DIGEST_LENGTH)
assert(lssl.SHA1_Final(self.md, self.ctx) == 1, "Could not final SHA_CTX.")
return self.md
end
--- Keyed-hash message authentication code (HMAC) is a specific construction
-- for calculating a message authentication code (MAC) involving a
-- cryptographic hash function in combination with a secret cryptographic key.
-- @param key (String) Sequence of bytes used as a key.
-- @param digest (String) String to digest.
-- @param raw (Boolean) Indicates whether the output should be a direct binary
-- equivalent of the message digest, or formatted as a hexadecimal string.
-- @return (String) Hex representation of digested string.
function hash.HMAC(key, digest, raw)
assert(type(key) == "string", "Key is invalid type: "..type(key))
assert(type(digest) == "string", "Can not hash: "..type(digest))
local digest =
lssl.HMAC(lssl.EVP_sha1(),
key, key:len(),
digest,
digest:len(),
nil,
nil)
hexstr:clear()
for i=0, hash.SHA_DIGEST_LENGTH-1 do
if (raw) then
hexstr:append_char_right(digest[i])
else
hexstr:append_right(string.format("%02x", digest[i]), 2)
end
end
local str = hexstr:__tostring()
hexstr:clear(true)
return str
end
--- Compare two SHA1 contexts with the equality operator ==.
-- @return (Boolean) True or false.
function hash.SHA1:__eq(cmp)
assert(self.final and cmp.final, "Can not compare non final SHA_CTX's")
assert(self.md and cmp.md, "Missing message digest(s).")
if ffi.C.memcmp(self.md, cmp.md, hash.SHA_DIGEST_LENGTH) == 0 then
return true
else
return false
end
end
--- Convert message digest to Lua hex string.
-- @return (String)
function hash.SHA1:hex()
assert(self.final, "SHA_CTX not final.")
hexstr:clear()
for i=0, hash.SHA_DIGEST_LENGTH-1 do
hexstr:append_right(string.format("%02x", self.md[i]), 2)
end
local str = hexstr:__tostring()
hexstr:clear(true)
return str
end
return hash
| apache-2.0 |
wolf9s/packages | net/mwan3-luci/files/usr/lib/lua/luci/model/cbi/mwan/advanced_hotplugscript.lua | 111 | 2018 | -- ------ hotplug script configuration ------ --
fs = require "nixio.fs"
sys = require "luci.sys"
ut = require "luci.util"
script = "/etc/hotplug.d/iface/16-mwancustom"
scriptBackup = "/etc/hotplug.d/iface/16-mwancustombak"
if luci.http.formvalue("cbid.luci.1._restorebak") then -- restore button has been clicked
luci.http.redirect(luci.dispatcher.build_url("admin/network/mwan/advanced/hotplugscript") .. "?restore=yes")
elseif luci.http.formvalue("restore") == "yes" then -- restore script from backup
os.execute("cp -f " .. scriptBackup .. " " .. script)
end
m5 = SimpleForm("luci", nil)
m5:append(Template("mwan/advanced_hotplugscript")) -- highlight current tab
f = m5:section(SimpleSection, nil,
translate("This section allows you to modify the contents of /etc/hotplug.d/iface/16-mwancustom<br />" ..
"This is useful for running system commands and/or scripts based on interface ifup or ifdown hotplug events<br /><br />" ..
"Notes:<br />" ..
"The first line of the script must be "#!/bin/sh" without quotes<br />" ..
"Lines beginning with # are comments and are not executed<br /><br />" ..
"Available variables:<br />" ..
"$ACTION is the hotplug event (ifup, ifdown)<br />" ..
"$INTERFACE is the interface name (wan1, wan2, etc.)<br />" ..
"$DEVICE is the device name attached to the interface (eth0.1, eth1, etc.)"))
restore = f:option(Button, "_restorebak", translate("Restore default hotplug script"))
restore.inputtitle = translate("Restore...")
restore.inputstyle = "apply"
t = f:option(TextValue, "lines")
t.rmempty = true
t.rows = 20
function t.cfgvalue()
local hps = fs.readfile(script)
if not hps or hps == "" then -- if script does not exist or is blank restore from backup
sys.call("cp -f " .. scriptBackup .. " " .. script)
return fs.readfile(script)
else
return hps
end
end
function t.write(self, section, data) -- format and write new data to script
return fs.writefile(script, ut.trim(data:gsub("\r\n", "\n")) .. "\n")
end
return m5
| gpl-2.0 |
jshackley/darkstar | scripts/zones/RuLude_Gardens/npcs/Perisa-Neburusa.lua | 38 | 1048 | -----------------------------------
-- Area: Ru'Lude Gardens
-- NPC: Perisa-Neburusa
-- Type: Residence Renter
-- @zone: 243
-- @pos 54.651 8.999 -74.372
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x004c);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Northern_San_dOria/npcs/Gaudylox.lua | 17 | 1599 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Gaudylox
-- Standard merchant, though he acts like a guild merchant
-- @pos -147.593 11.999 222.550 231
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(60418,11,22,0)) then
player:showText(npc,GAUDYLOX_SHOP_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
blackman1380/man | plugins/plugins.lua | 11 | 5915 | --------------------------------------------------
-- ____ ____ _____ --
-- | \| _ )_ _|___ ____ __ __ --
-- | |_ ) _ \ | |/ ·__| _ \_| \/ | --
-- |____/|____/ |_|\____/\_____|_/\/\_| --
-- --
--------------------------------------------------
-- --
-- Developers: @Josepdal & @MaSkAoS --
-- Support: @Skneos, @iicc1 & @serx666 --
-- --
--------------------------------------------------
do
to_id = ""
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_plugins(only_enabled)
local text = 'ℹ️ '..lang_text(to_id, 'plugins')..':\n'
local psum = 0
for k, v in pairs( plugins_names( )) do
-- ✅ enabled, ❎ disabled
local status = '❎'
psum = psum+1
pact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✅'
end
pact = pact+1
end
if not only_enabled or status == '✅' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..status..' '..v..'\n'
end
end
local text = text..'\n🔢 '..psum..' '..lang_text(to_id, 'installedPlugins')..'\n✅ '
..pact..' '..lang_text(to_id, 'pEnabled')..'\n❎ '..psum-pact..' '..lang_text(to_id, 'pDisabled')..''
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return 'ℹ️ '..lang_text(to_id, 'isEnabled:1')..' '..plugin_name..' '..lang_text(to_id, 'isEnabled:2')
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return 'ℹ️ '..lang_text(to_id, 'notExist:1')..' '..plugin_name..' '..lang_text(to_id, 'notExist:2')
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return 'ℹ️ '..lang_text(to_id, 'notExist:1')..' '..name..' '..lang_text(to_id, 'notExist:2')
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return 'ℹ️ '..lang_text(to_id, 'notEnabled:1')..' '..name..' '..lang_text(to_id, 'notEnabled:2')
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return 'ℹ️ '..lang_text(to_id, 'pNotExists')
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return 'ℹ️ '..lang_text(to_id, 'pDisChat:1')..' '..plugin..' '..lang_text(to_id, 'pDisChat:2')
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'ℹ️ '..lang_text(to_id, 'anyDisPlugin')
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'ℹ️ '..lang_text(to_id, 'anyDisPluginChat')
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return 'ℹ️ '..lang_text(to_id, 'notDisabled')
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return 'ℹ️ '..lang_text(to_id, 'enabledAgain:1')..' '..plugin..' '..lang_text(to_id, 'enabledAgain:2')
end
local function run(msg, matches)
to_id = msg.to.id
-- Show the available plugins
if permissions(msg.from.id, msg.to.id, "plugins") then
if matches[1] == '#plugins' then
return list_plugins()
end
-- Re-enable a plugin for this chat
if matches[1] == 'enable' and matches[3] == 'chat' then
local receiver = get_receiver(msg)
local plugin = matches[2]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
-- Enable a plugin
if matches[1] == 'enable' then
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
-- Disable a plugin on a chat
if matches[1] == 'disable' and matches[3] == 'chat' then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
end
-- Disable a plugin
if matches[1] == 'disable' then
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == 'reload' then
return reload_plugins(true)
end
else
return '🚫 '..lang_text(msg.to.id, 'require_sudo')
end
end
return {
patterns = {
"^[!/#]plugins$",
"^[!/#]plugins? (enable) ([%w_%.%-]+)$",
"^[!/#]plugins? (disable) ([%w_%.%-]+)$",
"^[!/#]plugins? (enable) ([%w_%.%-]+) (chat)",
"^[!/#]plugins? (disable) ([%w_%.%-]+) (chat)",
"^[!/#]plugins? (reload)$" },
run = run
}
end
| gpl-2.0 |
jshackley/darkstar | scripts/globals/spells/dextrous_etude.lua | 18 | 1765 | -----------------------------------------
-- Spell: Dextrous Etude
-- Static DEX Boost, BRD 32
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED);
local power = 0;
if (sLvl+iLvl <= 181) then
power = 3;
elseif ((sLvl+iLvl >= 182) and (sLvl+iLvl <= 235)) then
power = 4;
elseif ((sLvl+iLvl >= 236) and (sLvl+iLvl <= 288)) then
power = 5;
elseif ((sLvl+iLvl >= 289) and (sLvl+iLvl <= 342)) then
power = 6;
elseif ((sLvl+iLvl >= 343) and (sLvl+iLvl <= 396)) then
power = 7;
elseif ((sLvl+iLvl >= 397) and (sLvl+iLvl <= 449)) then
power = 8;
elseif (sLvl+iLvl >= 450) then
power = 9;
end
local iBoost = caster:getMod(MOD_ETUDE_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
power = power + iBoost;
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_ETUDE,power,0,duration,caster:getID(), MOD_DEX, 1)) then
spell:setMsg(75);
end
return EFFECT_ETUDE;
end; | gpl-3.0 |
yagop/telegram-bot | plugins/tweet.lua | 634 | 7120 | local OAuth = require "OAuth"
local consumer_key = ""
local consumer_secret = ""
local access_token = ""
local access_token_secret = ""
local twitter_url = "https://api.twitter.com/1.1/statuses/user_timeline.json"
local client = OAuth.new(consumer_key,
consumer_secret,
{ RequestToken = "https://api.twitter.com/oauth/request_token",
AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"},
AccessToken = "https://api.twitter.com/oauth/access_token"},
{ OAuthToken = access_token,
OAuthTokenSecret = access_token_secret})
local function send_generics_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
local f = cb_extra.func
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path,
func = f
}
-- Send first and postpone the others as callback
f(receiver, file_path, send_generics_from_url_callback, cb_extra)
end
local function send_generics_from_url(f, receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil,
func = f
}
send_generics_from_url_callback(cb_extra)
end
local function send_gifs_from_url(receiver, urls)
send_generics_from_url(send_document, receiver, urls)
end
local function send_videos_from_url(receiver, urls)
send_generics_from_url(send_video, receiver, urls)
end
local function send_all_files(receiver, urls)
local data = {
images = {
func = send_photos_from_url,
urls = {}
},
gifs = {
func = send_gifs_from_url,
urls = {}
},
videos = {
func = send_videos_from_url,
urls = {}
}
}
local table_to_insert = nil
for i,url in pairs(urls) do
local _, _, extension = string.match(url, "(https?)://([^\\]-([^\\%.]+))$")
local mime_type = mimetype.get_content_type_no_sub(extension)
if extension == 'gif' then
table_to_insert = data.gifs.urls
elseif mime_type == 'image' then
table_to_insert = data.images.urls
elseif mime_type == 'video' then
table_to_insert = data.videos.urls
else
table_to_insert = nil
end
if table_to_insert then
table.insert(table_to_insert, url)
end
end
for k, v in pairs(data) do
if #v.urls > 0 then
end
v.func(receiver, v.urls)
end
end
local function check_keys()
if consumer_key:isempty() then
return "Twitter Consumer Key is empty, write it in plugins/tweet.lua"
end
if consumer_secret:isempty() then
return "Twitter Consumer Secret is empty, write it in plugins/tweet.lua"
end
if access_token:isempty() then
return "Twitter Access Token is empty, write it in plugins/tweet.lua"
end
if access_token_secret:isempty() then
return "Twitter Access Token Secret is empty, write it in plugins/tweet.lua"
end
return ""
end
local function analyze_tweet(tweet)
local header = "Tweet from " .. tweet.user.name .. " (@" .. tweet.user.screen_name .. ")\n" -- "Link: https://twitter.com/statuses/" .. tweet.id_str
local text = tweet.text
-- replace short URLs
if tweet.entities.url then
for k, v in pairs(tweet.entities.urls) do
local short = v.url
local long = v.expanded_url
text = text:gsub(short, long)
end
end
-- remove urls
local urls = {}
if tweet.extended_entities and tweet.extended_entities.media then
for k, v in pairs(tweet.extended_entities.media) do
if v.video_info and v.video_info.variants then -- If it's a video!
table.insert(urls, v.video_info.variants[1].url)
else -- If not, is an image
table.insert(urls, v.media_url)
end
text = text:gsub(v.url, "") -- Replace the URL in text
end
end
return header, text, urls
end
local function sendTweet(receiver, tweet)
local header, text, urls = analyze_tweet(tweet)
-- send the parts
send_msg(receiver, header .. "\n" .. text, ok_cb, false)
send_all_files(receiver, urls)
return nil
end
local function getTweet(msg, base, all)
local receiver = get_receiver(msg)
local response_code, response_headers, response_status_line, response_body = client:PerformRequest("GET", twitter_url, base)
if response_code ~= 200 then
return "Can't connect, maybe the user doesn't exist."
end
local response = json:decode(response_body)
if #response == 0 then
return "Can't retrieve any tweets, sorry"
end
if all then
for i,tweet in pairs(response) do
sendTweet(receiver, tweet)
end
else
local i = math.random(#response)
local tweet = response[i]
sendTweet(receiver, tweet)
end
return nil
end
function isint(n)
return n==math.floor(n)
end
local function run(msg, matches)
local checked = check_keys()
if not checked:isempty() then
return checked
end
local base = {include_rts = 1}
if matches[1] == 'id' then
local userid = tonumber(matches[2])
if userid == nil or not isint(userid) then
return "The id of a user is a number, check this web: http://gettwitterid.com/"
end
base.user_id = userid
elseif matches[1] == 'name' then
base.screen_name = matches[2]
else
return ""
end
local count = 200
local all = false
if #matches > 2 and matches[3] == 'last' then
count = 1
if #matches == 4 then
local n = tonumber(matches[4])
if n > 10 then
return "You only can ask for 10 tweets at most"
end
count = matches[4]
all = true
end
end
base.count = count
return getTweet(msg, base, all)
end
return {
description = "Random tweet from user",
usage = {
"!tweet id [id]: Get a random tweet from the user with that ID",
"!tweet id [id] last: Get a random tweet from the user with that ID",
"!tweet name [name]: Get a random tweet from the user with that name",
"!tweet name [name] last: Get a random tweet from the user with that name"
},
patterns = {
"^!tweet (id) ([%w_%.%-]+)$",
"^!tweet (id) ([%w_%.%-]+) (last)$",
"^!tweet (id) ([%w_%.%-]+) (last) ([%d]+)$",
"^!tweet (name) ([%w_%.%-]+)$",
"^!tweet (name) ([%w_%.%-]+) (last)$",
"^!tweet (name) ([%w_%.%-]+) (last) ([%d]+)$"
},
run = run
}
| gpl-2.0 |
jessehorne/luadraw | main.lua | 1 | 1520 | currx = love.graphics.getWidth()/2
curry = love.graphics.getHeight()/2
currr = -90
if arg[2] then
love.graphics.setCaption(arg[2])
end
function string:split(sep)
local sep, fields = sep or " ", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
function load_string(s)
local f = {}
f.file = io.open(s, "r")
f.txt = f.file:read("*all")
f.file:close()
return f.txt
end
function parse_string(s)
local f = ""
f = table.concat(s:split("\n"), " ")
f = f:split(" ")
return f
end
function create_draw_table(t)
local points = {}
table.insert(points, currx)
table.insert(points, curry)
for i,v in ipairs(t) do
if v == "f" then
currx = (currx + math.cos(math.rad(currr)) * tonumber(t[i+1]))
curry = (curry + math.sin(math.rad(currr)) * tonumber(t[i+1]))
table.insert(points, currx)
table.insert(points, curry)
elseif v == "b" then
currx = (currx - math.cos(math.rad(currr)) * tonumber(t[i+1]))
curry = (curry - math.sin(math.rad(currr)) * tonumber(t[i+1]))
table.insert(points, currx)
table.insert(points, curry)
elseif v == "r" then
currr = currr + t[i+1]
end
end
return points
end
function love.load()
local file = arg[2]
if file ~= nil then
t = load_string(file)
t = parse_string(t)
t = create_draw_table(t)
else
print("No file input.")
end
end
function draw_table(t)
love.graphics.line(unpack(t))
end
function love.update(dt)
end
function love.draw()
draw_table(t)
end | mit |
jshackley/darkstar | scripts/globals/mobskills/Hurricane_Wing.lua | 36 | 1331 | ---------------------------------------------
-- Hurricane Wing
--
-- Description: Deals hurricane-force wind damage to enemies within a very wide area of effect. Additional effect: Blind
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes shadows
-- Range: 30' radial.
-- Notes: Used only by Dragua, Fafnir, Nidhogg, Cynoprosopi, Wyrm, and Odzmanouk. The blinding effect does not last long
-- but is very harsh. The attack is wide enough to generally hit an entire alliance.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (target:isBehind(mob, 48) == true) then
return 1;
elseif (mob:AnimationSub() ~= 0) then
return 1;
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_BLINDNESS;
MobStatusEffectMove(mob, target, typeEffect, 60, 0, 30);
local dmgmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_WIND,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WIND,MOBPARAM_WIPE_SHADOWS);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
botmohammad12344888/bot-888338888 | plugins/filterword.lua | 2 | 4416 | local function save_filter(msg, name, value)
local hash = nil
if msg.to.type == 'chat' then
hash = 'chat:'..msg.to.id..':filters'
end
if msg.to.type == 'user' then
return 'فقط در گروه'
end
if hash then
redis:hset(hash, name, value)
return "انجام شد"
end
end
local function get_filter_hash(msg)
if msg.to.type == 'chat' then
return 'chat:'..msg.to.id..':filters'
end
end
local function list_filter(msg)
if msg.to.type == 'user' then
return 'فقط در گروه'
end
local hash = get_filter_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = 'لیست کلمات فیلتر شده:\n______________________________\n'
for i=1, #names do
text = text..'> '..names[i]..'\n'
end
return text
end
end
local function get_filter(msg, var_name)
local hash = get_filter_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if value == 'msg' then
return 'کلمه ی کاربردی شما ممنوع است، در صورت تکرار با شما برخورد خواهد شد'
elseif value == 'kick' then
send_large_msg('chat#id'..msg.to.id, "به دلیل عدم رعایت قوانین گفتاری از ادامه ی گفتوگو محروم میشوید")
chat_del_user('chat#id'..msg.to.id, 'user#id'..msg.from.id, ok_cb, true)
end
end
end
local function get_filter_act(msg, var_name)
local hash = get_filter_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if value == 'msg' then
return 'اخطار و تذکر به این کلمه'
elseif value == 'kick' then
return 'این کلمه ممنوع است و حذف خواهید شد'
elseif value == 'none' then
return 'این کلمه از فیلتر خارج شده است'
end
end
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
if matches[1] == "filterlist" or matches[1] == "لیست فیلتر" then
return list_filter(msg)
elseif matches[1] == "filter" or matches[1] == "فیلتر" and matches[2] == ">" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "شما مدير نيستيد"
else
local value = 'msg'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "filter" or matches[1] == "فیلتر" and matches[2] == "+" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "شما مدير نيستيد"
else
local value = 'kick'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "filter" or matches[1] == "فیلتر" and matches[2] == "-" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "شما مدير نيستيد"
else
local value = 'none'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "filter" or matches[1] == "فیلتر" and matches[2] == "?" then
return get_filter_act(msg, matches[3]:lower())
else
if is_sudo(msg) then
return
elseif is_admin(msg) then
return
elseif is_momod(msg) then
return
elseif tonumber(msg.from.id) == tonumber(our_id) then
return
else
return get_filter(msg, msg.text:lower())
end
end
end
return {
description = "Word Filtering",
usage = {
user = {
"filter ? (word) : مشاهده عکس العمل",
"filterlist : لیست فیلتر شده ها",
"فیلتر ? (word) : مشاهده عکس العمل",
"لیست فیلتر : لیست فیلتر شده ها",
},
moderator = {
"فیلتر > (word) : اخطار کردن لغت",
"فیلتر + (word) : ممنوع کردن لغت",
"فیلتر - (word) : حذف از فیلتر",
},
},
patterns = {
"^(فیلتر) (.+) (.*)$",
"^(لیست فیلتر)$",
"(.*)",
},
run = run
}
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Apollyon/bcnms/NW_Apollyon.lua | 19 | 1065 | -----------------------------------
-- Area: Appolyon
-- Name:
-----------------------------------
require("scripts/globals/limbus");
require("scripts/globals/keyitems");
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
SetServerVariable("[NW_Apollyon]UniqueID",GenerateLimbusKey());
HideArmouryCrates(GetInstanceRegion(1290),APPOLLYON_NW_SW);
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
player:setVar("limbusbitmap",0);
player:setVar("characterLimbusKey",GetServerVariable("[NW_Apollyon]UniqueID"));
player:setVar("LimbusID",1290);
player:delKeyItem(COSMOCLEANSE);
player:delKeyItem(RED_CARD);
end;
-- Leaving the Dynamis by every mean possible, given by the LeaveCode
-- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3)
-- 4=Finish
function onBcnmLeave(player,instance,leavecode)
--print("leave code "..leavecode);
if (leavecode == 4) then
player:setPos(-668,0.1,-666);
ResetPlayerLimbusVariable(player)
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/items/pixie_mace.lua | 41 | 1075 | -----------------------------------------
-- ID: 17414
-- Item: Pixie Mace
-- Additional Effect: Light Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 10;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(4,11);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_LIGHT, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_LIGHT,0);
dmg = adjustForTarget(target,dmg,ELE_LIGHT);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHT,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_LIGHT_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/spells/absorb-vit.lua | 18 | 1299 | --------------------------------------
-- Spell: Absorb-VIT
-- Steals an enemy's vitality.
--------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
if (target:hasStatusEffect(EFFECT_VIT_DOWN) or caster:hasStatusEffect(EFFECT_VIT_BOOST)) then
spell:setMsg(75); -- no effect
else
local dINT = caster:getStat(MOD_INT) - target:getStat(MOD_INT);
local resist = applyResistance(caster,spell,target,dINT,37,0);
if (resist <= 0.125) then
spell:setMsg(85);
else
spell:setMsg(331);
caster:addStatusEffect(EFFECT_VIT_BOOST,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(MOD_AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_DISPELABLE); -- caster gains VIT
target:addStatusEffect(EFFECT_VIT_DOWN,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(MOD_AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_ERASBLE); -- target loses VIT
end
end
return EFFECT_VIT_DOWN;
end; | gpl-3.0 |
SamJBarney/Wasteland | Wasteland.lua | 1 | 7249 | local PLUGIN = nil
--- Minimum depth (number of blocks down from surface) of generated ores
local MIN_ORE_DEPTH = 8
--- Where and how much ores should generate:
-- Each item in the array represents one ore that is generated in each chunk.
-- The generator generates up to "count" ore blocks in each chunk in height up to maxHeight (inclusive)
local g_OreCounts =
{
{blockType = E_BLOCK_DIAMOND_ORE, maxHeight = 15, count = 8},
{blockType = E_BLOCK_LAPIS_ORE, maxHeight = 24, count = 16},
{blockType = E_BLOCK_REDSTONE_ORE, maxHeight = 24, count = 16},
{blockType = E_BLOCK_IRON_ORE, maxHeight = 54, count = 80},
{blockType = E_BLOCK_COAL_ORE, maxHeight = 80, count = 400},
{blockType = E_BLOCK_EMERALD_ORE, maxHeight = 15, count = 1},
}
--- How much sand should generate based on height
-- The higher the initial height of the chunk, the less sand gets placed.
local g_SandDepth =
{
6, 6, -- 20 - 59
5, -- 60 - 79
4, 4, -- 80 - 119
3, -- 120 - 139
2, -- 140 - 159
1, -- 160 - 179
0,0,0,0,0 -- 180+
}
-- Item Definitions
dofile(cPluginManager:GetPluginsPath() .. "/Wasteland/Items.lua")
-- Crafting Related
dofile(cPluginManager:GetPluginsPath() .. "/Wasteland/CraftingRecipe.lua")
dofile(cPluginManager:GetPluginsPath() .. "/Wasteland/Recipes.lua")
-- Hook Files
dofile(cPluginManager:GetPluginsPath() .. "/Wasteland/BreakBlockHooks.lua")
dofile(cPluginManager:GetPluginsPath() .. "/Wasteland/RightClickHooks.lua")
-- Block Tick Handling
dofile(cPluginManager:GetPluginsPath() .. "/Wasteland/Lib/TickerLib.lua")
dofile(cPluginManager:GetPluginsPath() .. "/Wasteland/BlockTickHandlers.lua")
local RegisteredWorlds = {}
function Initialize(Plugin)
-- Load the Info.lua file
dofile(cPluginManager:GetPluginsPath() .. "/Wasteland/Info.lua")
PLUGIN = Plugin
PLUGIN:SetName(g_PluginInfo.Name)
PLUGIN:SetVersion(g_PluginInfo.Version)
-- Generation Hooks
cPluginManager.AddHook(cPluginManager.HOOK_CHUNK_GENERATING, OnChunkGenerating)
cPluginManager.AddHook(cPluginManager.HOOK_CHUNK_GENERATED, OnChunkGenerated)
-- Crafting Hooks
cPluginManager.AddHook(cPluginManager.HOOK_PRE_CRAFTING, OnPreCrafting)
-- Misc Hooks
cPluginManager.AddHook(cPluginManager.HOOK_PLAYER_BROKEN_BLOCK, OnBlockBroken)
cPluginManager.AddHook(cPluginManager.HOOK_PLAYER_RIGHT_CLICK, OnPlayerRightClick)
cPluginManager.AddHook(cPluginManager.HOOK_BLOCK_SPREAD, OnGrassSpread)
-- Block Tick Callbacks
TickerSetup()
RegisterTickerCallback('world', E_BLOCK_GRASS, E_META_ANY, OnTickGrassBlock)
RegisterTickerCallback('world', E_BLOCK_FARMLAND, E_META_ANY, OnTickGrassBlock)
RegisterTickerCallback('world', E_BLOCK_ANY, E_META_ANY, OnMagmaCore)
LOG("Initialized " .. PLUGIN:GetName() .. " v." .. PLUGIN:GetVersion())
return true
end
function OnDisable()
LOG("Disabled " .. PLUGIN:GetName() .. "!")
end
-- Generation Callbacks
function OnChunkGenerating(World, ChunkX, ChunkZ, ChunkDesc)
--if (RegisteredWorlds[World.GetName()] ~= nil) then
ChunkDesc:SetUseDefaultBiomes(false)
ChunkDesc:SetUseDefaultFinish(false)
-- Change the biome to desert
for x=0,15 do
for z=0,15 do
ChunkDesc:SetBiome(x,z,biDesert)
end
end
return true
--end
--return false
end
function OnChunkGenerated(World, ChunkX, ChunkZ, ChunkDesc)
--if (RegisteredWorlds[World.GetName()] ~= nil) then
-- Replace all water with air
ChunkDesc:ReplaceRelCuboid(0,15, 0,255, 0,15, E_BLOCK_STATIONARY_WATER,0, E_BLOCK_AIR,0)
ChunkDesc:ReplaceRelCuboid(0,15, 0,255, 0,15, E_BLOCK_WATER,0, E_BLOCK_AIR,0)
-- Replace clay with hardend clay
ChunkDesc:ReplaceRelCuboid(0,15, 0,255, 0,15, E_BLOCK_CLAY,0, E_BLOCK_HARDENED_CLAY,0)
ChunkDesc:ReplaceRelCuboid(0,15, 0,255, 0,15, E_BLOCK_DIRT,0, E_BLOCK_DIRT, E_META_DIRT_COARSE)
-- Cover the chunk with the correct amount of sand
-- and fill the bottom three layers of the world with lava
for x = 0, 15 do
for z = 0, 15 do
local height = ChunkDesc:GetHeight(x, z)
local sand_depth = g_SandDepth[math.floor(height/20)]
-- If sand is supposed to be placed here, place it
if sand_depth > 0 then
for offset = 1, sand_depth do
ChunkDesc:SetBlockType(x, height + offset, z, E_BLOCK_SAND)
end
end
if (ChunkDesc:GetBlockType(x, height + sand_depth, z) == E_BLOCK_SAND) and (math.random() < 0.0007) then
ChunkDesc:SetBlockType(x, height + sand_depth + 1, z, E_BLOCK_DEAD_BUSH)
end
-- Place lava
ChunkDesc:SetBlockType(x, 1, z, E_BLOCK_STATIONARY_LAVA)
ChunkDesc:SetBlockType(x, 2, z, E_BLOCK_STATIONARY_LAVA)
ChunkDesc:SetBlockType(x, 3, z, E_BLOCK_STATIONARY_LAVA)
end -- for z
end -- for x
-- Seed Ores:
for _, oreCount in ipairs(g_OreCounts) do
for i = 1, oreCount.count do
local x = math.random(15)
local z = math.random(15)
local height = ChunkDesc:GetHeight(x, z)
if (height > MIN_ORE_DEPTH) then
local maxHeight = height - MIN_ORE_DEPTH
if (maxHeight > oreCount.maxHeight - 4) then
maxHeight = oreCount.maxHeight - 4
end
local y = 4 + math.random(maxHeight)
if (ChunkDesc:GetBlockType(x, y, z) == E_BLOCK_STONE) then
ChunkDesc:SetBlockType(x, y, z, oreCount.blockType)
end
end -- if (height acceptable)
end -- for i
end -- for oreCount - g_OreCounts[]
-- After changing the chunk, we need the server to recalculate the heightmap:
ChunkDesc:UpdateHeightmap()
return true
end
-- Crafting Callbacks
function OnPreCrafting(Player, Grid, Recipe)
local recipe_found = false
for i,recipe in ipairs(wasteland_Recipes) do
if recipe ~= nil and CraftingRecipe_Compare(recipe,Grid) then
recipe_found = true
local result = CraftingRecipe_GetResult(recipe):CopyOne()
result.m_ItemCount = CraftingRecipe_GetResult(recipe).m_ItemCount
Recipe:SetResult(result)
for x = 0, Grid:GetWidth() - 1 do
for y = 0, Grid:GetHeight() - 1 do
Recipe:SetIngredient(x,y, Grid:GetItem(x,y):CopyOne())
end
end
break
end
end
return recipe_found
end
-- Block Breaking Callback
-- If we have a handler for the block being broken, call it and return the result
function OnBlockBroken(Player, BlockX, BlockY, BlockZ, BlockFace, BlockType, BlockMeta)
local handler = BrokenBlockHooks[BlockType]
if handler ~= nil then
return handler(Player, BlockX, BlockY, BlockZ, BlockFace, BlockMeta)
end
end
-- Player Right Click Handler
-- If we have a handler for the item being used, call it and return the result
function OnPlayerRightClick(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ)
local held_item = Player:GetEquippedItem()
if held_item.m_ItemCount > 0 then
local handler = PlayerRightClick[held_item.m_ItemType]
if handler ~= nil then
return handler(Player, held_item, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ)
end
end
end
-- Grass Spread Handler
-- Grass should only be able to spread if the biome is not desert or the block is directly watered
function OnGrassSpread(World, BlockX, BlockY, BlockZ, Source)
if Source == ssGrassSpread and World:GetBiomeAt(BlockX, BlockZ) == biDesert and not World:IsBlockDirectlyWatered(BlockX, BlockY, BlockZ) then
return true
end
end
| apache-2.0 |
Xtrem65/esx_garagecompany | client/main.lua | 1 | 15359 | local Keys = {
["ESC"] = 322, ["F1"] = 288, ["F2"] = 289, ["F3"] = 170, ["F5"] = 166, ["F6"] = 167, ["F7"] = 168, ["F8"] = 169, ["F9"] = 56, ["F10"] = 57,
["~"] = 243, ["1"] = 157, ["2"] = 158, ["3"] = 160, ["4"] = 164, ["5"] = 165, ["6"] = 159, ["7"] = 161, ["8"] = 162, ["9"] = 163, ["-"] = 84, ["="] = 83, ["BACKSPACE"] = 177,
["TAB"] = 37, ["Q"] = 44, ["W"] = 32, ["E"] = 38, ["R"] = 45, ["T"] = 245, ["Y"] = 246, ["U"] = 303, ["P"] = 199, ["["] = 39, ["]"] = 40, ["ENTER"] = 18,
["CAPS"] = 137, ["A"] = 34, ["S"] = 8, ["D"] = 9, ["F"] = 23, ["G"] = 47, ["H"] = 74, ["K"] = 311, ["L"] = 182,
["LEFTSHIFT"] = 21, ["Z"] = 20, ["X"] = 73, ["C"] = 26, ["V"] = 0, ["B"] = 29, ["N"] = 249, ["M"] = 244, [","] = 82, ["."] = 81,
["LEFTCTRL"] = 36, ["LEFTALT"] = 19, ["SPACE"] = 22, ["RIGHTCTRL"] = 70,
["HOME"] = 213, ["PAGEUP"] = 10, ["PAGEDOWN"] = 11, ["DELETE"] = 178,
["LEFT"] = 174, ["RIGHT"] = 175, ["TOP"] = 27, ["DOWN"] = 173,
["NENTER"] = 201, ["N4"] = 108, ["N5"] = 60, ["N6"] = 107, ["N+"] = 96, ["N-"] = 97, ["N7"] = 117, ["N8"] = 61, ["N9"] = 118
}
local PlayerData = {}
local GUI = {}
GUI.Time = 0
local hasAlreadyEnteredMarker = false;
local lastZone = nil;
AddEventHandler('playerSpawned', function(spawn)
TriggerServerEvent('esx_garagejob:requestPlayerData', 'playerSpawned')
end)
RegisterNetEvent('esx_phone:loaded')
AddEventHandler('esx_phone:loaded', function(phoneNumber, contacts)
if (Config.HasEmergencyPhoneLine)then
TriggerEvent('esx_phone:addContact', Config.CompanyName, Config.CompanyName, 'special', false)
end
end)
AddEventHandler('esx_garagejob:hasEnteredMarker', function(zone)
if zone == 'CloakRoom' then
SendNUIMessage({
showControls = true,
controls = 'cloakroom'
})
end
if zone == 'VehicleSpawner' then
if (isInService())then
SendNUIMessage({
showControls = true,
controls = 'vehiclespawner'
})
else
ShowNotification("~g~Vous devez prendre votre service")
end
end
if zone == 'VehicleDeleter' then
if (isInService())then
local playerPed = GetPlayerPed(-1)
if IsPedInAnyVehicle(playerPed, 0) then
DeleteVehicle(GetVehiclePedIsIn(playerPed, 0))
end
else
ShowNotification("~g~Vous devez prendre votre service")
end
end
end)
AddEventHandler('esx_garagejob:hasExitedMarker', function(zone)
SendNUIMessage({
showControls = false,
showMenu = false,
})
end)
RegisterNetEvent('esx:setJob')
AddEventHandler('esx:setJob', function(job)
PlayerData.job = job
end)
RegisterNetEvent('esx_garagejob:responsePlayerData')
AddEventHandler('esx_garagejob:responsePlayerData', function(data, reason)
PlayerData = data
end)
RegisterNUICallback('select', function(data, cb)
if data.menu == 'cloakroom' then
if data.val == 'citizen_wear' then
TriggerEvent('esx_skin:loadSkin', PlayerData.skin)
RemoveWeaponFromPed(GetPlayerPed(-1), GetHashKey("WEAPON_HAMMER"))
TriggerServerEvent("updateJob", "unemployed", 0)
end
if data.val == 'job_wear' then
local grade = 0
for k,v in pairs(Config.AllowedUsers) do
if (v.identifier == PlayerData.identifier) then
grade = v.grade
end
end
TriggerServerEvent("updateJob", Config.JobName, grade)
if PlayerData.skin.sex == 0 then
TriggerEvent('esx_skin:loadJobSkin', PlayerData.skin, json.decode(Config.MaleSkin[tostring(grade)]))
else
TriggerEvent('esx_skin:loadJobSkin', PlayerData.skin, json.decode(Config.FemaleSkin[tostring(grade)]))
end
GiveWeaponToPed(GetPlayerPed(-1), GetHashKey("WEAPON_HAMMER"), true, true)
end
end
if data.menu == 'vehiclespawner' then
local playerPed = GetPlayerPed(-1)
Citizen.CreateThread(function()
local coords = Config.Zones.VehicleSpawnPoint.Pos
local vehicleModel = GetHashKey(data.val)
RequestModel(vehicleModel)
while not HasModelLoaded(vehicleModel) do
Citizen.Wait(0)
end
if not IsAnyVehicleNearPoint(coords.x, coords.y, coords.z, 5.0) then
local vehicle = CreateVehicle(vehicleModel, coords.x, coords.y, coords.z, 90.0, true, false)
SetVehicleHasBeenOwnedByPlayer(vehicle, true)
SetEntityAsMissionEntity(vehicle, true, true)
local id = NetworkGetNetworkIdFromEntity(vehicle)
SetNetworkIdCanMigrate(id, true)
TaskWarpPedIntoVehicle(playerPed, vehicle, -1)
end
end)
SendNUIMessage({
showControls = false,
showMenu = false,
})
end
cb('ok')
end)
RegisterNUICallback('select_control', function(data, cb)
cb('ok')
end)
function isAllowed()
if Config.AllowListedUsersOnly == true then
for k,v in pairs(Config.AllowedUsers) do
if (v.identifier == PlayerData.identifier) then
return true
end
end
return false
end
return true
end
function isInService()
if PlayerData.job ~= nil and PlayerData.job.name == Config.JobName then
return true
else
return false
end
end
-- Display markers
Citizen.CreateThread(function()
while (PlayerData.identifier == nil) do
Wait(100)
end
local allowed_player = isAllowed()
while true do
Wait(0)
local coords = GetEntityCoords(GetPlayerPed(-1))
for k,v in pairs(Config.Zones) do
if(allowed_player and v.Type ~= -1 and GetDistanceBetweenCoords(coords, v.Pos.x, v.Pos.y, v.Pos.z, true) < Config.DrawDistance) then
DrawMarker(v.Type, v.Pos.x, v.Pos.y, v.Pos.z, 0.0, 0.0, 0.0, 0, 0.0, 0.0, v.Size.x, v.Size.y, v.Size.z, v.Color.r, v.Color.g, v.Color.b, 100, false, true, 2, false, false, false, false)
end
end
end
end)
-- Menu
Citizen.CreateThread(function()
while (PlayerData.identifier == nil) do
Wait(100)
end
while true do
Wait(0)
if isInService() and IsControlPressed(0, Keys['F6']) and (GetGameTimer() - GUI.Time) > 300 then
SendNUIMessage({
showControls = false,
showMenu = true,
menu = 'actions'
})
GUI.Time = GetGameTimer()
end
end
end)
function spawn_object(model_name, freeze_object)
local x, y, z = table.unpack(GetEntityCoords(GetPlayerPed(-1), true))
local objectHash = GetHashKey(model_name)
local rotation = GetEntityRotation(GetPlayerPed(-1), true)
RequestModel(objectHash)
while not HasModelLoaded(objectHash) do
Wait(1)
end
local object = CreateObject(objectHash, x, y+0.5, z-1, true, true, true)
if object then
SetEntityRotation(object, rotation, 2, true)
if(freeze_object)then
FreezeEntityPosition(object, true)
end
end
end
function remove_object(model_name)
local coords = GetEntityCoords(GetPlayerPed(-1), true)
local object_name = model_name
local objectHash = GetHashKey(object_name)
RequestModel(objectHash)
while not HasModelLoaded(objectHash) do
Wait(1)
end
local object = GetClosestObjectOfType(coords, 10.0, objectHash, false, false, false)
SetEntityAsMissionEntity(object, 1, 1)
DeleteEntity(object)
end
RegisterNUICallback('select', function(data, cb)
if data.menu == 'actions' then
if data.val == 'add_plot' then
spawn_object("prop_roadcone01a", false)
SendNUIMessage({
showControls = false,
showMenu = false,
})
end
if data.val == 'delete_plot' then
remove_object("prop_roadcone01a")
SendNUIMessage({
showControls = false,
showMenu = false,
})
end
if data.val == 'reparer' then
TriggerEvent('esx_garage:reparer')
SendNUIMessage({
showControls = false,
showMenu = false,
})
end
if data.val == 'crocheter' then
TriggerEvent('esx_garage:crocheter')
SendNUIMessage({
showControls = false,
showMenu = false,
})
end
if data.val == 'charger' then
TriggerEvent('esx_garage:chargerDansFlatBed')
SendNUIMessage({
showControls = false,
showMenu = false,
})
end
end
end)
RegisterNetEvent('esx_garage:reparer')
AddEventHandler('esx_garage:reparer', function()
local playerped = GetPlayerPed(-1)
local coordA = GetEntityCoords(playerped, 1)
local coordB = GetOffsetFromEntityInWorldCoords(playerped, 0.0, -15.0, 0.0)
local veh = getVehicleInDirection(coordA, coordB)
if DoesEntityExist(veh) then
TaskStartScenarioInPlace(GetPlayerPed(-1), "WORLD_HUMAN_VEHICLE_MECHANIC", 0, true)
local model = GetEntityModel(veh)
local model_name = GetDisplayNameFromVehicleModel(model)
TriggerEvent("chatMessage", "[SAV-Garagiste]", {255, 255, 0}, "Debut des travaux sur le vehicule " .. model_name .. " ... cela devrait prendre 20 secondes.")
Citizen.Wait(20000)
SetVehicleFixed(veh)
SetVehicleDeformationFixed(veh, 1)
SetVehicleUndriveable(veh, 1)
ClearPedTasksImmediately(GetPlayerPed(-1))
TriggerEvent("chatMessage", "[SAV-Garagiste]", {255, 255, 0}, "Le vehicule " .. model_name .. " est maintenant réparé.")
else
TriggerEvent("chatMessage", "[SAV-Garagiste]", {255, 255, 0}, "Aucun vehicule a portée. (Il faut lui tourner le dos)")
end
end)
RegisterNetEvent('esx_garage:crocheter')
AddEventHandler('esx_garage:crocheter', function()
local playerped = GetPlayerPed(-1)
local coords = GetEntityCoords(playerped)
if IsAnyVehicleNearPoint(coords.x, coords.y, coords.z, 5.0) then
local vehicle = nil
if IsPedInAnyVehicle(playerped, false) then
vehicle = GetVehiclePedIsIn(playerped, false)
else
local coordA = GetEntityCoords(playerped, 1)
local coordB = GetOffsetFromEntityInWorldCoords(playerped, 0.0, 15.0, 0.0)
vehicle = getVehicleInDirection(coordA, coordB)
end
if DoesEntityExist(vehicle) then
SetVehicleDoorsLocked(vehicle, 1)
SetVehicleDoorsLockedForAllPlayers(vehicle, false)
TriggerEvent("chatMessage", "[SAV-Garagiste]", {255, 255, 0}, "Vehicule crocheté")
else
TriggerEvent("chatMessage", "[SAV-Garagiste]", {255, 255, 0}, "Aucun vehicule à crocheter.")
end
end
end)
local currentlyTowedVehicle = nil
RegisterNetEvent('esx_garage:chargerDansFlatBed')
AddEventHandler('esx_garage:chargerDansFlatBed', function()
local playerped = GetPlayerPed(-1)
local vehicle = GetVehiclePedIsIn(playerped, true)
local towmodel = GetHashKey('flatbed')
local isVehicleTow = IsVehicleModel(vehicle, towmodel)
if isVehicleTow then
local coordA = GetEntityCoords(playerped, 1)
local coordB = GetOffsetFromEntityInWorldCoords(playerped, 0.0, 15.0, 0.0)
local targetVehicle = getVehicleInDirection(coordA, coordB)
if currentlyTowedVehicle == nil then
if targetVehicle ~= 0 then
if not IsPedInAnyVehicle(playerped, true) then
if vehicle ~= targetVehicle then
AttachEntityToEntity(targetVehicle, vehicle, 20, -0.5, -5.0, 1.0, 0.0, 0.0, 0.0, false, false, false, false, 20, true)
currentlyTowedVehicle = targetVehicle
TriggerEvent("chatMessage", "[SAV-Garagiste]", {255, 255, 0}, "Vehicule chargé!")
else
TriggerEvent("chatMessage", "[SAV-Garagiste]", {255, 255, 0}, "Vous êtes stupides ? vous ne pouvez pas charger votre propre camion...")
end
end
else
TriggerEvent("chatMessage", "[SAV-Garagiste]", {255, 255, 0}, "Il faut se placer face au véhicule à charger ! (il vaut mieux être à pied !)")
end
else
AttachEntityToEntity(currentlyTowedVehicle, vehicle, 20, -0.5, -12.0, 1.0, 0.0, 0.0, 0.0, false, false, false, false, 20, true)
DetachEntity(currentlyTowedVehicle, true, true)
currentlyTowedVehicle = nil
TriggerEvent("chatMessage", "[SAV-Garagiste]", {255, 255, 0}, "Véhicule détaché !")
end
else
TriggerEvent("chatMessage", "[SAV-Garagiste]", {255, 255, 0}, "Vous devez etre dans un flatbed !")
end
end)
function getVehicleInDirection(coordFrom, coordTo)
local rayHandle = CastRayPointToPoint(coordFrom.x, coordFrom.y, coordFrom.z, coordTo.x, coordTo.y, coordTo.z, 10, GetPlayerPed(-1), 0)
local a, b, c, d, vehicle = GetRaycastResult(rayHandle)
return vehicle
end
-- Activate menu when player is inside marker
Citizen.CreateThread(function()
while (PlayerData.identifier == nil) do
Wait(100)
end
local allowed_player = isAllowed()
while true do
Wait(0)
if(allowed_player) then
local coords = GetEntityCoords(GetPlayerPed(-1))
local isInMarker = false
local currentZone = nil
for k,v in pairs(Config.Zones) do
if(GetDistanceBetweenCoords(coords, v.Pos.x, v.Pos.y, v.Pos.z, true) < v.Size.x) then
isInMarker = true
currentZone = k
end
end
if isInMarker and not hasAlreadyEnteredMarker then
hasAlreadyEnteredMarker = true
lastZone = currentZone
TriggerEvent('esx_garagejob:hasEnteredMarker', currentZone)
end
if not isInMarker and hasAlreadyEnteredMarker then
hasAlreadyEnteredMarker = false
TriggerEvent('esx_garagejob:hasExitedMarker', lastZone)
end
end
end
end)
-- Create blips
Citizen.CreateThread(function()
local blip = AddBlipForCoord(Config.Zones.Entreprise.Pos.x, Config.Zones.Entreprise.Pos.y, Config.Zones.Entreprise.Pos.z)
SetBlipSprite (blip, Config.Zones.Entreprise.BlipSprite)
SetBlipDisplay(blip, 4)
SetBlipScale (blip, 1.2)
SetBlipColour (blip, 5)
SetBlipAsShortRange(blip, true)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString(Config.CompanyName)
EndTextCommandSetBlipName(blip)
end)
-- Menu Controls
Citizen.CreateThread(function()
while true do
Wait(0)
if IsControlPressed(0, Keys['ENTER']) and (GetGameTimer() - GUI.Time) > 300 then
SendNUIMessage({
enterPressed = true
})
GUI.Time = GetGameTimer()
end
if IsControlPressed(0, Keys['BACKSPACE']) and (GetGameTimer() - GUI.Time) > 300 then
SendNUIMessage({
backspacePressed = true
})
GUI.Time = GetGameTimer()
end
if IsControlPressed(0, Keys['LEFT']) and (GetGameTimer() - GUI.Time) > 300 then
SendNUIMessage({
move = 'LEFT'
})
GUI.Time = GetGameTimer()
end
if IsControlPressed(0, Keys['RIGHT']) and (GetGameTimer() - GUI.Time) > 300 then
SendNUIMessage({
move = 'RIGHT'
})
GUI.Time = GetGameTimer()
end
if IsControlPressed(0, Keys['TOP']) and (GetGameTimer() - GUI.Time) > 300 then
SendNUIMessage({
move = 'UP'
})
GUI.Time = GetGameTimer()
end
if IsControlPressed(0, Keys['DOWN']) and (GetGameTimer() - GUI.Time) > 300 then
SendNUIMessage({
move = 'DOWN'
})
GUI.Time = GetGameTimer()
end
end
end)
function GetVehHealthPercent()
local ped = GetPlayerPed(-1)
local vehicle = GetVehiclePedIsUsing(ped)
local vehiclehealth = GetEntityHealth(vehicle) - 100
local maxhealth = GetEntityMaxHealth(vehicle) - 100
local procentage = (vehiclehealth / maxhealth) * 100
return procentage
end
function ShowNotification(text)
SetNotificationTextEntry("STRING")
AddTextComponentString(text)
DrawNotification(false, false)
end
Citizen.CreateThread(function()
if (Config.EnableVehicleBreakOnDamage == true)then
while true do
Citizen.Wait(0)
local ped = GetPlayerPed(-1)
local vehicle = GetVehiclePedIsUsing(ped)
local damage = GetVehHealthPercent(vehicle)
if IsPedInAnyVehicle(ped, false) then
SetPlayerVehicleDamageModifier(PlayerId(), 100) -- Seems to not work at the moment --
if damage < Config.VehicleBreakDamageLimit then
SetVehicleUndriveable(vehicle, true)
ShowNotification("~g~Votre véhicule est trop endommagé.")
end
end
end
end
end)
| mit |
jshackley/darkstar | scripts/globals/mobskills/Thundris_Shriek.lua | 13 | 1405 | ---------------------------------------------
-- Thundris Shriek
--
-- Description: Deals heavy lightning damage to targets in area of effect. Additional effect: Terror
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes shadows
-- Range: Unknown
-- Notes: Players will begin to be intimidated by the dvergr after this attack.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if(mob:getFamily() == 316) then
local mobSkin = mob:getModelId();
if (mobSkin == 1839) then
return 0;
else
return 1;
end
end
if(mob:getFamily() == 91) then
local mobSkin = mob:getModelId();
if (mobSkin == 1840) then
return 0;
else
return 1;
end
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_TERROR;
MobStatusEffectMove(mob, target, typeEffect, 1, 0, 15);
local dmgmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_THUNDER,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_THUNDER,MOBPARAM_WIPE_SHADOWS);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
iofun/treehouse | luerl/46f722e1424442a185f160914566554c.lua | 1 | 2154 | -- A pair of Scourge is spawned from a single morph of Larva, like doggos.
-- Our unit function table
local this_unit = {}
-- Where we are and fast we move
local x, y, dx, dy
-- Our name
local name = "Zerg_Scourge"
-- Our color
local color = "red"
-- Our BWAPI unit type
local type = 47
-- Our label
local label = "zerg_unit"
-- Our category
local category = "small_air"
-- Size of a clock tick msec
local tick
-- It's me, the unit structure
local me = unit.self()
-- The standard local variables
local armor = 0
local hitpoints,shield = 25,0
local ground_damage,air_damage = 0,110
local ground_cooldown,air_cooldown = 0,0
local ground_range,air_range = 0,1
local sight = 5
local speed = 4.963
local supply = 0.5
local cooldown = 19
local mineral = 25
local gas = 75
local holdkey = "s"
-- The size of the region
local xsize,ysize = region.size()
-- The unit interface.
function this_unit.start() end
function this_unit.get_position() return x,y end
function this_unit.set_position(a1, a2) x,y = a1,a2 end
function this_unit.get_speed() return dx,dy end
function this_unit.set_speed(a1, a2) dx,dy = a1,a2 end
function this_unit.set_tick(a1) tick = a1 end
local function move_xy_bounce(x, y, dx, dy, valid_x, valid_y)
local nx = x + dx
local ny = y + dy
-- Bounce off the edge
if (not valid_x(nx)) then
nx = x - dx
dx = -dx
end
-- Bounce off the edge
if (not valid_y(ny)) then
ny = y - dy
dy = -dy
end
return nx, ny, dx, dy
end
local function move(x, y, dx, dy)
local nx,ny,ndx,ndy = move_xy_bounce(x, y, dx, dy,
region.valid_x, region.valid_y)
-- Where we were and where we are now.
local osx,osy = region.sector(x, y)
local nsx,nsy = region.sector(nx, ny)
if (osx ~= nsx or osy ~= nsy) then
-- In new sector, move us to the right sector
region.rem_sector(x, y)
region.add_sector(nx, ny)
end
return nx,ny,ndx,ndy
end
function this_unit.tick()
x,y,dx,dy = move(x, y, dx, dy)
end
function this_unit.attack()
-- The unit has been zapped and will die
region.rem_sector(x, y)
end
-- Return the unit table
return this_unit
| agpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.