repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278 values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15 values |
|---|---|---|---|---|---|
starlightknight/darkstar | scripts/zones/Cloister_of_Gales/mobs/Garuda_Prime.lua | 8 | 1457 | -----------------------------------
-- Area: Cloister of Gales
-- Mob: Garuda Prime
-- Involved in Quest: Trial by Wind, Trial Size Trial by Wind
-- Involved in Mission: ASA-4 Sugar Coated Directive
-----------------------------------
require("scripts/globals/keyitems")
require("scripts/globals/settings")
require("scripts/globals/status")
-----------------------------------
function onMobSpawn(mob)
-- ASA-4: Avatar is Unkillable Until Its Used Astral Flow At Least 5 times At Specified Intervals
if mob:getBattlefieldID() == 420 then
mob:setLocalVar("astralflows", 0)
mob:setUnkillable(true)
end
end
function onMobFight(mob, target)
-- ASA-4: Astral Flow Behavior - Guaranteed to Use At Least 5 times before killable, at specified intervals.
if mob:getBattlefieldID() == 420 and mob:getCurrentAction() == dsp.act.ATTACK then
local astralFlows = mob:getLocalVar("astralflows")
if (astralFlows == 0 and mob:getHPP() <= 80)
or (astralFlows == 1 and mob:getHPP() <= 60)
or (astralFlows == 2 and mob:getHPP() <= 40)
or (astralFlows == 3 and mob:getHPP() <= 20)
or (astralFlows == 4 and mob:getHPP() <= 1) then
mob:setLocalVar("astralflows", astralFlows + 1)
mob:useMobAbility(875)
if astralFlows >= 5 then
mob:setUnkillable(false)
end
end
end
end
function onMobDeath(mob, player, isKiller)
end
| gpl-3.0 |
starlightknight/darkstar | scripts/zones/Empyreal_Paradox/IDs.lua | 8 | 1043 | -----------------------------------
-- Area: Empyreal_Paradox
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.EMPYREAL_PARADOX] =
{
text =
{
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
CONQUEST_BASE = 7420, -- Tallying conquest results...
PRISHE_TEXT = 7685, -- You're about to learn how strong the will to live makes us!
SELHTEUS_TEXT = 7698, -- The...Emptiness... Is this...how it was meant...to be...?
PROMATHIA_TEXT = 7701, -- Give thyself to the apathy within...
},
mob =
{
PROMATHIA_OFFSET = 16924673,
},
npc =
{
},
}
return zones[dsp.zone.EMPYREAL_PARADOX] | gpl-3.0 |
starlightknight/darkstar | scripts/globals/weaponskills/death_blossom.lua | 10 | 2640 | -----------------------------------
-- Death Blossom
-- Sword weapon skill (RDM main only)
-- Description: Delivers a threefold attack that lowers target's magic evasion. Chance of lowering target's magic evasion varies with TP. Murgleis: Aftermath effect varies with TP.
-- Lowers magic evasion by up to 10.
-- Effect lasts up to 55 seconds.
-- Available only after completing the Unlocking a Myth (Red Mage) quest.
-- Aligned with the Breeze Gorget, Thunder Gorget, Aqua Gorget & Snow Gorget.
-- Aligned with the Breeze Belt, Thunder Belt, Aqua Belt & Snow Belt.
-- Modifiers: STR:30% MND:50%
-- 100%TP 200%TP 300%TP
-- 4 4 4 new
-- 1.125 1.125 1.125 old
-----------------------------------
require("scripts/globals/aftermath")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.numHits = 3
-- ftp damage mods (for Damage Varies with TP lines are calculated in the function
params.ftp100 = 1.125 params.ftp200 = 1.125 params.ftp300 = 1.125
-- wscs are in % so 0.2=20%
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
-- critical mods, again in % (ONLY USE FOR critICAL HIT VARIES WITH TP)
params.crit100 = 0.0 params.crit200 = 0.0 params.crit300 = 0.0
params.canCrit = false
-- accuracy mods (ONLY USE FOR accURACY VARIES WITH TP) , should be the acc at those %s NOT the penalty values. Leave 0 if acc doesnt vary with tp.
params.acc100 = 0.0 params.acc200 = 0.0 params.acc300 = 0.0
-- attack multiplier (only some WSes use this, this varies the actual ratio value, see Tachi: Kasha) 1 is default.
params.atk100 = 1; params.atk200 = 1; params.atk300 = 1;
if USE_ADOULIN_WEAPON_SKILL_CHANGES then
params.ftp100 = 4.0 params.ftp200 = 4.0 params.ftp300 = 4.0
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar)
if damage > 0 then
local duration = tp / 1000 * 20 - 5
if not target:hasStatusEffect(dsp.effect.MAGIC_EVASION_DOWN) then
target:addStatusEffect(dsp.effect.MAGIC_EVASION_DOWN, 10, 0, duration)
end
-- Apply aftermath
dsp.aftermath.addStatusEffect(player, tp, dsp.slot.MAIN, dsp.aftermath.type.MYTHIC)
end
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Western_Adoulin/npcs/Jorin.lua | 3 | 2278 | -----------------------------------
-- Area: Western Adoulin
-- NPC: Jorin
-- Type: Standard NPC and Quest Giver
-- Starts, Involved with, and Finishes Quest: 'The Old Man and the Harpoon'
-- @zone 256
-- !pos 92 32 152 256
-----------------------------------
package.loaded["scripts/zones/Western_Adoulin/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Western_Adoulin/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local TOMATH = player:getQuestStatus(ADOULIN, THE_OLD_MAN_AND_THE_HARPOON);
if (TOMATH == QUEST_ACCEPTED) then
if (player:hasKeyItem(EXTRAVAGANT_HARPOON)) then
-- Finishing Quest: 'The Old Man and the Harpoon'
player:startEvent(0x09EE);
else
-- Dialgoue during Quest: 'The Old Man and the Harpoon'
player:startEvent(0x09ED);
end
elseif (TOMATH == QUEST_AVAILABLE) then
-- Starts Quest: 'The Old Man and the Harpoon'
player:startEvent(0x09EC);
else
-- Standard dialogue
player:startEvent(0x0230);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == 0x09EC) then
-- Starting Quest: 'The Old Man and the Harpoon'
player:addQuest(ADOULIN, THE_OLD_MAN_AND_THE_HARPOON);
player:addKeyItem(BROKEN_HARPOON);
player:messageSpecial(KEYITEM_OBTAINED, BROKEN_HARPOON);
elseif (csid == 0x09EE) then
-- Finishing Quest: 'The Old Man and the Harpoon'
player:completeQuest(ADOULIN, THE_OLD_MAN_AND_THE_HARPOON);
player:addExp(500 * EXP_RATE);
player:addCurrency('bayld', 300 * BAYLD_RATE);
player:messageSpecial(BAYLD_OBTAINED, 300 * BAYLD_RATE);
player:delKeyItem(EXTRAVAGANT_HARPOON);
player:addFame(ADOULIN);
end
end;
| gpl-3.0 |
zzzaaiidd/TCHUKY | plugins/getlink.lua | 11 | 28101 | --[[
โโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโ โโ โโ โโ
โโ โโ BY MOHAMMED HISHAM โโ โโ
โโ โโ BY MOHAMMEDHISHAM (@TH3BOSS) โโ โโ
โโ โโ JUST WRITED BY MOHAMMED HISHAM โโ โโ
โโ โโ A SPECiAL LINK : ุงูุฑุงุจุท ุฎุงุต โโ โโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
--]]
do
local function check_member(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as the owner.')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group has been removed')
end
end
end
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
return 'Group is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Chat rules:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted.')
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
if success == -1 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' then
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'rem' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 then
return automodadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local receiver = 'user#id'..msg.action.user.id
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return false
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Welcome to "' .. string.gsub(msg.to.print_name, '_', ' ') ..'" this group has rules that you should follow:\n'..rules
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..msg.action.user.id)
send_large_msg(receiver, rules)
end
if matches[1] == 'chat_del_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'promote' and matches[2] then
if not is_owner(msg) then
return "Only owner can promote"
end
local member = string.gsub(matches[2], "@", "")
local mod_cmd = 'promote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'demote' and matches[2] then
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username then
return "You can't demote yourself"
end
local member = string.gsub(matches[2], "@", "")
local mod_cmd = 'demote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'set' then
if matches[2] == 'rules' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'lock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
end
if matches[1] == 'settings' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
if matches[1] == 'newlink' then
if not is_momod(msg) then
return "For moderators only!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'ุงูุฑุงุจุท ุฎุงุต' then
if not is_momod(msg) then
return "๐๐ปูุชูุนูุจ ุจููููู ูููุทู ุงูู
ุฏูุฑ ุงู ุงูุงุฏุงุฑู ูุญูู ูููโ๏ธ"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "โูุฑุฌุฆ ุงุฑุณุงู [/ุชุบูุฑ ุงูุฑุงุจุท] ูุงูุดุงุก ุฑุงุจุท ุงูู
ุฌู
ูุนู๐๐ปโ๏ธ"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
send_large_msg('user#id'..msg.from.id, "โ๏ธ ุฑุงุจุท ู
ุฌู
ูุนุฉ ๐ฅ "..msg.to.title..'\n'..group_link)
return "ุชู
ุงุฑุณุงู ุงูุฑุงุจุท ุงูู ุงูุฎุงุต ๐๐"
end
if matches[1] == 'setowner' then
if not is_owner(msg) then
return "For owner only!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = matches[2].." added as owner"
return text
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "Group owner is ["..group_owner..']'
end
if matches[1] == 'setgpowner' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as owner"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "For moderators only!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'Group flood has been set to '..matches[2]
end
if matches[1] == 'clean' then
if not is_owner(msg) then
return "Only owner can clean"
end
if matches[2] == 'member' then
if not is_owner(msg) then
return "Only admins can clean members"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'help' then
if not is_momod(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
end
return {
patterns = {
"^(ุงูุฑุงุจุท ุฎุงุต)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
-- arabic : @SAJJADNOORI
| gpl-2.0 |
starlightknight/darkstar | scripts/zones/Port_San_dOria/npcs/Meinemelle.lua | 9 | 1078 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Meinemelle
-- !pos -8.289 -9.3 -146.093 232
-----------------------------------
local ID = require("scripts/zones/Port_San_dOria/IDs")
require("scripts/globals/npc_util")
require("scripts/globals/quests")
-----------------------------------
function onTrade(player, npc, trade)
if player:getQuestStatus(SANDORIA, dsp.quest.id.sandoria.FLYERS_FOR_REGINE) == QUEST_ACCEPTED and npcUtil.tradeHas(trade, 532) then
player:messageSpecial(ID.text.FLYER_REFUSED)
end
end
function onTrigger(player, npc)
if player:getCharVar("thePickpocket") == 1 and not player:getMaskBit(player:getCharVar("thePickpocketSkipNPC"), 0) then
player:showText(npc, ID.text.PICKPOCKET_MEINEMELLE)
player:setMaskBit(player:getCharVar("thePickpocketSkipNPC"), "thePickpocketSkipNPC", 0, true)
else
player:showText(npc, ID.text.ITEM_DELIVERY_DIALOG)
player:openSendBox()
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Palborough_Mines/npcs/HomePoint#1.lua | 3 | 1270 | -----------------------------------
-- Area: Palborough_Mines
-- NPC: HomePoint#1
-- !pos 109 -38.5 -147 143
-----------------------------------
package.loaded["scripts/zones/Palborough_Mines/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Palborough_Mines/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 53);
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 |
soccermitchy/heroku-lapis | opt/src/luarocks/src/luarocks/install.lua | 15 | 8077 | --- Module implementing the LuaRocks "install" command.
-- Installs binary rocks.
--module("luarocks.install", package.seeall)
local install = {}
package.loaded["luarocks.install"] = install
local path = require("luarocks.path")
local repos = require("luarocks.repos")
local fetch = require("luarocks.fetch")
local util = require("luarocks.util")
local fs = require("luarocks.fs")
local deps = require("luarocks.deps")
local manif = require("luarocks.manif")
local remove = require("luarocks.remove")
local cfg = require("luarocks.cfg")
install.help_summary = "Install a rock."
install.help_arguments = "{<rock>|<name> [<version>]}"
install.help = [[
Argument may be the name of a rock to be fetched from a repository
or a filename of a locally available rock.
--keep Do not remove previously installed versions of the
rock after installing a new one. This behavior can
be made permanent by setting keep_other_versions=true
in the configuration file.
--only-deps Installs only the dependencies of the rock.
]]..util.deps_mode_help()
--- Install a binary rock.
-- @param rock_file string: local or remote filename of a rock.
-- @param deps_mode: string: Which trees to check dependencies for:
-- "one" for the current default tree, "all" for all trees,
-- "order" for all trees with priority >= the current default, "none" for no trees.
-- @return (string, string) or (nil, string, [string]): Name and version of
-- installed rock if succeeded or nil and an error message followed by an error code.
function install.install_binary_rock(rock_file, deps_mode)
assert(type(rock_file) == "string")
local name, version, arch = path.parse_name(rock_file)
if not name then
return nil, "Filename "..rock_file.." does not match format 'name-version-revision.arch.rock'."
end
if arch ~= "all" and arch ~= cfg.arch then
return nil, "Incompatible architecture "..arch, "arch"
end
if repos.is_installed(name, version) then
repos.delete_version(name, version)
end
local rollback = util.schedule_function(function()
fs.delete(path.install_dir(name, version))
fs.remove_dir_if_empty(path.versions_dir(name))
end)
local ok, err, errcode = fetch.fetch_and_unpack_rock(rock_file, path.install_dir(name, version))
if not ok then return nil, err, errcode end
local rockspec, err, errcode = fetch.load_rockspec(path.rockspec_file(name, version))
if err then
return nil, "Failed loading rockspec for installed package: "..err, errcode
end
if deps_mode == "none" then
util.printerr("Warning: skipping dependency checks.")
else
ok, err, errcode = deps.check_external_deps(rockspec, "install")
if err then return nil, err, errcode end
end
-- For compatibility with .rock files built with LuaRocks 1
if not fs.exists(path.rock_manifest_file(name, version)) then
ok, err = manif.make_rock_manifest(name, version)
if err then return nil, err end
end
if deps_mode ~= "none" then
ok, err, errcode = deps.fulfill_dependencies(rockspec, deps_mode)
if err then return nil, err, errcode end
end
ok, err = repos.deploy_files(name, version, repos.should_wrap_bin_scripts(rockspec))
if err then return nil, err end
util.remove_scheduled_function(rollback)
rollback = util.schedule_function(function()
repos.delete_version(name, version)
end)
ok, err = repos.run_hook(rockspec, "post_install")
if err then return nil, err end
ok, err = manif.update_manifest(name, version, nil, deps_mode)
if err then return nil, err end
local license = ""
if rockspec.description.license then
license = ("(license: "..rockspec.description.license..")")
end
local root_dir = path.root_dir(cfg.rocks_dir)
util.printout()
util.printout(name.." "..version.." is now installed in "..root_dir.." "..license)
util.remove_scheduled_function(rollback)
return name, version
end
--- Installs the dependencies of a binary rock.
-- @param rock_file string: local or remote filename of a rock.
-- @param deps_mode: string: Which trees to check dependencies for:
-- "one" for the current default tree, "all" for all trees,
-- "order" for all trees with priority >= the current default, "none" for no trees.
-- @return (string, string) or (nil, string, [string]): Name and version of
-- the rock whose dependencies were installed if succeeded or nil and an error message
-- followed by an error code.
function install.install_binary_rock_deps(rock_file, deps_mode)
assert(type(rock_file) == "string")
local name, version, arch = path.parse_name(rock_file)
if not name then
return nil, "Filename "..rock_file.." does not match format 'name-version-revision.arch.rock'."
end
if arch ~= "all" and arch ~= cfg.arch then
return nil, "Incompatible architecture "..arch, "arch"
end
local ok, err, errcode = fetch.fetch_and_unpack_rock(rock_file, path.install_dir(name, version))
if not ok then return nil, err, errcode end
local rockspec, err, errcode = fetch.load_rockspec(path.rockspec_file(name, version))
if err then
return nil, "Failed loading rockspec for installed package: "..err, errcode
end
ok, err, errcode = deps.fulfill_dependencies(rockspec, deps_mode)
if err then return nil, err, errcode end
util.printout()
util.printout("Succesfully installed dependencies for " ..name.." "..version)
return name, version
end
--- Driver function for the "install" command.
-- @param name string: name of a binary rock. If an URL or pathname
-- to a binary rock is given, fetches and installs it. If a rockspec or a
-- source rock is given, forwards the request to the "build" command.
-- If a package name is given, forwards the request to "search" and,
-- if returned a result, installs the matching rock.
-- @param version string: When passing a package name, a version number
-- may also be given.
-- @return boolean or (nil, string, exitcode): True if installation was
-- successful, nil and an error message otherwise. exitcode is optionally returned.
function install.run(...)
local flags, name, version = util.parse_flags(...)
if type(name) ~= "string" then
return nil, "Argument missing. "..util.see_help("install")
end
local ok, err = fs.check_command_permissions(flags)
if not ok then return nil, err, cfg.errorcodes.PERMISSIONDENIED end
if name:match("%.rockspec$") or name:match("%.src%.rock$") then
util.printout("Using "..name.."... switching to 'build' mode")
local build = require("luarocks.build")
return build.run(name, util.forward_flags(flags, "local", "keep", "deps-mode", "only-deps"))
elseif name:match("%.rock$") then
if flags["only-deps"] then
ok, err = install.install_binary_rock_deps(name, deps.get_deps_mode(flags))
else
ok, err = install.install_binary_rock(name, deps.get_deps_mode(flags))
end
if not ok then return nil, err end
local name, version = ok, err
if (not flags["only-deps"]) and (not flags["keep"]) and not cfg.keep_other_versions then
local ok, err = remove.remove_other_versions(name, version, flags["force"])
if not ok then util.printerr(err) end
end
return name, version
else
local search = require("luarocks.search")
local results, err = search.find_suitable_rock(search.make_query(name:lower(), version))
if err then
return nil, err
elseif type(results) == "string" then
local url = results
util.printout("Installing "..url.."...")
return install.run(url, util.forward_flags(flags))
else
util.printout()
util.printerr("Could not determine which rock to install.")
util.title("Search results:")
search.print_results(results)
return nil, (next(results) and "Please narrow your query." or "No results found.")
end
end
end
return install
| gpl-2.0 |
gedads/Neodynamis | scripts/zones/Promyvion-Dem/mobs/Memory_Receptacle.lua | 2 | 2382 | -----------------------------------
-- Area: Promyvion-Dem
-- MOB: Memory Receptacle
-----------------------------------
package.loaded["scripts/zones/Promyvion-Dem/TextIDs"] = nil;
package.loaded["scripts/zones/Promyvion-Dem/MobIDs"] = nil;
-----------------------------------
require("scripts/zones/Promyvion-Dem/TextIDs");
require("scripts/zones/Promyvion-Dem/MobIDs");
require("scripts/globals/status");
function onMobInitialize(mob)
mob:addMod(MOD_REGAIN, 100); -- 10% Regain for now
mob:SetAutoAttackEnabled(false); -- Recepticles only use TP moves.
end;
function onMobSpawn(mob, target)
mob:setLocalVar("nextStray", os.time() + 30);
end;
function checkStray(mob)
local mobId = mob:getID();
local numStrays = MEMORY_RECEPTACLES[mobId][2];
if (os.time() > mob:getLocalVar("nextStray")) then
for i = mobId + 1, mobId + numStrays do
local stray = GetMobByID(i);
if (not stray:isSpawned()) then
mob:AnimationSub(1);
stray:setPos(mob:getXPos() + math.random(-1,1), mob:getYPos(), mob:getZPos() + math.random(-1,1));
SpawnMob(stray:getID());
mob:setLocalVar("nextStray", os.time() + 30);
break;
end
end
else
mob:AnimationSub(2);
end
end;
function onMobRoam(mob)
checkStray(mob);
end;
function onMobFight(mob, target)
local mobId = mob:getID();
local numStrays = MEMORY_RECEPTACLES[mobId][2];
-- keep pets linked
for i = mobId + 1, mobId + numStrays do
local stray = GetMobByID(i);
if (stray:isSpawned()) then
stray:updateEnmity(target);
end
end
-- summon a stray every 30 seconds
checkStray(mob);
end;
function onMobDeath(mob, player, isKiller)
if (isKiller) then
mob:AnimationSub(0);
-- chance to open portal
local mobId = mob:getID();
local floor = MEMORY_RECEPTACLES[mobId][1];
local numAlive = 1;
for k, v in pairs(MEMORY_RECEPTACLES) do
if (k ~= mobId and v[1] == floor and GetMobByID(k):isAlive()) then
numAlive = numAlive + 1;
end
end
if (math.random(numAlive) == 1) then
local stream = GetNPCByID(MEMORY_RECEPTACLES[mobId][3]);
stream:openDoor(180);
end
end
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Kazham/npcs/Kukupp.lua | 2 | 5591 | -----------------------------------
-- Area: Kazham
-- NPC: Kukupp
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/zones/Kazham/TextIDs");
require("scripts/globals/pathfind");
local path = {
43.067505, -11.000000, -177.214966,
43.583324, -11.000000, -178.104263,
44.581100, -11.000000, -178.253067,
45.459488, -11.000000, -177.616653,
44.988266, -11.000000, -176.728577,
43.920345, -11.000000, -176.549469,
42.843422, -11.000000, -176.469452,
41.840969, -11.000000, -176.413971,
41.849968, -11.000000, -177.460236,
42.699162, -11.000000, -178.046478,
41.800228, -11.000000, -177.440720,
40.896564, -11.000000, -176.834793,
41.800350, -11.000000, -177.440704,
43.494385, -11.000000, -178.577087,
44.525345, -11.000000, -178.332214,
45.382175, -11.000000, -177.664185,
44.612972, -11.000000, -178.457062,
43.574627, -11.000000, -178.455185,
42.603222, -11.000000, -177.950760,
41.747925, -11.000000, -177.402481,
40.826141, -11.000000, -176.787674,
41.709877, -11.000000, -177.380173,
42.570263, -11.000000, -177.957306,
43.600094, -11.000000, -178.648087,
44.603924, -11.000000, -178.268082,
45.453266, -11.000000, -177.590103,
44.892513, -11.000000, -176.698730,
43.765514, -11.000000, -176.532211,
42.616215, -11.000000, -176.454498,
41.549683, -11.000000, -176.399078,
42.671898, -11.000000, -176.463196,
43.670380, -11.000000, -176.518692,
45.595409, -11.000000, -176.626129,
44.485180, -11.000000, -176.564041,
43.398880, -11.000000, -176.503586,
40.778934, -11.000000, -176.357834,
41.781410, -11.000000, -176.413223,
42.799843, -11.000000, -176.469894,
45.758560, -11.000000, -176.782486,
45.296803, -11.000000, -177.683472,
44.568489, -11.000000, -178.516357,
45.321579, -11.000000, -177.759048,
45.199261, -11.000000, -176.765274,
44.072094, -11.000000, -176.558044,
43.054935, -11.000000, -176.482895,
41.952633, -11.000000, -176.421570,
43.014915, -11.000000, -176.482178,
45.664345, -11.000000, -176.790253,
45.225407, -11.000000, -177.712463,
44.465252, -11.000000, -178.519577,
43.388020, -11.000000, -178.364532,
42.406048, -11.000000, -177.838013,
41.515419, -11.000000, -177.255875,
40.609776, -11.000000, -176.645706
};
function onSpawn(npc)
npc:initNpcAi();
npc:setPos(pathfind.first(path));
onPath(npc);
end;
function onPath(npc)
pathfind.patrol(npc, path);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
-- item IDs
-- 483 Broken Mithran Fishing Rod
-- 22 Workbench
-- 1008 Ten of Coins
-- 1157 Sands of Silence
-- 1158 Wandering Bulb
-- 904 Giant Fish Bones
-- 4599 Blackened Toad
-- 905 Wyvern Skull
-- 1147 Ancient Salt
-- 4600 Lucky Egg
function onTrade(player,npc,trade)
local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, THE_OPO_OPO_AND_I);
local progress = player:getVar("OPO_OPO_PROGRESS");
local failed = player:getVar("OPO_OPO_FAILED");
local goodtrade = trade:hasItemQty(22,1);
local badtrade = (trade:hasItemQty(483,1) or trade:hasItemQty(1008,1) or trade:hasItemQty(1157,1) or trade:hasItemQty(1158,1) or trade:hasItemQty(904,1) or trade:hasItemQty(4599,1) or trade:hasItemQty(905,1) or trade:hasItemQty(1147,1) or trade:hasItemQty(4600,1));
if (OpoOpoAndIStatus == QUEST_ACCEPTED) then
if progress == 1 or failed == 2 then
if goodtrade then
player:startEvent(0x00DC);
elseif badtrade then
player:startEvent(0x00E6);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, THE_OPO_OPO_AND_I);
local progress = player:getVar("OPO_OPO_PROGRESS");
local failed = player:getVar("OPO_OPO_FAILED");
local retry = player:getVar("OPO_OPO_RETRY");
if (OpoOpoAndIStatus == QUEST_ACCEPTED) then
if retry >= 1 then -- has failed on future npc so disregard previous successful trade
player:startEvent(0x00C6);
npc:wait();
elseif (progress == 1 or failed == 2) then
player:startEvent(0x00D0); -- asking for workbench
elseif (progress >= 2 or failed >= 3) then
player:startEvent(0x00F3); -- happy with workbench
end
else
player:startEvent(0x00C6);
npc:wait();
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,npc)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x00DC) then -- correct trade, onto next opo
if player:getVar("OPO_OPO_PROGRESS") == 1 then
player:tradeComplete();
player:setVar("OPO_OPO_PROGRESS",2);
player:setVar("OPO_OPO_FAILED",0);
else
player:setVar("OPO_OPO_FAILED",3);
end
elseif (csid == 0x00E6) then -- wrong trade, restart at first opo
player:setVar("OPO_OPO_FAILED",1);
player:setVar("OPO_OPO_RETRY",2);
else
npc:wait(0);
end
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Port_Windurst/npcs/Ohruru.lua | 3 | 4928 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Ohruru
-- Starts & Finishes Repeatable Quest: Catch me if you can
-- Involved in Quest: Wonder Wands
-- Note: Animation for his "Cure" is not functioning. Unable to capture option 1, so if the user says no, he heals them anyways.
-- !pos -108 -5 94 240
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_Windurst/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- player:delQuest(WINDURST,CATCH_IT_IF_YOU_CAN); -- ======== FOR TESTING ONLY ==========-----
-- ======== FOR TESTING ONLY ==========-----
-- if (player:getVar("QuestCatchItIfYouCan_var") == 0 and player:hasStatusEffect(EFFECT_MUTE) == false and player:hasStatusEffect(EFFECT_BANE) == false and player:hasStatusEffect(EFFECT_PLAGUE) == false) then
-- rand = math.random(1,3);
-- if (rand == 1) then
-- player:addStatusEffect(EFFECT_MUTE,0,0,100);
-- elseif (rand == 2) then
-- player:addStatusEffect(EFFECT_BANE,0,0,100);
-- elseif (rand == 3) then
-- player:addStatusEffect(EFFECT_PLAGUE,0,0,100);
-- end
-- end
-- ======== FOR TESTING ONLY ==========-----
Catch = player:getQuestStatus(WINDURST,CATCH_IT_IF_YOU_CAN);
WonderWands = player:getQuestStatus(WINDURST,WONDER_WANDS);
if (WonderWands == QUEST_ACCEPTED) then
player:startEvent(0x0102,0,17053);
elseif (Catch == 0) then
prog = player:getVar("QuestCatchItIfYouCan_var");
if (prog == 0) then
player:startEvent(0x00e6); -- CATCH IT IF YOU CAN: Before Quest 1
player:setVar("QuestCatchItIfYouCan_var",1);
elseif (prog == 1) then
player:startEvent(0x00fd); -- CATCH IT IF YOU CAN: Before Start
player:setVar("QuestCatchItIfYouCan_var",2);
elseif (prog == 2) then
player:startEvent(0x00e7); -- CATCH IT IF YOU CAN: Before Quest 2
end
elseif (Catch >= 1 and (player:hasStatusEffect(EFFECT_MUTE) == true or player:hasStatusEffect(EFFECT_BANE) == true or player:hasStatusEffect(EFFECT_PLAGUE) == true)) then
player:startEvent(0x00f6); -- CATCH IT IF YOU CAN: Quest Turn In 1
elseif (Catch >= 1 and player:needToZone()) then
player:startEvent(0x00ff); -- CATCH IT IF YOU CAN: After Quest
elseif (Catch == 1 and player:hasStatusEffect(EFFECT_MUTE) == false and player:hasStatusEffect(EFFECT_BANE) == false and player:hasStatusEffect(EFFECT_PLAGUE) == false) then
rand = math.random(1,2);
if (rand == 1) then
player:startEvent(0x00f8); -- CATCH IT IF YOU CAN: During Quest 1
else
player:startEvent(0x00fb); -- CATCH IT IF YOU CAN: During Quest 2
end
elseif (WonderWands == QUEST_COMPLETED) then
player:startEvent(0x0109);
else
player:startEvent(0x00e6); -- 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);
if (csid == 0x00e7) then
player:addQuest(WINDURST,CATCH_IT_IF_YOU_CAN);
elseif (csid == 0x00f6 and option == 0) then
player:needToZone(true);
if (player:hasStatusEffect(EFFECT_MUTE) == true) then
player:delStatusEffect(EFFECT_MUTE);
player:addGil(GIL_RATE*1000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*1000);
elseif (player:hasStatusEffect(EFFECT_BANE) == true) then
player:delStatusEffect(EFFECT_BANE);
player:addGil(GIL_RATE*1200);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*1200);
elseif (player:hasStatusEffect(EFFECT_PLAGUE) == true) then
player:delStatusEffect(EFFECT_PLAGUE);
player:addGil(GIL_RATE*1500);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*1500);
end
player:setVar("QuestCatchItIfYouCan_var",0);
if (player:getQuestStatus(WINDURST,CATCH_IT_IF_YOU_CAN) == QUEST_ACCEPTED) then
player:completeQuest(WINDURST,CATCH_IT_IF_YOU_CAN);
player:addFame(WINDURST,75);
else
player:addFame(WINDURST,8);
end
end
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/globals/weaponskills/refulgent_arrow.lua | 10 | 1449 | -----------------------------------
-- Refulgent Arrow
-- Archery weapon skill
-- Skill level: 290
-- Delivers a twofold attack. Damage varies with TP.
-- Aligned with the Aqua Gorget & Light Gorget.
-- Aligned with the Aqua Belt & Light Belt.
-- Element: None
-- Modifiers: STR: 60% http://www.bg-wiki.com/bg/Refulgent_Arrow
-- 100%TP 200%TP 300%TP
-- 3.00 4.25 7.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 2;
params.ftp100 = 3; params.ftp200 = 4.25; params.ftp300 = 5;
params.str_wsc = 0.16; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.25; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 3; params.ftp200 = 4.25; params.ftp300 = 7;
params.str_wsc = 0.6;
end
local damage, criticalHit, tpHits, extraHits = doRangedWeaponskill(player, target, wsID, params, tp, primary, action);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
strava/thrift | lib/lua/TMemoryBuffer.lua | 100 | 2266 | --
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you 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.
--
require 'TTransport'
TMemoryBuffer = TTransportBase:new{
__type = 'TMemoryBuffer',
buffer = '',
bufferSize = 1024,
wPos = 0,
rPos = 0
}
function TMemoryBuffer:isOpen()
return 1
end
function TMemoryBuffer:open() end
function TMemoryBuffer:close() end
function TMemoryBuffer:peak()
return self.rPos < self.wPos
end
function TMemoryBuffer:getBuffer()
return self.buffer
end
function TMemoryBuffer:resetBuffer(buf)
if buf then
self.buffer = buf
self.bufferSize = string.len(buf)
else
self.buffer = ''
self.bufferSize = 1024
end
self.wPos = string.len(buf)
self.rPos = 0
end
function TMemoryBuffer:available()
return self.wPos - self.rPos
end
function TMemoryBuffer:read(len)
local avail = self:available()
if avail == 0 then
return ''
end
if avail < len then
len = avail
end
local val = string.sub(self.buffer, self.rPos + 1, self.rPos + len)
self.rPos = self.rPos + len
return val
end
function TMemoryBuffer:readAll(len)
local avail = self:available()
if avail < len then
local msg = string.format('Attempt to readAll(%d) found only %d available',
len, avail)
terror(TTransportException:new{message = msg})
end
-- read should block so we don't need a loop here
return self:read(len)
end
function TMemoryBuffer:write(buf)
self.buffer = self.buffer .. buf
self.wPos = self.wPos + string.len(buf)
end
function TMemoryBuffer:flush() end
| apache-2.0 |
gedads/Neodynamis | scripts/zones/Lower_Jeuno/npcs/Susu.lua | 17 | 1634 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Susu
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,SUSU_SHOP_DIALOG);
stock = {0x1227,20000, -- Banishga II
0x1248,244, -- Barsleep
0x1249,400, -- Barpoison
0x124a,780, -- Barparalyze
0x124b,2030, -- Barblind
0x124c,4608, -- Barsilence
0x1256,244, -- Barsleepra
0x1257,400, -- Barpoisonra
0x1258,780, -- Barparalyzra
0x1259,2030, -- Barblindra
0x125a,4608, -- Barsilencera
0x1214,8586, -- Cursna
0x1215,35000, -- Holy
0x1211,2330, -- Silena
0x1212,19200, -- Stona
0x1213,13300} -- Viruna
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 |
gedads/Neodynamis | scripts/zones/Cape_Teriggan/TextIDs.lua | 2 | 1536 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6380; -- You cannot obtain the item <item> come back again after sorting your inventory.
FULL_INVENTORY_AFTER_TRADE = 6384; -- You cannot obtain the #. Try trading again after sorting your inventory.
ITEM_OBTAINED = 6386; -- Obtained: <item>.
GIL_OBTAINED = 6387; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6389; -- Obtained key item: <keyitem>.
ITEMS_OBTAINED = 6395; -- You obtain
BEASTMEN_BANNER = 7128; -- There is a beastmen's banner.
FISHING_MESSAGE_OFFSET = 7548; -- You can't fish here.
HOMEPOINT_SET = 11251; -- Home point set!
-- Other dialog
NOTHING_OUT_OF_ORDINARY = 6400; -- There is nothing out of the ordinary here.
-- Conquest
CONQUEST = 7215; -- You've earned conquest points!
-- ZM4 Dialog
SOMETHING_BETTER = 7660; -- Don't you have something better to do right now?
CANNOT_REMOVE_FRAG = 7663; -- It is an oddly shaped stone monument. A shining stone is embedded in it, but cannot be removed...
ALREADY_OBTAINED_FRAG = 7664; -- You have already obtained this monument's . Try searching for another.
FOUND_ALL_FRAGS = 7665; -- You have obtained all of the fragments. You must hurry to the ruins of the ancient shrine!
ZILART_MONUMENT = 7667; -- It is an ancient Zilart monument.
-- Other
NOTHING_HAPPENS = 119; -- Nothing happens...?Possible Special Code: 00?
-- conquest Base
CONQUEST_BASE = 7047; -- Tallying conquest results...
| gpl-3.0 |
starlightknight/darkstar | scripts/zones/Northern_San_dOria/npcs/Arachagnon.lua | 11 | 1150 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Arachagnon
-- Standard Merchant NPC
-----------------------------------
local ID = require("scripts/zones/Northern_San_dOria/IDs")
require("scripts/globals/npc_util")
require("scripts/globals/quests")
require("scripts/globals/shop")
function onTrade(player,npc,trade)
if player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.FLYERS_FOR_REGINE) == QUEST_ACCEPTED and npcUtil.tradeHas(trade, 532) then
player:messageSpecial(ID.text.FLYER_REFUSED)
end
end
function onTrigger(player,npc)
local stock =
{
12633, 270, -- Elvaan Jerkin
12634, 270, -- Elvaan Bodice
12755, 162, -- Elvaan Gloves
12759, 162, -- Elvaan Gauntlets
12885, 234, -- Elvaan M Chausses
12889, 234, -- Elvaan F Chausses
13006, 162, -- Elvaan M Ledelsens
13011, 162, -- Elvaan F Ledelsens
}
player:showText(npc, ID.text.ARACHAGNON_SHOP_DIALOG)
dsp.shop.general(player, stock, SANDORIA)
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
| gpl-3.0 |
czegarram/rapid-troll | multipartForm.lua | 1 | 7290 | -------------------------------------------------
--
-- class_MultipartFormData.lua
-- Author: Brill Pappin, Sixgreen Labs Inc.
--
-- Generates multipart form-data for http POST calls that require it.
--
-- Caution:
-- In Corona SDK you have to set a string as the body, which means that the
-- entire POST needs to be encoded as a string, including any files you attach.
-- Needless to say, if the file you are sending is large, it''s going to use
-- up all your available memory!
--
-- Example:
--[[
local MultipartFormData = require("class_MultipartFormData")
local multipart = MultipartFormData.new()
multipart:addHeader("Customer-Header", "Custom Header Value")
multipart:addField("myFieldName","myFieldValue")
multipart:addField("banana","yellow")
multipart:addFile("myfile", system.pathForFile( "myfile.jpg", system.DocumentsDirectory ), "image/jpeg", "myfile.jpg")
local params = {}
params.body = multipart:getBody() -- Must call getBody() first!
params.headers = multipart:getHeaders() -- Headers not valid until getBody() is called.
local function networkListener( event )
if ( event.isError ) then
print( "Network error!")
else
print ( "RESPONSE: " .. event.response )
end
end
network.request( "http://www.example.com", "POST", networkListener, params)
]]
-------------------------------------------------
local crypto = require("crypto")
local ltn12 = require("ltn12")
local mime = require("mime")
MultipartFormData = {}
local MultipartFormData_mt = { __index = MultipartFormData }
function MultipartFormData.new() -- The constructor
local newBoundary = "MPFD-"..crypto.digest( crypto.sha1, "MultipartFormData"..tostring(object)..tostring(os.time())..tostring(os.clock()), false )
local object = {
isClass = true,
boundary = newBoundary,
headers = {},
elements = {},
}
object.headers["Content-Type"] = ""
object.headers["Content-Length"] = ""
object.headers["Accept"] = "*/*"
object.headers["Accept-Encoding"] = "gzip"
object.headers["Accept-Language"] = "en-us"
object.headers["connection"] = "keep-alive"
return setmetatable( object, MultipartFormData_mt )
end
function MultipartFormData:getBody()
local src = {}
-- always need two CRLF's as the beginning
--table.insert(src, ltn12.source.chain(ltn12.source.string("\n"), mime.normalize()))
for i = 1, #self.elements do
local el = self.elements[i]
if el then
if el.intent == "field" then
local elData = {
"--"..self.boundary.."\r\n",
"content-disposition: form-data; name=\"",
el.name,
"\"\r\n\r\n",
el.value,
--"\r\n"
}
local elBody = table.concat(elData)
table.insert(src, ltn12.source.chain(ltn12.source.string(elBody), mime.normalize()))
elseif el.intent == "file" then
local elData = {
"--"..self.boundary.."\r\n",
"content-disposition: form-data; name=\"",
el.name,
"\"; filename=\"",
el.filename,
"\"\r\n",
"Content-Type: ",
el.mimetype,
"\r\n\r\n",
}
local elHeader = table.concat(elData)
local elFile = io.open( el.path, "rb" )
assert(elFile)
local fileSource = ltn12.source.cat(
ltn12.source.chain(ltn12.source.string(elHeader), mime.normalize()),
ltn12.source.chain(
ltn12.source.file(elFile),
ltn12.filter.chain(
mime.encode(el.encoding),
mime.wrap()
)
)
)
table.insert(src, fileSource)
end
end
end
-- always need to end the body
table.insert(src, ltn12.source.chain(ltn12.source.string("\r\n--"..self.boundary.."--"), mime.normalize()))
local source = ltn12.source.empty()
for i = 1, #src do
source = ltn12.source.cat(source, src[i])
end
local sink, data = ltn12.sink.table()
ltn12.pump.all(source,sink)
local body = table.concat(data)
-- update the headers we now know how to add based on the multipart data we just generated.
self.headers["Content-Type"] = "multipart/form-data; boundary="..self.boundary
self.headers["Content-Length"] = string.len(body) -- must be total length of body
return body
end
function MultipartFormData:getHeaders()
assert(self.headers["Content-Type"])
assert(self.headers["Content-Length"])
return self.headers
end
function MultipartFormData:addHeader(name, value)
self.headers[name] = value
end
function MultipartFormData:setBoundry(string)
self.boundary = string
end
function MultipartFormData:addField(name, value)
self:add("field", name, value)
end
function MultipartFormData:addFile(name, path, mimeType, remoteFileName)
-- For Corona, we can really only use base64 as a simple binary
-- won't work with their network.request method.
local element = {intent="file", name=name, path=path,
mimetype = mimeType, filename = remoteFileName, encoding = "base64"}
self:addElement(element)
end
function MultipartFormData:add(intent, name, value)
local element = {intent=intent, name=name, value=value}
self:addElement(element)
end
function MultipartFormData:addElement(element)
table.insert(self.elements, element)
end
function MultipartFormData:toString()
return "MultipartFormData [elementCount:"..tostring(#self.elements)..", headerCount:"..tostring(#self.headers).."]"
end
return MultipartFormData | gpl-2.0 |
gedads/Neodynamis | scripts/zones/The_Garden_of_RuHmet/mobs/Ix_aern_drg_s_Wynav.lua | 17 | 1753 | -----------------------------------
-- Area: The Garden of Ru'Hmet
-- MOB: Ix'aern (drg)'s Wynav
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setLocalVar("hpTrigger", math.random(10,75));
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
local hpTrigger = mob:getLocalVar("hpTrigger");
if (mob:getLocalVar("SoulVoice") == 0 and mob:getHPP() <= hpTrigger) then
mob:setLocalVar("SoulVoice", 1);
mob:useMobAbility(696); -- Soul Voice
end
end;
-----------------------------------
-- onMonsterMagicPrepare
-----------------------------------
function onMonsterMagicPrepare(mob,target)
local spellList =
{
[1] = 382,
[2] = 376,
[3] = 372,
[4] = 392,
[5] = 397,
[6] = 400,
[7] = 422,
[8] = 462,
[9] = 466 -- Virelai (charm)
};
if (mob:hasStatusEffect(EFFECT_SOUL_VOICE)) then
return spellList[math.random(1,9)]; -- Virelai possible.
else
return spellList[math.random(1,8)]; -- No Virelai!
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
-----------------------------------
-- OnMobDespawn
-----------------------------------
function onMobDespawn(mob)
mob:setLocalVar("repop", mob:getBattleTime()); -- This get erased on respawn automatic.
end;
| gpl-3.0 |
dantezhu/neon | examples/tpl/src/cocos/extension/DeprecatedExtensionFunc.lua | 61 | 1351 | if nil == cc.Control then
return
end
--tip
local function deprecatedTip(old_name,new_name)
print("\n********** \n"..old_name.." was deprecated please use ".. new_name .. " instead.\n**********")
end
--functions of CCControl will be deprecated end
local CCControlDeprecated = { }
function CCControlDeprecated.addHandleOfControlEvent(self,func,controlEvent)
deprecatedTip("addHandleOfControlEvent","registerControlEventHandler")
print("come in addHandleOfControlEvent")
self:registerControlEventHandler(func,controlEvent)
end
CCControl.addHandleOfControlEvent = CCControlDeprecated.addHandleOfControlEvent
--functions of CCControl will be deprecated end
--Enums of CCTableView will be deprecated begin
CCTableView.kTableViewScroll = cc.SCROLLVIEW_SCRIPT_SCROLL
CCTableView.kTableViewZoom = cc.SCROLLVIEW_SCRIPT_ZOOM
CCTableView.kTableCellTouched = cc.TABLECELL_TOUCHED
CCTableView.kTableCellSizeForIndex = cc.TABLECELL_SIZE_FOR_INDEX
CCTableView.kTableCellSizeAtIndex = cc.TABLECELL_SIZE_AT_INDEX
CCTableView.kNumberOfCellsInTableView = cc.NUMBER_OF_CELLS_IN_TABLEVIEW
--Enums of CCTableView will be deprecated end
--Enums of CCScrollView will be deprecated begin
CCScrollView.kScrollViewScroll = cc.SCROLLVIEW_SCRIPT_SCROLL
CCScrollView.kScrollViewZoom = cc.SCROLLVIEW_SCRIPT_ZOOM
--Enums of CCScrollView will be deprecated end
| mit |
dantezhu/neon | examples/demo1/src/cocos/extension/DeprecatedExtensionFunc.lua | 61 | 1351 | if nil == cc.Control then
return
end
--tip
local function deprecatedTip(old_name,new_name)
print("\n********** \n"..old_name.." was deprecated please use ".. new_name .. " instead.\n**********")
end
--functions of CCControl will be deprecated end
local CCControlDeprecated = { }
function CCControlDeprecated.addHandleOfControlEvent(self,func,controlEvent)
deprecatedTip("addHandleOfControlEvent","registerControlEventHandler")
print("come in addHandleOfControlEvent")
self:registerControlEventHandler(func,controlEvent)
end
CCControl.addHandleOfControlEvent = CCControlDeprecated.addHandleOfControlEvent
--functions of CCControl will be deprecated end
--Enums of CCTableView will be deprecated begin
CCTableView.kTableViewScroll = cc.SCROLLVIEW_SCRIPT_SCROLL
CCTableView.kTableViewZoom = cc.SCROLLVIEW_SCRIPT_ZOOM
CCTableView.kTableCellTouched = cc.TABLECELL_TOUCHED
CCTableView.kTableCellSizeForIndex = cc.TABLECELL_SIZE_FOR_INDEX
CCTableView.kTableCellSizeAtIndex = cc.TABLECELL_SIZE_AT_INDEX
CCTableView.kNumberOfCellsInTableView = cc.NUMBER_OF_CELLS_IN_TABLEVIEW
--Enums of CCTableView will be deprecated end
--Enums of CCScrollView will be deprecated begin
CCScrollView.kScrollViewScroll = cc.SCROLLVIEW_SCRIPT_SCROLL
CCScrollView.kScrollViewZoom = cc.SCROLLVIEW_SCRIPT_ZOOM
--Enums of CCScrollView will be deprecated end
| mit |
gedads/Neodynamis | scripts/commands/goto.lua | 8 | 1425 | ---------------------------------------------------------------------------------------------------
-- func: goto
-- desc: Goes to the target player.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "si"
};
function error(player, msg)
player:PrintToPlayer(msg);
player:PrintToPlayer("!goto <player> {forceZone}");
end;
function onTrigger(player, target, forceZone)
-- validate target
if (target == nil) then
error(player, "You must enter a player name.");
return;
end
local targ = GetPlayerByName( target );
if (targ == nil) then
if not player:gotoPlayer( target ) then
error(player, string.format( "Player named '%s' not found!", target ) );
end
return;
end
-- validate forceZone
if (forceZone ~= nil) then
if (forceZone ~= 0 and forceZone ~= 1) then
error(player, "If provided, forceZone must be 1 (true) or 0 (false).");
return;
end
else
forceZone = 1;
end
-- goto target
if (targ:getZoneID() ~= player:getZoneID() or forceZone == 1) then
player:setPos( targ:getXPos(), targ:getYPos(), targ:getZPos(), targ:getRotPos(), targ:getZoneID() );
else
player:setPos( targ:getXPos(), targ:getYPos(), targ:getZPos(), targ:getRotPos() );
end
end | gpl-3.0 |
nathanaeljones/weaver-nodelua | default_universe/terra/town.lua | 1 | 3277 | center_ = "Go to the Town Center (c)"
function center()
p "You are standing in the center of a busy town. Smells of rotten fruit attack your nostrils."
p ("You have been here " .. inc("user.town.center.visits",1) .. " times.")
choose({
"market",
"world.house.outside",
"world.test.rabbithole.rabbithole",
"world.forest.entrance"
})
end
market_ = "Go to the market (m)"
function market()
p "You are standing in the center of a busy market."
choose({
"center",
"merchant",
"world.house.outside"
})
end
-- Ice Realm arc ---------------------------------------------------
merchant_ = "Inspect the hooded merchant"
function merchant()
p [[
You approach the odd merchant and examine each trinket individually. A
finely-crafted snowglobe catches your eye.
]]
choose({
"inspectsnowglobe",
"leave"
})
end
leave_ = "Leave"
function leave()
message("You politely nod your head as you leave the man\'s booth. His one visible glass eye follows your movement until you disappear back into the crowd.")
switchto("market")
end
inspectsnowglobe_ = "Inspect the snowglobe"
function inspectsnowglobe()
p [[
Curious, you pick up the snowglobe, handling it with care. In a low,
muffled voice, the merchant says, "That there is a magical artifact.
I'm told if you shake it, something...special may happen." As you begin
to rattle the item, the merchant grabs your wrists, stopping you.
"500 coins."
]]
choose({
"paymerchant",
"leave"
})
end
paymerchant_ = "Pay the merchant"
function paymerchant()
p [[
Reaching in your pant's pocket, you take out your money and place it on
the table. The merchant's fingers quickly parse the change, counting
every last coin. As he greedily thumbs through your money, you gaze
into the snowglobe.
Peering closely into it, you can see a tower, a boat, a cave, and an oasis--
quite odd items to be found inside a snowglobe.
]]
choose({
"shakesnowglobe"
})
end
shakesnowglobe_ = "Shake the snowglobe"
function shakesnowglobe()
message("Without hesitation, you shake the snowglobe and begin to feel lightheaded. Suddenly, you fall in a heap on the ground, forced into a dream-state. You awake, with no possessions, in any icy tundra.")
switchto("world.icerealm.chasm.snowdunes")
end
-- ---------------------------------------------------------
home_ = "Go to your home (h)"
function home()
p"You can see your little old wood house standing at the gate, you walk towards the door, turn the key in the lock and step in."
p("You have been here"..inc("user.home.visit",1).."times")
choose({
"bedroom",
"kitchen",
"center"
})
end
function bedroom()
p"You open the door and you realize something feels wrong"
choose({
"center",
["Go back to the hallway"] = "home",
"kitchen",
["check your cash stash under your pillow"]= function()
if (not get_var("user.home.cash", false)) then
p"You don't find your cash anywhere."
else
p"You find your cash, but you look around, and see that you lamp is broken."
end
end
})
end
-- TODO: Add clear(), yesno(),
| apache-2.0 |
starlightknight/darkstar | scripts/zones/Riverne-Site_B01/mobs/Bahamut.lua | 9 | 5477 | -----------------------------------
-- Area: Riverne - Site B01 (BCNM)
-- NM: Bahamut
-----------------------------------
local ID = require("scripts/zones/Riverne-Site_B01/IDs")
require("scripts/globals/quests");
require("scripts/globals/status");
function onMobInitialise(mob)
mob:setMobMod(dsp.mobMod.HP_STANDBACK,-1);
end;
function onMobSpawn(mob)
mob:addStatusEffect(dsp.effect.PHALANX,35,0,180);
mob:addStatusEffect(dsp.effect.STONESKIN,350,0,300);
mob:addStatusEffect(dsp.effect.PROTECT,175,0,1800);
mob:addStatusEffect(dsp.effect.SHELL,24,0,1800);
end;
function onMobFight(mob,target)
local MegaFlareQueue = mob:getLocalVar("MegaFlareQueue");
local MegaFlareTrigger = mob:getLocalVar("MegaFlareTrigger");
local MegaFlareUses = mob:getLocalVar("MegaFlareUses");
local FlareWait = mob:getLocalVar("FlareWait")
local GigaFlare = mob:getLocalVar("GigaFlare");
local tauntShown = mob:getLocalVar("tauntShown");
local mobHPP = mob:getHPP();
local isBusy = false;
local act = mob:getCurrentAction()
if act == dsp.act.MOBABILITY_START or act == dsp.act.MOBABILITY_USING or act == dsp.act.MOBABILITY_FINISH or act == dsp.act.MAGIC_START or act == dsp.act.MAGIC_CASTING or act == dsp.act.MAGIC_START then
isBusy = true; -- is set to true if Bahamut is in any stage of using a mobskill or casting a spell
end;
if (mobHPP < 90 and MegaFlareTrigger < 1) then -- if Megaflare hasn't been set to be used this many times, increase the queue of Megaflares. This will allow it to use multiple Megaflares in a row if the HP is decreased quickly enough.
mob:setLocalVar("MegaFlareTrigger", 1);
mob:setLocalVar("MegaFlareQueue", MegaFlareQueue + 1);
elseif (mobHPP < 80 and MegaFlareTrigger < 2) then
mob:setLocalVar("MegaFlareTrigger", 2);
mob:setLocalVar("MegaFlareQueue", MegaFlareQueue + 1);
elseif (mobHPP < 70 and MegaFlareTrigger < 3) then
mob:setLocalVar("MegaFlareTrigger", 3);
mob:setLocalVar("MegaFlareQueue", MegaFlareQueue + 1);
elseif (mobHPP < 60 and MegaFlareTrigger < 4) then
mob:setLocalVar("MegaFlareTrigger", 4);
mob:setLocalVar("MegaFlareQueue", MegaFlareQueue + 1);
elseif (mobHPP < 50 and MegaFlareTrigger < 5) then
mob:setLocalVar("MegaFlareTrigger", 5);
mob:setLocalVar("MegaFlareQueue", MegaFlareQueue + 1);
elseif (mobHPP < 40 and MegaFlareTrigger < 6) then
mob:setLocalVar("MegaFlareTrigger", 6);
mob:setLocalVar("MegaFlareQueue", MegaFlareQueue + 1);
elseif (mobHPP < 30 and MegaFlareTrigger < 7) then
mob:setLocalVar("MegaFlareTrigger", 7);
mob:setLocalVar("MegaFlareQueue", MegaFlareQueue + 1);
elseif (mobHPP < 20 and MegaFlareTrigger < 8) then
mob:setLocalVar("MegaFlareTrigger", 8);
mob:setLocalVar("MegaFlareQueue", MegaFlareQueue + 1);
end;
if (mob:actionQueueEmpty() == true and isBusy == false) then -- the last check prevents multiple Mega/Gigaflares from being called at the same time.
if (MegaFlareQueue > 0) then
mob:SetMobAbilityEnabled(false); -- disable all other actions until Megaflare is used successfully
mob:SetMagicCastingEnabled(false);
mob:SetAutoAttackEnabled(false);
if (FlareWait == 0 and tauntShown == 0) then -- if there is a queued Megaflare and the last Megaflare has been used successfully or if the first one hasn't been used yet.
target:showText(mob,ID.text.BAHAMUT_TAUNT);
mob:setLocalVar("FlareWait", mob:getBattleTime() + 2); -- second taunt happens two seconds after the first.
mob:setLocalVar("tauntShown", 1);
elseif (FlareWait < mob:getBattleTime() and FlareWait ~= 0 and tauntShown >= 0) then -- the wait time between the first and second taunt as passed. Checks for wait to be not 0 because it's set to 0 on successful use.
if (tauntShown == 1) then
mob:setLocalVar("tauntShown", 2); -- if Megaflare gets stunned it won't show the text again, until successful use.
target:showText(mob,ID.text.BAHAMUT_TAUNT + 1);
end;
if (mob:checkDistance(target) <= 15) then -- without this check if the target is out of range it will keep attemping and failing to use Megaflare. Both Megaflare and Gigaflare have range 15.
if (bit.band(mob:getBehaviour(),dsp.behavior.NO_TURN) > 0) then -- default behaviour
mob:setBehaviour(bit.band(mob:getBehaviour(), bit.bnot(dsp.behavior.NO_TURN)))
end;
mob:useMobAbility(1551);
end;
end;
elseif (MegaFlareQueue == 0 and mobHPP < 10 and GigaFlare < 1 and mob:checkDistance(target) <= 15) then -- All of the scripted Megaflares are to happen before Gigaflare.
if (tauntShown == 0) then
target:showText(mob,ID.text.BAHAMUT_TAUNT + 2);
mob:setLocalVar("tauntShown", 3); -- again, taunt won't show again until the move is successfully used.
end;
if (bit.band(mob:getBehaviour(),dsp.behavior.NO_TURN) > 0) then -- default behaviour
mob:setBehaviour(bit.band(mob:getBehaviour(), bit.bnot(dsp.behavior.NO_TURN)))
end;
mob:useMobAbility(1552);
end;
end;
end;
function onMobDeath(mob, player, isKiller)
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Rolanberry_Fields/Zone.lua | 9 | 4607 | -----------------------------------
--
-- Zone: Rolanberry_Fields (110)
--
-----------------------------------
package.loaded["scripts/zones/Rolanberry_Fields/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Rolanberry_Fields/TextIDs");
require("scripts/globals/icanheararainbow");
require("scripts/globals/zone");
require("scripts/globals/chocobo_digging");
-----------------------------------
-- Chocobo Digging vars
-----------------------------------
local itemMap = {
-- itemid, abundance, requirement
{ 4450, 30, DIGREQ_NONE },
{ 4566, 7, DIGREQ_NONE },
{ 768, 164, DIGREQ_NONE },
{ 748, 15, DIGREQ_NONE },
{ 846, 97, DIGREQ_NONE },
{ 17396, 75, DIGREQ_NONE },
{ 749, 45, DIGREQ_NONE },
{ 739, 3, DIGREQ_NONE },
{ 17296, 216, DIGREQ_NONE },
{ 4448, 15, DIGREQ_NONE },
{ 638, 82, DIGREQ_NONE },
{ 106, 37, DIGREQ_NONE },
{ 4096, 100, DIGREQ_NONE }, -- all crystals
{ 656, 200, DIGREQ_BURROW },
{ 750, 100, DIGREQ_BURROW },
{ 4375, 60, DIGREQ_BORE },
{ 4449, 15, DIGREQ_BORE },
{ 4374, 52, DIGREQ_BORE },
{ 4373, 10, 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)
-- Simurgh
SetRespawnTime(17228242, 900, 10800);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn( player, prevZone)
local cs = -1;
if ( player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos( -381.747, -31.068, -788.092, 211);
end
if ( triggerLightCutscene( player)) then -- Quest: I Can Hear A Rainbow
cs = 0x0002;
elseif (player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1) then
cs = 0x0004;
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;
-----------------------------------
-- onGameHour
-----------------------------------
function onGameHour(zone)
local vanadielHour = VanadielHour();
local silkCaterpillarId = 17227782;
--Silk Caterpillar should spawn every 6 hours from 03:00
--this is approximately when the Jeuno-Bastok airship is flying overhead towards Jeuno.
if (vanadielHour % 6 == 3 and GetMobAction(silkCaterpillarId) == ACTION_NONE) then
-- Despawn set to 210 seconds (3.5 minutes, approx when the Jeuno-Bastok airship is flying back over to Bastok).
SpawnMob(silkCaterpillarId, 210);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate( player, csid, option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if ( csid == 0x0002) then
lightCutsceneUpdate( player); -- Quest: I Can Hear A Rainbow
elseif (csid == 0x0004) then
if (player:getZPos() < 75) then
player:updateEvent(0,0,0,0,0,1);
else
player:updateEvent(0,0,0,0,0,2);
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish( player, csid, option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if ( csid == 0x0002) then
lightCutsceneFinish( player); -- Quest: I Can Hear A Rainbow
end
end;
| gpl-3.0 |
pedro-andrade-inpe/terrame | packages/base/lua/CellularSpace.lua | 1 | 59488 | -------------------------------------------------------------------------------------------
-- TerraME - a software platform for multiple scale spatially-explicit dynamic modeling.
-- Copyright (C) 2001-2017 INPE and TerraLAB/UFOP -- www.terrame.org
-- This code is part of the TerraME framework.
-- This framework is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library.
-- The authors reassure the license terms regarding the warranties.
-- They specifically disclaim any warranties, including, but not limited to,
-- the implied warranties of merchantability and fitness for a particular purpose.
-- The framework provided hereunder is on an "as is" basis, and the authors have no
-- obligation to provide maintenance, support, updates, enhancements, or modifications.
-- In no event shall INPE and TerraLAB / UFOP be held liable to any party for direct,
-- indirect, special, incidental, or consequential damages arising out of the use
-- of this software and its documentation.
--
-------------------------------------------------------------------------------------------
local gis = getPackage("gis")
TeCoord.type_ = "Coord" -- We now use Coord only internally, but it is necessary to set its type.
local function separatorCheck(data)
local header1 = File(tostring(data.file))
local header2 = File(tostring(data.file))
local header3 = File(tostring(data.file))
local lineTest1 = header1:readLine("\t") -- must not have \t
local lineTest2 = header2:readLine(" ") -- must have space
local lineTest3 = header3:readLine(";") -- must not have ;
if lineTest1[2] ~= nil and lineTest2[2] == nil or lineTest3[2] ~= nil then
customError("Could not read file '"..data.file.."': invalid header.")
end
header1:close()
header2:close()
header3:close()
end
local function loadNeighborhoodGAL(self, data)
local file = data.file
local lineTest = file:readLine(" ")
local layer = ""
if self.layer ~= nil then
layer = self.layer
end
if data.check then
local vallayer = ""
if lineTest[3] ~= nil then vallayer = lineTest[3] end
if vallayer ~= self.layer and vallayer ~= self.file then
customError("Neighborhood file '"..data.file.."' was not built for this CellularSpace. CellularSpace layer: '"..layer.."', GAL file layer: '"..vallayer.."'.")
end
end
forEachCell(self, function(cell)
cell:addNeighborhood(Neighborhood{}, data.name)
end)
local line = file:readLine(" ")
local counterLine = 2
while #line > 0 do
local cell = self:get(line[1])
if cell == nil then
customError("Could not find id '"..tostring(line[1]).."' in line "..counterLine..". It seems that it is corrupted.")
else
local neig = cell:getNeighborhood(data.name)
local lineID = file:readLine(" ")
counterLine = counterLine + 1
for i = 1, tonumber(line[2]) do
if lineID[i] == nil then
customError("Could not find id '"..tostring(lineID[i]).."' in line "..counterLine..". It seems that it is corrupted.")
else
local n = self:get(lineID[i])
neig:add(n)
end
end
end
line = file:readLine(" ")
counterLine = counterLine + 1
end
file:close()
end
local function loadNeighborhoodGPM(self, data)
local file = data.file
local lineTest = file:readLine(" ")
local layer = ""
if self.layer ~= nil then
layer = self.layer
end
if data.check then
local vallayer = ""
if lineTest[2] ~= nil then vallayer = lineTest[2] end
if vallayer ~= self.layer and vallayer ~= self.file then
customError("Neighborhood file '"..data.file.."' was not built for this CellularSpace. CellularSpace layer: '"..layer.."', GPM file layer: '"..vallayer.."'.")
end
end
if lineTest[2] ~= nil and lineTest[3] ~= nil then
if lineTest[3] ~= layer and lineTest[2] ~= layer then
customError("This function cannot load neighborhood between two layers. Use 'Environment:loadNeighborhood()' instead.")
end
end
local values = 2
if lineTest[4] == nil or lineTest[4] == "" then
values = 1
end
forEachCell(self, function(cell)
cell:addNeighborhood(Neighborhood{}, data.name)
end)
local line = file:readLine(" ")
local counterLine = 2
while #line > 0 do
local cell = self:get(line[1])
if cell == nil then
customError("Could not find id '"..tostring(line[i]).."' in line "..counterLine..". It seems that it is corrupted.")
end
local neig = cell:getNeighborhood(data.name)
local lineID = file:readLine(" ")
local valfor = (tonumber(line[2]) * 2)
counterLine = counterLine + 1
for i = 1, valfor, values do
if lineID[i] == nil and tonumber(line[2]) * values >= i then
customError("Could not find id '"..tostring(lineID[i]).."' in line "..counterLine..". It seems that it is corrupted.")
elseif lineID[i] ~= nil then
local n = self:get(lineID[i])
if values == 2 and n ~= nilthen then
neig:add(n, tonumber(lineID[i + 1]))
elseif values == 1 and n ~= nil then
neig:add(n, 1)
end
end
end
line = file:readLine(" ")
counterLine = counterLine + 1
end
file:close()
end
local function loadNeighborhoodGWT(self, data)
local file = data.file
local lineTest = file:readLine(" ")
local layer = ""
if self.layer ~= nil then
layer = self.layer
end
if data.check then
local vallayer = ""
if lineTest[3] ~= nil then vallayer = lineTest[3] end
if vallayer ~= self.layer and vallayer ~= self.file then
customError("Neighborhood file '"..data.file.."' was not built for this CellularSpace. CellularSpace layer: '"..layer.."', GWT file layer: '"..vallayer.."'.")
end
end
forEachCell(self, function(cell)
cell:addNeighborhood(Neighborhood{}, data.name)
end)
local line = file:readLine(" ")
local counterLine = 2
while #line > 0 do
local cell = self:get(line[1])
if cell == nil then
customError("Could not find id '"..tostring(line[1]).."' in line "..counterLine..". It seems that it is corrupted.")
elseif line[2] == nil then
customError("Could not find id '"..tostring(line[2]).."' in line "..counterLine..". It seems that it is corrupted.")
elseif line[3] == nil then
customError("Could not find id '"..tostring(line[3]).."' in line "..counterLine..". It seems that it is corrupted.")
else
local neig = cell:getNeighborhood(data.name)
local n = self:get(line[2])
neig:add(n, tonumber(line[3]))
end
line = file:readLine(" ")
counterLine = counterLine + 1
end
file:close()
end
local function getCoordCoupling(_, data)
return function(cell)
local neighborhood = Neighborhood()
local neighCell = data.target:get(cell.x, cell.y)
if neighCell and not neighborhood:isNeighbor(neighCell) then
neighborhood:add(neighCell, 1)
end
return neighborhood
end
end
local function getDiagonalNeighborhood(cs, data)
return function(cell)
local neigh = Neighborhood()
local indexes = {}
local lin = -1
while lin <= 1 do
local col = -1
while col <= 1 do
if (lin ~= 0 and col ~= 0) or (data.self and lin == 0 and col == 0) then
local index
if data.wrap then
index = cs:get(
((cell.x + col) - cs.xMin) % (cs.xMax - cs.xMin + 1) + cs.xMin,
((cell.y + lin) - cs.yMin) % (cs.yMax - cs.yMin + 1) + cs.yMin)
else
index = cs:get(cell.x + col, cell.y + lin)
end
if index ~= nil then
table.insert(indexes, index)
end
end
col = col + 1
end
lin = lin + 1
end
local weight = 1 / #indexes
for _, index in ipairs(indexes) do
if not neigh:isNeighbor(index) then
neigh:add(index, weight)
end
end
return neigh
end
end
local function getFunctionNeighborhood(cs, data)
return function(cell)
local neighborhood = Neighborhood()
forEachCell(cs, function(neighCell)
if data.filter(cell, neighCell) and not neighborhood:isNeighbor(cell) then
neighborhood:add(neighCell, data.weight(cell, neighCell))
end
end)
return neighborhood
end
end
local function getMooreNeighborhood(cs, data)
return function(cell)
local neigh = Neighborhood()
local indexes = {}
local lin = -1
while lin <= 1 do
local col = -1
while col <= 1 do
if data.self or (lin ~= col or col ~= 0) then
local index
if data.wrap then
index = cs:get(
((cell.x + col) - cs.xMin) % (cs.xMax - cs.xMin + 1) + cs.xMin,
((cell.y + lin) - cs.yMin) % (cs.yMax - cs.yMin + 1) + cs.yMin)
else
index = cs:get(cell.x + col, cell.y + lin)
end
if index ~= nil then
table.insert(indexes, index)
end
end
col = col + 1
end
lin = lin + 1
end
local weight = 1 / #indexes
for _, index in ipairs(indexes) do
if not neigh:isNeighbor(index) then
neigh:add(index, weight)
end
end
return neigh
end
end
local function getMxNNeighborhood(_, data)
local m = math.floor(data.m / 2)
local n = math.floor(data.n / 2)
local cs = data.target
return function(cell)
local neighborhood = Neighborhood()
for lin = -n, n do
for col = -m, m do
local neighCell
if data.wrap then
neighCell = cs:get(
((cell.x + col) - cs.xMin) % (cs.xMax - cs.xMin + 1) + cs.xMin,
((cell.y + lin) - cs.yMin) % (cs.yMax - cs.yMin + 1) + cs.yMin)
else
neighCell = cs:get(cell.x + col, cell.y + lin)
end
if neighCell then
if data.filter(cell, neighCell) and not neighborhood:isNeighbor(neighCell) then
neighborhood:add(neighCell, data.weight(cell, neighCell))
end
end
end
end
return neighborhood
end
end
local function getVonNeumannNeighborhood(cs, data)
return function(cell)
local neigh = Neighborhood()
local indexes = {}
local lin = -1
while lin <= 1 do
local col = -1
while col <= 1 do
if ((lin == 0 or col == 0) and lin ~= col) or (data.self and lin == 0 and col == 0) then
local index
if data.wrap then
index = cs:get(
((cell.x + col) - cs.xMin) % (cs.xMax - cs.xMin + 1) + cs.xMin,
((cell.y + lin) - cs.yMin) % (cs.yMax - cs.yMin + 1) + cs.yMin)
else
index = cs:get(cell.x + col, cell.y + lin)
end
if index ~= nil then
table.insert(indexes, index)
end
end
col = col + 1
end
lin = lin + 1
end
local weight = 1 / #indexes
for _, index in ipairs(indexes) do
if not neigh:isNeighbor(index) then
neigh:add(index, weight)
end
end
return neigh
end
end
local function checkCsv(self)
defaultTableValue(self, "sep", ",")
end
local function checkPGM(self)
defaultTableValue(self, "sep", " ")
local _, name = self.file:split()
defaultTableValue(self, "attrname", name)
end
local function checkShape(self)
local path, name = self.file:split()
local dbf = File(path..name..".dbf")
if not dbf:exists() then
customError("File '"..dbf.."' was not found.")
end
end
local function checkVirtual(self)
integerTableArgument(self, "xdim")
positiveTableArgument(self, "xdim")
defaultTableValue(self, "ydim", self.xdim)
integerTableArgument(self, "ydim")
positiveTableArgument(self, "ydim")
end
local function checkProject(self)
defaultTableValue(self, "geometry", true)
if type(self.layer) == "string" then
if type(self.project) ~= "Project" then
if type(self.project) == "string" then
self.project = File(self.project)
end
if type(self.project) == "File" then
if self.project:extension() ~= "tview" then
self.project = File(self.project..".tview")
end
if self.project:exists() then
self.project = gis.Project{
file = self.project
}
else
customError("Project '"..self.project.."' was not found.")
end
else
customError("Argument 'project' must be a Project or file path to a Project.")
end
end
if not self.project.layers[tostring(self.layer)] then
customError("Layer '"..self.layer.."' does not exist in Project '"..self.project.file.."'.")
end
self.layer = gis.Layer{
project = self.project,
name = self.layer
}
else
mandatoryTableArgument(self, "layer", "Layer")
if self.project then
customError("It is not possible to use Project when passing a Layer to CellularSpace.")
end
self.project = self.layer.project
end
end
local function loadCsv(self)
self.yMin = math.huge
self.xMin = math.huge
self.xMax = -math.huge
self.yMax = -math.huge
self.cells = {}
self.cObj_:clear()
local file = self.file
local data = file:read(self.sep)
local columns = data:columns()
for i = 1, #data do
local attributes = {id = tostring(i)}
local row = data[i]
forEachElement(columns, function(idx)
attributes[idx] = row[idx]
end)
local cell = Cell(attributes)
self:add(cell)
self.cObj_:addCell(cell.x, cell.y, cell.cObj_)
end
end
local function loadPGM(self)
local i = 0
local j = 0
self.yMin = math.huge
self.xMin = math.huge
self.xMax = -math.huge
self.yMax = -math.huge
self.cells = {}
self.cObj_:clear()
local file = self.file
local pgm = {}
pgm.comments = {}
pgm.type = file:readLine(self.sep)[1]
verify(pgm.type == "P2", "File '"..self.file.."' does not contain the PGM identifier 'P2' in its first line.")
local res = file:readLine(self.sep)
local len = #res
while len > 0 do
if res[1]:find("#", 1) then
if len > 1 then
table.remove(res, 1)
table.insert(pgm.comments, table.concat(res, " "))
end
elseif len == 2 and not pgm.size then
pgm.size = {tonumber(res[1]), tonumber(res[2])}
elseif len == 1 and not pgm.maximumValue then
pgm.maximumValue = tonumber(res[1])
else
j = 0
forEachElement(res, function(_, value)
local p = Cell {x = j, y = i, [self.attrname] = tonumber(value)}
self:add(p)
self.cObj_:addCell(p.x, p.y, p.cObj_)
j = j + 1
end)
i = i + 1
end
res = file:readLine(self.sep)
len = #res
end
file:close()
if j ~= pgm.size[1] or i ~= pgm.size[2] then
customWarning("Data from file '"..self.file.."' does not match declared size: expected '("..pgm.size[1]..", "..pgm.size[2]..")', got '("..j..", "..i..")'.")
end
if not pgm.maximumValue then
customWarning("File '"..self.file.."' does not have a maximum value declared.")
end
self.xdim = self.xMax
self.ydim = self.yMax
end
local function setCellsByTerraLibDataSet(self, dSet)
self.xMax = 0
self.yMin = 0
self.yMax = 0
self.xMin = 0
if type(self.xy) == "table" then
verify(#self.xy == 2, "Argument 'xy' should have exactly two values.")
verify(type(self.xy[1]) == "string", "Argument 'xy[1]' should be 'string', got '"..type(self.xy[1]).."'.")
verify(type(self.xy[2]) == "string", "Argument 'xy[2]' should be 'string', got '"..type(self.xy[2]).."'.")
defaultTableValue(self, "zero", "top")
elseif self.xy == nil then
self.xy = {"col", "row"}
defaultTableValue(self, "zero", "bottom")
elseif type(self.xy) ~= "function" then
customError("Argument 'xy' should be a 'table' or a 'function', got '"..type(self.xy).."'")
end
self.cells = {}
self.cObj_:clear()
if type(self.xy) == "table" then
local colname = self.xy[1]
local rowname = self.xy[2]
if colname ~= "col" and not dSet[1][colname] then
customError("Cells do not have attribute '"..colname.."'.")
elseif rowname ~= "row" and not dSet[1][rowname] then
customError("Cells do not have attribute '"..rowname.."'.")
end
end
for i = 0, #dSet do
local row = 0
local col = 0
if type(self.xy) == "table" then
col = tonumber(dSet[i][self.xy[1]]) or 0
row = tonumber(dSet[i][self.xy[2]]) or 0
elseif type(self.xy) == "function" then
col, row = self.xy(dSet[i])
end
self.xMin = math.min(self.xMin, col)
self.xMax = math.max(self.xMax, col)
self.yMin = math.min(self.yMin, row)
self.yMax = math.max(self.yMax, row)
end
for i = 0, #dSet do
local row = 0
local col = 0
if type(self.xy) == "table" then
col = tonumber(dSet[i][self.xy[1]]) or 0
row = tonumber(dSet[i][self.xy[2]]) or 0
elseif type(self.xy) == "function" then
col, row = self.xy(dSet[i])
end
if self.zero == "bottom" then
row = self.yMax - row + self.yMin -- bottom inverts row
end
local cell = Cell{id = tostring(i), x = col, y = row}
self.cObj_:addCell(cell.x, cell.y, cell.cObj_)
for k, v in pairs(dSet[i]) do
if (k == "OGR_GEOMETRY") or (k == "geom") or (k == "ogr_geometry") then
if self.geometry then
cell.geom = gis.TerraLib().castGeomToSubtype(v)
end
else
cell[k] = v
end
end
if cell.object_id0 then
cell:setId(cell.object_id0)
elseif cell.object_id_ then
cell:setId(cell.object_id_)
end
table.insert(self.cells, cell)
end
end
local function loadDataSet(self)
local dset
if self.project then
dset = gis.TerraLib().getDataSet{project = self.project,
layer = self.layer.name, missing = self.missing}
else --< file
dset = gis.TerraLib().getDataSet{file = self.file, missing = self.missing}
local file = self.file
self.layer = file:name()
self.cObj_:setLayer(self.layer)
end
setCellsByTerraLibDataSet(self, dset)
end
local function loadVector(self)
defaultTableValue(self, "geometry", true)
loadDataSet(self)
end
local function loadRaster(self)
loadDataSet(self)
end
local rasterFileRef
local function loadTifDirectory(self)
if #self.directory:list() == 0 then
customError("Directory '"..self.directory:name().."' is empty.")
end
local numberOfColumns
local numberOfRows
local resultSet
local tifCount = 0
forEachFile(self.directory, function(file)
if file:extension() == "tif" then
local info = gis.TerraLib().getRasterInfo(file)
if not numberOfColumns then
numberOfColumns = info.columns
numberOfRows = info.rows
rasterFileRef = file
end
if (numberOfColumns ~= info.columns) or (numberOfRows ~= info.rows) then
customError("Tif files '"..rasterFileRef:name().."' and '"..file:name().."' have different sizes: "
..math.floor(numberOfColumns).."x"..math.floor(numberOfRows).." and "
..math.floor(info.columns).."x"..math.floor(info.rows)..".")
end
local dset = gis.TerraLib().getDataSet{file = file, missing = self.missing}
local _, attrName = file:split()
if resultSet then
if info.bands > 1 then
for i = 0, getn(dset) - 1 do
for b = 0, info.bands - 1 do
resultSet[i][attrName.."b"..b] = dset[i]["b"..b] -- SKIP -- TODO: there is no data to test
end
end
else
for i = 0, getn(dset) - 1 do
resultSet[i][attrName] = dset[i].b0
end
end
else --< first time
resultSet = {}
if info.bands > 1 then
for i = 0, getn(dset) - 1 do
for b = 0, info.bands - 1 do
resultSet[i] = {}
resultSet[i].col = dset[i].col -- SKIP -- TODO: there is no data to test
resultSet[i].row = dset[i].row -- SKIP
resultSet[i][attrName.."b"..b] = dset[i]["b"..b] -- SKIP
end
end
else
for i = 0, getn(dset) - 1 do
resultSet[i] = {}
resultSet[i].col = dset[i].col
resultSet[i].row = dset[i].row
resultSet[i][attrName] = dset[i].b0
end
end
end
tifCount = tifCount + 1
end
end)
if not resultSet then
customError("There is no tif file in directory '"..self.directory:name().."/'.")
elseif tifCount == 1 then
customError("There is just one tif file on directory '"..self.directory:name().."/'. Please use argument file or layer instead of directory.")
end
setCellsByTerraLibDataSet(self, resultSet)
end
local function loadLayer(self)
loadDataSet(self)
end
local function loadVirtual(self)
self.yMin = 0
self.xMin = 0
self.xMax = self.xdim - 1
self.yMax = self.ydim - 1
self.cells = {}
self.cObj_:clear()
local cellIdCounter = 1
for row = 1, self.xdim do
for col = 1, self.ydim do
local c = Cell{id = tostring(cellIdCounter), x = row - 1, y = col - 1}
cellIdCounter = cellIdCounter + 1
c.parent = self
self.cObj_:addCell(c.x, c.y, c.cObj_)
table.insert(self.cells, c)
end
end
end
local CellularSpaceDrivers = {}
local function registerCellularSpaceDriver(data)
if type(data.compulsory) == "string" then
data.compulsory = {data.compulsory}
end
defaultTableValue(data, "compulsory", {})
defaultTableValue(data, "extension", true)
mandatoryTableArgument(data, "load", "function")
optionalTableArgument(data, "check", "function")
mandatoryTableArgument(data, "source", "string")
CellularSpaceDrivers[data.source] = data
end
registerCellularSpaceDriver{
source = "shp",
load = loadVector,
check = checkShape,
optional = "xy"
}
registerCellularSpaceDriver{
source = "virtual",
extension = false,
compulsory = "xdim",
optional = "ydim",
load = loadVirtual,
check = checkVirtual
}
registerCellularSpaceDriver{
source = "csv",
optional = "sep",
load = loadCsv,
check = checkCsv
}
registerCellularSpaceDriver{
source = "pgm",
optional = {"sep", "attrname"},
load = loadPGM,
check = checkPGM
}
registerCellularSpaceDriver{
source = "proj",
extension = false,
load = loadLayer,
compulsory = "layer",
optional = "project",
check = checkProject
}
registerCellularSpaceDriver{
source = "geojson",
load = loadVector,
optional = "xy"
}
registerCellularSpaceDriver{
source = "tif",
load = loadRaster
}
registerCellularSpaceDriver{
source = "nc",
load = loadRaster
}
registerCellularSpaceDriver{
source = "asc",
load = loadRaster
}
registerCellularSpaceDriver{
source = "directory",
load = loadTifDirectory,
extension = false,
compulsory = "directory"
}
CellularSpace_ = {
type_ = "CellularSpace",
--- Add a new Cell to the CellularSpace. It will be the last Cell of the CellularSpace when one uses Utils:forEachCell().
-- @arg cell A Cell.
-- @usage cs = CellularSpace{
-- xdim = 10
-- }
--
-- cell = Cell{x = 10, y = 11}
-- cs:add(cell)
add = function(self, cell)
if type(cell) ~= "Cell" then
incompatibleTypeError(1, "Cell", cell)
elseif cell.parent ~= nil then
customError("The cell already has a parent.")
end
verify(not self:get(cell.x, cell.y), "Cell ("..cell.x..", "..cell.y..") already belongs to the CellularSpace.")
cell.parent = self
self.cObj_:addCell(cell.x, cell.y, cell.cObj_)
table.insert(self.cells, cell)
self.yMin = math.min(self.yMin, cell.y)
self.xMin = math.min(self.xMin, cell.x)
self.xMax = math.max(self.xMax, cell.x)
self.yMax = math.max(self.yMax, cell.y)
self.index_id_ = nil
self.index_xy_ = nil
end,
--- Create a Neighborhood for each Cell of the CellularSpace.
-- Most of the available strategies require that each Cell has
-- attributes with (x, y) locations. It is possible to set the attributes
-- that represent (x, y) locations while creating the CellularSpace.
-- @arg data.inmemory If true (default), a Neighborhood will be built and stored for
-- each Cell of the CellularSpace. The Neighborhoods will change only if the
-- modeler add or remove neighbors explicitly. If false, a Neighborhood will be
-- computed every time the simulation calls Cell:getNeighborhood(), for
-- example when using Utils:forEachNeighbor(). In this case, if any of the attributes
-- the Neighborhood is based on changes then the resulting Neighborhood might be different.
-- Neighborhoods not in memory also help the simulation to run with larger datasets,
-- as they are not explicitly represented, but they consume more
-- time as they need to be built again and again along the simulation.
-- @arg data.strategy A string with the strategy to be used for creating the Neighborhood.
-- See the table below.
-- @tabular strategy
-- Strategy & Description & Compulsory Arguments & Optional Arguments \
-- "3x3" & A 3x3 (Couclelis) Neighborhood (Deprecated. Use mxn instead). & & name, filter, weight, inmemory \
-- "coord" & A bidirected relation between two CellularSpaces connecting Cells with the same
-- (x, y) coordinates. & target & name, inmemory\
-- "diagonal" & Connect each Cell to its (at most) four diagonal neighbors.
-- & & name, self, wrap, inmemory \
-- "function" & A Neighborhood based on a function where any other Cell can be a neighbor. &
-- filter & name, weight, inmemory \
-- "moore"(default) & A Moore (queen) Neighborhood, connecting each Cell to its (at most)
-- eight touching Cells. & & name, self, wrap, inmemory \
-- "mxn" & A m (columns) by n (rows) Neighborhood within the CellularSpace or between two
-- CellularSpaces if target is used. & & m, name, n, filter, weight, wrap, target, inmemory \
-- "vonneumann" & A von Neumann (rook) Neighborhood, connecting each Cell to its (at most)
-- four ortogonally surrounding Cells. & & name, self, wrap, inmemory
-- @arg data.filter A function(Cell, Cell)->bool, where the first argument is the Cell itself
-- and the other represent a possible neighbor. It returns true when the neighbor will be
-- included in the relation. In the case of two CellularSpaces, this function is called twice
-- for e ach pair of Cells, first filter(c1, c2) and then filter(c2, c1), where c1 belongs to
-- cs1 and c2 belongs to cs2. The default value is a function that returns true.
-- @arg data.m Number of columns. If m is even then it will be increased by one to keep the
-- Cell in the center of the Neighborhood. The default value is 3.
-- @arg data.n Number of rows. If n is even then it will be increased by one to keep the Cell
-- in the center of the Neighborhood. The default value is m.
-- @arg data.name A string with the name of the Neighborhood to be created.
-- The default value is "1".
-- @arg data.self Add the Cell as neighbor of itself? The default value is false. Note that the
-- functions that do not require this argument always depend on a filter function, which will
-- define whether the Cell can be neighbor of itself.
-- @arg data.target Another CellularSpace whose Cells will be used to create neighborhoods.
-- @arg data.weight A function (Cell, Cell)->number, where the first argument is the Cell
-- itself and the other represent its neighbor. It returns the weight of the relation. This
-- function will be called only if filter returns true.
-- @arg data.wrap Will the Cells in the borders be connected to the Cells in the
-- opposite border? The default value is false.
-- @usage cell = Cell{
-- height = Random{min = 0, max = 100}
-- }
--
-- cs = CellularSpace{
-- xdim = 10,
-- instance = cell
-- }
--
-- cs:createNeighborhood() -- moore
--
-- cs:createNeighborhood{
-- name = "moore"
-- }
--
-- cs:createNeighborhood{
-- strategy = "vonneumann",
-- name = "vonneumann",
-- self = true
-- }
--
-- cs:createNeighborhood{
-- strategy = "mxn",
-- m = 5,
-- name = "5",
-- filter = function(cell, candidate)
-- return cell.height > candidate.height
-- end,
-- weight = function(cell, candidate)
-- return (cell.height - candidate.height) / 100
-- end
-- }
--
--
-- cs2 = CellularSpace{
-- xdim = 10
-- }
--
-- cs:createNeighborhood{
-- strategy = "mxn",
-- target = cs2,
-- m = 5,
-- name = "spatialCoupling"
-- }
createNeighborhood = function(self, data)
if data == nil then
data = {}
else
verifyNamedTable(data)
end
defaultTableValue(data, "name", "1")
if self.cells[1] and #self.cells[1] > 0 then
if self.cells[1]:getNeighborhood(data.name) ~= nil then
customError("Neighborhood '"..data.name.."' already exists.")
end
end
defaultTableValue(data, "strategy", "moore")
defaultTableValue(data, "inmemory", true)
switch(data, "strategy"):caseof{
diagonal = function()
verifyUnnecessaryArguments(data, {"self", "wrap", "name", "strategy", "inmemory"})
defaultTableValue(data, "self", false)
defaultTableValue(data, "wrap", false)
data.func = getDiagonalNeighborhood
end,
["function"] = function()
verifyUnnecessaryArguments(data, {"filter", "weight", "name", "strategy", "inmemory"})
mandatoryTableArgument(data, "filter", "function")
defaultTableValue(data, "weight", function() return 1 end)
data.func = getFunctionNeighborhood
end,
moore = function()
verifyUnnecessaryArguments(data, {"self", "wrap", "name", "strategy", "inmemory"})
defaultTableValue(data, "self", false)
defaultTableValue(data, "wrap", false)
data.func = getMooreNeighborhood
end,
mxn = function()
verifyUnnecessaryArguments(data, {"filter", "weight", "wrap", "name", "strategy", "m", "n", "target", "inmemory"})
defaultTableValue(data, "filter", function() return true end)
defaultTableValue(data, "weight", function() return 1 end)
defaultTableValue(data, "target", self)
defaultTableValue(data, "wrap", false)
defaultTableValue(data, "m", 3)
integerTableArgument(data, "m")
positiveTableArgument(data, "m")
if data.m % 2 == 0 then
customError("Value or argument 'm' should be even, got "..data.m..".")
end
defaultTableValue(data, "n", data.m)
integerTableArgument(data, "n")
positiveTableArgument(data, "n")
if data.n % 2 == 0 then
customError("Value or argument 'n' should be even, got "..data.n..".")
end
data.func = getMxNNeighborhood
end,
vonneumann = function()
verifyUnnecessaryArguments(data, {"name", "strategy", "wrap", "self", "inmemory"})
defaultTableValue(data, "self", false)
defaultTableValue(data, "wrap", false)
data.func = getVonNeumannNeighborhood
end,
coord = function()
verifyUnnecessaryArguments(data, {"name", "strategy", "target", "inmemory"})
mandatoryTableArgument(data, "target", "CellularSpace")
data.func = getCoordCoupling
end
}
local func = data.func(self, data)
if data.inmemory then
forEachCell(self, function(cell)
cell:addNeighborhood(func(cell), data.name)
end)
else
forEachCell(self, function(cell)
cell:addNeighborhood(func, data.name)
end)
end
local mtarget = data.target
if mtarget and mtarget ~= self then
local data2 = {}
forEachElement(data, function(idx, value)
data2[idx] = value
end)
data2.target = self
local mfunc = data.func(mtarget, data2)
if data.inmemory then
forEachCell(mtarget, function(cell)
cell:addNeighborhood(mfunc(cell), data2.name)
end)
else
forEachCell(mtarget, function(cell)
cell:addNeighborhood(mfunc, data2.name)
end)
end
end
end,
--- Cut the CellularSpace according to maximum and minimum coordinates.
-- It returns a Trajectory with the selected Cells.
-- @arg data.xmin A number with the minimum value of x.
-- @arg data.xmax A number with the maximum value of x.
-- @arg data.ymin A number with the minimum value of y.
-- @arg data.ymax A number with the maximum value of y.
-- @usage cs = CellularSpace{xdim = 10}
--
-- cs2 = cs:cut{xmin = 3, ymax = 8}
-- print(#cs2)
cut = function(self, data)
if data == nil then
data = {}
else
verifyNamedTable(data)
end
verifyUnnecessaryArguments(data, {"xmin", "xmax", "ymin", "ymax"})
defaultTableValue(data, "xmin", self.xMin)
defaultTableValue(data, "xmax", self.xMax)
defaultTableValue(data, "ymin", self.yMin)
defaultTableValue(data, "ymax", self.yMax)
local result = Trajectory{target = self, build = false}
forEachCell(self, function(cell)
if cell.x >= data.xmin and cell.x <= data.xmax and
cell.y >= data.ymin and cell.y <= data.ymax then
result:add(cell)
end
end)
return result
end,
--- Return a Cell from the CellularSpace, given its unique identifier or its location. If the Cell
-- does not belong to the CellularSpace then it will return nil.
-- @arg xIndex A number indicating an x coordinate. It can also be a string with the object id.
-- @arg yIndex A number indicating a y coordinate. This argument is unnecessary when the first
-- argument is a string.
-- @usage cs = CellularSpace{xdim = 10}
--
-- cell = cs:get(2, 2)
-- print(cell.x)
-- print(cell.y)
--
-- cell = cs:get("5")
-- print(cell:getId())
get = function(self, xIndex, yIndex)
if type(xIndex) == "string" then
if yIndex ~= nil then
customWarning("As #1 is string, #2 should be nil, but got "..type(yIndex)..".")
end
if not self.index_id_ then
local index_id = {}
forEachCell(self, function(cell)
index_id[cell:getId()] = cell
end)
self.index_id_ = index_id
end
return self.index_id_[xIndex]
end
mandatoryArgument(1, "number", xIndex)
integerArgument(1, xIndex)
mandatoryArgument(2, "number", yIndex)
integerArgument(2, yIndex)
if not self.index_xy_ then
local index_xy = {}
forEachCell(self, function(cell)
if not index_xy[cell.x] then
index_xy[cell.x] = {}
end
index_xy[cell.x][cell.y] = cell
end)
self.index_xy_ = index_xy
end
if self.index_xy_[xIndex] then
return self.index_xy_[xIndex][yIndex]
end
end,
--- Load the CellularSpace from the database. TerraME automatically executes this function when
-- the CellularSpace is created, but one can execute this to load the attributes again, erasing
-- all attributes and relations created by the modeler.
-- @usage cs = CellularSpace{xdim = 10}
-- cs:load()
load = function()
customError("Load function was not implemented.")
end,
--- Load a Neighborhood stored in an external source. Each Cell receives its own set of
-- neighbors.
-- @arg data.file A File or a string with the location of the Neighborhood
-- file to be loaded.
-- @arg data.check A boolean value indicating whether this function should match the
-- layer name of the CellularSpace with the one described in the file. The default value is true.
-- @arg data.name A string with the name of the Neighborhood
-- to be loaded within TerraME. The default value is "1".
-- @tabular name
-- Extension & Description \
-- "gal" & Load a Neighborhood from contiguity relationships described as a GAL file.\
-- "gwt" & Load a Neighborhood from a GWT (generalized weights) file.\
-- "gpm" & Load a Neighborhood from a GPM (generalized proximity matrix) file. \
-- @usage -- DONTRUN
-- cs = CellularSpace{
-- file = filePath("cabecadeboi800.shp", "base")
-- }
--
-- cs:loadNeighborhood{file = filePath("cabecadeboi-neigh.gpm", "base")}
loadNeighborhood = function(self, data)
verifyNamedTable(data)
verifyUnnecessaryArguments(data, {"file", "name", "check"})
if type(data.file) == "string" then
data.file = File(data.file)
end
mandatoryTableArgument(data, "file", "File")
local ext = data.file:extension()
if ext == "" then
customError("Argument 'file' does not have an extension.")
elseif belong(ext, {"gal", "gwt", "gpm"}) then
if not data.file:exists() then
resourceNotFoundError("file", data.file)
end
else
invalidFileExtensionError("file", ext)
end
separatorCheck(data)
defaultTableValue(data, "name", "1")
defaultTableValue(data, "check", true)
if ext == "gal" then
loadNeighborhoodGAL(self, data)
elseif ext == "gwt" then
loadNeighborhoodGWT(self, data)
elseif ext == "gpm" then
loadNeighborhoodGPM(self, data)
end
end,
--- Notify every Observer connected to the CellularSpace.
-- @arg modelTime A number representing the notification time. The default value is zero.
-- It is also possible to use an Event as argument. In this case, it will use the result of
-- Event:getTime().
-- @usage cs = CellularSpace{
-- xdim = 10,
-- value = 5
-- }
--
-- Chart{target = cs}
--
-- cs:notify(1)
-- cs:notify(2)
notify = function(self, modelTime)
if modelTime == nil then
modelTime = 0
elseif type(modelTime) == "Event" then
modelTime = modelTime:getTime()
else
optionalArgument(1, "number", modelTime)
positiveArgument(1, modelTime, true)
end
if self.obsattrs_ then
forEachElement(self.obsattrs_, function(idx)
if type(self[idx]) ~= "function" then
customError("Could not execute function '"..idx.."' from CellularSpace because it was replaced by a '"..type(self[idx]).."'.")
end
self[idx.."_"] = self[idx](self)
end)
end
if self.cellobsattrs_ then
forEachElement(self.cellobsattrs_, function(idx)
forEachCell(self, function(cell)
if type(cell[idx]) ~= "function" then
customError("Could not execute function '"..idx.."' from Cell because it was replaced by a '"..type(cell[idx]).."'.")
end
cell[idx.."_"] = cell[idx](cell)
end)
end)
end
self.cObj_:notify(modelTime)
end,
--- Return a random Cell from the CellularSpace.
-- @usage cs = CellularSpace{
-- xdim = 10
-- }
--
-- cell = cs:sample()
-- print(type(cell))
sample = function(self)
return self.cells[Random():integer(1, #self)]
end,
--- Save the attributes of a CellularSpace into gis::Project or a tif file.
-- @arg newLayerNameOrFile Name of the gis::Layer or a tif file to store the saved attributes.
-- If the original data comes from a shapefile layer, it will create another shapefile using
-- the name of the new layer as file name and will save it in the same directory where the
-- original shapefile is stored. If the data comes from a PostGIS database, it
-- will create another table with name equals to the the layer's name.
-- If the data come from a tif directory, it must be used a file with '.tif' extension.
-- @arg attrNames A vector with the names of the attributes to be saved.
-- If the data come from a layer, these attributes should be only the attributes
-- that were created or modified. The other attributes of the layer will also
-- be saved in the new output.
-- If the data come from a tif directory, it is only possible save one attribute at a time.
-- The attribute value saved will have the same type of the loaded tif files, it means, if
-- the tif is 8 bits the new tif will be 8 bits as well.
-- When saving a single attribute, you can use a string "attribute" instead of a table {"attribute"}.
-- @usage -- DONTRUN
-- import("gis")
--
-- proj = Project{
-- file = "amazonia.tview",
-- clean = true,
-- amazonia = filePath("amazonia.shp")
-- }
--
-- cs = CellularSpace{
-- project = proj,
-- layer = "amazonia"
-- }
--
-- forEachCell(cs, function(cell)
-- cell.distweight = 1 / cell.distroad
-- end)
--
-- cs:save("myamazonia", "distweight")
save = function(self, newLayerNameOrFile, attrNames)
if (attrNames ~= nil) and (attrNames ~= "") then
if type(attrNames) == "string" then
attrNames = {attrNames}
elseif type(attrNames) ~= "table" then
customError("Incompatible types. Argument '#2' expected table or string.")
end
for _, attr in pairs(attrNames) do
if not self.cells[1][attr] then
customError("Attribute '"..attr.."' does not exist in the CellularSpace.")
end
end
end
if self.project then
local newLayerName = newLayerNameOrFile
mandatoryArgument(1, "string", newLayerName)
local dset = gis.TerraLib().getDataSet{project = self.project, layer = self.layer.name, missing = self.missing}
if not self.geometry then
for i = 0, #dset do
for k, v in pairs(dset[i]) do
if (k == "OGR_GEOMETRY") or (k == "geom") or (k == "ogr_geometry") then
self.cells[i + 1][k] = v
end
end
end
elseif dset[0].OGR_GEOMETRY or dset[0].ogr_geometry then
for i = 0, #dset do
for k, v in pairs(dset[i]) do
if (k == "OGR_GEOMETRY") or (k == "ogr_geometry") then
self.cells[i + 1].geom = nil
self.cells[i + 1][k] = v
end
end
end
end
gis.TerraLib().saveDataSet(self.project, self.layer.name, self.cells, newLayerName, attrNames)
elseif self.directory then
local outFile = newLayerNameOrFile
mandatoryArgument(1, "File", outFile)
if getn(attrNames) == 1 then
local attrName
for _, v in pairs(attrNames) do
attrName = v
end
gis.TerraLib().saveRasterFromTable(self.cells, rasterFileRef, outFile, attrName)
else
customError("It is only possible to save one attribute in each call to save() when working with tif files.")
end
else
customError("CellularSpace should be created from a project or directory to allow saving it.")
end
end,
--- Split the CellularSpace into a table of Trajectories according to a classification
-- strategy. The Trajectories will have empty intersection and union equal to the
-- whole CellularSpace (unless function below returns nil for some Cell). It works according
-- to the type of its only and compulsory argument.
-- @arg argument A string or a function, as follows:
-- @tabular argument
-- Type of argument & Description \
-- string & The argument must represent the name of one attribute of the Cells of the
-- CellularSpace. Split then creates one Trajectory for each possible value of the attribute
-- using the value as name and fills them with the Cells that have the respective attribute
-- value. If the CellularSpace has an instance and the respective attribute in the instance
-- is a Random value with discrete or categorical strategy, it will use the possible values
-- to create Trajectories, which means that the returning Trajectories can have size zero in
-- this case. \
-- function & The argument is a function that gets a Cell as argument and returns a
-- name for the Cell, which can be a number, string, or boolean value.
-- Trajectories are then named according to the
-- returning value.
-- @usage cell = Cell{
-- cover = Random{"pasture", "forest"},
-- forest = Random{min = 0, max = 1}
-- }
--
-- cs = CellularSpace{
-- xdim = 20,
-- instance = cell
-- }
--
-- ts = cs:split("cover")
-- print(#ts.forest) -- can be zero because it comes from an instance
-- print(#ts.pasture) -- also
--
-- ts2 = cs:split(function(cell)
-- if cell.forest > 0.5 then
-- return "gt"
-- else
-- return "lt"
-- end
-- end)
--
-- if ts2.gt then -- might not exist as it does not come from an instance
-- print(#ts2.gt)
-- end
split = function(self, argument)
if type(argument) ~= "function" and type(argument) ~= "string" then
if argument == nil then
mandatoryArgumentError(1)
else
incompatibleTypeError(1, "string or function", argument)
end
end
local result = {}
local class
local stringargument
if type(argument) == "string" then
stringargument = argument
if self:sample()[argument] == nil then
customError("Attribute '"..argument.."' does not exist.")
end
if self.instance and type(self.instance[argument]) == "Random" and self.instance[argument].values then
forEachElement(self.instance[argument].values, function(_, value)
result[value] = Trajectory{target = self, build = false}
end)
end
local value = argument
argument = function(cell)
return cell[value]
end
end
forEachCell(self, function(cell)
class = argument(cell)
if class == nil then return end -- the cell will not belong to any Trajectory
if result[class] == nil then
result[class] = Trajectory{target = self, build = false}
end
table.insert(result[class].cells, cell)
result[class].cObj_:add(#result[class], cell.cObj_)
end)
if stringargument then
forEachElement(result, function(idx, traj)
traj.select = function(cell)
return cell[stringargument] == idx
end
end)
end
return result
end,
--- Synchronize the CellularSpace, calling the function synchronize() for each of its Cells.
-- @arg values A string or a vector of strings with the attributes to be synchronized. If
-- empty, TerraME synchronizes every attribute of the Cells but the (x, y) coordinates.
-- If the CellularSpace has an instance and it implements Cell:on_synchronize() then it
-- will be called for each Cell.
-- @usage cell = Cell{
-- forest = Random{min = 0, max = 1}
-- }
--
-- cs = CellularSpace{
-- xdim = 10,
-- instance = cell
-- }
--
-- cs:synchronize()
-- c = cs:sample()
-- print(c.forest)
-- print(c.past.forest)
synchronize = function(self, values)
if values == nil then
values = {}
local cell = self.cells[1]
for k in pairs(cell) do
if not _Gtme.internalCellVariables[k] then
table.insert(values, k)
end
end
end
if type(values) == "string" then
values = {values}
elseif type(values) ~= "table" then
incompatibleTypeError(1, "string, table or nil", values)
end
local s = "return function(cell)\n"
s = s.."cell.past = {"
for _, v in pairs(values) do
if type(v) == "string" then
s = s..v.." = cell."..v..", "
else
customError("Argument 'values' should contain only strings.")
end
end
s = s.."} "
s = s.."if type(cell.on_synchronize) == 'function' then cell:on_synchronize() end "
s = s.."end"
forEachCell(self, load(s)())
end
}
metaTableCellularSpace_ = {
__index = CellularSpace_,
--- Return the number of Cells in the CellularSpace.
-- @usage cs = CellularSpace{xdim = 5}
--
-- print(#cs)
__len = function(self)
return #self.cells
end,
__tostring = _Gtme.tostring
}
--- A multivalued set of Cells. It can be retrieved from databases, files, or created
-- directly within TerraME. Each spatial object read from a data source becomes a Cell,
-- be it a point, a polygon, a line, or a pixel.
-- If the Cells have attributes "row" and "col" (the name can be set by argument xy, as shown below),
-- they can be used to CellularSpace:createNeighborhood()
-- and to draw the CellularSpace in the screen by using a Map.
-- The Cell with lower (row, col) represents the bottom left location (see argument zero below).
-- See the table below with the description and the arguments of each data source.
-- Calling Utils:forEachCell() traverses CellularSpaces.
-- @arg data.sep A string with the file separator. The default value is ",".
-- @arg data.layer A string with the name of the layer stored in a GIS project,
-- or a gis::Layer.
-- @arg data.project A string with the name of the GIS project to be used.
-- If this name does not ends with ".tview", this extension will be added to the name
-- of the file. It can also be a gis::Project.
-- @arg data.missing An optional number that replaces all numeric attributes read from a data source
-- that do not have any value. If this argument is not set and TerraME finds some attribute without
-- a value, the simulation will stop with an error.
-- @arg data.attrname A string with an attribute name. It is useful for files that have
-- only one attribute value for each cell but no attribute name. The default value is
-- the name of the file being read.
-- @arg data.as A table with string indexes and values. It renames the loaded attributes
-- of the CellularSpace from the values to its indexes.
-- @arg data.zero A string value describing where the zero in the y axis starts. The
-- default value is "bottom". When one uses argument xy, the
-- default value is "top", which is the most common representation in different data
-- formats. When zero is "bottom", the y values of each cell is inverted according to
-- the maximum and minimum values: newy = y maximum - y + y minimum. All cellular data
-- created using package gis will have their y values inverted.
-- @arg data.xy An optional table with two strings describing the names of the
-- column and row attributes, in this order. The default value is {"col", "row"},
-- representing the attribute names created by TerraLib for CellularSpaces. A Map
-- can only be created from a CellularSpace if each Cell has a (x, y) location. This
-- argument can also be a function that gets a Cell as argument and returns two values
-- with the (x, y) location.
-- @arg data.... Any other attribute or function for the CellularSpace.
-- @arg data.instance A Cell with the description of attributes and functions.
-- When using this argument, each Cell will have attributes and functions according to the
-- instance. It also calls Cell:init() from the instance for each of its Cells.
-- Every attribute from the Cell that is a Random will be converted into Random:sample().
-- Additional functions are also created to the CellularSpace, according to the attributes of the
-- instance. For each attribute of the instance, one function is created in the CellularSpace with
-- the same name (note that attributes declared exclusively in Cell:init() will not be mapped, as
-- they do not belong to the instance). The table below describes how each attribute is mapped:
-- @tabular instance
-- Type of attribute & Function within the CellularSpace \
-- function & Call the function of each of its Cells. \
-- number & Return the sum of the number in each of its Cells. \
-- boolean & Return the quantity of true values in its Cells. \
-- string & Return a table with positions equal to the unique strings and values equal to the
-- number of occurrences in each of its Cells.
-- @arg data.xdim Number of columns, in the case of creating a CellularSpace without needing to
-- load from a database.
-- @arg data.geometry A boolean value indicating whether the geometry should also be loaded.
-- The default value is true. If true, each cell will have an attribute called geom with a TerraLib object.
-- @arg data.ydim Number of lines, in the case of creating a CellularSpace without needing to
-- load from a database. The default value is equal to xdim.
-- @arg data.file A string with a file name (if it is stored in the current directory), or the complete
-- path to a given file.
-- @arg data.directory A directory. It opens a set of tif files using the file names as attribute names.
-- The directory must contains at least two tif files and they must have the same number of columns and rows.
-- @arg data.source A string with the name of the data source. It tries to infer the data source
-- according to the arguments passed to the function.
-- @tabular source
-- source & Description & Compulsory arguments & Optional arguments\
-- "asc" & Load an asc file. The name of the attribute will be b0. & file & as, ...\
-- "csv" & Load from a Comma-separated value (.csv) file. Each column will become an attribute. It
-- requires at least two attributes: x and y. & file & source, sep, as, geometry, ...\
-- "directory" & Reads a set of tif files within a given directory. The name of the tif files will be
-- the name of the attributes in the Cells. & directory & as, ...\
-- "geojson" & Load a GeoJSON file. & file & as, ...\
-- "nc" & Load a nc file. The name of the attribute will be b0. It only works in Windows. & file & \
-- "pgm" & Load from a text file where Cells are stored as numbers with its attribute value.
-- & & sep, attrname, as, ... \
-- "proj" & Load from a layer within a GIS project. See the documentation of package gis for
-- more information. & project, layer & source, geometry, as, missing, ... \
-- "shp" & Load data from a shapefile. It requires three files with the same name and
-- different extensions: .shp, .shx, and .dbf. The argument file must end with ".shp".
-- As default, each Cell will have its (x, y) location according
-- to the attributes (row, col) from the shapefile. & file & source, as, xy, missing, zero, geometry, ... \
-- "tif" & Load a tif file. The name of the attributes will be b0, b1, etc., according to the number of
-- bands in the file. & file & as, ... \
-- "virtual" & Create a rectangular CellularSpace from scratch. Cells will be instantiated with
-- only two attributes, x and y, starting from (0, 0). & xdim & ydim, as, geometry, ...
-- @output cells A vector of Cells pointed by the CellularSpace.
-- @output cObj_ A pointer to a C++ representation of the CellularSpace. Never use this object.
-- @output parent The Environment it belongs.
-- @output xMax The maximum value of the attribute x of its Cells.
-- @output yMax The maximum value of the attribute y of its Cells.
-- @output xMin The minimum value of the attribute x of its Cells.
-- @output yMin The minimum value of the attribute y of its Cells.
-- @usage cs = CellularSpace{
-- xdim = 20,
-- ydim = 25
-- }
--
-- states = CellularSpace{
-- file = filePath("brazilstates.shp", "base")
-- }
--
-- cabecadeboi = CellularSpace{
-- file = filePath("cabecadeboi.shp")
-- }
function CellularSpace(data)
verifyNamedTable(data)
optionalTableArgument(data, "as", "table")
optionalTableArgument(data, "missing", "number")
if data.as then
forEachElement(data.as, function(idx, value)
if type(idx) ~= "string" then
customError("All indexes of 'as' should be 'string', got '"..type(idx).."'.")
elseif type(value) ~= "string" then
customError("All values of 'as' should be 'string', got '"..type(value).."'.")
end
end)
end
local candidates = {}
if type(data.file) == "string" then
data.file = File(data.file)
end
if data.directory then
mandatoryTableArgument(data, "directory", "Directory")
if not data.source then
data.source = "directory"
else
customWarning("Argument 'source' is unnecessary.")
end
else
forEachOrderedElement(CellularSpaceDrivers, function(idx, value)
local all = true
forEachElement(value.compulsory, function(_, mvalue)
if data[mvalue] == nil then
all = false
end
end)
if value.extension and (not data.file or (type(data.file) == "File" and data.file:extension() ~= idx)) then
all = false
end
if all then
table.insert(candidates, idx)
end
end)
if data.source == nil then
if #candidates == 0 then
customError("Not enough information to infer argument 'source'.")
elseif #candidates == 1 then
data.source = candidates[1]
else
local str = ""
forEachElement(candidates, function(_, value)
str = str.."'"..value.."', "
end)
str = string.sub(str, 1, -3).."."
customError("More than one candidate to argument 'source': "..str)
end
else
if #candidates == 1 then
defaultTableValue(data, "source", candidates[1])
else
mandatoryTableArgument(data, "source", "string")
end
end
end
if CellularSpaceDrivers[data.source] == nil then
local word = "It must be a string from the set ["
forEachOrderedElement(CellularSpaceDrivers, function(a)
word = word.."'"..a.."', "
end)
word = string.sub(word, 0, string.len(word) - 2).."]."
customError("'"..data.source.."' is an invalid value for argument 'source'. "..word)
elseif CellularSpaceDrivers[data.source].extension then
mandatoryTableArgument(data, "file", "File")
if data.file:extension() ~= data.source then
customError("source and file extension should be the same.")
end
if not data.file:exists() then
resourceNotFoundError("file", data.file)
end
end
local cObj = TeCellularSpace()
data.cObj_= cObj
cObj:setDBType(data.source)
if CellularSpaceDrivers[data.source].check then
CellularSpaceDrivers[data.source].check(data)
end
data.load = CellularSpaceDrivers[data.source].load
setmetatable(data, metaTableCellularSpace_)
cObj:setReference(data)
local function createSummaryFunctions(cell)
forEachElement(cell, function(attribute, value, mtype)
if attribute == "id" or attribute == "parent" or string.endswith(attribute, "_") then return
elseif mtype == "function" then
if data[attribute] then
customWarning("Attribute '"..attribute.."' will not be replaced by a summary function.")
return
end
data[attribute] = function(cs, args)
return forEachCell(cs, function(mcell)
if type(mcell[attribute]) ~= "function" then
incompatibleTypeError(attribute, "function", mcell[attribute])
end
return mcell[attribute](mcell, args)
end)
end
elseif mtype == "number" or (mtype == "Random" and value.distrib ~= "categorical" and (value.distrib ~= "discrete" or type(value[1]) == "number")) then
if data[attribute] then
customWarning("Attribute '"..attribute.."' will not be replaced by a summary function.")
return
end
if attribute ~= "x" and attribute ~= "y" then
data[attribute] = function(cs)
local quantity = 0
forEachCell(cs, function(mcell)
if type(mcell[attribute]) ~= "number" then
incompatibleTypeError(attribute, "number", mcell[attribute])
end
quantity = quantity + mcell[attribute]
end)
return quantity
end
end
elseif mtype == "boolean" then
if data[attribute] then
customWarning("Attribute '"..attribute.."' will not be replaced by a summary function.")
return
end
data[attribute] = function(cs)
local quantity = 0
forEachCell(cs, function(mcell)
if mcell[attribute] then
quantity = quantity + 1
end
end)
return quantity
end
elseif mtype == "string" or (mtype == "Random" and (value.distrib == "categorical" or (value.distrib == "discrete" and type(value[1]) == "string"))) then
if data[attribute] then
customWarning("Attribute '"..attribute.."' will not be replaced by a summary function.")
return
end
data[attribute] = function(cs)
local result = {}
forEachCell(cs, function(mcell)
local mvalue = mcell[attribute]
if result[mvalue] then
result[mvalue] = result[mvalue] + 1
else
result[mvalue] = 1
end
end)
return result
end
end
end)
end
data:load()
if data.as then
forEachElement(data.as, function(idx, value)
if data.cells[1][idx] then
customError("Cannot rename '"..value.."' to '"..idx.."' as it already exists.")
elseif not data.cells[1][value] then
customError("Cannot rename attribute '"..value.."' as it does not exist.")
end
end)
local s = "return function(cell)\n"
forEachElement(data.as, function(idx, value)
s = s.."cell."..idx.." = cell."..value.."\n"
s = s.."cell."..value.." = nil\n"
end)
s = s.."end"
forEachCell(data, load(s)())
end
if data.instance ~= nil then
mandatoryTableArgument(data, "instance", "Cell")
if data.instance.isinstance then
customError("The same instance cannot be used in two CellularSpaces.")
end
forEachCell(data, function(cell)
setmetatable(cell, {__index = data.instance})
forEachElement(data.instance, function(attribute, value)
if not string.endswith(attribute, "_") and not belong(attribute, {"x", "id", "y", "past", "neighborhoods"}) then
cell[attribute] = value
end
end)
forEachOrderedElement(data.instance, function(idx, value, mtype)
if mtype == "Random" then
cell[idx] = value:sample()
end
end)
cell:init()
end)
createSummaryFunctions(data.instance)
local newAttTable = {}
forEachElement(data.cells[1], function(idx, value)
if data.instance[idx] == nil then
newAttTable[idx] = value
end
end)
setmetatable(data.instance, nil)
createSummaryFunctions(newAttTable)
forEachElement(Cell_, function(idx, value)
if idx == "init" then
if not data.instance[idx] then
data.instance[idx] = value
end
return
end
if data.instance[idx] then
if type(value) == "function" and idx ~= "on_synchronize" then
strictWarning("Function '"..idx.."()' from Cell is replaced in the instance.")
end
else
data.instance[idx] = value
end
end)
local metaTableInstance = {__index = data.instance, __tostring = _Gtme.tostring}
data.instance.type_ = "Cell"
data.instance.isinstance = true
forEachCell(data, function(cell)
setmetatable(cell, metaTableInstance)
end)
end
return data
end
| lgpl-3.0 |
Amorph/premake-stable | src/actions/make/make_solution.lua | 23 | 2363 | --
-- make_solution.lua
-- Generate a solution-level makefile.
-- Copyright (c) 2002-2009 Jason Perkins and the Premake project
--
function premake.make_solution(sln)
-- create a shortcut to the compiler interface
local cc = premake[_OPTIONS.cc]
-- build a list of supported target platforms that also includes a generic build
local platforms = premake.filterplatforms(sln, cc.platforms, "Native")
-- write a header showing the build options
_p('# %s solution makefile autogenerated by Premake', premake.action.current().shortname)
_p('# Type "make help" for usage help')
_p('')
-- set a default configuration
_p('ifndef config')
_p(' config=%s', _MAKE.esc(premake.getconfigname(sln.configurations[1], platforms[1], true)))
_p('endif')
_p('export config')
_p('')
-- list the projects included in the solution
_p('PROJECTS := %s', table.concat(_MAKE.esc(table.extract(sln.projects, "name")), " "))
_p('')
_p('.PHONY: all clean help $(PROJECTS)')
_p('')
_p('all: $(PROJECTS)')
_p('')
-- write the project build rules
for _, prj in ipairs(sln.projects) do
_p('%s: %s', _MAKE.esc(prj.name), table.concat(_MAKE.esc(table.extract(premake.getdependencies(prj), "name")), " "))
_p('\t@echo "==== Building %s ($(config)) ===="', prj.name)
_p('\t@${MAKE} --no-print-directory -C %s -f %s', _MAKE.esc(path.getrelative(sln.location, prj.location)), _MAKE.esc(_MAKE.getmakefilename(prj, true)))
_p('')
end
-- clean rules
_p('clean:')
for _ ,prj in ipairs(sln.projects) do
_p('\t@${MAKE} --no-print-directory -C %s -f %s clean', _MAKE.esc(path.getrelative(sln.location, prj.location)), _MAKE.esc(_MAKE.getmakefilename(prj, true)))
end
_p('')
-- help rule
_p('help:')
_p(1,'@echo "Usage: make [config=name] [target]"')
_p(1,'@echo ""')
_p(1,'@echo "CONFIGURATIONS:"')
local cfgpairs = { }
for _, platform in ipairs(platforms) do
for _, cfgname in ipairs(sln.configurations) do
_p(1,'@echo " %s"', premake.getconfigname(cfgname, platform, true))
end
end
_p(1,'@echo ""')
_p(1,'@echo "TARGETS:"')
_p(1,'@echo " all (default)"')
_p(1,'@echo " clean"')
for _, prj in ipairs(sln.projects) do
_p(1,'@echo " %s"', prj.name)
end
_p(1,'@echo ""')
_p(1,'@echo "For more information, see http://industriousone.com/premake/quick-start"')
end
| bsd-3-clause |
ironjade/DevStack | LanCom/DesignPattern/LUA/Experiment1.lua | 1 | 1107 | #!/usr/local/bin/lua
--[[
Copyright (c) 2004 by Bruno R. Preiss, P.Eng.
$Author: brpreiss $
$Date: 2004/12/03 02:47:07 $
$RCSfile: Experiment1.lua,v $
$Revision: 1.1 $
$Id: Experiment1.lua,v 1.1 2004/12/03 02:47:07 brpreiss Exp $
--]]
require "Example"
require "Timer"
-- Provides experiment 1.
Experiment1 = Module.new("Experiment1")
-- Program that measures the running times of both
-- a recursive and a non-recursive method to compute
-- the Fibonacci numbers.
-- @param arg Command-line arguments.
function Experiment1.main(arg)
print "Experiment1 test program."
print "3"
print "n"
print "fib1 s"
print "fib2 s"
local timer1 = Timer.new()
local timer2 = Timer.new()
for i = 0, 48 do
timer1:start()
local result = fibonacci1(i)
timer1:stop()
timer2:start()
result = fibonacci2(i)
timer2:stop()
local datum = string.format("%d\t%g\t%g",
i, timer1:elapsedTime(), timer2:elapsedTime())
print(datum)
io.stderr:write(datum .. "\n")
end
return 0
end
if _REQUIREDNAME == nil then
os.exit( Experiment1.main(arg) )
end
| apache-2.0 |
gedads/Neodynamis | scripts/zones/Windurst_Waters/npcs/Orez-Ebrez.lua | 17 | 1820 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Orez-Ebrez
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,OREZEBREZ_SHOP_DIALOG);
stock = {
0x30B2, 20000,1, --Red Cap
0x30AA, 8972,1, --Soil Hachimaki
0x30A7, 7026,1, --Beetle Mask
0x30B8, 144,2, --Circlet
0x30B1, 8024,2, --Cotton Headgear
0x3098, 396,2, --Leather Bandana
0x30B9, 1863,2, --Poet's Circlet
0x30D3, 14400,2, --Flax Headband
0x30A9, 3272,2, --Cotton Hachimaki
0x30A6, 3520,2, --Bone Mask
0x30BA, 10924,2, --Wool Hat
0x30B0, 1742,3, --Headgear
0x30A8, 552,3, --Hachimaki
0x30D2, 1800,3, --Cotton Headband
0x30A0, 151,3, --Bronze Cap
0x30A1, 1471,3 --Brass Cap
}
showNationShop(player, NATION_WINDURST, 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 |
gedads/Neodynamis | scripts/globals/abilities/elemental_siphon.lua | 3 | 2832 | -----------------------------------
-- Ability: Elemental Siphon
-- Drains MP from your summoned spirit.
-- Obtained: Summoner level 50
-- Recast Time: 5:00
-- Duration: Instant
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/pets");
require("scripts/globals/magic")
require("scripts/globals/utils")
require("scripts/globals/msg");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
local pet = player:getPetID();
if (pet >= 0 and pet <= 7) then -- spirits
return 0,0;
else
return msgBasic.UNABLE_TO_USE_JA,0;
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
local spiritEle = player:getPetID() + 1; -- get the spirit's ID, then make it line up with element value for the day order.
-- pet order: fire, ice, air, earth, thunder, water, light, dark
-- day order: fire, earth, water, wind, ice, thunder, light, dark
if (spiritEle == 2) then
spiritEle = 5
elseif (spiritEle == 3) then
spiritEle = 4
elseif (spiritEle == 4) then
spiritEle = 2
elseif (spiritEle == 5) then
spiritEle = 6
elseif (spiritEle == 6) then
spiritEle = 3
end;
local pEquipMods = player:getMod(MOD_ENHANCES_ELEMENTAL_SIPHON);
local basePower = player:getSkillLevel(SKILL_SUM) + pEquipMods - 50;
if (basePower < 0) then -- skill your summoning magic you lazy bastard !
basePower = 0;
end;
local weatherDayBonus = 1;
local dayElement = VanadielDayElement();
local weather = player:getWeather();
-- Day bonus/penalty
if (dayElement == dayStrong[spiritEle]) then
weatherDayBonus = weatherDayBonus + 0.1;
elseif (dayElement == dayWeak[spiritEle]) then
weatherDayBonus = weatherDayBonus - 0.1;
end
-- Weather bonus/penalty
if (weather == singleWeatherStrong[spiritEle]) then
weatherDayBonus = weatherDayBonus + 0.1;
elseif (weather == singleWeatherWeak[spiritEle]) then
weatherDayBonus = weatherDayBonus - 0.1;
elseif (weather == doubleWeatherStrong[spiritEle]) then
weatherDayBonus = weatherDayBonus + 0.25;
elseif (weather == doubleWeatherWeak[spiritEle]) then
weatherDayBonus = weatherDayBonus - 0.25;
end
local power = math.floor(basePower * weatherDayBonus);
local spirit = player:getPet();
power = utils.clamp(power, 0, spirit:getMP()); -- cap MP drained at spirit's MP
power = utils.clamp(power, 0, player:getMaxMP() - player:getMP()); -- cap MP drained at the max MP - current MP
spirit:delMP(power);
return player:addMP(power);
end; | gpl-3.0 |
mishin/Algorithm-Implementations | Egyptian_Fractions/Lua/Yonaba/egyptian_fractions_test.lua | 26 | 1335 | -- Tests for egyptian_fractions.lua
local egypt = require 'egyptian_fractions'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
-- Checks if two given fractions are the same
-- Note, f2 has a simplified representation: f2[1] is num, f2[2] is denum
local function sameFract(f1, f2)
return (f1.num == f2[1] and f1.denum == f2[2])
end
-- Compares two Egyptian fractions
-- Note: see sameFract definition
local function same(t1, t2)
for k, v in ipairs(t1) do
if not sameFract(v, t2[k]) then return false end
end
return true
end
run('Egyptian fractions test', function()
assert(same(egypt(2, 5), {{1,3},{1,15}}))
assert(same(egypt(2, 7), {{1,4},{1,28}}))
assert(same(egypt(2, 9), {{1,5},{1,45}}))
assert(same(egypt(2,11), {{1,6},{1,66}}))
assert(same(egypt(1023,1024), {{1,2},{1,3},{1,7},{1,44},{1,9462},{1,373029888}}))
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
pravsingh/Algorithm-Implementations | Egyptian_Fractions/Lua/Yonaba/egyptian_fractions_test.lua | 26 | 1335 | -- Tests for egyptian_fractions.lua
local egypt = require 'egyptian_fractions'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
-- Checks if two given fractions are the same
-- Note, f2 has a simplified representation: f2[1] is num, f2[2] is denum
local function sameFract(f1, f2)
return (f1.num == f2[1] and f1.denum == f2[2])
end
-- Compares two Egyptian fractions
-- Note: see sameFract definition
local function same(t1, t2)
for k, v in ipairs(t1) do
if not sameFract(v, t2[k]) then return false end
end
return true
end
run('Egyptian fractions test', function()
assert(same(egypt(2, 5), {{1,3},{1,15}}))
assert(same(egypt(2, 7), {{1,4},{1,28}}))
assert(same(egypt(2, 9), {{1,5},{1,45}}))
assert(same(egypt(2,11), {{1,6},{1,66}}))
assert(same(egypt(1023,1024), {{1,2},{1,3},{1,7},{1,44},{1,9462},{1,373029888}}))
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
mishin/Algorithm-Implementations | Monty_Hall_Problem/Lua/Yonaba/monty_hall.lua | 26 | 1033 | -- Monty-Hall problem implementation
-- See : http://en.wikipedia.org/wiki/Monty_Hall_problem
-- Create a range of values as a list
local function range(n)
local t = {}
for i = 1,n do t[i] = i end
return t
end
-- Simulates Monty Hall problem
-- ndoors : number of doors
-- switch : whether or not the player wants to switch his initial choice
-- return : true if the player won, false otherwise
local function simulate(ndoors, switch)
local winning_door = math.random(1,ndoors)
local choice = math.random(1,ndoors)
local doors = range(ndoors)
while #doors>2 do
local door_to_open_index = math.random(1,#doors)
local door_to_open = doors[door_to_open_index]
if (door_to_open ~= winning_door
and door_to_open ~= choice) then
table.remove(doors, door_to_open_index)
end
end
if switch then
choice = (doors[1] == choice and doors[2] or doors[1])
end
return (choice == winning_door)
end
math.randomseed(os.time())
local r = simulate(5,true)
print('won',r)
return simulate
| mit |
hades2013/openwrt-mtk | package/ralink/ui/luci-mtk/src/modules/admin-full/luasrc/model/cbi/admin_network/vlan.lua | 55 | 8246 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2010-2011 Jo-Philipp Wich <xm@subsignal.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
]]--
m = Map("network", translate("Switch"), translate("The network ports on this device can be combined to several <abbr title=\"Virtual Local Area Network\">VLAN</abbr>s in which computers can communicate directly with each other. <abbr title=\"Virtual Local Area Network\">VLAN</abbr>s are often used to separate different network segments. Often there is by default one Uplink port for a connection to the next greater network like the internet and other ports for a local network."))
local fs = require "nixio.fs"
local switches = { }
m.uci:foreach("network", "switch",
function(x)
local sid = x['.name']
local switch_name = x.name or sid
local has_vlan = nil
local has_learn = nil
local has_vlan4k = nil
local has_jumbo3 = nil
local min_vid = 0
local max_vid = 16
local num_vlans = 16
local cpu_port = tonumber(fs.readfile("/proc/switch/eth0/cpuport") or 5)
local num_ports = cpu_port + 1
local switch_title
local enable_vlan4k = false
-- Parse some common switch properties from swconfig help output.
local swc = io.popen("swconfig dev %q help 2>/dev/null" % switch_name)
if swc then
local is_port_attr = false
local is_vlan_attr = false
while true do
local line = swc:read("*l")
if not line then break end
if line:match("^%s+%-%-vlan") then
is_vlan_attr = true
elseif line:match("^%s+%-%-port") then
is_vlan_attr = false
is_port_attr = true
elseif line:match("cpu @") then
switch_title = line:match("^switch%d: %w+%((.-)%)")
num_ports, cpu_port, num_vlans =
line:match("ports: (%d+) %(cpu @ (%d+)%), vlans: (%d+)")
num_ports = tonumber(num_ports) or 6
num_vlans = tonumber(num_vlans) or 16
cpu_port = tonumber(cpu_port) or 5
min_vid = 1
elseif line:match(": pvid") or line:match(": tag") or line:match(": vid") then
if is_vlan_attr then has_vlan4k = line:match(": (%w+)") end
elseif line:match(": enable_vlan4k") then
enable_vlan4k = true
elseif line:match(": enable_vlan") then
has_vlan = "enable_vlan"
elseif line:match(": enable_learning") then
has_learn = "enable_learning"
elseif line:match(": max_length") then
has_jumbo3 = "max_length"
end
end
swc:close()
end
-- Switch properties
s = m:section(NamedSection, x['.name'], "switch",
switch_title and translatef("Switch %q (%s)", switch_name, switch_title)
or translatef("Switch %q", switch_name))
s.addremove = false
if has_vlan then
s:option(Flag, has_vlan, translate("Enable VLAN functionality"))
end
if has_learn then
x = s:option(Flag, has_learn, translate("Enable learning and aging"))
x.default = x.enabled
end
if has_jumbo3 then
x = s:option(Flag, has_jumbo3, translate("Enable Jumbo Frame passthrough"))
x.enabled = "3"
x.rmempty = true
end
-- VLAN table
s = m:section(TypedSection, "switch_vlan",
switch_title and translatef("VLANs on %q (%s)", switch_name, switch_title)
or translatef("VLANs on %q", switch_name))
s.template = "cbi/tblsection"
s.addremove = true
s.anonymous = true
-- Filter by switch
s.filter = function(self, section)
local device = m:get(section, "device")
return (device and device == switch_name)
end
-- Override cfgsections callback to enforce row ordering by vlan id.
s.cfgsections = function(self)
local osections = TypedSection.cfgsections(self)
local sections = { }
local section
for _, section in luci.util.spairs(
osections,
function(a, b)
return (tonumber(m:get(osections[a], has_vlan4k or "vlan")) or 9999)
< (tonumber(m:get(osections[b], has_vlan4k or "vlan")) or 9999)
end
) do
sections[#sections+1] = section
end
return sections
end
-- When creating a new vlan, preset it with the highest found vid + 1.
s.create = function(self, section, origin)
-- Filter by switch
if m:get(origin, "device") ~= switch_name then
return
end
local sid = TypedSection.create(self, section)
local max_nr = 0
local max_id = 0
m.uci:foreach("network", "switch_vlan",
function(s)
if s.device == switch_name then
local nr = tonumber(s.vlan)
local id = has_vlan4k and tonumber(s[has_vlan4k])
if nr ~= nil and nr > max_nr then max_nr = nr end
if id ~= nil and id > max_id then max_id = id end
end
end)
m:set(sid, "device", switch_name)
m:set(sid, "vlan", max_nr + 1)
if has_vlan4k then
m:set(sid, has_vlan4k, max_id + 1)
end
return sid
end
local port_opts = { }
local untagged = { }
-- Parse current tagging state from the "ports" option.
local portvalue = function(self, section)
local pt
for pt in (m:get(section, "ports") or ""):gmatch("%w+") do
local pc, tu = pt:match("^(%d+)([tu]*)")
if pc == self.option then return (#tu > 0) and tu or "u" end
end
return ""
end
-- Validate port tagging. Ensure that a port is only untagged once,
-- bail out if not.
local portvalidate = function(self, value, section)
-- ensure that the ports appears untagged only once
if value == "u" then
if not untagged[self.option] then
untagged[self.option] = true
elseif min_vid > 0 or tonumber(self.option) ~= cpu_port then -- enable multiple untagged cpu ports due to weird broadcom default setup
return nil,
translatef("Port %d is untagged in multiple VLANs!", tonumber(self.option) + 1)
end
end
return value
end
local vid = s:option(Value, has_vlan4k or "vlan", "VLAN ID", "<div id='portstatus-%s'></div>" % switch_name)
local mx_vid = has_vlan4k and 4094 or (num_vlans - 1)
vid.rmempty = false
vid.forcewrite = true
vid.vlan_used = { }
vid.datatype = "and(uinteger,range("..min_vid..","..mx_vid.."))"
-- Validate user provided VLAN ID, make sure its within the bounds
-- allowed by the switch.
vid.validate = function(self, value, section)
local v = tonumber(value)
local m = has_vlan4k and 4094 or (num_vlans - 1)
if v ~= nil and v >= min_vid and v <= m then
if not self.vlan_used[v] then
self.vlan_used[v] = true
return value
else
return nil,
translatef("Invalid VLAN ID given! Only unique IDs are allowed")
end
else
return nil,
translatef("Invalid VLAN ID given! Only IDs between %d and %d are allowed.", min_vid, m)
end
end
-- When writing the "vid" or "vlan" option, serialize the port states
-- as well and write them as "ports" option to uci.
vid.write = function(self, section, value)
local o
local p = { }
for _, o in ipairs(port_opts) do
local v = o:formvalue(section)
if v == "t" then
p[#p+1] = o.option .. v
elseif v == "u" then
p[#p+1] = o.option
end
end
if enable_vlan4k then
m:set(sid, "enable_vlan4k", "1")
end
m:set(section, "ports", table.concat(p, " "))
return Value.write(self, section, value)
end
-- Fallback to "vlan" option if "vid" option is supported but unset.
vid.cfgvalue = function(self, section)
return m:get(section, has_vlan4k or "vlan")
or m:get(section, "vlan")
end
-- Build per-port off/untagged/tagged choice lists.
local pt
for pt = 0, num_ports - 1 do
local title
if pt == cpu_port then
title = translate("CPU")
else
title = translatef("Port %d", pt)
end
local po = s:option(ListValue, tostring(pt), title)
po:value("", translate("off"))
po:value("u", translate("untagged"))
po:value("t", translate("tagged"))
po.cfgvalue = portvalue
po.validate = portvalidate
po.write = function() end
port_opts[#port_opts+1] = po
end
switches[#switches+1] = switch_name
end
)
-- Switch status template
s = m:section(SimpleSection)
s.template = "admin_network/switch_status"
s.switches = switches
return m
| gpl-2.0 |
starlightknight/darkstar | scripts/zones/Nyzul_Isle/instances/path_of_darkness.lua | 9 | 2307 | -----------------------------------
--
-- TOAU-42: Path of Darkness
--
-----------------------------------
local ID = require("scripts/zones/Nyzul_Isle/IDs")
require("scripts/globals/instance")
require("scripts/globals/keyitems");
-----------------------------------
function afterInstanceRegister(player)
local instance = player:getInstance();
player:messageSpecial(ID.text.TIME_TO_COMPLETE, instance:getTimeLimit());
end;
function onInstanceCreated(instance)
SpawnMob(ID.mob[58].AMNAF_BLU, instance);
SpawnMob(ID.mob[58].NAJA, instance);
end;
function onInstanceTimeUpdate(instance, elapsed)
updateInstanceTime(instance, elapsed, ID.text)
end;
function onInstanceFailure(instance)
local chars = instance:getChars();
for i,v in pairs(chars) do
v:messageSpecial(ID.text.MISSION_FAILED,10,10);
v:startEvent(1);
end
end;
function onInstanceProgressUpdate(instance, progress)
if(progress >= 10 and progress < 20) then
DespawnMob(ID.mob[58].AMNAF_BLU, instance);
elseif(progress == 24) then
local v = instance:getEntity(bit.band(ID.mob[58].NAJA, 0xFFF), dsp.objType.MOB)
v:setLocalVar("ready",0);
v:setLocalVar("Stage",2);
SpawnMob(ID.mob[58].AMNAF_BLU, instance);
elseif(progress >= 30 and progress < 40) then
DespawnMob(ID.mob[58].AMNAF_BLU, instance);
elseif(progress == 48) then
SpawnMob(ID.mob[58].AMNAF_PSYCHEFLAYER, instance);
local v = instance:getEntity(bit.band(ID.mob[58].NAJA, 0xFFF), dsp.objType.MOB)
v:setLocalVar("ready",0);
v:setLocalVar("Stage",3);
local npcs = instance:getNpcs();
for i,v in pairs(npcs) do
if(v:getID() == ID.npc._259) then
v:setAnimation(8);
end
end
elseif(progress == 50) then
instance:complete();
end
end;
function onInstanceComplete(instance)
local chars = instance:getChars();
for i,v in pairs(chars) do
if (v:getCurrentMission(TOAU) == dsp.mission.id.toau.PATH_OF_DARKNESS and v:getCharVar("AhtUrganStatus") == 1) then
v:setCharVar("AhtUrganStatus", 2);
end
v:setPos(0,0,0,0,72);
end
end;
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end | gpl-3.0 |
gedads/Neodynamis | scripts/globals/items/plate_of_patlican_salata_+1.lua | 12 | 1365 | -----------------------------------------
-- ID: 5583
-- Item: plate_of_patlican_salata_+1
-- Food Effect: 4Hrs, All Races
-----------------------------------------
-- Agility 5
-- Vitality -2
-- Evasion +7
-- hHP +3
-----------------------------------------
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,14400,5583);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 5);
target:addMod(MOD_VIT, -2);
target:addMod(MOD_EVA, 7);
target:addMod(MOD_HPHEAL, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 5);
target:delMod(MOD_VIT, -2);
target:delMod(MOD_EVA, 7);
target:delMod(MOD_HPHEAL, 3);
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Bastok_Markets_[S]/npcs/Porter_Moogle.lua | 3 | 1538 | -----------------------------------
-- Area: Bastok Markets [S]
-- NPC: Porter Moogle
-- Type: Storage Moogle
-- !zone 87
-- !pos TODO
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Bastok_Markets_[S]/TextIDs");
require("scripts/globals/porter_moogle_util");
local e =
{
TALK_EVENT_ID = 601,
STORE_EVENT_ID = 602,
RETRIEVE_EVENT_ID = 603,
ALREADY_STORED_ID = 604,
MAGIAN_TRIAL_ID = 605
};
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
porterMoogleTrade(player, trade, e);
end
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- No idea what the params are, other than event ID and gil.
player:startEvent(e.TALK_EVENT_ID, 0x6FFFFF, 0x01, 0x06DD, 0x27, 0x7C7E, 0x15, player:getGil(), 0x03E8);
end
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
porterEventUpdate(player, csid, option, e.RETRIEVE_EVENT_ID, RETRIEVE_DIALOG_ID, ITEM_CANNOT_BE_OBTAINED);
end
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
porterEventFinish(player, csid, option, e.TALK_EVENT_ID, ITEM_CANNOT_BE_OBTAINED, ITEM_OBTAINED, NOT_HAVE_ENOUGH_GIL);
end | gpl-3.0 |
gedads/Neodynamis | scripts/globals/mobskills/gigaflare.lua | 37 | 1686 | ---------------------------------------------
-- Gigaflare
-- Family: Bahamut
-- Description: Deals massive Fire damage to enemies within a fan-shaped area.
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes shadows
-- Range:
-- Notes: Used by Bahamut when at 10% of its HP, and can use anytime afterwards at will.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
local mobhp = mob:getHPP();
if (mobhp <= 10) then -- set up Gigaflare for being called by the script again.
mob:setLocalVar("GigaFlare", 0);
mob:SetMobAbilityEnabled(false); -- disable mobskills/spells until Gigaflare is used successfully (don't want to delay it/queue Megaflare)
mob:SetMagicCastingEnabled(false);
end;
return 1;
end;
function onMobWeaponSkill(target, mob, skill)
mob:setLocalVar("GigaFlare", 1); -- When set to 1 the script won't call it.
mob:setLocalVar("tauntShown", 0);
mob:SetMobAbilityEnabled(true); -- enable the spells/other mobskills again
mob:SetMagicCastingEnabled(true);
if (bit.band(mob:getBehaviour(),BEHAVIOUR_NO_TURN) == 0) then -- re-enable noturn
mob:setBehaviour(bit.bor(mob:getBehaviour(), BEHAVIOUR_NO_TURN))
end;
local dmgmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*15,ELE_FIRE,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_FIRE,MOBPARAM_WIPE_SHADOWS);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
CrazyEddieTK/Zero-K | scripts/turrettorp.lua | 16 | 2934 | include "constants.lua"
local base = piece 'base'
local arm1 = piece 'arm1'
local arm2 = piece 'arm2'
local turret = piece 'turret'
local firepoint = piece 'firepoint'
local waterFire = false
local smokePiece = {base}
-- Signal definitions
local SIG_AIM = 2
local function Bob(rot)
while true do
Turn(base, x_axis, math.rad(rot + math.random(-5,5)), math.rad(math.random(1,2)))
Turn(base, z_axis, math.rad(math.random(-5,5)), math.rad(math.random(1,2)))
Move(base, y_axis, 48 + math.rad(math.random(0,2)), math.rad(math.random(1,2)))
Sleep(2000)
Turn(base, x_axis, math.rad(rot + math.random(-5,5)), math.rad(math.random(1,2)))
Turn(base, z_axis, math.rad(math.random(-5,5)), math.rad(math.random(1,2)))
Move(base, y_axis, 48 + math.rad(math.random(-2,0)), math.rad(math.random(1,2)))
Sleep(1000)
end
end
function script.Create()
--while select(5, Spring.GetUnitHealth(unitID)) < 1 do
-- Sleep(400)
--end
local x,_,z = Spring.GetUnitBasePosition(unitID)
local y = Spring.GetGroundHeight(x,z)
if y > 0 then
Turn(arm1, z_axis, math.rad(-70), math.rad(80))
Turn(arm2, z_axis, math.rad(70), math.rad(80))
Move(base, y_axis, 20, 25)
elseif y > -19 then
StartThread(Bob, 0)
else
waterFire = true
StartThread(Bob, 180)
Turn(base, x_axis, math.rad(180))
Move(base, y_axis, 48)
Turn(arm1, x_axis, math.rad(180))
Turn(arm2, x_axis, math.rad(180))
--Turn(turret, x_axis, math.rad(0))
end
StartThread(SmokeUnit, smokePiece)
end
function script.AimWeapon1(heading, pitch)
Signal(SIG_AIM)
SetSignalMask(SIG_AIM)
if waterFire then
Turn(turret, y_axis, -heading + math.pi, math.rad(120))
else
Turn(turret, y_axis, heading, math.rad(120))
end
WaitForTurn(turret, y_axis)
return true
end
function script.FireWeapon(num)
local px, py, pz = Spring.GetUnitPosition(unitID)
if waterFire then
Spring.PlaySoundFile("sounds/weapon/torpedo.wav", 10, px, py, pz)
else
Spring.PlaySoundFile("sounds/weapon/torp_land.wav", 10, px, py, pz)
end
end
function script.AimFromWeapon(num)
return base
end
function script.QueryWeapon(num)
return firepoint
end
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage/maxHealth
if severity <= .25 then
Explode(base, sfxNone)
Explode(firepoint, sfxNone)
Explode(arm1, sfxNone)
Explode(turret, sfxNone)
return 1
elseif severity <= .50 then
Explode(base, sfxNone)
Explode(firepoint, sfxFall)
Explode(arm2, sfxShatter)
Explode(turret, sfxFall)
return 1
elseif severity <= .99 then
Explode(base, sfxNone)
Explode(firepoint, sfxFall + sfxSmoke + sfxFire + sfxExplode)
Explode(arm1, sfxShatter)
Explode(turret, sfxFall + sfxSmoke + sfxFire + sfxExplode)
return 2
else
Explode(base, sfxNone)
Explode(firepoint, sfxFall + sfxSmoke + sfxFire + sfxExplode)
Explode(arm2, sfxShatter + sfxExplode)
Explode(turret, sfxFall + sfxSmoke + sfxFire + sfxExplode)
return 2
end
end
| gpl-2.0 |
CrazyEddieTK/Zero-K | LuaUI/Widgets/gfx_dynamic_metal.lua | 5 | 1812 | function widget:GetInfo()
return {
name = "Lua Metal Decals",
desc = "Draws a decal on each metal spot",
author = "Bluestone (based on the Lua Metal Spots widget by Cheesecan)",
date = "April 2014",
license = "GPL v3 or later",
layer = 5,
enabled = true -- loaded by default?
}
end
local MEX_TEXTURE = "luaui/images/metal_spot.png"
local MEX_WIDTH = 80
local MEX_HEIGHT = 80
local displayList = 0
local mexRotation = {}
function drawPatches()
local mSpots = WG.metalSpots
-- Switch to texture matrix mode
gl.MatrixMode(GL.TEXTURE)
gl.PolygonOffset(-25, -2)
gl.Culling(GL.BACK)
gl.DepthTest(true)
gl.Texture(MEX_TEXTURE)
gl.Color(1, 1, 1, 0.85) -- fix color from other widgets
for i = 1, #mSpots do
mexRotation[i] = mexRotation[i] or math.random(0, 360)
gl.PushMatrix()
gl.Translate(0.5, 0.5, 0)
gl.Rotate(mexRotation[i], 0, 0, 1)
gl.DrawGroundQuad(mSpots[i].x - MEX_WIDTH/2, mSpots[i].z - MEX_HEIGHT/2, mSpots[i].x + MEX_WIDTH/2, mSpots[i].z + MEX_HEIGHT/2, false, -0.5, -0.5, 0.5, 0.5)
gl.PopMatrix()
end
gl.Texture(false)
gl.DepthTest(false)
gl.Culling(false)
gl.PolygonOffset(false)
-- Restore Modelview matrix
gl.MatrixMode(GL.MODELVIEW)
end
function widget:DrawWorldPreUnit()
local mode = Spring.GetMapDrawMode()
if (mode ~= "height" and mode ~= "path") then
gl.CallList(displayList)
end
end
function widget:Initialize()
if not (WG.metalSpots and Spring.GetGameRulesParam("mex_need_drawing")) then
widgetHandler:RemoveWidget(self)
return
end
displayList = gl.CreateList(drawPatches)
end
function widget:GameFrame(n)
if n%15 == 0 then
-- Update display to take terraform into account
displayList = gl.CreateList(drawPatches)
end
end
function widget:Shutdown()
gl.DeleteList(displayList)
end | gpl-2.0 |
alexgrist/NutScript | gamemode/languages/sh_polish.lua | 1 | 21546 | -- Autorzy: zgredinzyyy (Poprawki + Brakujฤ
ce rzeczy) || Veran120, Michaล, Lechu2375 https://github.com/lechu2375/helix-polishlocalization/blob/master/sh_polish.lua
NAME = "Polski"
LANGUAGE = {
helix = "Helix",
introTextOne = "fist industries prezentuje",
introTextTwo = "w wspรณลpracy z %s",
introContinue = "wciลnij spacjฤ by kontynuowaฤ",
helpIdle = "Wybierz kategoriฤ",
helpCommands = "Komendy z parametrami w <strzaลkach> sฤ
wymagane, a w [nawiasach kwadratowych] sฤ
opcjonalne",
helpFlags = "Flagi z zielonym tลem sฤ
dostฤpne przez tฤ
postaฤ.",
creditSpecial = "Podziฤkowania dla",
creditLeadDeveloper = "Gลรณwny Developer",
creditUIDesigner = "UI Designer",
creditManager = "Project Manager",
creditTester = "Lead Tester",
chatTyping = "Pisze...",
chatTalking = "Mรณwi...",
chatYelling = "Krzyczy...",
chatWhispering = "Szepcze...",
chatPerforming = "Wykonuje...",
chatNewTab = "Nowa karta",
chatReset = "Zresetuj pozycjฤ",
chatResetTabs = "Resetuj karty",
chatCustomize = "Personalizuj...",
chatCloseTab = "Zamknij kartฤ",
chatTabName = "Nazwa karty",
chatAllowedClasses = "Dostฤpne Klasy czatรณw",
chatTabExists = "Karta z takฤ
nazwฤ
juลผ instnieje!",
chatMarkRead = "Odznacz wszystko jako przeczytane",
community = "Community",
checkAll = "Zaznacz wszystko",
uncheckAll = "Odznacz wszystko",
color = "Kolor",
type = "Typ",
display = "Wyลwietlanie",
loading = "ลadowanie",
dbError = "Poลฤ
czenie z bazฤ
danych nie powiodลo siฤ",
unknown = "Nieznane",
noDesc = "Opis niedostฤpny",
create = "Stwรณrz",
update = "Zaktualizuj",
load = "Zaลaduj postaฤ",
loadTitle = "Zaลaduj swojฤ
postaฤ",
leave = "Opuลฤ serwer",
leaveTip = "Opuลฤ ten serwer.",
["return"] = "Powrรณt",
returnTip = "Powrรณฤ do poprzedniego menu.",
proceed = "Kontynuuj",
faction = "Frakcja",
skills = "Umiejฤtnoลci",
choose = "Wybierz",
chooseFaction = "Wybierz Frakcje",
chooseDescription = "Zdefiniuj swojฤ
postaฤ",
chooseSkills = "Dostosuj swoje umiejฤtnoลci",
name = "Imiฤ i Nazwisko",
description = "Opis",
model = "Model",
attributes = "Atrybuty",
attribPointsLeft = "Pozostaลe punkty",
charInfo = "Informacje o postaci",
charCreated = "Udaลo ci siฤ stworzyฤ swojฤ
postaฤ.",
charCreateTip = "Wypeลnij pola poniลผej i klinij 'Zakoลcz' aby stworzyฤ swojฤ
postaฤ.",
invalid = "Podaลeล niewลaลciwe(ฤ
) %s",
nameMinLen = "Twoje imiฤ musi zawieraฤ conajmniej %d znakรณw!",
nameMaxLen = "Twoje imiฤ nie moลผe posiadaฤ wiฤcej niลผ %d znakรณw!",
descMinLen = "Twoje imiฤ musi zawieraฤ conajmniej %d znakรณw!",
maxCharacters = "Nie moลผesz utworzyฤ wiฤcej postaci!",
player = "Gracz",
finish = "Zakoลcz",
finishTip = "Ukoลcz tworzenie postaci.",
needModel = "Musisz wybraฤ poprawny model!",
creating = "Twoja postaฤ jest aktualnie tworzona...",
unknownError = "Wystฤ
piล nieznany bลฤ
d!",
areYouSure = "jesteล pewien?",
delete = "Usuล",
deleteConfirm = "Ta postaฤ bฤdzie bezpowrotnie usuniฤta!",
deleteComplete = "%s zostaล(a) usuniฤty(a).",
no = "Nie",
yes = "Tak",
close = "Zamknij",
save = "Zapisz",
itemInfo = "Imiฤ Nazwisko: %s\nOpis: %s",
itemCreated = "Przedmiot(y) pomyลlnie utworzony.",
cloud_no_repo = "Repozytorium, ktรณre zostaลo podane jest nieprawidลowe.",
cloud_no_plugin = "Podany plugin jest nieprawidลowy.",
inv = "Ekwipunek",
plugins = "Pluginy",
pluginLoaded = "%s wลฤ
czyล \"%s\" plugin na nastฤpne zaลadowanie mapy.",
pluginUnloaded = "%s wyลฤ
czyล \"%s\" plugin z nastฤpnego zaลadowania mapy.",
loadedPlugins = "Zaลadowane Pluginy",
unloadedPlugins = "Niezaลadowane Pluginy",
on = "On",
off = "Off",
author = "Autor",
version = "Wersja",
characters = "Postacie",
business = "Biznes",
settings = "Opcje",
config = "Konfiguracja",
chat = "Czat",
appearance = "Wyglฤ
d",
misc = "Rรณลผne",
oocDelay = "Musisz poczekaฤ %s sekund przed ponownym uลผyciem OOC.",
loocDelay = "Musisz poczekaฤ %s sekund przed ponownym uลผyciem LOOC.",
usingChar = "Aktualnie uลผywasz tej postaci.",
notAllowed = "Przepraszamy, nie masz uprawnieล do zrobienia tego.",
itemNoExist = "Przedmiot o ktรณry prosiลeล nie istnieje.",
cmdNoExist = "Taka komenda nie istnieje.",
charNoExist = "Nie znaleziono pasujฤ
cej postaci.",
plyNoExist = "Nie znaleziono pasujฤ
cego gracza.",
cfgSet = "%s ustawiล \"%s\" na %s.",
drop = "Wyrzuฤ",
dropTip = "Upuszcza ten przedmiot z twojego ekwipunku.",
take = "Podnieล",
takeTip = "Weลบ ten przedmiot i umieลฤ go w swoim ekwipunku.",
dTitle = "Drzwi do kupienia",
dTitleOwned = "Wykupione Drzwi",
dIsNotOwnable = "Tych drzwi nie moลผna kupiฤ.",
dIsOwnable = "Moลผesz kupiฤ te drzwi naciskajฤ
c F2.",
dMadeUnownable = "Uczyniลeล te drzwi niemoลผliwymi do kupienia.",
dMadeOwnable = "Uczyniลeล te drzwi moลผliwymi do kupienia.",
dNotAllowedToOwn = "Nie moลผesz kupiฤ tych drzwi.",
dSetDisabled = "Wyลฤ
czyลeล te drzwi z uลผytku.",
dSetNotDisabled = "Ponownie moลผna uลผywaฤ tych drzwi.",
dSetHidden = "Schowaลeล te drzwi.",
dSetNotHidden = "Usunฤ
ลeล te drzwi z ukrytych.",
dSetParentDoor = "Uczyniลeล te drzwi swoimi drzwiami nadrzฤdnymi.",
dCanNotSetAsChild = "Nie moลผesz ustawi aby drzwi nadrzฤdne byลy drzwiami podrzฤdnymi.",
dAddChildDoor = "You have added a this door as a child.",
dRemoveChildren = "Usunฤ
ลeล wszystkie drzwi podrzฤdne naleลผฤ
ce do tych drzwi.",
dRemoveChildDoor = "Te drzwi juลผ nie sฤ
drzwiami podrzฤdnymi.",
dNoParentDoor = "Nie masz ustawionych drzwi nadrzฤdnych.",
dOwnedBy = "Te drzwi naleลผฤ
do %s.",
dConfigName = "Drzwi",
dSetFaction = "Te drzwi naleลผฤ
teraz do frakcji %s.",
dRemoveFaction = "Te drzwi juลผ nie naleลผฤ
do ลผadnej frakcji.",
dNotValid = "Nie patrzysz na prawidลowe drzwi.",
canNotAfford = "Nie staฤ Ciฤ na kupienie tego.",
dPurchased = "Kupiลeล te drzwi za %s.",
dSold = "Sprzedaลeล te drzwi za %s.",
notOwner = "Nie jesteล wลaลcicielem tego.",
invalidArg = "Podaลeล niepoprawnฤ
wartoลฤ dla argumentu #%s.",
invalidFaction = "Frakcja, ktรณrฤ
podaลeล nie zostaลa znaleziona!",
flagGive = "%s daล %s nastฤpujฤ
ce flagi: '%s'.",
flagGiveTitle = "Daj Flagi",
flagTake = "%s zabraล od %s nastฤpujฤ
ce flagi: '%s'.",
flagTakeTitle = "Zabierz Flagi",
flagNoMatch = "Musisz posiadaฤ flagฤ(i) \"%s\" aby wykonaฤ tฤ
czynnoลฤ.",
panelAdded = "Dodaลeล nowy panel.",
panelRemoved = "Usunฤ
ลฤล %d panel(e)",
textAdded = "Dodaลeล tekst.",
textRemoved = "Usunฤ
ลeล %s tekst(y).",
moneyTaken = "Znalazลeล %s.",
moneyGiven = "Otrzymaลeล %s.",
insufficientMoney = "Nie posiadasz tyle ลrodkรณw!",
businessPurchase = "Kupiลeล %s za %s.",
businessSell = "Sprzedaลeล %s za %s.",
businessTooFast = "Zaczekaj przed nastฤpnym kupnem!",
cChangeModel = "%s zmieniล model gracza %s na %s.",
cChangeName = "%s zmieniล imiฤ gracza %s na %s.",
cChangeSkin = "%s zmieniล model %s na %s.",
cChangeGroups = "%s zmieniล bodygroupy %s \"%s\" na %s.",
cChangeFaction = "%s przeniรณsล %s do frakcji %s.",
playerCharBelonging = "Ten przedmiot naleลผy do innej postaci naleลผฤ
cej do Ciebie.",
spawnAdd = "Dodaลeล punkt odradzania dla %s.",
spawnDeleted = "Usunฤ
ลeล %s punkt(y) odradzania siฤ.",
someone = "Ktoล",
rgnLookingAt = "Pozwรณl osobie na ktรณrฤ
patrzysz, aby Ciฤ rozpoznawaลa.",
rgnWhisper = "Pozwรณl tym, ktรณrzy sฤ
w zasiฤgu Twoich szeptรณw, aby Ciฤ rozpoznawali.",
rgnTalk = "Pozwรณl tym, ktรณrzy sฤ
w zasiฤgu normalnych rozmรณw, aby Ciฤ rozpoznawali.",
rgnYell = "Pozwรณl tym, ktรณrzy sฤ
w zasiฤgu Twoich krzykรณw, aby Ciฤ rozpoznawali.",
icFormat = "%s mรณwi: \"%s\"",
rollFormat = "%s wylosowaล %s.",
wFormat = "%s szepcze: \"%s\"",
yFormat = "%s krzyczy: \"%s\"",
sbOptions = "Kliknij aby zobaczyฤ opcje dla %s.",
spawnAdded = "Dodaลeล punkt odradzania dla %s.",
whitelist = "%s dodaล %s na whitelistฤ frakcji %s.",
unwhitelist = "%s usunฤ
ล %s z whitelisty frakcji %s.",
noWhitelist = "Nie masz dostฤpu do whitelisty na tฤ
postaฤ!",
gettingUp = "Podnosisz siฤ...",
wakingUp = "Wraca Ci ลwiadomoลฤ...",
Weapons = "Broล",
checkout = "Idลบ do kasy (%s)",
purchase = "Kup",
purchasing = "Kupujฤ...",
success = "Sukces",
buyFailed = "Zakupy nie powiodลy siฤ.",
buyGood = "Zakupy udane!",
shipment = "Dostawa",
shipmentDesc = "Ta dostawa naleลผy do %s.",
class = "Klasa",
classes = "Klasy",
illegalAccess = "Nielegalny Dostฤp.",
becomeClassFail = "Nie udaลo Ci siฤ zostaฤ %s.",
becomeClass = "Zostaลeล %s.",
setClass = "Ustawiลeล klasฤ %s na %s.",
attributeSet = "Ustawiลeล %s %s na %s.",
attributeNotFound = "You have specified an invalid attribute!",
attributeUpdate = "Podwyลผszyลeล %s %s o %s.",
noFit = "Nieposiadasz wystarczajฤ
co miejsca, aby zmieลciฤ ten przedmiot!",
itemOwned = "Nie moลผesz wchodziฤ w interakcje z przedmiotami, ktรณre posiadasz jako inna postaฤ!",
help = "Pomoc",
commands = "Komendy",
doorSettings = "Ustawienia Drzwi",
sell = "Sprzedaj",
access = "Dostฤp",
locking = "Blokowanie tego przedmiotu...",
unlocking = "Odblokowywanie tego przedmiotu...",
modelNoSeq = "Twรณj model nie obsลuguje tej animacji.",
notNow = "Nie moลผesz tego aktualnie zrobiฤ.",
faceWall = "Musisz patrzeฤ na ลcianฤ aby to wykonaฤ.",
faceWallBack = "Musisz staฤ tyลem do ลciany aby to wykonaฤ.",
descChanged = "Zmieniลeล rysopis swojej postaci.",
noOwner = "Nieprawidลowy wลaลciciel.",
invalidItem = "Wskazaลeล nieprawidลowy przedmiot!",
invalidInventory = "Wskazaลeล nieprawidลowy ekwipunek!",
home = "Strona Gลรณwna",
charKick = "%s wyrzuciล %s.",
charBan = "%s zablokowaล postaฤ %s.",
charBanned = "Ta postaฤ jest zablokowana.",
charBannedTemp = "Ta postaฤ jest tymczasowo zablokowana.",
playerConnected = "%s poลฤ
czyล siฤ z serwerem.",
playerDisconnected = "%s wyszedล z serwera.",
setMoney = "Ustawiลeล iloลฤ pieniฤdzy %s na %s.",
itemPriceInfo = "Moลผesz kupiฤ ten przedmiot za %s.\nMoลผesz sprzedaฤ ten przedmiot za %s",
free = "Darmowe",
vendorNoSellItems = "Nie ma przedmiotรณw do sprzedania.",
vendorNoBuyItems = "Nie ma przedmiotรณw do kupienia.",
vendorSettings = "Ustawienia sprzedawcรณw",
vendorUseMoney = "Czy sprzedawcy powinni uลผywaฤ pieniฤdzy?",
vendorNoBubble = "Ukryฤ dymek sprzedawcy?",
mode = "Tryb",
price = "Cena",
stock = "Zasรณb",
none = "Nic",
vendorBoth = "Kupowanie i Sprzedawanie",
vendorBuy = "Tylko kupowanie",
vendorSell = "Tylko sprzedawanie",
maxStock = "Maksymalny zasรณb",
vendorFaction = "Edytor frakcji",
buy = "Kup",
vendorWelcome = "Witaj w moim sklepie, czy mogฤ Ci coล podaฤ?",
vendorBye = "Przyjdลบ niedลugo z powrotem!",
charSearching = "Aktualnie szukasz juลผ innej postaci, proszฤ poczekaฤ.",
charUnBan = "%s odblokowaล postaฤ %s.",
charNotBanned = "Ta postaฤ nie jest zablokowana.",
quickSettings = "Szybkie Ustawienia",
vmSet = "Ustawiลeล swojฤ
pocztฤ gลosowฤ
.",
vmRem = "Usunฤ
ลฤล swojฤ
pocztฤ gลosowฤ
.",
noPerm = "Nie moลผesz tego zrobiฤ!",
youreDead = "Jesteล martwy",
injMajor = "Widoczne krytyczne obraลผenia.",
injLittle = "Widoczne obraลผenia.",
chgName = "Zmieล Imiฤ i Nazwisko.",
chgNameDesc = "Wprowadลบ nowฤ imiฤ i nazwisko postaci poniลผej.",
weaponSlotFilled = "Nie moลผesz uลผyฤ kolejnej broni typu %s!",
equippedBag = "Nie moลผesz przemieszczaฤ torby z wyekwipowanym przedmiotem!",
equippedWeapon = "Nie moลผesz przemieszczaฤ aktualnie wyekwipowanej broni!",
nestedBags = "Nie moลผesz wrzuciฤ torby do torby!",
outfitAlreadyEquipped = "Juลผ nosisz ubranie tego typu!",
useTip = "Uลผywa przedmiotu.",
equipTip = "Zakลada przedmiot.",
unequipTip = "Zdejmuje przedmiot.",
consumables = "Towary konsumpcyjne.",
plyNotValid = "Nie patrzysz na prawidลowego gracza.",
restricted = "Zostaลeล zwiฤ
zany.",
salary = "Otrzymaลeล wynagrodzenie w wysokoลci %s",
noRecog = "Nie poznajesz tej osoby.",
curTime = "Aktualny czas to %s.",
vendorEditor = "Edytor Sprzedawcy",
edit = "Edytuj",
disable = "Wyลฤ
cz",
vendorPriceReq = "Wprowadลบ nowฤ
cenฤ dla tego produktu.",
vendorEditCurStock = "Edytuj aktualny zapas",
vendorStockReq = "Wprowadลบ ile produktรณw powinno siฤ znajdowaฤ maksymalnie w zasobie",
vendorStockCurReq = "Wprowadลบ ile przedmiotรณw jest dostฤpnych do sprzedarzy z caลego zasobu.",
you = "Ty",
vendorSellScale = "Skala ceny sprzedaลผy",
vendorNoTrade = "Nie moลผesz dokonaฤ wymiany z tym sprzedawcฤ
!",
vendorNoMoney = "Sprzedawce nie staฤ na ten przedmiot!",
vendorNoStock = "Sprzedawca nie ma tego produktu aktualnie w asortymencie!",
contentTitle = "Nie znaleziono zawartoลci dla trybu Helix",
contentWarning = "Zawartoลฤ dla trybu Helix nie zostaล wgrana. Rezultatem tego moลผe byฤ brak czฤลci funkcji.\nCzy chciaลbyล otworzyฤ stronฤ warsztatu z danฤ
zawartoลciฤ
?",
flags = "Flagi",
mapRestarting = "Restart mapy za %d sekund!",
chooseTip = "Wybierz postaฤ do gry.",
deleteTip = "Usuล tฤ
postaฤ.",
storageInUse = "Ktoล inny uลผywa tego teraz!",
storageSearching = "Przeszukiwanie...",
container = "Pojemnik",
containerPassword = "Ustawiลeล hasลo tego pojemnika na %s.",
containerPasswordRemove = "Usunฤ
ลeล hasลo z tego pojemnika.",
containerPasswordWrite = "Wprowadลบ hasลo.",
containerName = "Ustawiลeล nazwฤ tego pojemnika na %s.",
containerNameWrite = "Wprowadลบ nazwฤ.",
containerNameRemove = "Usunฤ
ลeล nazwฤ z tego pojemnika.",
containerInvalid = "Musisz patrzeฤ na pojemnik, aby tego uลผyฤ!",
wrongPassword = "Wprowadziลeล zลe hasลo!",
respawning = "Odradzanie...",
tellAdmin = "Powiadom administracjฤ o tym bลฤdzie: %s",
mapAdd = "Dodaลeล nowฤ
scenerie mapy.",
mapDel = "Usunฤ
ลฤล %d scenerie mapy.",
mapRepeat = "Teraz dodaj punkt drugorzฤdny",
scoreboard = "Tabela",
ping = "Ping: %d",
viewProfile = "Obejrzyj profil Steam.",
copySteamID = "Skopiuj Steam ID",
money = "Pieniฤ
dze",
moneyLeft = "Twoje Pieniฤ
dze: ",
currentMoney = "Obecna iloลฤ pieniฤdzy: ",
invalidClass = "To nie jest odpowiednia klasa!",
invalidClassFaction = "To nie jest poprawna klasa dla tej frakcji!",
miscellaneous = "Rรณลผne",
general = "Generalne",
observer = "Obserwator",
performance = "Wydajnoลc",
thirdperson = "Trzecia osoba",
date = "Data",
interaction = "Interakcja",
server = "Serwer",
resetDefault = "Ustaw domyลlnie",
resetDefaultDescription = "To zresetuje \"%s\" do swojej domyลlej wartoลci \"%s\".",
optOpenBags = "Otwรณrz torbe z ekwipunkiem",
optdOpenBags = "Automatycznie pokazuje wszystkie torby w twoim ekwipunku gdy menu jest otwarte.",
optShowIntro = "Pokaลผ intro przy wchodzeniu na serwer",
optdShowIntro = "Pokazuje wstฤp do Helixa nastฤpnym razem gdy bฤdziesz wchodziฤ. Ta opcja jest zawsze wyลฤ
czona po tym gdy obejrzaลeล wstฤp.",
optCheapBlur = "Wyลฤ
cz rozmazanie",
optdCheapBlur = "Zastฤpuje rozmazanie interfejsu z zwykลym przyciemnieniem.",
optObserverTeleportBack = "Przywraca ciฤ do poprzedniej lokalizacji",
optdObserverTeleportBack = "Przywraca ciฤ do lokalizacji w ktรณrej wลฤ
czyลeล tryb obserwatora.",
optObserverESP = "Pokaลผ ESP administracyjne",
optdObserverESP = "Pokazuje nazwฤ i lokalizacjฤ kaลผdego gracza na serwerze.",
opt24hourTime = "Uลผywaj czasu 24-godzinnego",
optd24hourTime = "Pokazuj znacznik czasu w formacie 24-godzinnym, zamiast 12-godzinnego (AM/PM).",
optChatNotices = "Pokazuj uwagi/ogลoszenia na czacie",
optdChatNotices = "Przenosi wszystkie uwagi/ogลoszenia wyskakujฤ
ce w prawym gรณrnym rogu do czatu.",
optChatTimestamps = "Show timestamps in chat",
optdChatTimestamps = "Pokazuje godzinฤ wysลania przy kaลผdej wiadomoลci na czacie.",
optAlwaysShowBars = "Zawsze pokazuj tabelkฤ z informacjami",
optdAlwaysShowBars = "Tworzy tabelkฤ z informacjami w lewym gรณrnym rogu, bez znaczenia czy ma byฤ ukryte czy nie.",
optAltLower = "Ukryj rฤce gdy sฤ
opuszczone.",
optdAltLower = "Ukrywa rฤce, gdy sฤ
opuszczone.",
optThirdpersonEnabled = "Wลฤ
cz trzeciฤ
osobe",
optdThirdpersonEnabled = "Przenosi kamerฤ za ciebie. Rรณwnieลผ moลผe byฤ wลฤ
czone w konsoli za pomocฤ
\"ix_togglethirdperson\" ",
optThirdpersonClassic = "Wลฤ
cz klasycznฤ
trzeciฤ
osobe",
optdThirdpersonClassic = "Moves your character's view with your mouse.",
optThirdpersonVertical = "Wysokoลฤ kamery",
optdThirdpersonVertical = "Jak wysoko powinna byฤ kamera.",
optThirdpersonHorizontal = "Wyrรณwnanie kamery",
optdThirdpersonHorizontal = "Jak bardzo na lewo lub prawo powinna byฤ kamera.",
optThirdpersonDistance = "Odlegลoลฤ kamery",
optdThirdpersonDistance = "Jak oddalona powinna byฤ kamera.",
optThirdpersonCrouchOffset = "Kamera na wysokoลci kucania",
optdThirdpersonCrouchOffset = "Jak wysoko powinna byฤ kamera podczas kucania.",
optDisableAnimations = "Wyลฤ
cz animacje",
optdDisableAnimations = "Zatrzymuje animacjฤ by zapewniฤ natychmiastowe przejลcie.",
optAnimationScale = "Skala animacji",
optdAnimationScale = "Jak bardziej szybko lub dลugo powinny byฤ animacje.",
optLanguage = "Jฤzyk",
optdLanguage = "Jฤzyk interfejsu.",
optMinimalTooltips = "Minimalne powiadomienia z HUD'u",
optdMinimalTooltips = "Changes the HUD tooltip style to take up less space.",
optNoticeDuration = "Dลugoลฤ powiadomienia",
optdNoticeDuration = "Jak dลugo powinny wyลwietlaฤ siฤ uwagi/ogลoszenia (w sekundach).",
optNoticeMax = "Maksimum powiadomieล",
optdNoticeMax = "Iloลฤ powiadomieล zanim nadmiar zostanie usuniฤty.",
optChatFontScale = "Rozmiar czcionki",
optdChatFontScale = "Skalowanie czcionki na czacie.",
optChatOutline = "Obrysuj tekst w czacie",
optdChatOutline = " Obramowuje tekst czatu. Wลฤ
cz to, jeลli masz problemy z czytaniem czatu.",
cmdRoll = "Losuje liczbฤ pomiฤdzy 0 a wyznaczonฤ
liczbฤ
.",
cmdPM = "Wysyลa prywatnฤ
wiadomoลc do kogoล.",
cmdReply = "Wysyลa prywatnฤ
wiadomoลc do ostatniej osoby, od ktรณrej otrzymaลeล wiadomoลฤ.",
cmdSetVoicemail = "Ustawia lub usuwa automatycznฤ
odpowiedลบ gdy ktoล wysyลa ci prywatnฤ
wiadomoลฤ.",
cmdCharGiveFlag = "Daje wyznaczonฤ
flagฤ(i) do danej osoby.",
cmdCharTakeFlag = "Usuwa wyznaczonฤ
flagฤ(i) osobie jeลli jฤ
ma.",
cmdToggleRaise = "Podnosi albo opuscza broล, ktรณrฤ
trzymasz.",
cmdCharSetModel = "Ustawia model postaci.",
cmdCharSetSkin = "Ustawia skรณrkฤ dla danej postaci.",
cmdCharSetBodygroup = "Ustawia bodygroupy dla danego modelu.",
cmdCharSetAttribute = "Ustawia poziom danego atrybutu dla osoby.",
cmdCharAddAttribute = "Dodaje poziom do danego atrybutu.",
cmdCharSetName = "Zmienia nazwฤ na wyznaczonฤ
nazwฤ.",
cmdCharGiveItem = "Daje wyznaczony przedmiot osobie.",
cmdCharKick = "Zmusza osobฤ do wyjลcia z jej postaci.",
cmdCharBan = "Zabrania osobie wchodzenia na danej postaci.",
cmdCharUnban = "Unban na zbanowanฤ
postaฤ.",
cmdGiveMoney = "Daje wyznaczonฤ
iloลฤ pieniฤdzy osobie, na ktรณrฤ
patrzysz",
cmdCharSetMoney = "Zmienia iloลc pieniฤdzy do wyznaczonej iloลฤi.",
cmdDropMoney = "Wyrzuca wyznaczonฤ
iloลฤ pieniฤdzy przed tobฤ
.",
cmdPlyWhitelist = "Pozwala osobie na stworzenie postaci w wyznaczonej frakcji.",
cmdCharGetUp = "Sprrรณbuj wstaฤ po upadku.",
cmdPlyUnwhitelist = "Usuwa osobie whiteliste z danej frakcji.",
cmdCharFallOver = "Walisz salto na plecy",
cmdBecomeClass = "Zostaล danฤ
klasฤ
w obecnej frakcji.",
cmdCharDesc = "Ustaw opis zewnฤtrzny postaci.",
cmdCharDescTitle = "Opis zewnฤtrzny",
cmdCharDescDescription = "Napisz opis zewnฤtrzny twojej postaci.",
cmdPlyTransfer = "Przenosi osobฤ do wyznaczonej frakcji.",
cmdCharSetClass = "Zmusza osobฤ do zostania wyznaczonฤ
klasฤ
w obecnej frakcji.",
cmdMapRestart = "Restartuje mape po wyznaczonej iloลci czasu.",
cmdPanelAdd = "Dodaje Web Panel.",
cmdPanelRemove = "Usuwa Web Panel na ktรณry patrzysz.",
cmdTextAdd = "Dodaje napis.",
cmdTextRemove = "Usuwa napis na ktรณry patrzysz.",
cmdMapSceneAdd = "Dodaje punkt widokowy widoczny w menu postaci.",
cmdMapSceneRemove = "Usuwa punkt widokowy widoczny w menu postaci.",
cmdSpawnAdd = "Dodaje punkt odrodzenia danej frakcji.",
cmdSpawnRemove = "Usuwa punkt odrodzenia na ktรณry patrzysz.",
cmdAct = "Wykonuje animacjฤ %s .",
cmdContainerSetPassword = "Ustawia hasลo kontenera na ktรณry patrzysz.",
cmdDoorSell = "Sprzedaje drzwi na ktรณre patrzysz.",
cmdDoorBuy = "Kupuje drzwi na ktรณre patrzysz.",
cmdDoorSetUnownable = "Ustawia drzwi na ktรณre patrzysz na niemoลผliwe do posiadania.",
cmdDoorSetOwnable = "Ustawia drzwi na ktรณre patrzysz na moลผliwe do posiadania.",
cmdDoorSetFaction = "Ustawia drzwi na ktรณre patrzysz na posiadane przed danฤ
frakcjฤ.",
cmdDoorSetDisabled = "Zabrania wykonywania komend na drzwi na ktรณre patrzysz.",
cmdDoorSetTitle = "Ustawia opis drzwi na ktรณre patrzysz.",
cmdDoorSetParent = "Ustawia wลaลciciela danych drzwi.",
cmdDoorSetChild = "Ustawia podwลaลcicieli danych drzwi.",
cmdDoorRemoveChild = "Usuwa podwลaลciciela danych drzwi.",
cmdDoorSetHidden = "Ukrywa opis drzwi na ktรณre patrzysz. Wciฤ
ลผ sฤ
moลผliwe do posiadania.",
cmdDoorSetClass = "Ustawia drzwi na ktรณre patrzysz na posiadane przez danฤ
klasฤ.",
cmdMe = "Wykonaj akcjฤ fizycznฤ
.",
cmdIt = "Wykonaj akcjฤ twojego otoczenia.",
cmdW = "Szeptaj.",
cmdY = "Krzycz.",
cmdEvent = "Wykonuje akcjฤ, ktรณrฤ
kaลผdy widzi.",
cmdOOC = "Wysyลa wiadomoลฤ na czacie out-of-character.",
cmdLOOC = "Wysyลa wiadomoลฤ na lokalnym czacie out-of-character."
}
| mit |
czfshine/Don-t-Starve | data/DLC0001/scripts/components/inventorymoisture.lua | 1 | 2410 | local InventoryMoisture = Class(function(self, inst)
self.inst = inst
self.itemList = {}
self.itemIndex = 1
self.inst:StartUpdatingComponent(self)
end)
function InventoryMoisture:GetLastUpdate(item)
if not item then return nil end
if not item.components.moisturelistener then return nil end
return item.components.moisturelistener.lastUpdate
end
function InventoryMoisture:GetDebugString()
local str = ""
str = str..string.format("Total Items: %2.2f, OldestUpdate: %2.2f, itemIndex: %2.2f",
#self.itemList,
self:GetOldestUpdate(),
self.itemIndex)
return str
end
function InventoryMoisture:TrackItem(item)
-- Make sure item can actually get wet
if not (item and item.components.waterproofer) then
table.insert(self.itemList, item)
item.components.moisturelistener:UpdateMoisture(GetTime())
elseif item and item.components.moisturelistener and item.components.waterproofer then
-- Somehow we ended up with an item that has moisturelistener AND waterproofer: remove moisturelistener (waterproof items can't get wet)
item:RemoveComponent("moisturelistener")
end
end
function InventoryMoisture:ForgetItem(item)
local toRemove = nil
for k,v in pairs(self.itemList) do
if v == item then
toRemove = k
end
end
if toRemove then
table.remove(self.itemList, toRemove)
end
self.itemIndex = self.itemIndex - 1
self.itemIndex = math.clamp(self.itemIndex, 1, #self.itemList)
end
function InventoryMoisture:GetOldestUpdate()
local oldestUpdate = math.huge
for k,v in pairs(self.itemList) do
if v.components.moisturelistener and v.components.moisturelistener.lastUpdate < oldestUpdate then
oldestUpdate = v.components.moisturelistener.lastUpdate
end
end
return oldestUpdate
end
function InventoryMoisture:OnUpdate(dt)
if #self.itemList <= 0 then return end
local numToUpdate = #self.itemList * 0.01
numToUpdate = math.ceil(numToUpdate)
numToUpdate = math.clamp(numToUpdate, 1, 50)
local endNum = numToUpdate + self.itemIndex
endNum = (endNum > #self.itemList) and #self.itemList or endNum
for i = self.itemIndex, endNum do
local item = self.itemList[i]
if item and item.components.moisturelistener then
item.components.moisturelistener:UpdateMoisture(GetTime() - item.components.moisturelistener.lastUpdate)
end
end
self.itemIndex = endNum + 1
if self.itemIndex >= #self.itemList then
self.itemIndex = 1
end
end
return InventoryMoisture | gpl-2.0 |
CrazyEddieTK/Zero-K | LuaRules/Gadgets/unit_turn_without_interia.lua | 12 | 1401 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if not gadgetHandler:IsSyncedCode() then
return
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Turn Without Interia",
desc = "Remove turn interia because I don't want to deal with configuring it propperly right now (and such a change would not work for 91.0 anyway).",
author = "Google Frog",
date = "7 Sep 2014",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true
}
end
local spSetGroundMoveTypeData = Spring.MoveCtrl.SetGroundMoveTypeData
local getMovetype = Spring.Utilities.getMovetype
local spMoveCtrlGetTag = Spring.MoveCtrl.GetTag
function gadget:UnitCreated(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions)
local ud = UnitDefs[unitDefID]
if getMovetype(ud) == 2 and spMoveCtrlGetTag(unitID) == nil then -- Ground/Sea
spSetGroundMoveTypeData(unitID, "turnAccel", ud.turnRate*1.2)
end
end
function gadget:Initialize()
for _, unitID in ipairs(Spring.GetAllUnits()) do
local unitDefID = Spring.GetUnitDefID(unitID)
gadget:UnitCreated(unitID, unitDefID)
end
end | gpl-2.0 |
czfshine/Don-t-Starve | data/scripts/events.lua | 1 | 1082 | local EventHandler = Class(function(self, event, fn, processor)
self.event = event
self.fn = fn
self.processor = processor
end)
function EventHandler:Remove()
self.processor:RemoveHandler(self)
end
------------------------
EventProcessor = Class(function(self)
self.events = {}
end)
function EventProcessor:AddEventHandler(event, fn)
local handler = EventHandler(event, fn, self)
if self.events[event] == nil then
self.events[event] = {}
end
self.events[event][handler] = true
return handler
end
function EventProcessor:RemoveHandler(handler)
if handler then
local ev = self.events[handler.event]
if ev then
ev[handler] = nil
end
end
end
function EventProcessor:GetHandlersForEvent(event)
return self.events[event] or {}
end
function EventProcessor:HandleEvent(event, ...)
local handlers = self.events[event]
if handlers then
for k,v in pairs(handlers) do
k.fn(...)
end
end
end
--------------------------------------------- | gpl-2.0 |
czfshine/Don-t-Starve | data/scripts/prefabs/maxwellhead.lua | 1 | 2843 | local assets =
{
Asset("ANIM", "anim/maxwell_floatinghead.zip"),
Asset("SOUND", "sound/maxwell.fsb"),
}
local SPEECH =
{
NULL_SPEECH=
{
--appearanim = "appear",
idleanim= "idle_loop",
--dialogpreanim = "dialog_pre",
dialoganim="dialog_loop",
--dialogpostanim = "dialog_pst",
disappearanim = "disappear",
{
string = "You forgot to set a speech.",
wait = 2
},
{
string = "Go do it.",
wait = 1
},
},
SPEECH_1 =
{
--appearanim = "appear",
idleanim= "idle_loop",
--dialogpreanim = "dialog_pre",
dialoganim="dialog_loop",
--dialogpostanim = "dialog_pst",
disappearanim = "disappear",
{
string = STRINGS.MAXWELL_ADVENTURE_HEAD.LEVEL_6.ONE,
wait = 3
},
},
SPEECH_2 =
{
--appearanim = "appear",
idleanim= "idle_loop",
--dialogpreanim = "dialog_pre",
dialoganim="dialog_loop",
--dialogpostanim = "dialog_pst",
disappearanim = "disappear",
{
string = STRINGS.MAXWELL_ADVENTURE_HEAD.LEVEL_6.TWO.ONE,
wait = 3
},
{
string = STRINGS.MAXWELL_ADVENTURE_HEAD.LEVEL_6.TWO.TWO,
wait = 3
},
},
SPEECH_3 =
{
--appearanim = "appear",
idleanim= "idle_loop",
--dialogpreanim = "dialog_pre",
dialoganim="dialog_loop",
--dialogpostanim = "dialog_pst",
disappearanim = "disappear",
{
string = STRINGS.MAXWELL_ADVENTURE_HEAD.LEVEL_6.THREE.ONE,
wait = 3
},
{
string = STRINGS.MAXWELL_ADVENTURE_HEAD.LEVEL_6.THREE.TWO,
wait = 1
},
},
SPEECH_4 =
{
--appearanim = "appear",
idleanim= "idle_loop",
--dialogpreanim = "dialog_pre",
dialoganim="dialog_loop",
--dialogpostanim = "dialog_pst",
disappearanim = "disappear",
{
string = STRINGS.MAXWELL_ADVENTURE_HEAD.LEVEL_6.FOUR.ONE,
wait = 3
},
{
string = STRINGS.MAXWELL_ADVENTURE_HEAD.LEVEL_6.FOUR.TWO,
wait = 4
},
},
}
local function fn()
local inst = CreateEntity()
local trans = inst.entity:AddTransform()
local anim = inst.entity:AddAnimState()
local sound = inst.entity:AddSoundEmitter()
local shadow = inst.entity:AddDynamicShadow()
shadow:SetSize( 1.75, .75 )
inst.Transform:SetTwoFaced()
anim:SetBank("maxwell_floatinghead")
anim:SetBuild("maxwell_floatinghead")
--anim:PlayAnimation("appear")
anim:PlayAnimation("idle_loop", true)
--inst:DoTaskInTime(0.3, function() sound:PlaySound("dontstarve/maxwell/disappear") end)
inst.entity:AddLabel()
inst.Label:SetFontSize(28)
inst.Label:SetFont(TALKINGFONT)
inst.Label:SetPos(0,5,0)
inst.Label:Enable(false)
inst:AddComponent("talker")
inst:AddComponent("inspectable")
print(inst.speech)
inst:AddComponent("maxwelltalker")
inst.components.maxwelltalker.speeches = SPEECH
inst.task = inst:StartThread(function() inst.components.maxwelltalker:DoTalk() end)
return inst
end
return Prefab("common/characters/maxwellhead", fn, assets)
| gpl-2.0 |
EMCTEAM-IRAN/superflux-bot | plugins/boobs.lua | 1 | 1601 | do
-- Recursive function
local function getRandomButts(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.obutts.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt <= 3 then
print('Cannot get that butts, trying another one...')
return getRandomButts(attempt)
end
return 'http://media.obutts.ru/' .. data.preview
end
local function getRandomBoobs(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.oboobs.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt < 10 then
print('Cannot get that boobs, trying another one...')
return getRandomBoobs(attempt)
end
return 'http://media.oboobs.ru/' .. data.preview
end
local function run(msg, matches)
local url = nil
if matches[1] == "/boobs" then
url = getRandomBoobs()
end
if matches[1] == "/butts" then
url = getRandomButts()
end
if url ~= nil then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, url)
else
return 'Error getting boobs/butts for you, please try again later.'
end
end
return {
description = "Gets a random boobs or butts pic",
usage = {
"/boobs: Get a boobs NSFW image. ๐",
"/butts: Get a butts NSFW image. ๐"
},
patterns = {
"^/boobs$",
"^/butts$"
},
run = run
}
end
| gpl-3.0 |
rzh/mongocraft | world/Plugins/APIDump/Hooks/OnKilling.lua | 36 | 1190 | return
{
HOOK_KILLING =
{
CalledWhen = "A player or a mob is dying.",
DefaultFnName = "OnKilling", -- also used as pagename
Desc = [[
This hook is called whenever a {{cPawn|pawn}}'s (a player's or a mob's) health reaches zero. This
means that the pawn is about to be killed, unless a plugin "revives" them by setting their health
back to a positive value.
]],
Params =
{
{ Name = "Victim", Type = "{{cPawn}}", Notes = "The player or mob that is about to be killed" },
{ Name = "Killer", Type = "{{cEntity}}", Notes = "The entity that has caused the victim to lose the last point of health. May be nil for environment damage" },
{ Name = "TDI", Type = "{{TakeDamageInfo}}", Notes = "The damage type, cause and effects." },
},
Returns = [[
If the function returns false or no value, Cuberite calls other plugins with this event. If the
function returns true, no other plugin is called for this event.</p>
<p>
In either case, the victim's health is then re-checked and if it is greater than zero, the victim is
"revived" with that health amount. If the health is less or equal to zero, the victim is killed.
]],
}, -- HOOK_KILLING
}
| apache-2.0 |
CrazyEddieTK/Zero-K | units/shieldriot.lua | 4 | 5987 | unitDef = {
unitname = [[shieldriot]],
name = [[Outlaw]],
description = [[Riot Bot]],
acceleration = 0.25,
activateWhenBuilt = true,
brakeRate = 0.75,
buildCostMetal = 250,
buildPic = [[shieldriot.png]],
canGuard = true,
canMove = true,
canPatrol = true,
category = [[LAND]],
corpse = [[DEAD]],
selectionVolumeOffsets = [[0 0 0]],
selectionVolumeScales = [[45 45 45]],
selectionVolumeType = [[ellipsoid]],
customParams = {
},
explodeAs = [[BIG_UNITEX]],
footprintX = 3,
footprintZ = 3,
iconType = [[walkerriot]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
maxDamage = 1050,
maxSlope = 36,
maxVelocity = 1.9,
maxWaterDepth = 22,
minCloakDistance = 75,
movementClass = [[KBOT3]],
noChaseCategory = [[TERRAFORM FIXEDWING GUNSHIP SUB]],
objectName = [[behethud.s3o]],
onoffable = true,
selfDestructAs = [[BIG_UNITEX]],
script = [[shieldriot.lua]],
sfxtypes = {
explosiongenerators = {
[[custom:RIOTBALL]],
[[custom:RAIDMUZZLE]],
[[custom:LEVLRMUZZLE]],
[[custom:RIOT_SHELL_L]],
[[custom:BEAMWEAPON_MUZZLE_RED]],
},
},
sightDistance = 347,
trackOffset = 0,
trackStrength = 8,
trackStretch = 1,
trackType = [[ComTrack]],
trackWidth = 22,
turnRate = 2000,
upright = true,
weapons = {
{
def = [[FAKEGUN1]],
badTargetCategory = [[FIXEDWING GUNSHIP]],
onlyTargetCategory = [[LAND SINK TURRET SHIP SWIM FLOAT HOVER GUNSHIP FIXEDWING]],
},
{
def = [[BLAST]],
badTargetCategory = [[FIXEDWING GUNSHIP]],
onlyTargetCategory = [[LAND SINK TURRET SHIP SWIM FLOAT HOVER GUNSHIP FIXEDWING]],
},
{
def = [[FAKEGUN2]],
badTargetCategory = [[FIXEDWING GUNSHIP]],
onlyTargetCategory = [[LAND SINK TURRET SHIP SWIM FLOAT HOVER GUNSHIP FIXEDWING]],
},
},
weaponDefs = {
BLAST = {
name = [[Disruptor Pulser]],
areaOfEffect = 550,
craterBoost = 0,
craterMult = 0,
damage = {
default = 20,
planes = 20,
subs = 0.1,
},
customParams = {
light_radius = 0,
lups_explodespeed = 1,
lups_explodelife = 0.6,
nofriendlyfire = 1,
timeslow_damagefactor = 3.75,
},
edgeeffectiveness = 1,
explosionGenerator = [[custom:NONE]],
explosionSpeed = 11,
impulseBoost = 0,
impulseFactor = 0,
interceptedByShieldType = 1,
myGravity = 10,
noSelfDamage = true,
range = 300,
reloadtime = 0.95,
soundHitVolume = 1,
turret = true,
weaponType = [[Cannon]],
weaponVelocity = 230,
},
FAKEGUN1 = {
name = [[Fake Weapon]],
areaOfEffect = 8,
collideFriendly = false,
craterBoost = 0,
craterMult = 0,
damage = {
default = 1E-06,
planes = 1E-06,
subs = 5E-08,
},
explosionGenerator = [[custom:NONE]],
fireStarter = 0,
flightTime = 1,
impactOnly = true,
interceptedByShieldType = 1,
range = 32,
reloadtime = 0.95,
size = 1E-06,
smokeTrail = false,
textures = {
[[null]],
[[null]],
[[null]],
},
turnrate = 10000,
turret = true,
weaponAcceleration = 200,
weaponTimer = 0.1,
weaponType = [[StarburstLauncher]],
weaponVelocity = 200,
},
FAKEGUN2 = {
name = [[Fake Weapon]],
areaOfEffect = 8,
avoidFriendly = false,
collideFriendly = false,
craterBoost = 0,
craterMult = 0,
damage = {
default = 1E-06,
planes = 1E-06,
subs = 5E-08,
},
explosionGenerator = [[custom:NONE]],
fireStarter = 0,
flightTime = 1,
impactOnly = true,
interceptedByShieldType = 1,
range = 240,
reloadtime = 0.95,
size = 1E-06,
smokeTrail = false,
textures = {
[[null]],
[[null]],
[[null]],
},
turnrate = 10000,
turret = true,
weaponAcceleration = 200,
weaponTimer = 0.1,
weaponType = [[StarburstLauncher]],
weaponVelocity = 200,
},
},
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[behethud_dead.s3o]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2c.s3o]],
},
},
}
return lowerkeys({ shieldriot = unitDef })
| gpl-2.0 |
czfshine/Don-t-Starve | data/scripts/prefabs/resurrectionstone.lua | 1 | 3569 | local assets =
{
Asset("ANIM", "anim/resurrection_stone.zip"),
}
local prefabs =
{
"rocks",
"marble",
"nightmarefuel",
}
local function OnActivate(inst)
inst.components.resurrector.active = true
ProfileStatsSet("resurrectionstone_activated", true)
inst.AnimState:PlayAnimation("activate")
inst.AnimState:PushAnimation("idle_activate", true)
inst.SoundEmitter:PlaySound("dontstarve/common/resurrectionstone_activate")
inst.AnimState:SetLayer( LAYER_WORLD )
inst.AnimState:SetSortOrder( 0 )
inst.Physics:CollidesWith(COLLISION.CHARACTERS)
inst.components.resurrector:OnBuilt()
end
local function makeactive(inst)
inst.AnimState:PlayAnimation("idle_activate", true)
inst.components.activatable.inactive = false
end
local function makeused(inst)
inst.AnimState:PlayAnimation("idle_broken", true)
end
local function doresurrect(inst, dude)
inst:AddTag("busy")
inst.MiniMapEntity:SetEnabled(false)
if inst.Physics then
MakeInventoryPhysics(inst) -- collides with world, but not character
end
ProfileStatsSet("resurrectionstone_used", true)
GetClock():MakeNextDay()
dude.Transform:SetPosition(inst.Transform:GetWorldPosition())
dude:Hide()
TheCamera:SetDistance(12)
dude.components.hunger:Pause()
scheduler:ExecuteInTime(3, function()
dude:Show()
--inst:Hide()
GetSeasonManager():DoLightningStrike(Vector3(inst.Transform:GetWorldPosition()))
inst.SoundEmitter:PlaySound("dontstarve/common/resurrectionstone_break")
inst.components.lootdropper:DropLoot()
inst:Remove()
if dude.components.hunger then
dude.components.hunger:SetPercent(2/3)
end
if dude.components.health then
dude.components.health:Respawn(TUNING.RESURRECT_HEALTH)
end
if dude.components.sanity then
dude.components.sanity:SetPercent(.5)
end
dude.components.hunger:Resume()
dude.sg:GoToState("wakeup")
dude:DoTaskInTime(3, function(inst)
if dude.HUD then
dude.HUD:Show()
end
TheCamera:SetDefault()
inst:RemoveTag("busy")
--SaveGameIndex:SaveCurrent(function()
-- end)
end)
end)
end
local function fn()
local inst = CreateEntity()
local trans = inst.entity:AddTransform()
local anim = inst.entity:AddAnimState()
inst.entity:AddSoundEmitter()
MakeObstaclePhysics(inst, 1)
inst.Physics:SetCollisionGroup(COLLISION.OBSTACLES)
inst.Physics:ClearCollisionMask()
inst.Physics:CollidesWith(COLLISION.WORLD)
inst.Physics:CollidesWith(COLLISION.ITEMS)
inst:AddComponent("lootdropper")
inst.components.lootdropper:SetLoot({"rocks","rocks","marble","nightmarefuel","marble"})
anim:SetBank("resurrection_stone")
anim:SetBuild("resurrection_stone")
anim:PlayAnimation("idle_off")
anim:SetLayer( LAYER_BACKGROUND )
anim:SetSortOrder( 3 )
inst.entity:AddMiniMapEntity()
inst.MiniMapEntity:SetIcon( "resurrection_stone.png" )
inst:AddComponent("resurrector")
inst.components.resurrector.makeactivefn = makeactive
inst.components.resurrector.makeusedfn = makeused
inst.components.resurrector.doresurrect = doresurrect
inst:AddComponent("activatable")
inst.components.activatable.OnActivate = OnActivate
inst.components.activatable.inactive = true
inst:AddComponent("inspectable")
inst.components.inspectable:RecordViews()
return inst
end
return Prefab("forest/objects/resurrectionstone", fn, assets, prefabs)
| gpl-2.0 |
TimSimpson/Macaroni | Next/Tests/Bugs/6/manifest.lua | 2 | 1723 | upper = getUpperLibrary();
id =
{
group=upper.Group,
name= upper.Name .. ".4",
version="0.1.0.20",
author="Tim Simpson"
}
dependency {group="Macaroni", name="Boost-smart_ptr", version="1.46.1"}
dependency {group="Macaroni", name="CppStd", version="2003"}
description= [[
Its not possible to use two nodes with the same name even when their
full name is different. In C++ you can of course just reference them
in different ways, but Macaroni is forcing the "using" statement to
appear which causes problems.
To fix this, Macaroni needs some kind of alias functionality on its
import statement. So for example, you'd write:
~import Kennel::Dog;
~import Village::Dog as VDog;
Then Macaroni would define the header file as usual, but in the C++ file
create a macro for VDog:
#define Village::Dog VDog
That way users could use "VDog" in their code.
Another issue though is that this forces the C++ generation of
classes to either specify the full name of every node, which would
make it even uglier, or figure out that "VDog" is an acceptable
alias and use it.
There is also additional work on the parser side, where "VDog" would
need to be interpretted as "Village::Dog" every place it is
seen.
And of course, there's more trouble if this is used in inline methods
of the hidden header. Then this has to occur up there which could be
problematic.
]]
sources = { "src/test", "src/main" }
--source "src/test"
--source "src/main"
output = "target"
function generate()
run("HtmlView")
run "Cpp"
end
function build()
run("BoostBuild", {
ExcludePattern = "Tests.cpp",
Shared = True,
Tests = {"Tests.cpp"}
})
end
cavatappi("cavatappi.lua"); | apache-2.0 |
project-asap/IReS-Platform | resources/unusedAsapLibraryComponents/Maxim/operators/WIND_Join_test_VORONOI_Spark/WIND_Join_test_VORONOI_Postgres.lua | 3 | 1247 | -- General configuration of the operators belonging to Wind_Demo_o_Postgres workflow
BASE = "${JAVA_HOME}/bin/java -Xms64m -Xmx128m com.cloudera.kitten.appmaster.ApplicationMaster"
TIMEOUT = -1
MEMORY = 1024
CORES = 1
LABELS = "postgres"
EXECUTION_NODE_LOCATION = "hdp1"
-- Specific configuration of operator
OPERATOR = "WIND_Join_test_VORONOI_Postgres"
SCRIPT = OPERATOR .. ".sh"
SHELL_COMMAND = "./" .. SCRIPT
-- The actual distributed shell job.
operator = yarn {
name = "Execute " .. OPERATOR .. " Operator",
timeout = TIMEOUT,
memory = MEMORY,
cores = CORES,
labels = LABELS,
nodes = EXECUTION_NODE_LOCATION,
master = {
env = base_env,
resources = base_resources,
command = {
base = BASE,
args = { "-conf job.xml" },
}
},
container = {
instances = CONTAINER_INSTANCES,
env = base_env,
stageout = {"output"},
resources = {
["WIND_Join_test_VORONOI_Postgres.sh"] = {
file = "asapLibrary/operators/WIND_Join_test_VORONOI_Postgres/WIND_Join_test_VORONOI_Postgres.sh",
type = "file", -- other value: 'archive'
visibility = "application", -- other values: 'private', 'public'
}
},
command = {
base = SHELL_COMMAND
}
}
}
| apache-2.0 |
StoneDot/luasocket | test/urltest.lua | 30 | 17349 | local socket = require("socket")
socket.url = require("socket.url")
dofile("testsupport.lua")
local check_build_url = function(parsed)
local built = socket.url.build(parsed)
if built ~= parsed.url then
print("built is different from expected")
print(built)
print(expected)
os.exit()
end
end
local check_protect = function(parsed, path, unsafe)
local built = socket.url.build_path(parsed, unsafe)
if built ~= path then
print(built, path)
print("path composition failed.")
os.exit()
end
end
local check_invert = function(url)
local parsed = socket.url.parse(url)
parsed.path = socket.url.build_path(socket.url.parse_path(parsed.path))
local rebuilt = socket.url.build(parsed)
if rebuilt ~= url then
print(url, rebuilt)
print("original and rebuilt are different")
os.exit()
end
end
local check_parse_path = function(path, expect)
local parsed = socket.url.parse_path(path)
for i = 1, math.max(#parsed, #expect) do
if parsed[i] ~= expect[i] then
print(path)
os.exit()
end
end
if expect.is_directory ~= parsed.is_directory then
print(path)
print("is_directory mismatch")
os.exit()
end
if expect.is_absolute ~= parsed.is_absolute then
print(path)
print("is_absolute mismatch")
os.exit()
end
local built = socket.url.build_path(expect)
if built ~= path then
print(built, path)
print("path composition failed.")
os.exit()
end
end
local check_absolute_url = function(base, relative, absolute)
local res = socket.url.absolute(base, relative)
if res ~= absolute then
io.write("absolute: In test for '", relative, "' expected '",
absolute, "' but got '", res, "'\n")
os.exit()
end
end
local check_parse_url = function(gaba)
local url = gaba.url
gaba.url = nil
local parsed = socket.url.parse(url)
for i, v in pairs(gaba) do
if v ~= parsed[i] then
io.write("parse: In test for '", url, "' expected ", i, " = '",
v, "' but got '", tostring(parsed[i]), "'\n")
for i,v in pairs(parsed) do print(i,v) end
os.exit()
end
end
for i, v in pairs(parsed) do
if v ~= gaba[i] then
io.write("parse: In test for '", url, "' expected ", i, " = '",
tostring(gaba[i]), "' but got '", v, "'\n")
for i,v in pairs(parsed) do print(i,v) end
os.exit()
end
end
end
print("testing URL parsing")
check_parse_url{
url = "scheme://userinfo@host:port/path;params?query#fragment",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_parse_url{
url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme",
authority = "user:password@host:port",
host = "host",
port = "port",
userinfo = "user:password",
user = "user",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment",
}
check_parse_url{
url = "scheme://userinfo@host:port/path;params?query#",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "params",
query = "query",
fragment = ""
}
check_parse_url{
url = "scheme://userinfo@host:port/path;params?#fragment",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "params",
query = "",
fragment = "fragment"
}
check_parse_url{
url = "scheme://userinfo@host:port/path;params#fragment",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "params",
fragment = "fragment"
}
check_parse_url{
url = "scheme://userinfo@host:port/path;?query#fragment",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "",
query = "query",
fragment = "fragment"
}
check_parse_url{
url = "scheme://userinfo@host:port/path?query#fragment",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
query = "query",
fragment = "fragment"
}
check_parse_url{
url = "scheme://userinfo@host:port/;params?query#fragment",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/",
params = "params",
query = "query",
fragment = "fragment"
}
check_parse_url{
url = "scheme://userinfo@host:port",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
}
check_parse_url{
url = "//userinfo@host:port/path;params?query#fragment",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_parse_url{
url = "//userinfo@host:port/path",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
}
check_parse_url{
url = "//userinfo@host/path",
authority = "userinfo@host",
host = "host",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
}
check_parse_url{
url = "//user:password@host/path",
authority = "user:password@host",
host = "host",
userinfo = "user:password",
password = "password",
user = "user",
path = "/path",
}
check_parse_url{
url = "//user:@host/path",
authority = "user:@host",
host = "host",
userinfo = "user:",
password = "",
user = "user",
path = "/path",
}
check_parse_url{
url = "//user@host:port/path",
authority = "user@host:port",
host = "host",
userinfo = "user",
user = "user",
port = "port",
path = "/path",
}
check_parse_url{
url = "//host:port/path",
authority = "host:port",
port = "port",
host = "host",
path = "/path",
}
check_parse_url{
url = "//host/path",
authority = "host",
host = "host",
path = "/path",
}
check_parse_url{
url = "//host",
authority = "host",
host = "host",
}
check_parse_url{
url = "/path",
path = "/path",
}
check_parse_url{
url = "path",
path = "path",
}
-- IPv6 tests
check_parse_url{
url = "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html",
scheme = "http",
host = "FEDC:BA98:7654:3210:FEDC:BA98:7654:3210",
authority = "[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80",
port = "80",
path = "/index.html"
}
check_parse_url{
url = "http://[1080:0:0:0:8:800:200C:417A]/index.html",
scheme = "http",
host = "1080:0:0:0:8:800:200C:417A",
authority = "[1080:0:0:0:8:800:200C:417A]",
path = "/index.html"
}
check_parse_url{
url = "http://[3ffe:2a00:100:7031::1]",
scheme = "http",
host = "3ffe:2a00:100:7031::1",
authority = "[3ffe:2a00:100:7031::1]",
}
check_parse_url{
url = "http://[1080::8:800:200C:417A]/foo",
scheme = "http",
host = "1080::8:800:200C:417A",
authority = "[1080::8:800:200C:417A]",
path = "/foo"
}
check_parse_url{
url = "http://[::192.9.5.5]/ipng",
scheme = "http",
host = "::192.9.5.5",
authority = "[::192.9.5.5]",
path = "/ipng"
}
check_parse_url{
url = "http://[::FFFF:129.144.52.38]:80/index.html",
scheme = "http",
host = "::FFFF:129.144.52.38",
port = "80",
authority = "[::FFFF:129.144.52.38]:80",
path = "/index.html"
}
check_parse_url{
url = "http://[2010:836B:4179::836B:4179]",
scheme = "http",
host = "2010:836B:4179::836B:4179",
authority = "[2010:836B:4179::836B:4179]",
}
check_parse_url{
url = "//userinfo@[::FFFF:129.144.52.38]:port/path;params?query#fragment",
authority = "userinfo@[::FFFF:129.144.52.38]:port",
host = "::FFFF:129.144.52.38",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_parse_url{
url = "scheme://user:password@[::192.9.5.5]:port/path;params?query#fragment",
scheme = "scheme",
authority = "user:password@[::192.9.5.5]:port",
host = "::192.9.5.5",
port = "port",
userinfo = "user:password",
user = "user",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
print("testing URL building")
check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme",
host = "host",
port = "port",
user = "user",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url{
url = "//userinfo@[::FFFF:129.144.52.38]:port/path;params?query#fragment",
host = "::FFFF:129.144.52.38",
port = "port",
user = "userinfo",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url{
url = "scheme://user:password@[::192.9.5.5]:port/path;params?query#fragment",
scheme = "scheme",
host = "::192.9.5.5",
port = "port",
user = "user",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://user:password@host/path;params?query#fragment",
scheme = "scheme",
host = "host",
user = "user",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://user@host/path;params?query#fragment",
scheme = "scheme",
host = "host",
user = "user",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://host/path;params?query#fragment",
scheme = "scheme",
host = "host",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://host/path;params#fragment",
scheme = "scheme",
host = "host",
path = "/path",
params = "params",
fragment = "fragment"
}
check_build_url {
url = "scheme://host/path#fragment",
scheme = "scheme",
host = "host",
path = "/path",
fragment = "fragment"
}
check_build_url {
url = "scheme://host/path",
scheme = "scheme",
host = "host",
path = "/path",
}
check_build_url {
url = "//host/path",
host = "host",
path = "/path",
}
check_build_url {
url = "/path",
path = "/path",
}
check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme",
host = "host",
port = "port",
user = "user",
userinfo = "not used",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme",
host = "host",
port = "port",
user = "user",
userinfo = "not used",
authority = "not used",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme",
host = "host",
port = "port",
userinfo = "user:password",
authority = "not used",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme",
authority = "user:password@host:port",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
-- standard RFC tests
print("testing absolute resolution")
check_absolute_url("http://a/b/c/d;p?q#f", "g:h", "g:h")
check_absolute_url("http://a/b/c/d;p?q#f", "g", "http://a/b/c/g")
check_absolute_url("http://a/b/c/d;p?q#f", "./g", "http://a/b/c/g")
check_absolute_url("http://a/b/c/d;p?q#f", "g/", "http://a/b/c/g/")
check_absolute_url("http://a/b/c/d;p?q#f", "/g", "http://a/g")
check_absolute_url("http://a/b/c/d;p?q#f", "//g", "http://g")
check_absolute_url("http://a/b/c/d;p?q#f", "?y", "http://a/b/c/d;p?y")
check_absolute_url("http://a/b/c/d;p?q#f", "g?y", "http://a/b/c/g?y")
check_absolute_url("http://a/b/c/d;p?q#f", "g?y/./x", "http://a/b/c/g?y/./x")
check_absolute_url("http://a/b/c/d;p?q#f", "#s", "http://a/b/c/d;p?q#s")
check_absolute_url("http://a/b/c/d;p?q#f", "g#s", "http://a/b/c/g#s")
check_absolute_url("http://a/b/c/d;p?q#f", "g#s/./x", "http://a/b/c/g#s/./x")
check_absolute_url("http://a/b/c/d;p?q#f", "g?y#s", "http://a/b/c/g?y#s")
check_absolute_url("http://a/b/c/d;p?q#f", ";x", "http://a/b/c/d;x")
check_absolute_url("http://a/b/c/d;p?q#f", "g;x", "http://a/b/c/g;x")
check_absolute_url("http://a/b/c/d;p?q#f", "g;x?y#s", "http://a/b/c/g;x?y#s")
check_absolute_url("http://a/b/c/d;p?q#f", ".", "http://a/b/c/")
check_absolute_url("http://a/b/c/d;p?q#f", "./", "http://a/b/c/")
check_absolute_url("http://a/b/c/d;p?q#f", "..", "http://a/b/")
check_absolute_url("http://a/b/c/d;p?q#f", "../", "http://a/b/")
check_absolute_url("http://a/b/c/d;p?q#f", "../g", "http://a/b/g")
check_absolute_url("http://a/b/c/d;p?q#f", "../..", "http://a/")
check_absolute_url("http://a/b/c/d;p?q#f", "../../", "http://a/")
check_absolute_url("http://a/b/c/d;p?q#f", "../../g", "http://a/g")
check_absolute_url("http://a/b/c/d;p?q#f", "", "http://a/b/c/d;p?q#f")
check_absolute_url("http://a/b/c/d;p?q#f", "/./g", "http://a/./g")
check_absolute_url("http://a/b/c/d;p?q#f", "/../g", "http://a/../g")
check_absolute_url("http://a/b/c/d;p?q#f", "g.", "http://a/b/c/g.")
check_absolute_url("http://a/b/c/d;p?q#f", ".g", "http://a/b/c/.g")
check_absolute_url("http://a/b/c/d;p?q#f", "g..", "http://a/b/c/g..")
check_absolute_url("http://a/b/c/d;p?q#f", "..g", "http://a/b/c/..g")
check_absolute_url("http://a/b/c/d;p?q#f", "./../g", "http://a/b/g")
check_absolute_url("http://a/b/c/d;p?q#f", "./g/.", "http://a/b/c/g/")
check_absolute_url("http://a/b/c/d;p?q#f", "g/./h", "http://a/b/c/g/h")
check_absolute_url("http://a/b/c/d;p?q#f", "g/../h", "http://a/b/c/h")
-- extra tests
check_absolute_url("//a/b/c/d;p?q#f", "d/e/f", "//a/b/c/d/e/f")
check_absolute_url("/a/b/c/d;p?q#f", "d/e/f", "/a/b/c/d/e/f")
check_absolute_url("a/b/c/d", "d/e/f", "a/b/c/d/e/f")
check_absolute_url("a/b/c/d/../", "d/e/f", "a/b/c/d/e/f")
check_absolute_url("http://velox.telemar.com.br", "/dashboard/index.html",
"http://velox.telemar.com.br/dashboard/index.html")
print("testing path parsing and composition")
check_parse_path("/eu/tu/ele", { "eu", "tu", "ele"; is_absolute = 1 })
check_parse_path("/eu/", { "eu"; is_absolute = 1, is_directory = 1 })
check_parse_path("eu/tu/ele/nos/vos/eles/",
{ "eu", "tu", "ele", "nos", "vos", "eles"; is_directory = 1})
check_parse_path("/", { is_absolute = 1, is_directory = 1})
check_parse_path("", { })
check_parse_path("eu%01/%02tu/e%03l%04e/nos/vos%05/e%12les/",
{ "eu\1", "\2tu", "e\3l\4e", "nos", "vos\5", "e\18les"; is_directory = 1})
check_parse_path("eu/tu", { "eu", "tu" })
print("testing path protection")
check_protect({ "eu", "-_.!~*'():@&=+$,", "tu" }, "eu/-_.!~*'():@&=+$,/tu")
check_protect({ "eu ", "~diego" }, "eu%20/~diego")
check_protect({ "/eu>", "<diego?" }, "%2feu%3e/%3cdiego%3f")
check_protect({ "\\eu]", "[diego`" }, "%5ceu%5d/%5bdiego%60")
check_protect({ "{eu}", "|diego\127" }, "%7beu%7d/%7cdiego%7f")
check_protect({ "eu ", "~diego" }, "eu /~diego", 1)
check_protect({ "/eu>", "<diego?" }, "/eu>/<diego?", 1)
check_protect({ "\\eu]", "[diego`" }, "\\eu]/[diego`", 1)
check_protect({ "{eu}", "|diego\127" }, "{eu}/|diego\127", 1)
print("testing inversion")
check_invert("http:")
check_invert("a/b/c/d.html")
check_invert("//net_loc")
check_invert("http:a/b/d/c.html")
check_invert("//net_loc/a/b/d/c.html")
check_invert("http://net_loc/a/b/d/c.html")
check_invert("//who:isit@net_loc")
check_invert("http://he:man@boo.bar/a/b/c/i.html;type=moo?this=that#mark")
check_invert("/b/c/d#fragment")
check_invert("/b/c/d;param#fragment")
check_invert("/b/c/d;param?query#fragment")
check_invert("/b/c/d?query")
check_invert("/b/c/d;param?query")
check_invert("http://he:man@[::192.168.1.1]/a/b/c/i.html;type=moo?this=that#mark")
print("the library passed all tests")
| mit |
CrazyEddieTK/Zero-K | effects/gundam_dirt.lua | 24 | 11215 | -- dirt3
-- dirt
-- dirt2
return {
["dirt3"] = {
poof01 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 10,
ground = true,
properties = {
airdrag = 1.0,
alwaysvisible = false,
colormap = [[0.8 0.65 0.55 1.0 0 0 0 0.0]],
directional = true,
emitrot = 90,
emitrotspread = 25,
emitvector = [[0, 0, 0]],
gravity = [[r-0.05 r0.05, 0 r0.05, r-0.05 r0.05]],
numparticles = 5,
particlelife = 8,
particlelifespread = 40,
particlesize = 20,
particlesizespread = 0,
particlespeed = 3,
particlespeedspread = 10,
pos = [[r-5 r5, r-25 r1, r-5 r5]],
sizegrowth = 1.6,
sizemod = 1.0,
texture = [[dirt]],
},
},
poof02 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 10,
ground = true,
properties = {
airdrag = 1.0,
alwaysvisible = false,
colormap = [[0.8 0.65 0.55 1.0 0 0 0 0.0]],
directional = true,
emitrot = 45,
emitrotspread = 25,
emitvector = [[0, 1, 0]],
gravity = [[r-0.1 r0.1, 0 r0.1, r-0.1 r0.1]],
numparticles = 10,
particlelife = 8,
particlelifespread = 20,
particlesize = 20,
particlesizespread = 0,
particlespeed = 2,
particlespeedspread = 1,
pos = [[r-50 r50, r-25 r1, r-50 r50]],
sizegrowth = 1.6,
sizemod = 1.0,
texture = [[dirt]],
},
},
wpoof01 = {
class = [[CSimpleParticleSystem]],
count = 10,
water = true,
properties = {
airdrag = 1.0,
alwaysvisible = false,
colormap = [[0.2 0.2 0.4 0.01 0 0 0 0.0]],
directional = true,
emitrot = 45,
emitrotspread = 25,
emitvector = [[0, 0, 0]],
gravity = [[r-0.05 r0.05, 0 r0.05, r-0.05 r0.05]],
numparticles = 4,
particlelife = 6,
particlelifespread = 40,
particlesize = 20,
particlesizespread = 0,
particlespeed = 3,
particlespeedspread = 10,
pos = [[r-50 r50, r-25 r1, r-50 r50]],
sizegrowth = 1.6,
sizemod = 1.0,
texture = [[dirtold]],
},
},
wpoof02 = {
class = [[CSimpleParticleSystem]],
count = 10,
water = true,
properties = {
airdrag = 1.0,
alwaysvisible = false,
colormap = [[0.2 0.2 0.4 0.01 0 0 0 0.0]],
directional = true,
emitrot = 45,
emitrotspread = 25,
emitvector = [[0, 1, 0]],
gravity = [[r-0.1 r0.1, 0 r0.1, r-0.1 r0.1]],
numparticles = 10,
particlelife = 4,
particlelifespread = 20,
particlesize = 20,
particlesizespread = 0,
particlespeed = 2,
particlespeedspread = 1,
pos = [[r-50 r50, r-25 r1, r-50 r50]],
sizegrowth = 1.6,
sizemod = 1.0,
texture = [[dirtold]],
},
},
},
["dirt"] = {
poof01 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
properties = {
airdrag = 1.0,
alwaysvisible = false,
colormap = [[0.8 0.65 0.55 1.0 0 0 0 0.0]],
directional = true,
emitrot = 90,
emitrotspread = 25,
emitvector = [[0, 0, 0]],
gravity = [[r-0.05 r0.05, 0 r0.05, r-0.05 r0.05]],
numparticles = 5,
particlelife = 4,
particlelifespread = 40,
particlesize = 10,
particlesizespread = 0,
particlespeed = 3,
particlespeedspread = 10,
pos = [[r-1 r1, r-1 r1, r-1 r1]],
sizegrowth = 0.8,
sizemod = 1.0,
texture = [[dirt]],
},
},
poof02 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
properties = {
airdrag = 1.0,
alwaysvisible = false,
colormap = [[0.8 0.65 0.55 1.0 0 0 0 0.0]],
directional = true,
emitrot = 90,
emitrotspread = 25,
emitvector = [[0, 1, 0]],
gravity = [[r-0.1 r0.1, 0 r0.1, r-0.1 r0.1]],
numparticles = 10,
particlelife = 4,
particlelifespread = 20,
particlesize = 10,
particlesizespread = 0,
particlespeed = 2,
particlespeedspread = 1,
pos = [[r-1 r1, r-1 r1, r-1 r1]],
sizegrowth = 0.8,
sizemod = 1.0,
texture = [[dirt]],
},
},
wpoof01 = {
class = [[CSimpleParticleSystem]],
count = 1,
water = true,
properties = {
airdrag = 1.0,
alwaysvisible = false,
colormap = [[0.2 0.2 0.4 0.2 0 0 0 0.0]],
directional = true,
emitrot = 25,
emitrotspread = 25,
emitvector = [[0, 1, 0]],
gravity = [[r-0.01 r0.01, -0.18 r0.05, r-0.01 r0.01]],
numparticles = 5,
particlelife = 10,
particlelifespread = 20,
particlesize = 20,
particlesizespread = 0,
particlespeed = 2,
particlespeedspread = 0.5,
pos = [[r-1 r1, r-1 r1, r-1 r1]],
sizegrowth = 0.6,
sizemod = 1.0,
texture = [[debris2]],
},
},
wpoof02 = {
class = [[CSimpleParticleSystem]],
count = 1,
water = true,
properties = {
airdrag = 0.9,
alwaysvisible = false,
colormap = [[0.2 0.2 0.4 0.05 0 0 0 0.0]],
directional = true,
emitrot = 90,
emitrotspread = 25,
emitvector = [[0, 1, 0]],
gravity = [[r-0.1 r0.1, 0 r0.1, r-0.1 r0.1]],
numparticles = 10,
particlelife = 2,
particlelifespread = 20,
particlesize = 10,
particlesizespread = 0,
particlespeed = 1.8,
particlespeedspread = 1,
pos = [[r-1 r1, r-1 r1, r-1 r1]],
sizegrowth = 0.8,
sizemod = 1.0,
texture = [[dirtplosion2]],
},
},
},
["dirt2"] = {
poof01 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
properties = {
airdrag = 1.0,
alwaysvisible = false,
colormap = [[0.8 0.65 0.55 1.0 0 0 0 0.0]],
directional = true,
emitrot = 90,
emitrotspread = 25,
emitvector = [[0, 0, 0]],
gravity = [[r-0.05 r0.05, 0 r0.05, r-0.05 r0.05]],
numparticles = 5,
particlelife = 4,
particlelifespread = 40,
particlesize = 3,
particlesizespread = 0,
particlespeed = 1,
particlespeedspread = 3,
pos = [[r-50 r5, r-25 r1, r-50 r50]],
sizegrowth = 0.2,
sizemod = 1.0,
texture = [[dirt]],
},
},
poof02 = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
properties = {
airdrag = 1.0,
alwaysvisible = false,
colormap = [[0.8 0.65 0.55 1.0 0 0 0 0.0]],
directional = true,
emitrot = 45,
emitrotspread = 25,
emitvector = [[0, 1, 0]],
gravity = [[r-0.1 r0.1, 0 r0.1, r-0.1 r0.1]],
numparticles = 10,
particlelife = 4,
particlelifespread = 20,
particlesize = 3,
particlesizespread = 0,
particlespeed = 0.6,
particlespeedspread = 0.3,
pos = [[r-50 r50, r-25 r1, r-50 r50]],
sizegrowth = 0.2,
sizemod = 1.0,
texture = [[dirt]],
},
},
wpoof01 = {
class = [[CSimpleParticleSystem]],
count = 1,
water = true,
properties = {
airdrag = 1.0,
alwaysvisible = false,
colormap = [[0.2 0.2 0.4 0.01 0 0 0 0.0]],
directional = true,
emitrot = 45,
emitrotspread = 25,
emitvector = [[0, 0, 0]],
gravity = [[r-0.05 r0.05, 0 r0.05, r-0.05 r0.05]],
numparticles = 4,
particlelife = 3,
particlelifespread = 40,
particlesize = 3,
particlesizespread = 0,
particlespeed = 1,
particlespeedspread = 3,
pos = [[r-50 r50, r-25 r1, r-50 r50]],
sizegrowth = 0.2,
sizemod = 1.0,
texture = [[dirtold]],
},
},
wpoof02 = {
class = [[CSimpleParticleSystem]],
count = 1,
water = true,
properties = {
airdrag = 1.0,
alwaysvisible = false,
colormap = [[0.2 0.2 0.4 0.01 0 0 0 0.0]],
directional = true,
emitrot = 45,
emitrotspread = 25,
emitvector = [[0, 1, 0]],
gravity = [[r-0.1 r0.1, 0 r0.1, r-0.1 r0.1]],
numparticles = 10,
particlelife = 2,
particlelifespread = 20,
particlesize = 3,
particlesizespread = 0,
particlespeed = 0.6,
particlespeedspread = 0.3,
pos = [[r-50 r50, r-25 r1, r-50 r50]],
sizegrowth = 0.2,
sizemod = 1.0,
texture = [[dirtold]],
},
},
},
}
| gpl-2.0 |
CrazyEddieTK/Zero-K | scripts/energywind.lua | 5 | 3246 | local base, fan, cradle, flaot = piece('base', 'fan', 'cradle', 'flaot')
include "constants.lua"
local baseDirection
local smokePiece = {base}
local tau = math.pi*2
local pi = math.pi
local hpi = math.pi*0.5
local pi34 = math.pi*1.5
local UPDATE_PERIOD = 1000
local BUILD_PERIOD = 500
local turnSpeed = math.rad(20)
local isWind, baseWind, rangeWind
function BobTidal()
baseDirection = baseDirection + math.random(0,math.rad(2))
while true do
Turn(cradle, y_axis, baseDirection, math.rad(1))
Move(cradle, x_axis, math.random(-2,2), 0.2)
Move(cradle, y_axis, math.random(-0.5,0.5) - 51, 0.05)
Move(cradle, z_axis, math.random(-2,2), 0.2)
Sleep(1000)
end
end
function SpinWind()
while true do
if select(5, Spring.GetUnitHealth(unitID)) < 1 then
Spin(fan, z_axis, 0)
Sleep(BUILD_PERIOD)
else
local st = baseWind + (Spring.GetGameRulesParam("WindStrength") or 0)*rangeWind
local direction = Spring.GetGameRulesParam("WindHeading")
Spin(fan, z_axis, -st*(0.94 + 0.08*math.random()))
Turn(cradle, y_axis, direction - baseDirection + pi, turnSpeed)
Sleep(UPDATE_PERIOD + 200*math.random())
end
end
end
function script.Create()
StartThread(SmokeUnit, smokePiece)
baseDirection = math.random(0,tau)
Turn(base, y_axis, baseDirection)
baseDirection = baseDirection + hpi * Spring.GetUnitBuildFacing(unitID)
isWind, baseWind, rangeWind = GG.SetupWindmill(unitID)
if isWind then
StartThread(SpinWind)
else
StartThread(BobTidal)
Hide(base)
Hide(flaot)
Move(cradle, y_axis, -51)
Turn(fan, x_axis, math.rad(90))
Move(fan, z_axis, 9)
Move(fan, y_axis, -5)
--[[ diagonal down, needs teamcolour
Move(cradle, y_axis, -41)
Move(cradle, z_axis, -10)
Turn(cradle, z_axis, math.pi)
Turn(cradle, x_axis, math.rad(-15))
Turn(fan, x_axis, math.rad(50))
Move(fan, x_axis, 0)
Move(fan, z_axis, 14)
Move(fan, y_axis, 18)
--]]
Spin(fan, z_axis, math.rad(30))
end
end
local function CreateTidalWreck()
local x,y,z = Spring.GetUnitPosition(unitID)
local heading = Spring.GetUnitHeading(unitID)
local team = Spring.GetUnitTeam(unitID)
local featureID = Spring.CreateFeature("energywind_deadwater", x, y, z, heading + baseDirection*65536/tau, team)
Spring.SetFeatureResurrect(featureID, "energywind")
end
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage / maxHealth
if isWind then
if severity <= 0.25 then
Explode(base, sfxShatter)
Explode(fan, sfxFall + sfxSmoke + sfxFire + sfxExplodeOnHit)
Explode(base, sfxShatter)
return 1
elseif severity <= 0.5 then
Explode(base, sfxShatter)
Explode(fan, sfxFall + sfxSmoke + sfxFire + sfxExplodeOnHit)
Explode(cradle, sfxShatter)
return 1
else
Explode(base, sfxShatter)
Explode(fan, sfxFall + sfxSmoke + sfxFire + sfxExplodeOnHit)
Explode(cradle, sfxSmoke)
return 2
end
else
if severity <= 0.25 then
--Explode(fan, sfxSmoke)
--Explode(cradle, sfxFire)
CreateTidalWreck()
return 3
elseif severity <= 0.5 then
--Explode(fan, sfxFall + sfxSmoke + sfxFire + sfxExplodeOnHit)
--Explode(cradle, sfxSmoke)
CreateTidalWreck()
return 3
else
Explode(fan, sfxShatter)
Explode(cradle, sfxShatter)
return 2
end
end
end
| gpl-2.0 |
czfshine/Don-t-Starve | data/scripts/components/childspawner.lua | 1 | 10322 | local trace = function() end
-- local trace = function(inst, ...)
-- if inst.prefab == "beebox" then
-- print(inst, ...)
-- end
-- end
--- Spawns and tracks child entities in the world
-- For setup the following params should be set
-- @param childname The prefab name of the default child to be spawned. This can be overridden in the SpawnChild method
-- @param delay The time between spawning children when the spawner is actively spawning. If nil, only manual spawning works.
-- @param newchilddelay The time it takes for a killed/captured child to be regenerated in the childspawner. If nil, dead children aren't regenerated.
-- It's also a good idea to call SetMaxChildren as part of the childspawner setup.
local ChildSpawner = Class(function(self, inst)
self.inst = inst
self.childrenoutside = {}
self.childreninside = 1
self.numchildrenoutside = 0
self.maxchildren = 0
self.childname = ""
self.rarechild = nil
self.rarechildchance = 0.1
self.onvacate = nil
self.onoccupied = nil
self.onspawned = nil
self.ongohome = nil
self.spawning = false
self.timetonextspawn = 0
self.spawnperiod = 20
self.spawnvariance = 2
self.regening = true
self.timetonextregen = 0
self.regenperiod = 20
self.regenvariance = 2
self.spawnoffscreen = false
end)
function ChildSpawner:StartRegen()
self.regening = true
if self.numchildrenoutside + self.childreninside < self.maxchildren then
self.timetonextregen = self.regenperiod + (math.random()*2-1)*self.regenvariance
self:StartUpdate(6)
end
end
function ChildSpawner:SetRareChild(childname, chance)
self.rarechild = childname
self.rarechildchance = chance
end
function ChildSpawner:StopRegen()
self.regening = false
end
function ChildSpawner:SetSpawnPeriod(period, variance)
self.spawnperiod = period
self.spawnvariance = variance or period * 0.1
end
function ChildSpawner:SetRegenPeriod(period, variance)
self.regenperiod = period
self.regenvariance = variance or period * 0.1
end
function ChildSpawner:OnUpdate(dt)
if self.regening then
if self.numchildrenoutside + self.childreninside < self.maxchildren then
self.timetonextregen = self.timetonextregen - dt
if self.timetonextregen < 0 then
self.timetonextregen = self.regenperiod + (math.random()*2-1)*self.regenvariance
self:AddChildrenInside(1)
end
else
self.timetonextregen = self.regenperiod + (math.random()*2-1)*self.regenvariance
end
end
if self.spawning then
if self.childreninside > 0 then
self.timetonextspawn = self.timetonextspawn - dt
if self.timetonextspawn < 0 then
self.timetonextspawn = self.spawnperiod + (math.random()*2-1)*self.spawnvariance
self:SpawnChild()
end
else
self.timetonextspawn = 0
end
end
local need_to_continue_spawning = self.spawning and self.childreninside > 0
local need_to_continue_regening = self.regening and self.numchildrenoutside + self.childreninside < self.maxchildren
if not need_to_continue_spawning and not need_to_continue_regening then
if self.task then
self.task:Cancel()
self.task = nil
end
--self.inst:StopUpdatingComponent(self)
end
end
function ChildSpawner:StartUpdate(dt)
if not self.task then
local dt = 5 + math.random()*5
self.task = self.inst:DoPeriodicTask(dt, function() self:OnUpdate(dt) end)
end
end
function ChildSpawner:StartSpawning()
trace(self.inst, "ChildSpawner:StartSpawning()")
self.spawning = true
self.timetonextspawn = 0
self:StartUpdate(6)
end
function ChildSpawner:StopSpawning()
self.spawning = false
end
function ChildSpawner:SetOccupiedFn(fn)
self.onoccupied = fn
end
function ChildSpawner:SetSpawnedFn(fn)
self.onspawned = fn
end
function ChildSpawner:SetGoHomeFn(fn)
self.ongohome = fn
end
function ChildSpawner:SetVacateFn(fn)
self.onvacate = fn
end
function ChildSpawner:CountChildrenOutside(fn)
local vacantchildren = 0
for k,v in pairs(self.childrenoutside) do
if v and v:IsValid() and (not fn or fn(v) ) then
vacantchildren = vacantchildren + 1
end
end
return vacantchildren
end
function ChildSpawner:SetMaxChildren(max)
self.childreninside = max - self:CountChildrenOutside()
self.maxchildren = max
if self.childreninside < 0 then self.childreninside = 0 end
end
function ChildSpawner:OnSave()
local data = {}
local references = {}
for k,v in pairs(self.childrenoutside) do
if not data.childrenoutside then
data.childrenoutside = {v.GUID}
else
table.insert(data.childrenoutside, v.GUID)
end
table.insert(references, v.GUID)
end
data.childreninside = self.childreninside
data.spawning = self.spawning
data.regening = self.regening
data.timetonextregen = math.floor(self.timetonextregen)
data.timetonextspawn = math.floor(self.timetonextspawn)
return data, references
end
function ChildSpawner:GetDebugString()
local str = string.format("%s - %d in, %d out", self.childname, self.childreninside, self.numchildrenoutside )
local num_children = self.numchildrenoutside + self.childreninside
if num_children < self.maxchildren and self.regening then
str = str..string.format(" Regen in %2.2f ", self.timetonextregen )
end
if self.childreninside > 0 and self.spawning then
str = str..string.format(" Spawn in %2.2f ", self.timetonextspawn )
end
if self.spawning then
str = str.."S"
end
if self.regening then
str = str.."R"
end
return str
end
function ChildSpawner:OnLoad(data)
trace(self.inst, "ChildSpawner:OnLoad")
--convert previous data
if data.occupied then
data.childreninside = 1
end
if data.childid then
data.childrenoutside = {data.childid}
end
if data.childreninside then
self.childreninside = 0
self:AddChildrenInside(data.childreninside)
if self.childreninside > 0 and self.onoccupied then
self.onoccupied(self.inst)
elseif self.childreninside == 0 and self.onvacate then
self.onvacate(self.inst)
end
end
self.spawning = data.spawning or self.spawning
self.regening = data.regening or self.regening
self.timetonextregen = data.timetonextregen or self.timetonextregen
self.timetonextspawn = data.timetonextspawn or self.timetonextspawn
if self.spawning or self.regening then
self:StartUpdate(6)
end
end
function ChildSpawner:TakeOwnership(child)
if child.components.knownlocations then
child.components.knownlocations:RememberLocation("home", Vector3(self.inst.Transform:GetWorldPosition()))
end
child:AddComponent("homeseeker")
child.components.homeseeker:SetHome(self.inst)
self.inst:ListenForEvent( "ontrapped", function() self:OnChildKilled( child ) end, child )
self.inst:ListenForEvent( "death", function() self:OnChildKilled( child ) end, child )
self.childrenoutside[child] = child
self.numchildrenoutside = self.numchildrenoutside + 1
end
function ChildSpawner:LoadPostPass(newents, savedata)
trace(self.inst, "ChildSpawner:LoadPostPass")
if savedata.childrenoutside then
for k,v in pairs(savedata.childrenoutside) do
local child = newents[v]
if child then
child = child.entity
self:TakeOwnership(child)
end
end
end
end
function ChildSpawner:SpawnChild(target, prefab, radius)
if not self:CanSpawn() then
return
end
trace(self.inst, "ChildSpawner:SpawnChild")
local pos = Vector3(self.inst.Transform:GetWorldPosition())
local start_angle = math.random()*PI*2
local rad = radius or 0.5
if self.inst.Physics then
rad = rad + self.inst.Physics:GetRadius()
end
local offset = FindWalkableOffset(pos, start_angle, rad, 8, false)
if offset == nil then
return
end
pos = pos + offset
local childtospawn = prefab or self.childname
if self.rarechild and math.random() < self.rarechildchance then
childtospawn = self.rarechild
end
local child = SpawnPrefab(childtospawn)
if child ~= nil then
child.Transform:SetPosition(pos:Get())
self:TakeOwnership(child)
if target and child.components.combat then
child.components.combat:SetTarget(target)
end
if self.onspawned then
self.onspawned(self.inst, child)
end
if self.childreninside == 1 and self.onvacate then
self:onvacate(self.inst)
end
self.childreninside = self.childreninside - 1
end
return child
end
function ChildSpawner:GoHome( child )
if self.childrenoutside[child] then
self.inst:PushEvent("childgoinghome", {child = child})
child:PushEvent("goinghome", {home = self.inst})
if self.ongohome then
self.ongohome(self.inst, child)
end
child:Remove()
self.childrenoutside[child] = nil
self.numchildrenoutside = self.numchildrenoutside - 1
self:AddChildrenInside(1)
return true
end
end
function ChildSpawner:CanSpawn()
if self.childreninside <= 0 then
return false
end
if self.inst:IsAsleep() and not self.spawnoffscreen then
return false
end
if not self.inst:IsValid() then
return false
end
if self.inst.components.health and self.inst.components.health:IsDead() then
return false
end
return true
end
function ChildSpawner:OnChildKilled( child )
if self.childrenoutside[child] then
self.childrenoutside[child] = nil
self.numchildrenoutside = self.numchildrenoutside - 1
if self.regening then
self:StartUpdate(6)
end
end
end
function ChildSpawner:ReleaseAllChildren(target, prefab)
while self:CanSpawn() do
self:SpawnChild(target, prefab)
end
end
function ChildSpawner:AddChildrenInside(count)
if self.childreninside == 0 and self.onoccupied then
self.onoccupied(self.inst)
end
self.childreninside = self.childreninside + count
if self.maxchildren then
self.childreninside = math.min(self.maxchildren, self.childreninside)
end
end
function ChildSpawner:LongUpdate(dt)
if self.spawning then
self:OnUpdate(dt)
end
end
return ChildSpawner
| gpl-2.0 |
rzh/mongocraft | world/Plugins/Core/spawn.lua | 5 | 2174 | function HandleSpawnCommand(Split, Player)
local WorldIni = cIniFile()
WorldIni:ReadFile(Player:GetWorld():GetIniFileName())
local SpawnX = WorldIni:GetValue("SpawnPosition", "X")
local SpawnY = WorldIni:GetValue("SpawnPosition", "Y")
local SpawnZ = WorldIni:GetValue("SpawnPosition", "Z")
local flag = 0
if (#Split == 2 and Split[2] ~= Player:GetName()) then
if Player:HasPermission("core.spawn.others") then
local FoundPlayerCallback = function(OtherPlayer)
if (OtherPlayer:GetName() == Split[2]) then
World = OtherPlayer:GetWorld()
local OnAllChunksAvaliable = function()
OtherPlayer:TeleportToCoords(SpawnX, SpawnY, SpawnZ)
SendMessageSuccess( Player, "Returned " .. OtherPlayer:GetName() .. " to world spawn" )
flag=1
end
World:ChunkStay({{SpawnX/16, SpawnZ/16}}, OnChunkAvailable, OnAllChunksAvaliable)
end
end
cRoot:Get():FindAndDoWithPlayer(Split[2], FoundPlayerCallback)
if flag == 0 then
SendMessageFailure( Player, "Player " .. Split[2] .. " not found!" )
end
else
SendMessageFailure( Player, "You need core.spawn.others permission to do that!" )
end
else
World = Player:GetWorld()
local OnAllChunksAvaliable = function()
Player:TeleportToCoords(SpawnX, SpawnY, SpawnZ)
SendMessageSuccess( Player, "Returned to world spawn" )
end
World:ChunkStay({{SpawnX/16, SpawnZ/16}}, OnChunkAvailable, OnAllChunksAvaliable)
end
return true
end
function HandleSetSpawnCommand(Split, Player)
local WorldIni = cIniFile()
WorldIni:ReadFile(Player:GetWorld():GetIniFileName())
local PlayerX = Player:GetPosX()
local PlayerY = Player:GetPosY()
local PlayerZ = Player:GetPosZ()
WorldIni:DeleteValue("SpawnPosition", "X")
WorldIni:DeleteValue("SpawnPosition", "Y")
WorldIni:DeleteValue("SpawnPosition", "Z")
WorldIni:SetValue("SpawnPosition", "X", PlayerX)
WorldIni:SetValue("SpawnPosition", "Y", PlayerY)
WorldIni:SetValue("SpawnPosition", "Z", PlayerZ)
WorldIni:WriteFile(Player:GetWorld():GetIniFileName())
SendMessageSuccess( Player, string.format("Changed spawn position to [X:%i Y:%i Z:%i]", PlayerX, PlayerY, PlayerZ) )
return true
end
| apache-2.0 |
matthewhesketh/mattata | plugins/movies.lua | 2 | 2736 | --[[
Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com>
This code is licensed under the MIT. See LICENSE for details.
]]
local movies = {}
local mattata = require('mattata')
local https = require('ssl.https')
local http = require('socket.http')
local url = require('socket.url')
local json = require('dkjson')
function movies:init(configuration)
movies.commands = mattata.commands(self.info.username):command('movies?'):command('imdb'):command('films?').table
movies.help = '/movie <query> - Searches IMDb for the given search query and returns the most relevant result(s). Aliases: /imdb, /film.'
movies.key = configuration.keys.movies
movies.url = string.format('http://www.omdbapi.com/?apikey=%s&page=1&s=', movies.key.omdb)
end
function movies.on_message(_, message, _, language)
local input = mattata.input(message.text)
if not input then
return mattata.send_reply(message, movies.help)
end
local jstr_search, res_search = http.request(movies.url .. url.escape(input))
if res_search ~= 200 then
return mattata.send_reply(message, language.errors.connection)
end
local jdat_search = json.decode(jstr_search)
if jdat_search.Response ~= 'True' then
return mattata.send_reply(message, language.errors.results)
end
local jstr, res = http.request('http://www.omdbapi.com/?i=' .. jdat_search.Search[1].imdbID .. '&r=json&tomatoes=true&apikey=' .. movies.key.omdb)
if res ~= 200 then
return false
end
local jdat = json.decode(jstr)
if jdat.Response ~= 'True' then
return false
end
local poster
poster, res = https.request('https://www.myapifilms.com/imdb/idIMDB?idIMDB=' .. jdat.imdbID .. '&token=' .. movies.key.poster)
if res == 200 then
poster = json.decode(poster)
if not poster.error and poster.data.movies[1].urlPoster then
poster = poster.data.movies[1].urlPoster:gsub('(U%a%d*)(_%a%a%d,%d,%d*)(,%d*)', '%10%20%30')
end
else -- We'll set it to a placeholder image I've already got stored on Telegram's servers, we can always update this.
poster = 'AgACAgQAAx0CVClmWQACHGNe-VQxIvsfNMOn5jJceOVhfc4llQACpLAxG0qiyFNNvPCVaco5ZKoWdiNdAAMBAAMCAAN5AAOqagEAARoE'
end
local output = string.format('<a href="https://imdb.com/title/%s">%s</a> (%s)\n%s/10 | %s | %s\n\n<em>%s</em>', jdat_search.Search[1].imdbID, mattata.escape_html(jdat.Title), jdat.Year, jdat.imdbRating, jdat.Runtime, jdat.Genre, mattata.escape_html(jdat.Plot))
if not poster or not output then
return mattata.send_reply(message, language.errors.results)
end
return mattata.send_photo(message.chat.id, poster, output, 'html', false)
end
return movies | mit |
CrazyEddieTK/Zero-K | LuaRules/Configs/tactical_ai_defs.lua | 2 | 33450 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function Union(t1, t2)
local ret = {}
for i, v in pairs(t1) do
ret[i] = v
end
for i, v in pairs(t2) do
ret[i] = v
end
return ret
end
local function NameToDefID(nameTable)
local defTable = {}
for _,unitName in pairs(nameTable) do
local ud = UnitDefNames[unitName]
if ud then
defTable[ud.id] = true
end
end
return defTable
end
local function SetMinus(set, exclusion)
local copy = {}
for i,v in pairs(set) do
if not exclusion[i] then
copy[i] = v
end
end
return copy
end
-- general arrays
local allGround = {}
local allMobileGround = {}
local armedLand = {}
for name,data in pairs(UnitDefNames) do
if not data.canfly then
allGround[data.id] = true
if data.canAttack and data.weapons[1] and data.weapons[1].onlyTargets.land then
armedLand[data.id] = true
end
if not data.isImmobile then
allMobileGround[data.id] = true
end
end
end
---------------------------------------------------------------------------
-- swarm arrays
---------------------------------------------------------------------------
-- these are not strictly required they just help with inputting the units
local longRangeSwarmieeArray = NameToDefID({
"tankarty",
"jumparty",
"spiderskirm",
"shieldskirm",
"shiparty",
"cloakarty",
"shiparty",
})
local medRangeSwarmieeArray = NameToDefID({
"cloakskirm",
"amphfloater",
"chickens",
"shipskirm",
})
local lowRangeSwarmieeArray = NameToDefID({
"shieldassault",
"spiderassault",
"vehassault",
"cloakassault",
"hoverassault",
"tankassault",
"tankheavyassault",
"spidercrabe",
"hoverarty",
"chickenr",
"chickenblobber",
"cloaksnipe", -- only worth swarming sniper at low range, too accurate otherwise.
})
medRangeSwarmieeArray = Union(medRangeSwarmieeArray,longRangeSwarmieeArray)
lowRangeSwarmieeArray = Union(lowRangeSwarmieeArray,medRangeSwarmieeArray)
---------------------------------------------------------------------------
-- skirm arrays
---------------------------------------------------------------------------
-- these are not strictly required they just help with inputting the units
local veryShortRangeSkirmieeArray = NameToDefID({
"shieldscout",
"jumpassault",
"cloakheavyraid",
"cloakbomb",
"jumpscout",
"shieldbomb",
"chicken",
"chickena",
"chicken_tiamat",
"chicken_dragon",
"hoverdepthcharge",
"vehraid",
"spiderscout",
"cloakraid",
"vehscout",
})
local shortRangeSkirmieeArray = NameToDefID({
"jumpraid",
"tankraid",
"amphraid",
"jumpsumo",
"amphbomb",
"jumpbomb",
"shieldraid",
})
local riotRangeSkirmieeArray = NameToDefID({
"tankheavyraid",
"cloakriot",
"hoverraid",
"hoverscout",
"amphriot",
"striderantiheavy",
"striderdante",
"cloakaa",
"shieldaa",
"jumpaa",
"hoveraa",
"spideraa",
"amphaa",
"shipaa",
"cloakcon",
"shieldcon",
"vehcon",
"hovercon",
"tankcon",
"spidercon",
"jumpcon",
"amphcon",
"shipcon",
"cloakjammer",
"shieldshield",
"shiptorpraider",
"subraider",
})
local lowMedRangeSkirmieeArray = NameToDefID({
"cloakriot",
"hoverassault",
"spideremp",
"shieldriot",
"shieldassault",
"vehassault",
"shipscout",
"shipriot",
})
local medRangeSkirmieeArray = NameToDefID({
"spiderriot",
"cloakassault",
"amphimpulse",
"spiderassault",
"vehriot",
"hoverriot",
"shieldfelon",
"tankassault",
"tankheavyassault",
"tankriot", -- banisher
"striderscorpion",
"shipassault",
})
for name, data in pairs(UnitDefNames) do -- add all comms to mid ranged skirm because they might be short ranged (and also explode)
if data.customParams.commtype then
medRangeSkirmieeArray[data.id] = true
end
end
local longRangeSkirmieeArray = NameToDefID({
"cloakskirm",
"jumpskirm",
"amphfloater",
"hoverskirm", -- hover janus
"vehcapture",
"chickenc",
"striderbantha",
"turretlaser",
"turretriot",
"turretemp",
})
local artyRangeSkirmieeArray = NameToDefID({
"spiderskirm",
"shieldskirm",
"vehsupport",
"amphassault",
"chicken_sporeshooter",
"turretmissile",
"turretheavylaser",
"turretgauss",
"turretheavy",
"striderdetriment",
"ampharty",
"shipskirm",
})
local slasherSkirmieeArray = NameToDefID({
"jumpsumo",
"striderdante",
"cloakriot",
"hoverassault",
"shieldriot",
"shieldassault",
"spiderriot",
"cloakassault",
"spiderassault",
"vehassault",
"vehriot",
"hoverriot",
"tankriot",
"shieldfelon",
"tankassault",
"cloakskirm",
"turretgauss",
"turretlaser",
"turretriot",
"turretemp",
})
-- Nested union so long ranged things also skirm the things skirmed by short ranged things
shortRangeSkirmieeArray = Union(shortRangeSkirmieeArray,veryShortRangeSkirmieeArray)
riotRangeSkirmieeArray = Union(riotRangeSkirmieeArray,shortRangeSkirmieeArray)
lowMedRangeSkirmieeArray = Union(lowMedRangeSkirmieeArray, riotRangeSkirmieeArray)
medRangeSkirmieeArray = Union(medRangeSkirmieeArray, lowMedRangeSkirmieeArray)
longRangeSkirmieeArray = Union(longRangeSkirmieeArray, medRangeSkirmieeArray)
artyRangeSkirmieeArray = Union(artyRangeSkirmieeArray, longRangeSkirmieeArray)
---------------------------------------------------------------------------
-- Explosion avoidance
---------------------------------------------------------------------------
local veryShortRangeExplodables = NameToDefID({
"energywind",
"staticmex",
})
local shortRangeExplodables = NameToDefID({
"energywind",
"staticmex",
"turretriot",
"energypylon",
})
local diverExplodables = NameToDefID({
"energypylon",
})
local medRangeExplodables = NameToDefID({
"energyfusion", -- don't suicide vs fusions if possible.
"energygeo",
"energysingu", -- same with singu, at least to make an effort for survival.
"energyheavygeo",
"striderbantha", -- striderbanthas also have a fairly heavy but dodgeable explosion.
})
for name, data in pairs(UnitDefNames) do -- avoid factory death explosions.
if string.match(name, "factory") or string.match(name, "hub") then
shortRangeExplodables[data.id] = true
medRangeExplodables[data.id] = true
end
end
-- Notably, this occurs after the skirm nested union
veryShortRangeSkirmieeArray = Union(veryShortRangeSkirmieeArray, veryShortRangeExplodables)
local diverSkirmieeArray = Union(shortRangeSkirmieeArray, diverExplodables)
shortRangeSkirmieeArray = Union(shortRangeSkirmieeArray, shortRangeExplodables)
riotRangeSkirmieeArray = Union(riotRangeSkirmieeArray, shortRangeExplodables)
lowMedRangeSkirmieeArray = Union(lowMedRangeSkirmieeArray, medRangeExplodables)
medRangeSkirmieeArray = Union(medRangeSkirmieeArray, medRangeExplodables)
longRangeSkirmieeArray = Union(longRangeSkirmieeArray, medRangeExplodables)
artyRangeSkirmieeArray = Union(artyRangeSkirmieeArray, medRangeExplodables)
-- Stuff that mobile AA skirms
local skirmableAir = NameToDefID({
"gunshipbomb",
"gunshipemp",
"gunshipraid",
"gunshipskirm",
"gunshipheavyskirm",
"gunshipassault",
"gunshipheavytrans",
"gunshipkrow",
})
-- Brawler, for AA to swarm.
local brawler = NameToDefID({
"gunshipheavyskirm",
})
-- Things that are fled by some things
local fleeables = NameToDefID({
"turretlaser",
"turretriot",
"turretemp",
"turretimpulse",
"armcom",
"armadvcom",
"corcom",
"coradvcom",
"cloakriot",
"cloakassault",
"spideremp",
"spiderriot",
"shieldriot",
"vehriot",
"vehcapture",
"hoverriot", -- mumbo
"shieldfelon",
"jumpsumo",
})
-- Submarines to be fled by some things
local subfleeables = NameToDefID({
"subraider",
})
-- Some short ranged units dive everything that they don't skirm or swarm.
local shortRangeDiveArray = SetMinus(SetMinus(allGround, diverSkirmieeArray), lowRangeSwarmieeArray)
-- waterline(defaults to 0): Water level at which the unit switches between land and sea behaviour
-- sea: table of behaviour for sea. Note that these tables are optional.
-- land: table of behaviour for land
-- weaponNum(defaults to 1): Weapon to use when skirming
-- searchRange(defaults to 800): max range of GetNearestEnemy for the unit.
-- defaultAIState (defaults in config): (1 or 0) state of AI when unit is initialised
-- externallyHandled (defaults to nil): Enable to disable all tactical AI handling, only the state toggle is added.
--*** skirms(defaults to empty): the table of units that this unit will attempt to keep at max range
-- skirmEverything (defaults to false): Skirms everything (does not skirm radar with this enabled only)
-- skirmLeeway (defaults to 0): (Weapon range - skirmLeeway) = distance that the unit will try to keep from units while skirming
-- stoppingDistance (defaults to 0): (skirmLeeway - stoppingDistance) = max distance from target unit that move commands can be given while skirming
-- skirmRadar (defaults to false): Skirms radar dots
-- skirmOnlyNearEnemyRange (defaults to false): If true, skirms only when the enemy unit is withing enemyRange + skirmOnlyNearEnemyRange
-- skirmOrderDis (defaults in config): max distance the move order is from the unit when skirming
-- skirmKeepOrder (defaults to false): If true the unit does not clear its move order when too far away from the unit it is skirming.
-- velocityPrediction (defaults in config): number of frames of enemy velocity prediction for skirming and fleeing
-- selfVelocityPrediction (defaults to false): Whether the unit predicts its own velocity when calculating range.
-- reloadSkirmLeeway (defaults to false): Increase skirm range by reloadSkirmLeeway*remainingReloadFrames when reloading.
-- skirmBlockedApproachFrames (defaults to false): Stop skirming after this many frames of being fully reloaded if not set to attack move.
--*** swarms(defaults to empty): the table of units that this unit will jink towards and strafe
-- maxSwarmLeeway (defaults to Weapon range): (Weapon range - maxSwarmLeeway) = Max range that the unit will begin strafing targets while swarming
-- minSwarmLeeway (defaults to Weapon range): (Weapon range - minSwarmLeeway) = Range that the unit will attempt to move further away from the target while swarming
-- jinkTangentLength (default in config): component of jink vector tangent to direction to enemy
-- jinkParallelLength (default in config): component of jink vector parallel to direction to enemy
-- circleStrafe (defaults to false): when set to true the unit will run all around the target unit, false will cause the unit to jink back and forth
-- minCircleStrafeDistance (default in config): (weapon range - minCircleStrafeDistance) = distance at which the circle strafer will attempt to move away from target
-- strafeOrderLength (default in config): length of move order while strafing
-- swarmLeeway (defaults to 50): adds to enemy range when swarming
-- swarmEnemyDefaultRange (defaults to 800): range of the enemy used if it cannot be seen.
-- alwaysJinkFight (defaults to false): If enabled the unit with jink whenever it has a fight command
-- localJinkOrder (defaults in config): Causes move commands to be given near the unit, otherwise given next to opponent
--*** flees(defaults to empty): the table of units that this unit will flee like the coward it is!!!
-- fleeCombat (defaults to false): if true will flee everything without catergory UNARMED
-- fleeLeeway (defaults to 100): adds to enemy range when fleeing
-- fleeDistance (defaults to 100): unit will flee to enemy range + fleeDistance away from enemy
-- fleeRadar (defaults to false): does the unit flee radar dots?
-- minFleeRange (defaults to 0): minumun range at which the unit will flee, will flee at higher range if the attacking unit outranges it
-- fleeOrderDis (defaults to 120): max distance the move order is from the unit when fleeing
--*** hugs(defaults to empty): the table of units to close range with.
-- hugRange (default in config): Range to close to
--*** fightOnlyUnits(defaults to empty): the table of units that the unit will only interact with when it has a fight command. No AI invoked with manual attack or leashing.
--*** fightOnlyOverride(defaults to empty): Table tbat overrides parameters when fighting fight only units.
local ENABLE_OLD_JINK_STRAFE = false
--- Array loaded into gadget
local behaviourDefaults = {
defaultState = 1,
defaultJinkTangentLength = 80,
defaultJinkParallelLength = 200,
defaultStrafeOrderLength = 100,
defaultMinCircleStrafeDistance = 40,
defaultLocalJinkOrder = true,
defaultSkirmOrderDis = 120,
defaultVelocityPrediction = 30,
defaultHugRange = 50,
}
local behaviourConfig = {
-- swarmers
["cloakbomb"] = {
skirms = {},
swarms = lowRangeSwarmieeArray,
flees = {},
circleStrafe = ENABLE_OLD_JINK_STRAFE,
maxSwarmLeeway = 40,
jinkTangentLength = 100,
minCircleStrafeDistance = 0,
minSwarmLeeway = 100,
swarmLeeway = 30,
alwaysJinkFight = true,
},
["shieldbomb"] = {
skirms = {},
swarms = lowRangeSwarmieeArray,
flees = {},
circleStrafe = ENABLE_OLD_JINK_STRAFE,
maxSwarmLeeway = 40,
jinkTangentLength = 100,
minCircleStrafeDistance = 0,
minSwarmLeeway = 100,
swarmLeeway = 30,
alwaysJinkFight = true,
},
["amphbomb"] = {
skirms = {},
swarms = lowRangeSwarmieeArray,
flees = {},
circleStrafe = ENABLE_OLD_JINK_STRAFE,
maxSwarmLeeway = 40,
jinkTangentLength = 100,
minCircleStrafeDistance = 0,
minSwarmLeeway = 100,
swarmLeeway = 30,
alwaysJinkFight = true,
},
["jumpscout"] = {
skirms = {},
swarms = lowRangeSwarmieeArray,
flees = {},
localJinkOrder = false,
circleStrafe = ENABLE_OLD_JINK_STRAFE,
minCircleStrafeDistance = 170,
maxSwarmLeeway = 170,
jinkTangentLength = 100,
minSwarmLeeway = 100,
swarmLeeway = 200,
},
["cloakraid"] = {
skirms = veryShortRangeSkirmieeArray,
swarms = lowRangeSwarmieeArray,
flees = {},
fightOnlyUnits = veryShortRangeExplodables,
circleStrafe = ENABLE_OLD_JINK_STRAFE,
maxSwarmLeeway = 35,
swarmLeeway = 50,
skirmLeeway = 10,
jinkTangentLength = 140,
stoppingDistance = 10,
},
["spiderscout"] = {
skirms = veryShortRangeSkirmieeArray,
swarms = lowRangeSwarmieeArray,
flees = fleeables,
fightOnlyUnits = veryShortRangeExplodables,
circleStrafe = ENABLE_OLD_JINK_STRAFE,
skirmLeeway = 5,
maxSwarmLeeway = 5,
swarmLeeway = 30,
stoppingDistance = 0,
strafeOrderLength = 100,
minCircleStrafeDistance = 20,
fleeLeeway = 150,
fleeDistance = 150,
},
["vehscout"] = {
skirms = veryShortRangeSkirmieeArray,
swarms = lowRangeSwarmieeArray,
flees = fleeables,
fightOnlyUnits = veryShortRangeExplodables,
fightOnlyOverride = {
skirms = veryShortRangeSkirmieeArray,
swarms = lowRangeSwarmieeArray,
flees = fleeables,
skirmLeeway = 40,
skirmOrderDis = 30,
stoppingDistance = 30,
},
circleStrafe = ENABLE_OLD_JINK_STRAFE,
skirmLeeway = 15,
strafeOrderLength = 180,
maxSwarmLeeway = 40,
swarmLeeway = 40,
stoppingDistance = 25,
minCircleStrafeDistance = 50,
fleeLeeway = 100,
fleeDistance = 150,
},
-- longer ranged swarmers
["shieldraid"] = {
skirms = shortRangeSkirmieeArray,
swarms = lowRangeSwarmieeArray,
flees = {},
fightOnlyUnits = shortRangeExplodables,
circleStrafe = ENABLE_OLD_JINK_STRAFE,
maxSwarmLeeway = 35,
swarmLeeway = 30,
jinkTangentLength = 140,
stoppingDistance = 10,
minCircleStrafeDistance = 10,
velocityPrediction = 30,
},
["amphraid"] = {
waterline = -5,
land = {
weaponNum = 1,
skirms = shortRangeSkirmieeArray,
swarms = lowRangeSwarmieeArray,
flees = {},
fightOnlyUnits = shortRangeExplodables,
circleStrafe = ENABLE_OLD_JINK_STRAFE,
maxSwarmLeeway = 35,
swarmLeeway = 30,
jinkTangentLength = 140,
stoppingDistance = 25,
minCircleStrafeDistance = 10,
velocityPrediction = 30,
},
sea = {
weaponNum = 2,
skirms = shortRangeSkirmieeArray,
swarms = lowRangeSwarmieeArray,
flees = {},
fightOnlyUnits = shortRangeExplodables,
circleStrafe = ENABLE_OLD_JINK_STRAFE,
maxSwarmLeeway = 35,
swarmLeeway = 30,
jinkTangentLength = 140,
stoppingDistance = 25,
minCircleStrafeDistance = 10,
velocityPrediction = 30,
},
},
["vehraid"] = {
skirms = diverSkirmieeArray,
swarms = lowRangeSwarmieeArray,
flees = {},
hugs = shortRangeDiveArray,
fightOnlyUnits = shortRangeExplodables,
localJinkOrder = false,
jinkTangentLength = 50,
circleStrafe = ENABLE_OLD_JINK_STRAFE,
strafeOrderLength = 100,
minCircleStrafeDistance = 260,
maxSwarmLeeway = 0,
minSwarmLeeway = 100,
swarmLeeway = 300,
skirmLeeway = 10,
stoppingDistance = 8,
},
["hoverscout"] = {
skirms = shortRangeSkirmieeArray,
swarms = lowRangeSwarmieeArray,
flees = {},
fightOnlyUnits = shortRangeExplodables,
circleStrafe = ENABLE_OLD_JINK_STRAFE,
strafeOrderLength = 180,
maxSwarmLeeway = 40,
swarmLeeway = 40,
stoppingDistance = 8,
skirmOrderDis = 150,
},
["hoverraid"] = {
skirms = shortRangeSkirmieeArray,
swarms = lowRangeSwarmieeArray,
flees = {},
fightOnlyUnits = shortRangeExplodables,
circleStrafe = ENABLE_OLD_JINK_STRAFE,
strafeOrderLength = 180,
maxSwarmLeeway = 40,
swarmLeeway = 40,
stoppingDistance = 8,
skirmOrderDis = 150,
},
["jumpraid"] = {
skirms = shortRangeSkirmieeArray,
swarms = lowRangeSwarmieeArray,
flees = {},
fightOnlyUnits = shortRangeExplodables,
circleStrafe = ENABLE_OLD_JINK_STRAFE,
maxSwarmLeeway = 100,
minSwarmLeeway = 200,
swarmLeeway = 30,
stoppingDistance = 8,
velocityPrediction = 20
},
["tankraid"] = {
skirms = medRangeSkirmieeArray,
swarms = medRangeSwarmieeArray,
flees = {},
fightOnlyUnits = shortRangeExplodables,
circleStrafe = ENABLE_OLD_JINK_STRAFE,
maxSwarmLeeway = 40,
swarmLeeway = 30,
stoppingDistance = 8,
reloadSkirmLeeway = 1.2,
skirmOrderDis = 150,
},
["tankheavyraid"] = {
skirms = shortRangeSkirmieeArray,
swarms = lowRangeSwarmieeArray,
flees = {},
fightOnlyUnits = shortRangeExplodables,
circleStrafe = ENABLE_OLD_JINK_STRAFE,
strafeOrderLength = 180,
maxSwarmLeeway = 40,
swarmLeeway = 50,
stoppingDistance = 15,
skirmOrderDis = 150,
},
["amphimpulse"] = {
skirms = riotRangeSkirmieeArray,
swarms = lowRangeSwarmieeArray,
flees = {},
fightOnlyUnits = shortRangeExplodables,
circleStrafe = ENABLE_OLD_JINK_STRAFE,
maxSwarmLeeway = 40,
skirmLeeway = 30,
minCircleStrafeDistance = 10,
velocityPrediction = 20
},
["shiptorpraider"] = {
skirms = shortRangeSkirmieeArray,
swarms = lowRangeSwarmieeArray,
flees = {},
fightOnlyUnits = shortRangeExplodables,
circleStrafe = ENABLE_OLD_JINK_STRAFE,
maxSwarmLeeway = 40,
swarmLeeway = 30,
stoppingDistance = 8,
skirmOrderDis = 200,
velocityPrediction = 90,
},
-- could flee subs but isn't fast enough for it to be useful
["shipriot"] = {
skirms = diverSkirmieeArray,
swarms = lowRangeSwarmieeArray,
flees = {},
hugs = shortRangeDiveArray,
fightOnlyUnits = shortRangeExplodables,
localJinkOrder = false,
jinkTangentLength = 50,
circleStrafe = ENABLE_OLD_JINK_STRAFE,
strafeOrderLength = 100,
minCircleStrafeDistance = 260,
maxSwarmLeeway = 0,
minSwarmLeeway = 100,
swarmLeeway = 300,
skirmLeeway = 10,
stoppingDistance = 8,
},
-- riots
["cloakriot"] = {
skirms = riotRangeSkirmieeArray,
swarms = {},
flees = {},
fightOnlyUnits = shortRangeExplodables,
maxSwarmLeeway = 0,
skirmLeeway = 20,
velocityPrediction = 20
},
["spiderriot"] = {
skirms = lowMedRangeSkirmieeArray,
swarms = {},
flees = {},
fightOnlyUnits = medRangeExplodables,
maxSwarmLeeway = 0,
skirmLeeway = 0,
velocityPrediction = 20
},
["spideremp"] = {
skirms = riotRangeSkirmieeArray,
swarms = lowRangeSwarmieeArray,
flees = {},
fightOnlyUnits = shortRangeExplodables,
circleStrafe = ENABLE_OLD_JINK_STRAFE,
maxSwarmLeeway = 40,
skirmLeeway = 30,
minCircleStrafeDistance = 10,
velocityPrediction = 20
},
["shieldriot"] = {
skirms = riotRangeSkirmieeArray,
swarms = {},
flees = {},
fightOnlyUnits = shortRangeExplodables,
maxSwarmLeeway = 0,
skirmLeeway = 50,
velocityPrediction = 20
},
["vehriot"] = {
skirms = lowMedRangeSkirmieeArray,
swarms = {},
flees = {},
fightOnlyUnits = medRangeExplodables,
maxSwarmLeeway = 0,
skirmLeeway = -30,
stoppingDistance = 5
},
["shieldfelon"] = {
skirms = medRangeSkirmieeArray,
swarms = medRangeSwarmieeArray,
flees = {},
fightOnlyUnits = medRangeExplodables,
maxSwarmLeeway = 0,
skirmLeeway = 50,
stoppingDistance = 5,
skirmBlockedApproachFrames = 40,
},
["hoverriot"] = {
skirms = lowMedRangeSkirmieeArray,
swarms = lowRangeSwarmieeArray,
flees = {},
fightOnlyUnits = medRangeExplodables,
maxSwarmLeeway = 0,
skirmLeeway = -30,
stoppingDistance = 5,
skirmBlockedApproachFrames = 40,
},
["tankriot"] = {
skirms = medRangeSkirmieeArray,
swarms = {},
flees = {},
fightOnlyUnits = medRangeExplodables,
maxSwarmLeeway = 0,
skirmOrderDis = 220,
skirmLeeway = -30,
reloadSkirmLeeway = 2,
stoppingDistance = 10
},
["amphriot"] = {
waterline = -5,
land = {
weaponNum = 1,
skirms = riotRangeSkirmieeArray,
swarms = {},
flees = {},
fightOnlyUnits = shortRangeExplodables,
circleStrafe = ENABLE_OLD_JINK_STRAFE,
maxSwarmLeeway = 40,
skirmLeeway = 30,
minCircleStrafeDistance = 10,
},
sea = {
weaponNum = 2,
skirms = riotRangeSkirmieeArray,
swarms = {},
flees = {},
fightOnlyUnits = shortRangeExplodables,
circleStrafe = ENABLE_OLD_JINK_STRAFE,
maxSwarmLeeway = 40,
skirmLeeway = 30,
minCircleStrafeDistance = 10,
},
},
["ampharty"] = {
waterline = -5,
land = {
weaponNum = 1,
skirms = artyRangeSkirmieeArray,
swarms = {},
flees = {},
fightOnlyUnits = medRangeExplodables,
skirmRadar = true,
maxSwarmLeeway = 10,
minSwarmLeeway = 130,
skirmLeeway = 40,
},
sea = {
weaponNum = 2,
skirms = medRangeSkirmieeArray,
swarms = {},
flees = {},
fightOnlyUnits = medRangeExplodables,
skirmRadar = true,
maxSwarmLeeway = 10,
minSwarmLeeway = 130,
skirmLeeway = 40,
},
},
["shipscout"] = { -- scout boat
skirms = lowMedRangeSkirmieeArray,
swarms = lowRangeSwarmieeArray,
flees = subfleeables,
circleStrafe = ENABLE_OLD_JINK_STRAFE,
maxSwarmLeeway = 40,
swarmLeeway = 30,
stoppingDistance = 8,
skirmLeeway = 100,
skirmOrderDis = 200,
velocityPrediction = 90,
fleeLeeway = 250,
fleeDistance = 300,
},
["shipassault"] = {
skirms = lowMedRangeSkirmieeArray,
swarms = {},
flees = {},
fightOnlyUnits = medRangeExplodables,
maxSwarmLeeway = 0,
skirmLeeway = -30,
stoppingDistance = 5
},
["hoverdepthcharge"] = {
skirms = {},
swarms = {},
flees = {},
skirmEverything = true,
skirmLeeway = 200,
skirmOrderDis = 180,
reloadSkirmLeeway = 2,
},
--assaults
["cloakassault"] = {
skirms = lowMedRangeSkirmieeArray,
swarms = medRangeSwarmieeArray,
flees = {},
fightOnlyUnits = medRangeExplodables,
maxSwarmLeeway = 30,
minSwarmLeeway = 90,
skirmLeeway = 20,
},
["shieldassault"] = {
skirms = riotRangeSkirmieeArray,
swarms = medRangeSwarmieeArray,
flees = {},
fightOnlyUnits = shortRangeExplodables,
maxSwarmLeeway = 50,
minSwarmLeeway = 120,
skirmLeeway = 40,
},
["spiderassault"] = {
skirms = medRangeSkirmieeArray,
swarms = medRangeSwarmieeArray,
flees = {},
fightOnlyUnits = medRangeExplodables,
maxSwarmLeeway = 50,
minSwarmLeeway = 120,
skirmLeeway = 40,
},
["shipraider"] = {
skirms = riotRangeSkirmieeArray,
swarms = lowRangeSwarmieeArray,
flees = {},
fightOnlyUnits = shortRangeExplodables,
maxSwarmLeeway = 30,
minSwarmLeeway = 90,
skirmLeeway = 60,
},
["vehassault"] = {
skirms = riotRangeSkirmieeArray,
swarms = {},
flees = {},
fightOnlyUnits = shortRangeExplodables,
maxSwarmLeeway = 50,
minSwarmLeeway = 120,
skirmLeeway = 40,
},
["tankassault"] = {
skirms = lowMedRangeSkirmieeArray,
swarms = {},
flees = {},
fightOnlyUnits = shortRangeExplodables,
skirmOrderDis = 220,
skirmLeeway = 50,
},
-- med range skirms
["cloakskirm"] = {
skirms = Union(medRangeSkirmieeArray, NameToDefID({"turretriot"})),
swarms = medRangeSwarmieeArray,
flees = {},
fightOnlyUnits = medRangeExplodables,
maxSwarmLeeway = 30,
minSwarmLeeway = 130,
skirmLeeway = 10,
skirmBlockedApproachFrames = 40,
},
["jumpskirm"] = {
skirms = medRangeSkirmieeArray,
swarms = medRangeSwarmieeArray,
flees = {},
fightOnlyUnits = medRangeExplodables,
maxSwarmLeeway = 10,
minSwarmLeeway = 130,
skirmLeeway = 20,
skirmBlockedApproachFrames = 40,
},
["striderdante"] = {
skirms = medRangeSkirmieeArray,
swarms = {},
flees = {},
fightOnlyUnits = medRangeExplodables,
skirmLeeway = 40,
},
["amphfloater"] = {
skirms = medRangeSkirmieeArray,
swarms = medRangeSwarmieeArray,
flees = {},
maxSwarmLeeway = 30,
minSwarmLeeway = 130,
skirmLeeway = 10,
skirmBlockedApproachFrames = 40,
},
["hoverskirm"] = {
skirms = medRangeSkirmieeArray,
swarms = medRangeSwarmieeArray,
flees = {},
fightOnlyUnits = medRangeExplodables,
maxSwarmLeeway = 30,
minSwarmLeeway = 130,
skirmLeeway = 30,
skirmOrderDis = 200,
velocityPrediction = 90,
skirmBlockedApproachFrames = 60,
},
["tankheavyassault"] = {
skirms = medRangeSkirmieeArray,
swarms = {},
flees = {},
fightOnlyUnits = shortRangeExplodables,
skirmOrderDis = 220,
skirmLeeway = 50,
skirmBlockedApproachFrames = 60,
},
["gunshipskirm"] = {
skirms = medRangeSkirmieeArray,
swarms = medRangeSwarmieeArray,
flees = {},
fightOnlyUnits = medRangeExplodables,
skirmOrderDis = 120,
selfVelocityPrediction = true,
velocityPrediction = 30,
},
-- long range skirms
["jumpblackhole"] = {
skirms = longRangeSkirmieeArray,
swarms = longRangeSwarmieeArray,
flees = {},
fightOnlyUnits = medRangeExplodables,
maxSwarmLeeway = 30,
minSwarmLeeway = 130,
skirmLeeway = 20,
skirmBlockedApproachFrames = 40,
},
["shieldskirm"] = {
skirms = longRangeSkirmieeArray,
swarms = longRangeSwarmieeArray,
flees = {},
fightOnlyUnits = medRangeExplodables,
maxSwarmLeeway = 30,
minSwarmLeeway = 130,
skirmLeeway = 10,
skirmBlockedApproachFrames = 40,
},
["spiderskirm"] = {
skirms = longRangeSkirmieeArray,
swarms = longRangeSwarmieeArray,
flees = {},
fightOnlyUnits = medRangeExplodables,
maxSwarmLeeway = 10,
minSwarmLeeway = 130,
skirmLeeway = 10,
skirmBlockedApproachFrames = 40,
},
["amphassault"] = {
skirms = longRangeSkirmieeArray,
swarms = longRangeSwarmieeArray,
flees = {},
fightOnlyUnits = medRangeExplodables,
maxSwarmLeeway = 10,
minSwarmLeeway = 130,
skirmLeeway = 20,
skirmBlockedApproachFrames = 40,
},
["gunshipkrow"] = {
skirms = medRangeSkirmieeArray,
swarms = medRangeSwarmieeArray,
flees = {},
fightOnlyUnits = medRangeExplodables,
maxSwarmLeeway = 10,
minSwarmLeeway = 130,
skirmLeeway = 20,
},
["vehcapture"] = {
skirms = longRangeSkirmieeArray,
swarms = longRangeSwarmieeArray,
flees = {},
fightOnlyUnits = medRangeExplodables,
maxSwarmLeeway = 30,
minSwarmLeeway = 130,
skirmLeeway = 30,
skirmOrderDis = 200,
velocityPrediction = 60,
skirmBlockedApproachFrames = 40,
},
["shipskirm"] = {
skirms = longRangeSkirmieeArray,
swarms = longRangeSwarmieeArray,
flees = {},
fightOnlyUnits = medRangeExplodables,
maxSwarmLeeway = 30,
minSwarmLeeway = 130,
skirmLeeway = 10,
skirmOrderDis = 200,
velocityPrediction = 90,
skirmBlockedApproachFrames = 40,
},
-- weird stuff
["vehsupport"] = {
defaultAIState = 0,
skirms = slasherSkirmieeArray,
swarms = {},
flees = {},
skirmLeeway = -400,
skirmOrderDis = 700,
skirmKeepOrder = true,
velocityPrediction = 10,
skirmOnlyNearEnemyRange = 80
},
-- arty range skirms
["cloaksnipe"] = {
skirms = allMobileGround,
skirmRadar = true,
swarms = {},
flees = {},
skirmLeeway = 40,
skirmBlockedApproachFrames = 120,
},
["veharty"] = {
skirms = allMobileGround,
skirmRadar = true,
swarms = {},
flees = {},
skirmLeeway = 20,
skirmOrderDis = 200,
skirmOrderDisMin = 100, -- Make it turn around.
},
["vehheavyarty"] = {
skirms = allMobileGround,
skirmRadar = true,
swarms = {},
flees = {},
skirmLeeway = 100,
stoppingDistance = -80,
velocityPrediction = 0,
},
["tankarty"] = {
skirms = allMobileGround,
skirmRadar = true,
swarms = {},
flees = {},
skirmLeeway = 200,
skirmKeepOrder = true,
stoppingDistance = -180,
velocityPrediction = 0,
skirmOrderDis = 250,
skirmOnlyNearEnemyRange = 120,
},
["striderarty"] = {
skirms = allMobileGround,
skirmRadar = true,
swarms = {},
flees = {},
skirmLeeway = 100,
},
["cloakarty"] = {
skirms = allMobileGround,
swarms = {},
flees = {},
skirmRadar = true,
skirmLeeway = 40,
skirmBlockedApproachFrames = 40,
},
["jumparty"] = {
skirms = allMobileGround,
swarms = {},
flees = {},
skirmRadar = true,
maxSwarmLeeway = 10,
minSwarmLeeway = 130,
skirmLeeway = 20,
},
["shieldarty"] = {
skirms = Union(artyRangeSkirmieeArray, skirmableAir),
swarms = {},
flees = {},
fightOnlyUnits = medRangeExplodables,
skirmRadar = true,
maxSwarmLeeway = 10,
minSwarmLeeway = 130,
skirmLeeway = 150,
},
["hoverarty"] = {
skirms = allMobileGround,
swarms = {},
flees = {},
skirmRadar = true,
skirmKeepOrder = true,
skirmLeeway = 150,
skirmOrderDis = 200,
stoppingDistance = -100,
velocityPrediction = 0,
},
["striderbantha"] = {
skirms = allMobileGround,
swarms = {},
flees = {},
skirmRadar = true,
skirmLeeway = 120,
},
["shiparty"] = {
skirms = allMobileGround,
swarms = {},
flees = {},
skirmRadar = true,
maxSwarmLeeway = 10,
minSwarmLeeway = 130,
skirmLeeway = 40,
},
-- cowardly support units
--[[
["example"] = {
skirms = {},
swarms = {},
flees = {},
fleeCombat = true,
fleeLeeway = 100,
fleeDistance = 100,
minFleeRange = 500,
},
--]]
-- support
["cloakjammer"] = {
skirms = {},
swarms = {},
flees = armedLand,
fleeLeeway = 100,
fleeDistance = 100,
minFleeRange = 400,
},
["shieldshield"] = {
skirms = {},
swarms = {},
flees = armedLand,
fleeLeeway = 100,
fleeDistance = 100,
minFleeRange = 450,
},
-- mobile AA
["cloakaa"] = {
skirms = skirmableAir,
swarms = brawler,
flees = armedLand,
fleeLeeway = 100,
fleeDistance = 100,
minFleeRange = 500,
skirmLeeway = 150,
swarmLeeway = 250,
minSwarmLeeway = 300,
maxSwarmLeeway = 200,
},
["shieldaa"] = {
skirms = skirmableAir,
swarms = brawler,
flees = armedLand,
minSwarmLeeway = 500,
fleeLeeway = 100,
fleeDistance = 100,
minFleeRange = 500,
skirmLeeway = 50,
},
["vehaa"] = {
skirms = skirmableAir,
swarms = brawler,
flees = armedLand,
minSwarmLeeway = 100,
strafeOrderLength = 180,
fleeLeeway = 100,
fleeDistance = 100,
minFleeRange = 500,
skirmLeeway = 50,
},
["jumpaa"] = {
skirms = skirmableAir,
swarms = brawler,
flees = armedLand,
minSwarmLeeway = 300,
fleeLeeway = 100,
fleeDistance = 100,
minFleeRange = 500,
skirmLeeway = 50,
},
["hoveraa"] = {
skirms = skirmableAir,
swarms = brawler,
flees = armedLand,
minSwarmLeeway = 100,
fleeLeeway = 100,
fleeDistance = 100,
minFleeRange = 500,
skirmLeeway = 50,
skirmOrderDis = 200,
},
["spideraa"] = {
skirms = skirmableAir,
swarms = brawler,
flees = armedLand,
minSwarmLeeway = 300,
fleeLeeway = 100,
fleeDistance = 100,
minFleeRange = 500,
skirmLeeway = 50,
},
["tankaa"] = {
skirms = skirmableAir,
swarms = brawler,
flees = armedLand,
minSwarmLeeway = 100,
fleeLeeway = 100,
fleeDistance = 100,
minFleeRange = 500,
skirmLeeway = 50,
skirmOrderDis = 200,
},
["amphaa"] = {
skirms = skirmableAir,
swarms = brawler,
flees = armedLand,
fleeLeeway = 100,
fleeDistance = 100,
minFleeRange = 500,
skirmLeeway = 50,
skirmOrderDis = 200,
},
["gunshipaa"] = {
skirms = skirmableAir,
swarms = brawler,
flees = armedLand,
minSwarmLeeway = 100,
fleeLeeway = 100,
fleeDistance = 100,
minFleeRange = 500,
skirmLeeway = 50,
skirmOrderDis = 200,
},
["shipaa"] = {
skirms = skirmableAir,
swarms = {},
flees = {},
skirmRadar = true,
maxSwarmLeeway = 10,
minSwarmLeeway = 130,
skirmLeeway = 40,
},
-- chickens
["chicken_tiamat"] = {
skirms = {},
swarms = {},
flees = {},
hugs = allGround,
hugRange = 100,
},
["chicken_dragon"] = {
skirms = {},
swarms = {},
flees = {},
hugs = allGround,
hugRange = 150,
},
["chickenlandqueen"] = {
skirms = {},
swarms = {},
flees = {},
hugs = allGround,
hugRange = 150,
},
-- Externally handled units
["energysolar"] = {
externallyHandled = true,
},
}
return behaviourConfig, behaviourDefaults
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
CrazyEddieTK/Zero-K | LuaUI/Configs/clippy.lua | 13 | 4709 | local THRESHOLD_EXPENSIVE = 1200
INCOME_TO_SPLURGE = 20 -- ignore expensive warning if you have this much income
METAL_PER_NANO = 8 -- suggested nanos per metal ^ -1
MIN_PULL_FOR_NANOS = -10 -- don't make more nanos if our pull is already this low --unused
NANO_DEF_ID = UnitDefNames.staticcon.id
ENERGY_TO_METAL_RATIO = 6 -- suggested maximum for energy
ENERGY_LOW_THRESHOLD = 200
DEFENSE_QUOTA = 0.4 -- suggested maximum proportion of total assets that is defense
RANK_LIMIT = 3
DELAY_BETWEEN_FACS = 5*60*30 -- gameframes
--seconds
TIMER_EXPENSIVE_UNITS = 60 * 10
TIMER_ADV_FACTORY = 60 * 6
TIMER_SUPERWEAPON = 60 * 10
TIMER_HYPERWEAPON = 60 * 20
tips = {
nano_excess = {str = {"We already have plenty of\nCaretakers. We should get more\nresources before building more."}, life = 9, cooldown = 20},
expensive_unit = {str = {"Boss, I'm not sure\nwe can afford that at\nthis stage of the game.",
"Sir, I don't think that\nunit is in our price\nrange right now."}, life = 9, cooldown = 20, verbosity = 2},
superweapon = {str = {"A superweapon now?\nThat may not be\nsuch a good idea."}, life = 7, cooldown = 60},
adv_factory = {str = {"Are you sure that's\na good starting\nfac, chief?"}, life = 7, cooldown = 60},
retreat_repair = {str = {"Getting shot up!\nRequesting permission\nto pull out, sir!",
"Get me out of here!\nI need repairs!",}, life = 7, cooldown = 20},
energy_excess = {str = {"I think we've got\nenough energy for\nnow, boss.",
"Energy storage already\nat full capacity.",
"Sir, we've got plenty\nof energy as it is."}, life = 7, cooldown = 20},
energy_deficit = {str = {"Got an energy deficit, sir.\nMore energy structures?",
"Commander, we'll soon run\nout of energy. Build more\nenergy structures."}, life = 7, cooldown = 45},
metal_excess = {str = {"Sir, we have a metal glut.\nPut some more buildpower\ninto making units.",
"Boss, we have too much metal.\nGet more of us making stuff."}, life = 7, cooldown = 30},
metal_deficit = {str = {"Running low on metal, chief.\nWe should try reclaiming\nor getting more mexes."}, life = 7, cooldown = 60, verbosity = 3},
facplop = {str = {"Remember to place your\nfirst free factory."}, life = 7, cooldown = 30},
factory_duplicate = {str = {"We already have one of\nthat factory. Remember you can\nassist it with constructors."}, life = 9, cooldown = 60},
factory_multiple = {str = {"Sir, we might not need another\nfactory so soon. You can assist your\nfirst factory with constructors."}, life = 10, cooldown = 60, verbosity = 2},
defense_excess = {str = {"Boss, we have plenty of defence.\nMight want some mobile units instead.",
"Chief, we should build mobile\nunits instead. We already\nhave plenty of defence."}, life = 9, cooldown = 20}
}
for name,data in pairs(tips) do
data.lastUsed = -10000
end
local superweaponDefs = {
"staticheavyarty",
"staticnuke",
}
local hyperweaponDefs = {
"mahlazer",
"zenith",
"raveparty",
"striderdetriment",
}
local canRetreatDefs = {
"gunshipheavyskirm",
"gunshipassault",
"gunshipkrow",
"tankassault",
"tankheavyassault",
--"tankheavyarty",
"jumpassault",
"jumpsumo",
"striderdante",
--"striderarty",
"striderscorpion",
"striderbantha",
"striderdetriment",
"shipheavyarty",
"reef",
}
local energyDefs = {
"energysolar",
"energywind",
"energyfusion",
--"energygeo",
"energysingu",
}
local defenseDefs = {
"turretlaser",
"turretmissile",
"turretriot",
"turretimpulse",
"turretheavylaser",
"turretgauss",
"turretaalaser",
"turretaaclose",
"turretaaflak",
"turretaafar",
"turretaaheavy",
"turretheavy",
"turretantiheavy",
"turrettorp",
"staticjammer",
"staticshield"
}
factoryDefs = {
"factoryship",
"striderhub",
}
for name in pairs(UnitDefNames) do
if string.find(name, "factory") then factoryDefs[#factoryDefs+1] = name end
end
--unitDefID-indexed tables
expensive_units = {}
superweapons = {}
hyperweapons = {}
commanders = {}
factories = {}
adv_factories = {}
energy = {}
defenses = {}
canRetreat = {}
for i=1,#UnitDefs do
if UnitDefs[i].customParams.commtype then commanders[i]=true
--elseif (not UnitDefs[i].canMove) and UnitDefs[i].canAttack then defenses[i]=true -- bad idea: includes superweapons
elseif UnitDefs[i].metalCost >= THRESHOLD_EXPENSIVE then expensive_units[i] = true end
end
local function CreateArray(source, target)
for i=1, #source do
local def = UnitDefNames[source[i]]
if def then target[def.id] = true end
end
end
CreateArray(superweaponDefs, superweapons)
CreateArray(hyperweaponDefs, hyperweapons)
CreateArray(canRetreatDefs, canRetreat)
CreateArray(energyDefs, energy)
CreateArray(defenseDefs, defenses)
CreateArray(factoryDefs, factories)
| gpl-2.0 |
CrazyEddieTK/Zero-K | LuaRules/Gadgets/CAI/PathfinderGenerator.lua | 9 | 13785 | --[[ Handles Pathfinding
* Use this file to create pathfinding objects with movetypes.
* This ojbect can generate paths between two points or return
false when there is no path.
* Can be passed heatmaps which weight the nodes.
--]]
---------------------------------------------------------------
-- Configuration and Localization
---------------------------------------------------------------
local ceil = math.ceil
local floor = math.floor
local max = math.max
local min = math.min
local sqrt = math.sqrt
local abs = math.abs
local MAP_WIDTH = Game.mapSizeX
local MAP_HEIGHT = Game.mapSizeZ
local MAP_WATER_DAMAGE = Game.waterDamage > 0
local PATH_SQUARE_SIZE = 256 -- Matches low resolution spring pathfinder size
local PATH_MID = PATH_SQUARE_SIZE/2
local PATH_X = ceil(MAP_WIDTH/PATH_SQUARE_SIZE)
local PATH_Z = ceil(MAP_HEIGHT/PATH_SQUARE_SIZE)
local PathfinderGenerator = {
PATH_SQUARE_SIZE = PATH_SQUARE_SIZE,
PATH_X = PATH_X,
PATH_Z = PATH_Z,
}
local DRAW_PATHMAP = false
local DRAW_FOUND_PATH = false
---------------------------------------------------------------
-- Helper local functions
---------------------------------------------------------------
local CoordToIDarray = {}
local IdToCoordarray = {}
for i = 1, PATH_X do
CoordToIDarray[i] = {}
for j = 1, PATH_Z do
IdToCoordarray[#IdToCoordarray+1] = {x = i, z = j}
CoordToIDarray[i][j] = #IdToCoordarray
end
end
local function IdToCoords(id)
return IdToCoordarray[id].x, IdToCoordarray[id].z
end
local function CoordsToID(x, z)
return CoordToIDarray[x][z]
end
local function DisSQ(x1,z1,x2,z2)
return (x1 - x2)^2 + (z1 - z2)^2
end
local function WorldToArray(x,z)
local i,j
if x < 0 then
i = 1
elseif x >= MAP_WIDTH then
i = PATH_X
else
i = ceil(x/PATH_SQUARE_SIZE)
end
if z < 0 then
j = 1
elseif z >= MAP_HEIGHT then
j = PATH_Z
else
j = ceil(z/PATH_SQUARE_SIZE)
end
return i, j
end
local function ArrayToWorld(i,j) -- gets midpoint
return i*PATH_SQUARE_SIZE - PATH_MID, j*PATH_SQUARE_SIZE - PATH_MID
end
---------------------------------------------------------------
-- astar overrides
---------------------------------------------------------------
local function astarOverride_GetDistanceEstimate(id1, id2)
local x1,z1 = IdToCoords(id1)
local x2,z2 = IdToCoords(id2)
return sqrt((x1 - x2)^2 + (z1 - z2)^2)
end
---------------------------------------------------------------
-- PathMap creation
---------------------------------------------------------------
-- Points to check around the middle of a path point for the creation of a valid point.
local checkPoints = {
{x = 0, z = 0},
{x = 64, z = 0},
{x = 0, z = 64},
{x = -64, z = 0},
{x = 0, z = -64},
{x = 64, z = 64},
{x = -64, z = -64},
{x = -64, z = 64},
{x = 64, z = -64},
{x = 100, z = 0},
{x = 0, z = 100},
{x = -100, z = 0},
{x = 0, z = -100},
{x = 100, z = 100},
{x = -100, z = -100},
{x = -100, z = 100},
{x = 100, z = -100},
}
-- local functions for modifying and checking links.
local function AddLink(point, relation, cost)
point.linkCount = point.linkCount + 1
point.linkList[point.linkCount] = {x = point.x + relation[1], z = point.z + relation[2], cost = cost}
--if relation[1] == 0 then
-- relation[1] = 0
--end
--if relation[2] == 0 then
-- relation[2] = 0
--end
if not point.linkRelationMap[relation[1]] then
point.linkRelationMap[relation[1]] = {}
end
point.linkRelationMap[relation[1]][relation[2]] = point.linkCount
end
local function UpdatePathLink(start, finish, relation, moveDef)
if moveDef then
if start.passable and finish.passable then
local sx = start.px
local sz = start.pz
local fx = finish.px
local fz = finish.pz
local myPath = Spring.RequestPath(moveDef, sx, 0, sz, fx, 0, fz, 16)
if myPath then
local waypoints = myPath:GetPathWayPoints()
if waypoints and #waypoints > 0 then
local endX = waypoints[#waypoints][1]
local endZ = waypoints[#waypoints][3]
if #waypoints <= 20 and DisSQ(endX, endZ, fx, fz) < 256 then
AddLink(start, relation, #waypoints)
AddLink(finish, {-relation[1], -relation[2]}, #waypoints)
if DRAW_PATH then
Spring.MarkerAddLine(sx, 0, sz, fx, 0, fz)
end
end
--if DisSQ(endX, endZ, fx, fz) > 256 then
-- Spring.MarkerAddPoint(fx, 0, fz, sqrt(DisSQ(endX, endZ, fx, fz)))
-- for i = 1, #waypoints do
-- local w = waypoints[i]
-- Spring.MarkerAddPoint(w[1], w[2], w[3], i)
-- end
--end
end
end
end
else
AddLink(start, relation, 1)
AddLink(finish, {-relation[1], -relation[2]}, 1)
end
end
local function CreatePathMap(pathUnitDefID, pathMoveDefName, avoidWaterDamage)
-- pathUnitDefID is an example unitDef to use to check for valid location
-- pathMoveDefName is the name of the movedef used for the path
local avoidWater = avoidWaterDamage and MAP_WATER_DAMAGE
local pathMap = {}
-- Create the positions of the path map which will be used for connection testing.
for i = 1, PATH_X do
pathMap[i] = {}
for j = 1, PATH_Z do
pathMap[i][j] = {
x = i,
z = j,
mx = i*PATH_SQUARE_SIZE - PATH_MID,
mz = j*PATH_SQUARE_SIZE - PATH_MID,
linkList = {},
linkCount = 0,
linkRelationMap = {}
}
local function IsValidUnitLocation(x, z)
return Spring.TestMoveOrder(pathUnitDefID, x, 0, z) and not (avoidWater and Spring.GetGroundHeight(x,z) < 0)
end
local point = 1
local px = checkPoints[point].x + i*PATH_SQUARE_SIZE - PATH_MID
local pz = checkPoints[point].z + j*PATH_SQUARE_SIZE - PATH_MID
while point < #checkPoints and pathUnitDefID and not IsValidUnitLocation(px,pz) do
point = point + 1
px = checkPoints[point].x + i*PATH_SQUARE_SIZE - PATH_MID
pz = checkPoints[point].z + j*PATH_SQUARE_SIZE - PATH_MID
--Spring.MarkerAddPoint(px,0,pz, "")
end
if point < #checkPoints then
pathMap[i][j].px = px
pathMap[i][j].py = Spring.GetGroundHeight(px, pz)
pathMap[i][j].pz = pz
pathMap[i][j].passable = true
else
pathMap[i][j].passable = false
end
end
end
-- Check links between points, this only checks orthagonal but could easily change.
--for i = 5, 5 do
-- for j = 5, 5 do
for i = 1, PATH_X do
for j = 1, PATH_Z do
if i < PATH_X then
UpdatePathLink(pathMap[i][j], pathMap[i+1][j], {1,0}, pathMoveDefName)
end
if j < PATH_Z then
UpdatePathLink(pathMap[i][j], pathMap[i][j+1], {0,1}, pathMoveDefName)
end
end
end
--for i = 1, PATH_X do
-- for j = 1, PATH_Z do
-- if pathMap[i][j].passable then
-- local str = ""
-- local linkList = pathMap[i][j].linkList
-- for id = 1, pathMap[i][j].linkCount do
-- str = str .. "(" .. linkList[id].x .. ", " .. linkList[id].z .. ") "
-- end
-- Spring.MarkerAddPoint(pathMap[i][j].px,0,pathMap[i][j].pz,str)
-- end
-- end
--end
return pathMap
end
---------------------------------------------------------------
-- Pathfinder object definition
---------------------------------------------------------------
function PathfinderGenerator.CreatePathfinder(pathUnitDefID, pathMoveDefName, avoidWaterDamage)
local aStar = VFS.Include("LuaRules/Gadgets/CAI/astar.lua")
local heatmapFear = false
local heatFearFactor = false
local defenseHeatmaps = {}
local defenseHeatmapCount = 0
local pathMap = CreatePathMap(pathUnitDefID, pathMoveDefName, avoidWaterDamage)
local fearSumCache = {}
-- Heatmap local functions
local function SetDefenseHeatmaps(newDefenseHeatmaps)
defenseHeatmaps = newDefenseHeatmaps
defenseHeatmapCount = #newDefenseHeatmaps
end
local function IsPositionHeatmapFeared(x,z)
if heatmapFear then
for i = 1, defenseHeatmapCount do
local heatValue = defenseHeatmaps[i].GetValueByIndex(x, z)
if heatValue >= heatmapFear then
return true
end
end
end
return false
end
local function GetHeatmapFearSum(x,z)
if fearSumCache[x] then
if fearSumCache[x][z] then
return fearSumCache[x][z]
end
else
fearSumCache[x] = {}
end
local sum = 0
for i = 1, defenseHeatmapCount do
local heatValue = defenseHeatmaps[i].GetValueByIndex(x, z)
sum = sum + heatValue
end
fearSumCache[x][z] = sum
return sum
end
-- aStar overrides
function aStar.GetNeighbors(id)
local x, z = IdToCoords(id)
local posData = pathMap[x][z]
local passable = {}
local passableCount = 0
for i = 1, posData.linkCount do
local linkData = posData.linkList[i]
local nx, nz = linkData.x, linkData.z
if not IsPositionHeatmapFeared(nx, nz) then
passableCount = passableCount + 1
passable[passableCount] = CoordsToID(nx, nz)
end
end
return passable
end
aStar.GetDistanceEstimate = astarOverride_GetDistanceEstimate
function aStar.GetDistance(id1, id2)
if heatFearFactor then
local x1, z1 = IdToCoords(id1)
local x2, z2 = IdToCoords(id2)
return 1 + (GetHeatmapFearSum(x1, z1) + GetHeatmapFearSum(x2, z2))*heatFearFactor
else
return 1
end
end
local function GetPath(startX, startZ, finishX, finishZ, newHeatmapFear, newHeatFearFactor, minWaypointDistance)
fearSumCache = {}
heatmapFear = newHeatmapFear
heatFearFactor = (newHeatFearFactor and newHeatFearFactor > 0 and newHeatFearFactor) or false
minWaypointDistance = minWaypointDistance or 1
local sx, sz = WorldToArray(startX,startZ)
local fx, fz = WorldToArray(finishX,finishZ)
--Spring.MarkerAddPoint(startX, 0, startZ, sx .. " " .. sz .. ": " .. CoordsToID(sx, sz))
--Spring.MarkerAddPoint(finishX, 0, finishZ, fx .. " " .. fz .. ": " .. CoordsToID(fx, fz))
local path = aStar.GetPath(CoordsToID(sx, sz), CoordsToID(fx, fz))
if (not path) or #path == 0 then
return false
end
--for i = 1, #path do
-- local x, z = IdToCoords(path[i])
-- local wx, wz = ArrayToWorld(x, z)
-- Spring.MarkerAddPoint(wx, 0, wz, "")
--end
-- local functions for culling the path of useless nodes
local function CheckLink(x1, z1, x2, z2, maxFear)
local dx, dz = x2 - x1, z2 - z1
local linkRelationMap = pathMap[x1][z1].linkRelationMap
local linked = linkRelationMap[dx] and linkRelationMap[dx][dz]
if linked and maxFear then
if GetHeatmapFearSum(x1, z1) > maxFear or GetHeatmapFearSum(x2, z2) > maxFear then
linked = false
end
end
--GG.TableEcho(linkRelationMap)
--Spring.Echo(dx .. " " .. dz)
--Spring.Echo((linkRelationMap[dx] and linkRelationMap[dx][dz] and "link") or "no link")
return linked
end
local function CheckDirectPath(x1, z1, x2, z2, maxFear)
local xDiff = x2 - x1
local zDiff = z2 - z1
local stepsNeeded = abs(xDiff) + abs(zDiff)
if xDiff == 0 then
if zDiff == 0 then
return true
end
zDiff = zDiff/abs(zDiff)
elseif zDiff == 0 then
xDiff = xDiff/abs(xDiff)
elseif abs(xDiff) > abs(zDiff) then
zDiff = zDiff/abs(xDiff)
xDiff = xDiff/abs(xDiff)
else
xDiff = xDiff/abs(zDiff)
zDiff = zDiff/abs(zDiff)
end
local directPath = true
local steps = 1
local x, z = x1, z1
local rx, rz = x1, z1
--Spring.Echo(xDiff .. " " .. zDiff)
while steps <= stepsNeeded do
x = x + xDiff
local newRx = floor(x + 0.5)
if newRx ~= rx then
steps = steps + 1
if (not CheckLink(rx, rz, newRx, rz, maxFear)) or IsPositionHeatmapFeared(newRx, rz) then
--local w1, w2 = ArrayToWorld(rx,rz)
--local w3, w4 = ArrayToWorld(newRx,rz)
--Spring.MarkerAddLine(w1, 0, w2, w3, 0, w4)
--Spring.MarkerAddPoint(w3, 0, w4, "bla")
directPath = false
break
end
rx = newRx
end
z = z + zDiff
local newRz = floor(z + 0.5)
if newRz ~= rz then
steps = steps + 1
if (not CheckLink(rx, rz, rx, newRz, maxFear)) or IsPositionHeatmapFeared(rx, newRz) then
--local w1, w2 = ArrayToWorld(rx,rz)
--local w3, w4 = ArrayToWorld(rx,newRz)
--Spring.MarkerAddLine(w1, 0, w2, w3, 0, w4)
--Spring.MarkerAddPoint(w3, 0, w4, "bla")
directPath = false
break
end
rz = newRz
end
end
return directPath, rx, rz
end
-- Cull the path returned by aStar
local waypoints = {}
local waypointCount = 0
local function AddWaypoint(x, z)
local pathPoint = pathMap[x][z]
local px, py, pz = pathPoint.px, pathPoint.py, pathPoint.pz
waypointCount = waypointCount + 1
waypoints[waypointCount] = {x = px, y = py, z = pz}
end
local from = 1
local fromX, fromZ = IdToCoords(path[from])
local fromFear = false
if heatFearFactor then
fromFear = GetHeatmapFearSum(fromX, fromZ)
end
local to = 1 + minWaypointDistance
while to <= #path do
local x, z = IdToCoords(path[to])
local maxFear = fromFear
if heatFearFactor then
local toFear = GetHeatmapFearSum(x, z)
if toFear < maxFear then
maxFear = toFear
end
end
local clear, rx, rz = CheckDirectPath(fromX,fromZ,x,z,maxFear)
if clear then
to = to + 1
else
from = to - 1
fromX, fromZ = IdToCoords(path[from])
local fromFear = false
if heatFearFactor then
fromFear = GetHeatmapFearSum(fromX, fromZ)
end
local toX, toZ = IdToCoords(path[from])
AddWaypoint(toX, toZ)
to = to + minWaypointDistance
--local wrx, wrz = ArrayToWorld(rx, rz)
--Spring.MarkerAddPoint(wx, 0, wz, "Path: " .. from)
--Spring.MarkerAddPoint(wrx, 0, wrz, "Blocked: " .. from)
end
end
-- Note that the final waypoint is added by CAI directly because it may want
-- the units to spread out when they reach their destination.
return waypoints, waypointCount
end
local pathMapData = {
pathMap = pathMap,
aStar = aStar,
GetPath = GetPath,
SetDefenseHeatmaps = SetDefenseHeatmaps,
}
return pathMapData
end
return PathfinderGenerator | gpl-2.0 |
CrazyEddieTK/Zero-K | units/staticjammer.lua | 5 | 2429 | unitDef = {
unitname = [[staticjammer]],
name = [[Cornea]],
description = [[Area Cloaker/Jammer]],
activateWhenBuilt = true,
buildCostMetal = 420,
builder = false,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 4,
buildingGroundDecalSizeY = 4,
buildingGroundDecalType = [[staticjammer_aoplane.dds]],
buildPic = [[staticjammer.png]],
category = [[SINK UNARMED]],
cloakCost = 1,
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[32 70 32]],
collisionVolumeType = [[CylY]],
corpse = [[DEAD]],
customParams = {
removewait = 1,
morphto = [[cloakjammer]],
morphtime = 30,
area_cloak = 1,
area_cloak_upkeep = 12,
area_cloak_radius = 550,
area_cloak_decloak_distance = 75,
priority_misc = 2, -- High
},
energyUse = 1.5,
explodeAs = [[BIG_UNITEX]],
floater = true,
footprintX = 2,
footprintZ = 2,
iconType = [[staticjammer]],
idleAutoHeal = 5,
idleTime = 1800,
initCloaked = true,
levelGround = false,
maxDamage = 700,
maxSlope = 36,
minCloakDistance = 100,
noAutoFire = false,
objectName = [[radarjammer.dae]],
onoffable = true,
radarDistanceJam = 550,
script = [[staticjammer.lua]],
selfDestructAs = [[BIG_UNITEX]],
sightDistance = 250,
useBuildingGroundDecal = true,
yardMap = [[oo oo]],
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
object = [[radarjammer_dead.dae]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2a.s3o]],
},
},
}
return lowerkeys({ staticjammer = unitDef })
| gpl-2.0 |
timroes/awesome | lib/awful/rules.lua | 1 | 16538 | ---------------------------------------------------------------------------
--- Apply rules to clients at startup.
--
-- All existing `client` properties can be used in rules. It is also possible
-- to add random properties that will be later accessible as `c.property_name`
-- (where `c` is a valid client object)
--
-- In addition to the existing properties, the following are supported:
--
-- * placement
-- * honor_padding
-- * honor_workarea
-- * tag
-- * new_tag
-- * switchtotag
-- * focus
-- * titlebars_enabled
-- * callback
--
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2009 Julien Danjou
-- @module awful.rules
---------------------------------------------------------------------------
-- Grab environment we need
local client = client
local awesome = awesome
local screen = screen
local table = table
local type = type
local ipairs = ipairs
local pairs = pairs
local atag = require("awful.tag")
local gtable = require("gears.table")
local a_place = require("awful.placement")
local protected_call = require("gears.protected_call")
local rules = {}
--[[--
This is the global rules table.
You should fill this table with your rule and properties to apply.
For example, if you want to set xterm maximized at startup, you can add:
{ rule = { class = "xterm" },
properties = { maximized_vertical = true, maximized_horizontal = true } }
If you want to set mplayer floating at startup, you can add:
{ rule = { name = "MPlayer" },
properties = { floating = true } }
If you want to put Firefox on a specific tag at startup, you can add:
{ rule = { instance = "firefox" },
properties = { tag = mytagobject } }
Alternatively, you can specify the tag by name:
{ rule = { instance = "firefox" },
properties = { tag = "3" } }
If you want to put Thunderbird on a specific screen at startup, use:
{ rule = { instance = "Thunderbird" },
properties = { screen = 1 } }
Assuming that your X11 server supports the RandR extension, you can also specify
the screen by name:
{ rule = { instance = "Thunderbird" },
properties = { screen = "VGA1" } }
If you want to put Emacs on a specific tag at startup, and immediately switch
to that tag you can add:
{ rule = { class = "Emacs" },
properties = { tag = mytagobject, switchtotag = true } }
If you want to apply a custom callback to execute when a rule matched,
for example to pause playing music from mpd when you start dosbox, you
can add:
{ rule = { class = "dosbox" },
callback = function(c)
awful.spawn('mpc pause')
end }
Note that all "rule" entries need to match. If any of the entry does not
match, the rule won't be applied.
If a client matches multiple rules, they are applied in the order they are
put in this global rules table. If the value of a rule is a string, then the
match function is used to determine if the client matches the rule.
If the value of a property is a function, that function gets called and
function's return value is used for the property.
To match multiple clients to a rule one need to use slightly different
syntax:
{ rule_any = { class = { "MPlayer", "Nitrogen" }, instance = { "xterm" } },
properties = { floating = true } }
To match multiple clients with an exception one can couple `rules.except` or
`rules.except_any` with the rules:
{ rule = { class = "Firefox" },
except = { instance = "Navigator" },
properties = {floating = true},
},
{ rule_any = { class = { "Pidgin", "Xchat" } },
except_any = { role = { "conversation" } },
properties = { tag = "1" }
}
{ rule = {},
except_any = { class = { "Firefox", "Vim" } },
properties = { floating = true }
}
]]--
rules.rules = {}
--- Check if a client matches a rule.
-- @client c The client.
-- @tab rule The rule to check.
-- @treturn bool True if it matches, false otherwise.
function rules.match(c, rule)
if not rule then return false end
for field, value in pairs(rule) do
if c[field] then
if type(c[field]) == "string" then
if not c[field]:match(value) and c[field] ~= value then
return false
end
elseif c[field] ~= value then
return false
end
else
return false
end
end
return true
end
--- Check if a client matches any part of a rule.
-- @client c The client.
-- @tab rule The rule to check.
-- @treturn bool True if at least one rule is matched, false otherwise.
function rules.match_any(c, rule)
if not rule then return false end
for field, values in pairs(rule) do
if c[field] then
for _, value in ipairs(values) do
if c[field] == value then
return true
elseif type(c[field]) == "string" and c[field]:match(value) then
return true
end
end
end
end
return false
end
--- Does a given rule entry match a client?
-- @client c The client.
-- @tab entry Rule entry (with keys `rule`, `rule_any`, `except` and/or
-- `except_any`).
-- @treturn bool
function rules.matches(c, entry)
return (rules.match(c, entry.rule) or rules.match_any(c, entry.rule_any)) and
(not rules.match(c, entry.except) and not rules.match_any(c, entry.except_any))
end
--- Get list of matching rules for a client.
-- @client c The client.
-- @tab _rules The rules to check. List with "rule", "rule_any", "except" and
-- "except_any" keys.
-- @treturn table The list of matched rules.
function rules.matching_rules(c, _rules)
local result = {}
for _, entry in ipairs(_rules) do
if (rules.matches(c, entry)) then
table.insert(result, entry)
end
end
return result
end
--- Check if a client matches a given set of rules.
-- @client c The client.
-- @tab _rules The rules to check. List of tables with `rule`, `rule_any`,
-- `except` and `except_any` keys.
-- @treturn bool True if at least one rule is matched, false otherwise.
function rules.matches_list(c, _rules)
for _, entry in ipairs(_rules) do
if (rules.matches(c, entry)) then
return true
end
end
return false
end
--- Apply awful.rules.rules to a client.
-- @client c The client.
function rules.apply(c)
local props = {}
local callbacks = {}
for _, entry in ipairs(rules.matching_rules(c, rules.rules)) do
if entry.properties then
for property, value in pairs(entry.properties) do
props[property] = value
end
end
if entry.callback then
table.insert(callbacks, entry.callback)
end
end
rules.execute(c, props, callbacks)
end
local function add_to_tag(c, t)
if not t then return end
local tags = c:tags()
table.insert(tags, t)
c:tags(tags)
end
--- Extra rules properties.
--
-- These properties are used in the rules only and are not sent to the client
-- afterward.
--
-- To add a new properties, just do:
--
-- function awful.rules.extra_properties.my_new_property(c, value, props)
-- -- do something
-- end
--
-- By default, the table has the following functions:
--
-- * geometry
-- * switchtotag
--
-- @tfield table awful.rules.extra_properties
rules.extra_properties = {}
--- Extra high priority properties.
--
-- Some properties, such as anything related to tags, geometry or focus, will
-- cause a race condition if set in the main property section. This is why
-- they have a section for them.
--
-- To add a new properties, just do:
--
-- function awful.rules.high_priority_properties.my_new_property(c, value, props)
-- -- do something
-- end
--
-- By default, the table has the following functions:
--
-- * tag
-- * new_tag
--
-- @tfield table awful.rules.high_priority_properties
rules.high_priority_properties = {}
--- Delayed properties.
-- Properties applied after all other categories.
-- @tfield table awful.rules.delayed_properties
rules.delayed_properties = {}
local force_ignore = {
titlebars_enabled=true, focus=true, screen=true, x=true,
y=true, width=true, height=true, geometry=true,placement=true,
border_width=true,floating=true,size_hints_honor=true
}
function rules.high_priority_properties.tag(c, value, props)
if value then
if type(value) == "string" then
value = atag.find_by_name(c.screen, value)
end
-- In case the tag has been forced to another screen, move the client
if c.screen ~= value.screen then
c.screen = value.screen
props.screen = value.screen -- In case another rule query it
end
c:tags{ value }
end
end
function rules.delayed_properties.switchtotag(c, value)
if not value then return end
atag.viewmore(c:tags())
end
function rules.extra_properties.geometry(c, _, props)
local cur_geo = c:geometry()
local new_geo = type(props.geometry) == "function"
and props.geometry(c, props) or props.geometry or {}
for _, v in ipairs {"x", "y", "width", "height"} do
new_geo[v] = type(props[v]) == "function" and props[v](c, props)
or props[v] or new_geo[v] or cur_geo[v]
end
c:geometry(new_geo) --TODO use request::geometry
end
--- Create a new tag based on a rule.
-- @tparam client c The client
-- @tparam boolean|function|string value The value.
-- @tparam table props The properties.
-- @treturn tag The new tag
function rules.high_priority_properties.new_tag(c, value, props)
local ty = type(value)
local t = nil
if ty == "boolean" then
-- Create a new tag named after the client class
t = atag.add(c.class or "N/A", {screen=c.screen, volatile=true})
elseif ty == "string" then
-- Create a tag named after "value"
t = atag.add(value, {screen=c.screen, volatile=true})
elseif ty == "table" then
-- Assume a table of tags properties. Set the right screen, but
-- avoid editing the original table
local values = value.screen and value or gtable.clone(value)
values.screen = values.screen or c.screen
t = atag.add(value.name or c.class or "N/A", values)
-- In case the tag has been forced to another screen, move the client
c.screen = t.screen
props.screen = t.screen -- In case another rule query it
else
assert(false)
end
add_to_tag(c, t)
return t
end
function rules.extra_properties.placement(c, value, props)
-- Avoid problems
if awesome.startup and
(c.size_hints.user_position or c.size_hints.program_position) then
return
end
local ty = type(value)
local args = {
honor_workarea = props.honor_workarea ~= false,
honor_padding = props.honor_padding ~= false
}
if ty == "function" or (ty == "table" and
getmetatable(value) and getmetatable(value).__call
) then
value(c, args)
elseif ty == "string" and a_place[value] then
a_place[value](c, args)
end
end
function rules.high_priority_properties.tags(c, value, props)
local current = c:tags()
local tags, s = {}, nil
for _, t in ipairs(value) do
if type(t) == "string" then
t = atag.find_by_name(c.screen, t)
end
if t and ((not s) or t.screen == s) then
table.insert(tags, t)
s = s or t.screen
end
end
if s and s ~= c.screen then
c.screen = s
props.screen = s -- In case another rule query it
end
if #current == 0 or (value[1] and value[1].screen ~= current[1].screen) then
c:tags(tags)
else
c:tags(gtable.merge(current, tags))
end
end
--- Apply properties and callbacks to a client.
-- @client c The client.
-- @tab props Properties to apply.
-- @tab[opt] callbacks Callbacks to apply.
function rules.execute(c, props, callbacks)
-- This has to be done first, as it will impact geometry related props.
if props.titlebars_enabled then
c:emit_signal("request::titlebars", "rules", {properties=props})
end
-- Border width will also cause geometry related properties to fail
if props.border_width then
c.border_width = type(props.border_width) == "function" and
props.border_width(c, props) or props.border_width
end
-- Size hints will be re-applied when setting width/height unless it is
-- disabled first
if props.size_hints_honor ~= nil then
c.size_hints_honor = type(props.size_hints_honor) == "function" and props.size_hints_honor(c,props)
or props.size_hints_honor
end
-- Geometry will only work if floating is true, otherwise the "saved"
-- geometry will be restored.
if props.floating ~= nil then
c.floating = type(props.floating) == "function" and props.floating(c,props)
or props.floating
end
-- Before requesting a tag, make sure the screen is right
if props.screen then
c.screen = type(props.screen) == "function" and screen[props.screen(c,props)]
or screen[props.screen]
end
-- Some properties need to be handled first. For example, many properties
-- require that the client is tagged, this isn't yet the case.
for prop, handler in pairs(rules.high_priority_properties) do
local value = props[prop]
if value ~= nil then
if type(value) == "function" then
value = value(c, props)
end
handler(c, value, props)
end
end
-- Make sure the tag is selected before the main rules are called.
-- Otherwise properties like "urgent" or "focus" may fail (if they were
-- overridden by other callbacks).
-- Previously this was done in a second client.manage callback, but caused
-- a race condition where the order of modules being loaded would change
-- the outcome.
c:emit_signal("request::tag", nil, {reason="rules"})
-- By default, rc.lua uses no_overlap+no_offscreen placement. This has to
-- be executed before x/y/width/height/geometry as it would otherwise
-- always override the user specified position with the default rule.
if props.placement then
-- It may be a function, so this one doesn't execute it like others
rules.extra_properties.placement(c, props.placement, props)
end
-- Handle the geometry (since tags and screen are set).
if props.height or props.width or props.x or props.y or props.geometry then
rules.extra_properties.geometry(c, nil, props)
end
-- Apply the remaining properties (after known race conditions are handled).
for property, value in pairs(props) do
if property ~= "focus" and type(value) == "function" then
value = value(c, props)
end
local ignore = rules.high_priority_properties[property] or
rules.delayed_properties[property] or force_ignore[property]
if not ignore then
if rules.extra_properties[property] then
rules.extra_properties[property](c, value, props)
elseif type(c[property]) == "function" then
c[property](c, value)
else
c[property] = value
end
end
end
-- Apply all callbacks.
if callbacks then
for _, callback in pairs(callbacks) do
protected_call(callback, c)
end
end
-- Apply the delayed properties
for prop, handler in pairs(rules.delayed_properties) do
if not force_ignore[prop] then
local value = props[prop]
if value ~= nil then
if type(value) == "function" then
value = value(c, props)
end
handler(c, value, props)
end
end
end
-- Do this at last so we do not erase things done by the focus signal.
if props.focus and (type(props.focus) ~= "function" or props.focus(c)) then
c:emit_signal('request::activate', "rules", {raise=true})
end
end
function rules.completed_with_payload_callback(c, props, callbacks)
rules.execute(c, props, callbacks)
end
client.connect_signal("spawn::completed_with_payload", rules.completed_with_payload_callback)
client.connect_signal("manage", rules.apply)
return rules
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
mercury233/ygopro-scripts | c5220687.lua | 4 | 1235 | --็ด ๆฉใใใใฐใใ ในใฟใผ
function c5220687.initial_effect(c)
--flip
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(5220687,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_FLIP+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetTarget(c5220687.target)
e1:SetOperation(c5220687.operation)
c:RegisterEffect(e1)
end
function c5220687.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c5220687.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c5220687.filter(c,e,tp)
return c:IsLevelBelow(3) and c:IsRace(RACE_BEAST) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEDOWN_DEFENSE)
end
function c5220687.operation(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
local g=Duel.GetMatchingGroup(c5220687.filter,tp,LOCATION_DECK,0,nil,e,tp)
if g:GetCount()>0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sg=g:Select(tp,1,1,nil)
Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEDOWN_DEFENSE)
Duel.ConfirmCards(1-tp,sg)
end
end
| gpl-2.0 |
wenhuizhang/MoonGen | examples/ipsec/ah-gmac.lua | 6 | 4384 | local dpdk = require "dpdk"
local ipsec = require "ipsec"
local memory = require "memory"
local device = require "device"
local ffi = require "ffi"
local stats = require "stats"
function master(txPort, rxPort)
if not txPort or not rxPort then
return print("Usage: txPort rxPort")
end
local txDev = device.config(txPort, 1)
local rxDev = device.config(rxPort, 1)
device.waitForLinks()
dpdk.launchLua("rxSlave", rxPort, rxDev:getRxQueue(0), rxDev)
dpdk.launchLua("txSlave", txPort, txDev:getTxQueue(0), rxDev:getRxQueue(0), txDev)
dpdk.waitForSlaves()
end
-- txSlave sends out (ipsec crypto) packages
function txSlave(port, srcQueue, dstQueue, txDev)
-- Enable hw crypto engine
ipsec.enable(port)
-- Install TX Security Association (SA), here only Key and Salt.
-- SPI, Mode and Type are set in the packet
ipsec.tx_set_key(port, 0, "77777777deadbeef77777777DEADBEEF", "ff0000ff")
--local key, salt = ipsec.tx_get_key(port, 0)
--print("Key: 0x"..key)
--print("Salt: 0x"..salt)
-- Prepare Initialization Vector for the packet
local iv = ffi.new("union ipsec_iv")
iv.uint32[0] = 0x01020304
iv.uint32[1] = 0x05060708
-- Create a packet Blueprint
local pkt_len = 70 -- 70 bytes is the minimum for IPv4/AHv4
local mem = memory.createMemPool(function(buf)
buf:getAhPacket():fill{
pktLength = pkt_len,
ethSrc = srcQueue,
ethDst = "a0:36:9f:3b:71:da", --dstQueue,
ip4Protocol = 0x33, --AH, 0x32=ESP
ip4Src = "192.168.1.1",
ip4Dst = "192.168.1.2",
ahSPI = 0xdeadbeef,
ahSQN = 0,
ahIV = iv,
ahNextHeader = 0x11, --UDP
}
end)
local txCtr = stats:newDevTxCounter(txDev, "plain")
-- Prepare an Array of packets
--bufs = mem:bufArray(10)
bufs = mem:bufArray(128)
local count = 0
while dpdk.running() do
bufs:alloc(pkt_len)
for _, buf in ipairs(bufs) do
--local pkt = buf:getAhPacket()
--pkt.ah:setSQN(count) -- increment AH-SQN with each packet
--pkt.payload.uint16[0] = bswap16(12) -- UDP src port (not assigned to service)
--pkt.payload.uint16[1] = bswap16(14) -- UDP dst port (not assigned to service)
--pkt.payload.uint16[2] = bswap16(16) -- UDP len (header + payload in bytes)
--pkt.payload.uint16[3] = bswap16(0) -- UDP checksum (0 = unused)
--pkt.payload.uint32[2] = 0xdeadbeef -- real payload
--pkt.payload.uint32[3] = 0xffffffff -- real payload
buf:offloadIPSec(0, "ah") -- enable hw IPSec in AH mode, with SA/Key at index 0
--count = count+1
end
bufs:offloadIPChecksums()
--bufs:offloadIPSec(0, "ah")
srcQueue:send(bufs)
-- Update TX counter
txCtr:update()
end
-- Finalize TX counter
txCtr:finalize()
-- Disable hw crypto engine
ipsec.disable(port)
end
-- rxSlave logs received packages
function rxSlave(port, queue, rxDev)
-- Enable hw crypto engine
ipsec.enable(port)
-- Install RX Security Association (SA)
ipsec.rx_set_ip(port, 127, "192.168.1.2")
ipsec.rx_set_spi(port, 0, 0xdeadbeef, 127)
ipsec.rx_set_key(port, 0, "77777777deadbeef77777777DEADBEEF", "ff0000ff", 4, "ah")
--local key, salt, valid, proto, decrypt, ipv6 = ipsec.rx_get_key(port, 0)
--print("Key: 0x"..key)
--print("Salt: 0x"..salt)
--print("Valid ("..valid.."), Proto ("..proto.."), Decrypt ("..decrypt.."), IPv6 ("..ipv6..")")
--local ip = ipsec.rx_get_ip(port, 0)
--print("IP: "..ip)
--ipsec.rx_set_ip(port, 1, "0123:4567:89AB:CDEF:1011:1213:1415:1617")
--local ip = ipsec.rx_get_ip(port, 1, false)
--print("IP: "..ip)
--local spi, ip_idx = ipsec.rx_get_spi(port, 0)
--print("SPI: 0x"..bit.tohex(spi, 8))
--print("IP_IDX: "..ip_idx)
local rxCtr = stats:newDevRxCounter(rxDev, "plain")
local bufs = memory.bufArray()
while dpdk.running() do
local rx = queue:recv(bufs)
for i = rx, rx do
local buf = bufs[i]
--local pkt = buf:getAhPacket()
--local secp, secerr = buf:getSecFlags()
--print("IPSec HW status: SECP (" .. secp .. ") SECERR (0x" .. bit.tohex(secerr, 1) .. ")")
--buf:dump(128) -- hexdump of received packet (incl. header)
--printf("uint32[0]: %x", pkt.payload.uint32[0]) --UDP header
--printf("uint32[1]: %x", pkt.payload.uint32[1]) --UDP header
--printf("uint32[2]: %x", pkt.payload.uint32[2])
--printf("uint32[3]: %x", pkt.payload.uint32[3])
end
bufs:freeAll()
-- Update RX counter
rxCtr:update()
end
-- Finalize RX counter
rxCtr:finalize()
-- Disable hw crypto engine
ipsec.disable(port)
end
| mit |
mercury233/ygopro-scripts | c1918087.lua | 9 | 1223 | --ใดใใชใณใฎๅฐๅฝนไบบ
function c1918087.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,TIMING_DRAW_PHASE)
e1:SetCondition(c1918087.actcon)
c:RegisterEffect(e1)
--damage
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(1918087,0))
e2:SetCategory(CATEGORY_DAMAGE)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e2:SetRange(LOCATION_SZONE)
e2:SetCountLimit(1)
e2:SetCode(EVENT_PHASE+PHASE_STANDBY)
e2:SetCondition(c1918087.damcon)
e2:SetTarget(c1918087.damtg)
e2:SetOperation(c1918087.damop)
c:RegisterEffect(e2)
end
function c1918087.actcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetLP(1-tp)<=3000
end
function c1918087.damcon(e,tp,eg,ep,ev,re,r,rp)
return tp~=Duel.GetTurnPlayer()
end
function c1918087.damtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(1-tp)
Duel.SetTargetParam(500)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,500)
end
function c1918087.damop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Damage(p,d,REASON_EFFECT)
end
| gpl-2.0 |
Zenny89/darkstar | scripts/globals/items/plate_of_beef_paella_+1.lua | 36 | 1429 | -----------------------------------------
-- ID: 5973
-- Item: Plate of Beef Paella +1
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- HP 45
-- Strength 6
-- Attack % 19 Cap 95
-- Undead Killer 6
-----------------------------------------
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,14400,5973);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 45);
target:addMod(MOD_STR, 6);
target:addMod(MOD_FOOD_ATTP, 19);
target:addMod(MOD_FOOD_ATT_CAP, 95);
target:addMod(MOD_UNDEAD_KILLER, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 45);
target:delMod(MOD_STR, 6);
target:delMod(MOD_FOOD_ATTP, 19);
target:delMod(MOD_FOOD_ATT_CAP, 95);
target:delMod(MOD_UNDEAD_KILLER, 6);
end;
| gpl-3.0 |
sudhaMR/Animal_Book | mainMenu.lua | 1 | 4735 | ----------------------------------------------------------------------------------
--
-- scenetemplate.lua
--
----------------------------------------------------------------------------------
local widget = require "widget"
local composer = require( "composer" )
local scene = composer.newScene()
require "sqlite3"
---------------------------------------------------------------------------------
print( display.pixelWidth / display.actualContentWidth )
function scene:create( event )
local sceneGroup = self.view
-- Called when the scene's view does not exist.
--
-- INSERT code here to initialize the scene
-- e.g. add display objects to 'sceneGroup', add touch listeners, etc.
local sceneGroup = self.view
local function onSystemEvent( event )
if( event.type == "applicationExit" ) then
db:close()
end
end
local function onPressDomestic( event )
if event.phase == "ended" then
composer.gotoScene( "gridDomesticMenu", "slideLeft", 800 )
return true
end
end
local function onPressFarm( event )
if event.phase == "ended" then
composer.gotoScene( "gridFarmMenu", "slideLeft", 800 )
return true
end
end
local function onPressWild( event )
if event.phase == "ended" then
composer.gotoScene( "gridWildMenu", "slideLeft", 800 )
return true
end
end
local function onPressMarine( event )
if event.phase == "ended" then
composer.gotoScene( "gridMarineMenu", "slideLeft", 800 )
return true
end
end
local domesticButton = widget.newButton
{
width = display.viewableContentWidth - display.viewableContentWidth/32,
height = display.viewableContentHeight/5,
defaultFile = "categoryDom.png",
overFile = "categoryDomOff.png",
onEvent = onPressDomestic
}
domesticButton.x = display.contentCenterX
domesticButton.y = display.viewableContentHeight/8
sceneGroup:insert(domesticButton)
local farmButton = widget.newButton
{
width = display.viewableContentWidth - display.viewableContentWidth/32,
height = display.viewableContentHeight/5,
defaultFile = "categoryFarm.png",
overFile = "categoryFarmOff.png",
onEvent = onPressFarm
}
farmButton.x = display.contentCenterX
farmButton.y = display.viewableContentHeight/8 + domesticButton.y*2
sceneGroup:insert(farmButton)
local wildButton = widget.newButton
{
x = display.contentCenterX,
y = display.viewableContentHeight/8 + domesticButton.y*4,
width = display.viewableContentWidth - display.viewableContentWidth/32,
height = display.viewableContentHeight/5,
defaultFile = "categoryWildOn.png",
overFile = "categoryWildOff.png",
onEvent = onPressWild
}
sceneGroup:insert(wildButton)
local marineButton = widget.newButton
{
x = display.contentCenterX,
y = display.viewableContentHeight/8 + domesticButton.y*4,
width = display.viewableContentWidth - display.viewableContentWidth/32,
height = display.viewableContentHeight/5,
defaultFile = "categoryMarineOn.png",
overFile = "categoryMarineOff.png",
onEvent = onPressMarine
}
sceneGroup:insert(marineButton)
end
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if phase == "will" then
composer.removeScene("splash")
--composer.removeScene( "dogPage" )
-- Called when the scene is still off screen and is about to move on screen
elseif phase == "did" then
composer.removeScene( "dogPage" )
composer.removeScene("catPage")
-- Called when the scene is now on screen
--
-- INSERT code here to make the scene come alive
-- e.g. start timers, begin animation, play audio, etc.
end
end
function scene:hide( event )
local sceneGroup = self.view
local phase = event.phase
if event.phase == "will" then
-- Called when the scene is on screen and is about to move off screen
--
-- INSERT code here to pause the scene
-- e.g. stop timers, stop animation, unload sounds, etc.)
elseif phase == "did" then
-- Called when the scene is now off screen
--local showMem = function()
--image:addEventListener( "touch", image )
--end
end
end
function scene:destroy( event )
local sceneGroup = self.view
-- Called prior to the removal of scene's "view" (sceneGroup)
--
-- INSERT code here to cleanup the scene
-- e.g. remove display objects, remove touch listeners, save state, etc.
end
---------------------------------------------------------------------------------
-- Listener setup
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
---------------------------------------------------------------------------------
return scene | mit |
mercury233/ygopro-scripts | c25669282.lua | 2 | 3570 | --ๅฎๅ
จ็็ผ
function c25669282.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,25669282+EFFECT_COUNT_CODE_OATH)
e1:SetCost(c25669282.cost)
e1:SetTarget(c25669282.target)
e1:SetOperation(c25669282.activate)
c:RegisterEffect(e1)
--special summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(25669282,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_ATTACK_ANNOUNCE)
e2:SetRange(LOCATION_GRAVE)
e2:SetCondition(c25669282.spcon)
e2:SetCost(aux.bfgcost)
e2:SetTarget(c25669282.sptg)
e2:SetOperation(c25669282.spop)
c:RegisterEffect(e2)
end
c25669282.has_text_type=TYPE_DUAL
function c25669282.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0xeb) and c:IsAbleToRemoveAsCost()
end
function c25669282.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c25669282.cfilter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c25669282.cfilter,tp,LOCATION_MZONE,0,1,1,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c25669282.spfilter1(c,e,tp)
return c:IsSetCard(0xeb) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
and Duel.IsExistingMatchingCard(c25669282.spfilter2,tp,LOCATION_DECK,0,1,nil,e,tp,c:GetCode())
end
function c25669282.spfilter2(c,e,tp,code)
return c:IsSetCard(0xeb) and not c:IsCode(code) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c25669282.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return not Duel.IsPlayerAffectedByEffect(tp,59822133)
and Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c25669282.spfilter1,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,tp,LOCATION_DECK)
end
function c25669282.activate(e,tp,eg,ep,ev,re,r,rp)
if not Duel.IsPlayerAffectedByEffect(tp,59822133)
and Duel.GetLocationCount(tp,LOCATION_MZONE)>1 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g1=Duel.SelectMatchingCard(tp,c25669282.spfilter1,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if g1:GetCount()<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g2=Duel.SelectMatchingCard(tp,c25669282.spfilter2,tp,LOCATION_DECK,0,1,1,nil,e,tp,g1:GetFirst():GetCode())
g1:Merge(g2)
Duel.SpecialSummon(g1,0,tp,tp,false,false,POS_FACEUP)
end
end
function c25669282.spcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetAttacker():IsControler(1-tp) and Duel.GetAttackTarget()==nil
and aux.exccon(e,tp,eg,ep,ev,re,r,rp)
end
function c25669282.spfilter3(c,e,tp)
return c:IsFaceup() and c:IsType(TYPE_DUAL) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c25669282.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_REMOVED) and chkc:IsControler(tp) and c25669282.spfilter3(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c25669282.spfilter3,tp,LOCATION_REMOVED,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c25669282.spfilter3,tp,LOCATION_REMOVED,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c25669282.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP) then
tc:EnableDualState()
end
Duel.SpecialSummonComplete()
end
| gpl-2.0 |
mercury233/ygopro-scripts | c77421977.lua | 2 | 2907 | --Aiใทใฃใใผ
function c77421977.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_CONTINUOUS_TARGET)
e1:SetCondition(aux.dscon)
e1:SetTarget(c77421977.target)
e1:SetOperation(c77421977.activate)
c:RegisterEffect(e1)
--atk up
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_TARGET)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetRange(LOCATION_SZONE)
e2:SetValue(800)
c:RegisterEffect(e2)
--must attack
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetCode(EFFECT_MUST_ATTACK)
e3:SetRange(LOCATION_SZONE)
e3:SetTargetRange(0,LOCATION_MZONE)
e3:SetCondition(c77421977.effcon)
c:RegisterEffect(e3)
--must attack monster
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD)
e4:SetCode(EFFECT_MUST_ATTACK_MONSTER)
e4:SetRange(LOCATION_SZONE)
e4:SetTargetRange(0,LOCATION_MZONE)
e4:SetCondition(c77421977.effcon)
e4:SetValue(c77421977.atklimit)
c:RegisterEffect(e4)
--draw
local e5=Effect.CreateEffect(c)
e5:SetCategory(CATEGORY_DRAW)
e5:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e5:SetCode(EVENT_TO_GRAVE)
e5:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e5:SetCountLimit(1,77421977)
e5:SetCondition(c77421977.drcon)
e5:SetTarget(c77421977.drtg)
e5:SetOperation(c77421977.drop)
c:RegisterEffect(e5)
local e6=e5:Clone()
e6:SetCode(EVENT_REMOVE)
c:RegisterEffect(e6)
end
function c77421977.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0x135)
end
function c77421977.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c77421977.cfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c77421977.cfilter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
Duel.SelectTarget(tp,c77421977.cfilter,tp,LOCATION_MZONE,0,1,1,nil)
end
function c77421977.activate(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) then
c:SetCardTarget(tc)
end
end
function c77421977.effcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetFirstCardTarget()~=nil
end
function c77421977.atklimit(e,c)
return e:GetHandler():IsHasCardTarget(c)
end
function c77421977.drcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsPreviousPosition(POS_FACEUP) and c:IsPreviousLocation(LOCATION_SZONE) and c:IsPreviousControler(tp)
and c:IsReason(REASON_EFFECT) and rp==1-tp
end
function c77421977.drtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(1)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c77421977.drop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Draw(p,d,REASON_EFFECT)
end
| gpl-2.0 |
AntonioModer/fuccboiGDX | fuccboi/world/Query.lua | 1 | 8147 | local Class = require (fuccboi_path .. '/libraries/classic/classic')
local Query = Class:extend()
function Query:queryNew()
end
function Query:getEntitiesBy(key, value, object_types)
local entities = {}
if object_types then
for _, type in ipairs(object_types) do
for _, group in ipairs(self.groups) do
if group.name == type then
for _, object in ipairs(group:getEntities()) do
if object[key] == value then
table.insert(entities, object)
end
end
end
end
end
else
for _, group in ipairs(self.groups) do
for _, object in ipairs(group:getEntities()) do
if object[key] == value then
table.insert(entities, object)
end
end
end
end
return entities
end
function Query:getEntitiesWhere(condition, object_types)
local entities = {}
if object_types then
for _, type in ipairs(object_types) do
for _, group in ipairs(self.groups) do
if group.name == type then
for _, object in ipairs(group:getEntities()) do
if condition(object) then
table.insert(entities, object)
end
end
end
end
end
else
for _, group in ipairs(self.groups) do
for _, object in ipairs(group:getEntities()) do
if condition(object) then
table.insert(entities, object)
end
end
end
end
return entities
end
function Query:queryClosestAreaCircle(ids, x, y, radius, object_types)
if self.fg.debugDraw.query_enabled then
self:createEntity('DebugShape', x, y, {r = radius, shape = 'circle', query = true})
end
local out_object = nil
local min_distance = 100000
for _, type in ipairs(object_types) do
for _, group in ipairs(self.groups) do
if group.name == type then
for _, object in ipairs(group:getEntities()) do
if not self.fg.fn.contains(ids, object.id) then
local _x, _y = object.body:getPosition()
local dx, dy = math.abs(x - _x), math.abs(y - _y)
local distance = math.sqrt(dx*dx + dy*dy)
if distance < min_distance and distance < radius then
min_distance = distance
out_object = object
end
end
end
end
end
end
if out_object and self.fg.debugDraw.query_enabled then
self:createEntity('DebugShape', x, y,
{xf = out_object.x, yf = out_object.y, shape = 'line', link = true})
end
return out_object
end
function Query:queryAreaCircle(x, y, radius, object_types)
if self.fg.debugDraw.query_enabled then
self:createEntity('DebugShape', x, y, {r = radius, shape = 'circle', query = true})
end
local objects = {}
for _, type in ipairs(object_types) do
for _, group in ipairs(self.groups) do
if group.name == type then
for _, object in ipairs(group:getEntities()) do
local _x, _y = object.x, object.y
local dx, dy = math.abs(x - _x), math.abs(y - _y)
local distance = math.sqrt(dx*dx + dy*dy)
if distance < radius then
table.insert(objects, object)
end
end
end
end
end
return objects
end
function Query:queryAreaRectangle(x, y, w, h, object_types)
local objects = {}
for _, type in ipairs(object_types) do
for _, group in ipairs(self.groups) do
if group.name == type then
for _, object in ipairs(group:getEntities()) do
local _x, _y = object.x, object.y
local dx, dy = math.abs(x - _x), math.abs(y - _y)
if dx <= object.w/2 + w/2 and dy <= object.h/2 + h/2 then
table.insert(objects, object)
end
end
end
end
end
return objects
end
function Query:queryAreaLine(x1, y1, x2, y2, object_types)
local objects = {}
for _, type in ipairs(object_types) do
for _, group in ipairs(self.groups) do
if group.name == type then
for _, object in ipairs(group:getEntities()) do
if object.shape_name == 'chain' or object.shape_name == 'bsgrectangle' or
object.shape_name == 'rectangle' or object.shape_name == 'polygon' then
-- Get object lines
local object_lines = {}
local object_points = {object.body:getWorldPoints(object.shape:getPoints())}
if self.fg.mlib.Polygon.LineIntersects(x1, y1, x2, y2, unpack(object_points)) then
table.insert(objects, object)
end
elseif object.shape_name == 'circle' then
local x, y = object.body:getPosition()
if self.fg.mlib.Circle.IsSegmentSecant(x, y, object.r, x1, y2, x2, y2) then
table.insert(objects, object)
end
end
end
end
end
end
return objects
end
function Query:queryAreaPolygon(polygon_points, object_types)
local objects = {}
for _, type in ipairs(object_types) do
for _, group in ipairs(self.groups) do
if group.name == type then
for _, object in ipairs(group:getEntities()) do
if object.shape_name == 'chain' or object.shape_name == 'bsgrectangle' or
object.shape_name == 'rectangle' or object.shape_name == 'polygon' then
local object_points = {object.body:getWorldPoints(object.shape:getPoints())}
if self.fg.mlib.Polygon.PolygonIntersects(polygon_points, object_points) then
table.insert(objects, object)
end
elseif object.shape_name == 'circle' then
if self.fg.mlib.Polygon.CircleIntersects(x, y, object.r, unpack(polygon_points)) then
table.insert(objects, object)
end
end
end
end
end
end
return objects
end
function Query:applyAreaLine(x1, y1, x2, y2, object_types, action)
local objects = self:queryLine(x1, y1, x2, y2, object_types)
if #objects > 0 then
for _, object in ipairs(objects) do
action(object)
end
end
end
function Query:applyAreaCircle(x, y, r, object_types, action)
local objects = self:queryAreaCircle(x, y, r, object_types)
if #objects > 0 then
for _, object in ipairs(objects) do
action(object)
end
end
end
function Query:applyAreaPolygon(polygon_points, object_types, action)
local objects = self:queryPolygon(polygon_points, object_types)
if #objects > 0 then
for _, object in ipairs(objects) do
action(object)
end
end
end
function Query:applyAreaRectangle(x, y, w, h, object_types, action)
local objects = self:queryAreaRectangle(x, y, w, h, object_types)
if #objects > 0 then
for _, object in ipairs(objects) do
action(object)
end
end
end
function Query:applyEntitiesWhere(condition, object_types, action)
local objects = self:getEntitiesWhere(condition, object_types)
if #objects > 0 then
for _, object in ipairs(objects) do
action(object)
end
end
end
return Query
| mit |
Zenny89/darkstar | scripts/globals/items/silken_sash.lua | 36 | 1212 | -----------------------------------------
-- ID: 5632
-- Item: Silken Sash
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- TODO: Group Effect
-- HP Recovered while healing +3
-- MP Recovered while healing +5
-----------------------------------------
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,14400,5632);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HPHEAL, 3);
target:addMod(MOD_MPHEAL, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HPHEAL, 3);
target:delMod(MOD_MPHEAL, 5);
end;
| gpl-3.0 |
mercury233/ygopro-scripts | c12332865.lua | 2 | 1251 | --่ๅบงๅคฉๅฃในใใณ
function c12332865.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(12332865,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetRange(LOCATION_HAND)
e1:SetCountLimit(1,12332865)
e1:SetCondition(c12332865.condition)
e1:SetTarget(c12332865.target)
e1:SetOperation(c12332865.operation)
c:RegisterEffect(e1)
end
function c12332865.filter(c,tp)
return c:GetOriginalAttribute()==ATTRIBUTE_EARTH and c:GetOriginalRace()==RACE_FAIRY
and c:IsPreviousLocation(LOCATION_HAND+LOCATION_MZONE) and c:IsPreviousControler(tp)
end
function c12332865.condition(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c12332865.filter,1,nil,tp)
end
function c12332865.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c12332865.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
bryancall/trafficserver | plugins/lua/example/test_fetch.lua | 17 | 1604 | -- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you 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.
function send_response()
if ts.ctx['flen'] ~= nil then
ts.client_response.header['Flen'] = ts.ctx['flen']
end
end
function post_remap()
local url = string.format('http://%s/foo.txt', ts.ctx['host'])
local hdr = {
['Host'] = ts.ctx['host'],
['User-Agent'] = 'dummy',
}
local res = ts.fetch(url, {method = 'GET', header=hdr})
if res.status == 200 then
ts.ctx['flen'] = string.len(res.body)
print(res.body)
end
end
function do_remap()
local inner = ts.http.is_internal_request()
if inner ~= 0 then
return 0
end
local host = ts.client_request.header['Host']
ts.ctx['host'] = host
ts.hook(TS_LUA_HOOK_POST_REMAP, post_remap)
ts.hook(TS_LUA_HOOK_SEND_RESPONSE_HDR, send_response)
end
| apache-2.0 |
valhallaGaming/uno | branches/2_0_3_STABLE/vgscoreboard/scoreboard_client.lua | 1 | 9360 | local columnByName = {}
local scoreboardColumns = {}
local scoreboardRows = {}
local scoreboardGrid
local updateInterval = 1000 --ms
local visibilityCheckInterval = 500 --ms
local indent = ' '
local playerCount
local localPlayer = getLocalPlayer()
local playerTeam = getPlayerTeam(localPlayer)
local playerParent = getElementParent(localPlayer)
local rootElement = getRootElement()
local thisResourceRoot = getResourceRootElement(getThisResource())
function getName(element)
local eType = getElementType(element)
if eType == "player" then
return getPlayerName(element)
elseif eType == "team" then
return getTeamName(element)..' ('..countPlayersInTeam(element)..' players)'
end
end
function updateScoreboardData(element,field,data)
local sectionheader = (getElementType(element) == "team")
if scoreboardRows[element] and columnByName[field] then
data = tostring(data or "")
if field == "name" and getElementType(element) == "player" and getPlayerTeam(element) then
data = indent .. data
end
guiGridListSetItemText(
scoreboardGrid,
scoreboardRows[element],
scoreboardColumns[columnByName[field]].id,
data,
sectionheader,
false
)
end
end
function updatePlayerNick()
updateScoreboardData(source,"name",getPlayerName(source))
end
function updateChangedData(field)
if not isElement(source) then return false end --!wk
local eType = getElementType(source)
if eType == "player" or eType == "team" then
updateScoreboardData(source,field,getElementData(source,field))
end
end
function addToScoreboard(element)
element = element or source
local row = guiGridListAddRow(scoreboardGrid)
scoreboardRows[element] = row
updateScoreboardData(element,"name",getName(element))
return row
end
function removeFromScoreboard(element)
element = element or source
if not scoreboardRows[element] then return false end
guiGridListRemoveRow(scoreboardRows[element])
scoreboardRows[element] = nil
end
function refreshScoreboardElementData()
for element, row in pairs(scoreboardRows) do
for i, column in ipairs(scoreboardColumns) do
local columnName = column.name
if columnName ~= "name" and columnName ~= "ping" then
if isElement(element) then
updateScoreboardData(element,columnName,getElementData(element,columnName))
-- else outputDebugString("Unexpected: "..tostring(element),0)
end
end
end
end
end
function refreshScoreboardPings()
for i,player in ipairs(getElementsByType("player")) do
updateScoreboardData(player,"ping",getPlayerPing(player))
end
guiSetText(playerCount, guiGridListGetRowCount(scoreboardGrid))
end
function refreshScoreboardTeams()
guiGridListClear(scoreboardGrid)
scoreboardRows = {}
for i, player in ipairs(getElementsByType("player")) do
addToScoreboard(player)
end
--[[for i,team in ipairs(getElementsByType("team")) do
addToScoreboard(team)
local teamname = getTeamName(team)
for i,player in ipairs(getPlayersInTeam(team)) do
addToScoreboard(player)
updateScoreboardData(player,"team",teamname)
end
end]]--
end
function updateScoreboard()
refreshScoreboardTeams()
refreshScoreboardPings()
refreshScoreboardElementData()
guiSetText(playerCount, "Players: " .. guiGridListGetRowCount(scoreboardGrid))
if scoreboardColumns[1] then
guiGridListSetSelectedItem(scoreboardGrid, scoreboardRows[localPlayer], scoreboardColumns[1].id)
end
end
function refreshScoreboard()
if guiGetVisible(scoreboardGrid) and not isCursorShowing() then
updateScoreboard()
end
end
function addScoreboardColumn(columnData, position)
local name = columnData[1]
local size = columnData[2] or 0.1
local numberOfColumns = #scoreboardColumns
position = position or numberOfColumns
if name and not columnByName[name] then
if position <= numberOfColumns and numberOfColumns > 0 then
--delete all columns to the right of the new one, insert it and readd them
for i=position, numberOfColumns do
guiGridListRemoveColumn(scoreboardGrid,scoreboardColumns[i].id)
end
columnByName[name] = position
table.insert(scoreboardColumns,position,{name=name,id=guiGridListAddColumn(scoreboardGrid,name,size),size=size})
for i=position+1, numberOfColumns+1 do
columnByName[scoreboardColumns[i].name] = i
scoreboardColumns[i].id = guiGridListAddColumn(scoreboardGrid,scoreboardColumns[i].name,scoreboardColumns[i].size)
end
else
columnByName[name] = #scoreboardColumns + 1
table.insert(scoreboardColumns,{name=name,id=guiGridListAddColumn(scoreboardGrid,name,size), size=size})
end
end
return true
end
function removeScoreboardColumn(name)
if name and columnByName[name] then
local index = columnByName[name]
columnByName[name] = nil
guiGridListRemoveColumn(scoreboardGrid,scoreboardColumns[index].id)
table.remove(scoreboardColumns,index)
for i=index, #scoreboardColumns do
columnByName[scoreboardColumns[i].name] = i
end
return true
end
end
function replaceAllColumns(columnList)
for name in pairs(columnByName) do
removeScoreboardColumn(name)
end
for i, columnData in ipairs(columnList) do
addScoreboardColumn(columnData,#scoreboardColumns+1)
end
end
function showScoreboardCursor(key,keystate,show)
showCursor(show)
end
function toggleScoreboard(state)
if state == nil then state = not guiGetVisible(scoreboardGrid) end
if state == true then
showCursor(false)
updateScoreboard()
bindKey("mouse2","down",showScoreboardCursor,true)
bindKey("mouse2","up",showScoreboardCursor,false)
guiBringToFront(scoreboardGrid)
elseif state == false then
showCursor(false)
unbindKey("mouse2","down",showScoreboardCursor)
unbindKey("mouse2","up",showScoreboardCursor)
end
guiSetVisible(scoreboardGrid,state)
end
function toggleScoreboardPressed(key,keystate,state)
toggleScoreboard(state)
end
function checkVisibility()
local currentTeam = getPlayerTeam(localPlayer)
local currentParent = getElementParent(localPlayer)
if not ( currentTeam == playerTeam and currentParent == playerParent ) then
triggerServerEvent("onClientVisibilityChange",localPlayer)
playerTeam = currentTeam
playerParent = currentParent
end
end
function setScoreboardForced(state)
if state == true then
unbindKey("tab","down",toggleScoreboardPressed)
unbindKey("tab","up",toggleScoreboardPressed)
elseif state == false then
bindKey("tab","down",toggleScoreboardPressed,true)
bindKey("tab","up",toggleScoreboardPressed,false)
else
return false
end
toggleScoreboard(state)
end
addEventHandler("onClientResourceStart", thisResourceRoot,
function ()
scoreboardGrid = guiCreateGridList(0.15,0.2,0.7,0.6,true)
guiSetAlpha(scoreboardGrid,0.7)
guiSetVisible(scoreboardGrid,false)
local rmbLabel = guiCreateLabel(0, 0, 0, 0, "(Hold right mouse button to enable scrolling)",false,scoreboardGrid)
local scoreX, scoreY = guiGetSize(scoreboardGrid, false)
local labelWidth = guiLabelGetTextExtent(rmbLabel)
local labelHeight = guiLabelGetFontHeight(rmbLabel)
guiSetPosition(rmbLabel, (scoreX - labelWidth)/6, scoreY - labelHeight - 10, false)
guiSetSize(rmbLabel, labelWidth, labelHeight, false)
guiSetAlpha(rmbLabel, .8)
guiLabelSetColor(rmbLabel, 200, 200, 255)
playerCount = guiCreateLabel(0, 0, 0, 0, "Players: ",false,scoreboardGrid)
labelWidth = guiLabelGetTextExtent(playerCount)
labelHeight = guiLabelGetFontHeight(playerCount)
guiSetPosition(playerCount, (scoreX - labelWidth)/1.25, scoreY - labelHeight - 10, false)
guiSetSize(playerCount, labelWidth, labelHeight, false)
guiSetAlpha(playerCount, .8)
guiLabelSetColor(playerCount, 200, 200, 255)
bindKey("tab","down",toggleScoreboardPressed,true)
bindKey("tab","up",toggleScoreboardPressed,false)
addCommandHandler("scoreboard", toggleScoreboard)
setTimer(refreshScoreboard, updateInterval, 0)
updateScoreboard()
--serverside control events
addEvent("onServerSendColumns", true)
addEvent("doAddColumn", true)
addEvent("doRemoveColumn", true)
addEvent("doForceScoreboard", true)
--serverside control event handlers
addEventHandler("onServerSendColumns", rootElement, replaceAllColumns)
addEventHandler("doAddColumn", rootElement, addScoreboardColumn)
addEventHandler("doRemoveColumn", rootElement, removeScoreboardColumn)
addEventHandler("doForceScoreboard", rootElement, setScoreboardForced)
--scoreboard update event handlers
addEventHandler("onClientPlayerJoin", rootElement, addToScoreboard)
addEventHandler("onClientPlayerQuit", rootElement, removeFromScoreboard)
addEventHandler("onClientPlayerChangeNick", rootElement, updatePlayerNick)
addEventHandler("onClientElementDataChange", rootElement, updateChangedData)
addEventHandler("onClientClick", scoreboardGrid,
function()
if scoreboardColumns[1] and guiGetVisible(scoreboardGrid) then
guiGridListSetSelectedItem(scoreboardGrid, scoreboardRows[localPlayer], scoreboardColumns[1].id)
end
end
)
triggerServerEvent("onClientScoreboardLoaded", localPlayer)
setTimer(checkVisibility, visibilityCheckInterval, 0)
end
) | bsd-3-clause |
Zenny89/darkstar | scripts/zones/Crawlers_Nest/npcs/qm12.lua | 57 | 2120 | -----------------------------------
-- Area: Crawlers' Nest
-- NPC: qm12 (??? - Exoray Mold Crumbs)
-- Involved in Quest: In Defiant Challenge
-- @pos 99.326 -0.126 -188.869 197
-----------------------------------
package.loaded["scripts/zones/Crawlers_Nest/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/zones/Crawlers_Nest/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (OldSchoolG1 == false) then
if (player:hasItem(1089) == false and player:hasKeyItem(EXORAY_MOLD_CRUMB3) == false
and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then
player:addKeyItem(EXORAY_MOLD_CRUMB3);
player:messageSpecial(KEYITEM_OBTAINED,EXORAY_MOLD_CRUMB3);
end
if (player:hasKeyItem(EXORAY_MOLD_CRUMB1) and player:hasKeyItem(EXORAY_MOLD_CRUMB2) and player:hasKeyItem(EXORAY_MOLD_CRUMB3)) then
if (player:getFreeSlotsCount() >= 1) then
player:addItem(1089, 1);
player:messageSpecial(ITEM_OBTAINED, 1089);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1089);
end
end
if (player:hasItem(1089)) then
player:delKeyItem(EXORAY_MOLD_CRUMB1);
player:delKeyItem(EXORAY_MOLD_CRUMB2);
player:delKeyItem(EXORAY_MOLD_CRUMB3);
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);
end; | gpl-3.0 |
mercury233/ygopro-scripts | c76981308.lua | 2 | 3974 | --ใกใซใใฃใผใจใซใใใฃใ
function c76981308.initial_effect(c)
--Activate
local e0=Effect.CreateEffect(c)
e0:SetType(EFFECT_TYPE_ACTIVATE)
e0:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e0)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TODECK+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_SZONE)
e1:SetCountLimit(1,76981308)
e1:SetCost(c76981308.cost)
e1:SetTarget(c76981308.target)
e1:SetOperation(c76981308.operation)
c:RegisterEffect(e1)
--atk down
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(76981308,1))
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_PHASE+PHASE_BATTLE_START)
e2:SetRange(LOCATION_SZONE)
e2:SetCountLimit(1,76981309)
e2:SetCondition(c76981308.atkcon)
e2:SetTarget(c76981308.atktg)
e2:SetOperation(c76981308.atkop)
c:RegisterEffect(e2)
--atk down
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetCode(EFFECT_UPDATE_ATTACK)
e3:SetRange(LOCATION_SZONE)
e3:SetTargetRange(0,LOCATION_MZONE)
e3:SetValue(c76981308.atkval)
c:RegisterEffect(e3)
e3:SetLabelObject(e2)
end
function c76981308.cfilter(c,tp)
return not c:IsPublic() and c:IsRace(RACE_BEAST) and c:IsAbleToDeck()
and Duel.IsExistingMatchingCard(c76981308.cfilter2,tp,LOCATION_DECK+LOCATION_GRAVE,0,1,nil,c)
end
function c76981308.cfilter2(c,oc)
return not c:IsCode(oc:GetCode()) and c:IsAbleToHand() and c:IsSetCard(0x146) and c:IsType(TYPE_MONSTER)
end
function c76981308.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
e:SetLabel(1)
return Duel.IsExistingMatchingCard(c76981308.cfilter,tp,LOCATION_HAND,0,1,nil,tp)
end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectMatchingCard(tp,c76981308.cfilter,tp,LOCATION_HAND,0,1,1,nil,tp)
Duel.ConfirmCards(1-tp,g)
Duel.ShuffleHand(tp)
e:SetLabelObject(g:GetFirst())
end
function c76981308.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
local b=e:GetLabel()
e:SetLabel(0)
return b==1
end
e:GetLabelObject():CreateEffectRelation(e)
Duel.SetOperationInfo(0,CATEGORY_TODECK,e:GetLabelObject(),1,0,0)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c76981308.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
if not tc:IsRelateToEffect(e) then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(c76981308.cfilter2),tp,LOCATION_DECK+LOCATION_GRAVE,0,1,1,nil,tc)
if #g>0 and Duel.SendtoHand(g,nil,REASON_EFFECT)>0 then
Duel.ConfirmCards(1-tp,g)
Duel.ShuffleDeck(tp)
Duel.SendtoDeck(tc,nil,SEQ_DECKBOTTOM,REASON_EFFECT)
end
end
function c76981308.atkcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==1-tp
end
function c76981308.atkfilter(c)
return not c:IsPublic() and c:IsSetCard(0x146) and c:IsType(TYPE_MONSTER)
end
function c76981308.atktg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c76981308.atkfilter,tp,LOCATION_HAND,0,1,nil) end
end
function c76981308.atkop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(76981308,2))
local g=Duel.SelectMatchingCard(tp,c76981308.atkfilter,tp,LOCATION_HAND,0,1,99,nil)
if #g==0 then return end
for tc in aux.Next(g) do
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetDescription(66)
e1:SetCode(EFFECT_PUBLIC)
e1:SetProperty(EFFECT_FLAG_CLIENT_HINT)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_BATTLE)
tc:RegisterEffect(e1)
tc:RegisterFlagEffect(76981308,RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_BATTLE,0,1)
end
g:KeepAlive()
local g2=e:GetLabelObject()
if g2 then g2:DeleteGroup() end
e:SetLabelObject(g)
end
function c76981308.sum(c)
if c:GetFlagEffect(76981308)==0 then return 0 end
return c:GetAttack()+c:GetDefense()
end
function c76981308.atkval(e,c)
local g=e:GetLabelObject():GetLabelObject()
if g and #g>0 then
return -g:GetSum(c76981308.sum)
end
return 0
end
| gpl-2.0 |
XavierCHN/dota-hexagons | utils/class.lua | 1 | 9810 | -- class.lua
-- Compatible with Lua 5.1 (not 5.0).
--
--[[
Usage:
-- Define a class A
A = class(
-- First parameter to class function is a table with properties and
-- constructor method. Error if not specified or not a table
--
{
-- Define our properties. These are the values each new instance will start out with.
--
a = 0;
b = 0;
c = 0;
-- Implement a constructor that will get called once for each instance and create/set
-- property values. You are responsible for ensuring the first parameter is the self
-- parameter as it will be invoked with the instanceObj when a new instance is created.
-- Defining functions here is kind of ugly as you have to use table name = value syntax
-- See __tostring example below for a better looking way to do it.
--
constructor = function (self, a, b, c)
-- For each parameter specified, overwrite default value, otherwise keep default value
--
self.a = a or self.a
self.b = b or self.b
self.c = c or self.c
end
-- Define any further class methods here. Again, you are responsible
-- for making sure the first parameter is the self parameter and calling
-- the method with the : syntax (e.g. instanceObj:method) so that Lua will
-- pass instanceObj as the first parameter to the method.
},
-- Second parameter is an optional (non-nil) table that defines
-- static member variables. Error if specified and not a table.
--
{
__class__name = "A"
},
-- Third parameter is an optional (non-nil) table that defines
-- the base class. If present, this class will inherit, via copy,
-- the base classes properties and methods. Error if specified
-- and not a table created by the the class function
--
nil
)
-- Add a new property d to the class definition before we create any instances
--
A.d = 0
-- Implement a tostring method to return string representation of instance
-- Using classname: syntax allows a more natural definition and eliminates the
-- need to explicitly specify the self parameter
--
function A:__tostring()
return "A: " .. self.a .. " B: " .. self.b .. " C: " .. self.c .. " D: " .. self.d
end
-- Implement a method to do a random calculation on the instance property values.
--
function A:Step(amount)
self.a = self.b + (self.c * amount);
end
-- Create an instance of class A
test = A(1,2,3);
-- Display its value
print("test.tostring: " .. test.tostring();
-- Call Step method to do a random calculation
test.Step(10);
-- Display its value to see what changed.
print("test.tostring: " .. test.tostring();
]]--
function class(def, statics, base)
-- Error if def argument missing or is not a table
if not def or type(def) ~= 'table' then error("class definition missing or not a table") end
-- Error if statics argument is not nil and not a table
if statics and type(statics) ~= 'table' then error("statics parameter specified but not a table") end
-- Error if base argument not nil and not a table created by this function.
if base and (type(base) ~= 'table' or not isclass(base)) then error("base parameter specified but not a table created by class function") end
-- Start with a table for this class. This will be the metatable for
-- all instances of this class and where all class methods and static properties
-- will be kept. Initially it has two slots, __class__ == true to indicate this
-- table represents a class created by this function and __base__, which if not
-- nil is a reference to a base class created by this function
--
local c = {__base__ = base}
c.__class__ = c
-- Local function that will be used to create an instance of the class
-- when the class is called
--
local function create(class_tbl, ...)
-- Create an instance initialized with per instance properties
--
local instanceObj = {}
-- Shallow copy of any class instance property initializers into our copy
--
for i,v in pairs(c.__initprops__) do
instanceObj[i] = v
end
-- __index for each instance is the class object
--
local _c_mt = {}
for k,v in pairs(c) do
_c_mt[k] = v
end
_c_mt.__index = c
-- _c_mt.__tostring = function() return "instance of" .. tostring(c) end
setmetatable(instanceObj, _c_mt)
-- If constructor key is not nil then it is this class's constructor
-- so call it with our arguments
--
if instanceObj.constructor then
instanceObj:constructor(...)
end
-- Return new instance of the class
--
return instanceObj
end
-- Create a metatable for the class whose __index field is just the class
-- This will be the metatable for each new instance of this class created.
--
local c_mt = { __call = create}
if base then
-- Redirect class metatable __index slot to base class if specified
--
c_mt.__index = base
end
-- If statics is specified, shallow copy of non-function slots to our class
--
if statics then
for i,v in pairs(statics) do
if type(v) ~= 'function' then
-- Ignore functions in statics table as we only support
-- static properties.
--
c[i] = v
else
-- Error if this happens?
error("function definitions not supported in statics table")
end
end
end
-- Table for instance property initial values
--
c.__initprops__ = {}
-- Copy base class slots first if any so they will get overlayed
-- by class slots of the same key
--
if base then
-- Copy instance property initializers from base class
--
for i,v in pairs(base.__initprops__) do
c.__initprops__[i] = v
end
end
-- Now copy slots from the definition passed in. For functions,
-- store shallow copy to our class table. For anything not a
-- function slot, shallow copy to c.__initprops__ table for use
-- when a new object of this class is instantiated.
--
for i,v in pairs(def) do
if type(v) ~= 'function' then
c.__initprops__[i] = v
else
c[i] = v
end
end
-- Define an__instanceof__ method to determine if an instance.
-- was derived from the passed class. Used to emulate Squirrel
-- instanceof binary operator
--
c.__instanceof__ = function(instanceObj, classObj)
local c = getclass(instanceObj)
while c do
if c == classObj then return true end
c = c.__base__
end
return false
end
-- Define an __getclass__ method to emulate Squirrel 3 object.getclass()
--
c.__getclass__ =function(instanceObj)
-- class object is __class__ slot of instance object's metatable
--
local classObj = getmetatable(instanceObj).__index
-- Sanity check the metatable is really a class object
-- we created. If so return it otherwise nil
--
if isclass(classObj) then
return classObj
else
return nil
end
end
-- Define a __getbase__ method to emulate Squirrel 3 object.getbase()
-- method.
--
c.__getbase__ = function(classObj)
-- Sanity check the metatable is really a class object
-- we created. If so return it's __base__ property
-- otherwise nil
--
if isclass(classObj) then
-- base class, if any, is stored in class __base__ slot
--
return classObj.__base__
else
return nil
end
end
setmetatable(c, c_mt)
return c
end
-- Implement Squirrel instanceof binary operator
--
function instanceof(instanceObj, classObj)
c = rawget(getmetatable(instanceObj) or {}, "__index")
h = rawget(c or {}, "__instanceof__")
return h and h(instanceObj, classObj) or nil
end
-- Implement Squirrel getclass function
--
function getclass(instanceObj)
c = rawget(getmetatable(instanceObj) or {}, "__index")
h = rawget(c or {}, "__getclass__")
return h and h(instanceObj) or nil
end
-- Implement Squirrel getbase function
--
function getbase(instanceObj)
c = isclass(instanceObj) and instanceObj or rawget(getmetatable(instanceObj) or {}, "__index")
h = rawget(c or {}, "__getbase__")
return h and h(c) or nil
end
-- Implement isclass function
--
function isclass(classObj)
return classObj and classObj.__class__ == classObj
end
| mit |
mercury233/ygopro-scripts | c97053215.lua | 2 | 2621 | --Gใดใผใฌใ ใปในใฟใใณใปใกใณใใซ
function c97053215.initial_effect(c)
--link summon
aux.AddLinkProcedure(c,aux.FilterBoolFunction(Card.IsLinkAttribute,ATTRIBUTE_EARTH),2,2)
c:EnableReviveLimit()
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(97053215,0))
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SPECIAL_SUMMON+CATEGORY_GRAVE_ACTION+CATEGORY_GRAVE_SPSUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_CARD_TARGET)
e1:SetCountLimit(1,97053215)
e1:SetCondition(c97053215.spcon)
e1:SetTarget(c97053215.sptg)
e1:SetOperation(c97053215.spop)
c:RegisterEffect(e1)
end
function c97053215.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousLocation(LOCATION_GRAVE)
end
function c97053215.spfilter(c,e,tp,ft)
return c:IsAttribute(ATTRIBUTE_EARTH) and c:IsSummonableCard()
and (c:IsAbleToHand() or (ft>0 and c:IsCanBeSpecialSummoned(e,0,tp,false,false)))
end
function c97053215.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c97053215.spfilter(chkc,e,tp,ft) end
if chk==0 then return Duel.IsExistingTarget(c97053215.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp,ft) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
local g=Duel.SelectTarget(tp,c97053215.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp,ft)
end
function c97053215.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
if aux.NecroValleyNegateCheck(tc) then return end
if Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and tc:IsCanBeSpecialSummoned(e,0,tp,false,false)
and (not tc:IsAbleToHand() or Duel.SelectOption(tp,1190,1152)==1) then
Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetReset(RESET_EVENT+RESETS_STANDARD)
e2:SetValue(RESET_TURN_SET)
tc:RegisterEffect(e2)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_LEAVE_FIELD_REDIRECT)
e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e3:SetReset(RESET_EVENT+RESETS_REDIRECT)
e3:SetValue(LOCATION_REMOVED)
tc:RegisterEffect(e3)
Duel.SpecialSummonComplete()
else
Duel.SendtoHand(tc,nil,REASON_EFFECT)
end
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c54100561.lua | 2 | 2654 | --ใใกใใฌใใณใผใใปใใกใณใทใข
function c54100561.initial_effect(c)
--pendulum summon
aux.EnablePendulumAttribute(c)
--cannot disable spsummon
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_DISABLE_SPSUMMON)
e1:SetProperty(EFFECT_FLAG_IGNORE_RANGE+EFFECT_FLAG_SET_AVAILABLE)
e1:SetRange(LOCATION_PZONE)
e1:SetTarget(c54100561.distg)
c:RegisterEffect(e1)
--to extra
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(54100561,0))
e2:SetCategory(CATEGORY_TOEXTRA)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,54100561)
e2:SetTarget(c54100561.tetg)
e2:SetOperation(c54100561.teop)
c:RegisterEffect(e2)
--destroy replace
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e3:SetCode(EFFECT_DESTROY_REPLACE)
e3:SetRange(LOCATION_MZONE)
e3:SetCondition(c54100561.repcon)
e3:SetTarget(c54100561.reptg)
e3:SetValue(c54100561.repval)
c:RegisterEffect(e3)
end
function c54100561.distg(e,c)
return c:IsControler(e:GetHandlerPlayer()) and c:IsSetCard(0x162) and c:IsType(TYPE_PENDULUM) and c:IsSummonType(SUMMON_TYPE_PENDULUM)
end
function c54100561.tefilter(c)
return not c:IsCode(54100561) and c:IsSetCard(0x162) and c:IsType(TYPE_PENDULUM)
end
function c54100561.tetg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c54100561.tefilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOEXTRA,nil,1,tp,LOCATION_DECK)
end
function c54100561.teop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(54100561,1))
local g=Duel.SelectMatchingCard(tp,c54100561.tefilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoExtraP(g,nil,REASON_EFFECT)
end
end
function c54100561.pfilter(c)
return c:GetCurrentScale()%2~=0
end
function c54100561.repcon(e)
local tp=e:GetHandlerPlayer()
return Duel.IsExistingMatchingCard(c54100561.pfilter,tp,LOCATION_PZONE,0,1,nil)
end
function c54100561.repfilter(c,tp)
return c:IsFaceup() and c:IsControler(tp) and c:IsLocation(LOCATION_MZONE) and c:IsSetCard(0x162) and c:IsType(TYPE_PENDULUM)
and c:IsReason(REASON_BATTLE) and not c:IsReason(REASON_REPLACE)
end
function c54100561.reptg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return c:IsDestructable(e) and not c:IsStatus(STATUS_DESTROY_CONFIRMED) and eg:IsExists(c54100561.repfilter,1,c,tp) end
if Duel.SelectEffectYesNo(tp,c,96) then
Duel.Destroy(c,REASON_EFFECT+REASON_REPLACE)
return true
else return false end
end
function c54100561.repval(e,c)
return c54100561.repfilter(c,e:GetHandlerPlayer())
end
| gpl-2.0 |
mercury233/ygopro-scripts | c38737148.lua | 2 | 1991 | --ใฉใคใใฌใค ใใคใใญใน
function c38737148.initial_effect(c)
c:EnableReviveLimit()
--special summon
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetRange(LOCATION_HAND)
e1:SetCondition(c38737148.spcon)
c:RegisterEffect(e1)
--spsummon limit
local e2=Effect.CreateEffect(c)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_SPSUMMON_CONDITION)
c:RegisterEffect(e2)
--remove
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(38737148,0))
e3:SetCategory(CATEGORY_DESTROY)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetCountLimit(1)
e3:SetRange(LOCATION_MZONE)
e3:SetTarget(c38737148.destg)
e3:SetOperation(c38737148.desop)
c:RegisterEffect(e3)
end
function c38737148.spcon(e,c)
if c==nil then return true end
local tp=c:GetControler()
return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(Card.IsAttribute,tp,LOCATION_GRAVE,0,4,nil,ATTRIBUTE_LIGHT)
end
function c38737148.desfilter(c)
return Duel.IsExistingTarget(nil,0,LOCATION_ONFIELD,LOCATION_ONFIELD,2,c)
end
function c38737148.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return false end
if chk==0 then return Duel.IsExistingTarget(c38737148.desfilter,tp,LOCATION_FZONE,LOCATION_FZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g1=Duel.SelectTarget(tp,c38737148.desfilter,tp,LOCATION_FZONE,LOCATION_FZONE,1,1,nil)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g2=Duel.SelectTarget(tp,aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,2,2,g1:GetFirst())
g1:Merge(g2)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g1,g1:GetCount(),0,0)
end
function c38737148.desop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e)
Duel.Destroy(g,REASON_EFFECT)
end
| gpl-2.0 |
ajayk/kong | kong/plugins/key-auth/handler.lua | 2 | 3290 | local cache = require "kong.tools.database_cache"
local responses = require "kong.tools.responses"
local constants = require "kong.constants"
local BasePlugin = require "kong.plugins.base_plugin"
local KeyAuthHandler = BasePlugin:extend()
KeyAuthHandler.PRIORITY = 1000
-- Fast lookup for credential retrieval depending on the type of the authentication
--
-- All methods must respect:
--
-- @param request ngx request object
-- @param {table} conf Plugin config
-- @return {string} public_key
-- @return {string} private_key
local retrieve_credentials = {
[constants.AUTHENTICATION.HEADER] = function(request, conf)
local key
local headers = request.get_headers()
if conf.key_names then
for _, key_name in ipairs(conf.key_names) do
if headers[key_name] ~= nil then
key = headers[key_name]
if conf.hide_credentials then
request.clear_header(key_name)
end
return key
end
end
end
end,
[constants.AUTHENTICATION.QUERY] = function(request, conf)
if conf.key_names then
local key
local uri_params = request.get_uri_args()
for _, key_name in ipairs(conf.key_names) do
key = uri_params[key_name]
if key ~= nil then
if conf.hide_credentials then
uri_params[key_name] = nil
request.set_uri_args(uri_params)
end
return key
end
end
end
end
}
function KeyAuthHandler:new()
KeyAuthHandler.super.new(self, "key-auth")
end
function KeyAuthHandler:access(conf)
KeyAuthHandler.super.access(self)
local key, key_found, credential
for _, v in ipairs({ constants.AUTHENTICATION.QUERY, constants.AUTHENTICATION.HEADER }) do
key = retrieve_credentials[v](ngx.req, conf)
if key then
key_found = true
credential = cache.get_or_set(cache.keyauth_credential_key(key), function()
local credentials, err = dao.keyauth_credentials:find_by_keys {key = key}
local result
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
elseif #credentials > 0 then
result = credentials[1]
end
return result
end)
if credential then break end
end
end
-- No key found in the request's headers or parameters
if not key_found then
ngx.header["WWW-Authenticate"] = "Key realm=\""..constants.NAME.."\""
return responses.send_HTTP_UNAUTHORIZED("No API Key found in headers, body or querystring")
end
-- No key found in the DB, this credential is invalid
if not credential then
return responses.send_HTTP_FORBIDDEN("Invalid authentication credentials")
end
-- Retrieve consumer
local consumer = cache.get_or_set(cache.consumer_key(credential.consumer_id), function()
local result, err = dao.consumers:find_by_primary_key({id = credential.consumer_id})
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
return result
end)
ngx.req.set_header(constants.HEADERS.CONSUMER_ID, consumer.id)
ngx.req.set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id)
ngx.req.set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username)
ngx.ctx.authenticated_credential = credential
end
return KeyAuthHandler
| apache-2.0 |
mercury233/ygopro-scripts | c81278754.lua | 3 | 1825 | --่ฃใฌใจใซ
function c81278754.initial_effect(c)
--turn set
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(81278754,0))
e1:SetCategory(CATEGORY_POSITION)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetTarget(c81278754.target)
e1:SetOperation(c81278754.operation)
c:RegisterEffect(e1)
--damage
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(81278754,1))
e2:SetCategory(CATEGORY_TOHAND)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_FLIP)
e2:SetTarget(c81278754.rettg)
e2:SetOperation(c81278754.retop)
c:RegisterEffect(e2)
end
function c81278754.target(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return c:IsCanTurnSet() and c:GetFlagEffect(81278754)==0 end
c:RegisterFlagEffect(81278754,RESET_EVENT+RESETS_STANDARD-RESET_TURN_SET+RESET_PHASE+PHASE_END,0,1)
Duel.SetOperationInfo(0,CATEGORY_POSITION,c,1,0,0)
end
function c81278754.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and c:IsFaceup() then
Duel.ChangePosition(c,POS_FACEDOWN_DEFENSE)
end
end
function c81278754.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0x12)
end
function c81278754.rettg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c81278754.cfilter,tp,LOCATION_MZONE,0,1,nil)
and Duel.IsExistingMatchingCard(Card.IsAbleToHand,tp,0,LOCATION_MZONE,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,0,0)
end
function c81278754.retop(e,tp,eg,ep,ev,re,r,rp)
local ct=Duel.GetMatchingGroupCount(c81278754.cfilter,tp,LOCATION_MZONE,0,nil)
if ct==0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND)
local g=Duel.SelectMatchingCard(tp,Card.IsAbleToHand,tp,0,LOCATION_MZONE,1,ct,nil)
Duel.HintSelection(g)
Duel.SendtoHand(g,nil,REASON_EFFECT)
end
| gpl-2.0 |
ArchiveTeam/toshiba-grab | urlcode.lua | 58 | 3476 | ----------------------------------------------------------------------------
-- Utility functions for encoding/decoding of URLs.
--
-- @release $Id: urlcode.lua,v 1.10 2008/01/21 16:11:32 carregal Exp $
----------------------------------------------------------------------------
local ipairs, next, pairs, tonumber, type = ipairs, next, pairs, tonumber, type
local string = string
local table = table
module ("cgilua.urlcode")
----------------------------------------------------------------------------
-- Decode an URL-encoded string (see RFC 2396)
----------------------------------------------------------------------------
function unescape (str)
str = string.gsub (str, "+", " ")
str = string.gsub (str, "%%(%x%x)", function(h) return string.char(tonumber(h,16)) end)
str = string.gsub (str, "\r\n", "\n")
return str
end
----------------------------------------------------------------------------
-- URL-encode a string (see RFC 2396)
----------------------------------------------------------------------------
function escape (str)
str = string.gsub (str, "\n", "\r\n")
str = string.gsub (str, "([^0-9a-zA-Z ])", -- locale independent
function (c) return string.format ("%%%02X", string.byte(c)) end)
str = string.gsub (str, " ", "+")
return str
end
----------------------------------------------------------------------------
-- Insert a (name=value) pair into table [[args]]
-- @param args Table to receive the result.
-- @param name Key for the table.
-- @param value Value for the key.
-- Multi-valued names will be represented as tables with numerical indexes
-- (in the order they came).
----------------------------------------------------------------------------
function insertfield (args, name, value)
if not args[name] then
args[name] = value
else
local t = type (args[name])
if t == "string" then
args[name] = {
args[name],
value,
}
elseif t == "table" then
table.insert (args[name], value)
else
error ("CGILua fatal error (invalid args table)!")
end
end
end
----------------------------------------------------------------------------
-- Parse url-encoded request data
-- (the query part of the script URL or url-encoded post data)
--
-- Each decoded (name=value) pair is inserted into table [[args]]
-- @param query String to be parsed.
-- @param args Table where to store the pairs.
----------------------------------------------------------------------------
function parsequery (query, args)
if type(query) == "string" then
local insertfield, unescape = insertfield, unescape
string.gsub (query, "([^&=]+)=([^&=]*)&?",
function (key, val)
insertfield (args, unescape(key), unescape(val))
end)
end
end
----------------------------------------------------------------------------
-- URL-encode the elements of a table creating a string to be used in a
-- URL for passing data/parameters to another script
-- @param args Table where to extract the pairs (name=value).
-- @return String with the resulting encoding.
----------------------------------------------------------------------------
function encodetable (args)
if args == nil or next(args) == nil then -- no args or empty args?
return ""
end
local strp = ""
for key, vals in pairs(args) do
if type(vals) ~= "table" then
vals = {vals}
end
for i,val in ipairs(vals) do
strp = strp.."&"..escape(key).."="..escape(val)
end
end
-- remove first &
return string.sub(strp,2)
end
| unlicense |
Shockah/IB-Raid-Loot | Libs/LibDBIcon-1.0/LibDBIcon-1.0.lua | 3 | 10822 | --[[
Name: DBIcon-1.0
Revision: $Rev: 25 $
Author(s): Rabbit (rabbit.magtheridon@gmail.com)
Description: Allows addons to register to recieve a lightweight minimap icon as an alternative to more heavy LDB displays.
Dependencies: LibStub
License: GPL v2 or later.
]]
--[[
Copyright (C) 2008-2011 Rabbit
This program 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 2
of the License, or (at your option) 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
]]
-----------------------------------------------------------------------
-- DBIcon-1.0
--
-- Disclaimer: Most of this code was ripped from Barrel but fixed, streamlined
-- and cleaned up a lot so that it no longer sucks.
--
local DBICON10 = "LibDBIcon-1.0"
local DBICON10_MINOR = tonumber(("$Rev: 25 $"):match("(%d+)"))
if not LibStub then error(DBICON10 .. " requires LibStub.") end
local ldb = LibStub("LibDataBroker-1.1", true)
if not ldb then error(DBICON10 .. " requires LibDataBroker-1.1.") end
local lib = LibStub:NewLibrary(DBICON10, DBICON10_MINOR)
if not lib then return end
lib.disabled = lib.disabled or nil
lib.objects = lib.objects or {}
lib.callbackRegistered = lib.callbackRegistered or nil
lib.notCreated = lib.notCreated or {}
function lib:IconCallback(event, name, key, value, dataobj)
if lib.objects[name] then
if key == "icon" then
lib.objects[name].icon:SetTexture(value)
elseif key == "iconCoords" then
lib.objects[name].icon:UpdateCoord()
end
end
end
if not lib.callbackRegistered then
ldb.RegisterCallback(lib, "LibDataBroker_AttributeChanged__icon", "IconCallback")
ldb.RegisterCallback(lib, "LibDataBroker_AttributeChanged__iconCoords", "IconCallback")
lib.callbackRegistered = true
end
-- Tooltip code ripped from StatBlockCore by Funkydude
local function getAnchors(frame)
local x, y = frame:GetCenter()
if not x or not y then return "CENTER" end
local hhalf = (x > UIParent:GetWidth()*2/3) and "RIGHT" or (x < UIParent:GetWidth()/3) and "LEFT" or ""
local vhalf = (y > UIParent:GetHeight()/2) and "TOP" or "BOTTOM"
return vhalf..hhalf, frame, (vhalf == "TOP" and "BOTTOM" or "TOP")..hhalf
end
local function onEnter(self)
if self.isMoving then return end
local obj = self.dataObject
if obj.OnTooltipShow then
GameTooltip:SetOwner(self, "ANCHOR_NONE")
GameTooltip:SetPoint(getAnchors(self))
obj.OnTooltipShow(GameTooltip)
GameTooltip:Show()
elseif obj.OnEnter then
obj.OnEnter(self)
end
end
local function onLeave(self)
local obj = self.dataObject
GameTooltip:Hide()
if obj.OnLeave then obj.OnLeave(self) end
end
--------------------------------------------------------------------------------
local onClick, onMouseUp, onMouseDown, onDragStart, onDragEnd, updatePosition
do
local minimapShapes = {
["ROUND"] = {true, true, true, true},
["SQUARE"] = {false, false, false, false},
["CORNER-TOPLEFT"] = {false, false, false, true},
["CORNER-TOPRIGHT"] = {false, false, true, false},
["CORNER-BOTTOMLEFT"] = {false, true, false, false},
["CORNER-BOTTOMRIGHT"] = {true, false, false, false},
["SIDE-LEFT"] = {false, true, false, true},
["SIDE-RIGHT"] = {true, false, true, false},
["SIDE-TOP"] = {false, false, true, true},
["SIDE-BOTTOM"] = {true, true, false, false},
["TRICORNER-TOPLEFT"] = {false, true, true, true},
["TRICORNER-TOPRIGHT"] = {true, false, true, true},
["TRICORNER-BOTTOMLEFT"] = {true, true, false, true},
["TRICORNER-BOTTOMRIGHT"] = {true, true, true, false},
}
function updatePosition(button)
local angle = math.rad(button.db and button.db.minimapPos or button.minimapPos or 225)
local x, y, q = math.cos(angle), math.sin(angle), 1
if x < 0 then q = q + 1 end
if y > 0 then q = q + 2 end
local minimapShape = GetMinimapShape and GetMinimapShape() or "ROUND"
local quadTable = minimapShapes[minimapShape]
if quadTable[q] then
x, y = x*80, y*80
else
local diagRadius = 103.13708498985 --math.sqrt(2*(80)^2)-10
x = math.max(-80, math.min(x*diagRadius, 80))
y = math.max(-80, math.min(y*diagRadius, 80))
end
button:SetPoint("CENTER", Minimap, "CENTER", x, y)
end
end
function onClick(self, b) if self.dataObject.OnClick then self.dataObject.OnClick(self, b) end end
function onMouseDown(self) self.isMouseDown = true; self.icon:UpdateCoord() end
function onMouseUp(self) self.isMouseDown = false; self.icon:UpdateCoord() end
do
local function onUpdate(self)
local mx, my = Minimap:GetCenter()
local px, py = GetCursorPosition()
local scale = Minimap:GetEffectiveScale()
px, py = px / scale, py / scale
if self.db then
self.db.minimapPos = math.deg(math.atan2(py - my, px - mx)) % 360
else
self.minimapPos = math.deg(math.atan2(py - my, px - mx)) % 360
end
updatePosition(self)
end
function onDragStart(self)
self:LockHighlight()
self.isMouseDown = true
self.icon:UpdateCoord()
self:SetScript("OnUpdate", onUpdate)
self.isMoving = true
GameTooltip:Hide()
end
end
function onDragStop(self)
self:SetScript("OnUpdate", nil)
self.isMouseDown = false
self.icon:UpdateCoord()
self:UnlockHighlight()
self.isMoving = nil
end
local defaultCoords = {0, 1, 0, 1}
local function updateCoord(self)
local coords = self:GetParent().dataObject.iconCoords or defaultCoords
local deltaX, deltaY = 0, 0
if not self:GetParent().isMouseDown then
deltaX = (coords[2] - coords[1]) * 0.05
deltaY = (coords[4] - coords[3]) * 0.05
end
self:SetTexCoord(coords[1] + deltaX, coords[2] - deltaX, coords[3] + deltaY, coords[4] - deltaY)
end
local function createButton(name, object, db)
local button = CreateFrame("Button", "LibDBIcon10_"..name, Minimap)
button.dataObject = object
button.db = db
button:SetFrameStrata("MEDIUM")
button:SetWidth(31); button:SetHeight(31)
button:SetFrameLevel(8)
button:RegisterForClicks("anyUp")
button:RegisterForDrag("LeftButton")
button:SetHighlightTexture("Interface\\Minimap\\UI-Minimap-ZoomButton-Highlight")
local overlay = button:CreateTexture(nil, "OVERLAY")
overlay:SetWidth(53); overlay:SetHeight(53)
overlay:SetTexture("Interface\\Minimap\\MiniMap-TrackingBorder")
overlay:SetPoint("TOPLEFT")
local background = button:CreateTexture(nil, "BACKGROUND")
background:SetWidth(20); background:SetHeight(20)
background:SetTexture("Interface\\Minimap\\UI-Minimap-Background")
background:SetPoint("TOPLEFT", 7, -5)
local icon = button:CreateTexture(nil, "ARTWORK")
icon:SetWidth(17); icon:SetHeight(17)
icon:SetTexture(object.icon)
icon:SetPoint("TOPLEFT", 7, -6)
button.icon = icon
button.isMouseDown = false
icon.UpdateCoord = updateCoord
icon:UpdateCoord()
button:SetScript("OnEnter", onEnter)
button:SetScript("OnLeave", onLeave)
button:SetScript("OnClick", onClick)
if not db or not db.lock then
button:SetScript("OnDragStart", onDragStart)
button:SetScript("OnDragStop", onDragStop)
end
button:SetScript("OnMouseDown", onMouseDown)
button:SetScript("OnMouseUp", onMouseUp)
lib.objects[name] = button
if lib.loggedIn then
updatePosition(button)
if not db or not db.hide then button:Show()
else button:Hide() end
end
end
-- We could use a metatable.__index on lib.objects, but then we'd create
-- the icons when checking things like :IsRegistered, which is not necessary.
local function check(name)
if lib.notCreated[name] then
createButton(name, lib.notCreated[name][1], lib.notCreated[name][2])
lib.notCreated[name] = nil
end
end
lib.loggedIn = lib.loggedIn or false
-- Wait a bit with the initial positioning to let any GetMinimapShape addons
-- load up.
if not lib.loggedIn then
local f = CreateFrame("Frame")
f:SetScript("OnEvent", function()
for _, object in pairs(lib.objects) do
updatePosition(object)
if not lib.disabled and (not object.db or not object.db.hide) then object:Show()
else object:Hide() end
end
lib.loggedIn = true
f:SetScript("OnEvent", nil)
f = nil
end)
f:RegisterEvent("PLAYER_LOGIN")
end
local function getDatabase(name)
return lib.notCreated[name] and lib.notCreated[name][2] or lib.objects[name].db
end
function lib:Register(name, object, db)
if not object.icon then error("Can't register LDB objects without icons set!") end
if lib.objects[name] or lib.notCreated[name] then error("Already registered, nubcake.") end
if not lib.disabled and (not db or not db.hide) then
createButton(name, object, db)
else
lib.notCreated[name] = {object, db}
end
end
function lib:Lock(name)
if not lib:IsRegistered(name) then return end
if lib.objects[name] then
lib.objects[name]:SetScript("OnDragStart", nil)
lib.objects[name]:SetScript("OnDragStop", nil)
end
local db = getDatabase(name)
if db then db.lock = true end
end
function lib:Unlock(name)
if not lib:IsRegistered(name) then return end
if lib.objects[name] then
lib.objects[name]:SetScript("OnDragStart", onDragStart)
lib.objects[name]:SetScript("OnDragStop", onDragStop)
end
local db = getDatabase(name)
if db then db.lock = nil end
end
function lib:Hide(name)
if not lib.objects[name] then return end
lib.objects[name]:Hide()
end
function lib:Show(name)
if lib.disabled then return end
check(name)
lib.objects[name]:Show()
updatePosition(lib.objects[name])
end
function lib:IsRegistered(name)
return (lib.objects[name] or lib.notCreated[name]) and true or false
end
function lib:Refresh(name, db)
if lib.disabled then return end
check(name)
local button = lib.objects[name]
if db then button.db = db end
updatePosition(button)
if not button.db or not button.db.hide then
button:Show()
else
button:Hide()
end
if not button.db or not button.db.lock then
button:SetScript("OnDragStart", onDragStart)
button:SetScript("OnDragStop", onDragStop)
else
button:SetScript("OnDragStart", nil)
button:SetScript("OnDragStop", nil)
end
end
function lib:GetMinimapButton(name)
return lib.objects[name]
end
function lib:EnableLibrary()
lib.disabled = nil
for name, object in pairs(lib.objects) do
if not object.db or not object.db.hide then
object:Show()
updatePosition(object)
end
end
for name, data in pairs(lib.notCreated) do
if not data.db or not data.db.hide then
createButton(name, data[1], data[2])
lib.notCreated[name] = nil
end
end
end
function lib:DisableLibrary()
lib.disabled = true
for name, object in pairs(lib.objects) do
object:Hide()
end
end
| apache-2.0 |
openwrt-stuff/openwrt-extra | luci/applications/luci-ngrokc/luasrc/model/cbi/ngrokc/detail.lua | 2 | 2817 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Copyright 2013 Manuel Munz <freifunk at somakoma dot de>
-- Copyright 2014-2015 Christian Schoenebeck <christian dot schoenebeck at gmail dot com>
-- Licensed to the public under the Apache License 2.0.
local UCI = (require "luci.model.uci").cursor()
local NX = require "nixio"
local NXFS = require "nixio.fs"
local SYS = require "luci.sys"
local UTIL = require "luci.util"
local DISP = require "luci.dispatcher"
local DTYP = require "luci.cbi.datatypes"
local apply = luci.http.formvalue("cbi.apply")
if apply then
os.execute("/etc/init.d/ngrokc reload &") -- reload configuration
end
-- takeover arguments -- #######################################################
local section = arg[1]
m = Map("ngrokc")
m.redirect = DISP.build_url("admin", "services", "ngrokc")
tunnels = m:section( NamedSection, section, "tunnel", "<h3>" .. translate("Details") .. " : " .. section .. "</h3>")
tunnels.instance = section -- arg [1]
enabled=tunnels:option(Flag, "enabled", translate("Enable"))
enabled.anonymous = true
enabled.addremove = false
server=tunnels:option(ListValue, "server", translate("Server"))
--server:value("tunnel_mobi", "tunnel.mobi:44433")
--server:value("tunnel_org_cn", "tunnel.org.cn:4443")
UCI.foreach("ngrokc", "servers", function(s) server:value(s['.name'], s['.name'] .. " ( " .. s.host .. ":" .. s.port .. " ) ") end)
ptype=tunnels:option(ListValue, "type", translate("Type"))
ptype:value("tcp", translate("TCP"))
ptype:value("http", translate("HTTP"))
ptype:value("https", translate("HTTPS"))
lhost=tunnels:option(Value, "lhost", translate("Local Address"))
lhost.rmempty = true
lhost.placeholder="127.0.0.1"
lhost.datatype = "ip4addr"
lport=tunnels:option(Value, "lport", translate("Local Port"))
lport.datatype = "port"
lport.rmempty = false
custom_domain=tunnels:option(Flag, "custom_domain", translate("Use Custom Domain"))
custom_domain.default = "0"
custom_domain.disabled = "0"
custom_domain.enabled = "1"
custom_domain.rmempty = false
custom_domain:depends("type", "http")
custom_domain:depends("type", "https")
dname=tunnels:option(Value, "dname", translate("Custom Domain") .. "/" .. translate("SubDomain"), translate("Please set your domain's CNAME or A record to the tunnel server."))
dname.datatype = "hostname"
--dname.rmempty = false
dname.rmempty = true
dname:depends("type", "http")
dname:depends("type", "https")
rport=tunnels:option(Value, "rport", translate("Remote Port"))
rport.datatype = "port"
--rport.rmempty = false
rport.rmempty = true
rport:depends("type", "tcp")
custom_html=tunnels:option(DummyValue, "none")
custom_html.template = "ngrokc/ngrokc_script"
return m
| gpl-2.0 |
rouing/FHLG-BW | entities/entities/bigbomb/init.lua | 1 | 11550 | /* ======================================
bigbomb
the big bomb
====================================== */
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
function ENT:SpawnFunction( ply, tr )
if ( !tr.Hit ) then return end
local SpawnPos = tr.HitPos + tr.HitNormal * 20
local ent = ents.Create( "bigbomb" )
ent:SetPos( SpawnPos )
ent:Spawn()
ent:Activate()
return ent
end
/*---------------------------------------------------------
Name: Initialize
---------------------------------------------------------*/
//models/dav0r/tnt/tnt.mdl
function ENT:Initialize()
self.Entity:SetModel("models/props_c17/oildrum001.mdl")
self.Entity:SetSkin(1)
self.BombPanel = ents.Create("prop_dynamic_override")
self.BombPanel:SetModel( "models/weapons/w_c4_planted.mdl" )
self.BombPanel:SetPos(self.Entity:GetPos()+self.Entity:GetAngles():Forward()*10+self.Entity:GetAngles():Up()*25)
self.BombPanel:SetAngles(Angle(0,90,90))
self.BombPanel:SetParent(self.Entity)
self.BombPanel:SetSolid(SOLID_NONE)
//self.BombPanel:PhysicsInit(SOLID_NONE)
self.BombPanel:SetMoveType(MOVETYPE_NONE)
self.BombPanel2 = ents.Create("prop_dynamic_override")
self.BombPanel2:SetModel( "models/dav0r/tnt/tnt.mdl" )
self.BombPanel2:SetPos(self.Entity:GetPos()+self.Entity:GetAngles():Forward()*-6+self.Entity:GetAngles():Right()*-12+self.Entity:GetAngles():Up()*15)
self.BombPanel2:SetAngles(Angle(0,45,0))
self.BombPanel2:SetParent(self.Entity)
self.BombPanel2:SetSolid(SOLID_NONE)
//self.BombPanel2:PhysicsInit(SOLID_NONE)
self.BombPanel2:SetMoveType(MOVETYPE_NONE)
self.BombPanel3 = ents.Create("prop_dynamic_override")
self.BombPanel3:SetModel( "models/dav0r/tnt/tnt.mdl" )
self.BombPanel3:SetPos(self.Entity:GetPos()+self.Entity:GetAngles():Forward()*-6+self.Entity:GetAngles():Right()*12+self.Entity:GetAngles():Up()*15)
self.BombPanel3:SetAngles(Angle(0,-45,0))
self.BombPanel3:SetParent(self.Entity)
self.BombPanel3:SetSolid(SOLID_NONE)
//self.BombPanel3:PhysicsInit(SOLID_NONE)
self.BombPanel3:SetMoveType(MOVETYPE_NONE)
self.Entity:PhysicsInit( SOLID_VPHYSICS )
self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
self.Entity:SetSolid( SOLID_VPHYSICS )
local phys = self.Entity:GetPhysicsObject()
if (phys:IsValid()) then
phys:Wake()
end
self.Armed = false
self.Time = CurTime()
self.LastUsed = CurTime()
local ply = self.Owner
ply:GetTable().maxBigBombs=ply:GetTable().maxBigBombs + 1
self.Arming = 50
self.Disarming = 60
self.Tick = 0
util.PrecacheSound("weapons/c4/c4_beep1.wav")
util.PrecacheSound("weapons/c4/c4_disarm.wav")
util.PrecacheSound("weapons/c4/c4_explode1.wav")
util.PrecacheSound("weapons/c4/c4_exp_deb1.wav")
self.Entity:SetNWBool("armed", false)
end
function ENT:Think()
if (IsValid(self.Owner)==false) then
self.Entity:Remove()
end
if (self.Armed==true) then
if self.LastUsed+3<CurTime() && self.Disarming<60 then
self.Disarming=self.Disarming+1
self.Entity:SetColor(Color(self.Disarming*4, self.Disarming*4, self.Disarming*4, 255))
end
self.Entity:Beep()
if (self.Time<CurTime()+5) then
self.Entity:NextThink(CurTime()+0.125)
elseif (self.Time<CurTime()+30) then
self.Entity:NextThink(CurTime()+0.25)
elseif (self.Time<CurTime()+60) then
self.Entity:NextThink(CurTime()+0.5)
else
self.Entity:NextThink(CurTime()+1)
end
return true
end
end
function ENT:OnRemove()
timer.Destroy(tostring(self.Entity) .. "goboom")
timer.Destroy(tostring(self.Entity) .. "checkpropshit")
timer.Destroy(tostring(self.Entity) .. "checkpropshit2")
timer.Destroy(tostring(self.Entity) .. "checkblast" )
end
function ENT:PhysicsCollide( data, physobj )
end
function ENT:Touch()
end
function ENT:PhysicsUpdate()
end
function ENT:HitShit()
self.Entity:GetPhysicsObject():Wake()
self.DidHit = true
end
function ENT:Beep()
self.Entity:EmitSound(Sound("weapons/c4/c4_beep1.wav"))
end
function ENT:Explode()
// shield slayer
for k,v in pairs(player.GetAll()) do
if v:IsPlayer() && v:GetPos():Distance(self.Entity:GetPos())<1024 &&v:GetNWBool("shielded")==true then
v:SetNWBool("shielded", false)
v:GetTable().Shieldon = false
Notify(v, 1, 3, "The force of the Big Bomb shattered your shield!")
end
end
util.BlastDamage( self.Entity, self.Owner, self.Entity:GetPos(), 1536, 2000 )
// thanks to Fatal Muffin for Cinematic Explosions! your effect is made of win.
local effectdata = EffectData()
effectdata:SetStart(Vector(0,0,90))
effectdata:SetOrigin(self.Entity:GetPos())
effectdata:SetScale(3)
util.Effect("cinematicexplosion", effectdata)
self.Entity:EmitSound(Sound("weapons/c4/c4_explode1.wav"))
self.Entity:EmitSound(Sound("weapons/c4/c4_exp_deb1.wav"))
local owners,props = self.Entity:FindBreakables()
for k, v in pairs(player.GetAll()) do
local uid = v:UniqueID()
local propnum = tonumber(owners[uid])
if (propnum==nil) then propnum = 0 end
if (tonumber(propnum)>0) then
Notify(player.GetByUniqueID(uid), 1, 3, "A bigbomb has destroyed " .. tostring(owners[uid]) .. " of your props!")
player.GetByUniqueID(uid):PrintMessage(HUD_PRINTTALK, "A bigbomb has destroyed " .. tostring(owners[uid]) .. " of your props!")
end
end
for k, v in pairs(props) do
local class = v:GetClass()
if (class=="prop_physics_multiplayer" || class=="prop_physics_respawnable" || class=="prop_physics" || class=="phys_magnet" || class=="gmod_spawner" || class=="gmod_wheel" || class=="gmod_thruster" || class=="gmod_button" || class=="sent_keypad" || class=="auto_turret") then
local entowner = player.GetByUniqueID(v:GetVar("PropProtection"))
if (IsValid(entowner)) then
entowner:GetTable().shitweldcount=entowner:GetTable().shitweldcount+1
entowner:SetNWBool("shitwelding", true)
// keep the mingebag that just got bomb raped from spawning anything for the next minute.
timer.Destroy(tostring(v) .. "unweldamage")
timer.Create(tostring(v) .. "unweldamage", 60, 1, function() WeldControl(v, entowner) end)
end
v:Remove()
end
end
// lets make it unique from other bombs, and make this take a giant shit all over where it just exploded.
for i=0, 15, 1 do
local bomblet = ents.Create("bigbomb_fragment")
local randpos = Vector(math.random(-5,5), math.random(-5,5), math.random(0,5))
bomblet.Owner = self.Owner
bomblet:SetPos(self.Entity:GetPos()+randpos)
bomblet:Spawn()
bomblet:Activate()
bomblet:GetPhysicsObject():SetVelocity(randpos*65)
end
// this is only here, to just entirely ruin anything that takes damage that would be within blast, no matter whats in the way
local pos = self.Entity:GetPos()
local exp = ents.Create("env_physexplosion")
exp:SetKeyValue("magnitude", 9999)
exp:GetTable().attacker = self.Owner
exp:SetKeyValue("radius", 1536)
exp:SetPos(pos)
exp:Spawn()
exp:SetOwner(self.Owner)
exp:Fire("explode","",0)
self.Entity:Remove()
end
function ENT:Use(activator,caller)
if self.LastUsed>CurTime() then return end
if (self.Armed) then
if (self.LastUsed+0.3>CurTime() && self.Disarming==60) then
self.LastUsed = CurTime()+0.1
else
self.LastUsed = CurTime()+0.1
self.Disarming = self.Disarming-1
if activator:GetTable().Tooled && self.Tick==1 then
self.Disarming = self.Disarming-1
end
if self.Tick==1 then self.Tick=0 else self.Tick=1 end
self.Entity:SetColor(Color(self.Disarming*4, self.Disarming*4, self.Disarming*4, 255))
if (self.Disarming%5==0) then
self.Entity:Beep()
end
if (self.Disarming<=0) then
Notify(activator,1,3, "Bomb defused!")
Notify(self.Owner,1,3, "Bomb has been defused.")
self.Entity:EmitSound(Sound("weapons/c4/c4_disarm.wav"))
self.Entity:Remove()
end
end
else
if (self.LastUsed+0.3<CurTime()) then
self.LastUsed = CurTime()-0.1
self.Arming = 50
end
self.LastUsed = CurTime()+0.1
self.Arming = self.Arming-1
if (self.Arming%5==0) then
self.Entity:Beep()
end
if (self.Arming<=0) then
self.Entity:Armbomb(activator)
end
end
end
function ENT:Armbomb(planter)
// make damn sure the owner of the bomb isnt just gonna wall it off to keep people from defusing.
if (self.Entity:CheckPropFaggotry()==false) then
// self.Entity:DropToFloor()
self.Entity:GetPhysicsObject():EnableMotion(false)
self.Armed = true
self.Entity:SetNWBool("armed", true)
self.Time = CurTime()+120
self.Entity:SetNWFloat("goofytiem",self.Time)
self.Arming = 50
local owners,props = self.Entity:FindBreakables()
for k, v in pairs(player.GetAll()) do
local uid = v:UniqueID()
local propnum = tonumber(owners[uid])
if (propnum==nil) then propnum = 0 end
if (tonumber(propnum)>0) then
Notify(player.GetByUniqueID(uid), 1, 3, "A bigbomb has been planted near " .. tostring(owners[uid]) .. " of your props!")
player.GetByUniqueID(uid):PrintMessage(HUD_PRINTTALK, "A bigbomb has been planted near " .. tostring(owners[uid]) .. " of your props!")
end
end
timer.Create( tostring(self.Entity) .. "checkpropshit", 5, 18, function() self:PropCheck() end)
timer.Create( tostring(self.Entity) .. "checkpropshit2", 30, 5, function() self:PropCheck() end)
timer.Create( tostring(self.Entity) .. "checkblast", 89, 1, function() self:PropCheck() end)
timer.Create( tostring(self.Entity) .. "checkblast2", 119, 1, function() self:PropCheck() end)
timer.Create( tostring(self.Entity) .. "goboom", 120, 1, function() self:Explode() end)
Notify(planter, 1, 3, "Bomb has been planted.")
else
self.Arming = 50
Notify(self.Owner, 4, 3, "Get your props away from the bomb for it to be usable.")
Notify(planter, 4, 3, "bomb owner's props are too close.")
end
end
function ENT:CheckPropFaggotry()
local propwallingbitch = false
for k, v in pairs(ents.FindInSphere( self.Entity:GetPos(), 1536) ) do
if (player.Owner!=false) then
local entowner = player.GetByUniqueID(v:GetVar("PropProtection"))
if self.Owner==entowner then
// were going through all this, so that some mingebag does not plant a bomb,
// and then block the bomb with a prop to keep people from defusing it.
propwallingbitch = true
end
end
end
return propwallingbitch
end
function ENT:PropCheck()
if (self.Entity:CheckPropFaggotry()==true) then
Notify(self.Owner,1,3, "Your props are too close, Bomb will automatically disarm.")
self.Entity:EmitSound(Sound("weapons/c4/c4_disarm.wav"))
self.Entity:GetPhysicsObject():EnableMotion(true)
self.Armed = false
self.Entity:SetNWBool("armed", false)
self.Time = false
self.Entity:SetNWFloat("goofytiem","")
timer.Destroy(tostring(self.Entity) .. "goboom")
timer.Destroy(tostring(self.Entity) .. "checkblast" )
end
end
function ENT:FindBreakables()
local owners = {}
local props = ents.FindInSphere(self.Entity:GetPos(), 512)
for k, v in pairs(props) do
local class = v:GetClass()
if (class=="prop_physics_multiplayer" || class=="prop_physics_respawnable" || class=="prop_ragdoll" || class=="prop_physics" || class=="phys_magnet" || class=="gmod_spawner" || class=="gmod_wheel" || class=="gmod_thruster" || class=="gmod_button" || class=="auto_turret") then
local ownerid = v:GetVar("PropProtection")
if (ownerid!=nil && ownerid!=false) then
if (owners[ownerid]==nil) then
owners[ownerid]=0
end
owners[ownerid] = owners[ownerid]+1
end
end
end
return owners,props
end
function ENT:OnRemove()
local ply = self.Owner
if IsValid(ply) then
ply:GetTable().maxBigBombs=ply:GetTable().maxBigBombs - 1
end
end
function ENT:UpdateTransmitState()
return TRANSMIT_ALWAYS
end | unlicense |
mercury233/ygopro-scripts | c22454453.lua | 2 | 1144 | --่ฌ่ใช็ถ
function c22454453.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TODECK)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,TIMINGS_CHECK_MONSTER+TIMING_END_PHASE)
e1:SetTarget(c22454453.target)
e1:SetOperation(c22454453.activate)
c:RegisterEffect(e1)
end
function c22454453.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsAbleToDeck,tp,LOCATION_HAND,0,1,e:GetHandler()) end
Duel.SetOperationInfo(0,CATEGORY_TODECK,nil,1,tp,LOCATION_HAND)
end
function c22454453.activate(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectMatchingCard(tp,Card.IsAbleToDeck,tp,LOCATION_HAND,0,1,1,nil)
if g:GetCount()>0 then
if Duel.GetFieldGroupCount(tp,LOCATION_DECK,0)==0 then
Duel.SendtoDeck(g,nil,SEQ_DECKBOTTOM,REASON_EFFECT)
else
local opt=Duel.SelectOption(tp,aux.Stringid(22454453,0),aux.Stringid(22454453,1))
if opt==0 then
Duel.SendtoDeck(g,nil,SEQ_DECKTOP,REASON_EFFECT)
else
Duel.SendtoDeck(g,nil,SEQ_DECKBOTTOM,REASON_EFFECT)
end
end
end
end
| gpl-2.0 |
un1q/oLua | OLuaArgsValidator.lua | 1 | 3296 | ------------------------------------------------------------------------------
-- OLuaArgsValidator
-- Validator of arguments
declare('OLuaArgsValidator').inherit('OLuaValidator')
function OLuaArgsValidator:constructor(...)
self.expectedArgs = {...}
table.insert(self.expectedArgs, 1, 'table') --we expect self as first argument
end
function OLuaArgsValidator:tableToString(t)
local result = {}
for _,v in ipairs(t) do
if type(v) == 'string' or type(v) == 'number' then
table.insert(result, '"'..tostring(v)..'"')
else
table.insert(result, type(v))
end
end
return table.concat(result, ',')
end
function OLuaArgsValidator:errorMessage (arguments, argNumber)
--local str_expectedArgs = table.concat(self.expectedArgs, ",")
local str_expectedArgs = ""
for j,v in ipairs(self.expectedArgs) do
if j>1 then str_expectedArgs = str_expectedArgs .. "," end
if type(v) == 'string' then
str_expectedArgs = str_expectedArgs .. v
elseif type(v) == 'table' then
str_expectedArgs = str_expectedArgs .. '[ table validator: {'..OLuaArgsValidator:tableToString(v)..'}]'
else
str_expectedArgs = str_expectedArgs .. '[ ' .. type(v) .. ' validator]'
end
end
local str_args = ""
for j,v in ipairs(arguments) do
if j>1 then str_args = str_args .. "," end
if type(v) == "string" then
str_args = str_args .. '"'.. v ..'"'
else
str_args = str_args .. type(v)
end
end
if argNumber == nil then
return string.format("Wrong arguments. Expected: %s, was:%s",str_expectedArgs, str_args)
else
return string.format("Wrong arguments (argument number: %s). Expected: %s, was:%s",argNumber, str_expectedArgs, str_args)
end
end
function OLuaArgsValidator:tableContain(t,value)
for _,v in ipairs(t) do
if v == value then
return true
end
end
return false
end
function OLuaArgsValidator:before (str_typeName, functionName, arguments)
if #arguments ~= #self.expectedArgs then
self:error(str_typeName, functionName, self:errorMessage(arguments))
end
if self.expectedArgs ~= nil then
for i,expectedArg in ipairs(self.expectedArgs) do
local validatorType = type(expectedArg)
if validatorType == "string" then
if not(OLua.isInstanceOf(arguments[i], expectedArg)) then
self:error(str_typeName, functionName, self:errorMessage(arguments,i))
end
elseif validatorType == "table" then
if not(OLuaArgsValidator:tableContain(expectedArg, arguments[i])) then
self:error(str_typeName, functionName, self:errorMessage(arguments,i))
end
elseif validatorType == "function" then
if not(expectedArg(arguments[i])) then
self:error(str_typeName, functionName, self:errorMessage(arguments,i))
end
else
error("Wrong OLuaArgsValidator argument type: " .. validatorType .. " (use string, table or function)")
end
end
end
end
OLua.addValidator('args', OLuaArgsValidator)
| mit |
mercury233/ygopro-scripts | c91228233.lua | 2 | 2839 | --่ฟทใ่ฑใฎๆฃฎ
function c91228233.initial_effect(c)
aux.AddCodeList(c,3285552)
--Activate
local e0=Effect.CreateEffect(c)
e0:SetType(EFFECT_TYPE_ACTIVATE)
e0:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e0)
--immune
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_IMMUNE_EFFECT)
e1:SetRange(LOCATION_FZONE)
e1:SetTargetRange(LOCATION_MZONE,0)
e1:SetTarget(c91228233.immtg)
e1:SetValue(c91228233.immval)
c:RegisterEffect(e1)
--draw
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_DRAW)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_BATTLE_DESTROYING)
e2:SetRange(LOCATION_FZONE)
e2:SetCountLimit(1)
e2:SetCondition(c91228233.drcon)
e2:SetTarget(c91228233.drtg)
e2:SetOperation(c91228233.drop)
c:RegisterEffect(e2)
--search
local e3=Effect.CreateEffect(c)
e3:SetCategory(CATEGORY_SEARCH+CATEGORY_TOHAND)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetRange(LOCATION_FZONE)
e3:SetCountLimit(1)
e3:SetCondition(c91228233.thcon)
e3:SetTarget(c91228233.thtg)
e3:SetOperation(c91228233.thop)
c:RegisterEffect(e3)
end
function c91228233.immtg(e,c)
return c:GetEquipCount()>0 and c:GetEquipGroup():IsExists(Card.IsCode,1,nil,92341815)
end
function c91228233.immval(e,re)
return re:IsActivated() and re:GetOwnerPlayer()~=e:GetHandlerPlayer()
end
function c91228233.drcon(e,tp,eg,ep,ev,re,r,rp)
local rc=eg:GetFirst()
return rc:IsRelateToBattle() and rc:IsStatus(STATUS_OPPO_BATTLE)
and rc:IsFaceup() and rc:IsCode(3285552) and rc:IsControler(tp)
end
function c91228233.drtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(1)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c91228233.drop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Draw(p,d,REASON_EFFECT)
c:RegisterFlagEffect(91228233,RESET_PHASE+PHASE_END,0,1)
end
function c91228233.thcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetFlagEffect(91228233)>0 and Duel.GetCurrentPhase()==PHASE_MAIN2
end
function c91228233.thfilter(c)
return aux.IsCodeListed(c,3285552) and c:IsType(TYPE_FIELD) and not c:IsCode(91228233) and c:IsAbleToHand()
end
function c91228233.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c91228233.thfilter,tp,LOCATION_DECK+LOCATION_GRAVE,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK+LOCATION_GRAVE)
end
function c91228233.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(c91228233.thfilter),tp,LOCATION_DECK+LOCATION_GRAVE,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
mjssw/cuberite | lib/tolua++/src/bin/lua/compat.lua | 23 | 4095 | -------------------------------------------------------------------
-- Real globals
-- _ALERT
-- _ERRORMESSAGE
-- _VERSION
-- _G
-- assert
-- error
-- metatable
-- next
-- print
-- require
-- tonumber
-- tostring
-- type
-- unpack
-------------------------------------------------------------------
-- collectgarbage
-- gcinfo
-- globals
-- call -> protect(f, err)
-- loadfile
-- loadstring
-- rawget
-- rawset
-- getargs = Main.getargs ??
rawtype = type
function do_ (f, err)
if not f then print(err); return end
local a,b = pcall(f)
if not a then print(b); return nil
else return b or true
end
end
function dostring(s) return do_(loadstring(s)) end
-- function dofile(s) return do_(loadfile(s)) end
-------------------------------------------------------------------
-- Table library
local tab = table
foreach = tab.foreach
foreachi = tab.foreachi
getn = tab.getn
tinsert = tab.insert
tremove = tab.remove
sort = tab.sort
-------------------------------------------------------------------
-- Debug library
local dbg = debug
getinfo = dbg.getinfo
getlocal = dbg.getlocal
setcallhook = function () error"`setcallhook' is deprecated" end
setlinehook = function () error"`setlinehook' is deprecated" end
setlocal = dbg.setlocal
-------------------------------------------------------------------
-- math library
local math = math
abs = math.abs
acos = function (x) return math.deg(math.acos(x)) end
asin = function (x) return math.deg(math.asin(x)) end
atan = function (x) return math.deg(math.atan(x)) end
atan2 = function (x,y) return math.deg(math.atan2(x,y)) end
ceil = math.ceil
cos = function (x) return math.cos(math.rad(x)) end
deg = math.deg
exp = math.exp
floor = math.floor
frexp = math.frexp
ldexp = math.ldexp
log = math.log
log10 = math.log10
max = math.max
min = math.min
mod = math.mod
PI = math.pi
--??? pow = math.pow
rad = math.rad
random = math.random
randomseed = math.randomseed
sin = function (x) return math.sin(math.rad(x)) end
sqrt = math.sqrt
tan = function (x) return math.tan(math.rad(x)) end
-------------------------------------------------------------------
-- string library
local str = string
strbyte = str.byte
strchar = str.char
strfind = str.find
format = str.format
gsub = str.gsub
strlen = str.len
strlower = str.lower
strrep = str.rep
strsub = str.sub
strupper = str.upper
-------------------------------------------------------------------
-- os library
clock = os.clock
date = os.date
difftime = os.difftime
execute = os.execute --?
exit = os.exit
getenv = os.getenv
remove = os.remove
rename = os.rename
setlocale = os.setlocale
time = os.time
tmpname = os.tmpname
-------------------------------------------------------------------
-- compatibility only
getglobal = function (n) return _G[n] end
setglobal = function (n,v) _G[n] = v end
-------------------------------------------------------------------
local io, tab = io, table
-- IO library (files)
_STDIN = io.stdin
_STDERR = io.stderr
_STDOUT = io.stdout
_INPUT = io.stdin
_OUTPUT = io.stdout
seek = io.stdin.seek -- sick ;-)
tmpfile = io.tmpfile
closefile = io.close
openfile = io.open
function flush (f)
if f then f:flush()
else _OUTPUT:flush()
end
end
function readfrom (name)
if name == nil then
local f, err, cod = io.close(_INPUT)
_INPUT = io.stdin
return f, err, cod
else
local f, err, cod = io.open(name, "r")
_INPUT = f or _INPUT
return f, err, cod
end
end
function writeto (name)
if name == nil then
local f, err, cod = io.close(_OUTPUT)
_OUTPUT = io.stdout
return f, err, cod
else
local f, err, cod = io.open(name, "w")
_OUTPUT = f or _OUTPUT
return f, err, cod
end
end
function appendto (name)
local f, err, cod = io.open(name, "a")
_OUTPUT = f or _OUTPUT
return f, err, cod
end
function read (...)
local f = _INPUT
if rawtype(arg[1]) == 'userdata' then
f = tab.remove(arg, 1)
end
return f:read(unpack(arg))
end
function write (...)
local f = _OUTPUT
if rawtype(arg[1]) == 'userdata' then
f = tab.remove(arg, 1)
end
return f:write(unpack(arg))
end
| apache-2.0 |
Cavitt/vanilla-ot | data/movements/scripts/tiles.lua | 1 | 3374 | local config = {
increasing = {[416] = 417, [426] = 425, [446] = 447, [3216] = 3217, [3202] = 3215, [11062] = 11063},
decreasing = {[417] = 416, [425] = 426, [447] = 446, [3217] = 3216, [3215] = 3202, [11063] = 11062},
maxLevel = getConfigInfo('maximumDoorLevel')
}
local checkCreature = {isPlayer, isMonster, isNpc}
local function pushBack(cid, position, fromPosition, displayMessage)
doTeleportThing(cid, fromPosition, false)
doSendMagicEffect(position, CONST_ME_MAGIC_BLUE)
if(displayMessage) then
doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, "The tile seems to be protected against unwanted intruders.")
end
end
function onStepIn(cid, item, position, fromPosition)
if(not config.increasing[item.itemid]) then
return false
end
if(not isPlayerGhost(cid)) then
doTransformItem(item.uid, config.increasing[item.itemid])
end
if(item.actionid >= 194 and item.actionid <= 196) then
local f = checkCreature[item.actionid - 193]
if(f(cid)) then
pushBack(cid, position, fromPosition, false)
end
return true
end
if(item.actionid >= 191 and item.actionid <= 193) then
local f = checkCreature[item.actionid - 190]
if(not f(cid)) then
pushBack(cid, position, fromPosition, false)
end
return true
end
if(not isPlayer(cid)) then
return true
end
if(item.actionid == 189 and not isPremium(cid)) then
pushBack(cid, position, fromPosition, true)
return true
end
local gender = item.actionid - 186
if(isInArray({PLAYERSEX_FEMALE, PLAYERSEX_MALE, PLAYERSEX_GAMEMASTER}, gender)) then
if(gender ~= getPlayerSex(cid)) then
pushBack(cid, position, fromPosition, true)
end
return true
end
local skull = item.actionid - 180
if(skull >= SKULL_NONE and skull <= SKULL_BLACK) then
if(skull ~= getCreatureSkullType(cid)) then
pushBack(cid, position, fromPosition, true)
end
return true
end
local group = item.actionid - 150
if(group >= 0 and group < 30) then
if(group > getPlayerGroupId(cid)) then
pushBack(cid, position, fromPosition, true)
end
return true
end
local vocation = item.actionid - 100
if(vocation >= 0 and vocation < 50) then
local playerVocation = getVocationInfo(getPlayerVocation(cid))
if(playerVocation.id ~= vocation and playerVocation.fromVocation ~= vocation) then
pushBack(cid, position, fromPosition, true)
end
return true
end
if(item.actionid >= 1000 and item.actionid - 1000 <= config.maxLevel) then
if(getPlayerLevel(cid) < item.actionid - 1000) then
pushBack(cid, position, fromPosition, true)
end
return true
end
if(item.actionid ~= 0 and getCreatureStorage(cid, item.actionid) <= 0) then
pushBack(cid, position, fromPosition, true)
return true
end
if(getTileInfo(position).protection) then
local depotItem = getTileItemByType(getCreatureLookPosition(cid), ITEM_TYPE_DEPOT)
if(depotItem.itemid ~= 0) then
local depotItems = getPlayerDepotItems(cid, getDepotId(depotItem.uid))
doPlayerSendTextMessage(cid, MESSAGE_STATUS_DEFAULT, "Your depot contains " .. depotItems .. " item" .. (depotItems > 1 and "s" or "") .. ".")
return true
end
end
return false
end
function onStepOut(cid, item, position, fromPosition)
if(not config.decreasing[item.itemid]) then
return false
end
if(not isPlayerGhost(cid)) then
doTransformItem(item.uid, config.decreasing[item.itemid])
return true
end
return false
end
| agpl-3.0 |
mercury233/ygopro-scripts | c15462014.lua | 2 | 2210 | --้พ้ฆฌ่บๅณ
function c15462014.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCondition(c15462014.actcon)
c:RegisterEffect(e1)
--disable
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_DISABLE)
e2:SetRange(LOCATION_SZONE)
e2:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE)
e2:SetTarget(c15462014.distg)
c:RegisterEffect(e2)
--send to GY
local e3=Effect.CreateEffect(c)
e3:SetCategory(CATEGORY_TOGRAVE+CATEGORY_DAMAGE)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e3:SetCode(EVENT_BATTLE_DESTROYED)
e3:SetRange(LOCATION_SZONE)
e3:SetCondition(c15462014.tgcon)
e3:SetTarget(c15462014.tgtg)
e3:SetOperation(c15462014.tgop)
c:RegisterEffect(e3)
end
function c15462014.cfilter(c)
return c:IsSummonLocation(LOCATION_EXTRA)
end
function c15462014.actcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c15462014.cfilter,tp,LOCATION_MZONE,0,1,nil)
and Duel.IsExistingMatchingCard(c15462014.cfilter,tp,0,LOCATION_MZONE,1,nil)
end
function c15462014.distg(e,c)
return c:IsSummonLocation(LOCATION_EXTRA)
end
function c15462014.egfilter(c)
local d=c:GetBattleTarget()
return c:IsSummonLocation(LOCATION_EXTRA) and d:IsSummonLocation(LOCATION_EXTRA)
end
function c15462014.pcheck(c,tp)
return c:IsPreviousControler(tp)
end
function c15462014.tgcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c15462014.egfilter,1,nil)
end
function c15462014.tgtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,e:GetHandler(),1,0,0)
local tg,pct,player=eg:Filter(c15462014.egfilter,nil),0,0
for p=0,1 do
if tg:IsExists(c15462014.pcheck,1,nil,p) then
pct=pct+1
player=p
end
end
if pct==2 then player=PLAYER_ALL end
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,player,1000)
end
function c15462014.tgop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SendtoGrave(c,REASON_EFFECT)
local tg=eg:Filter(c15462014.egfilter,nil)
for p=0,1 do
if tg:IsExists(c15462014.pcheck,1,nil,p) then
Duel.Damage(p,1000,REASON_EFFECT,true)
end
end
Duel.RDComplete()
end
end
| gpl-2.0 |
Zenny89/darkstar | scripts/zones/Kazham/npcs/Thali_Mhobrum.lua | 15 | 1696 | -----------------------------------
-- Area: Kazham
-- NPC: Thali Mhobrum
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/zones/Kazham/TextIDs");
local path = {
55.816410, -11.000000, -43.992680,
54.761787, -11.000000, -44.046181,
51.805824, -11.000000, -44.200321,
52.922001, -11.000000, -44.186420,
51.890709, -11.000000, -44.224312,
47.689358, -11.000000, -44.374969,
52.826096, -11.000000, -44.191029,
47.709465, -11.000000, -44.374393,
52.782181, -11.000000, -44.192482,
47.469643, -11.000000, -44.383091
};
function onSpawn(npc)
npc:initNpcAi();
npc:setPos(pathfind.first(path));
onPath(npc);
end;
function onPath(npc)
pathfind.patrol(npc, path);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("BathedInScent") == 1) then
player:startEvent(0x00A3); -- scent from Blue Rafflesias
npc:wait(-1);
else
player:startEvent(0x00BE);
npc:wait(-1);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,npc)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
npc:wait(0);
end;
| gpl-3.0 |
gibtang/CCNSCoding | scripting/lua/script/CCBReaderLoad.lua | 1 | 5162 | ccb = ccb or {}
function CCBReaderLoad(strFilePath,proxy,owner)
if nil == proxy then
return
end
local ccbReader = proxy:createCCBReader()
local node = ccbReader:load(strFilePath)
local rootName = ""
--owner set in readCCBFromFile is proxy
if nil ~= owner then
--Callbacks
local ownerCallbackNames = ccbReader:getOwnerCallbackNames()
local ownerCallbackNodes = ccbReader:getOwnerCallbackNodes()
local ownerCallbackControlEvents = ccbReader:getOwnerCallbackControlEvents()
local i = 1
for i = 1,table.getn(ownerCallbackNames) do
local callbackName = ownerCallbackNames[i]
local callbackNode = tolua.cast(ownerCallbackNodes[i],"Node")
if "function" == type(owner[callbackName]) then
proxy:setCallback(callbackNode, owner[callbackName], ownerCallbackControlEvents[i])
else
print("Warning: Cannot find owner's lua function:" .. ":" .. callbackName .. " for ownerVar selector")
end
end
--Variables
local ownerOutletNames = ccbReader:getOwnerOutletNames()
local ownerOutletNodes = ccbReader:getOwnerOutletNodes()
for i = 1, table.getn(ownerOutletNames) do
local outletName = ownerOutletNames[i]
local outletNode = tolua.cast(ownerOutletNodes[i],"Node")
owner[outletName] = outletNode
end
end
local nodesWithAnimationManagers = ccbReader:getNodesWithAnimationManagers()
local animationManagersForNodes = ccbReader:getAnimationManagersForNodes()
for i = 1 , table.getn(nodesWithAnimationManagers) do
local innerNode = tolua.cast(nodesWithAnimationManagers[i], "Node")
local animationManager = tolua.cast(animationManagersForNodes[i], "CCBAnimationManager")
local documentControllerName = animationManager:getDocumentControllerName()
if "" == documentControllerName then
end
if nil ~= ccb[documentControllerName] then
ccb[documentControllerName]["mAnimationManager"] = animationManager
end
--Callbacks
local documentCallbackNames = animationManager:getDocumentCallbackNames()
local documentCallbackNodes = animationManager:getDocumentCallbackNodes()
local documentCallbackControlEvents = animationManager:getDocumentCallbackControlEvents()
for i = 1,table.getn(documentCallbackNames) do
local callbackName = documentCallbackNames[i]
local callbackNode = tolua.cast(documentCallbackNodes[i],"Node")
if "" ~= documentControllerName and nil ~= ccb[documentControllerName] then
if "function" == type(ccb[documentControllerName][callbackName]) then
proxy:setCallback(callbackNode, ccb[documentControllerName][callbackName], documentCallbackControlEvents[i])
else
print("Warning: Cannot found lua function [" .. documentControllerName .. ":" .. callbackName .. "] for docRoot selector")
end
end
end
--Variables
local documentOutletNames = animationManager:getDocumentOutletNames()
local documentOutletNodes = animationManager:getDocumentOutletNodes()
for i = 1, table.getn(documentOutletNames) do
local outletName = documentOutletNames[i]
local outletNode = tolua.cast(documentOutletNodes[i],"Node")
if nil ~= ccb[documentControllerName] then
ccb[documentControllerName][outletName] = tolua.cast(outletNode, proxy:getNodeTypeName(outletNode))
end
end
--[[
if (typeof(controller.onDidLoadFromCCB) == "function")
controller.onDidLoadFromCCB();
]]--
--Setup timeline callbacks
local keyframeCallbacks = animationManager:getKeyframeCallbacks()
for i = 1 , table.getn(keyframeCallbacks) do
local callbackCombine = keyframeCallbacks[i]
local beignIndex,endIndex = string.find(callbackCombine,":")
local callbackType = tonumber(string.sub(callbackCombine,1,beignIndex - 1))
local callbackName = string.sub(callbackCombine,endIndex + 1, -1)
--Document callback
if 1 == callbackType and nil ~= ccb[documentControllerName] then
local callfunc = cc.CallFunc:create(ccb[documentControllerName][callbackName])
animationManager:setCallFuncForLuaCallbackNamed(callfunc, callbackCombine);
elseif 2 == callbackType and nil ~= owner then --Owner callback
local callfunc = cc.CallFunc:create(owner[callbackName])--need check
animationManager:setCallFuncForLuaCallbackNamed(callfunc, callbackCombine)
end
end
--start animation
local autoPlaySeqId = animationManager:getAutoPlaySequenceId()
if -1 ~= autoPlaySeqId then
animationManager:runAnimationsForSequenceIdTweenDuration(autoPlaySeqId, 0)
end
end
return node
end
| mit |
EasonYi/thrift | lib/lua/TMemoryBuffer.lua | 100 | 2266 | --
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you 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.
--
require 'TTransport'
TMemoryBuffer = TTransportBase:new{
__type = 'TMemoryBuffer',
buffer = '',
bufferSize = 1024,
wPos = 0,
rPos = 0
}
function TMemoryBuffer:isOpen()
return 1
end
function TMemoryBuffer:open() end
function TMemoryBuffer:close() end
function TMemoryBuffer:peak()
return self.rPos < self.wPos
end
function TMemoryBuffer:getBuffer()
return self.buffer
end
function TMemoryBuffer:resetBuffer(buf)
if buf then
self.buffer = buf
self.bufferSize = string.len(buf)
else
self.buffer = ''
self.bufferSize = 1024
end
self.wPos = string.len(buf)
self.rPos = 0
end
function TMemoryBuffer:available()
return self.wPos - self.rPos
end
function TMemoryBuffer:read(len)
local avail = self:available()
if avail == 0 then
return ''
end
if avail < len then
len = avail
end
local val = string.sub(self.buffer, self.rPos + 1, self.rPos + len)
self.rPos = self.rPos + len
return val
end
function TMemoryBuffer:readAll(len)
local avail = self:available()
if avail < len then
local msg = string.format('Attempt to readAll(%d) found only %d available',
len, avail)
terror(TTransportException:new{message = msg})
end
-- read should block so we don't need a loop here
return self:read(len)
end
function TMemoryBuffer:write(buf)
self.buffer = self.buffer .. buf
self.wPos = self.wPos + string.len(buf)
end
function TMemoryBuffer:flush() end
| apache-2.0 |
SuperAwesomeLTD/thrift | lib/lua/TMemoryBuffer.lua | 100 | 2266 | --
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you 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.
--
require 'TTransport'
TMemoryBuffer = TTransportBase:new{
__type = 'TMemoryBuffer',
buffer = '',
bufferSize = 1024,
wPos = 0,
rPos = 0
}
function TMemoryBuffer:isOpen()
return 1
end
function TMemoryBuffer:open() end
function TMemoryBuffer:close() end
function TMemoryBuffer:peak()
return self.rPos < self.wPos
end
function TMemoryBuffer:getBuffer()
return self.buffer
end
function TMemoryBuffer:resetBuffer(buf)
if buf then
self.buffer = buf
self.bufferSize = string.len(buf)
else
self.buffer = ''
self.bufferSize = 1024
end
self.wPos = string.len(buf)
self.rPos = 0
end
function TMemoryBuffer:available()
return self.wPos - self.rPos
end
function TMemoryBuffer:read(len)
local avail = self:available()
if avail == 0 then
return ''
end
if avail < len then
len = avail
end
local val = string.sub(self.buffer, self.rPos + 1, self.rPos + len)
self.rPos = self.rPos + len
return val
end
function TMemoryBuffer:readAll(len)
local avail = self:available()
if avail < len then
local msg = string.format('Attempt to readAll(%d) found only %d available',
len, avail)
terror(TTransportException:new{message = msg})
end
-- read should block so we don't need a loop here
return self:read(len)
end
function TMemoryBuffer:write(buf)
self.buffer = self.buffer .. buf
self.wPos = self.wPos + string.len(buf)
end
function TMemoryBuffer:flush() end
| apache-2.0 |
Zenny89/darkstar | scripts/zones/Garlaige_Citadel_[S]/npcs/Randecque.lua | 21 | 1805 | -----------------------------------
-- Area: Garlaige Citadel [S]
-- NPC: Randecque
-- @pos 61 -6 137 164
-- Notes: Gives Red Letter required to start "Steamed Rams"
-----------------------------------
package.loaded["scripts/zones/Garlaige_Citadel_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Garlaige_Citadel_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCampaignAllegiance() > 0) then
if (player:getCampaignAllegiance() == 2) then
player:startEvent(3);
else
-- message for other nations missing
player:startEvent(3);
end
elseif (player:hasKeyItem(RED_RECOMMENDATION_LETTER) == true) then
player:startEvent(2);
elseif (player:hasKeyItem(RED_RECOMMENDATION_LETTER) == false) then
player:startEvent(1);
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);
if (csid == 1 and option == 0) then
player:addKeyItem(RED_RECOMMENDATION_LETTER);
player:messageSpecial(KEYITEM_OBTAINED, RED_RECOMMENDATION_LETTER);
end
end; | gpl-3.0 |
mercury233/ygopro-scripts | c67797569.lua | 2 | 3099 | --ใฉใดใกใซใใซใปใตใฉใใณใใผ
function c67797569.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,nil,aux.NonTuner(Card.IsAttribute,ATTRIBUTE_FIRE),1)
c:EnableReviveLimit()
--Draw
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(67797569,0))
e1:SetCategory(CATEGORY_DRAW+CATEGORY_TOGRAVE)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetCountLimit(1,67797569)
e1:SetCondition(c67797569.drcon)
e1:SetTarget(c67797569.drtg)
e1:SetOperation(c67797569.drop)
c:RegisterEffect(e1)
--
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(67797569,1))
e2:SetCategory(CATEGORY_POSITION)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetCountLimit(1)
e2:SetRange(LOCATION_MZONE)
e2:SetCost(c67797569.cost)
e2:SetTarget(c67797569.settg)
e2:SetOperation(c67797569.setop)
c:RegisterEffect(e2)
end
function c67797569.drcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsSummonType(SUMMON_TYPE_SYNCHRO)
end
function c67797569.drtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,2) end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(2)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,2)
end
function c67797569.tgcheck(g)
return g:IsExists(Card.IsAttribute,1,nil,ATTRIBUTE_FIRE)
end
function c67797569.drop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Draw(p,d,REASON_EFFECT)
Duel.BreakEffect()
local g=Duel.GetFieldGroup(tp,LOCATION_HAND,0)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
tg=g:SelectSubGroup(tp,c67797569.tgcheck,false,2,2)
if tg then
if Duel.SendtoGrave(tg,REASON_EFFECT)==0 then
Duel.ShuffleHand(p)
end
else
local sg=Duel.GetFieldGroup(p,LOCATION_HAND,0)
Duel.ConfirmCards(1-p,sg)
Duel.SendtoDeck(sg,nil,SEQ_DECKSHUFFLE,REASON_EFFECT)
end
end
function c67797569.refilter(c)
return c:IsAttribute(ATTRIBUTE_FIRE) and c:IsType(TYPE_MONSTER) and c:IsAbleToRemoveAsCost()
end
function c67797569.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c67797569.refilter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c67797569.refilter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c67797569.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0x39)
end
function c67797569.posfilter(c)
return c:IsFaceup() and c:IsCanTurnSet()
end
function c67797569.settg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c67797569.cfilter,tp,LOCATION_MZONE,0,1,nil)
and Duel.IsExistingMatchingCard(c67797569.posfilter,tp,0,LOCATION_MZONE,1,nil) end
end
function c67797569.setop(e,tp,eg,ep,ev,re,r,rp)
local ct=Duel.GetMatchingGroupCount(c67797569.cfilter,tp,LOCATION_MZONE,0,nil)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_POSCHANGE)
local g=Duel.SelectMatchingCard(tp,c67797569.posfilter,tp,0,LOCATION_MZONE,1,ct,nil)
if #g>0 then
Duel.HintSelection(g)
Duel.ChangePosition(g,POS_FACEDOWN_DEFENSE)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c36429703.lua | 2 | 3340 | --RR๏ผใฏใคใบใปในใใชใฏใน
function c36429703.initial_effect(c)
--link summon
aux.AddLinkProcedure(c,c36429703.matfilter,2,2)
c:EnableReviveLimit()
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(36429703,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCountLimit(1,36429703)
e1:SetCondition(c36429703.spcon)
e1:SetTarget(c36429703.sptg)
e1:SetOperation(c36429703.spop)
c:RegisterEffect(e1)
--set
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(36429703,1))
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e3:SetCode(EVENT_CHAINING)
e3:SetRange(LOCATION_MZONE)
e3:SetCountLimit(1,36429704)
e3:SetCondition(c36429703.setcon)
e3:SetOperation(c36429703.setop)
c:RegisterEffect(e3)
end
function c36429703.matfilter(c)
return c:IsLinkRace(RACE_WINDBEAST) and c:IsLinkAttribute(ATTRIBUTE_DARK)
end
function c36429703.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsSummonType(SUMMON_TYPE_LINK)
end
function c36429703.spfilter(c,e,tp)
return c:IsLevel(4) and c:IsRace(RACE_WINDBEAST) and c:IsAttribute(ATTRIBUTE_DARK) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP_DEFENSE)
end
function c36429703.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c36429703.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c36429703.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c36429703.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
local tc=g:GetFirst()
if tc and Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP_DEFENSE) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetValue(RESET_TURN_SET)
e2:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e2)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_CANNOT_BE_LINK_MATERIAL)
e3:SetValue(1)
e3:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e3)
end
Duel.SpecialSummonComplete()
end
function c36429703.setcon(e,tp,eg,ep,ev,re,r,rp)
local rc=re:GetHandler()
return re:IsActiveType(TYPE_XYZ) and rc:IsSetCard(0xba) and rc:IsControler(tp)
end
function c36429703.setfilter(c)
return c:IsSetCard(0x95) and c:IsType(TYPE_SPELL) and c:IsSSetable()
end
function c36429703.setop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SET)
local g=Duel.SelectMatchingCard(tp,c36429703.setfilter,tp,LOCATION_DECK,0,1,1,nil)
local tc=g:GetFirst()
if tc and Duel.SSet(tp,tc)~=0 then
if tc:IsType(TYPE_QUICKPLAY) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SET_AVAILABLE)
e1:SetCode(EFFECT_QP_ACT_IN_SET_TURN)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e1)
end
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c92142169.lua | 2 | 1769 | --ใใฏใใฐ
function c92142169.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e1:SetRange(LOCATION_HAND)
e1:SetCondition(c92142169.spcon)
e1:SetValue(SUMMON_VALUE_SELF)
c:RegisterEffect(e1)
--atkchange
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(92142169,0))
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCondition(c92142169.atkcon)
e2:SetTarget(c92142169.atktg)
e2:SetOperation(c92142169.atkop)
c:RegisterEffect(e2)
end
function c92142169.filter(c)
return c:IsFaceup() and c:IsType(TYPE_XYZ)
end
function c92142169.spcon(e,c)
if c==nil then return true end
return Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0 and
Duel.IsExistingMatchingCard(c92142169.filter,c:GetControler(),0,LOCATION_MZONE,1,nil)
end
function c92142169.atkcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_SPECIAL+SUMMON_VALUE_SELF
end
function c92142169.atktg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and chkc:IsFaceup() end
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
Duel.SelectTarget(tp,Card.IsFaceup,tp,0,LOCATION_MZONE,1,1,nil)
end
function c92142169.atkop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) and tc:IsFaceup() then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(-300)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e1)
end
end
| gpl-2.0 |
notcake/gcompute | lua/gcompute/interop/epoe.lua | 1 | 1236 | local self = {}
GCompute.EPOE = GCompute.MakeConstructor (self)
function self:ctor ()
self.LineBuffer =
{
{
Text = ""
}
}
hook.Add ("EPOE", "GCompute.EPOE",
function (message, colorId, color)
if not color then
if colorId == 2 then
color = GLib.Colors.IndianRed
elseif colorId == 4 then
color = GLib.Colors.White
elseif colorId == 8 then
color = GLib.Colors.SandyBrown
end
end
local lines = message:Split ("\n")
for i = 1, #lines do
if i > 1 then
self.LineBuffer [#self.LineBuffer + 1] =
{
Text = ""
}
end
local line = self.LineBuffer [#self.LineBuffer]
line.Text = line.Text .. lines [i]
line [#line + 1] =
{
Text = lines [i],
Color = color
}
end
while #self.LineBuffer > 1 do
self:DispatchEvent ("LineReceived", self.LineBuffer [1])
table.remove (self.LineBuffer, 1)
end
end
)
GCompute.AddEventListener ("Unloaded", self:GetHashCode (),
function ()
self:dtor ()
end
)
GCompute.EventProvider (self)
end
function self:dtor ()
hook.Remove ("EPOE", "GCompute.EPOE")
GCompute.RemoveEventListener ("Unloaded", self:GetHashCode ())
end
GCompute.EPOE = GCompute.EPOE () | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.