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
Metastruct/pac3
lua/pac3/extra/client/pac2_compat.lua
2
17322
local bones = { ["pelvis"] = "valvebiped.bip01_pelvis", ["spine"] = "valvebiped.bip01_spine", ["spine 2"] = "valvebiped.bip01_spine1", ["spine 3"] = "valvebiped.bip01_spine2", ["spine 4"] = "valvebiped.bip01_spine4", ["neck"] = "valvebiped.bip01_neck1", ["head"] = "valvebiped.bip01_head1", ["right clavicle"] = "valvebiped.bip01_r_clavicle", ["right upper arm"] = "valvebiped.bip01_r_upperarm", ["right upperarm"] = "valvebiped.bip01_r_upperarm", ["right forearm"] = "valvebiped.bip01_r_forearm", ["right hand"] = "valvebiped.bip01_r_hand", ["left clavicle"] = "valvebiped.bip01_l_clavicle", ["left upper arm"] = "valvebiped.bip01_l_upperarm", ["left upperarm"] = "valvebiped.bip01_l_upperarm", ["left forearm"] = "valvebiped.bip01_l_forearm", ["left hand"] = "valvebiped.bip01_l_hand", ["right thigh"] = "valvebiped.bip01_r_thigh", ["right calf"] = "valvebiped.bip01_r_calf", ["right foot"] = "valvebiped.bip01_r_foot", ["right toe"] = "valvebiped.bip01_r_toe0", ["left thigh"] = "valvebiped.bip01_l_thigh", ["left calf"] = "valvebiped.bip01_l_calf", ["left foot"] = "valvebiped.bip01_l_foot", ["left toe"] = "valvebiped.bip01_l_toe0", } local function translate_bone(bone) if bones[bone] then return bones[bone] end if not bone.lower then debug.Trace() return "" end bone = bone:lower() for key, val in pairs(bones) do if bone == val then return key end end return bone end function pacx.ConvertPAC2Config(data, name) local _out = {} local base = pac.CreatePart("group") base:SetName(name or "pac2 outfit") for key, data in pairs(data.parts) do if data.sprite.Enabled then local part = pac.CreatePart("sprite") part:SetParent(base) part.pac2_part = data part:SetName(data.name .. " sprite") part:SetBone(translate_bone(data.bone)) part:SetColor(Vector(data.sprite.color.r, data.sprite.color.g, data.sprite.color.b)) part:SetAlpha(data.sprite.color.a / 255) part:SetPosition(data.offset*1) part:SetAngles(data.angles*1) --part:SetAngleVelocity(Angle(data.anglevelocity.p, -data.anglevelocity.r, data.anglevelocity.y)*0.5) part:SetMaterial(data.sprite.material) part:SetSizeX(data.sprite.x) part:SetSizeY(data.sprite.y) part:SetEyeAngles(data.eyeangles) if data.weaponclass and data.weaponclass ~= "" then local part_ = pac.CreatePart("event") part_:SetName(part.Name .. " weapon class") part_:SetParent(part) part_:SetEvent("weapon_class") part_:SetOperator("find simple") part_:SetInvert(true) part_:SetArguments(data.weaponclass .. "@@" .. (data.hideweaponclass and "1" or "0")) end end if data.light.Enabled then local part = pac.CreatePart("light") part:SetParent(base) part.pac2_part = data part:SetName(data.name .. " light") part:SetBone(translate_bone(data.bone)) part:SetColor(Vector(data.light.r, data.light.g, data.light.b)) part:SetPosition(data.offset*1) part:SetAngles(data.angles*1) --part:SetAngleVelocity(Angle(data.anglevelocity.p, -data.anglevelocity.r, data.anglevelocity.y)*0.5) part:SetBrightness(data.light.Brightness) part:SetSize(data.light.Size) if data.weaponclass and data.weaponclass ~= "" then local part_ = pac.CreatePart("event") part_:SetName(part.Name .. " weapon class") part_:SetParent(part) part_:SetEvent("weapon_class") part_:SetOperator("find simple") part_:SetInvert(true) part_:SetArguments(data.weaponclass .. "@@" .. (data.hideweaponclass and "1" or "0")) end end if data.text.Enabled then local part = pac.CreatePart("text") part:SetParent(base) part.pac2_part = data part:SetName(data.name .. " text") part:SetBone(translate_bone(data.bone)) part:SetColor(Vector(data.text.color.r, data.text.color.g, data.text.color.b)) part:SetAlpha(data.text.color.a / 255) part:SetColor(Vector(data.text.outlinecolor.r, data.text.outlinecolor.g, data.text.outlinecolor.b)) part:SetAlpha(data.text.outlinecolor.a / 255) part:SetPosition(data.offset*1) part:SetAngles(data.angles*1) --part:SetAngleVelocity(Angle(data.anglevelocity.p, -data.anglevelocity.r, data.anglevelocity.y)*0.5) part:SetOutline(data.text.outline) part:SetText(data.text.text) part:SetFont(data.text.font) part:SetSize(data.text.size) part:SetEyeAngles(data.eyeangles) if data.weaponclass and data.weaponclass ~= "" then local part_ = pac.CreatePart("event") part_:SetName(part.Name .. " weapon class") part_:SetParent(part) part_:SetEvent("weapon_class") part_:SetOperator("find simple") part_:SetInvert(true) part_:SetArguments(data.weaponclass .. "@@" .. (data.hideweaponclass and "1" or "0")) end end if data.trail.Enabled then local part = pac.CreatePart("trail") part:SetParent(base) part.pac2_part = data part:SetName(data.name .. " trail") part:SetBone(translate_bone(data.bone)) part:SetPosition(data.offset*1) part:SetAngles(data.angles*1) --part:SetAngleVelocity(Angle(data.anglevelocity.p, -data.anglevelocity.r, data.anglevelocity.y)*0.5) part:SetStartSize(data.trail.startsize) part:SetStartColor(Vector(data.trail.color.r, data.trail.color.g, data.trail.color.b)) part:SetEndColor(Vector(data.trail.color.r, data.trail.color.g, data.trail.color.b)) part:SetStartAlpha(data.trail.color.a/255) part:SetEndAlpha(data.trail.color.a/255) part:SetSpacing(0) part:SetMaterial(data.trail.material) part:SetLength(data.trail.length) if data.weaponclass and data.weaponclass ~= "" then local part_ = pac.CreatePart("event") part_:SetName(part.Name .. " weapon class") part_:SetParent(part) part_:SetEvent("weapon_class") part_:SetOperator("find simple") part_:SetInvert(true) part_:SetArguments(data.weaponclass .. "@@" .. (data.hideweaponclass and "1" or "0")) end end if true or data.color.a ~= 0 and data.size ~= 0 and data.scale ~= vector_origin or data.effect.Enabled then local part = pac.CreatePart("model") part:SetParent(base) part.pac2_part = data part:SetName(data.name .. " model") part:SetBone(translate_bone(data.bone)) part:SetMaterial(data.material) part:SetColor(Vector(data.color.r, data.color.g, data.color.b)) part:SetAlpha(data.color.a / 255) part:SetModel(data.model) part:SetSize(data.size) part:SetScale(data.scale*1) part:SetPosition(data.offset*1) part:SetAngles(data.angles*1) --part:SetAngleVelocity(Angle(data.anglevelocity.p, -data.anglevelocity.r, data.anglevelocity.y)*0.5) part:SetInvert(data.mirrored) part:SetFullbright(data.fullbright) part:SetEyeAngles(data.eyeangles) if data.effect.Enabled then local part2 = pac.CreatePart("effect") part2:SetName(data.name .. " effect") part2:SetParent(part) part2:SetBone(translate_bone(data.bone)) part2:SetLoop(data.effect.loop) part2:SetRate(data.effect.rate) part2:SetEffect(data.effect.effect) if data.weaponclass and data.weaponclass ~= "" then local part_ = pac.CreatePart("event") part_:SetName(part2.Name .. " weapon class") part_:SetParent(part2) part_:SetEvent("weapon_class") part_:SetOperator("find simple") part_:SetInvert(true) part_:SetArguments(data.weaponclass .. "@@" .. (data.hideweaponclass and "1" or "0")) end end if data.clip.Enabled then local part2 = part:CreatePart("clip") part2:SetName(data.name .. " clip") if data.clip.bone and data.clip.bone ~= "" then part2:SetBone(data.clip.bone) end part2:SetParent(part) part2:SetPosition(data.clip.angles:Forward() * data.clip.distance) part2:SetAngles(data.clip.angles*-1) end if data.animation.Enabled then local part2 = part:CreatePart("animation") part2:SetParent(part) part2:SetName(data.name .. " animation") part2:SetSequenceName(data.animation.sequence or "") part2:SetRate(data.animation.rate) part2:SetMin(data.animation.min) part2:SetMax(data.animation.max) part2:SetOffset(data.animation.offset) part2:SetPingPongLoop(data.animation.loopmode) part:AddChild(part2) end if data.modelbones.Enabled then part:SetBoneMerge(data.modelbones.merge) part.pac2_modelbone = data.modelbones.redirectparent for key, bone in pairs(data.modelbones.bones) do bone.size = tonumber(bone.size) if bone.scale == Vector(1,1,1) and bone.angles == Vector(0,0,0) and bone.offset == Vector(0,0,0) and bone.size == 1 then goto CONTINUE end local part2 = pac.CreatePart("bone") part2:SetName("model bone " .. part:GetName() .. " " .. key) part2:SetParent(part) part2:SetBone(part:GetEntity():GetBoneName(key)) part2:SetScale(bone.scale*1) part2:SetAngles(bone.angles*1) part2:SetPosition(bone.offset*1) part2:SetSize(bone.size) ::CONTINUE:: end end if data.weaponclass and data.weaponclass ~= "" then local part_ = pac.CreatePart("event") part_:SetName(part.Name .. " weapon class") part_:SetParent(part) part_:SetEvent("weapon_class") part_:SetOperator("find simple") part_:SetInvert(true) part_:SetArguments(data.weaponclass .. "@@" .. (data.hideweaponclass and "1" or "0")) end end end local part = pac.CreatePart("entity") part:SetParent(base) part:SetName("player") part:SetColor(Vector(data.player_color.r, data.player_color.g, data.player_color.b)) part:SetAlpha(data.player_color.a/255) part:SetMaterial(data.player_material) part:SetScale(data.overall_scale*1) part:SetDrawWeapon(data.drawwep) for bone, data in pairs(data.bones) do local part_ = pac.CreatePart("bone") part_:SetParent(part) part_:SetName(bone .. " bone") part_:SetBone(translate_bone(bone)) part_:SetSize(tonumber(data.size)) part_:SetScale(data.scale*1) part_:SetPosition(data.offset*1) part_:SetAngles(data.angles*1) end for key, part in pairs(pac.GetLocalParts()) do if part.pac2_part and part.pac2_part.parent and part.pac2_part.parent ~= "none" then for key, parent in pairs(pac.GetLocalParts()) do if parent:GetName() == (part.pac2_part.parent .. " model") then part:SetParent(parent) if parent.pac2_modelbone then part:SetBone(translate_bone(parent.pac2_modelbone)) end end end end end -- hacks for key, part in pairs(pac.GetLocalParts()) do part:SetParent(part:GetParent()) end return base end local glon = {} do local decode_types decode_types = { -- \2\6omg\1\6omgavalue\1\1 [2 ] = function(reader, rtabs) -- table local t, c, pos = {}, reader:Next() rtabs[#rtabs+1] = t local stage = false local key while true do c, pos = reader:Peek() if c == "\1" then if stage then error(string.format("Expected value to match key at %s! (Got EO Table)", pos)) else reader:Next() return t end else if stage then t[key] = Read(reader, rtabs) else key = Read(reader, rtabs) end stage = not stage end end end, [3 ] = function(reader, rtabs) -- array local t, i, c, pos = {}, 1, reader:Next() rtabs[#rtabs+1] = t while true do c, pos = reader:Peek() if c == "\1" then reader:Next() return t else t[i] = Read(reader, rtabs) i = i+1 end end end, [4 ] = function(reader) -- false boolean reader:Next() return false end, [5 ] = function(reader) -- true boolean reader:Next() return true end, [6 ] = function(reader) -- number local s, c, pos, e = "", reader:Next() while true do c = reader:Next() if not c then error(string.format("Expected \1 to end number at %s! (Got EOF!)", pos)) elseif c == "\1" then break else s = s..c end end if s == "" then s = "0" end local n = tonumber(s) if not n then error(string.format("Invalid number at %s! (%q)", pos, s)) end return n end, [7 ] = function(reader) -- string local s, c, pos, e = "", reader:Next() while true do c = reader:Next() if not c then error(string.format("Expected unescaped \1 to end string at position %s! (Got EOF)", pos)) elseif e then if c == "\3" then s = s.."\0" else s = s..c end e = false elseif c == "\2" then e = true elseif c == "\1" then s = string.gsub(s, "\4", "\"") -- unescape quotes return s else s = s..c end end end, [8 ] = function(reader) -- Vector local x = decode_types[6](reader) reader:StepBack() local y = decode_types[6](reader) reader:StepBack() local z = decode_types[6](reader) return Vector(x, y, z) end, [9 ] = function(reader) -- Angle local p = decode_types[6](reader) reader:StepBack() local y = decode_types[6](reader) reader:StepBack() local r = decode_types[6](reader) return Angle(p, y, r) end, [13 ] = function(reader) -- ConVar return GetConVar(decode_types[7](reader)) end, [15 ] = function(reader) -- Color local r = decode_types[6](reader) reader:StepBack() local g = decode_types[6](reader) reader:StepBack() local b = decode_types[6](reader) reader:StepBack() local a = decode_types[6](reader) return Color(r, g, b, a) end, [253] = function(reader) -- -math.huge reader:Next() return -math.huge end, [254] = function(reader) -- math.huge reader:Next() return math.huge end, [255] = function(reader, rtabs) -- Reference return rtabs[decode_types[6](reader) - 1] end, } function Read(reader, rtabs) local t, pos = reader:Peek() if not t then error(string.format("Expected type ID at %s! (Got EOF)", pos)) else local dt = decode_types[string.byte(t)] if not dt then error(string.format("Unknown type ID, %s!", string.byte(t))) else return dt(reader, rtabs or {0}) end end end local reader_meta = {} reader_meta.__index = reader_meta function reader_meta:Next() self.i = self.i+1 self.c = string.sub(self.s, self.i, self.i) if self.c == "" then self.c = nil end self.p = string.sub(self.s, self.i+1, self.i+1) if self.p == "" then self.p = nil end return self.c, self.i end function reader_meta:StepBack() self.i = self.i-1 self.c = string.sub(self.s, self.i, self.i) if self.c == "" then self.c = nil end self.p = string.sub(self.s, self.i+1, self.i+1) if self.p == "" then self.p = nil end return self.c, self.i end function reader_meta:Peek() return self.p, self.i+1 end function glon.decode(data) if type(data) == "nil" then return nil elseif type(data) ~= "string" then error(string.format("Expected string to decode! (Got type %s)", type(data) )) elseif data:len() == 0 then return nil end return Read(setmetatable({ s = data, i = 0, c = string.sub(data, 0, 0), p = string.sub(data, 1, 1), }, reader_meta), {}) end end concommand.Add("pac_convert_pac2_outfits", function() if not file.IsDir("pac2_outfits", "DATA") then pac.Message("garrysmod/data/pac2_outfits/ does not exist") return end local folders = select(2, file.Find("pac2_outfits/*", "DATA")) if #folders == 0 then pac.Message("garrysmod/data/pac2_outfits/ is empty") return end for _, uniqueid in ipairs(folders) do local owner_nick = file.Read("pac2_outfits/" .. uniqueid .. "/__owner.txt", "DATA") if not owner_nick then owner_nick = LocalPlayer():Nick() pac.Message("garrysmod/data/pac2_outfits/" .. uniqueid .. "/__owner.txt does not exist (it contains the player nickname) defaulting to " .. owner_nick) end local folders = select(2, file.Find("pac2_outfits/" .. uniqueid .. "/*", "DATA")) if #folders == 0 then pac.Message("garrysmod/data/pac2_outfits/" .. uniqueid .. "/ is empty") return end for _, folder_name in ipairs(folders) do local name = file.Read("pac2_outfits/" .. uniqueid .. "/" .. folder_name .. "/name.txt", "DATA") local data = file.Read("pac2_outfits/" .. uniqueid .. "/" .. folder_name .. "/outfit.txt", "DATA") if not name then pac.Message("garrysmod/data/pac2_outfits/" .. uniqueid .. "/" .. folder_name .. "/name.txt does not exist. defaulting to: " .. folder_name) end if data then pace.ClearParts() local ok, res = pcall(function() pacx.ConvertPAC2Config(glon.decode(data), name) end) if ok then file.CreateDir("pac3/pac2_outfits/") file.CreateDir("pac3/pac2_outfits/" .. uniqueid .. "/") pace.SaveParts("pac2_outfits/" .. uniqueid .. "/" .. folder_name) else pac.Message("garrysmod/data/pac2_outfits/" .. uniqueid .. "/" .. folder_name .. "(" .. name .. ") failed to convert : " .. res) end else pac.Message("garrysmod/data/pac2_outfits/" .. uniqueid .. "/" .. folder_name .. "/data.txt does not exist. this file contains the outfit data") end end end pace.ClearParts() pac.Message("pac2 outfits are stored under pac > load > pac2_outfits in the editor") pac.Message("you may need to restart the editor to see them") end)
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c25280974.lua
2
1571
--魔道化リジョン function c25280974.initial_effect(c) --extra summon local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_EXTRA_SUMMON_COUNT) e1:SetRange(LOCATION_MZONE) e1:SetTargetRange(LOCATION_HAND,0) e1:SetTarget(aux.TargetBoolFunction(Card.IsRace,RACE_SPELLCASTER)) e1:SetValue(0x1) c:RegisterEffect(e1) --tohand local e2=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(25280974,0)) e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e2:SetCode(EVENT_TO_GRAVE) e2:SetCountLimit(1,25280974) e2:SetCondition(c25280974.thcon) e2:SetTarget(c25280974.thtg) e2:SetOperation(c25280974.thop) c:RegisterEffect(e2) end function c25280974.thcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD) end function c25280974.filter(c) return c:IsType(TYPE_NORMAL) and c:IsRace(RACE_SPELLCASTER) and c:IsAbleToHand() end function c25280974.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c25280974.filter,tp,LOCATION_DECK+LOCATION_GRAVE,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK+LOCATION_GRAVE) end function c25280974.thop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(c25280974.filter),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
dickeyf/darkstar
scripts/zones/Phomiuna_Aqueducts/npcs/_0rr.lua
13
1451
----------------------------------- -- Area: Phomiuna_Aqueducts -- NPC: Oil lamp -- @pos -60 -23 60 27 ----------------------------------- package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Phomiuna_Aqueducts/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DoorOffset = npc:getID(); player:messageSpecial(LAMP_OFFSET+7); -- dark lamp npc:openDoor(7); -- lamp animation local element = VanadielDayElement(); --printf("element: %u",element); if (element == 6 or element == 7) then -- lightday or darkday if (GetNPCByID(DoorOffset-1):getAnimation() == 8) then -- lamp light open ? GetNPCByID(DoorOffset-6):openDoor(15); -- Open Door _0rk end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c69610326.lua
2
3635
--覇王眷竜ダークヴルム function c69610326.initial_effect(c) aux.EnablePendulumAttribute(c) --pendulum set local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(69610326,0)) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_PZONE) e1:SetCountLimit(1) e1:SetCondition(c69610326.pccon) e1:SetTarget(c69610326.pctg) e1:SetOperation(c69610326.pcop) c:RegisterEffect(e1) --search local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(69610326,1)) e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_SUMMON_SUCCESS) e2:SetProperty(EFFECT_FLAG_DELAY) e2:SetCountLimit(1,69610326) e2:SetTarget(c69610326.thtg) e2:SetOperation(c69610326.thop) c:RegisterEffect(e2) local e3=e2:Clone() e3:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e3) --spsummon local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(69610326,2)) e4:SetCategory(CATEGORY_SPECIAL_SUMMON) e4:SetType(EFFECT_TYPE_IGNITION) e4:SetRange(LOCATION_GRAVE) e4:SetCountLimit(1,69610327) e4:SetCondition(c69610326.pccon) e4:SetTarget(c69610326.sptg) e4:SetOperation(c69610326.spop) c:RegisterEffect(e4) end function c69610326.pccon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetFieldGroupCount(tp,LOCATION_MZONE,0)==0 end function c69610326.pcfilter(c) return c:IsSetCard(0x10f8) and c:IsType(TYPE_PENDULUM) and not c:IsForbidden() end function c69610326.pctg(e,tp,eg,ep,ev,re,r,rp,chk) local seq=e:GetHandler():GetSequence() if chk==0 then return Duel.CheckLocation(tp,LOCATION_SZONE,13-seq) and Duel.IsExistingMatchingCard(c69610326.pcfilter,tp,LOCATION_DECK,0,1,nil) end end function c69610326.pcop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsRelateToEffect(e) then return end local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetTargetRange(1,0) e1:SetTarget(c69610326.splimit) e1:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e1,tp) local seq=c:GetSequence() if not Duel.CheckLocation(tp,LOCATION_SZONE,13-seq) then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOFIELD) local g=Duel.SelectMatchingCard(tp,c69610326.pcfilter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.MoveToField(g:GetFirst(),tp,tp,LOCATION_SZONE,POS_FACEUP,true) end end function c69610326.splimit(e,c,sump,sumtype,sumpos,targetp,se) return not c:IsAttribute(ATTRIBUTE_DARK) and bit.band(sumtype,SUMMON_TYPE_PENDULUM)==SUMMON_TYPE_PENDULUM end function c69610326.thfilter(c) return c:IsSetCard(0x10f8) and c:IsType(TYPE_PENDULUM) and c:IsAbleToHand() end function c69610326.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c69610326.thfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c69610326.thop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c69610326.thfilter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end function c69610326.sptg(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,0,0) end function c69610326.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 then Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
Turttle/darkstar
scripts/zones/Port_San_dOria/npcs/Prietta.lua
13
1435
----------------------------------- -- Area: Port San d'Oria -- NPC: Prietta -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) ==QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradePrietta") == 0) then player:messageSpecial(7121); player:setVar("FFR",player:getVar("FFR") - 1); player:setVar("tradePrietta",1); player:messageSpecial(7122,17 - player:getVar("FFR")); trade:complete(); elseif (player:getVar("tradePrietta") ==1) then player:messageSpecial(7120); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x254); 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
Nak2/StormFox
lua/stormfox/language/fr.lua
1
9379
return [[Stormfox French #StormFox sf_description.newversion = Vous utilisez une version bêta de SF sf_description.oldversion = Vous utilisez une ancienne version de SF #Tool sf_tool.menu = Menu sf_tool.maptexture = Texture de la map sf_tool.maptexture.helpm1 = Appuyez sur click gauche pour ajouter une texture sf_tool.maptexture.helpm2 = Appuyez sur click droit pour ajouter une texture sf_tool.permaentity = Entité permanente sf_tool.addmaterial = Ajouter sf_tool.cancel = Annuler sf_tool.menu_reload = Appuyez sur R pour ouvrir le menu #Variables sf_type.roof = Toit sf_type.dirtgrass = Terre/Herbe sf_type.road = Route sf_type.pavement = Pavé # - Weather sf_weather.clear = Clair sf_weather.rain = Pluie sf_weather.raining = Pluie sf_weather.sleet = Neige fondue sf_weather.snowing = Neige sf_weather.fog = Brouillard sf_weather.light_fog = Brouillard léger sf_weather.heavy_fog = Brouillard épais sf_weather.storm = Orage sf_weather.thunder = Tonnerre sf_weather.cloudy = Nuageux sf_weather.lava = Lave sf_weather.lava_eruption= Éruption volcanique sf_weather.sandstorm = Tempête de sable sf_weather.radioactive = Radioactive sf_weather.radioactive_rain = Pluie radioactive # - Wind sf_winddescription.calm = Calme sf_winddescription.light_air = Air léger sf_winddescription.light_breeze = Légère brise sf_winddescription.gentle_breeze = Brise douce sf_winddescription.moderate_breeze = Brise modérée sf_winddescription.fresh_breeze = Brise fraîche sf_winddescription.strong_breeze = Forte brise sf_winddescription.near_gale = Leger coup de vent sf_winddescription.gale = Coup de vent sf_winddescription.strong_gale = Forte tempête sf_winddescription.storm = Tempête sf_winddescription.violent_storm = Tempête violente sf_winddescription.hurricane = Ouragan sf_winddescription.cat2 = Categorie 2 sf_winddescription.cat3 = Categorie 3 sf_winddescription.cat4 = Categorie 4 sf_winddescription.cat5 = Categorie 5 #Weather sf_current_weather = Météo actuelle #Server Settings sf_description.autopilot = Essayer de résoudre tous les problèmes au lancement. sf_description.timespeed = Les secondes du temps de jeu en secondes réelles. sf_description.moonscale = Echelle de la lune. sf_description.moonphase = Activez les phases de lune. sf_description.enablefog = Autoriser SF à éditer le brouillard. sf_description.weatherdebuffs = Activer les affaiblissements/dommages/impactes dus aux intempéries. sf_description.windpush = Activer la poussée du vent sur les props. sf_description.lightningbolts = Activer les coups de foudre. sf_description.enable_mapsupport = Activer le support des entités pour les maps. sf_description.sunmoon_yaw = Décalage soleil/lune. sf_description.debugcompatibility = Activer le débugueur de compatibilité SF. sf_description.skybox = Activer la skybox de SF. sf_description.enable_ekstra_lightsupport = Activer la prise en charge de l'éclairage de l'extra (lags sur les grandes maps) sf_description.start_time = Démarrez le serveur à un moment précis. sf_description.mapbloom = Autoriser SF a éditer le flou lumineuse. sf_description.enable_mapbrowser = Permettre aux administrateurs de changer la map avec le navigateur SF. sf_description.allowcl_disableeffects = Permet aux joueurs de désactiver les effets de SF. sf_description.autoweather = Activer la génération automatique de la météo. sf_description.realtime = Suivre l'heure locale. sf_description.foliagesway = Activer le mouvement des feuillages. sf_description.override_soundscape = Remplacer les sons d'ambiance de la map. sf_description.sf_enable_ekstra_entsupport = Mettez à jour tous les droits sur les changements légers (Lourd pour les serveurs.) #Client Settings sf_description.disableeffects = Désactive tous les effets. sf_description.exspensive = [0-7+] Permet des calculs météorologiques coûteux. sf_description.exspensive_fps = Met à l'échelle le réglage de qualité avec FPS. sf_description.exspensive_manually = Régle manuellement les paramètres de la qualité. sf_description.material_replacment = Permet le remplacement des textures pendant les intempéries. sf_description.allow_rainsound = Active les sons de pluie. sf_description.allow_windsound = Active les sons du vent. sf_description.allow_dynamiclights = Permet d'allumer les lampes de SF. sf_description.allow_sunbeams = Active les rayons du soleil. sf_description.allow_dynamicshadow = Active les ombres et lumières dynamiques. sf_description.dynamiclightamount = Contrôle le volume de lumière dynamique. sf_description.redownloadlightmaps = Mise à jour des maps lumineuses (Lag sur grandes maps) sf_description.allow_raindrops = Active les gouttes de pluie sur l'écran sf_description.renderscreenspace_effects = Active les effets d'espace d'écran de rendu sf_description.useAInode = Utilise les noeuds AI pour des sons et des effets plus fiables. sf_description.enable_breath = Active les effets de respiration. sf_description.enable_windoweffect = Active les gouttes de pluie sur les vitres. sf_description.enable_windoweffect_enable_tr = Vérifie s'il pleut sur les vitres. sf_description.rainpuddle_enable = Flaques d'eau de pluie. (Besoin des noeuds AI) sf_description.footsteps_enable = Traces de pas dans la neige. sf_description.footsteps_max = Traces de pas maximales. sf_description.footsteps_distance = Distance de rendu pour les pas dans la neige. sf_description.hq_shadowmaterial = Définir les options d'ombre haute qualité #Map Settings sf_description.map_entities = Entités maximales sf_description.dynamiclight = Permet l'utilisation de la lumière dynamique pour tous les joueurs. sf_description.replace_dirtgrassonly = Remplace uniquement l'herbe et la terre. sf_description.wind_breakconstraints = Brise les contraintes et dégele les props par vent fort. #StormFox msg sf_added_content = Ajout de fichiers de contenu %i sf_permisson.deny = Vous n'avez pas accès aux paramètres météorologiques sf_permisson.denysettings = Vous n'avez pas accès aux paramètres SF sf_permisson.denymap = Vous n'avez pas l'autorisation de changer la map sf_permisson.denymapsetting = Ce serveur a désactivé le navigateur de map sf_permisson.denymapmissing = Le serveur n'a pas la map sf_generating.puddles = Positions des flaques d'eau générées sf_missinglanguage = Fichier de langue manquant : #MapData sf_mapdata_load = Données cartographiques chargées. sf_mapdata_invalid = Les données cartographiques du serveur ne sont pas valides ! sf_mapdata_cleanup = Nettoyage des changements de maps .... sf_ain_load = Fichier .ain chargé #Interface basics Settings = Réglages Server Settings = Paramètres du serveur Client Settings = Paramètres du client Controller = Contrôleur Troubleshooter = Dépannage Reset = Réinitialiser Weather Controller = Contrôleur météorologique Effects = Effets Map Browser = Navigateur de map Map = Map Clients = Joueurs Other = Autres Time = Temps Misc = Divers Weather = Météo Auto Weather = Météo automatique Adv Light = Lumière avancée Sun / Moon = Soleil / Lune Changelog = Changelog Temperature = Température Wind = Vent Quality = Qualité Materials = Matériaux Rain/Snow Effects= Effets de la pluie et de la neige #Interface adv sf_troubleshooter.description = Ceci affichera les problèmes courants avec les réglages. sf_temperature_range = Plage de température sf_setwindangle = Régler l'angle de vent sf_setweather = Changer la météo sf_settime = Changer l'heure sf_holdc = Maintenir C sf_interface_lighttheme = Thème clair sf_interface_darktheme = Thème sombre sf_interface_light = Lumière sf_interface_light_range = Portée de la lumière: sf_interface_save_on_exit = Sauvegarder à la sortie sf_interface_adv_light = Lumière avancée sf_interface_closechat = Fermer le chat pour interagir sf_interface_closeconsole = Fermer la console sf_interface_material_replacment= Remplacement des textures sf_interface_max_wind = Vent maximum sf_interface_max_footprints = Traces de pas maximales sf_interface_footprint_render = Distance de rendu des traces de pas sf_interface_language = Forcer une langue #Errors and warning sf_missing_convar = option non-existante sf_warning_clientlag = Peut ralentir certains joueurs ! sf_warning_serverlag = Peut causer des lags importants sur un serveur ! sf_warning_reqmapchange = Nécessite un changement de map sf_description.disabled_on_server = Désactivé sur ce serveur sf_warning_unsupportmap = Requis sur les maps non prises en charge sf_warning_missingmaterial.title = Il vous manque des textures. sf_warning_missingmaterial.nevershow = Ne plus jamais montrer ça sf_warning_missingmaterial = Il vous manque %i texture. sf_warning_unfinished_a = Ce n'est pas encore fini. Veuillez utiliser le dépannage dans les paramètres du serveur. sf_warning_unfinished_b = Ouvrir le dépannage côté serveur (nécessite l'autorisation) ]]
apache-2.0
darcy0511/Dato-Core
src/unity/python/graphlab/lua/pl/lapp.lua
20
13955
--- Simple command-line parsing using human-readable specification. -- Supports GNU-style parameters. -- -- lapp = require 'pl.lapp' -- local args = lapp [[ -- Does some calculations -- -o,--offset (default 0.0) Offset to add to scaled number -- -s,--scale (number) Scaling factor -- <number>; (number ) Number to be scaled -- ]] -- -- print(args.offset + args.scale * args.number) -- -- Lines begining with '-' are flags; there may be a short and a long name; -- lines begining wih '<var>' are arguments. Anything in parens after -- the flag/argument is either a default, a type name or a range constraint. -- -- See @{08-additional.md.Command_line_Programs_with_Lapp|the Guide} -- -- Dependencies: `pl.sip` -- @module pl.lapp local status,sip = pcall(require,'pl.sip') if not status then sip = require 'sip' end local match = sip.match_at_start local append,tinsert = table.insert,table.insert sip.custom_pattern('X','(%a[%w_%-]*)') local function lines(s) return s:gmatch('([^\n]*)\n') end local function lstrip(str) return str:gsub('^%s+','') end local function strip(str) return lstrip(str):gsub('%s+$','') end local function at(s,k) return s:sub(k,k) end local function isdigit(s) return s:find('^%d+$') == 1 end local lapp = {} local open_files,parms,aliases,parmlist,usage,windows,script lapp.callback = false -- keep Strict happy local filetypes = { stdin = {io.stdin,'file-in'}, stdout = {io.stdout,'file-out'}, stderr = {io.stderr,'file-out'} } --- controls whether to dump usage on error. -- Defaults to true lapp.show_usage_error = true --- quit this script immediately. -- @string msg optional message -- @bool no_usage suppress 'usage' display function lapp.quit(msg,no_usage) if no_usage == 'throw' then error(msg) end if msg then io.stderr:write(msg..'\n\n') end if not no_usage then io.stderr:write(usage) end os.exit(1) end --- print an error to stderr and quit. -- @string msg a message -- @bool no_usage suppress 'usage' display function lapp.error(msg,no_usage) if not lapp.show_usage_error then no_usage = true elseif lapp.show_usage_error == 'throw' then no_usage = 'throw' end lapp.quit(script..': '..msg,no_usage) end --- open a file. -- This will quit on error, and keep a list of file objects for later cleanup. -- @string file filename -- @string[opt] opt same as second parameter of `io.open` function lapp.open (file,opt) local val,err = io.open(file,opt) if not val then lapp.error(err,true) end append(open_files,val) return val end --- quit if the condition is false. -- @bool condn a condition -- @string msg message text function lapp.assert(condn,msg) if not condn then lapp.error(msg) end end local function range_check(x,min,max,parm) lapp.assert(min <= x and max >= x,parm..' out of range') end local function xtonumber(s) local val = tonumber(s) if not val then lapp.error("unable to convert to number: "..s) end return val end local types = {} local builtin_types = {string=true,number=true,['file-in']='file',['file-out']='file',boolean=true} local function convert_parameter(ps,val) if ps.converter then val = ps.converter(val) end if ps.type == 'number' then val = xtonumber(val) elseif builtin_types[ps.type] == 'file' then val = lapp.open(val,(ps.type == 'file-in' and 'r') or 'w' ) elseif ps.type == 'boolean' then return val end if ps.constraint then ps.constraint(val) end return val end --- add a new type to Lapp. These appear in parens after the value like -- a range constraint, e.g. '<ival> (integer) Process PID' -- @string name name of type -- @param converter either a function to convert values, or a Lua type name. -- @func[opt] constraint optional function to verify values, should use lapp.error -- if failed. function lapp.add_type (name,converter,constraint) types[name] = {converter=converter,constraint=constraint} end local function force_short(short) lapp.assert(#short==1,short..": short parameters should be one character") end -- deducing type of variable from default value; local function process_default (sval,vtype) local val if not vtype or vtype == 'number' then val = tonumber(sval) end if val then -- we have a number! return val,'number' elseif filetypes[sval] then local ft = filetypes[sval] return ft[1],ft[2] else if sval == 'true' and not vtype then return true, 'boolean' end if sval:match '^["\']' then sval = sval:sub(2,-2) end return sval,vtype or 'string' end end --- process a Lapp options string. -- Usually called as `lapp()`. -- @string str the options text -- @tparam {string} args a table of arguments (default is `_G.arg`) -- @return a table with parameter-value pairs function lapp.process_options_string(str,args) local results = {} local opts = {at_start=true} local varargs local arg = args or _G.arg open_files = {} parms = {} aliases = {} parmlist = {} local function check_varargs(s) local res,cnt = s:gsub('^%.%.%.%s*','') return res, (cnt > 0) end local function set_result(ps,parm,val) parm = type(parm) == "string" and parm:gsub("%W", "_") or parm -- so foo-bar becomes foo_bar in Lua if not ps.varargs then results[parm] = val else if not results[parm] then results[parm] = { val } else append(results[parm],val) end end end usage = str for line in lines(str) do local res = {} local optspec,optparm,i1,i2,defval,vtype,constraint,rest line = lstrip(line) local function check(str) return match(str,line,res) end -- flags: either '-<short>', '-<short>,--<long>' or '--<long>' if check '-$v{short}, --$o{long} $' or check '-$v{short} $' or check '--$o{long} $' then if res.long then optparm = res.long:gsub('[^%w%-]','_') -- I'm not sure the $o pattern will let anything else through? if res.short then aliases[res.short] = optparm end else optparm = res.short end if res.short and not lapp.slack then force_short(res.short) end res.rest, varargs = check_varargs(res.rest) elseif check '$<{name} $' then -- is it <parameter_name>? -- so <input file...> becomes input_file ... optparm,rest = res.name:match '([^%.]+)(.*)' optparm = optparm:gsub('%A','_') varargs = rest == '...' append(parmlist,optparm) end -- this is not a pure doc line and specifies the flag/parameter type if res.rest then line = res.rest res = {} local optional -- do we have ([optional] [<type>] [default <val>])? if match('$({def} $',line,res) or match('$({def}',line,res) then local typespec = strip(res.def) local ftype, rest = typespec:match('^(%S+)(.*)$') rest = strip(rest) if ftype == 'optional' then ftype, rest = rest:match('^(%S+)(.*)$') rest = strip(rest) optional = true end local default if ftype == 'default' then default = true if rest == '' then lapp.error("value must follow default") end else -- a type specification if match('$f{min}..$f{max}',ftype,res) then -- a numerical range like 1..10 local min,max = res.min,res.max vtype = 'number' constraint = function(x) range_check(x,min,max,optparm) end elseif not ftype:match '|' then -- plain type vtype = ftype else -- 'enum' type is a string which must belong to -- one of several distinct values local enums = ftype local enump = '|' .. enums .. '|' vtype = 'string' constraint = function(s) lapp.assert(enump:match('|'..s..'|'), "value '"..s.."' not in "..enums ) end end end res.rest = rest typespec = res.rest -- optional 'default value' clause. Type is inferred as -- 'string' or 'number' if there's no explicit type if default or match('default $r{rest}',typespec,res) then defval,vtype = process_default(res.rest,vtype) end else -- must be a plain flag, no extra parameter required defval = false vtype = 'boolean' end local ps = { type = vtype, defval = defval, required = defval == nil and not optional, comment = res.rest or optparm, constraint = constraint, varargs = varargs } varargs = nil if types[vtype] then local converter = types[vtype].converter if type(converter) == 'string' then ps.type = converter else ps.converter = converter end ps.constraint = types[vtype].constraint elseif not builtin_types[vtype] then lapp.error(vtype.." is unknown type") end parms[optparm] = ps end end -- cool, we have our parms, let's parse the command line args local iparm = 1 local iextra = 1 local i = 1 local parm,ps,val local function check_parm (parm) local eqi = parm:find '=' if eqi then tinsert(arg,i+1,parm:sub(eqi+1)) parm = parm:sub(1,eqi-1) end return parm,eqi end local function is_flag (parm) return parms[aliases[parm] or parm] end while i <= #arg do local theArg = arg[i] local res = {} -- look for a flag, -<short flags> or --<long flag> if match('--$S{long}',theArg,res) or match('-$S{short}',theArg,res) then if res.long then -- long option parm = check_parm(res.long) elseif #res.short == 1 or is_flag(res.short) then parm = res.short else local parmstr,eq = check_parm(res.short) if not eq then parm = at(parmstr,1) local flag = is_flag(parm) if flag and flag.type ~= 'boolean' then --if isdigit(at(parmstr,2)) then -- a short option followed by a digit is an exception (for AW;)) -- push ahead into the arg array tinsert(arg,i+1,parmstr:sub(2)) else -- push multiple flags into the arg array! for k = 2,#parmstr do tinsert(arg,i+k-1,'-'..at(parmstr,k)) end end else parm = parmstr end end if aliases[parm] then parm = aliases[parm] end if not parms[parm] and (parm == 'h' or parm == 'help') then lapp.quit() end else -- a parameter parm = parmlist[iparm] if not parm then -- extra unnamed parameters are indexed starting at 1 parm = iextra ps = { type = 'string' } parms[parm] = ps iextra = iextra + 1 else ps = parms[parm] end if not ps.varargs then iparm = iparm + 1 end val = theArg end ps = parms[parm] if not ps then lapp.error("unrecognized parameter: "..parm) end if ps.type ~= 'boolean' then -- we need a value! This should follow if not val then i = i + 1 val = arg[i] end lapp.assert(val,parm.." was expecting a value") else -- toggle boolean flags (usually false -> true) val = not ps.defval end ps.used = true val = convert_parameter(ps,val) set_result(ps,parm,val) if builtin_types[ps.type] == 'file' then set_result(ps,parm..'_name',theArg) end if lapp.callback then lapp.callback(parm,theArg,res) end i = i + 1 val = nil end -- check unused parms, set defaults and check if any required parameters were missed for parm,ps in pairs(parms) do if not ps.used then if ps.required then lapp.error("missing required parameter: "..parm) end set_result(ps,parm,ps.defval) end end return results end if arg then script = arg[0] script = script or rawget(_G,"LAPP_SCRIPT") or "unknown" -- strip dir and extension to get current script name script = script:gsub('.+[\\/]',''):gsub('%.%a+$','') else script = "inter" end setmetatable(lapp, { __call = function(tbl,str,args) return lapp.process_options_string(str,args) end, }) return lapp
agpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c92729410.lua
2
1889
--子狸ぽんぽこ function c92729410.initial_effect(c) --spsummon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(92729410,0)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_SUMMON_SUCCESS) e2:SetCost(c92729410.spcost) e2:SetTarget(c92729410.sptg) e2:SetOperation(c92729410.spop) c:RegisterEffect(e2) Duel.AddCustomActivityCounter(92729410,ACTIVITY_SPSUMMON,c92729410.counterfilter) end function c92729410.counterfilter(c) return c:IsRace(RACE_BEAST) end function c92729410.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetCustomActivityCount(92729410,tp,ACTIVITY_SPSUMMON)==0 end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH) e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) e1:SetReset(RESET_PHASE+PHASE_END) e1:SetTargetRange(1,0) e1:SetTarget(c92729410.splimit) Duel.RegisterEffect(e1,tp) end function c92729410.splimit(e,c) return c:GetRace()~=RACE_BEAST end function c92729410.filter(c,e,tp) return c:GetCode()~=92729410 and c:GetLevel()==2 and c:IsRace(RACE_BEAST) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEDOWN) end function c92729410.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c92729410.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK) end function c92729410.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c92729410.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEDOWN_DEFENSE) Duel.ConfirmCards(1-tp,g) end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c46259438.lua
6
1173
--契約洗浄 function c46259438.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_DESTROY+CATEGORY_DRAW+CATEGORY_RECOVER) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetTarget(c46259438.target) e1:SetOperation(c46259438.activate) c:RegisterEffect(e1) end function c46259438.filter(c) return c:IsFaceup() and c:IsSetCard(0xae) and c:GetSequence()<5 end function c46259438.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsPlayerCanDraw(tp) and Duel.IsExistingMatchingCard(c46259438.filter,tp,LOCATION_SZONE,0,1,nil) end local g=Duel.GetMatchingGroup(c46259438.filter,tp,LOCATION_SZONE,0,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,g:GetCount()) Duel.SetOperationInfo(0,CATEGORY_RECOVER,nil,0,tp,g:GetCount()*1000) end function c46259438.activate(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(c46259438.filter,tp,LOCATION_SZONE,0,nil) local ct1=Duel.Destroy(g,REASON_EFFECT) if ct1==0 then return end local ct2=Duel.Draw(tp,ct1,REASON_EFFECT) Duel.BreakEffect() Duel.Recover(tp,ct2*1000,REASON_EFFECT) end
gpl-2.0
eugeneia/snabb
src/apps/ipfix/dns.lua
2
10798
module(..., package.seeall) local ffi = require("ffi") local lib = require("core.lib") -- By default, CNAME and RRSIG records in the answer section are -- skipped. skip_CNAMEs_RRSIGs = true local uint16_ptr_t = ffi.typeof("uint16_t *") local uint8_ptr_t = ffi.typeof("uint8_t *") local dns_hdr_t = ffi.typeof([[ struct { uint16_t id; uint16_t flags; uint16_t qcount; uint16_t anscount; uint16_t authcount; uint16_t addcount; } __attribute__((packed)) ]]) local dns_hdr_ptr_t = ffi.typeof("$*", dns_hdr_t) -- The part of a RR following the encoded name local rr_t = ffi.typeof([[ struct { uint16_t type; uint16_t class; uint32_t ttl; uint16_t rdlength; uint8_t rdata[0]; } __attribute__((packed)) ]]) local rr_ptr_t = ffi.typeof("$*", rr_t) -- Given a region of memory of size size starting at start_ptr, return -- the number of bytes in the sub-region starting at data_ptr. A -- result <= 0 indicates that data_ptr is not within the region. local function available_bytes(start_ptr, size, data_ptr) assert(data_ptr >= start_ptr) return size - (data_ptr - start_ptr) end -- Incorrectly compressed domain names can form loops. We use a table -- that can hold all possible offsets (14 bits) encoded in compressed -- names to detect such loops in a branch-free fashion by marking -- which offsets have been encountered while de-compressing a -- name. The marker consist of a 16-bit number which is increased for -- each invocation of decompress_name(). The offset table must be -- reset each time the marker wraps around to zero. Because a valid -- offset must be at least 12 (due it being relative to the start of -- the DNS header), the current marker is stored in offset_table[0] -- without causing a conflict. local offset_table = ffi.new("uint16_t [16384]") -- Decompress the on-the-wire representation of a domain name starting -- at ptr and write up to size bytes of the decompressed name to the -- location pointed to by buffer. hdr_ptr is a pointer to the -- beginning of the DNS header to resolve compressed names. -- -- Note that DNS extraction is only initiated if the packet is not -- truncated. Even then, decompression can lead us out of the message -- if -- -- * the message is corrupt -- * the messages is fragmented and decompression points into -- a non-initial fragment -- -- msg_size is the number of bytes in the message, including the -- header, used to check whether decompression stays within the -- message. -- -- Returns a pointer to the first byte after the name or nil if the -- name could not be decompressed and the number of bytes that have -- been copied to the buffer. If the pointer is nil, the buffer -- contains what has been decompressed so far. local function decompress_name(hdr_ptr, msg_size, ptr, buffer, size) offset_table[0] = offset_table[0] + 1 if offset_table[0] == 0 then ffi.fill(offset_table, ffi.sizeof(offset_table)) offset_table[0] = 1 end local offset = 0 if available_bytes(hdr_ptr, msg_size, ptr) < 1 then return nil, offset end local result_ptr = nil local length = ptr[0] while length ~= 0 do local label_type = bit.band(0xc0, length) if label_type == 0xc0 then if available_bytes(hdr_ptr, msg_size, ptr) < 2 then return nil, offset end -- Compressed name, length is the offset relative to the start -- of the DNS message where the remainder of the name is stored local name_offset = bit.band(0x3fff, lib.ntohs(ffi.cast(uint16_ptr_t, ptr)[0])) -- Sanity check and Loop detection if (name_offset < ffi.sizeof(dns_hdr_t) or name_offset >= msg_size or offset_table[name_offset] == offset_table[0]) then return nil, offset end offset_table[name_offset] = offset_table[0] if result_ptr == nil then -- This is the first redirection encountered in the name, -- the final result is the location just behind that -- pointer result_ptr = ptr + 2 end ptr = hdr_ptr + name_offset elseif label_type ~= 0 then -- Unsupported/undefined label type return nil, offset else if available_bytes(hdr_ptr, msg_size, ptr) < length + 1 then -- Truncated label return nil, offset end -- Remaining space in the buffer for the name local avail = size - offset if avail > 0 then -- Copy as much of the label as possible local eff_length = math.min(length+1, avail) ffi.copy(buffer + offset, ptr, eff_length) offset = offset + eff_length end ptr = ptr + length + 1 end length = ptr[0] end -- We've reached the root label if offset < size then buffer[offset] = 0 offset = offset + 1 end if result_ptr == nil then result_ptr = ptr + 1 end return result_ptr, offset end -- RDATA with a single domain name local function decompress_RR_plain(hdr_ptr, msg_size, rr, entry) local ptr, rdlength = decompress_name(hdr_ptr, msg_size, rr.rdata, entry.key.dnsAnswerRdata, ffi.sizeof(entry.key.dnsAnswerRdata)) entry.key.dnsAnswerRdataLen = rdlength return ptr end local mx_rdata_t = ffi.typeof([[ struct { uint16_t preference; uint8_t exchange[0]; } ]]) local mx_rdata_ptr_t = ffi.typeof("$*", mx_rdata_t) local function decompress_RR_MX(hdr_ptr, msg_size, rr, entry) local mx_src = ffi.cast(mx_rdata_ptr_t, rr.rdata) local mx_dst = ffi.cast(mx_rdata_ptr_t, entry.key.dnsAnswerRdata) mx_dst.preference = mx_src.preference local ptr, length = decompress_name(hdr_ptr, msg_size, mx_src.exchange, mx_dst.exchange, ffi.sizeof(entry.key.dnsAnswerRdata) - 2) local rdlength = length + 2 entry.key.dnsAnswerRdataLen = rdlength return ptr end local soa_rdata_t = ffi.typeof([[ struct { uint32_t serial; uint32_t refresh; uint32_t retry; uint32_t expire; uint32_t minimum; } ]]) local function decompress_RR_SOA(hdr_ptr, msg_size, rr, entry) local size = ffi.sizeof(entry.key.dnsAnswerRdata) local dst = entry.key.dnsAnswerRdata -- MNAME local ptr, length = decompress_name(hdr_ptr, msg_size, rr.rdata, dst, size) if ptr ~= nil then local rdlength = ffi.sizeof(soa_rdata_t) + length local avail = size - length dst = dst + length -- RNAME ptr, length = decompress_name(hdr_ptr, msg_size, ptr, dst, avail) if ptr ~= nil then rdlength = rdlength + length avail = avail - length dst = dst + length if avail > 0 then ffi.copy(dst, ptr, math.min(avail, ffi.sizeof(soa_rdata_t))) end entry.key.dnsAnswerRdataLen = rdlength end end return ptr end local function decompress_rdata_none(hdr_ptr, msg_size, rr, entry) local rdlength = lib.ntohs(rr.rdlength) ffi.copy(entry.key.dnsAnswerRdata, rr.rdata, math.min(rdlength, ffi.sizeof(entry.key.dnsAnswerRdata))) entry.key.dnsAnswerRdataLen = rdlength return true end -- List of well-known RR types (see RFC3597, section 4) whose RDATA -- sections can contain compressed names. The functions referenced -- here replace such names with their uncompressed equivalent. local decompress_rdata_fns = setmetatable( { [2] = decompress_RR_plain, -- NS [5] = decompress_RR_plain, -- CNAME [6] = decompress_RR_SOA, -- SOA [12] = decompress_RR_plain, -- PTR [15] = decompress_RR_MX, -- MX }, { __index = function() return decompress_rdata_none end } ) local function extract_answer_rr(hdr_ptr, msg_size, ptr, entry) local ptr, len = decompress_name(hdr_ptr, msg_size, ptr, entry.key.dnsAnswerName, ffi.sizeof(entry.key.dnsAnswerName)) if ptr == nil then return nil, nil, nil end if available_bytes(hdr_ptr, msg_size, ptr) < ffi.sizeof(rr_t) then return nil, nil, nil end local rr = ffi.cast(rr_ptr_t, ptr) local type = lib.ntohs(rr.type) local rdlength = lib.ntohs(rr.rdlength) if rdlength > 0 then if available_bytes(hdr_ptr, msg_size, rr.rdata) < rdlength then return nil, nil, nil end if not decompress_rdata_fns[type](hdr_ptr, msg_size, rr, entry) then return nil, nil, nil end end local class = lib.ntohs(rr.class) entry.key.dnsAnswerType = type entry.key.dnsAnswerClass = class entry.key.dnsAnswerTtl = lib.ntohl(rr.ttl) return type, class, rr.rdata + rdlength end function extract(hdr_ptr, msg_size, entry) if ffi.sizeof(dns_hdr_t) > msg_size then return end local dns_hdr = ffi.cast(dns_hdr_ptr_t, hdr_ptr) entry.key.dnsFlagsCodes = lib.ntohs(dns_hdr.flags) if lib.ntohs(dns_hdr.qcount) == 1 then entry.key.dnsQuestionCount = 1 local ptr, _ = decompress_name(hdr_ptr, msg_size, hdr_ptr + ffi.sizeof(dns_hdr_t), entry.key.dnsQuestionName, ffi.sizeof(entry.key.dnsQuestionName)) if ptr == nil then ffi.fill(entry.key.dnsQuestionName, ffi.sizeof(entry.key.dnsQuestionName)) return end -- The question section only has a type and class if available_bytes(hdr_ptr, msg_size, ptr) < 4 then return end local rr = ffi.cast(rr_ptr_t, ptr) entry.key.dnsQuestionType = lib.ntohs(rr.type) entry.key.dnsQuestionClass = lib.ntohs(rr.class) ptr = ptr + 4 local anscount = lib.ntohs(dns_hdr.anscount) entry.key.dnsAnswerCount = anscount if anscount > 0 then -- Extract the first answer local type, class, ptr = extract_answer_rr(hdr_ptr, msg_size, ptr, entry) -- Skip to the first RR which is neither a CNAME nor a RRSIG if skip_CNAMEs_RRSIGs then anscount = anscount - 1 while (type == 5 or type == 46) and class == 1 and anscount > 0 do ffi.fill(entry.key.dnsAnswerName, ffi.sizeof(entry.key.dnsAnswerName)) ffi.fill(entry.key.dnsAnswerRdata, ffi.sizeof(entry.key.dnsAnswerRdata)) type, class, ptr = extract_answer_rr(hdr_ptr, msg_size, ptr, entry) anscount = anscount - 1 end end end end end
apache-2.0
mimetic/DIG-corona-library
scripts/funx.lua
4
145657
-- funx.lua -- -- Version 2.0 -- -- Copyright (C) 2014 David I. Gross. All Rights Reserved. -- --[[ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] -- -- =================== -- USEFUL FUNCTIONS. -- =================== local FUNX = {} local pathToFunxFolder = "scripts/funx/" local dotPathToFunxFolder = "scripts.funx." -- Requires json library local json = require ( "json" ) local lfs = require ( "lfs" ) local widget = require ("widget") -- Used by tellUser...the handler for the timed message local timedMessage = nil local timedMessageList = {} -- Make a local copy of the application settings global local screenW, screenH = display.contentWidth, display.contentHeight local viewableScreenW, viewableScreenH = display.viewableContentWidth, display.viewableContentHeight local midscreenX = screenW*(0.5) local midscreenY = screenH*(0.5) -- functions local floor = math.floor local ceil = math.ceil local min = math.min local max = math.max local random = math.random local char = string.char local byte = string.byte local match = string.match local gmatch = string.gmatch local find = string.find local gsub = string.gsub local substring = string.sub local gfind = string.gfind local lower = string.lower local upper = string.upper local strlen = string.len local format = string.format -- ALPHA VALUES, can change for RGB or HDR systems local OPAQUE = 255 local TRANSPARENT = 0 -- ------------------------------------------------------------- -- HARDWARE SETTINGS -- This exposes the system hardware settings to FUNX. -- Easy to find out what kind of device, for example. -- ------------------------------------------------------------- hardwareInfo = {} hardwareInfo.isApple = false hardwareInfo.isAndroid = false hardwareInfo.isGoogle = false hardwareInfo.isKindleFire = false hardwareInfo.isNook = false hardwareInfo.is_iPad = false hardwareInfo.isTall = false hardwareInfo.isSimulator = false local model = system.getInfo("model") -- Are we on the simulator? if "simulator" == system.getInfo("environment") then hardwareInfo.isSimulator = true end -- lets see if we are a tall device hardwareInfo.isTall = false if (display.pixelHeight/display.pixelWidth) > 1.5 then hardwareInfo.isTall = true end -- first, look to see if we are on some Apple platform. -- All models start with iP, so we can check that. if string.sub(model,1,2) == "iP" then -- We are an iOS device of some sort hardwareInfo.isApple = true if string.sub(model, 1, 4) == "iPad" then hardwareInfo.is_iPad = true end else -- Not Apple, then we must be one of the Android devices hardwareInfo.isAndroid = true -- lets assume we are Google for the moment hardwareInfo.isGoogle = true -- All the Kindles start with K, though Corona SDK before build 976's Kindle Fire 9 returned "WFJWI" instead of "KFJWI" if model == "Kindle Fire" or model == "WFJWI" or string.sub(model,1,2) == "KF" then hardwareInfo.isKindleFire = true hardwareInfo.isGoogle = false end -- Are we a nook? if string.sub(model,1,4) == "Nook" or string.sub(model,1,4) == "BNRV" then hardwareInfo.isNook = true hardwareInfo.isGoogle = false end end -- ------------------------------------------------------------- -- Problem is, if this goes to quickly, you'll still get non-random numbers, -- and I've found some lines execute so fast the local function uniqueID() -- Initialize the pseudo random number generator math.randomseed( os.clock() + system.getTimer() ) math.random(); math.random(); math.random() return math.random() end ----------- -- Shortcut to set x,y to 0,0 local function toZero(o) o.x, o.y = 0,0 end -- ------------------------------------------------------------- -- GRAPHICS 2.0 POSITIONING -- ------------------------------------------------------------ local function anchor(obj, pos) if (not obj) then return; end if pos == "TopLeft" then obj.anchorX, obj.anchorY = 0, 0 elseif pos == "TopCenter" then obj.anchorX, obj.anchorY = 0.5, 0 elseif pos == "TopRight" then obj.anchorX, obj.anchorY = 1, 0 elseif pos == "CenterLeft" then obj.anchorX, obj.anchorY = 0, 0.5 elseif pos == "Center" then obj.anchorX, obj.anchorY = 0.5, 0.5 elseif pos == "CenterRight" then obj.anchorX, obj.anchorY = 1, 0.5 elseif pos == "BottomLeft" then obj.anchorX, obj.anchorY = 0, 1 elseif pos == "BottomCenter" then obj.anchorX, obj.anchorY = 0.5, 1 elseif pos == "BottomRight" then obj.anchorX, obj.anchorY = 1, 1 elseif pos == "Left" then obj.anchorX = 0 elseif pos == "Right" then obj.anchorX = 1 elseif pos == "Top" then obj.anchorY = 0 elseif pos == "Bottom" then obj.anchorY = 1 elseif pos == "TopLeftReferencePoint" then obj.anchorX, obj.anchorY = 0, 0 elseif pos == "TopCenterReferencePoint" then obj.anchorX, obj.anchorY = 0.5, 0 elseif pos == "TopRightReferencePoint" then obj.anchorX, obj.anchorY = 1, 0 elseif pos == "CenterLeftReferencePoint" then obj.anchorX, obj.anchorY = 0, 0.5 elseif pos == "CenterReferencePoint" then obj.anchorX, obj.anchorY = 0.5, 0.5 elseif pos == "CenterRightReferencePoint" then obj.anchorX, obj.anchorY = 1, 0.5 elseif pos == "BottomLeftReferencePoint" then obj.anchorX, obj.anchorY = 0, 1 elseif pos == "BottomCenterReferencePoint" then obj.anchorX, obj.anchorY = 0.5, 1 elseif pos == "BottomRightReferencePoint" then obj.anchorX, obj.anchorY = 1, 1 else obj.anchorX, obj.anchorY = 0.5, 0.5 end end local function anchorZero(obj,pos) if (not obj) then return; end anchor(obj, pos) obj.x, obj.y = 0,0 end -- Add an invisible positioning rectangle for a group -- @param g [group] Group into which we add a position rect at 0,0 -- @param vis [boolean] True = visible, False = hidden -- @param c [table] RGBa color table {r,g,b,a} local function addPosRect(g, vis, c ) local r = display.newRect(g, 0,0,10,10) r.isVisible = vis c = c or {250,0,0,100} r:setFillColor(unpack(c)) anchorZero(r, "TopLeft") return g end local function centerInParent(g) anchor(g, "Center") g.x = g.parent.width/2 g.y = g.parent.height/2 return g end -- ------------------------------------------------------------ -- Simple encrypt/decrypt --[[ EXAMPLE: local enc1 = {29, 58, 93, 28, 27}; local str = "This is an encrypted string."; local crypted = crypt(str,enc1) print("Encryption: " .. crypted); print("Decryption: " .. crypt(crypted,enc1,true)); --]] -- ------------------------------------------------------------ local function crypt(str,k,inv) local function convert( chars, dist, inv ) return string.char( ( string.byte( chars ) - 32 + ( inv and -dist or dist ) ) % 95 + 32 ) end local enc= ""; for i=1,#str do if(#str-k[5] >= i or not inv) then for inc=0,3 do if(i%4 == inc)then enc = enc .. convert(string.sub(str,i,i),k[inc+1],inv); break; end end end end if(not inv)then for i=1,k[5] do enc = enc .. string.char(math.random(32,126)); end end return enc; end -- ------------------------------------------------------------ -- Get the string index in system table of a system directory -- ------------------------------------------------------------ local function indexOfSystemDirectory( systemPath ) local i = "" if (systemPath == system.DocumentsDirectory) then i = "DocumentsDirectory" elseif (systemPath == system.ResourceDirectory) then i = "ResourceDirectory" elseif (systemPath == system.CachesDirectory) then i = "CachesDirectory" end return i end -- ------------------------------------------------------------ -- DEBUGGING Timer -- ------------------------------------------------------------ local firstTime = system.getTimer() local lastTimePassed = system.getTimer() local function timePassed(msg) local t2 = system.getTimer() local t = t2 - lastTimePassed lastTimePassed = t2 msg = msg or "" print ("funx.timePassed: ", floor(t) .. "ms", msg) --, "Total:", floor(t2-firstTime)) io.flush( ) end ----------------- -- 'n' is the call stack level to show -- '2' will show the calling function local function printFuncName(n) n = n or 2 local info = debug.getinfo(n, "Snl") if info.what == "C" then -- is a C function? print(n, "C function") else -- a Lua function print(format("[%s]:%d", info.name, info.currentline)) end end local function isTable(t) return (type(t) == "table") end ----------------- -- Traceback -- Writes a call stack, showing what called the current code. -- Hopefully. local function traceback () print ("FUNX.TRACEBACK:") local level = 1 while true do local info = debug.getinfo(level, "Sl") if not info then break end if info.what == "C" then -- is a C function? print(level, "C function") else -- a Lua function print(format("[%s]:%d", info.short_src, info.currentline)) end level = level + 1 end end ----------------- -- Fails for negatives, apparently local function round2(num, idp) local mult = 10^(idp or 0) return floor(num * mult + 0.5) / mult end local function round(num, idp) return tonumber(format("%." .. (idp or 0) .. "f", num)) end ----------------- -- Given a value from an XML element, it could be x=y or x.value=y -- Return y in either case. -- If asNil is true, then if the value is "" or nil, return nil local function getValue(x,asNil) local r if (type(x) == "table") then if (x.value) then r = x.value elseif (x.Attributes and x.Attributes.value) then r = x.Attributes.value elseif (x._attr and x._attr.value) then r = x._attr.value end else r = x end if (asNil and (r == "" or r == nil or r == false)) then r = nil end return r end -------------- -- unescape/escape a hex string local function unescape (s) if (not s) then return "" end s = gsub(s, "+", " ") s = gsub(s, "%%(%x%x)", function (h) return char(tonumber(h, 16)) end) return s end local function escape(s) s = gsub(s, "([&=+%c])", function(c)return format("%%%02X", byte(c))end) s = gsub(s, " ", "+") return s end --========= --- Remove a value from a table. The table is searched and the value removed from it. local function removeFromTable(t,obj) for i,o in pairs(t) do if (o == obj) then t[i] = nil print ("removeFromTable: removed item #" .. i) return true end end return false end ----------------- -- Table is empty? local function tableIsEmpty(t) if (t and type(t) == "table" ) then if (next(t) == nil) then return true end end return false end ----------------- -- Length of a table, i.e. number elements in it. local function tablelength (t) if (type(t) ~= "table") then return 0 end local count = 0 for _, _ in pairs(t) do count = count + 1 end return count end --=========== --- Escape keys in tables so the key name can be used in a gsub search/replace -- @param t Table with keys that might need escaping -- @return res Key:value pairs: original key => clean key -- e.g. { "icon-1" = "myicon.jpg" } ===> { "icon-1" = "icon%-1" } local function getEscapedKeysForGsub(t) -- Chars to escape: ( ) . % + - * ? [ ^ $ local res = {} for i,v in pairs(t) do res[i] = gsub(i, "([%(%)%.%%%+%-%*%?%[%^%$])", "%%%1") end return res end --- Flatten a table for substitutions -- Create a flat table from the prefs that can be used for word subsitutions in strings, -- e.g. Replacing name in "My {{name}}", where name is inside of a subtable such as "user". -- Seems like a waste of processing, but this way we can use hierarchical prefs, probably a good thing -- @flatPrefs [table] Used for recursion, so don't pass anything to it or it won't start with the PREFS.values table. local function flattenTable(t) local res = {} for k,v in pairs(t) do if (type(v) ~= "table") then -- Capture a non-table value res[k] = v else -- Flatten a subtable local subset = flattenTable(v) for ks,vs in pairs(subset) do res[k .. ":" .. ks] = vs end end end return res end --- Substitute for {{x}} with table.x from a table. -- There can be multiple fields in the string, s. -- Returns the string with the fields filled in. -- @param s String with codes to replace -- @param t Table of key:value pairs to use for replacement (search for key) -- @param escapeTheKeys if TRUE then escape the keys of the subsitutions table (t), if a table then use that table as the escaped keys table -- @return s string with replacements local function substitutions (s, t, escapeTheKeys) if (not s or not t or t=={}) then --print ("funx.substitutions: No Values passed!") return s end local tclean = {} if (escapeTheKeys) then if (type(escapeTheKeys) == "table") then tclean = escapeTheKeys else tclean = getEscapedKeysForGsub(t) end end local r = gfind(s,"%{%{(.-)%}%}") for wrd in r do local searchTerm = tclean[wrd] or wrd if (t[wrd]) then s = gsub(s, "{{"..searchTerm.."}}", tostring(t[wrd])) end end return s end -- Substitute for {x} with table.x from a table. -- There can be multiple fields in the string, s. -- Returns the string with the fields filled in. local function OLD_substitutionsSLOWER (s, t) if (not s or not t or t=={}) then --print ("funx.substitutions: No Values passed!") return s end --local r = gfind(s,"%b{}") local r = gfind(s,"%{%{.-%}%}") local res = s for wrd in r do local i,j = find(wrd, "%{%{(.-)%}%}") local k = sub(wrd,i+2,j-2) if (t[k]) then res = gsub(res, wrd, t[k]) end --print ("substitutions for in "..res.." for {{"..k.."}} with ",t[k], "RESULT:",res) end return res end --=========== --- Replace all substitutions in the entire table, including -- nested tables. -- @param t Table in which to substitute -- @param subs table Table of substitutions local function tableSubstitutions(t, subs, escapeTheKeys) if (type(t) ~= "table") then return t end if (type(subs) ~= "table" or not subs or subs == {} ) then return t end local tclean if (escapeTheKeys) then if (type(escapeTheKeys) == "table") then tclean = escapeTheKeys else tclean = getEscapedKeysForGsub(subs) end end for i,element in pairs(t) do if (i ~= "screen") then if (type(element) == "string") then t[i] = substitutions (element, subs, tclean) --print ("element:", element, t[i]) elseif (type(element) == "table") then tableSubstitutions( t[i], subs, tclean) elseif (element == "[[null]]" or element == "[[NULL]]" ) then t[i] = nil end end end end --=========== --- Remove elements that contain unresolved {{}} codes. -- @param t Table in which to substitute local function tableRemoveUnusedCodedElements(t ) if (type(t) ~= "table") then return t end for i,element in pairs(t) do if (i ~= "screen") then if (type(element) == "string" and find(element, "%{%{.-%}%}")) then --print ("tableRemoveUnusedCodedElements: Remove ", t[i]) t[i] = "" elseif (type(element) == "table") then tableRemoveUnusedCodedElements( t[i] ) end end end end -- hasFieldCodes(s) -- Return true/false if the string has field codes, i.e. {x} inside it local function hasFieldCodes(s) if (type(s) ~= "string") then return false end s = s or "" local r = find(s,"%{%{.-%}%}") if (r) then return true else return false end end -- hasFieldCodes(s) -- Return true/false if the string has field codes, i.e. {x} inside it local function hasFieldCodesSingle(s) if (type(s) ~= "string") then return false end s = s or "" local r = find(s,"%b{}") if (r) then return true else return false end end -- Get element name from string. -- If the string is {{xxx}} then the field name is "xxx" local function getElementName (s) local r = gfind(s,"%{%{(.-)%}%}") local res = "" for wrd in r do print ("extracted ",wrd) res = wrd break end return res end -- Dump an XML table local function dumptable(_class, no_func, depth, maxDepth, filter) -- = string.match("foo 123 bar", '%d%d%d') -- %d matches a digit local function passedFilter(t) if not filter then return true end return string.match(t, filter) end if (not _class) then print ("dumptable: not a class."); return; end if(depth==nil) then depth=0; end local str=""; for n=0,depth,1 do str=str.."\t"; end maxDepth = maxDepth or 3 if (depth > maxDepth) then print ("Oops, running away! Depth is "..depth) return end print (str.."["..type(_class).."]"); print (str.."{"); if (type(_class) == "table") then for i,field in pairs(_class) do if(type(field)=="table") then local fn = tostring(i) if (substring(fn,1,2) == "__") then print (str.."\t"..tostring(i).." = (not expanding this internal table)"); else print (str.."\t"..tostring(i).." ="); dumptable(field, no_func, depth+1, maxDepth, filter); end else if (passedFilter(i)) then if(type(field)=="number") then print (str.." [num]\t"..tostring(i).."="..field); elseif(type(field) == "string") then print (str.." [str]\t"..tostring(i).."=".."\""..field.."\""); elseif(type(field) == "boolean") then print (str.." [bool]\t"..tostring(i).."=".."\""..tostring(field).."\""); else if(not no_func)then if(type(field)=="function")then print (str.."\t"..tostring(i).."()"); else print (str.."\t"..tostring(i).."<userdata=["..type(field).."]>"); end end end end end end end print (str.."}"); end -------------------------------------------------------- -- tableCopy local function tableCopy(object) local lookup_table = {} local function _copy(object) if type(object) ~= "table" then return object elseif lookup_table[object] then return lookup_table[object] end local new_table = {} lookup_table[object] = new_table for index, value in pairs(object) do new_table[_copy(index)] = _copy(value) end return setmetatable(new_table, _copy(getmetatable(object))) end return _copy(object) end -------------------------------------------------------- -- Trim -- Remove white space from a string, OR table of strings -- recursively -- Only act on strings -- If flag set, return nil for an empty string local function trim(s, returnNil) if (s) then if (type(s) == "table") then for i,v in ipairs(s) do s[i] = trim(v, returnNil) end elseif (type(s) == "string") then s = s:gsub("^%s*(.-)%s*$", "%1") end end if (returnNil and s == "") then return nil end return s end -------------------------------------------------------- -- ltrim -- Remove white space from the start of a string, OR table of strings recursively -- Only act on strings -- If flag set, return nil for an empty string local function ltrim(s, returnNil) if (s) then if (type(s) == "table") then for i,v in ipairs(s) do s[i] = ltrim(v, returnNil) end elseif (type(s) == "string") then s = s:gsub("^%s*(.-)", "%1") end end if (returnNil and s == "") then return nil end return s end -------------------------------------------------------- -- rtrim -- Remove white space from the end of a string, OR table of strings recursively -- Only act on strings -- If flag set, return nil for an empty string local function rtrim(s, returnNil) if (s) then if (type(s) == "table") then for i,v in ipairs(s) do s[i] = rtrim(v, returnNil) end elseif (type(s) == "string") then s = s:gsub("(.-)%s*$", "%1") end end if (returnNil and s == "") then return nil end return s end -- Delete fields of the form {{x}} in the string s local function removeFields (s) if (not s) then return nil end local r = gfind(s,"%{%{.-%}%}") local res = s for wrd in r do res = trim(gsub(res, wrd, "")) end return res end -- Delete fields of the form {x} in the string s local function removeFieldsSingle (s) if (not s) then return nil end local r = gfind(s,"%b{}") local res = s for wrd in r do res = trim(gsub(res, wrd, "")) end return res end -------------------------------------------------------- -- table merge -- Overwrite elements in the first table with the second table! local function tableMerge(t1, t2) if (type(t1) ~= "table") then return t2 end if (type(t2) ~= "table") then return t1 end for k,v in pairs(t2) do if type(v) == "table" then if type(t1[k] or false) == "table" then tableMerge(t1[k] or {}, t2[k] or {}) else t1[k] = v end else t1[k] = v end end return t1 end local function split(str, pat, doTrim) pat = pat or "," if (not str) then return nil end str = tostring(str) local t = {} local fpat = "(.-)" .. pat local last_end = 1 local s, e, cap = str:find(fpat, 1) while s do if s ~= 1 or cap ~= "" then if doTrim then cap = trim(cap) end table.insert(t,cap) end last_end = e+1 s, e, cap = str:find(fpat, last_end) end if last_end <= #str then cap = str:sub(last_end) if doTrim then cap = trim(cap) end table.insert(t,cap) end return t end ------------------------------------------------- --- GET DEVICE SCALE FACTOR FOR RETINA RESIZING --1 = no need to change anything --2 = multiply by 2 -- examples: -- local scalingRatio = scaleFactorForRetina() -- local scalesuffix = "@"..scalingRatio.."x" -- -- local scalingRatio = 1/scaleFactorForRetina() -- width = width/scalingRatio -- height = height/scalingRatio ------------------------------------------------- local function scaleFactorForRetina() local deviceWidth = ( display.contentWidth - (display.screenOriginX * 2) ) / display.contentScaleX local scaleFactor = floor( deviceWidth / display.contentWidth ) return scaleFactor end ------------------------------------------------- -- CHECK IMAGE DIMENSION & SCALE ACCORDINGLY ------------------------------------------------- local function checkScale(p) if p.width > viewableScreenW or p.height > viewableScreenH then if p.width/viewableScreenW > p.height/viewableScreenH then p.xScale = viewableScreenW/p.width p.yScale = viewableScreenW/p.width else p.xScale = viewableScreenH/p.height p.yScale = viewableScreenH/p.height end end end ------------------------------------------------- -- RESCALE AN IMAGE THAT WAS DESIGNED FOR THE IPAD (1024X768) FOR THE CURRENT PLATFORM -- Assuming the graphic was made for a different platform -- this resizes it ------------------------------------------------- local function resizeFromIpad(p) local currentR = viewableScreenW/viewableScreenH local ipadR = 1024/768 local r if (currentR > ipadR) then -- use ration based on different heights r = viewableScreenH / 768 else r = viewableScreenW / 1024 end if (r ~= 1) then p:scale(r,r) --print ("Resize image by (viewableScreenW/1024) = "..r) end end ------------------------------------------------- -- RESCALE COORDINATES THAT WERE DESIGNED FOR THE IPAD (1024X768) FOR THE CURRENT PLATFORM -- Used to reposition coordinates that were set up for the iPad, e.g. x,y positions -- If the screen is a different shape, pad the x to make up for it -- iPad is 1024/768 = 133/100 (1.33) -- CONVERT results to integer (floor) local function rescaleFromIpad(x,y) -- Do nothing if this is an iPad screen! if ( (screenW == 1024 and screenH == 768) or (screenW == 768 and screenH == 1024) )then return x,y end if (x == nil) then return 0,0 end --print ("viewableScreenW="..viewableScreenW..", viewableScreenH="..viewableScreenH) local currentR = viewableScreenW/viewableScreenH local ipadR = 1024/768 local fixedH = 768 local fixedW = 1024 if (currentR > 1) then ipadR = 1/ipadR fixedH = 1024 fixedW = 768 end local r if (currentR > ipadR) then -- use ration based on different heights r = viewableScreenH / fixedH else r = viewableScreenW / fixedW end -- Pad for different shape local screenR = floor((viewableScreenW / viewableScreenH) * 100 )/100 local px = 0 --print ("screenR="..screenR) if (y and (screenR ~= floor((ipadR)*100)/100)) then px = floor((viewableScreenW - (viewableScreenH * ipadR))/2) end x = floor((x * r) + (px)) --print ("Padding x="..px) if (y ~= nil) then y = floor(y * r) return x,y else return x end end -- If the value is a percentage, multiply by the 2nd param, else return the 1st param -- value is rounded to nearest integer, UNLESS the 2nd param is less than 1 -- or noRound = true -- If x is nil, but y is not, then return the y (i.e. assume 100%) local function applyPercent (x,y,noRound) if (x == nil and y == nil) then return nil end if (x == nil and y ~= nil) then return tonumber(y) end x = x or 0 y = y or 0 local v = match(trim(x), "(.+)%%$") if v then v = (v / 100) * y if ((not noRound) and (y>1)) then v = floor(v+0.5) end else v = x end return tonumber(v) end -- =========== --- Get a percentage of the screen height -- @param y -- @param noRound If false, value NOT rounded to nearest integer local function percentOfScreenHeight (y,noRound) return applyPercent (y, screenH, noRound) end -- =========== --- Get a percentage of the screen height -- @param y -- @param noRound If false, value NOT rounded to nearest integer local function percentOfScreenWidth (x,noRound) return applyPercent (x, screenW, noRound) end -------------------------------------------------------- -- File Exists -- default directory is system.ResourceDirectory -- not system.DocumentsDirectory -------------------------------------------------------- local function fileExists(f,d) if (f) then d = d or system.ResourceDirectory local filePath = system.pathForFile( f, d ) local exists = false -- Determine if file exists if (filePath ~= nil) then local fileHandle = io.open( filePath, "r" ) if (fileHandle) then -- nil if no file found exists = true io.close(fileHandle) else --print ("WARNING: Missing file: ",tostring(filePath)) end end return (exists) else --print ("WARNING: Missing file: ",tostring(filePath)) return false end end ------------------------------------------------------------------------ -- Save table, load table, default from documents directory ------------------------------------------------------------------------ ---------------------- -- Save/load functions local function saveData(filePath, text) --local levelseq = table.concat( levelArray, "-" ) local file = io.open( filePath, "w" ) if (file) then file:write( text ) io.close( file ) return true else print ("Error: funx.saveData: Could not create file "..tostring(filePath)) return false end end local function loadData(filePath) local t = nil --local levelseq = table.concat( levelArray, "-" ) local file = io.open( filePath, "r" ) if (file) then t = file:read( "*a" ) io.close( file ) else print ("scripts.funx.loadData: No file found at "..tostring(filePath)) end return t end local function saveTableToFile(filePath, dataTable) --local levelseq = table.concat( levelArray, "-" ) local myfile = io.open( filePath, "w" ) for k,v in pairs( dataTable ) do myfile:write( k .. "=" .. v .. "," ) end io.close( myfile ) end -- Load a table form a text file. -- The table is stored as comma-separated name=value pairs. local function loadTableFromFile(filePath, s) local substring = substring if (not filePath) then print ("WARNING: loadTableFromFile: Missing file name.") return false end local file = io.open( filePath, "r" ) -- separator, default is comma s = s or "," if file then -- Read file contents into a string local dataStr = file:read( "*a" ) -- Break string into separate variables and construct new table from resulting data local datavars = split(dataStr, s) local dataTableNew = {} for i = 1, #datavars do local firstchar = substring(trim(datavars[i]),1,1) -- split each name/value pair if ( not ((firstchar == "#") or (firstchar == "/") or (firstchar == "-") ) ) then local onevalue = trim(split(datavars[i], "=")) if (onevalue[1]) then dataTableNew[onevalue[1]] = onevalue[2] end end end io.close( file ) -- important! -- Note: all values arrive as strings; cast to numbers where numbers are expected dataTableNew["randomValue"] = tonumber(dataTableNew["randomValue"]) return dataTableNew else print ("WARNING: loadTableFromFile: File not found ("..filePath..")") return false end end local function saveTable(t, filename, path) if (not t or not filename) then return true end path = path or system.DocumentsDirectory --print ("scripts.funx.saveTable: save to "..filename) local json = json.encode (t) local filePath = system.pathForFile( filename, path ) return saveData(filePath, json) end local function loadTable(filename, path) path = path or system.DocumentsDirectory if (fileExists(filename,path)) then local filePath = system.pathForFile( filename, path ) --print ("scripts.funx.loadTable: load from "..filePath) local t = {} local f = loadData(filePath) if (f and f ~= "") then t = json.decode(f) end --print ("loadTable: end") return t else return false end end ------------------------------------------------------------------------ -- Image loading ------------------------------------------------------------------------ local function getScaledFilename(filename, d) local scalingRatio = scaleFactorForRetina() if (scalingRatio <= 1) then return filename, scalingRatio else local scalesuffix = "@"..scalingRatio.."x" -- Is there an other sized version? local suffix = substring(filename, strlen(filename)-3, -1) local name = substring(filename, 1, strlen(filename)-4) local f2 = name .. scalesuffix .. suffix -- If no scaled file, get original if (fileExists(f2,d)) then filename = f2 return filename, scalingRatio else return filename, 1 end end end ---------------------------------------------------------------------- -- Get an image size (height, width) -- We need this to use it for display.newImageRect -- Let's keep a list of image sizes so we can avoid double-loading.align -- Every time we load, save the size to a list we maintain. ---------------------------------------------------------------------- -- Get an image size (height, width) -- We need this to use it for display.newImageRect -- Let's keep a list of image sizes so we can avoid double-loading.align -- Every time we load, save the size to a list we maintain. -- *** The first time, the list will be taken from the resources directory! local function getImageSize(f,d) d = d or system.ResourceDirectory local imageInfoList if (not FUNX.imageInfoList) then imageInfoList = loadTable("images_info.json", system.CachesDirectory) if (not imageInfoList) then imageInfoList = loadTable("_user/images_info.json", system.ResourceDirectory) or {} if (not imageInfoList) then print ("Warning: funx.getImageSize() : Could not find file, images_info.json") end end FUNX.imageInfoList = imageInfoList else imageInfoList = FUNX.imageInfoList end -- load info table, if not loaded if (not imageInfoList) then imageInfoList = loadTable("images_info.json", system.CachesDirectory) end -- Check the sizes list for this image if (imageInfoList[f]) then return imageInfoList[f].width, imageInfoList[f].height else -- add to the list local i = display.newImage(f,d,true) local w = i.contentWidth local h = i.contentHeight i:removeSelf() i = nil imageInfoList[f] = { width = w, height = h } saveTable(imageInfoList, "images_info.json", system.CachesDirectory) return w,h end end -------------------------------------------------------- -- An attempt to load images async, rather than force everything to wait. -- SO FAR, IT DOESN'T QUITE WORK! IMAGES GET LOADED, BUT DON'T -- END UP IN THE RIGHT PLACES. local function getDisplayObjectParams(i) -- Save the useful values from the target we are replacing local params = { alpha = i.alpha, height = i.height, isHitTestMasked = i.isHitTestMasked, isHitTestable = i.isHitTestable, isVisible = i.isVisible, maskRotation = i.maskRotation, maskScaleX = i.maskScaleX, maskScaleY = i.maskScaleY, maskX = i.maskX, maskY = i.maskY, parent = i.parent, rotation = i.rotation, width = i.width, xReference = i.xReference, x = i.x, xOrigin = i.xOrigin, xScale = i.xScale, yReference = i.yReference, y = i.y, yOrigin = i.yOrigin, yScale = i.yScale, } return params end local function lazyLoad(target,f,w,h) local params, g if (target) then params = getDisplayObjectParams(target) end local function loadImage() if (target) then if (target.parent) then g = target.parent end target:removeSelf() --target = nil else target = {} end target = display.newImageRect(f,w,h) if (g) then g:insert(target) end for i,j in pairs (params) do if (i ~= "width" and i ~= "height") then target[i] = j end end print ("Loaded"..f ) end timer.performWithDelay( 1000, loadImage ) end -------------------------------------------------------- -- Replace placeholder directory in path name with real value -- p : a single character placeholder, default is "*" -- v : the real value, e.g. "mypath" -- Any slashes must be in the original. -- Example: -- replaceWildcard ("*/images/pic.jpg", "mydir", "?") -------------------------------------------------------- local function replaceWildcard(text, v, p) --print ("scripts.funx.replaceWildcard", text, v, p) if (text and v) then p = p or "*" text = text:gsub("%"..p, v) end return text end -------------------------------------------------------- -- Load an image file. If it is not there, load a "missing image" file -- filename is a full pathname, e.g. images/in/my/folder/pic.jpg -- Default system directory is system.ResourceDirectory -- If filepath is set, replace "*" in the filename with the filepath. -- If no "*" in the filename, then the file MUST be a system file! -- If there is a "*" in the filename, the file MUST be a user file, found in the CachesDirectory. -- DEPRECATED: ALWAYS USE CORONA METHOD: method: true = use my method, false means use Corona method -------------------------------------------------------- local function loadImageFile(filename, wildcardPath, whichSystemDirectory, showTraceOnFailure) local scalingRatio = 1 local scaleFraction = 1 local scalesuffix = "" local otherFound = false if (_DEVELOPING) then showTraceOnFailure = true end if (filename) then wildcardPath = wildcardPath or "_user" -- If the filename starts with a wildcard, then replace it with the wildcardPath local wc = substring(filename,1,1) if (wc == "*" and wildcardPath) then filename = replaceWildcard(filename, wildcardPath) -- Files inside _user are system files, everything else with a wildcard is -- a downloaded book. if (not find(wildcardPath, "^_user") ) then --if (wildcardPath ~= "_user") then whichSystemDirectory = whichSystemDirectory or system.CachesDirectory else whichSystemDirectory = whichSystemDirectory or system.ResourceDirectory end end -- default to system for files, e.g. _ui/mygraphic.jpg whichSystemDirectory = whichSystemDirectory or system.ResourceDirectory -- ANDROID FIX -- To allow images inside folders, we can add ".txt" to the image -- frg 2016-01-23 -- added check for existence of file and then adding .txt to extension -- to try again. On Android devices, it is not possible to read .png or .jpg -- files, but appending .txt will work. if (hardwareInfo.isAndroid) then if ( not fileExists(filename, whichSystemDirectory)) then filename = filename .. ".txt" end end if (fileExists(filename, whichSystemDirectory)) then local image -- Corona newImageRect version for loading images -- Check for a scaled file before loading it local f,s = getScaledFilename(filename, whichSystemDirectory) --timePassed("loadImageFile start loading..."..filename) -- If scale comes back ~= 1 then there is a scaled version -- and there is need of one. if (s ~= 1) then local w,h = getImageSize(filename,whichSystemDirectory) image = display.newImageRect(filename, whichSystemDirectory, w, h) --timePassed("loadImageFile, Loaded using newImageRect, C1:"..filename) else image = display.newImage(filename, whichSystemDirectory, true) --timePassed("loadImageFile, loaded using newImage, C2:"..filename) end --print ("loadImageFile: Using Corona method:", filename) anchorZero(image, "Center") return image, scaleFraction end end -- FAILURE -- DEBUGGING TOOL if (showTraceOnFailure) then print ("scripts.funx.loadImageFile called by:") traceback() end local i = display.newGroup() i.anchorChildren = true anchorZero(i, "Center") local image = display.newImage(i, "_ui/missing-image.png", system.ResourceDirectory, true) -- Write to the log! local syspath = system.pathForFile( "", whichSystemDirectory ) --print ("loadImageFile: whichSystemDirectory", syspath ) if (syspath == "") then syspath = "ResourceDirectory" end print ("WARNING: loadImageFile cannot find ",filename," in ",syspath) local t = display.newText( "Cannot find:" .. filename, 0, 0, native.systemFontBold, 24 ) i:insert(t) image.x = midscreenX image.y = midscreenY anchor(t, "Center") t.x = midscreenX t.y = midscreenY+40 anchor(i, "Center") i.x = 0 i.y = 0 -- second returned value is scaleFraction and 1 does nothing but won't crash stuff return i, 1 end -------------------------------------------------------- -- Verify Net Connection OR QUIT! -- WARNING, THIS QUITS THE APP IF NO CONNECTION!!! -------------------------------------------------------- local function verifyNetConnectionOrQuit() local http = require("socket.http") local ltn12 = require("ltn12") if http.request( "http://www.google.com" ) == nil then local function onCloseApp( event ) if "clicked" == event.action then os.exit() end end native.showAlert( "Alert", "An internet connection is required to use this application.", { "Exit" }, onCloseApp ) end end -------------------------------------------------------- -- hasNetConnection: return true if connected, false if not. -- url: a server to check (use http://...) -- showActivity: Turn off the activity indicator (must be turned on before starting) -------------------------------------------------------- local function hasNetConnection(url,showActivity) local socket = require("socket") local test = socket.tcp() test:settimeout(1, 't') -- timeout 5 sec url = url or "www.google.com" if (substring(url, 1, 4) == "http") then url = url:gsub("^https?://", "") end local testResult = test:connect(url,80) test:close() if (testResult == nil) then if (showActivity) then native.setActivityIndicator( false ) end return false else if (showActivity) then native.setActivityIndicator( false ) end return true end end -------------------------------------------------------- -- canConnectWithServer: return true if connected, false if not. -- url: a server to check (use http://...) -- showActivity: Turn off the activity indicator (must be turned on before starting) -------------------------------------------------------- local function canConnectWithServer(url, showActivity, callback, testing) local function MyNetworkReachabilityListener(event) if (testing) then print( "url", url ) print( "address", event.address ) print( "isReachable", event.isReachable ) print("isConnectionRequired", event.isConnectionRequired) print("isConnectionOnDemand", event.isConnectionOnDemand) print("IsInteractionRequired", event.isInteractionRequired) print("IsReachableViaCellular", event.isReachableViaCellular) print("IsReachableViaWiFi", event.isReachableViaWiFi) end network.setStatusListener( url, nil) -- Simulator bug or something...always returns failure local isSimulator = "simulator" == system.getInfo("environment") if (isSimulator) then event.isReachable = true print ("scripts.funx.canConnectWithServer: Corona simulator: Forcing a TRUE for event.isReachable because this fails in simulator.") end -- Turn OFF native busy activity indicator if (showActivity) then native.setActivityIndicator( false ) end if (type(callback) ~= "function") then return event.isReachable else callback(event.isReachable) end end if network.canDetectNetworkStatusChanges then network.setStatusListener( url, MyNetworkReachabilityListener ) else print("scripts.funx.canConnectWithServer: network reachability not supported on this platform") end end -------------- --- Given an array of values, e.g. {"a", "b", "c" } -- convert to an array of key = true, so we can very quickly -- ask whether value is in the array. -- IF we pass anything other than a table, return what was passed. local function tableConvertValuesToKeys(t) if ( "table" == type(t) ) then local t2 = {} for k,v in pairs (t) do t2[v] = true end return t2 else return t end end -------------- --- Check that a key in table 1 exists in table 2. -- Useful for making sure the a setting value in the user settings is correctly named. -- example: keysExistInTable(usersettings,settings) local function keysExistInTable(t1,t2) for k,v in pairs (t1) do if (type(v) == "table") then for kk,vv in pairs (v) do if (t2[k] == nil or t2[k][kk] == nil) then print ("WARNING: '"..k.." . "..kk.." is an unknown key.") end end end end end --- Check if a value is in a table -- Same as in_array(myarray, value) local function inTable(needle, haystack) -- find element v of haystack satisfying f(v) if (haystack and type(haystack) == "table") then for _, v in ipairs(haystack) do if ( v == needle ) then return v end end end return nil end -------------- -- A Handy way to store an RGB or RGBA color is as a string, e.g. "250,250,10,50%" -- The 4th value is an alpha, 0-255, or OPAQUE or TRANSPARENT -- This returns a table from such a string. -- If given a table, this does nothing (in case the value was already converted somewhere!) -- -- If any value is between 0 & 1, then we must be dealing with HDR values, not RGB values -- e.g. 0,0,2 must be RGB, but 0,0,0.1 must be HDR. -- We only have a problem when the highest value is 1, but when would anyone use an RGB value of 1? Never. -- Therefore, if all values <= 1 then it's and HDR value. -- -- If toHDR, then force the result to be HDR. This is useful for widgets and other libraries -- that don't let us redefine their display.setFillColor functions. local function stringToColorTable(s, toHDR, isHDR) if (type(s) == "string") then s = trim(s, true) if (s) then s = split(s, ",") local maxVal = 255 -- RGB max --[[ local valSum = ( tonumber(s[1]) or 0) + (tonumber(s[2]) or 0) + (tonumber(s[3]) or 0) if ( isHDR or ( valSum > 0 and valSum <= 3 ) ) then maxVal = 1 -- HDR max end --]] local opacity = lower(s[4] or maxVal) if ( opacity == "opaque" ) then s[4] = maxVal elseif (opacity == "transparent") then s[4] = 0 else s[4] = applyPercent(s[4], maxVal) or maxVal end -- force numeric for i,j in pairs(s) do s[i] = tonumber(j) s[i] = applyPercent(j,maxVal) or maxVal end if (toHDR) then s = { s[1]/255, s[2]/255, s[3]/255, s[4]/255 } end end end return s end -- *** Apparently, not necessary! I built this due to a bug in the dmc_kolor patch. -- Here's a shortcut for getting an HDR color from RGB or HDR values -- Set isHDR to true if the input string uses HDR values local function stringToColorTableHDR(s, isHDR) return stringToColorTable(s, true, isHDR) end --=================================== --- Frame a group by adding rectangle to a group, behind it. local function frameGroup(g, s, color) local w,h = g.contentWidth or screenW, g.contentHeight or screenH local a = g.anchorChildren g.anchorChildren = true local bounds = g.contentBounds -- print( "xMin: ".. bounds.xMin ) -- xMin: 100 -- print( "yMin: ".. bounds.yMin ) -- yMin: 100 -- print( "xMax: ".. bounds.xMax ) -- xMax: 150 -- print( "yMax: ".. bounds.yMax ) -- yMax: 150 g.anchorChildren = a local r = display.newRect(g, bounds.xMin, bounds.yMin, w, h) r.strokeWidth = s or 1 color = color or "255,0,0" if (type(color) == "string") then color = stringToColorTable(color) end r:setStrokeColor(unpack(color)) r:setFillColor(255,0,0, 50) r:toBack() r.anchorX, r.anchorY = 0,0 r.x, r.y = bounds.xMin, bounds.yMin g._frame = r end ------------------------------------------------- -- Darken the screen -- by drawing a dark opaque rectangle over it. -- Returns the darkening object. -- Undim, below, will destroy the object. -- Because the object which will contain the image might -- be scaled, we need to include a scaling -- factor, to adjust the screen image. -- locked: if true or a function then lock the screen from touches or pass touch to the function. ------------------------------------------------- local function dimScreen(transitionTime, color, scaling, onTouch) transitionTime = tonumber(transitionTime or 300) color = color or { 0.75 * OPAQUE } local opacity = applyPercent(color[4],OPAQUE) or (0.75 * OPAQUE) scaling = scaling or 1 local c = stringToColorTable(color or "55,55,55,75%") -- cover all rect, darken background local bkgdrect = display.newRect(0,0,screenW,screenH) bkgdrect.x, bkgdrect.y = midscreenX, midscreenY bkgdrect:setFillColor( unpack(c) ) bkgdrect:scale(1/scaling, 1/scaling) transition.to (bkgdrect, {alpha=opacity, time=transitionTime } ) if (type(onTouch) ~= "function") then onTouch = function() return onTouch; end end bkgdrect:addEventListener("touch", onTouch ) return bkgdrect end local function undimScreen(handle, transitionTime, f) local function killme() display.remove(handle) handle = nil if (type(transitionTime) == "function") then transitionTime() elseif (type(f) == "function") then f() end end local t if (type(transitionTime) == "number") then t = transitionTime else t = 300 end transition.to (handle, {alpha=0, time=t, onComplete=killme } ) end ------------------------------------------------- -- Shrink the obj away until it is small, then disappear it. -- Restore its size when done, but leave it hidden -- Default is shrink to center, but can set destX, destY local function shrinkAway (obj, callback, transitionSpeed, destX, destY) destX = destX or midscreenX destY = destY or midscreenY local xs = obj.yScale local ys = obj.xScale local w = obj.width local h = obj.height local a = obj.alpha local function cb() obj.xScale = xs obj.yScale = ys obj.width = w obj.height = h obj.alpha = a obj.isVisible = false callback() end callback = callback or nil local t = transitionSpeed or 500 anchor(obj, "Center") transition.to( obj, { time=t, xScale=0.01, yScale=0.01, alpha=0, x=destX, y=destY, onComplete=cb } ) end ------------------------------------------------- local function fadeOut (obj, callback, transitionSpeed) callback = callback or nil if (type(callback) ~= "function") then callback = nil end local function myCallback() obj._isTweening = false if (callback) then callback() end end local t = transitionSpeed or 500 transition.to( obj, { time=t, alpha=0, onComplete=myCallback } ) obj._isTweening = true end ------------------------------------------------- local function fadeIn (obj, callback, transitionSpeed) callback = callback or nil if (type(callback) ~= "function") then callback = nil end local function myCallback() obj._isTweening = false if (callback) then callback() end end if (not obj.isVisible) then obj.alpha = 0 obj.isVisible = true end local t = transitionSpeed or 500 transition.to( obj, { time=t, alpha=1, onComplete=myCallback} ) obj._isTweening = true end ------------------------------------------------------------------------ -- Show a message, then fade away ------------------------------------------------------------------------ local function tellUser(message, x,y) if (not message) then return true end local screenW, screenH = display.contentWidth, display.contentHeight local viewableScreenW, viewableScreenH = display.viewableContentWidth, display.viewableContentHeight local screenOffsetW, screenOffsetH = display.contentWidth - display.viewableContentWidth, display.contentHeight - display.viewableContentHeight local midscreenX = screenW*(0.5) local midscreenY = screenH*(0.5) local TimeToShowMessage = 2000 local FadeMessageTime = 500 -- message object local msg = display.newGroup() local x = x or 0 local y = y or 0 local w = screenW - 40 local h = 0 -- height matches text -- msg corner radius local r = 10 ------------------------------------------------------------------------ local function closeMessage( event ) -- remove from display hierarchy msg.parent:remove( msg ) return true end ------------------------------------------------------------------------ local function fadeAwayThenClose() transition.to( msg, { time=FadeMessageTime, alpha=0, onComplete=closeMessage} ) timedMessage = nil timedMessageList[1] = nil -- remove first element table.remove(timedMessageList, 1) --print ("Messages:", #timedMessageList) end ------------------------------------------------------------------------ -- Create empty text box, using default bold font of device (Helvetica on iPhone) -- Screen Width version: local textObject = display.newText( message, 0, 0, w/3,h, native.systemFontBold, 24 ) -- Fitted width version, does NOT wrap text! --local textObject = display.newText( message, 0, 0, native.systemFontBold, 24 ) textObject:setFillColor( 255,255,255 ) w = textObject.width -- A trick to get text to be centered msg.x = midscreenX msg.y = screenH/3 msg:insert( textObject, true ) -- hide initially msg.alpha = 0 -- Insert rounded rect behind textObject local bkgd = display.newRoundedRect( 0, 0, textObject.contentWidth + 2*r, textObject.contentHeight + 2*r, r ) bkgd:setFillColor( 55, 55, 55, 190 ) msg:insert( 1, bkgd, true ) msg.bkgd = bkgd msg.textObject = textObject -- Show message msg.textObject.text = message msg.bkgd.width = msg.textObject.width + 2*r -- If there is a current message showing, cancel it if (timedMessage) then --timer.cancel(timedMessage) end msg.y = msg.y + (#timedMessageList - 1) * msg.bkgd.height --print ("msg:show width = "..msg.textObject.width) transition.to( msg, { time=FadeMessageTime, alpha=1} ) timedMessage = timer.performWithDelay( TimeToShowMessage, fadeAwayThenClose ) timedMessageList[#timedMessageList + 1] = timedMessage end ------------------------------------------------- -- POPUP: popup a display group -- We have white and black popups. Default is white. -- If the first param is a table, then we assume all params are in that table, IN ORDER!!!, -- If alpha > 0, then ignore a call to show it. --[[ @param [table] t = table of params, below: @param [display object] table.object @param [string] table.backgroundColor @param [string] table.showBackground @param [string] table.bkgdAlpha @param [string] table.transitionTime @param [string] table.filename --]] ------------------------------------------------- local function popupDisplayGroup(t, frontstage) local obj = t.object if (not obj or (obj.isVisible == true and obj.alpha > 0) ) then return false end --[[ local backgroundColor = trim(t.backgroundColor) local showBackground = t.showBackground local bkgdAlpha = applyPercent(bkgdAlpha or 0.95,1) local backgroundFile = trim(t.backgroundFile ) --]] local transitionTime = tonumber(t.time) or 300 local doDimScreen = t.doDimScreen local cancelOnTouch = t.cancelOnTouch local closing = false local function moveToFrontstage(obj) if (not obj.onFrontstage) then --------------- -- Move the object to the front stage, above buttons and everything -- Save the x,y from whence we pluck the object obj.localX = obj.x obj.localY = obj.y -- Save the parent group reference obj._parentGroup = obj.parent frontstage:insert(obj) if (obj.dimBackgroundOnZoom and frontstage.numChildren < 3) then frontstage.background.alpha = 0 transition.to(frontstage.background, { time=obj.zoomTransitionTime, alpha=frontstage.background._alpha } ) end obj:toFront() obj.onFrontstage = true end end local function restoreFromFrontstage(obj) --------------- -- Move object from the frontstage back to the group it came from. -- Do this first, so we can restore the picture to its proper -- zLayer in the set of pictures! if (obj.onFrontstage) then --local lx, ly = obj:localToContent(obj.x, obj.y) local lx, ly = obj.localX, obj.localY obj._parentGroup:insert(obj) --obj:setReferencePoint(display[obj.originalReferencePoint .. "ReferencePoint"]) anchor(obj, obj.originalReferencePoint) obj.x = lx obj.y = ly -- Get rid of this reference just in case, to avoid memory leaks obj._parentGroup = nil obj.onFrontstage = false end -- Restore objects to their proper layers if (obj.layer == "top" ) then obj:toFront() elseif (obj.layer == "bottom" ) then obj:toBack() elseif (obj.layer and obj.restoreLayersOnZoomOut) then zSort(obj.parent) end end local function cleanup() if (doDimScreen) then undimScreen(obj._dim) end if (frontstage) then restoreFromFrontstage(obj) end end local function closeMe(event) if (not closing and obj ~= nil) then -- remove the close button if (obj._popupCloseButton) then obj._popupCloseButton:removeSelf() obj._popupCloseButton = nil end transition.to (obj, {alpha=0, time=transitionTime, onComplete=cleanup} ) closing = true end return true end -- w/h of the popup local w,h = obj.contentWidth, obj.contentHeight --[[ -- BACKGROUND -- cover all rect, darken background local bkgdrect = display.newRect(0,0,screenW,screenH) obj:insert(bkgdrect) bkgdrect:setFillColor( 55, 55, 55, 190 ) -- background graphic for popup -- If the default fails, try using the value as a filename local bkgd if (backgroundFile) then bkgd = display.newImage( backgroundFile, true) elseif (backgroundColor) then bkgd = display.newRect(0,0, obj.contentWidth, obj.contentHeight) bkgd:setFillColor( stringToColorTable(backgroundColor)) end local bkgdWidth, bkgdHeight if (bkgd) then checkScale(bkgd) obj:insert (bkgd) anchor(bkgd, "Center") bkgd.x = midscreenX bkgd.y = midscreenY bkgd.alpha = bkgdAlpha bkgdWidth = bkgd.width bkgdHeight = bkgd.height w,h = bkgd.contentWidth, bkgd.contentHeight end --]] local closeButton = widget.newButton{ defaultFile = "_ui/button-cancel-round.png", overFile = "_ui/button-cancel-round-over.png", onRelease = closeMe, } obj:insert(closeButton) obj._popupCloseButton = closeButton anchorZero(closeButton, "Center") closeButton.x = (w) - closeButton.width/4 closeButton.y = closeButton.height/4 closeButton:toFront() obj.alpha = 0 obj.isVisible = true --[[ -- Dimming requires moving to front stage, etc. No time for that now if (doDimScreen) then -- true means lock the background against touches local c = "0,0,0,75%" obj._dim = dimScreen(transitionTime, c, nil, true) end --]] if (frontstage) then moveToFrontstage(obj) end -- Capture touch events and do nothing. if (cancelOnTouch) then obj:addEventListener( "touch", closeMe ) else obj:addEventListener( "touch", function() return true end ) end transition.to (obj, {alpha=1, time=transitionTime } ) end ------------------------------------------------- -- POPUP: popup image with close button -- We have white and black popups. Default is white. -- If the first param is a table, then we assume all params are in that table, IN ORDER!!!, -- starting with filename, e.g. { "filename.jpg", "white", 1000, true} ------------------------------------------------- local function popup(filename, color, bkgdAlpha, transitionTime, cancelOnTouch) local mainImage local pgroup = display.newGroup() pgroup.anchorChildren = true local closing = false if (type(filename) == "table") then color = filename.color bkgdAlpha = filename.bkgdAlpha transitionTime = tonumber(filename.time) cancelOnTouch = filename.cancelOnTouch or false filename = trim(filename.filename) end bkgdAlpha = applyPercent(bkgdAlpha, 1) color = trim(color) if (color == "") then color = "white" end bkgdAlpha = applyPercent(bkgdAlpha,1) or 0.95 transitionTime = tonumber(transitionTime) transitionTime = transitionTime or 300 cancelOnTouch = cancelOnTouch or false local function killme() if (pgroup ~= nil) then display.remove(pgroup) pgroup=nil --print "Killed it" else --print ("Tried to kill pGroup, but it was dead.") end end local function closeMe(event) if (not closing and pgroup ~= nil) then transition.to (pgroup, {alpha=0, time=transitionTime, onComplete=killme} ) closing = true end return true end -- cover all rect, darken background local bkgdrect = display.newRect(0,0,screenW,screenH) pgroup:insert(bkgdrect) bkgdrect:setFillColor( 55, 55, 55, 190 ) -- background graphic for popup -- If the default fails, try using the value as a filename local bkgd = display.newImage("_ui/popup-"..color..".png", true) if (not bkgd) then bkgd = display.newImage(color, true) if (not bkgd) then print ("ERROR: Missing popup background image ("..color..")") end end local bkgdWidth, bkgdHeight if (bkgd) then checkScale(bkgd) pgroup:insert (bkgd) anchor(bkgd, "Center") bkgd.x = midscreenX bkgd.y = midscreenY bkgd.alpha = bkgdAlpha bkgdWidth = bkgd.width bkgdHeight = bkgd.height else bkgdWidth = screenW * 0.95 bkgdHeight = screenH * 0.95 end mainImage = display.newImage(filename, true) checkScale(mainImage) pgroup:insert (mainImage) anchor(mainImage, "Center") mainImage.x = midscreenX mainImage.y = midscreenY local closeButton = widget.newButton{ defaultFile = "_ui/button-cancel-round.png", overFile = "_ui/button-cancel-round-over.png", onRelease = closeMe, } pgroup:insert(closeButton) anchorZero(closeButton, "Center") closeButton.x = (bkgd.width/2) - closeButton.width/4 closeButton.y = -(bkgd.height/2) + closeButton.height/4 closeButton:toFront() pgroup.alpha = 0 -- Capture touch events and do nothing. if (cancelOnTouch) then pgroup:addEventListener( "touch", closeMe ) else pgroup:addEventListener( "touch", function() return true end ) end transition.to (pgroup, {alpha=1, time=transitionTime } ) end ------------------------------------------------- -- POPUP: popup web page ------------------------------------------------- local function popupWebpage(targetURL, color, bkgdAlpha, transitionTime, netrequired, noNetMsg) local testing = false local closing = false if (type(targetURL) == "table") then color = trim(targetURL[2]) bkgdAlpha = tonumber(targetURL[3]) transitionTime = tonumber(targetURL[4]) targetURL = trim(targetURL[1]) end -------------------------- local function doPop(isReachable) --print ("doPop says, isReachable =", isReachable) if (isReachable) then local mainImage local pgroup = display.newGroup() anchor(pgroup, "Center") pgroup.x, pgroup.y = midscreenX, midscreenY color = color or "white" bkgdAlpha = bkgdAlpha or 0.95 transitionTime = transitionTime or 300 local function killme() if (pgroup ~= nil) then display.remove(pgroup) pgroup=nil --print "Killed it" else --print ("Tried to kill pGroup, but it was dead.") end end local function closeMe(event) if (not closing and pgroup ~= nil) then native.cancelWebPopup() transition.to (pgroup, {alpha=0, time=transitionTime, onComplete=killme} ) closing = true end return true end -- cover all rect, darken background local bkgdrect = display.newRect(0,0,screenW,screenH) pgroup:insert(bkgdrect) anchor(bkgdrect, "Center") bkgdrect:setFillColor( 55, 55, 55, 190 ) -- background graphic for popup local bkgd = display.newImage("_ui/popup-"..color..".png", true) checkScale(bkgd) pgroup:insert (bkgd) anchor(bkgdrect, "Center") bkgd.alpha = bkgdAlpha local closeButton = widget.newButton { id = "close", defaultFile = "_ui/button-cancel-round.png", overFile = "_ui/button-cancel-round-over.png", onRelease = closeMe, } pgroup:insert(closeButton) anchor(closeButton, "TopRight") anchorZero(closeButton, "Center") closeButton.x = (bkgd.width/2) - closeButton.width/4 closeButton.y = -(bkgd.height/2) + closeButton.height/4 closeButton:toFront() pgroup.alpha = 0 -- Capture touch events and do nothing. pgroup:addEventListener( "touch", function() return true end ) local function showMyWebPopup() local function listener( event ) local shouldLoad = true --print ("popupWebpage:listener") --dumptable(event) --print ("========") --print ("event.errorCode",event.errorCode) if ( event.errorCode and event.errorCode ~= -999 ) then -- Error loading page print( "showMyWebPopup: Error: " .. tostring( event.errorMessage ) ) shouldLoad = false end return shouldLoad end -- web popup local x = (screenW - bkgd.width)/2 + (closeButton.width) local y = (screenH - bkgd.height)/2 + (closeButton.height) local w = bkgd.width - (2 * closeButton.width) local h = bkgd.height - (2 * closeButton.width) --print ("showWebMap: go to ",targetURL) --print (x, y, w, h, targetURL) local options = { hasBackground=true, urlRequest = listener, -- Only need this for local URLs --baseUrl=system.ResourceDirectory, } --print ("showWebPopup:",targetURL) --print ("========") native.showWebPopup(x, y, w, h, targetURL, options ) end transitionTime = tonumber(transitionTime) transition.to (pgroup, {alpha=1, time=transitionTime, onComplete=showMyWebPopup } ) else noNetMsg = noNetMsg or "No Internet" tellUser(noNetMsg .. ":" .. targetURL) end end -- callback function -------------------------- -- Do we have network? -- Don't test with our URL, since it might have authentication in it, -- e.g. human:password@myurl.com --local testurl = targetURL local testurl = "http://google.com" if (substring(testurl, 1, 4) == "http") then testurl = testurl:gsub("^https?://", "") end -- strip subfolders b/c of iOS bug testurl = gsub(testurl, "/.*", "") canConnectWithServer(testurl, false, doPop, testing) end ------------------------------------------------------------------------ -- OPEN a URL ------------------------------------------------------------------------ local function openURLWithConfirm(urlToOpen, title, msg) -- Handler that gets notified when the alert closes local function onComplete( event ) if "clicked" == event.action then local i = event.index if 1 == i then system.openURL(urlToOpen) elseif 2 == i then -- do nothing, dialog with close end end end -- Show alert with five buttons local alert = native.showAlert(title, msg , { "OK", "Cancel" }, onComplete ) end ------------------------------------------------------------------------ -- SHADOW - Image-based version for Graphics 1.0 -- Build a drop shadow ------------------------------------------------------------------------ local function buildShadow(w,h,sw,opacity) local shadow = display.newGroup() --addPosRect(shadow,false) --shadow.anchorChildren = true --print ("buildShadow: ",w,h) local tl = display.newImage(shadow, "_ui/shadow_tl.png") local tr = display.newImage(shadow, "_ui/shadow_tl.png") local bl = display.newImage(shadow, "_ui/shadow_tl.png") local br = display.newImage(shadow, "_ui/shadow_tl.png") -- Rotations make these non-obvious! anchorZero(tl, "TopLeft") anchorZero(tr, "TopLeft") anchorZero(bl, "TopRight") anchorZero(br, "BottomRight") local left = display.newImage(shadow, "_ui/shadow_l.png") local right = display.newImage(shadow, "_ui/shadow_l.png") local top = display.newImage(shadow, "_ui/shadow_l.png") local bottom = display.newImage(shadow, "_ui/shadow_l.png") anchor(left, "TopLeft") anchor(right, "TopLeft") anchor(top, "TopLeft") anchor(bottom, "TopLeft") anchor(left, "TopLeft") anchor(right, "BottomLeft") top.anchorX, top.anchorY = 0.5,1 bottom.anchorX, bottom.anchorY = 0.5,0 -- SIZING local corner = sw local edge = sw -- Start with a solid rect --local srect = display.newRect(shadow, corner,corner,w-(2*corner),h-(2*corner)) -- Alpha visually matches the graphic pieces. Probably we should use another graphic --srect:setFillColor( 0,0,0,70 ) local srect = display.newImage(shadow, "_ui/shadow_rect.png") srect.width = w -- (2*corner) srect.height = h -- (2*corner) anchor(srect, "TopLeft") srect.x = corner srect.y = corner -- rotate tr:rotate( 90 ) bl:rotate( -90 ) br:rotate( 180 ) right:rotate( 180 ) top:rotate( 90 ) bottom:rotate( -90 ) if (h<(2*corner) or w<(2*corner)) then print ("scripts.funx.buildShadow: ERROR! The shadow box is to small..I can't compute this one") end --scale corner = sw local cornerPad = sw/2 edge = sw local edgePad = sw/2 local r = sw / tl.width if (r>1) then tl:scale(r,r) tr:scale(r,r) bl:scale(r,r) br:scale(r,r) -- Rotations make this non-obvious, x,y get flipped! top.width = sw top.height = w bottom.width = sw bottom.height = w left.width = sw left.height = h right.width = sw right.height = h end if (corner == h/2) then display.remove(left) left = nil display.remove(right) right = nil end if (w <= (2*corner)) then display.remove(top) top = nil display.remove(bottom) bottom = nil end if (h > (2*corner) and left) then --left.height = h-corner --right.height = h-corner end if (w > (2*corner) and top) then --top.height = sw --bottom.height = w-corner end -- position --[[ anchor(tl, "TopLeft") anchor(tr, "TopLeft") anchor(bl, "TopLeft") anchor(br, "TopLeft") anchor(left, "TopLeft") anchor(right, "TopLeft") anchor(top, "TopLeft") anchor(bottom, "TopLeft") ]] if (top) then top.x = corner top.y = cornerPad bottom.x = corner bottom.y = h+ corner + cornerPad end if (left) then left.x = 0 left.y = sw right.x = w + 2*sw right.y = sw end tr.x = w + 2*corner tr.y = 0 br.x = w + corner br.y = h + corner bl.y = h + corner return shadow end ------------------------------------------------------------------------ -- SHADOW - Filter Effects based using Graphics 2.0 -- Build a drop shadow by duplicating any object in a snapshot -- and blurring and coloring it. ------------------------------------------------------------------------ local function buildShadowObj(obj, sw, color, opacity) w = obj.contentWidth h = obj.contentHeight sw = sw or 20 local shadow = display.newSnapshot( w + 2*sw, h + 2*sw ) -- Start with a solid rect local srect = display.newRect(0,0,w + 1*sw,h + 1*sw) color = color or "0,0,0,100%" local c = stringToColorTable(color) if opacity then c[4] = applyPercent(opacity,1) end -- Alpha visually matches the graphic pieces. Probably we should use another graphic srect:setFillColor( 0,0,0, opacity ) shadow.group:insert(srect) shadow.fill.effect = "filter.blurGaussian" shadow.fill.effect.horizontal.blurSize = sw shadow.fill.effect.horizontal.sigma = 140 shadow.fill.effect.vertical.blurSize = sw shadow.fill.effect.vertical.sigma = 140 --shadow.fill.effect = "filter.blur" return shadow end ------------------------------------------------------------------------ -- Functions to do on a system event, -- e.g. load or exit -- Options: -- options.onAppStart = function for start or resume -- options.onAppExit = function for exit or suspend ------------------------------------------------------------------------ local function initSystemEventHandler(options) --------------------- local function shouldResume() return true end --------------------- --------------------- local function onSystemEvent( event ) if (options == nil) then return true end if (event.type == "applicationExit" ) then options.onAppExit() elseif ( event.type == "applicationSuspend" ) then options.onAppSuspend() elseif ( event.type == "applicationStart" ) then options.onAppStart() elseif ( event.type == "applicationResume" ) then options.onAppResume() end --[[ if ( (event.type == "applicationExit" or event.type == "applicationSuspend") and type(options.onAppExit) == "function" ) then options.onAppExit() elseif ( (event.type == "applicationStart" or event.type == "applicationResume") and type(options.onAppStart) == "function" ) then if shouldResume() then options.onAppStart() else -- start app up normally end end --]] end --------------------- Runtime:addEventListener( "system", onSystemEvent ); end --===================================================== -- the reason this routine is needed is because lua does not -- have a sort indexed table function -- reverse : if set, sort reverse local function table_sort(a, sortfield, reverse) local new1 = {} local new2 = {} for k,v in pairs(a) do table.insert(new1, { key=k, val=v } ) end if (reverse) then table.sort(new1, function (a,b) return ((a.val[sortfield] or '') > (b.val[sortfield] or '') ) end) else table.sort(new1, function (a,b) return ((a.val[sortfield] or '') < (b.val[sortfield] or '') ) end) end for k,v in pairs(new1) do table.insert(new2, v.val) end return new2 end --[[ Sort a table of strings As a more advanced solution, we can write an iterator that traverses a table following the order of its keys. An optional parameter f allows the specification of an alternative order. It first sorts the keys into an array, and then iterates on the array. At each step, it returns the key and value from the original table: t : the table f : a function which compares two keys, e.g. f = function(a,b) return a<b end With this function, it is easy to print those function names in alphabetical order. The loop for name, line in pairsByKeys(lines) do print(name, line) end ]] local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end --[[ ===================================================== Multi-column table sort. If returnNumericArray is false, returns an associated array, but there is a warning these are unstable, whatever that really means. If returnNumericArray is true, then returns a table with NUMERICAL indeces { 1,2,3 } instead of the original keys because "The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort." So, if returnNumericArray is set, we return a table of this form: t = { {key="key", val={whatever the value was}, .... } The reverseSort parameter is a table that matches the sortfields, with true/false for each item, indicating whether that item should be reverse sorted (true), e.g. lower->highest ** If NO reverseSort table is given, DEFAULT is all reverse sort, from low to high and A->Z!!! Example: local t= { cows = { title = "cows", author="Zak", publisherid="2" }, mice = { title = "Art", author="Bob", publisherid="2" }, zebra = { title = "zebra", author="Gary", publisherid="3" }, } t = table_multi_sort(t, {"publisherid", "title", "author" },{ true, false, false }, true ) --]] local function table_multi_sort(a, sortfields, reverseSort, returnNumericArray) if ( (not reverseSort) or #reverseSort == 0) then reverseSort = {} for i=1,#sortfields do reverseSort[i] = false end end local function cmp2 (a, b) for i=1,(#sortfields-1) do if (reverseSort[i]) then a,b = b,a end local colTitle = sortfields[i] local aa = a.val[colTitle] or "" local bb = b.val[colTitle] or "" if aa < bb then return true end if aa > bb then return false end end local colTitle = sortfields[#sortfields] if (reverseSort[#sortfields]) then a,b = b,a end return a.val[colTitle] < b.val[colTitle] end local new1 = {} local new2 = {} for k,v in pairs(a) do table.insert(new1, { key=k, val=v } ) end table.sort(new1, cmp2) if (returnNumericArray) then return new1 else for k,v in ipairs(new1) do new2[v.key] = v.val end return new2 end end --======================================================================== -- Order objects in a display group by the "layer" field of each object -- We can't use "z-index" cuz the hyphen doesn't work in XML. -- This allows for ordered layering. local function zSort(myGroup) local n = myGroup.numChildren local kids = {} for i=1,n do kids[i] = myGroup[i] end --print ("Zsort: "..n.." children") table.sort(kids, function(a, b) local al = a.layer or 0 local bl = b.layer or 0 --print ("zSort:", al, bl, a.index, a.name) if (al=="top" or bl=="bottom") then return false end if (bl=="top" or al=="bottom") then return true end --print ("a1, b1", al,bl) return (al or 1) < (bl or 1) -- "layer" is your custom z-index field end ) for i = 1,n do myGroup:insert(kids[i]) --print ("zSort result:",i, kids[i].name, " Layer:", kids[i].layer) end return myGroup end --======================================================================== -- get date parts for a given ISO 8601 date format (http://richard.warburton.it ) local function get_date_parts(date_str) if (date_str) then local _,_,y,m,d=find(date_str, "(%d+)-(%d+)-(%d+)") return tonumber(y),tonumber(m),tonumber(d) else return nil,nil,nil end end -- This converts a unix time stamp in GMT time to current local Lua time. -- This is a string of the form, yyyy-mm-dd hh:mm:ss local function datetime_to_unix_time(s) if (s) then local p="(%d+)-(%d+)-(%d+) (%d+):(%d+):(%d+)" local year,month,day,hour,min,sec=s:match(p) local offset=os.time()-os.time(os.date("!*t")) local dateTable = {day=day,month=month,year=year,hour=hour,min=min,sec=sec} local t = os.time{day=day,month=month,year=year,hour=hour,min=min,sec=sec} return (t+offset) else return 0 end end --==================================================== local function getmonth(month) local months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" } return months[tonumber(month)] end --==================================================== local function getday_posfix(day) local idd = math.mod(day,10) return (idd==1 and day~=11 and "st") or (idd==2 and day~=12 and "nd") or (idd==3 and day~=13 and "rd") or "th" end --======================================================================== -- Format a STRING date, e.g. 2005-10-4 in ISO format, into a human format. -- Default for stripZeros is TRUE. local function formatDate(s, f, stripZeros) if (stripZeros == nil) then stripZeros = true end if (s ~= "") then f = f or "%x" local y,m,d = get_date_parts(s) if (y and m and d) then local t = os.time({year=y,month=m,day=d}) s = os.date(f, t) if (stripZeros) then s = s:gsub("/0", "/") s = s:gsub("%.0", ".") s = s:gsub("%, 0", ", ") s = s:gsub("^0", "") end else --print ("Warning: funx.formatDate: the dates provided for formatting are not in xx-xx-xx format: ", s) end return s else return "" end end ------------------------------------------------- -- loadingSpinner -- Show a loading spinner graphic -- *** THIS REQUIRES GRAPHICS IN THE "funx" DIRECTORY! *** -- If these graphics are missing, well, it will break. -- Params is a table: -- @param sheet [string] The path to a sprite sheet for the spinner -- @param delay [int] Time to wait before showing message. If our loading happens fast enough, we don't need -- @param handle [table] Timer reference. If this value is set, then the spinner will be cancelled! -- the message to show. -- Examples of the table: -- { handle = mytimerhandle } -- { message="message", delay=1000 } --[[ local p = { sheet = message="Loading", delay=1000} local myTimerHandle = spinner(p) ... local p = { handle = myTimerHandle } spinner(p) --]] ------------------------------------------------- local function spinner(p) p = p or {} local delay = p.delay or 500 --------------------------spinnerSprite -- Show spinner if (not p.handler) then local spinnerSprite local sheetInfo = require( dotPathToFunxFolder .. "spinner") local myImageSheet = graphics.newImageSheet( pathToFunxFolder.."spinner.png", sheetInfo:getSheet() ) local spinnerSprite = display.newSprite( myImageSheet , sheetInfo.sequenceData ) -- Put in screen center spinnerSprite.x = display.contentCenterX spinnerSprite.y = display.contentCenterY -- I like this size reduction spinnerSprite:scale( 0.5, 0.5 ) -- Hide the spinner until called spinnerSprite.isVisible = false local function showSpinner() spinnerSprite.isVisible = true spinnerSprite:play() if (p.message) then tellUser(p.message) end end --print ("start timer") --print ("spinner started at",os.time(),"seconds") local t = timer.performWithDelay( delay, showSpinner ) t.starttime = os.time() t._spinnerObject = spinnerSprite return t else -------------------------- -- Hide spinner --print ("Spinner canceled!") --print ("spinner cancelled at",os.time(),"seconds after ",os.time()-p.handler.starttime,"seconds.") timer.cancel(p.handler) p.handler._spinnerObject:pause() p.handler._spinnerObject:removeSelf() p.handler._spinnerObject = nil end end local function activityIndicator( mode ) if mode then native.setActivityIndicator( true ) else native.setActivityIndicator( false ) end end local function activityIndicatorOn( mode ) timer.performWithDelay(1, function() native.setActivityIndicator( true ) end ) end local function activityIndicatorOff( mode ) timer.performWithDelay(1, function() native.setActivityIndicator( false ) end ) end ------------------------------------------------------------------------ -- CLEAN GROUP ------------------------------------------------------------------------ local function cleanGroups ( curGroup, level ) if curGroup.numChildren then while curGroup.numChildren > 0 do cleanGroups ( curGroup[curGroup.numChildren], level+1 ) end if level > 0 then display.remove(curGroup) end else display.remove(curGroup) curGroup = nil return true end end ------------------------------------------------------------------------ -- CALL CLEAN FUNCTION ------------------------------------------------------------------------ local function callClean ( moduleName ) if type(package.loaded[moduleName]) == "table" then if lower(moduleName) ~= "main" then for k,v in pairs(package.loaded[moduleName]) do if k == "clean" and type(v) == "function" then package.loaded[moduleName].clean() end end end end end ------------------------------------------------------------------------ -- UNLOAD SCENE ------------------------------------------------------------------------ local function unloadModule ( moduleName ) local fxTime = 200 if type(package.loaded[moduleName]) == "table" then package.loaded[moduleName] = nil local function garbage ( event ) collectgarbage("collect") end garbage() timer.performWithDelay(fxTime,garbage) end end --[[ local function spinner() local isAndroid = "Android" == system.getInfo("platformName") if(isAndroid) then local alert = native.showAlert( "Information", "Activity indicator API not yet available on Android devices.", { "OK"}) end -- local label = display.newText( "Activity indicator will disappear in:", 0, 0, system.systemFont, 16 ) label.x = display.contentWidth * 0.5 label.y = display.contentHeight * 0.3 label:setFillColor( 10, 10, 255 ) local numSeconds = 5 local counterSize = 36 local counter = display.newText( tostring( numSeconds ), 0, 0, system.systemFontBold, counterSize ) counter.x = label.x counter.y = label.y + counterSize counter:setFillColor( 10, 10, 255 ) function counter:timer( event ) numSeconds = numSeconds - 1 counter.text = tostring( numSeconds ) if 0 == numSeconds then native.setActivityIndicator( false ); end end timer.performWithDelay( 1000, counter, numSeconds ) native.setActivityIndicator( true ); end ]] ------------------------------------------------- -- Toggle an object, transitioning between a given alpha, and zero. local function toggleObject(obj, fxTime, opacity, onComplete) fxTime = tonumber(fxTime) opacity = applyPercent(opacity,1) --print () --print () --print ("------------- ToggleObject Begin (opacity: "..opacity) -- Actual alpha of a display object is not exact local currentAlpha = math.ceil(obj.alpha * 100)/100 -- be sure these properties exist obj.tween = obj.tween or {} if (obj._isTweening == nil) then obj._isTweening = false end local function transitionComplete(obj) local currentAlpha = math.ceil(obj.alpha * 100)/100 if (currentAlpha == 0) then obj.isVisible = false else obj.isVisible = true end obj._isTweening = false obj.tweenDirection = nil if (onComplete) then onComplete() end end -- Cancel transition if caught in the middle if (obj.tween and obj._isTweening) then transition.cancel(obj.tween) obj._isTweening = false obj.tween = nil --print ("toggleObject: CANCELLED TRANSITION") end if (obj.alpha == 0 or (obj.alpha > 0 and obj.tweenDirection == "going") ) then -- Fade in --print ("toggleObject: fade In") obj.isVisible = true obj.tween = transition.to( obj, { time=fxTime, alpha=opacity, onComplete=transitionComplete } ) if (obj.tweenDirection) then --print ("Fade in because we were : "..obj.tweenDirection) end obj.tweenDirection = "coming" else -- Fade out obj.tween = transition.to( obj, { time=fxTime, alpha=0, onComplete=transitionComplete } ) --print ("toggleObject: fade Out") if (obj.tweenDirection) then --print ("Fade out because we are : "..obj.tweenDirection) end obj.tweenDirection = "going" end --print ("obj alpha = "..obj.alpha) --print ("obj.tweenDirection: "..obj.tweenDirection) obj._isTweening = true --print "------------- END" end ------------------------------------------------- -- Hide an object, transitioning between a given alpha, and zero. local function hideObject(obj, fxTime, opacity, onComplete) fxTime = tonumber(fxTime) opacity = tonumber(opacity) if (not obj or type(obj) ~= "table") then print ("ERROR! : funx.hideObject : the object is missing, perhaps display object was removed but table not nil'ed?") return false end if (not obj.alpha) then obj.alpha = 0 end -- Actual alpha of a display object is not exact local currentAlpha = math.ceil(obj.alpha * 100)/100 -- be sure these properties exist obj.tween = obj.tween or {} if (obj._isTweening == nil) then obj._isTweening = false end local function transitionComplete(obj) if (not obj) then print ("scripts.funx.hideObject:transitionComplete: WARNING: object is gone!") return false end local currentAlpha = math.ceil(obj.alpha * 100)/100 if (currentAlpha == 0) then obj.isVisible = false else obj.isVisible = true end obj._isTweening = false obj.tweenDirection = nil if (onComplete) then onComplete() end end -- Cancel transition if caught in the middle if (obj.tween and obj._isTweening) then transition.cancel(obj.tween) obj._isTweening = false obj.tween = nil --print ("toggleObject: CANCELLED TRANSITION") end -- Fade out obj.tween = transition.to( obj, { time=fxTime, alpha=0, onComplete=transitionComplete } ) --print ("toggleObject: fade Out") if (obj.tweenDirection) then --print ("Fade out because we are : "..obj.tweenDirection) end obj.tweenDirection = "going" obj._isTweening = true end -- returns true/false depending whether value is a percent local function isPercent (x) local v,s = match(x, "(%d+)(%%)$") if (s == "%") then return true else return false end end -- Return x%, e.g. 10% returns .10 local function percent (x) local v = match(x, "(%d+)%%$") if v then v = v / 100 end return v end local function applyPercentIfSet(x,y,noRound) if (x ~= nil) then return applyPercent (x,y,noRound) else return nil end end ---------- -- Find new width/height to margins within an x,y -- x,y default to the screen -- fit: true/false, where true = fill -- Return ration r, the amount to use for rescaling, e.g. obj:scale(r,r) -- To fit into the screen, just call ratioToFitMargins (obj.w, obj.h) local function ratioToFitMargins (w,h, fill, t,b,l,r, x,y) local x = x or screenW local y = y or screenH t = t or 0 b = b or 0 l = l or 0 r = r or 0 -- Space to fit into local ww = x - l - r local hh = y - t - b -- Ratios to fit local wr = ww/w local hr = hh/h -- default is fit, i.e. not fill local cond = (wr >= hr) if (not fill) then cond = (wr < hr) end if (cond) then r = wr else r = hr end return r end ---------- -- Reduce an element if necessary so it fits -- with margins insdie of an space of xMax by yMax. -- xMax,yMax default to the screen -- DEFAULT: do not resize larger! -- RETURNS THE RATIO for scaling. Why? Because it seems there's a bug in Corona -- that means rescaling inside of this function screws up positioning. local function scaleObjectToMargins (obj, t,b,l,r, xMax,yMax, reduceOnly) local ratio if (reduceOnly == nil) then reduceOnly = true end xMax = xMax or 0 yMax = yMax or 0 if (xMax <= 0) then xMax = screenW end if (yMax <= 0) then yMax = screenH end local w = obj.contentWidth local h = obj.contentHeight if reduceOnly then if (w < screenW and h < screenH) then return 1 end end local ww = xMax - l - r local hh = yMax - t - b --print (xMax,l,r,ww) --print (yMax,t,b,hh) local wr = ww/w local hr = hh/h if (wr < hr) then ratio = wr else ratio = hr end return ratio --if (ratio ~= 1) then -- obj:scale(ratio,ratio) --end --print ("ratio", ratio, obj.contentWidth, obj.contentHeight) end ------- -- getFinalSizes -- Return the final width/height based on the original width/height and new values. -- The new values are w,h. They could be percentages, and if only one is present, the other is the same. -- If the Proportional flag is true, then if both width and height -- are set, resize proportionally to fit INSIDE of width/height -- EXAMPLE: -- w,h = maxWidth, maxHeight -- pic = loadImageFile(filename) -- pic.width, pic.height = funx.getFinalSizes (w,h, pic.width, pic.height, true) local function getFinalSizes (w,h, originalW, originalH, p) local wPercent, hPercent if p == nil then p = true end w = tonumber(w) h = tonumber(h) originalW = tonumber(originalW) originalH = tonumber(originalH) if (w and not h) then if (isPercent(w)) then h = applyPercent(w,originalH) w = applyPercent(w,originalW) else h = originalH * (w/originalW) end elseif (h and not w) then if (isPercent(h)) then w = applyPercent(h,originalW) h = applyPercent(h,originalH) else w = originalW * (h/originalH) end elseif (h and w) then if (p) then local doScaleW = (originalH/h) <= (originalW/w) if (doScaleW) then w = applyPercent(w, originalW) h = originalH * (w/originalW) else h = applyPercent(h, originalH) w = originalW * (h/originalH) end else h = applyPercent(h, originalH) w = applyPercent(w, originalW) end else w = originalW h = originalH end return w,h end ------- -- ScaleObjToSize -- Scale an object to width/height settings. -- The new values are w,h. They could be percentages, and if only one is present, the other is the same. local function ScaleObjToSize (obj, w,h) local wPercent, hPercent local originalW = obj.contentWidth local originalH = obj.contentHeight if (w and not h) then if (isPercent(w)) then h = applyPercent(w,originalH) w = applyPercent(w,originalW) else h = originalH * (w/originalW) end elseif (h and not w) then if (isPercent(h)) then w = applyPercent(h,originalW) h = applyPercent(h,originalH) else w = originalW * (h/originalH) end elseif (h and w) then h = applyPercent(h, originalH) w = applyPercent(w, originalW) else w = originalW h = originalH end local ratio = w/originalW obj:scale(ratio,ratio) end local function AddCommas( number, maxPos ) local s = tostring( number ) local len = strlen( s ) if len > maxPos then -- Add comma to the string local s2 = substring( s, -maxPos ) local s1 = substring( s, 1, len - maxPos ) s = (s1 .. "," .. s2) end maxPos = maxPos - 3 -- next comma position if maxPos > 0 then return AddCommas( s, maxPos ) else return s end end local function lines(str) local t = {} local function helper(line) table.insert(t, line) return "" end helper((str:gsub("(.-)\r?\n", helper))) return t end -- Load a file into a variable local function readFile(filename) local filePath = system.pathForFile( filename, system.ResourceDirectory ) local hFile,err = io.open(filePath,"r"); if (not err) then local contents = hFile:read("*a"); io.close(hFile); return contents,nil; else return nil,err; end end ---------------- -- buildTextDisplayObjectFromTemplate -- Build a display object using a template and a table -- Each line of the template is settings for text the display object -- Each line is comma separated, starting with the name of the field in the obj to use local function buildTextDisplayObjectsFromTemplate (template, obj) -- split the template local objs = {} for i,line in pairs(lines(trim(template))) do --print ("Line : "..line) local params = split (line, ",") local name = params[1] --print (name) -- Set the text and size local t = "BLANK" if obj then local t = obj[name] --print ("OBJ.NAME = " .. t) end local o = display.newText(t, 0, 0, native.systemFontBold, params[4]) -- color o:setFillColor(0, 0, 0) -- Set the coordinates o.x = params[2] o.y = params[3] -- opacity o.alpha = 1.0 objs[name] = o --print ("Params for "..name..":") dumptable(params) end return objs end -------------------------------------------------------- -- local function stripCommandLinesFromText(text) local substring = substring local cleanText = "" for line in gmatch(text, "[^\n]+") do line = trim(line) if (substring(line,1,3) ~= "###") then cleanText = cleanText .. "\n" .. line end end return cleanText end -- Text styles used by autoWrappedText --local textStyles = {} -------------------------------------------------------- -- Styles for autoWrappedText, below. -- Styles are simply the formatting lines, ### set, .... -- We pass a table of styles: -- styles = { stylename = stylestring, ... } local function loadTextStyles(filename, path) if (filename) then path = path or system.DocumentsDirectory local filePath = system.pathForFile( filename, path ) if (not filePath) then print ("WARNING: missing file ",filename) return {} end local textStyles = loadTableFromFile(filePath, "\n") -- split sub-arrays (rows) into tables local t = {} if (textStyles) then for n,v in pairs(textStyles) do if (type(v) ~= "table") then v = "set,"..v -- Record both Mixed Case and lowercase versions of the key -- to be sure we can find it. t[lower(n)] = split(v, ",", true) t[n] = split(v, ",", true) end end else t = {} end return t else return {} end end --[[ local function getTextStyles () return textStyles or {} end ]] --[[ local function setTextStyles (t) textStyles = t or {} for n,v in pairs(textStyles) do if (type(v) ~= "table") then v = "set,"..v textStyles[n] = split(v, ",", true) end end end ]] -- Get an adjustment for a font, to position it closer to its real baseline -- Assume x-height is about 60% of the font height. local function getXHeightAdjustment (font,size) local c = "X" local t = display.newText(c,0,0,font,size) local h = t.height display.remove(t) t=nil local adj = h * 0.6 --print ("getXHeightAdjustment of '"..c.."' "..font.." at size "..size.." is "..xHeight..", ratio", r) return adj end -- Testing function to show a line and insert into group g local function showTestBox (g,x,y,len, font,size,lineHeight,fontMetrics) local fontInfo = fontMetrics.getMetrics(font) local baseline = fontInfo.baseline local yAdjustment = lineHeight -- + (-baseline * size) len = len or 100 local b = display.newRect(g, x, y, x+len, y+yAdjustment) anchor(b, "TopLeft") b.x = x b.y = y b:setFillColor(0,0,250, 0.3) print ("showTestLine: lineheight:",lineHeight) end -- Testing function to show a line and insert into group g local function showTestLine (g,x,y,t,leading) y = floor(y) leading = leading or 0 local len = 100 local b = display.newLine(g, x, y, x+len, y) b:setStrokeColor(0,0,100,0.9) local t = display.newText(g, "y="..y..":"..", "..leading..": "..t,x,y,"Georgia-Italic",9) t:setFillColor(0,0,0) end -------------------------------------------------------- -- Wrap text to a width -- Blank lines are ignored. -- -- Very important: -- text: a table of named parameters OR the text. -- -- *** To show a blank line, put a space on it. -- The minCharCount is the number of chars to assume are in the line, which means -- fewer calculations to figure out first line's. -- It starts at 25, about 5 words or so, which is probabaly fine in 99% of the cases. -- You can raise lower this for very narrow columns. -- opacity : 0.0-1.0 -- "minWordLen" is the shortest word a line can end with, usually 2, i.e, don't end with single letter words. -- NOTE: the "floor" is crucial in the y-position of the lines. If they are not integer values, the text blurs! -- -- Look for CR codes. Since clumsy XML, such as that from inDesign, cannot include line breaks, -- we have to allow for a special code for line breaks: [[[cr]]] -------------------------------------------------------- local function autoWrappedText ( p ) local textwrap = require ("scripts.textrender.textrender") return textwrap.autoWrappedText( p ) end local function capitalize(str) local function tchelper(first, rest) return first:upper()..rest:lower() end -- Add extra characters to the pattern if you need to. _ and ' are -- found in the middle of identifiers and English words. -- We must also put %w_' into [%w_'] to make it handle normal stuff -- and extra stuff the same. -- This also turns hex numbers into, eg. 0Xa7d4 str = str:gsub("(%a)([%w_']*)", tchelper) return str end -------------------------------------------------------- -- Adjust x,y for a shadow thickness. -- If an object has a drop shadow, the corner of the object will be inside the shadow area. -- So, to position the object properly at x,y we need to find the x,y that includes the shadowing. -- Scale doesn't seem to work right, so ignore it, and it will be 1, which is OK. -------------------------------------------------------- local function adjustXYforShadow (x, y, rp, shadowOffset, scale) local stringFind = find if (shadowOffset) then local shadowOffsetX = 0 local shadowOffsetY = 0 local offsetX, offsetY scale = scale or 1 --print ("a) adjustXYforShadow", x, y, rp) rp = rp:lower() -- Horizontal offsets if (stringFind(rp, "left")) then shadowOffsetX = shadowOffset elseif (stringFind(rp, "right")) then shadowOffsetX = (-1*shadowOffset) else offsetX = 0 end -- Vertical offsets if (stringFind(rp, "top")) then shadowOffsetY = shadowOffset elseif (stringFind(rp, "bottom")) then shadowOffsetY = (-1*shadowOffset) else offsetY = 0 end x = x or 0 y = y or 0 x = floor((x + shadowOffsetX) * scale) y = floor((y + shadowOffsetY) * scale) --print ("b) adjustXYforShadow adjustedment:", x, y, scale) end return x,y end -------------------------------------------------------- -- referenceAdjustedXY -- Calculate the x,y of an object when offset by a new reference point -- but without resetting the reference point of the object. -- This allow the user to spec the position of an object with x,y and -- a reference alignement, e.g. BottomRight. We do the calculations -- to correct the x,y so the object is correctly positioned, based on the -- the provided newReferencePoint (e.g. center). -------------------------------------------------------- local function referenceAdjustedXY (obj, x, y, newReferencePoint, scale, shadowOffset) local stringFind = find local rx, ry, rp, offsetX, offsetY rx = obj.xReference ry = obj.yReference if (obj and newReferencePoint) then scale = scale or 1 shadowOffset = shadowOffset or 0 local w = obj.width local h = obj.height --print ("a) referenceAdjustedXY adjustedment: x, y, newReferencePoint, scale, shadowOffset", x, y, newReferencePoint, scale, shadowOffset) rp = newReferencePoint:lower() -- Horizontal offsets if (stringFind(rp, "left")) then offsetX = w/2 - shadowOffset elseif (stringFind(rp, "right")) then offsetX = (w/-2) + shadowOffset else offsetX = 0 end -- Vertical offsets if (stringFind(rp, "top")) then offsetY = h/2 - shadowOffset elseif (stringFind(rp, "bottom")) then offsetY = (h/-2) + shadowOffset else offsetY = 0 end --x = floor( (x + offsetX) * scale) --y = floor( (y + offsetY) * scale) if (x == "center") then x = midscreenX elseif (x == "left") then x = 0 elseif (x == "right") then x = screenW end if (y == "center") then y = midscreenY elseif (y == "top") then y = 0 elseif (y == "bottom") then y = screenH end x = floor( x + (offsetX * scale)) y = floor( y + (offsetY * scale)) --print ("b) referenceAdjustedXY adjustedment:", x, y, scale, shadowOffset) end return x,y end local function fixCapsForReferencePoint(r) if (r) then r = tostring(r) r = r:gsub("top", "Top") r = r:gsub("bottom", "Bottom") r = r:gsub("left", "Left") r = r:gsub("right", "Right") r = r:gsub("center", "Center") end return r end --------------- -- positionObject -- Given user settings for x,y, return the real x,y in the space of width x height -- margins = {top,bottom,left,right} margins/padding -- x can be left, center, right, a number, or a percent -- y can be top, center, bottom, a number, or a percent -- ref is the reference point, used like this: display[ref] -- Example: x,y = positionObject("left", "center", screenW, screenH) -- *** This is based on 0,0 being the center of the space defined by w x h *** -- Default w,h is the screen. local function positionObject(x,y,w,h,margins) w = w or screenW h = h or screenH --x = funx.applyPercent(x,w) or 0 --y = funx.applyPercent(y,h) or 0 margins = margins or {top=0, bottom=0,left=0,right=0} local xpos, ypos -- Horizontal offsets if (x == "left") then xpos = w/-2 + margins.left elseif (x == "right") then xpos = (w/2) - margins.right elseif (x == "center") then xpos = 0 else xpos = applyPercent(x,w) or 0 end -- Vertical offsets if (y == "top") then ypos = h/-2 + margins.top elseif (y == "bottom") then ypos = (h/2) - margins.bottom elseif (y == "center") then ypos = 0 else ypos = applyPercent(y,h) or 0 end return xpos, ypos end --===== --- Make a margins table from a string, order is T/L/B/R, e.g. "10,20,40,20" local function stringToMarginsTable(str, default) local m default = default or {0,0,0,0} if (type(default) == "string") then m = split ( (str or default), ",") elseif (not str or str == "") then m = split ( default, ",") else m = split ( str, ",") end local margins = { top=applyPercent(m[1], screenH), left=applyPercent(m[2], screenW), bottom=applyPercent(m[3], screenH), right=applyPercent(m[4], screenW), } return margins end --------------- -- positionObjectAroundCenter -- Given user settings for x,y, return the real x,y in the space of width x height -- margins = {top,bottom,left,right} margins/padding -- x can be left, center, right, a number, or a percent -- y can be top, center, bottom, a number, or a percent -- ref is the reference point, used like this: display[ref] -- Example: x,y = positionObject("left", "center", screenW, screenH) -- *** This is based on 0,0 being the center of the space defined by w x h *** -- Default w,h is the screen. local function positionObjectAroundCenter(x,y,w,h,margins) w = w or screenW h = h or screenH --x = applyPercent(x,w) or 0 --y = applyPercent(y,h) or 0 margins = margins or {top=0, bottom=0,left=0,right=0} -- Horizontal offsets local xpos, ypos if (x == "left") then xpos = w/-2 + margins.left elseif (x == "right") then xpos = (w/2) - margins.right elseif (x == "center") then xpos = 0 else xpos = applyPercent(x,w) or 0 end -- Vertical offsets if (y == "top") then ypos = h/-2 + margins.top elseif (y == "bottom") then ypos = (h/2) - margins.bottom elseif (y == "center") then ypos = 0 else ypos = applyPercent(y,h) or 0 end return xpos, ypos end --------------- -- positionObjectWithReferencePoint -- Given user settings for x,y, return the real x,y in the space of width x height -- margins = {top,bottom,left,right} margins/padding -- x can be left, center, right, a number, or a percent -- y can be top, center, bottom, a number, or a percent -- ref is the reference point, used like this: display[ref] -- Example: x,y = positionObject("left", "center", screenW, screenH) -- This is based on 0,0 being the center of the space defined by w x h -- Default w,h is the screen. -- refPointSimpleText=true means do NOT return "ReferencePoint" with the position text, -- i.e. instead of "TopLeftReferencePoint" just return "TopLeft" -- Default is FALSE -- -- WHY BE BASED ON THE CENTER OF THE PARENT OBJECT? -- The reason we want to position based on center of the space provided is that we -- can easily center objects that way. -- Also, we can easily position something inside another group this way. If you have a -- picture inside a box, this function returns its proper position in the box, so you -- only need to set the x,y. local function positionObjectWithReferencePoint(x,y,w,h,margins, absoluteflag, refPointSimpleText) local xpos, ypos w = w or screenW h = h or screenH absoluteflag = absoluteflag or false if (not margins or absoluteflag) then margins = {left = 0, right=0, top=0, bottom=0 } end local xref = "Left" local yref = "Top" if (type(x) == "string") then x = lower(x) end if (type(y) == "string") then y = lower(y) end -- Horizontal offsets if (x == "left") then xpos = w/-2 + margins.left xref = "Left" elseif (x == "right") then xpos = (w/2) - margins.right xref = "Right" elseif (x == "center") then xpos = 0 xref = "Center" else x = applyPercent(x,w) or 0 xpos = x - (w/2) + margins.left xref = "Left" end -- Vertical offsets if (y == "top") then ypos = h/-2 + margins.top elseif (y == "bottom") then ypos = (h/2) - margins.bottom yref = "Bottom" elseif (y == "center") then ypos = 0 yref = "Center" else y = applyPercent(y,h) or 0 ypos = y - (h/2) + margins.top yref = "Top" end -- avoid "CenterCenter"... if (xref == "Center" and yref == "Center") then yref="" end --print (xpos, ypos, yref..xref.."ReferencePoint") if (refPointSimpleText) then return xpos, ypos, yref..xref else return xpos, ypos, yref..xref.."ReferencePoint" end end local function setAnchorFromReferencePoint(obj, pos) pos = lower(pos) if pos == "topleftreferencepoint" then obj.anchorX, obj.anchorY = 0, 0 elseif pos == "topcenterreferencepoint" then obj.anchorX, obj.anchorY = 0.5, 0 elseif pos == "toprightreferencepoint" then obj.anchorX, obj.anchorY = 1, 0 elseif pos == "centerleftreferencepoint" then obj.anchorX, obj.anchorY = 0, 0.5 elseif pos == "centerreferencepoint" then obj.anchorX, obj.anchorY = 0.5, 0.5 elseif pos == "centerrightreferencepoint" then obj.anchorX, obj.anchorY = 1, 0.5 elseif pos == "bottomleftreferencepoint" then obj.anchorX, obj.anchorY = 0, 1 elseif pos == "bottomcenterreferencepoint" then obj.anchorX, obj.anchorY = 0.5, 1 elseif pos == "bottomrightreferencepoint" then obj.anchorX, obj.anchorY = 1, 1 else obj.anchorX, obj.anchorY = 0.5, 0.5 end end local function convertAnchorToReferencePointName (obj) local post = "" if ( {obj.anchorX, obj.anchorY} == {0, 0} ) then post = "TopLeftReferencePoint" elseif ( {obj.anchorX, obj.anchorY} == {0.5, 0} ) then post = "TopCenterReferencePoint" elseif ( {obj.anchorX, obj.anchorY} == {1, 0} ) then post = "TopRightReferencePoint" elseif ( {obj.anchorX, obj.anchorY} == {0, 0.5} ) then post = "CenterLeftReferencePoint" elseif ( {obj.anchorX, obj.anchorY} == {0.5, 0.5} ) then post = "CenterReferencePoint" elseif ( {obj.anchorX, obj.anchorY} == {1, 0.5} ) then post = "CenterRightReferencePoint" elseif ( {obj.anchorX, obj.anchorY} == {0.5, 1} ) then post = "BottomCenterReferencePoint" elseif ( {obj.anchorX, obj.anchorY} == {1, 1} ) then post = "BottomRightReferencePoint" end return post end ------------------------------------------------------- -- Reanchor to new point -- This version of reanchoring adjusts the x,y of an object for a new anchor point, using -- anchorX and anchorY local function reanchor(obj, ax, ay) local dx, dy = obj.anchorX - ax, obj.anchorY - ay local newX = obj.x - (dx * obj.width) local newY = obj.y - (dy * obj.height) obj.anchorX, obj.anchorY = ax, ay obj.x = newX obj.y = newY end -- Keep an object in the same place on screen while changing its anchor point. -- This is useful if an object is positioned Top Left (0,0), then we want to change the -- anchor point but not change the objects position on screen. local function reanchorToCenter (obj, a, x, y) if not a then return x,y; end if (lower(a) == "centerreferencepoint") then return x,y end -- old anchor values, and x,y local oaX, oaY = obj.anchorX, obj.anchorY -- x = x or obj.x -- y = y or obj.y -- a is a table, then it is an anchor point, else it is the name of a reference point -- if (type(a) == "table") then -- obj.anchorX, obj.anchorY = a.x, a.y -- else -- setAnchorFromReferencePoint(obj, a) -- end -- new anchor values local naX, naY = 0.5, 0.5 -- -- -- Get width/height local ac = obj.anchorChildren obj.anchorChildren = true local width, height = obj.width, obj.height obj.anchorChildren = ac -- distance from top-left local deltaX = (naX * width) - (oaX * width) local deltaY = (naY * height) - (oaY * height) local x = x + deltaX local y = y + deltaY return x,y end ---------------------------------------------------------------------- -- Picture Corners -- Given a width/height, build picture corners to fit. -- filenames are of each corner -- offsets specify positioning correction -- 0,0 of the corners is the CENTER! local function buildPictureCorners (w,h, filenames, offsets) local g = display.newGroup() local imageTL = display.newImage(g, filenames.TL) local imageTR = display.newImage(g, filenames.TR) local imageBL = display.newImage(g, filenames.BL) local imageBR = display.newImage(g, filenames.BR) anchor(imageTL, "TopLeft") imageTL.x = floor(0 + offsets.TLx - w/2); imageTL.y = floor(0 + offsets.TLy - h/2); anchor(imageTR, "TopRight") imageTR.x = ceil(w/2 + offsets.TRx); imageTR.y = floor(-h/2 + offsets.TRy); anchor(imageBL, "BottomLeft") imageBL.x = floor(-w/2 + offsets.BLx); imageBL.y = ceil(h/2 + offsets.BLy); anchor(imageBR, "BottomRight") imageBR.x = ceil(w/2 + offsets.BRx); imageBR.y = ceil(h/2 + offsets.BRy); return g end ---------------------------------------------------------------------- ---------------------------------------------------------------------- -- TESTING TOOLS: -- Print local vs. stage coordinates by touching an object. local function showContentToLocal(obj, state) local function showCoordinates( event ) -- Get x, y of touch event in content coordinates local contentx, contenty = event.x, event.y -- Convert to local coordinates of local localx, localy = event.target:contentToLocal(contentx, contenty) -- Display content and local coordinate values print ("showContentToLocal (content=>local): ", contentx..", "..contenty, "=>", floor(localx) ..", ".. floor(localy), ":", obj.localX ) return true end if (state == "toggle") then state = not obj._showContentToLocal end if (state) then print ("showContentToLocal: on") obj:addEventListener("touch", showCoordinates) obj._showContentToLocal = true else print ("showContentToLocal: off") obj:removeEventListener("touch", showCoordinates) obj._showContentToLocal = false end end ------------------------------------------------------------ ------------------------------------------------------------ -- Alert the user that something significant has happened by flashing the screen to white. local function flashscreen(t,a) t = t or 100 a = a or 0.5 local r = display.newRect(0,0,screenW,screenH) anchorZero(r, "TopLeft") r.alpha = 0 local function removeFlasher() r:removeSelf() r = nil end local function fadeOutAgain() transition.to(r, { alpha = 0, time=t, onComplete=removeFlasher } ) end -- Fade In the white screen transition.to(r, { alpha = a, time=t, onComplete = fadeOutAgain } ) end ------------------------------------------------------------ ------------------------------------------------------------ -- Use the file suffix to determine a file type, -- e.g. xxx.m4a is sound, m4v is video, jpg is image -- We only handle really common formats that iOS likes, so -- don't expect to handle everything. And, mp4 could be either, -- so I'm using audio for it. -- Return FALSE if the type is unknown -- NOTE: we're checking for 3 letter suffixes, so .html will mess up...use ".htm" local function mediaFileType(f) local suffix = substring(f, strlen(f)-3, -1) local t = { jpg="image", png="image", mov="video", m4v="video", m4a="audio", mp4="audio", mp3="audio", aac="audio", wav="audio", txt="text", htm="html", } if (suffix) then return t[suffix] else return false end end ----------- -- Make a directory to hold something new -- Use a handy prefix for future selecting of the type of dir, -- e.g. all "o_..." dirs -- dirname: path INSIDE the system.DocumentsDirecotyr (or systemdir) -- unique: if the directory exists, make a unique version -- systemdir: Default to the system.DocumentsDirectory local function mkdir (dirname, prefix, unique, systemdir) local systemdir = systemdir or system.DocumentsDirectory if (prefix == nil) then prefix = "o_" end -- Use a unique-ish file name if necessary local mydirname = dirname or os.time() .. "_" ..os.clock() local temp_path = system.pathForFile( mydirname, systemdir ) if (unique) then -- Does the path already exist? If so, modify to be sure it is unique while ( lfs.chdir( temp_path ) ) do mydirname = dirname .. "_" .. os.time() .. "_" ..os.clock() temp_path = system.pathForFile( mydirname, systemdir ) end elseif (lfs.chdir( temp_path )) then -- we're done, return the name of the directory return mydirname end -- Change to documents directory --local temp_path = system.pathForFile( "", system.TemporaryDirectory ) local temp_path = system.pathForFile( "", systemdir ) -- change current working directory local success = lfs.chdir( temp_path ) -- returns true on success local new_folder_path if success then lfs.mkdir( mydirname ) new_folder_path = lfs.currentdir() .. "/"..mydirname return mydirname else return false end end ------------------------------------------------------------ ------------------------------------------------------------ -- Make cover up bars for differenly shaped screens -- Color is a color string "R,G,B" local function coverUpScreenEdges(color) color = color or "0,0,0" --color = "200,30,30" local c = stringToColorTable(color) -- Put cover-up bars for a different screen shape. local deviceWidth = round(( display.contentWidth - (display.screenOriginX * 2) ) / display.contentScaleX) local deviceHeight = round(( display.contentHeight - (display.screenOriginY * 2) ) / display.contentScaleY) local actualWidth = deviceWidth * display.contentScaleX local actualHeight = deviceHeight * display.contentScaleY -- Don't make bars if no need for them if (screenW == actualWidth and screenH == actualHeight) then return false end local coverup = display.newGroup() local barWidth = (actualWidth - screenW)/2 local barL = display.newRect(coverup, 0,0,barWidth,screenH) local barR = display.newRect(coverup, 0,0,barWidth,screenH) barL:setFillColor(c[1],c[2], c[3]) barR:setFillColor(c[1],c[2], c[3]) anchor(barL, "TopLeft") anchor(barR, "TopLeft") barL.x = -barWidth barL.y = 0 barR.x = screenW barR.y = 0 --[[ local o = system.orientation if ( o == "portrait" or o == "portraitUpsideDown" ) then coverup.rotation = 90 end --]] return coverup end ------------------------------------------------- ------------------------------------------------- -- Special Strokes around objects -- Designed to go behind an image, not in front. -- params may include: -- stroke width (stroke) -- params MUST tell us what kind of object, e.g. "rectangle", etc. -- Styles: -- solid : a stroke 100% outside the image (not like a Corona stroke that is on the edge) -- thin-thick : 25% inner stroke, 50% out, with 25% padding -- thick-thin : 50% inner stroke, 25% out, with 25% padding -- The matte color is for a matte around the image. The tintColor is laid over the group, tinting it. --[[ @param obj A display group to frame @param params A table, params = { stroke = integer, style = solid | thick-thin | thin-thick, color = RGBAColorString, matteColor = RGBAColorString, tintColor = RGBAColorString, matte = integer, } --]] local function strokeGroupObject(obj,params) local floor = floor local function framingObject(o, padding, fillcolor, strokeWidth, strokeColor) local dup = display.newRect(0,0,o.contentWidth+(2*padding), o.contentHeight+(2*padding)) dup:setFillColor(fillcolor[1], fillcolor[2], fillcolor[3], fillcolor[4]) dup.strokeWidth = strokeWidth dup:setStrokeColor(strokeColor[1], strokeColor[2], strokeColor[3], strokeColor[4]) return dup end -- Default is transparent fill for stroking boxes local color = stringToColorTable(params.color or "0,0,0") local tintColor = stringToColorTable(params.tintColor or "0,0,0,0") local mattecolor = stringToColorTable(params.matteColor or "255,255,255,100%") params.stroke = params.stroke or 0 params.matte = params.matte or 0 -- The frame local temp -- FRAME local f = display.newGroup() --f.anchorChildren = true local w,h = obj.contentWidth, obj.contentHeight params.style = lower(params.style) if ( params.style == "solid") then local fr = display.newRect(f, 0,0, w + params.stroke, h + params.stroke) fr.strokeWidth = params.stroke or 0 fr:setStrokeColor(color[1], color[2], color[3], color[4]) if (mattecolor) then fr:setFillColor(mattecolor[1], mattecolor[2], mattecolor[3], mattecolor[4]) end elseif (params.style == "thick-thin") then local sw = params.stroke or 0 local innerW = floor(sw * 0.5) or 1 local outerW = floor(sw * 0.25) or 1 local padding = (sw-(innerW + outerW)) or 1 local innerFrame = display.newRect(f, 0,0, w + innerW - 1, h + innerW - 1 ) innerFrame.strokeWidth = innerW innerFrame:setStrokeColor(color[1], color[2], color[3], color[4]) if (mattecolor) then innerFrame:setFillColor(mattecolor[1], mattecolor[2], mattecolor[3], mattecolor[4]) end local outerOffset = innerW + padding + outerW/2 local outerFrame = display.newRect(f, 0,0, w - 1 + 2*outerOffset, h - 1 + 2*outerOffset) outerFrame.strokeWidth = outerW outerFrame:setStrokeColor(color[1], color[2], color[3], color[4]) outerFrame:setFillColor(255) outerFrame:toBack() elseif (params.style == "thin-thick") then local sw = params.stroke or 0 local innerW = floor(sw * 0.25) or 1 local outerW = floor(sw * 0.5) or 1 local padding = (sw-(innerW + outerW)) or 1 local innerFrame = display.newRect(f, 0,0, w + innerW, h + innerW ) innerFrame.strokeWidth = innerW innerFrame:setStrokeColor(color[1], color[2], color[3], color[4]) if (mattecolor) then innerFrame:setFillColor(mattecolor[1], mattecolor[2], mattecolor[3], mattecolor[4]) end local outerOffset = innerW + padding + outerW/2 local outerFrame = display.newRect(f, 0,0, w + 2*outerOffset, h + 2*outerOffset) outerFrame.strokeWidth = outerW outerFrame:setStrokeColor(color[1], color[2], color[3], color[4]) outerFrame:setFillColor(255) outerFrame:toBack() end temp = obj.anchorChildren obj.anchorChildren = true obj:insert(f) f:toBack() obj.anchorChildren = temp return f end ------------------------------------------------- -- Convert "left", "center", "right" to numerics or percentages local function positionByName(t, margins, absoluteflag) if (not margins or absoluteflag) then margins = {left = 0, right=0, top=0, bottom=0 } end local v = "" if (t == "left" ) then v = margins.left elseif (t == "top") then v = margins.top elseif (t == "center") then v = "50%" elseif (t == "bottom") then v = margins.bottom elseif (t == "right") then v = margins.right else v = t end return v end ------------------------------------------------- -- cleanPath: clean up a path local function cleanPath (p) if (p) then local substring = substring p = p:gsub("/\./","/") p = p:gsub("//","/") p = p:gsub("/\.$","") return p end end ------------------------------------------------- -- joinAsPath: make a path from different elements of a table. -- Useful to join pieces together, e.g. server + path + filename -- If username/password are passed, add them to the URL, e.g. username:password@restofurl local function joinAsPath( pieces, username, password) trim(pieces) for i = #pieces, 1, -1 do if (pieces[i] == nil or pieces[i] == "") then table.remove(pieces, i) end end local path = cleanPath(table.concat(pieces, "/")) local pre = table.concat({username,password},":") if (pre ~= "") then path = pre .. "@" .. path end return path end ------------------------------------------------- -- Pure Lua version of dirname. -- local function dirname(path) while true do if path == "" or substring(path, -1) == "/" or -- find(path, "^/\..") or -- substring(path, -2) == "/." or substring(path, -3) == "/.." or (substring(path, -1) == "." and strlen(path) == 1) or (substring(path, -2) == ".." and strlen(path) == 2) then break end path = substring(path, 1, -2) end if path == "" then path = "." end if substring(path, -1) ~= "/" then path = path .. "/" end return path end ------------------------------------------------- -- basename() -- Returns trailing name component of path -- Extract my/dir/bottomdir => bottomdir local function basename (path) path = gsub(path, "%/$", "") path = "/"..path local d = gsub(path, "^.*/","") return d end ------------------------------------------------- -- Copy File (binary copy) -- This is a binary file copy local function copyFile (src, srcPath, srcBaseDir, target, targetBaseDir) local size = 2^13 local sourcePath = system.pathForFile( nil, srcBaseDir ) .. "/"..srcPath.."/"..src local targetPath = system.pathForFile( nil, targetBaseDir ) .. "/"..target.."/"..src local f = assert(io.open(sourcePath, "rb")) local out = assert(io.open(targetPath, "wb")) while true do local block = f:read(size) if not block then break end out:write(block) end assert(f:close()) assert(out:close()) end ------------------------------------------------- -- Copy a directory -- Create a copy of the directory 'src' inside of the directory 'target' local function copyDir (src, srcBaseDir, target, targetBaseDir, newname) srcBaseDir = srcBaseDir or system.CachesDirectory targetBaseDir = targetBaseDir or system.CachesDirectory local srcBaseName = basename(src.."/") newname = newname or srcBaseName -- make a dir inside the target container directory, -- e.g. make "mydir" inside "mytarget" to get "mytarget/mydir" local sbase = system.pathForFile( nil, srcBaseDir ) local tbase = system.pathForFile( nil, targetBaseDir ) local targetPath = tbase .. "/" .. target .. "/" --print ("copyDir:",sbase, targetPath) local res, err = lfs.chdir(targetPath) if (not res) then print ("ERROR: copyDir tried to change directories to "..targetPath.." but failed: "..err) return false else res, err = lfs.mkdir( newname ) end --if (err) then print (err) end local s = src local t = target local srcPath = sbase .. "/" .. src local res = lfs.chdir (srcPath) local allowDotFiles = false if (res) then local filename for filename in lfs.dir(srcPath) do local res = lfs.chdir (srcPath) if (res and allowDotFiles or substring(filename, 1, 1) ~= ".") then if (filename ~= "." and filename ~= ".." ) then local attr = lfs.attributes (filename) if (attr.mode == "directory") then -- make dir in new location copyDir (s.."/"..filename, srcBaseDir, t.."/"..newname, targetBaseDir) else -- copy a file copyFile (filename, s, srcBaseDir, t.."/"..newname, targetBaseDir) end end end end end end ------------------------------------------------- -- Delete a directory even if not empty -- If keepDir is true, then only delete the contents local function rmDir(dir,path, keepDir) path = path or system.DocumentsDirectory local doc_path = system.pathForFile( dir, path ) local res = lfs.chdir (doc_path) if (res) then for filename in lfs.dir(doc_path) do if (filename ~= "." and filename ~= ".." ) then lfs.chdir (doc_path) local attr = lfs.attributes (filename) if (attr.mode == "directory") then rmDir(dir.."/"..filename, path) else lfs.chdir (doc_path) local results, reason = os.remove(doc_path .. "/" .. filename, system.DocumentsDirectory) end end end if (not keepDir) then local results, reason = os.remove(doc_path) end end end ----------- -- Make a directory Tree -- If we ask for "dirA/dirB/dirC", we might need to create dirA and dirB before creating -- dirC. local function mkdirTree (dirname, systemdir) systemdir = systemdir or system.CachesDirectory dirname = cleanPath(dirname) local dirs = split(dirname,"/") local nextDir local currDir = "" for i=1,#dirs do local nextDir = currDir.."/"..dirs[i] local fullpath = system.pathForFile( nextDir, systemdir ) if (fullpath and lfs.chdir( fullpath ) ) then currDir = nextDir else local success = lfs.chdir( system.pathForFile( currDir, systemdir ) ) if (success) then local success = lfs.mkdir( dirs[i] ) if (success) then currDir = nextDir else print ("ERROR: mkdirTree: Cannot create directory: "..nextDir) end else print ("ERROR: mkdirTree: Cannot find directory: "..currDir) end end end end local function url_decode(str) str = gsub (str, "+", " ") str = gsub (str, "%%(%x%x)", function(h) return char(tonumber(h,16)) end) str = gsub (str, "\r\n", "\n") return str end local function url_encode(str) if (str) then str = gsub (str, "\n", "\r\n") str = gsub (str, "([^%w ])", function (c) return format ("%%%02X", string.byte(c)) end) str = gsub (str, " ", "+") end return str end local function newArc(x,y,w,h,s,e) local xc,yc,cos,sin = x+w/2,y+h/2,math.cos,math.sin s,e = s or 0, e or 360 s,e = math.rad(s),math.rad(e) w,h = w/2,h/2 local l = display.newLine(0,0,0,0) for t=s,e,0.02 do l:append(xc + w*cos(t), yc - h*sin(t)) end return l end -- Call like this: setFillColorFromString(obj, "10,20,30,30%") -- All values can be number or percent local function setFillColorFromString(obj, cstring) local s = stringToColorTable(cstring) if (obj.setFillColor) then obj:setFillColor(s[1], s[2], s[3], s[4]) else obj:setFillColor(s[1], s[2], s[3], s[4]) end end local function getDeviceMetrics( ) -- See: http://en.wikipedia.org/wiki/List_of_displays_by_pixel_density local corona_width = -display.screenOriginX * 2 + display.contentWidth local corona_height = -display.screenOriginY * 2 + display.contentHeight --print("Corona unit width: " .. corona_width .. ", height: " .. corona_height) -- I was rounding these, on the theory that they would always round to the correct integer pixel -- size, but I noticed that in practice it rounded to an incorrect size sometimes, so I think it's -- better to use the computed fractional values instead of possibly introducing more error. -- local pixel_width = corona_width / display.contentScaleX local pixel_height = corona_height / display.contentScaleY --print("Pixel width: " .. pixel_width .. ", height: " .. pixel_height) local model = system.getInfo("model") local default_device = { model = model, inchesDiagonal = 4.0, } -- Approximation (assumes average sized phone) local devices = { { model = "iPhone", inchesDiagonal = 3.5, }, { model = "iPad", inchesDiagonal = 9.7, }, { model = "iPod touch", inchesDiagonal = 3.5, }, { model = "Nexus One", inchesDiagonal = 3.7, }, { model = "Nexus S", inchesDiagonal = 4.0, }, -- Unverified model value { model = "Droid", inchesDiagonal = 3.7, }, { model = "Droid X", inchesDiagonal = 4.3, }, -- Unverified model value { model = "Galaxy Tab", inchesDiagonal = 7.0, }, { model = "Galaxy Tab X", inchesDiagonal = 10.1, }, -- Unverified model value { model = "Kindle Fire", inchesDiagonal = 7.0, }, { model = "Nook Color", inchesDiagonal = 7.0, }, } local device = default_device for _, deviceEntry in pairs(devices) do if deviceEntry.model == model then device = deviceEntry end end -- Pixel width, height, and pixels per inch device.pixelWidth = pixel_width device.pixelHeight = pixel_height device.ppi = math.sqrt((pixel_width^2) + (pixel_height^2)) / device.inchesDiagonal -- Corona unit width, height, and "Corona units per inch" device.coronaWidth = corona_width device.coronaHeight = corona_height device.cpi = math.sqrt(corona_width^2 + corona_height^2)/device.inchesDiagonal --print("Device: " .. device.model .. ", size: " .. device.inchesDiagonal .. " inches, ppi: " .. device.ppi .. ", cpi: " .. device.cpi) return device end -- This makes a mask for a widget.scrollView local function makeMask(width, height, maskDirectory) -- Display.save uses the screen size, so a retina will save a double-size image than what we need maskDirectory = maskDirectory or "_masks" local baseDir = system.CachesDirectory local maskfilename = maskDirectory .. "/" .. "mask-"..width.."-"..height..".jpg" if (not fileExists(maskfilename, baseDir) ) then mkdirTree (maskDirectory, baseDir) local g = display.newGroup() local scalingRatio = scaleFactorForRetina() width = width * scalingRatio height = height * scalingRatio local mask = display.newRect(g, 0,0,width+4, height+4 ) mask:setFillColor(0) local opening = display.newRect(g, 0,0,width, height ) opening:setFillColor(255) anchor(opening, "TopLeft") opening.x = 2 opening.y = 2 display.save( g, maskfilename, baseDir ) g:removeSelf() end return maskfilename end -- This makes a mask for a rectangle on the screen at a particular x,y local function makeMaskForRect(x,y,width, height, maskDirectory, maskfilename, baseDir) -- Display.save uses the screen size, so a retina will save a double-size image than what we need x = math.max(x,0) y = math.max(y,0) maskDirectory = maskDirectory or "_masks" maskfilename = maskfilename or "mask-" .. width .. "x" .. height .. "@" .. x .. "," .. y .. "-" ..screenW.."x"..screenH..".png" local baseDir = baseDir or system.CachesDirectory local maskfilename = maskDirectory .. "/" .. maskfilename if (not fileExists(maskfilename, baseDir) ) then mkdirTree (maskDirectory, baseDir) local g = display.newGroup() -- Mask sizing. Needs min. 3px on each side, must be divisible by 4 local bw = math.max(display.contentWidth, 4*math.ceil((width+6)/4) ) local bh = math.max(display.contentHeight, 4*math.ceil((height+6)/4) ) if (bw > display.contentWidth or bh > display.contentHeight) then print ("ERROR: funx.makeMaskForRect: Cannot create a mask larger than the display. This mask won't work.") end local scalingRatio = scaleFactorForRetina() bw = bw * scalingRatio bh = bh * scalingRatio width = width * scalingRatio height = height * scalingRatio -- black background. local mask = display.newRect(g, 0,0, bw, bh ) mask:setFillColor(0) anchor(mask, "TopLeft") -- opening local opening = display.newRect(g, 0,0,width, height ) opening:setFillColor(255) anchor(opening, "TopLeft") opening.x = x + 3 opening.y = y + 3 display.save( g, maskfilename, baseDir ) g:removeSelf() end return maskfilename end -- This requires a generic mask file!!!! --- Masking using a single mask file, from the Corona SDK forum -- @params (table) object = object to mask, width/height = of mask, --[[ local OPTIONS_LIST_HEIGHT = 300 local OPTIONS_LIST_HEIGHT = 200 local thingToMask = somedisplayobject applyMask({ object = thingToMask, width = OPTIONS_LIST_WIDTH, height = OPTIONS_LIST_HEIGHT }) --]] local function applyMask(params) local GENERIC_MASK_FILE = "_ui/generic-mask-1024x768.png" local generic_mask_width = 1024 local generic_mask_height = 768 if params.object == nil then return end if params.width == nil then params.width = params.object.width end if params.height == nil then params.height = params.object.height end if params.mask == nil then params.mask = "_ui/generic-mask-1024x768.png" end local myMask = graphics.newMask(params.mask) params.object:setMask(myMask) params.object.maskScaleX = params.width/generic_mask_width params.object.maskScaleY = params.height/generic_mask_height --there may be a need in the future add logic to the positioning for different reference points params.object.maskX = 0 --params.width/2 params.object.maskY = 0 --params.height/2 end -- DOES NOT WORK local function translateHTMLEntity(s) local _ENTITIES = { ["&lt;"] = "<", ["&gt;"] = ">", ["&amp;"] = "&", ["&quot;"] = '"', ["&apos;"] = "'", ["&bull;"] = char(149), ["&dash;"] = char(150), ["&mdash;"] = char(151), ["&#(%d+);"] = function (x) local d = tonumber(x) if d >= 0 and d < 256 then return char(d) else return "&#"..d..";" end end, ["&#x(%x+);"] = function (x) local d = tonumber(x,16) if d >= 0 and d < 256 then return char(d) else return "&#x"..x..";" end end, } -- Replace the entities found in s for k,v in pairs(_ENTITIES) do --print (k, v) s = gsub(s,k,v) end return s end local function checksum(str) local temp = 0 local weight = 10 for i = 1, strlen(str) do local c = str:byte(i,i) temp = temp + c * weight weight = weight - 1 end --[[ temp = 11 - (temp % 11) if temp == 10 then return "X" else if temp == 11 then return "0" else return tostring(temp) end end --]] return temp end -- Get status bar height. -- Problem is, if the bar is hidden, the height is zero local function getStatusBarHeight() local t = display.topStatusBarContentHeight if (t == 0) then display.setStatusBar( display.DefaultStatusBar ) t = display.topStatusBarContentHeight display.setStatusBar( display.HiddenStatusBar ) end return t end ----------------------------------- -- Clear all contents of the directory local function deleteDirectoryContents(dir, whichSystemDirectory) whichSystemDirectory = whichSystemDirectory or system.CachesDirectory rmDir(dir, whichSystemDirectory, true) --print ("deleteDirectoryContents", dir) end --- Get a random set from a table -- Check the validity of each key, does it exist in the db param? -- The db should be { key1 = value, key2 = value, ...} -- @param src table = { key1, key2, ... } -- @param n number of elements of src to use -- @param db key-value table to check for validity -- @param indexOrdered (Boolean) If true, index result using ordered numbers not source keys. If indexed by keys, the result will be a key/value set using keys from src. Otherwise, result will be indexed numerically, starting at 1. local function getRandomSet(src, n, db, indexOrdered) local keys = {} local i = 1 for k,v in pairs(src) do if ( (not db) or db[v]) then keys[i] = {key=k,val=v} i=i+1 end end local set = {} n = min(n, #keys) for i = 1,n do local k = random(#keys) if (indexOrdered) then set[#set+1] = keys[k].val else set[ keys[k].key ] = keys[k].val end table.remove(keys,k) end return set end local function getFirstElement(t) local res for i,j in pairs (t) do res = {i,j} break end return res[1], res[2] end -- ==================================================================== -- Check multiple paths for a file -- Used to look for book files in multiple places, hierarchically, -- e.g. look first in _user/books/ then on shelves -- Default with no values is to return the default book. -- @param locations Table: { 1 = { path = "path/to/book/folders", bookDir = "bookfolder", systemDirectory = system.ResourceDirectory }, ... } -- Example: -- findFile ( "book.xml", "_user/books" , "_user" ) -- ==================================================================== local function findFile (filename, locations, default) default = default or "_user" if (not filename or not locations or type(locations) ~= "table") then return { path = default, systemDirectory = system.ResourceDirectory } end local p for i,loc in pairs(locations) do if (loc.bookDir == "default" or loc.bookDir == "" ) then return default, system.ResourceDirectory end --print ("Look for ", joinAsPath{loc.path, loc.bookDir, filename} ) if ( fileExists( joinAsPath{loc.path, loc.bookDir, filename}, loc.systemDirectory) ) then --print ("Found ", filename, "in", loc.path .. loc.bookDir) return loc.path, loc.systemDirectory else --print ("NOT FOUND AT ", joinAsPath{loc.path, loc.bookDir, filename}) end end return false end -- ==================================================================== -- Set case of some text using CSS case names, --none No capitalization. The text renders as it is. This is default --capitalize Transforms the first character of each word to uppercase --uppercase Transforms all characters to uppercase --lowercase Transforms all characters to lowercase --initial Sets this property to its default value. Read about initial --inherit Inherits this property from its parent element. -- -- Synonyms : title, normal -- ==================================================================== local function setCase(case, str) if case and case ~= "" and case ~= "none" then case = lower(trim(case)) if (case == "lowercase") then str = lower(str) elseif (case == "uppercase") then str = upper(str) elseif (case == "capitalize" or case == "title") then -- turns out we added this earlier to FUNX str = capitalize(str) end end return str end ------------------------------------------------------------ ------------------------------------------------------------ -- Alert the user that something significant has happened by flashing an object function FUNX.flashObject(obj, t, a) if (obj._flashObject == true) then return end obj._flashObject = true t = t or 100 a = a or 0.5 obj._originalAlpha = obj.alpha local function removeFlasher() obj._originalAlpha = nil obj._flashObject = nil end local function fadeOutAgain() transition.to(obj, { alpha = obj._originalAlpha, time=t, onComplete=removeFlasher } ) end -- Fade In the white screen transition.to(obj, { alpha = a, time = t, onComplete = fadeOutAgain } ) end -- ==================================================================== -- Tables of values -- ==================================================================== FUNX.hardwareInfo = hardwareInfo -- ==================================================================== -- Register new functions here -- ==================================================================== FUNX.activityIndicator = activityIndicator FUNX.activityIndicatorOff = activityIndicatorOff FUNX.activityIndicatorOn = activityIndicatorOn FUNX.AddCommas = AddCommas FUNX.addPosRect = addPosRect FUNX.adjustXYforShadow = adjustXYforShadow --FUNX.anchorBottomLeftZero = anchorBottomLeftZero --FUNX.anchorBottomLeft = anchorBottomLeft --FUNX.anchorBottomRightZero = anchorBottomRightZero --FUNX.anchorBottomRight = anchorBottomRight --FUNX.anchorBottomCenterZero = anchorBottomCenterZero --FUNX.anchorBottomCenter = anchorBottomCenter -- --FUNX.anchorCenter = anchorCenter --FUNX.anchorCenterZero = anchorCenterZero -- --FUNX.anchorTopCenter = anchorTopCenter --FUNX.anchorTopCenterZero = anchorTopCenterZero --FUNX.anchorTopLeft = anchorTopLeft --FUNX.anchorTopLeftZero = anchorTopLeftZero --FUNX.anchorTopRight = anchorTopRight --FUNX.anchorTopRightZero = anchorTopRightZero FUNX.anchor = anchor FUNX.anchorZero = anchorZero FUNX.applyMask = applyMask FUNX.applyPercent = applyPercent FUNX.applyPercentIfSet = applyPercentIfSet FUNX.autoWrappedText = autoWrappedText FUNX.basename = basename FUNX.buildPictureCorners = buildPictureCorners FUNX.buildShadow = buildShadow --FUNX.buildShadowObj = buildShadowObj FUNX.buildTextDisplayObjectsFromTemplate = buildTextDisplayObjectsFromTemplate FUNX.callClean = callClean FUNX.canConnectWithServer = canConnectWithServer FUNX.capitalize = capitalize FUNX.centerInParent = centerInParent FUNX.checkScale = checkScale FUNX.checksum = checksum FUNX.cleanGroups = cleanGroups FUNX.cleanPath = cleanPath FUNX.copyDir = copyDir FUNX.copyFile = copyFile FUNX.coverUpScreenEdges = coverUpScreenEdges FUNX.crypt = crypt FUNX.datetime_to_unix_time = datetime_to_unix_time FUNX.deleteDirectoryContents = deleteDirectoryContents FUNX.dimScreen = dimScreen FUNX.dirname = dirname FUNX.newArc = newArc FUNX.dump = dumptable FUNX.escape = escape FUNX.fadeIn = fadeIn FUNX.fadeOut = fadeOut FUNX.fileExists = fileExists FUNX.findFile = findFile FUNX.fixCapsForReferencePoint = fixCapsForReferencePoint FUNX.flashscreen = flashscreen FUNX.formatDate = formatDate FUNX.frameGroup = frameGroup FUNX.get_date_parts = get_date_parts FUNX.getday_posfix = getday_posfix FUNX.getDeviceMetrics = getDeviceMetrics FUNX.getDisplayObjectParams = getDisplayObjectParams FUNX.getElementName = getElementName FUNX.getEscapedKeysForGsub = getEscapedKeysForGsub FUNX.getFinalSizes = getFinalSizes FUNX.getFirstElement = getFirstElement FUNX.getImageSize = getImageSize FUNX.getmonth = getmonth FUNX.getRandomSet = getRandomSet FUNX.getScaledFilename = getScaledFilename FUNX.getStatusBarHeight = getStatusBarHeight --FUNX.getTextStyles = getTextStyles FUNX.getValue = getValue FUNX.getXHeightAdjustment = getXHeightAdjustment FUNX.hasFieldCodes = hasFieldCodes FUNX.hasFieldCodesSingle = hasFieldCodesSingle FUNX.hasNetConnection = hasNetConnection FUNX.hideObject = hideObject FUNX.indexOfSystemDirectory = indexOfSystemDirectory FUNX.initSystemEventHandler = initSystemEventHandler FUNX.inTable = inTable FUNX.isPercent = isPercent FUNX.isTable = isTable FUNX.joinAsPath = joinAsPath FUNX.keysExistInTable = keysExistInTable FUNX.lazyLoad = lazyLoad FUNX.lines = lines FUNX.loadData = loadData FUNX.readFile = readFile FUNX.loadImageFile = loadImageFile FUNX.loadTable = loadTable FUNX.loadTableFromFile = loadTableFromFile FUNX.loadTextStyles = loadTextStyles FUNX.ltrim = ltrim FUNX.makeMask = makeMask FUNX.makeMaskForRect = makeMaskForRect FUNX.mediaFileType = mediaFileType FUNX.mkdir = mkdir FUNX.mkdirTree = mkdirTree FUNX.OLD_substitutionsSLOWER = OLD_substitutionsSLOWER FUNX.openURLWithConfirm = openURLWithConfirm FUNX.pairsByKeys = pairsByKeys FUNX.percent = percent FUNX.percentOfScreenHeight = percentOfScreenHeight FUNX.percentOfScreenWidth = percentOfScreenWidth FUNX.popup = popup FUNX.popupDisplayGroup = popupDisplayGroup FUNX.popupWebpage = popupWebpage FUNX.positionByName = positionByName FUNX.positionObject = positionObject FUNX.positionObjectAroundCenter = positionObjectAroundCenter FUNX.positionObjectWithReferencePoint = positionObjectWithReferencePoint FUNX.setAnchorFromReferencePoint = setAnchorFromReferencePoint FUNX.convertAnchorToReferencePointName = convertAnchorToReferencePointName FUNX.reanchor = reanchor FUNX.reanchorToCenter = reanchorToCenter FUNX.printFuncName = printFuncName FUNX.ratioToFitMargins = ratioToFitMargins FUNX.referenceAdjustedXY = referenceAdjustedXY FUNX.removeFields = removeFields FUNX.removeFieldsSingle = removeFieldsSingle FUNX.removeFromTable = removeFromTable FUNX.replaceWildcard = replaceWildcard FUNX.rescaleFromIpad = rescaleFromIpad FUNX.resizeFromIpad = resizeFromIpad FUNX.rmDir = rmDir FUNX.round = round FUNX.round2 = round2 FUNX.rtrim = rtrim FUNX.saveData = saveData FUNX.saveTable = saveTable FUNX.saveTableToFile = saveTableToFile FUNX.scaleFactorForRetina = scaleFactorForRetina FUNX.scaleObjectToMargins = scaleObjectToMargins FUNX.ScaleObjToSize = ScaleObjToSize FUNX.setCase = setCase FUNX.setFillColorFromString = setFillColorFromString --FUNX.setTextStyles = setTextStyles FUNX.showContentToLocal = showContentToLocal FUNX.showTestBox = showTestBox FUNX.showTestLine = showTestLine FUNX.shrinkAway = shrinkAway FUNX.spinner = spinner FUNX.spinner = spinner FUNX.split = split FUNX.stringToColorTable = stringToColorTable FUNX.stringToColorTableHDR = stringToColorTableHDR FUNX.stringToMarginsTable = stringToMarginsTable FUNX.stripCommandLinesFromText = stripCommandLinesFromText FUNX.strokeGroupObject = strokeGroupObject FUNX.flattenTable = flattenTable FUNX.substitutions = substitutions FUNX.table_multi_sort = table_multi_sort FUNX.table_sort = table_sort FUNX.tableConvertValuesToKeys = tableConvertValuesToKeys FUNX.tableCopy = tableCopy FUNX.tableIsEmpty = tableIsEmpty FUNX.tablelength = tablelength FUNX.tableMerge = tableMerge FUNX.tableRemoveUnusedCodedElements = tableRemoveUnusedCodedElements FUNX.tableSubstitutions = tableSubstitutions FUNX.tellUser = tellUser FUNX.timePassed = timePassed FUNX.toggleObject = toggleObject FUNX.toZero = toZero FUNX.traceback = traceback FUNX.translateHTMLEntity = translateHTMLEntity FUNX.trim = trim FUNX.undimScreen = undimScreen FUNX.unescape = unescape FUNX.unloadModule = unloadModule FUNX.url_decode = url_decode FUNX.url_encode = url_encode FUNX.verifyNetConnectionOrQuit = verifyNetConnectionOrQuit FUNX.zSort = zSort return FUNX
mit
mimetic/DIG-corona-library
examples/textrender/scripts/funx.lua
4
145657
-- funx.lua -- -- Version 2.0 -- -- Copyright (C) 2014 David I. Gross. All Rights Reserved. -- --[[ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] -- -- =================== -- USEFUL FUNCTIONS. -- =================== local FUNX = {} local pathToFunxFolder = "scripts/funx/" local dotPathToFunxFolder = "scripts.funx." -- Requires json library local json = require ( "json" ) local lfs = require ( "lfs" ) local widget = require ("widget") -- Used by tellUser...the handler for the timed message local timedMessage = nil local timedMessageList = {} -- Make a local copy of the application settings global local screenW, screenH = display.contentWidth, display.contentHeight local viewableScreenW, viewableScreenH = display.viewableContentWidth, display.viewableContentHeight local midscreenX = screenW*(0.5) local midscreenY = screenH*(0.5) -- functions local floor = math.floor local ceil = math.ceil local min = math.min local max = math.max local random = math.random local char = string.char local byte = string.byte local match = string.match local gmatch = string.gmatch local find = string.find local gsub = string.gsub local substring = string.sub local gfind = string.gfind local lower = string.lower local upper = string.upper local strlen = string.len local format = string.format -- ALPHA VALUES, can change for RGB or HDR systems local OPAQUE = 255 local TRANSPARENT = 0 -- ------------------------------------------------------------- -- HARDWARE SETTINGS -- This exposes the system hardware settings to FUNX. -- Easy to find out what kind of device, for example. -- ------------------------------------------------------------- hardwareInfo = {} hardwareInfo.isApple = false hardwareInfo.isAndroid = false hardwareInfo.isGoogle = false hardwareInfo.isKindleFire = false hardwareInfo.isNook = false hardwareInfo.is_iPad = false hardwareInfo.isTall = false hardwareInfo.isSimulator = false local model = system.getInfo("model") -- Are we on the simulator? if "simulator" == system.getInfo("environment") then hardwareInfo.isSimulator = true end -- lets see if we are a tall device hardwareInfo.isTall = false if (display.pixelHeight/display.pixelWidth) > 1.5 then hardwareInfo.isTall = true end -- first, look to see if we are on some Apple platform. -- All models start with iP, so we can check that. if string.sub(model,1,2) == "iP" then -- We are an iOS device of some sort hardwareInfo.isApple = true if string.sub(model, 1, 4) == "iPad" then hardwareInfo.is_iPad = true end else -- Not Apple, then we must be one of the Android devices hardwareInfo.isAndroid = true -- lets assume we are Google for the moment hardwareInfo.isGoogle = true -- All the Kindles start with K, though Corona SDK before build 976's Kindle Fire 9 returned "WFJWI" instead of "KFJWI" if model == "Kindle Fire" or model == "WFJWI" or string.sub(model,1,2) == "KF" then hardwareInfo.isKindleFire = true hardwareInfo.isGoogle = false end -- Are we a nook? if string.sub(model,1,4) == "Nook" or string.sub(model,1,4) == "BNRV" then hardwareInfo.isNook = true hardwareInfo.isGoogle = false end end -- ------------------------------------------------------------- -- Problem is, if this goes to quickly, you'll still get non-random numbers, -- and I've found some lines execute so fast the local function uniqueID() -- Initialize the pseudo random number generator math.randomseed( os.clock() + system.getTimer() ) math.random(); math.random(); math.random() return math.random() end ----------- -- Shortcut to set x,y to 0,0 local function toZero(o) o.x, o.y = 0,0 end -- ------------------------------------------------------------- -- GRAPHICS 2.0 POSITIONING -- ------------------------------------------------------------ local function anchor(obj, pos) if (not obj) then return; end if pos == "TopLeft" then obj.anchorX, obj.anchorY = 0, 0 elseif pos == "TopCenter" then obj.anchorX, obj.anchorY = 0.5, 0 elseif pos == "TopRight" then obj.anchorX, obj.anchorY = 1, 0 elseif pos == "CenterLeft" then obj.anchorX, obj.anchorY = 0, 0.5 elseif pos == "Center" then obj.anchorX, obj.anchorY = 0.5, 0.5 elseif pos == "CenterRight" then obj.anchorX, obj.anchorY = 1, 0.5 elseif pos == "BottomLeft" then obj.anchorX, obj.anchorY = 0, 1 elseif pos == "BottomCenter" then obj.anchorX, obj.anchorY = 0.5, 1 elseif pos == "BottomRight" then obj.anchorX, obj.anchorY = 1, 1 elseif pos == "Left" then obj.anchorX = 0 elseif pos == "Right" then obj.anchorX = 1 elseif pos == "Top" then obj.anchorY = 0 elseif pos == "Bottom" then obj.anchorY = 1 elseif pos == "TopLeftReferencePoint" then obj.anchorX, obj.anchorY = 0, 0 elseif pos == "TopCenterReferencePoint" then obj.anchorX, obj.anchorY = 0.5, 0 elseif pos == "TopRightReferencePoint" then obj.anchorX, obj.anchorY = 1, 0 elseif pos == "CenterLeftReferencePoint" then obj.anchorX, obj.anchorY = 0, 0.5 elseif pos == "CenterReferencePoint" then obj.anchorX, obj.anchorY = 0.5, 0.5 elseif pos == "CenterRightReferencePoint" then obj.anchorX, obj.anchorY = 1, 0.5 elseif pos == "BottomLeftReferencePoint" then obj.anchorX, obj.anchorY = 0, 1 elseif pos == "BottomCenterReferencePoint" then obj.anchorX, obj.anchorY = 0.5, 1 elseif pos == "BottomRightReferencePoint" then obj.anchorX, obj.anchorY = 1, 1 else obj.anchorX, obj.anchorY = 0.5, 0.5 end end local function anchorZero(obj,pos) if (not obj) then return; end anchor(obj, pos) obj.x, obj.y = 0,0 end -- Add an invisible positioning rectangle for a group -- @param g [group] Group into which we add a position rect at 0,0 -- @param vis [boolean] True = visible, False = hidden -- @param c [table] RGBa color table {r,g,b,a} local function addPosRect(g, vis, c ) local r = display.newRect(g, 0,0,10,10) r.isVisible = vis c = c or {250,0,0,100} r:setFillColor(unpack(c)) anchorZero(r, "TopLeft") return g end local function centerInParent(g) anchor(g, "Center") g.x = g.parent.width/2 g.y = g.parent.height/2 return g end -- ------------------------------------------------------------ -- Simple encrypt/decrypt --[[ EXAMPLE: local enc1 = {29, 58, 93, 28, 27}; local str = "This is an encrypted string."; local crypted = crypt(str,enc1) print("Encryption: " .. crypted); print("Decryption: " .. crypt(crypted,enc1,true)); --]] -- ------------------------------------------------------------ local function crypt(str,k,inv) local function convert( chars, dist, inv ) return string.char( ( string.byte( chars ) - 32 + ( inv and -dist or dist ) ) % 95 + 32 ) end local enc= ""; for i=1,#str do if(#str-k[5] >= i or not inv) then for inc=0,3 do if(i%4 == inc)then enc = enc .. convert(string.sub(str,i,i),k[inc+1],inv); break; end end end end if(not inv)then for i=1,k[5] do enc = enc .. string.char(math.random(32,126)); end end return enc; end -- ------------------------------------------------------------ -- Get the string index in system table of a system directory -- ------------------------------------------------------------ local function indexOfSystemDirectory( systemPath ) local i = "" if (systemPath == system.DocumentsDirectory) then i = "DocumentsDirectory" elseif (systemPath == system.ResourceDirectory) then i = "ResourceDirectory" elseif (systemPath == system.CachesDirectory) then i = "CachesDirectory" end return i end -- ------------------------------------------------------------ -- DEBUGGING Timer -- ------------------------------------------------------------ local firstTime = system.getTimer() local lastTimePassed = system.getTimer() local function timePassed(msg) local t2 = system.getTimer() local t = t2 - lastTimePassed lastTimePassed = t2 msg = msg or "" print ("funx.timePassed: ", floor(t) .. "ms", msg) --, "Total:", floor(t2-firstTime)) io.flush( ) end ----------------- -- 'n' is the call stack level to show -- '2' will show the calling function local function printFuncName(n) n = n or 2 local info = debug.getinfo(n, "Snl") if info.what == "C" then -- is a C function? print(n, "C function") else -- a Lua function print(format("[%s]:%d", info.name, info.currentline)) end end local function isTable(t) return (type(t) == "table") end ----------------- -- Traceback -- Writes a call stack, showing what called the current code. -- Hopefully. local function traceback () print ("FUNX.TRACEBACK:") local level = 1 while true do local info = debug.getinfo(level, "Sl") if not info then break end if info.what == "C" then -- is a C function? print(level, "C function") else -- a Lua function print(format("[%s]:%d", info.short_src, info.currentline)) end level = level + 1 end end ----------------- -- Fails for negatives, apparently local function round2(num, idp) local mult = 10^(idp or 0) return floor(num * mult + 0.5) / mult end local function round(num, idp) return tonumber(format("%." .. (idp or 0) .. "f", num)) end ----------------- -- Given a value from an XML element, it could be x=y or x.value=y -- Return y in either case. -- If asNil is true, then if the value is "" or nil, return nil local function getValue(x,asNil) local r if (type(x) == "table") then if (x.value) then r = x.value elseif (x.Attributes and x.Attributes.value) then r = x.Attributes.value elseif (x._attr and x._attr.value) then r = x._attr.value end else r = x end if (asNil and (r == "" or r == nil or r == false)) then r = nil end return r end -------------- -- unescape/escape a hex string local function unescape (s) if (not s) then return "" end s = gsub(s, "+", " ") s = gsub(s, "%%(%x%x)", function (h) return char(tonumber(h, 16)) end) return s end local function escape(s) s = gsub(s, "([&=+%c])", function(c)return format("%%%02X", byte(c))end) s = gsub(s, " ", "+") return s end --========= --- Remove a value from a table. The table is searched and the value removed from it. local function removeFromTable(t,obj) for i,o in pairs(t) do if (o == obj) then t[i] = nil print ("removeFromTable: removed item #" .. i) return true end end return false end ----------------- -- Table is empty? local function tableIsEmpty(t) if (t and type(t) == "table" ) then if (next(t) == nil) then return true end end return false end ----------------- -- Length of a table, i.e. number elements in it. local function tablelength (t) if (type(t) ~= "table") then return 0 end local count = 0 for _, _ in pairs(t) do count = count + 1 end return count end --=========== --- Escape keys in tables so the key name can be used in a gsub search/replace -- @param t Table with keys that might need escaping -- @return res Key:value pairs: original key => clean key -- e.g. { "icon-1" = "myicon.jpg" } ===> { "icon-1" = "icon%-1" } local function getEscapedKeysForGsub(t) -- Chars to escape: ( ) . % + - * ? [ ^ $ local res = {} for i,v in pairs(t) do res[i] = gsub(i, "([%(%)%.%%%+%-%*%?%[%^%$])", "%%%1") end return res end --- Flatten a table for substitutions -- Create a flat table from the prefs that can be used for word subsitutions in strings, -- e.g. Replacing name in "My {{name}}", where name is inside of a subtable such as "user". -- Seems like a waste of processing, but this way we can use hierarchical prefs, probably a good thing -- @flatPrefs [table] Used for recursion, so don't pass anything to it or it won't start with the PREFS.values table. local function flattenTable(t) local res = {} for k,v in pairs(t) do if (type(v) ~= "table") then -- Capture a non-table value res[k] = v else -- Flatten a subtable local subset = flattenTable(v) for ks,vs in pairs(subset) do res[k .. ":" .. ks] = vs end end end return res end --- Substitute for {{x}} with table.x from a table. -- There can be multiple fields in the string, s. -- Returns the string with the fields filled in. -- @param s String with codes to replace -- @param t Table of key:value pairs to use for replacement (search for key) -- @param escapeTheKeys if TRUE then escape the keys of the subsitutions table (t), if a table then use that table as the escaped keys table -- @return s string with replacements local function substitutions (s, t, escapeTheKeys) if (not s or not t or t=={}) then --print ("funx.substitutions: No Values passed!") return s end local tclean = {} if (escapeTheKeys) then if (type(escapeTheKeys) == "table") then tclean = escapeTheKeys else tclean = getEscapedKeysForGsub(t) end end local r = gfind(s,"%{%{(.-)%}%}") for wrd in r do local searchTerm = tclean[wrd] or wrd if (t[wrd]) then s = gsub(s, "{{"..searchTerm.."}}", tostring(t[wrd])) end end return s end -- Substitute for {x} with table.x from a table. -- There can be multiple fields in the string, s. -- Returns the string with the fields filled in. local function OLD_substitutionsSLOWER (s, t) if (not s or not t or t=={}) then --print ("funx.substitutions: No Values passed!") return s end --local r = gfind(s,"%b{}") local r = gfind(s,"%{%{.-%}%}") local res = s for wrd in r do local i,j = find(wrd, "%{%{(.-)%}%}") local k = sub(wrd,i+2,j-2) if (t[k]) then res = gsub(res, wrd, t[k]) end --print ("substitutions for in "..res.." for {{"..k.."}} with ",t[k], "RESULT:",res) end return res end --=========== --- Replace all substitutions in the entire table, including -- nested tables. -- @param t Table in which to substitute -- @param subs table Table of substitutions local function tableSubstitutions(t, subs, escapeTheKeys) if (type(t) ~= "table") then return t end if (type(subs) ~= "table" or not subs or subs == {} ) then return t end local tclean if (escapeTheKeys) then if (type(escapeTheKeys) == "table") then tclean = escapeTheKeys else tclean = getEscapedKeysForGsub(subs) end end for i,element in pairs(t) do if (i ~= "screen") then if (type(element) == "string") then t[i] = substitutions (element, subs, tclean) --print ("element:", element, t[i]) elseif (type(element) == "table") then tableSubstitutions( t[i], subs, tclean) elseif (element == "[[null]]" or element == "[[NULL]]" ) then t[i] = nil end end end end --=========== --- Remove elements that contain unresolved {{}} codes. -- @param t Table in which to substitute local function tableRemoveUnusedCodedElements(t ) if (type(t) ~= "table") then return t end for i,element in pairs(t) do if (i ~= "screen") then if (type(element) == "string" and find(element, "%{%{.-%}%}")) then --print ("tableRemoveUnusedCodedElements: Remove ", t[i]) t[i] = "" elseif (type(element) == "table") then tableRemoveUnusedCodedElements( t[i] ) end end end end -- hasFieldCodes(s) -- Return true/false if the string has field codes, i.e. {x} inside it local function hasFieldCodes(s) if (type(s) ~= "string") then return false end s = s or "" local r = find(s,"%{%{.-%}%}") if (r) then return true else return false end end -- hasFieldCodes(s) -- Return true/false if the string has field codes, i.e. {x} inside it local function hasFieldCodesSingle(s) if (type(s) ~= "string") then return false end s = s or "" local r = find(s,"%b{}") if (r) then return true else return false end end -- Get element name from string. -- If the string is {{xxx}} then the field name is "xxx" local function getElementName (s) local r = gfind(s,"%{%{(.-)%}%}") local res = "" for wrd in r do print ("extracted ",wrd) res = wrd break end return res end -- Dump an XML table local function dumptable(_class, no_func, depth, maxDepth, filter) -- = string.match("foo 123 bar", '%d%d%d') -- %d matches a digit local function passedFilter(t) if not filter then return true end return string.match(t, filter) end if (not _class) then print ("dumptable: not a class."); return; end if(depth==nil) then depth=0; end local str=""; for n=0,depth,1 do str=str.."\t"; end maxDepth = maxDepth or 3 if (depth > maxDepth) then print ("Oops, running away! Depth is "..depth) return end print (str.."["..type(_class).."]"); print (str.."{"); if (type(_class) == "table") then for i,field in pairs(_class) do if(type(field)=="table") then local fn = tostring(i) if (substring(fn,1,2) == "__") then print (str.."\t"..tostring(i).." = (not expanding this internal table)"); else print (str.."\t"..tostring(i).." ="); dumptable(field, no_func, depth+1, maxDepth, filter); end else if (passedFilter(i)) then if(type(field)=="number") then print (str.." [num]\t"..tostring(i).."="..field); elseif(type(field) == "string") then print (str.." [str]\t"..tostring(i).."=".."\""..field.."\""); elseif(type(field) == "boolean") then print (str.." [bool]\t"..tostring(i).."=".."\""..tostring(field).."\""); else if(not no_func)then if(type(field)=="function")then print (str.."\t"..tostring(i).."()"); else print (str.."\t"..tostring(i).."<userdata=["..type(field).."]>"); end end end end end end end print (str.."}"); end -------------------------------------------------------- -- tableCopy local function tableCopy(object) local lookup_table = {} local function _copy(object) if type(object) ~= "table" then return object elseif lookup_table[object] then return lookup_table[object] end local new_table = {} lookup_table[object] = new_table for index, value in pairs(object) do new_table[_copy(index)] = _copy(value) end return setmetatable(new_table, _copy(getmetatable(object))) end return _copy(object) end -------------------------------------------------------- -- Trim -- Remove white space from a string, OR table of strings -- recursively -- Only act on strings -- If flag set, return nil for an empty string local function trim(s, returnNil) if (s) then if (type(s) == "table") then for i,v in ipairs(s) do s[i] = trim(v, returnNil) end elseif (type(s) == "string") then s = s:gsub("^%s*(.-)%s*$", "%1") end end if (returnNil and s == "") then return nil end return s end -------------------------------------------------------- -- ltrim -- Remove white space from the start of a string, OR table of strings recursively -- Only act on strings -- If flag set, return nil for an empty string local function ltrim(s, returnNil) if (s) then if (type(s) == "table") then for i,v in ipairs(s) do s[i] = ltrim(v, returnNil) end elseif (type(s) == "string") then s = s:gsub("^%s*(.-)", "%1") end end if (returnNil and s == "") then return nil end return s end -------------------------------------------------------- -- rtrim -- Remove white space from the end of a string, OR table of strings recursively -- Only act on strings -- If flag set, return nil for an empty string local function rtrim(s, returnNil) if (s) then if (type(s) == "table") then for i,v in ipairs(s) do s[i] = rtrim(v, returnNil) end elseif (type(s) == "string") then s = s:gsub("(.-)%s*$", "%1") end end if (returnNil and s == "") then return nil end return s end -- Delete fields of the form {{x}} in the string s local function removeFields (s) if (not s) then return nil end local r = gfind(s,"%{%{.-%}%}") local res = s for wrd in r do res = trim(gsub(res, wrd, "")) end return res end -- Delete fields of the form {x} in the string s local function removeFieldsSingle (s) if (not s) then return nil end local r = gfind(s,"%b{}") local res = s for wrd in r do res = trim(gsub(res, wrd, "")) end return res end -------------------------------------------------------- -- table merge -- Overwrite elements in the first table with the second table! local function tableMerge(t1, t2) if (type(t1) ~= "table") then return t2 end if (type(t2) ~= "table") then return t1 end for k,v in pairs(t2) do if type(v) == "table" then if type(t1[k] or false) == "table" then tableMerge(t1[k] or {}, t2[k] or {}) else t1[k] = v end else t1[k] = v end end return t1 end local function split(str, pat, doTrim) pat = pat or "," if (not str) then return nil end str = tostring(str) local t = {} local fpat = "(.-)" .. pat local last_end = 1 local s, e, cap = str:find(fpat, 1) while s do if s ~= 1 or cap ~= "" then if doTrim then cap = trim(cap) end table.insert(t,cap) end last_end = e+1 s, e, cap = str:find(fpat, last_end) end if last_end <= #str then cap = str:sub(last_end) if doTrim then cap = trim(cap) end table.insert(t,cap) end return t end ------------------------------------------------- --- GET DEVICE SCALE FACTOR FOR RETINA RESIZING --1 = no need to change anything --2 = multiply by 2 -- examples: -- local scalingRatio = scaleFactorForRetina() -- local scalesuffix = "@"..scalingRatio.."x" -- -- local scalingRatio = 1/scaleFactorForRetina() -- width = width/scalingRatio -- height = height/scalingRatio ------------------------------------------------- local function scaleFactorForRetina() local deviceWidth = ( display.contentWidth - (display.screenOriginX * 2) ) / display.contentScaleX local scaleFactor = floor( deviceWidth / display.contentWidth ) return scaleFactor end ------------------------------------------------- -- CHECK IMAGE DIMENSION & SCALE ACCORDINGLY ------------------------------------------------- local function checkScale(p) if p.width > viewableScreenW or p.height > viewableScreenH then if p.width/viewableScreenW > p.height/viewableScreenH then p.xScale = viewableScreenW/p.width p.yScale = viewableScreenW/p.width else p.xScale = viewableScreenH/p.height p.yScale = viewableScreenH/p.height end end end ------------------------------------------------- -- RESCALE AN IMAGE THAT WAS DESIGNED FOR THE IPAD (1024X768) FOR THE CURRENT PLATFORM -- Assuming the graphic was made for a different platform -- this resizes it ------------------------------------------------- local function resizeFromIpad(p) local currentR = viewableScreenW/viewableScreenH local ipadR = 1024/768 local r if (currentR > ipadR) then -- use ration based on different heights r = viewableScreenH / 768 else r = viewableScreenW / 1024 end if (r ~= 1) then p:scale(r,r) --print ("Resize image by (viewableScreenW/1024) = "..r) end end ------------------------------------------------- -- RESCALE COORDINATES THAT WERE DESIGNED FOR THE IPAD (1024X768) FOR THE CURRENT PLATFORM -- Used to reposition coordinates that were set up for the iPad, e.g. x,y positions -- If the screen is a different shape, pad the x to make up for it -- iPad is 1024/768 = 133/100 (1.33) -- CONVERT results to integer (floor) local function rescaleFromIpad(x,y) -- Do nothing if this is an iPad screen! if ( (screenW == 1024 and screenH == 768) or (screenW == 768 and screenH == 1024) )then return x,y end if (x == nil) then return 0,0 end --print ("viewableScreenW="..viewableScreenW..", viewableScreenH="..viewableScreenH) local currentR = viewableScreenW/viewableScreenH local ipadR = 1024/768 local fixedH = 768 local fixedW = 1024 if (currentR > 1) then ipadR = 1/ipadR fixedH = 1024 fixedW = 768 end local r if (currentR > ipadR) then -- use ration based on different heights r = viewableScreenH / fixedH else r = viewableScreenW / fixedW end -- Pad for different shape local screenR = floor((viewableScreenW / viewableScreenH) * 100 )/100 local px = 0 --print ("screenR="..screenR) if (y and (screenR ~= floor((ipadR)*100)/100)) then px = floor((viewableScreenW - (viewableScreenH * ipadR))/2) end x = floor((x * r) + (px)) --print ("Padding x="..px) if (y ~= nil) then y = floor(y * r) return x,y else return x end end -- If the value is a percentage, multiply by the 2nd param, else return the 1st param -- value is rounded to nearest integer, UNLESS the 2nd param is less than 1 -- or noRound = true -- If x is nil, but y is not, then return the y (i.e. assume 100%) local function applyPercent (x,y,noRound) if (x == nil and y == nil) then return nil end if (x == nil and y ~= nil) then return tonumber(y) end x = x or 0 y = y or 0 local v = match(trim(x), "(.+)%%$") if v then v = (v / 100) * y if ((not noRound) and (y>1)) then v = floor(v+0.5) end else v = x end return tonumber(v) end -- =========== --- Get a percentage of the screen height -- @param y -- @param noRound If false, value NOT rounded to nearest integer local function percentOfScreenHeight (y,noRound) return applyPercent (y, screenH, noRound) end -- =========== --- Get a percentage of the screen height -- @param y -- @param noRound If false, value NOT rounded to nearest integer local function percentOfScreenWidth (x,noRound) return applyPercent (x, screenW, noRound) end -------------------------------------------------------- -- File Exists -- default directory is system.ResourceDirectory -- not system.DocumentsDirectory -------------------------------------------------------- local function fileExists(f,d) if (f) then d = d or system.ResourceDirectory local filePath = system.pathForFile( f, d ) local exists = false -- Determine if file exists if (filePath ~= nil) then local fileHandle = io.open( filePath, "r" ) if (fileHandle) then -- nil if no file found exists = true io.close(fileHandle) else --print ("WARNING: Missing file: ",tostring(filePath)) end end return (exists) else --print ("WARNING: Missing file: ",tostring(filePath)) return false end end ------------------------------------------------------------------------ -- Save table, load table, default from documents directory ------------------------------------------------------------------------ ---------------------- -- Save/load functions local function saveData(filePath, text) --local levelseq = table.concat( levelArray, "-" ) local file = io.open( filePath, "w" ) if (file) then file:write( text ) io.close( file ) return true else print ("Error: funx.saveData: Could not create file "..tostring(filePath)) return false end end local function loadData(filePath) local t = nil --local levelseq = table.concat( levelArray, "-" ) local file = io.open( filePath, "r" ) if (file) then t = file:read( "*a" ) io.close( file ) else print ("scripts.funx.loadData: No file found at "..tostring(filePath)) end return t end local function saveTableToFile(filePath, dataTable) --local levelseq = table.concat( levelArray, "-" ) local myfile = io.open( filePath, "w" ) for k,v in pairs( dataTable ) do myfile:write( k .. "=" .. v .. "," ) end io.close( myfile ) end -- Load a table form a text file. -- The table is stored as comma-separated name=value pairs. local function loadTableFromFile(filePath, s) local substring = substring if (not filePath) then print ("WARNING: loadTableFromFile: Missing file name.") return false end local file = io.open( filePath, "r" ) -- separator, default is comma s = s or "," if file then -- Read file contents into a string local dataStr = file:read( "*a" ) -- Break string into separate variables and construct new table from resulting data local datavars = split(dataStr, s) local dataTableNew = {} for i = 1, #datavars do local firstchar = substring(trim(datavars[i]),1,1) -- split each name/value pair if ( not ((firstchar == "#") or (firstchar == "/") or (firstchar == "-") ) ) then local onevalue = trim(split(datavars[i], "=")) if (onevalue[1]) then dataTableNew[onevalue[1]] = onevalue[2] end end end io.close( file ) -- important! -- Note: all values arrive as strings; cast to numbers where numbers are expected dataTableNew["randomValue"] = tonumber(dataTableNew["randomValue"]) return dataTableNew else print ("WARNING: loadTableFromFile: File not found ("..filePath..")") return false end end local function saveTable(t, filename, path) if (not t or not filename) then return true end path = path or system.DocumentsDirectory --print ("scripts.funx.saveTable: save to "..filename) local json = json.encode (t) local filePath = system.pathForFile( filename, path ) return saveData(filePath, json) end local function loadTable(filename, path) path = path or system.DocumentsDirectory if (fileExists(filename,path)) then local filePath = system.pathForFile( filename, path ) --print ("scripts.funx.loadTable: load from "..filePath) local t = {} local f = loadData(filePath) if (f and f ~= "") then t = json.decode(f) end --print ("loadTable: end") return t else return false end end ------------------------------------------------------------------------ -- Image loading ------------------------------------------------------------------------ local function getScaledFilename(filename, d) local scalingRatio = scaleFactorForRetina() if (scalingRatio <= 1) then return filename, scalingRatio else local scalesuffix = "@"..scalingRatio.."x" -- Is there an other sized version? local suffix = substring(filename, strlen(filename)-3, -1) local name = substring(filename, 1, strlen(filename)-4) local f2 = name .. scalesuffix .. suffix -- If no scaled file, get original if (fileExists(f2,d)) then filename = f2 return filename, scalingRatio else return filename, 1 end end end ---------------------------------------------------------------------- -- Get an image size (height, width) -- We need this to use it for display.newImageRect -- Let's keep a list of image sizes so we can avoid double-loading.align -- Every time we load, save the size to a list we maintain. ---------------------------------------------------------------------- -- Get an image size (height, width) -- We need this to use it for display.newImageRect -- Let's keep a list of image sizes so we can avoid double-loading.align -- Every time we load, save the size to a list we maintain. -- *** The first time, the list will be taken from the resources directory! local function getImageSize(f,d) d = d or system.ResourceDirectory local imageInfoList if (not FUNX.imageInfoList) then imageInfoList = loadTable("images_info.json", system.CachesDirectory) if (not imageInfoList) then imageInfoList = loadTable("_user/images_info.json", system.ResourceDirectory) or {} if (not imageInfoList) then print ("Warning: funx.getImageSize() : Could not find file, images_info.json") end end FUNX.imageInfoList = imageInfoList else imageInfoList = FUNX.imageInfoList end -- load info table, if not loaded if (not imageInfoList) then imageInfoList = loadTable("images_info.json", system.CachesDirectory) end -- Check the sizes list for this image if (imageInfoList[f]) then return imageInfoList[f].width, imageInfoList[f].height else -- add to the list local i = display.newImage(f,d,true) local w = i.contentWidth local h = i.contentHeight i:removeSelf() i = nil imageInfoList[f] = { width = w, height = h } saveTable(imageInfoList, "images_info.json", system.CachesDirectory) return w,h end end -------------------------------------------------------- -- An attempt to load images async, rather than force everything to wait. -- SO FAR, IT DOESN'T QUITE WORK! IMAGES GET LOADED, BUT DON'T -- END UP IN THE RIGHT PLACES. local function getDisplayObjectParams(i) -- Save the useful values from the target we are replacing local params = { alpha = i.alpha, height = i.height, isHitTestMasked = i.isHitTestMasked, isHitTestable = i.isHitTestable, isVisible = i.isVisible, maskRotation = i.maskRotation, maskScaleX = i.maskScaleX, maskScaleY = i.maskScaleY, maskX = i.maskX, maskY = i.maskY, parent = i.parent, rotation = i.rotation, width = i.width, xReference = i.xReference, x = i.x, xOrigin = i.xOrigin, xScale = i.xScale, yReference = i.yReference, y = i.y, yOrigin = i.yOrigin, yScale = i.yScale, } return params end local function lazyLoad(target,f,w,h) local params, g if (target) then params = getDisplayObjectParams(target) end local function loadImage() if (target) then if (target.parent) then g = target.parent end target:removeSelf() --target = nil else target = {} end target = display.newImageRect(f,w,h) if (g) then g:insert(target) end for i,j in pairs (params) do if (i ~= "width" and i ~= "height") then target[i] = j end end print ("Loaded"..f ) end timer.performWithDelay( 1000, loadImage ) end -------------------------------------------------------- -- Replace placeholder directory in path name with real value -- p : a single character placeholder, default is "*" -- v : the real value, e.g. "mypath" -- Any slashes must be in the original. -- Example: -- replaceWildcard ("*/images/pic.jpg", "mydir", "?") -------------------------------------------------------- local function replaceWildcard(text, v, p) --print ("scripts.funx.replaceWildcard", text, v, p) if (text and v) then p = p or "*" text = text:gsub("%"..p, v) end return text end -------------------------------------------------------- -- Load an image file. If it is not there, load a "missing image" file -- filename is a full pathname, e.g. images/in/my/folder/pic.jpg -- Default system directory is system.ResourceDirectory -- If filepath is set, replace "*" in the filename with the filepath. -- If no "*" in the filename, then the file MUST be a system file! -- If there is a "*" in the filename, the file MUST be a user file, found in the CachesDirectory. -- DEPRECATED: ALWAYS USE CORONA METHOD: method: true = use my method, false means use Corona method -------------------------------------------------------- local function loadImageFile(filename, wildcardPath, whichSystemDirectory, showTraceOnFailure) local scalingRatio = 1 local scaleFraction = 1 local scalesuffix = "" local otherFound = false if (_DEVELOPING) then showTraceOnFailure = true end if (filename) then wildcardPath = wildcardPath or "_user" -- If the filename starts with a wildcard, then replace it with the wildcardPath local wc = substring(filename,1,1) if (wc == "*" and wildcardPath) then filename = replaceWildcard(filename, wildcardPath) -- Files inside _user are system files, everything else with a wildcard is -- a downloaded book. if (not find(wildcardPath, "^_user") ) then --if (wildcardPath ~= "_user") then whichSystemDirectory = whichSystemDirectory or system.CachesDirectory else whichSystemDirectory = whichSystemDirectory or system.ResourceDirectory end end -- default to system for files, e.g. _ui/mygraphic.jpg whichSystemDirectory = whichSystemDirectory or system.ResourceDirectory -- ANDROID FIX -- To allow images inside folders, we can add ".txt" to the image -- frg 2016-01-23 -- added check for existence of file and then adding .txt to extension -- to try again. On Android devices, it is not possible to read .png or .jpg -- files, but appending .txt will work. if (hardwareInfo.isAndroid) then if ( not fileExists(filename, whichSystemDirectory)) then filename = filename .. ".txt" end end if (fileExists(filename, whichSystemDirectory)) then local image -- Corona newImageRect version for loading images -- Check for a scaled file before loading it local f,s = getScaledFilename(filename, whichSystemDirectory) --timePassed("loadImageFile start loading..."..filename) -- If scale comes back ~= 1 then there is a scaled version -- and there is need of one. if (s ~= 1) then local w,h = getImageSize(filename,whichSystemDirectory) image = display.newImageRect(filename, whichSystemDirectory, w, h) --timePassed("loadImageFile, Loaded using newImageRect, C1:"..filename) else image = display.newImage(filename, whichSystemDirectory, true) --timePassed("loadImageFile, loaded using newImage, C2:"..filename) end --print ("loadImageFile: Using Corona method:", filename) anchorZero(image, "Center") return image, scaleFraction end end -- FAILURE -- DEBUGGING TOOL if (showTraceOnFailure) then print ("scripts.funx.loadImageFile called by:") traceback() end local i = display.newGroup() i.anchorChildren = true anchorZero(i, "Center") local image = display.newImage(i, "_ui/missing-image.png", system.ResourceDirectory, true) -- Write to the log! local syspath = system.pathForFile( "", whichSystemDirectory ) --print ("loadImageFile: whichSystemDirectory", syspath ) if (syspath == "") then syspath = "ResourceDirectory" end print ("WARNING: loadImageFile cannot find ",filename," in ",syspath) local t = display.newText( "Cannot find:" .. filename, 0, 0, native.systemFontBold, 24 ) i:insert(t) image.x = midscreenX image.y = midscreenY anchor(t, "Center") t.x = midscreenX t.y = midscreenY+40 anchor(i, "Center") i.x = 0 i.y = 0 -- second returned value is scaleFraction and 1 does nothing but won't crash stuff return i, 1 end -------------------------------------------------------- -- Verify Net Connection OR QUIT! -- WARNING, THIS QUITS THE APP IF NO CONNECTION!!! -------------------------------------------------------- local function verifyNetConnectionOrQuit() local http = require("socket.http") local ltn12 = require("ltn12") if http.request( "http://www.google.com" ) == nil then local function onCloseApp( event ) if "clicked" == event.action then os.exit() end end native.showAlert( "Alert", "An internet connection is required to use this application.", { "Exit" }, onCloseApp ) end end -------------------------------------------------------- -- hasNetConnection: return true if connected, false if not. -- url: a server to check (use http://...) -- showActivity: Turn off the activity indicator (must be turned on before starting) -------------------------------------------------------- local function hasNetConnection(url,showActivity) local socket = require("socket") local test = socket.tcp() test:settimeout(1, 't') -- timeout 5 sec url = url or "www.google.com" if (substring(url, 1, 4) == "http") then url = url:gsub("^https?://", "") end local testResult = test:connect(url,80) test:close() if (testResult == nil) then if (showActivity) then native.setActivityIndicator( false ) end return false else if (showActivity) then native.setActivityIndicator( false ) end return true end end -------------------------------------------------------- -- canConnectWithServer: return true if connected, false if not. -- url: a server to check (use http://...) -- showActivity: Turn off the activity indicator (must be turned on before starting) -------------------------------------------------------- local function canConnectWithServer(url, showActivity, callback, testing) local function MyNetworkReachabilityListener(event) if (testing) then print( "url", url ) print( "address", event.address ) print( "isReachable", event.isReachable ) print("isConnectionRequired", event.isConnectionRequired) print("isConnectionOnDemand", event.isConnectionOnDemand) print("IsInteractionRequired", event.isInteractionRequired) print("IsReachableViaCellular", event.isReachableViaCellular) print("IsReachableViaWiFi", event.isReachableViaWiFi) end network.setStatusListener( url, nil) -- Simulator bug or something...always returns failure local isSimulator = "simulator" == system.getInfo("environment") if (isSimulator) then event.isReachable = true print ("scripts.funx.canConnectWithServer: Corona simulator: Forcing a TRUE for event.isReachable because this fails in simulator.") end -- Turn OFF native busy activity indicator if (showActivity) then native.setActivityIndicator( false ) end if (type(callback) ~= "function") then return event.isReachable else callback(event.isReachable) end end if network.canDetectNetworkStatusChanges then network.setStatusListener( url, MyNetworkReachabilityListener ) else print("scripts.funx.canConnectWithServer: network reachability not supported on this platform") end end -------------- --- Given an array of values, e.g. {"a", "b", "c" } -- convert to an array of key = true, so we can very quickly -- ask whether value is in the array. -- IF we pass anything other than a table, return what was passed. local function tableConvertValuesToKeys(t) if ( "table" == type(t) ) then local t2 = {} for k,v in pairs (t) do t2[v] = true end return t2 else return t end end -------------- --- Check that a key in table 1 exists in table 2. -- Useful for making sure the a setting value in the user settings is correctly named. -- example: keysExistInTable(usersettings,settings) local function keysExistInTable(t1,t2) for k,v in pairs (t1) do if (type(v) == "table") then for kk,vv in pairs (v) do if (t2[k] == nil or t2[k][kk] == nil) then print ("WARNING: '"..k.." . "..kk.." is an unknown key.") end end end end end --- Check if a value is in a table -- Same as in_array(myarray, value) local function inTable(needle, haystack) -- find element v of haystack satisfying f(v) if (haystack and type(haystack) == "table") then for _, v in ipairs(haystack) do if ( v == needle ) then return v end end end return nil end -------------- -- A Handy way to store an RGB or RGBA color is as a string, e.g. "250,250,10,50%" -- The 4th value is an alpha, 0-255, or OPAQUE or TRANSPARENT -- This returns a table from such a string. -- If given a table, this does nothing (in case the value was already converted somewhere!) -- -- If any value is between 0 & 1, then we must be dealing with HDR values, not RGB values -- e.g. 0,0,2 must be RGB, but 0,0,0.1 must be HDR. -- We only have a problem when the highest value is 1, but when would anyone use an RGB value of 1? Never. -- Therefore, if all values <= 1 then it's and HDR value. -- -- If toHDR, then force the result to be HDR. This is useful for widgets and other libraries -- that don't let us redefine their display.setFillColor functions. local function stringToColorTable(s, toHDR, isHDR) if (type(s) == "string") then s = trim(s, true) if (s) then s = split(s, ",") local maxVal = 255 -- RGB max --[[ local valSum = ( tonumber(s[1]) or 0) + (tonumber(s[2]) or 0) + (tonumber(s[3]) or 0) if ( isHDR or ( valSum > 0 and valSum <= 3 ) ) then maxVal = 1 -- HDR max end --]] local opacity = lower(s[4] or maxVal) if ( opacity == "opaque" ) then s[4] = maxVal elseif (opacity == "transparent") then s[4] = 0 else s[4] = applyPercent(s[4], maxVal) or maxVal end -- force numeric for i,j in pairs(s) do s[i] = tonumber(j) s[i] = applyPercent(j,maxVal) or maxVal end if (toHDR) then s = { s[1]/255, s[2]/255, s[3]/255, s[4]/255 } end end end return s end -- *** Apparently, not necessary! I built this due to a bug in the dmc_kolor patch. -- Here's a shortcut for getting an HDR color from RGB or HDR values -- Set isHDR to true if the input string uses HDR values local function stringToColorTableHDR(s, isHDR) return stringToColorTable(s, true, isHDR) end --=================================== --- Frame a group by adding rectangle to a group, behind it. local function frameGroup(g, s, color) local w,h = g.contentWidth or screenW, g.contentHeight or screenH local a = g.anchorChildren g.anchorChildren = true local bounds = g.contentBounds -- print( "xMin: ".. bounds.xMin ) -- xMin: 100 -- print( "yMin: ".. bounds.yMin ) -- yMin: 100 -- print( "xMax: ".. bounds.xMax ) -- xMax: 150 -- print( "yMax: ".. bounds.yMax ) -- yMax: 150 g.anchorChildren = a local r = display.newRect(g, bounds.xMin, bounds.yMin, w, h) r.strokeWidth = s or 1 color = color or "255,0,0" if (type(color) == "string") then color = stringToColorTable(color) end r:setStrokeColor(unpack(color)) r:setFillColor(255,0,0, 50) r:toBack() r.anchorX, r.anchorY = 0,0 r.x, r.y = bounds.xMin, bounds.yMin g._frame = r end ------------------------------------------------- -- Darken the screen -- by drawing a dark opaque rectangle over it. -- Returns the darkening object. -- Undim, below, will destroy the object. -- Because the object which will contain the image might -- be scaled, we need to include a scaling -- factor, to adjust the screen image. -- locked: if true or a function then lock the screen from touches or pass touch to the function. ------------------------------------------------- local function dimScreen(transitionTime, color, scaling, onTouch) transitionTime = tonumber(transitionTime or 300) color = color or { 0.75 * OPAQUE } local opacity = applyPercent(color[4],OPAQUE) or (0.75 * OPAQUE) scaling = scaling or 1 local c = stringToColorTable(color or "55,55,55,75%") -- cover all rect, darken background local bkgdrect = display.newRect(0,0,screenW,screenH) bkgdrect.x, bkgdrect.y = midscreenX, midscreenY bkgdrect:setFillColor( unpack(c) ) bkgdrect:scale(1/scaling, 1/scaling) transition.to (bkgdrect, {alpha=opacity, time=transitionTime } ) if (type(onTouch) ~= "function") then onTouch = function() return onTouch; end end bkgdrect:addEventListener("touch", onTouch ) return bkgdrect end local function undimScreen(handle, transitionTime, f) local function killme() display.remove(handle) handle = nil if (type(transitionTime) == "function") then transitionTime() elseif (type(f) == "function") then f() end end local t if (type(transitionTime) == "number") then t = transitionTime else t = 300 end transition.to (handle, {alpha=0, time=t, onComplete=killme } ) end ------------------------------------------------- -- Shrink the obj away until it is small, then disappear it. -- Restore its size when done, but leave it hidden -- Default is shrink to center, but can set destX, destY local function shrinkAway (obj, callback, transitionSpeed, destX, destY) destX = destX or midscreenX destY = destY or midscreenY local xs = obj.yScale local ys = obj.xScale local w = obj.width local h = obj.height local a = obj.alpha local function cb() obj.xScale = xs obj.yScale = ys obj.width = w obj.height = h obj.alpha = a obj.isVisible = false callback() end callback = callback or nil local t = transitionSpeed or 500 anchor(obj, "Center") transition.to( obj, { time=t, xScale=0.01, yScale=0.01, alpha=0, x=destX, y=destY, onComplete=cb } ) end ------------------------------------------------- local function fadeOut (obj, callback, transitionSpeed) callback = callback or nil if (type(callback) ~= "function") then callback = nil end local function myCallback() obj._isTweening = false if (callback) then callback() end end local t = transitionSpeed or 500 transition.to( obj, { time=t, alpha=0, onComplete=myCallback } ) obj._isTweening = true end ------------------------------------------------- local function fadeIn (obj, callback, transitionSpeed) callback = callback or nil if (type(callback) ~= "function") then callback = nil end local function myCallback() obj._isTweening = false if (callback) then callback() end end if (not obj.isVisible) then obj.alpha = 0 obj.isVisible = true end local t = transitionSpeed or 500 transition.to( obj, { time=t, alpha=1, onComplete=myCallback} ) obj._isTweening = true end ------------------------------------------------------------------------ -- Show a message, then fade away ------------------------------------------------------------------------ local function tellUser(message, x,y) if (not message) then return true end local screenW, screenH = display.contentWidth, display.contentHeight local viewableScreenW, viewableScreenH = display.viewableContentWidth, display.viewableContentHeight local screenOffsetW, screenOffsetH = display.contentWidth - display.viewableContentWidth, display.contentHeight - display.viewableContentHeight local midscreenX = screenW*(0.5) local midscreenY = screenH*(0.5) local TimeToShowMessage = 2000 local FadeMessageTime = 500 -- message object local msg = display.newGroup() local x = x or 0 local y = y or 0 local w = screenW - 40 local h = 0 -- height matches text -- msg corner radius local r = 10 ------------------------------------------------------------------------ local function closeMessage( event ) -- remove from display hierarchy msg.parent:remove( msg ) return true end ------------------------------------------------------------------------ local function fadeAwayThenClose() transition.to( msg, { time=FadeMessageTime, alpha=0, onComplete=closeMessage} ) timedMessage = nil timedMessageList[1] = nil -- remove first element table.remove(timedMessageList, 1) --print ("Messages:", #timedMessageList) end ------------------------------------------------------------------------ -- Create empty text box, using default bold font of device (Helvetica on iPhone) -- Screen Width version: local textObject = display.newText( message, 0, 0, w/3,h, native.systemFontBold, 24 ) -- Fitted width version, does NOT wrap text! --local textObject = display.newText( message, 0, 0, native.systemFontBold, 24 ) textObject:setFillColor( 255,255,255 ) w = textObject.width -- A trick to get text to be centered msg.x = midscreenX msg.y = screenH/3 msg:insert( textObject, true ) -- hide initially msg.alpha = 0 -- Insert rounded rect behind textObject local bkgd = display.newRoundedRect( 0, 0, textObject.contentWidth + 2*r, textObject.contentHeight + 2*r, r ) bkgd:setFillColor( 55, 55, 55, 190 ) msg:insert( 1, bkgd, true ) msg.bkgd = bkgd msg.textObject = textObject -- Show message msg.textObject.text = message msg.bkgd.width = msg.textObject.width + 2*r -- If there is a current message showing, cancel it if (timedMessage) then --timer.cancel(timedMessage) end msg.y = msg.y + (#timedMessageList - 1) * msg.bkgd.height --print ("msg:show width = "..msg.textObject.width) transition.to( msg, { time=FadeMessageTime, alpha=1} ) timedMessage = timer.performWithDelay( TimeToShowMessage, fadeAwayThenClose ) timedMessageList[#timedMessageList + 1] = timedMessage end ------------------------------------------------- -- POPUP: popup a display group -- We have white and black popups. Default is white. -- If the first param is a table, then we assume all params are in that table, IN ORDER!!!, -- If alpha > 0, then ignore a call to show it. --[[ @param [table] t = table of params, below: @param [display object] table.object @param [string] table.backgroundColor @param [string] table.showBackground @param [string] table.bkgdAlpha @param [string] table.transitionTime @param [string] table.filename --]] ------------------------------------------------- local function popupDisplayGroup(t, frontstage) local obj = t.object if (not obj or (obj.isVisible == true and obj.alpha > 0) ) then return false end --[[ local backgroundColor = trim(t.backgroundColor) local showBackground = t.showBackground local bkgdAlpha = applyPercent(bkgdAlpha or 0.95,1) local backgroundFile = trim(t.backgroundFile ) --]] local transitionTime = tonumber(t.time) or 300 local doDimScreen = t.doDimScreen local cancelOnTouch = t.cancelOnTouch local closing = false local function moveToFrontstage(obj) if (not obj.onFrontstage) then --------------- -- Move the object to the front stage, above buttons and everything -- Save the x,y from whence we pluck the object obj.localX = obj.x obj.localY = obj.y -- Save the parent group reference obj._parentGroup = obj.parent frontstage:insert(obj) if (obj.dimBackgroundOnZoom and frontstage.numChildren < 3) then frontstage.background.alpha = 0 transition.to(frontstage.background, { time=obj.zoomTransitionTime, alpha=frontstage.background._alpha } ) end obj:toFront() obj.onFrontstage = true end end local function restoreFromFrontstage(obj) --------------- -- Move object from the frontstage back to the group it came from. -- Do this first, so we can restore the picture to its proper -- zLayer in the set of pictures! if (obj.onFrontstage) then --local lx, ly = obj:localToContent(obj.x, obj.y) local lx, ly = obj.localX, obj.localY obj._parentGroup:insert(obj) --obj:setReferencePoint(display[obj.originalReferencePoint .. "ReferencePoint"]) anchor(obj, obj.originalReferencePoint) obj.x = lx obj.y = ly -- Get rid of this reference just in case, to avoid memory leaks obj._parentGroup = nil obj.onFrontstage = false end -- Restore objects to their proper layers if (obj.layer == "top" ) then obj:toFront() elseif (obj.layer == "bottom" ) then obj:toBack() elseif (obj.layer and obj.restoreLayersOnZoomOut) then zSort(obj.parent) end end local function cleanup() if (doDimScreen) then undimScreen(obj._dim) end if (frontstage) then restoreFromFrontstage(obj) end end local function closeMe(event) if (not closing and obj ~= nil) then -- remove the close button if (obj._popupCloseButton) then obj._popupCloseButton:removeSelf() obj._popupCloseButton = nil end transition.to (obj, {alpha=0, time=transitionTime, onComplete=cleanup} ) closing = true end return true end -- w/h of the popup local w,h = obj.contentWidth, obj.contentHeight --[[ -- BACKGROUND -- cover all rect, darken background local bkgdrect = display.newRect(0,0,screenW,screenH) obj:insert(bkgdrect) bkgdrect:setFillColor( 55, 55, 55, 190 ) -- background graphic for popup -- If the default fails, try using the value as a filename local bkgd if (backgroundFile) then bkgd = display.newImage( backgroundFile, true) elseif (backgroundColor) then bkgd = display.newRect(0,0, obj.contentWidth, obj.contentHeight) bkgd:setFillColor( stringToColorTable(backgroundColor)) end local bkgdWidth, bkgdHeight if (bkgd) then checkScale(bkgd) obj:insert (bkgd) anchor(bkgd, "Center") bkgd.x = midscreenX bkgd.y = midscreenY bkgd.alpha = bkgdAlpha bkgdWidth = bkgd.width bkgdHeight = bkgd.height w,h = bkgd.contentWidth, bkgd.contentHeight end --]] local closeButton = widget.newButton{ defaultFile = "_ui/button-cancel-round.png", overFile = "_ui/button-cancel-round-over.png", onRelease = closeMe, } obj:insert(closeButton) obj._popupCloseButton = closeButton anchorZero(closeButton, "Center") closeButton.x = (w) - closeButton.width/4 closeButton.y = closeButton.height/4 closeButton:toFront() obj.alpha = 0 obj.isVisible = true --[[ -- Dimming requires moving to front stage, etc. No time for that now if (doDimScreen) then -- true means lock the background against touches local c = "0,0,0,75%" obj._dim = dimScreen(transitionTime, c, nil, true) end --]] if (frontstage) then moveToFrontstage(obj) end -- Capture touch events and do nothing. if (cancelOnTouch) then obj:addEventListener( "touch", closeMe ) else obj:addEventListener( "touch", function() return true end ) end transition.to (obj, {alpha=1, time=transitionTime } ) end ------------------------------------------------- -- POPUP: popup image with close button -- We have white and black popups. Default is white. -- If the first param is a table, then we assume all params are in that table, IN ORDER!!!, -- starting with filename, e.g. { "filename.jpg", "white", 1000, true} ------------------------------------------------- local function popup(filename, color, bkgdAlpha, transitionTime, cancelOnTouch) local mainImage local pgroup = display.newGroup() pgroup.anchorChildren = true local closing = false if (type(filename) == "table") then color = filename.color bkgdAlpha = filename.bkgdAlpha transitionTime = tonumber(filename.time) cancelOnTouch = filename.cancelOnTouch or false filename = trim(filename.filename) end bkgdAlpha = applyPercent(bkgdAlpha, 1) color = trim(color) if (color == "") then color = "white" end bkgdAlpha = applyPercent(bkgdAlpha,1) or 0.95 transitionTime = tonumber(transitionTime) transitionTime = transitionTime or 300 cancelOnTouch = cancelOnTouch or false local function killme() if (pgroup ~= nil) then display.remove(pgroup) pgroup=nil --print "Killed it" else --print ("Tried to kill pGroup, but it was dead.") end end local function closeMe(event) if (not closing and pgroup ~= nil) then transition.to (pgroup, {alpha=0, time=transitionTime, onComplete=killme} ) closing = true end return true end -- cover all rect, darken background local bkgdrect = display.newRect(0,0,screenW,screenH) pgroup:insert(bkgdrect) bkgdrect:setFillColor( 55, 55, 55, 190 ) -- background graphic for popup -- If the default fails, try using the value as a filename local bkgd = display.newImage("_ui/popup-"..color..".png", true) if (not bkgd) then bkgd = display.newImage(color, true) if (not bkgd) then print ("ERROR: Missing popup background image ("..color..")") end end local bkgdWidth, bkgdHeight if (bkgd) then checkScale(bkgd) pgroup:insert (bkgd) anchor(bkgd, "Center") bkgd.x = midscreenX bkgd.y = midscreenY bkgd.alpha = bkgdAlpha bkgdWidth = bkgd.width bkgdHeight = bkgd.height else bkgdWidth = screenW * 0.95 bkgdHeight = screenH * 0.95 end mainImage = display.newImage(filename, true) checkScale(mainImage) pgroup:insert (mainImage) anchor(mainImage, "Center") mainImage.x = midscreenX mainImage.y = midscreenY local closeButton = widget.newButton{ defaultFile = "_ui/button-cancel-round.png", overFile = "_ui/button-cancel-round-over.png", onRelease = closeMe, } pgroup:insert(closeButton) anchorZero(closeButton, "Center") closeButton.x = (bkgd.width/2) - closeButton.width/4 closeButton.y = -(bkgd.height/2) + closeButton.height/4 closeButton:toFront() pgroup.alpha = 0 -- Capture touch events and do nothing. if (cancelOnTouch) then pgroup:addEventListener( "touch", closeMe ) else pgroup:addEventListener( "touch", function() return true end ) end transition.to (pgroup, {alpha=1, time=transitionTime } ) end ------------------------------------------------- -- POPUP: popup web page ------------------------------------------------- local function popupWebpage(targetURL, color, bkgdAlpha, transitionTime, netrequired, noNetMsg) local testing = false local closing = false if (type(targetURL) == "table") then color = trim(targetURL[2]) bkgdAlpha = tonumber(targetURL[3]) transitionTime = tonumber(targetURL[4]) targetURL = trim(targetURL[1]) end -------------------------- local function doPop(isReachable) --print ("doPop says, isReachable =", isReachable) if (isReachable) then local mainImage local pgroup = display.newGroup() anchor(pgroup, "Center") pgroup.x, pgroup.y = midscreenX, midscreenY color = color or "white" bkgdAlpha = bkgdAlpha or 0.95 transitionTime = transitionTime or 300 local function killme() if (pgroup ~= nil) then display.remove(pgroup) pgroup=nil --print "Killed it" else --print ("Tried to kill pGroup, but it was dead.") end end local function closeMe(event) if (not closing and pgroup ~= nil) then native.cancelWebPopup() transition.to (pgroup, {alpha=0, time=transitionTime, onComplete=killme} ) closing = true end return true end -- cover all rect, darken background local bkgdrect = display.newRect(0,0,screenW,screenH) pgroup:insert(bkgdrect) anchor(bkgdrect, "Center") bkgdrect:setFillColor( 55, 55, 55, 190 ) -- background graphic for popup local bkgd = display.newImage("_ui/popup-"..color..".png", true) checkScale(bkgd) pgroup:insert (bkgd) anchor(bkgdrect, "Center") bkgd.alpha = bkgdAlpha local closeButton = widget.newButton { id = "close", defaultFile = "_ui/button-cancel-round.png", overFile = "_ui/button-cancel-round-over.png", onRelease = closeMe, } pgroup:insert(closeButton) anchor(closeButton, "TopRight") anchorZero(closeButton, "Center") closeButton.x = (bkgd.width/2) - closeButton.width/4 closeButton.y = -(bkgd.height/2) + closeButton.height/4 closeButton:toFront() pgroup.alpha = 0 -- Capture touch events and do nothing. pgroup:addEventListener( "touch", function() return true end ) local function showMyWebPopup() local function listener( event ) local shouldLoad = true --print ("popupWebpage:listener") --dumptable(event) --print ("========") --print ("event.errorCode",event.errorCode) if ( event.errorCode and event.errorCode ~= -999 ) then -- Error loading page print( "showMyWebPopup: Error: " .. tostring( event.errorMessage ) ) shouldLoad = false end return shouldLoad end -- web popup local x = (screenW - bkgd.width)/2 + (closeButton.width) local y = (screenH - bkgd.height)/2 + (closeButton.height) local w = bkgd.width - (2 * closeButton.width) local h = bkgd.height - (2 * closeButton.width) --print ("showWebMap: go to ",targetURL) --print (x, y, w, h, targetURL) local options = { hasBackground=true, urlRequest = listener, -- Only need this for local URLs --baseUrl=system.ResourceDirectory, } --print ("showWebPopup:",targetURL) --print ("========") native.showWebPopup(x, y, w, h, targetURL, options ) end transitionTime = tonumber(transitionTime) transition.to (pgroup, {alpha=1, time=transitionTime, onComplete=showMyWebPopup } ) else noNetMsg = noNetMsg or "No Internet" tellUser(noNetMsg .. ":" .. targetURL) end end -- callback function -------------------------- -- Do we have network? -- Don't test with our URL, since it might have authentication in it, -- e.g. human:password@myurl.com --local testurl = targetURL local testurl = "http://google.com" if (substring(testurl, 1, 4) == "http") then testurl = testurl:gsub("^https?://", "") end -- strip subfolders b/c of iOS bug testurl = gsub(testurl, "/.*", "") canConnectWithServer(testurl, false, doPop, testing) end ------------------------------------------------------------------------ -- OPEN a URL ------------------------------------------------------------------------ local function openURLWithConfirm(urlToOpen, title, msg) -- Handler that gets notified when the alert closes local function onComplete( event ) if "clicked" == event.action then local i = event.index if 1 == i then system.openURL(urlToOpen) elseif 2 == i then -- do nothing, dialog with close end end end -- Show alert with five buttons local alert = native.showAlert(title, msg , { "OK", "Cancel" }, onComplete ) end ------------------------------------------------------------------------ -- SHADOW - Image-based version for Graphics 1.0 -- Build a drop shadow ------------------------------------------------------------------------ local function buildShadow(w,h,sw,opacity) local shadow = display.newGroup() --addPosRect(shadow,false) --shadow.anchorChildren = true --print ("buildShadow: ",w,h) local tl = display.newImage(shadow, "_ui/shadow_tl.png") local tr = display.newImage(shadow, "_ui/shadow_tl.png") local bl = display.newImage(shadow, "_ui/shadow_tl.png") local br = display.newImage(shadow, "_ui/shadow_tl.png") -- Rotations make these non-obvious! anchorZero(tl, "TopLeft") anchorZero(tr, "TopLeft") anchorZero(bl, "TopRight") anchorZero(br, "BottomRight") local left = display.newImage(shadow, "_ui/shadow_l.png") local right = display.newImage(shadow, "_ui/shadow_l.png") local top = display.newImage(shadow, "_ui/shadow_l.png") local bottom = display.newImage(shadow, "_ui/shadow_l.png") anchor(left, "TopLeft") anchor(right, "TopLeft") anchor(top, "TopLeft") anchor(bottom, "TopLeft") anchor(left, "TopLeft") anchor(right, "BottomLeft") top.anchorX, top.anchorY = 0.5,1 bottom.anchorX, bottom.anchorY = 0.5,0 -- SIZING local corner = sw local edge = sw -- Start with a solid rect --local srect = display.newRect(shadow, corner,corner,w-(2*corner),h-(2*corner)) -- Alpha visually matches the graphic pieces. Probably we should use another graphic --srect:setFillColor( 0,0,0,70 ) local srect = display.newImage(shadow, "_ui/shadow_rect.png") srect.width = w -- (2*corner) srect.height = h -- (2*corner) anchor(srect, "TopLeft") srect.x = corner srect.y = corner -- rotate tr:rotate( 90 ) bl:rotate( -90 ) br:rotate( 180 ) right:rotate( 180 ) top:rotate( 90 ) bottom:rotate( -90 ) if (h<(2*corner) or w<(2*corner)) then print ("scripts.funx.buildShadow: ERROR! The shadow box is to small..I can't compute this one") end --scale corner = sw local cornerPad = sw/2 edge = sw local edgePad = sw/2 local r = sw / tl.width if (r>1) then tl:scale(r,r) tr:scale(r,r) bl:scale(r,r) br:scale(r,r) -- Rotations make this non-obvious, x,y get flipped! top.width = sw top.height = w bottom.width = sw bottom.height = w left.width = sw left.height = h right.width = sw right.height = h end if (corner == h/2) then display.remove(left) left = nil display.remove(right) right = nil end if (w <= (2*corner)) then display.remove(top) top = nil display.remove(bottom) bottom = nil end if (h > (2*corner) and left) then --left.height = h-corner --right.height = h-corner end if (w > (2*corner) and top) then --top.height = sw --bottom.height = w-corner end -- position --[[ anchor(tl, "TopLeft") anchor(tr, "TopLeft") anchor(bl, "TopLeft") anchor(br, "TopLeft") anchor(left, "TopLeft") anchor(right, "TopLeft") anchor(top, "TopLeft") anchor(bottom, "TopLeft") ]] if (top) then top.x = corner top.y = cornerPad bottom.x = corner bottom.y = h+ corner + cornerPad end if (left) then left.x = 0 left.y = sw right.x = w + 2*sw right.y = sw end tr.x = w + 2*corner tr.y = 0 br.x = w + corner br.y = h + corner bl.y = h + corner return shadow end ------------------------------------------------------------------------ -- SHADOW - Filter Effects based using Graphics 2.0 -- Build a drop shadow by duplicating any object in a snapshot -- and blurring and coloring it. ------------------------------------------------------------------------ local function buildShadowObj(obj, sw, color, opacity) w = obj.contentWidth h = obj.contentHeight sw = sw or 20 local shadow = display.newSnapshot( w + 2*sw, h + 2*sw ) -- Start with a solid rect local srect = display.newRect(0,0,w + 1*sw,h + 1*sw) color = color or "0,0,0,100%" local c = stringToColorTable(color) if opacity then c[4] = applyPercent(opacity,1) end -- Alpha visually matches the graphic pieces. Probably we should use another graphic srect:setFillColor( 0,0,0, opacity ) shadow.group:insert(srect) shadow.fill.effect = "filter.blurGaussian" shadow.fill.effect.horizontal.blurSize = sw shadow.fill.effect.horizontal.sigma = 140 shadow.fill.effect.vertical.blurSize = sw shadow.fill.effect.vertical.sigma = 140 --shadow.fill.effect = "filter.blur" return shadow end ------------------------------------------------------------------------ -- Functions to do on a system event, -- e.g. load or exit -- Options: -- options.onAppStart = function for start or resume -- options.onAppExit = function for exit or suspend ------------------------------------------------------------------------ local function initSystemEventHandler(options) --------------------- local function shouldResume() return true end --------------------- --------------------- local function onSystemEvent( event ) if (options == nil) then return true end if (event.type == "applicationExit" ) then options.onAppExit() elseif ( event.type == "applicationSuspend" ) then options.onAppSuspend() elseif ( event.type == "applicationStart" ) then options.onAppStart() elseif ( event.type == "applicationResume" ) then options.onAppResume() end --[[ if ( (event.type == "applicationExit" or event.type == "applicationSuspend") and type(options.onAppExit) == "function" ) then options.onAppExit() elseif ( (event.type == "applicationStart" or event.type == "applicationResume") and type(options.onAppStart) == "function" ) then if shouldResume() then options.onAppStart() else -- start app up normally end end --]] end --------------------- Runtime:addEventListener( "system", onSystemEvent ); end --===================================================== -- the reason this routine is needed is because lua does not -- have a sort indexed table function -- reverse : if set, sort reverse local function table_sort(a, sortfield, reverse) local new1 = {} local new2 = {} for k,v in pairs(a) do table.insert(new1, { key=k, val=v } ) end if (reverse) then table.sort(new1, function (a,b) return ((a.val[sortfield] or '') > (b.val[sortfield] or '') ) end) else table.sort(new1, function (a,b) return ((a.val[sortfield] or '') < (b.val[sortfield] or '') ) end) end for k,v in pairs(new1) do table.insert(new2, v.val) end return new2 end --[[ Sort a table of strings As a more advanced solution, we can write an iterator that traverses a table following the order of its keys. An optional parameter f allows the specification of an alternative order. It first sorts the keys into an array, and then iterates on the array. At each step, it returns the key and value from the original table: t : the table f : a function which compares two keys, e.g. f = function(a,b) return a<b end With this function, it is easy to print those function names in alphabetical order. The loop for name, line in pairsByKeys(lines) do print(name, line) end ]] local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end --[[ ===================================================== Multi-column table sort. If returnNumericArray is false, returns an associated array, but there is a warning these are unstable, whatever that really means. If returnNumericArray is true, then returns a table with NUMERICAL indeces { 1,2,3 } instead of the original keys because "The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort." So, if returnNumericArray is set, we return a table of this form: t = { {key="key", val={whatever the value was}, .... } The reverseSort parameter is a table that matches the sortfields, with true/false for each item, indicating whether that item should be reverse sorted (true), e.g. lower->highest ** If NO reverseSort table is given, DEFAULT is all reverse sort, from low to high and A->Z!!! Example: local t= { cows = { title = "cows", author="Zak", publisherid="2" }, mice = { title = "Art", author="Bob", publisherid="2" }, zebra = { title = "zebra", author="Gary", publisherid="3" }, } t = table_multi_sort(t, {"publisherid", "title", "author" },{ true, false, false }, true ) --]] local function table_multi_sort(a, sortfields, reverseSort, returnNumericArray) if ( (not reverseSort) or #reverseSort == 0) then reverseSort = {} for i=1,#sortfields do reverseSort[i] = false end end local function cmp2 (a, b) for i=1,(#sortfields-1) do if (reverseSort[i]) then a,b = b,a end local colTitle = sortfields[i] local aa = a.val[colTitle] or "" local bb = b.val[colTitle] or "" if aa < bb then return true end if aa > bb then return false end end local colTitle = sortfields[#sortfields] if (reverseSort[#sortfields]) then a,b = b,a end return a.val[colTitle] < b.val[colTitle] end local new1 = {} local new2 = {} for k,v in pairs(a) do table.insert(new1, { key=k, val=v } ) end table.sort(new1, cmp2) if (returnNumericArray) then return new1 else for k,v in ipairs(new1) do new2[v.key] = v.val end return new2 end end --======================================================================== -- Order objects in a display group by the "layer" field of each object -- We can't use "z-index" cuz the hyphen doesn't work in XML. -- This allows for ordered layering. local function zSort(myGroup) local n = myGroup.numChildren local kids = {} for i=1,n do kids[i] = myGroup[i] end --print ("Zsort: "..n.." children") table.sort(kids, function(a, b) local al = a.layer or 0 local bl = b.layer or 0 --print ("zSort:", al, bl, a.index, a.name) if (al=="top" or bl=="bottom") then return false end if (bl=="top" or al=="bottom") then return true end --print ("a1, b1", al,bl) return (al or 1) < (bl or 1) -- "layer" is your custom z-index field end ) for i = 1,n do myGroup:insert(kids[i]) --print ("zSort result:",i, kids[i].name, " Layer:", kids[i].layer) end return myGroup end --======================================================================== -- get date parts for a given ISO 8601 date format (http://richard.warburton.it ) local function get_date_parts(date_str) if (date_str) then local _,_,y,m,d=find(date_str, "(%d+)-(%d+)-(%d+)") return tonumber(y),tonumber(m),tonumber(d) else return nil,nil,nil end end -- This converts a unix time stamp in GMT time to current local Lua time. -- This is a string of the form, yyyy-mm-dd hh:mm:ss local function datetime_to_unix_time(s) if (s) then local p="(%d+)-(%d+)-(%d+) (%d+):(%d+):(%d+)" local year,month,day,hour,min,sec=s:match(p) local offset=os.time()-os.time(os.date("!*t")) local dateTable = {day=day,month=month,year=year,hour=hour,min=min,sec=sec} local t = os.time{day=day,month=month,year=year,hour=hour,min=min,sec=sec} return (t+offset) else return 0 end end --==================================================== local function getmonth(month) local months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" } return months[tonumber(month)] end --==================================================== local function getday_posfix(day) local idd = math.mod(day,10) return (idd==1 and day~=11 and "st") or (idd==2 and day~=12 and "nd") or (idd==3 and day~=13 and "rd") or "th" end --======================================================================== -- Format a STRING date, e.g. 2005-10-4 in ISO format, into a human format. -- Default for stripZeros is TRUE. local function formatDate(s, f, stripZeros) if (stripZeros == nil) then stripZeros = true end if (s ~= "") then f = f or "%x" local y,m,d = get_date_parts(s) if (y and m and d) then local t = os.time({year=y,month=m,day=d}) s = os.date(f, t) if (stripZeros) then s = s:gsub("/0", "/") s = s:gsub("%.0", ".") s = s:gsub("%, 0", ", ") s = s:gsub("^0", "") end else --print ("Warning: funx.formatDate: the dates provided for formatting are not in xx-xx-xx format: ", s) end return s else return "" end end ------------------------------------------------- -- loadingSpinner -- Show a loading spinner graphic -- *** THIS REQUIRES GRAPHICS IN THE "funx" DIRECTORY! *** -- If these graphics are missing, well, it will break. -- Params is a table: -- @param sheet [string] The path to a sprite sheet for the spinner -- @param delay [int] Time to wait before showing message. If our loading happens fast enough, we don't need -- @param handle [table] Timer reference. If this value is set, then the spinner will be cancelled! -- the message to show. -- Examples of the table: -- { handle = mytimerhandle } -- { message="message", delay=1000 } --[[ local p = { sheet = message="Loading", delay=1000} local myTimerHandle = spinner(p) ... local p = { handle = myTimerHandle } spinner(p) --]] ------------------------------------------------- local function spinner(p) p = p or {} local delay = p.delay or 500 --------------------------spinnerSprite -- Show spinner if (not p.handler) then local spinnerSprite local sheetInfo = require( dotPathToFunxFolder .. "spinner") local myImageSheet = graphics.newImageSheet( pathToFunxFolder.."spinner.png", sheetInfo:getSheet() ) local spinnerSprite = display.newSprite( myImageSheet , sheetInfo.sequenceData ) -- Put in screen center spinnerSprite.x = display.contentCenterX spinnerSprite.y = display.contentCenterY -- I like this size reduction spinnerSprite:scale( 0.5, 0.5 ) -- Hide the spinner until called spinnerSprite.isVisible = false local function showSpinner() spinnerSprite.isVisible = true spinnerSprite:play() if (p.message) then tellUser(p.message) end end --print ("start timer") --print ("spinner started at",os.time(),"seconds") local t = timer.performWithDelay( delay, showSpinner ) t.starttime = os.time() t._spinnerObject = spinnerSprite return t else -------------------------- -- Hide spinner --print ("Spinner canceled!") --print ("spinner cancelled at",os.time(),"seconds after ",os.time()-p.handler.starttime,"seconds.") timer.cancel(p.handler) p.handler._spinnerObject:pause() p.handler._spinnerObject:removeSelf() p.handler._spinnerObject = nil end end local function activityIndicator( mode ) if mode then native.setActivityIndicator( true ) else native.setActivityIndicator( false ) end end local function activityIndicatorOn( mode ) timer.performWithDelay(1, function() native.setActivityIndicator( true ) end ) end local function activityIndicatorOff( mode ) timer.performWithDelay(1, function() native.setActivityIndicator( false ) end ) end ------------------------------------------------------------------------ -- CLEAN GROUP ------------------------------------------------------------------------ local function cleanGroups ( curGroup, level ) if curGroup.numChildren then while curGroup.numChildren > 0 do cleanGroups ( curGroup[curGroup.numChildren], level+1 ) end if level > 0 then display.remove(curGroup) end else display.remove(curGroup) curGroup = nil return true end end ------------------------------------------------------------------------ -- CALL CLEAN FUNCTION ------------------------------------------------------------------------ local function callClean ( moduleName ) if type(package.loaded[moduleName]) == "table" then if lower(moduleName) ~= "main" then for k,v in pairs(package.loaded[moduleName]) do if k == "clean" and type(v) == "function" then package.loaded[moduleName].clean() end end end end end ------------------------------------------------------------------------ -- UNLOAD SCENE ------------------------------------------------------------------------ local function unloadModule ( moduleName ) local fxTime = 200 if type(package.loaded[moduleName]) == "table" then package.loaded[moduleName] = nil local function garbage ( event ) collectgarbage("collect") end garbage() timer.performWithDelay(fxTime,garbage) end end --[[ local function spinner() local isAndroid = "Android" == system.getInfo("platformName") if(isAndroid) then local alert = native.showAlert( "Information", "Activity indicator API not yet available on Android devices.", { "OK"}) end -- local label = display.newText( "Activity indicator will disappear in:", 0, 0, system.systemFont, 16 ) label.x = display.contentWidth * 0.5 label.y = display.contentHeight * 0.3 label:setFillColor( 10, 10, 255 ) local numSeconds = 5 local counterSize = 36 local counter = display.newText( tostring( numSeconds ), 0, 0, system.systemFontBold, counterSize ) counter.x = label.x counter.y = label.y + counterSize counter:setFillColor( 10, 10, 255 ) function counter:timer( event ) numSeconds = numSeconds - 1 counter.text = tostring( numSeconds ) if 0 == numSeconds then native.setActivityIndicator( false ); end end timer.performWithDelay( 1000, counter, numSeconds ) native.setActivityIndicator( true ); end ]] ------------------------------------------------- -- Toggle an object, transitioning between a given alpha, and zero. local function toggleObject(obj, fxTime, opacity, onComplete) fxTime = tonumber(fxTime) opacity = applyPercent(opacity,1) --print () --print () --print ("------------- ToggleObject Begin (opacity: "..opacity) -- Actual alpha of a display object is not exact local currentAlpha = math.ceil(obj.alpha * 100)/100 -- be sure these properties exist obj.tween = obj.tween or {} if (obj._isTweening == nil) then obj._isTweening = false end local function transitionComplete(obj) local currentAlpha = math.ceil(obj.alpha * 100)/100 if (currentAlpha == 0) then obj.isVisible = false else obj.isVisible = true end obj._isTweening = false obj.tweenDirection = nil if (onComplete) then onComplete() end end -- Cancel transition if caught in the middle if (obj.tween and obj._isTweening) then transition.cancel(obj.tween) obj._isTweening = false obj.tween = nil --print ("toggleObject: CANCELLED TRANSITION") end if (obj.alpha == 0 or (obj.alpha > 0 and obj.tweenDirection == "going") ) then -- Fade in --print ("toggleObject: fade In") obj.isVisible = true obj.tween = transition.to( obj, { time=fxTime, alpha=opacity, onComplete=transitionComplete } ) if (obj.tweenDirection) then --print ("Fade in because we were : "..obj.tweenDirection) end obj.tweenDirection = "coming" else -- Fade out obj.tween = transition.to( obj, { time=fxTime, alpha=0, onComplete=transitionComplete } ) --print ("toggleObject: fade Out") if (obj.tweenDirection) then --print ("Fade out because we are : "..obj.tweenDirection) end obj.tweenDirection = "going" end --print ("obj alpha = "..obj.alpha) --print ("obj.tweenDirection: "..obj.tweenDirection) obj._isTweening = true --print "------------- END" end ------------------------------------------------- -- Hide an object, transitioning between a given alpha, and zero. local function hideObject(obj, fxTime, opacity, onComplete) fxTime = tonumber(fxTime) opacity = tonumber(opacity) if (not obj or type(obj) ~= "table") then print ("ERROR! : funx.hideObject : the object is missing, perhaps display object was removed but table not nil'ed?") return false end if (not obj.alpha) then obj.alpha = 0 end -- Actual alpha of a display object is not exact local currentAlpha = math.ceil(obj.alpha * 100)/100 -- be sure these properties exist obj.tween = obj.tween or {} if (obj._isTweening == nil) then obj._isTweening = false end local function transitionComplete(obj) if (not obj) then print ("scripts.funx.hideObject:transitionComplete: WARNING: object is gone!") return false end local currentAlpha = math.ceil(obj.alpha * 100)/100 if (currentAlpha == 0) then obj.isVisible = false else obj.isVisible = true end obj._isTweening = false obj.tweenDirection = nil if (onComplete) then onComplete() end end -- Cancel transition if caught in the middle if (obj.tween and obj._isTweening) then transition.cancel(obj.tween) obj._isTweening = false obj.tween = nil --print ("toggleObject: CANCELLED TRANSITION") end -- Fade out obj.tween = transition.to( obj, { time=fxTime, alpha=0, onComplete=transitionComplete } ) --print ("toggleObject: fade Out") if (obj.tweenDirection) then --print ("Fade out because we are : "..obj.tweenDirection) end obj.tweenDirection = "going" obj._isTweening = true end -- returns true/false depending whether value is a percent local function isPercent (x) local v,s = match(x, "(%d+)(%%)$") if (s == "%") then return true else return false end end -- Return x%, e.g. 10% returns .10 local function percent (x) local v = match(x, "(%d+)%%$") if v then v = v / 100 end return v end local function applyPercentIfSet(x,y,noRound) if (x ~= nil) then return applyPercent (x,y,noRound) else return nil end end ---------- -- Find new width/height to margins within an x,y -- x,y default to the screen -- fit: true/false, where true = fill -- Return ration r, the amount to use for rescaling, e.g. obj:scale(r,r) -- To fit into the screen, just call ratioToFitMargins (obj.w, obj.h) local function ratioToFitMargins (w,h, fill, t,b,l,r, x,y) local x = x or screenW local y = y or screenH t = t or 0 b = b or 0 l = l or 0 r = r or 0 -- Space to fit into local ww = x - l - r local hh = y - t - b -- Ratios to fit local wr = ww/w local hr = hh/h -- default is fit, i.e. not fill local cond = (wr >= hr) if (not fill) then cond = (wr < hr) end if (cond) then r = wr else r = hr end return r end ---------- -- Reduce an element if necessary so it fits -- with margins insdie of an space of xMax by yMax. -- xMax,yMax default to the screen -- DEFAULT: do not resize larger! -- RETURNS THE RATIO for scaling. Why? Because it seems there's a bug in Corona -- that means rescaling inside of this function screws up positioning. local function scaleObjectToMargins (obj, t,b,l,r, xMax,yMax, reduceOnly) local ratio if (reduceOnly == nil) then reduceOnly = true end xMax = xMax or 0 yMax = yMax or 0 if (xMax <= 0) then xMax = screenW end if (yMax <= 0) then yMax = screenH end local w = obj.contentWidth local h = obj.contentHeight if reduceOnly then if (w < screenW and h < screenH) then return 1 end end local ww = xMax - l - r local hh = yMax - t - b --print (xMax,l,r,ww) --print (yMax,t,b,hh) local wr = ww/w local hr = hh/h if (wr < hr) then ratio = wr else ratio = hr end return ratio --if (ratio ~= 1) then -- obj:scale(ratio,ratio) --end --print ("ratio", ratio, obj.contentWidth, obj.contentHeight) end ------- -- getFinalSizes -- Return the final width/height based on the original width/height and new values. -- The new values are w,h. They could be percentages, and if only one is present, the other is the same. -- If the Proportional flag is true, then if both width and height -- are set, resize proportionally to fit INSIDE of width/height -- EXAMPLE: -- w,h = maxWidth, maxHeight -- pic = loadImageFile(filename) -- pic.width, pic.height = funx.getFinalSizes (w,h, pic.width, pic.height, true) local function getFinalSizes (w,h, originalW, originalH, p) local wPercent, hPercent if p == nil then p = true end w = tonumber(w) h = tonumber(h) originalW = tonumber(originalW) originalH = tonumber(originalH) if (w and not h) then if (isPercent(w)) then h = applyPercent(w,originalH) w = applyPercent(w,originalW) else h = originalH * (w/originalW) end elseif (h and not w) then if (isPercent(h)) then w = applyPercent(h,originalW) h = applyPercent(h,originalH) else w = originalW * (h/originalH) end elseif (h and w) then if (p) then local doScaleW = (originalH/h) <= (originalW/w) if (doScaleW) then w = applyPercent(w, originalW) h = originalH * (w/originalW) else h = applyPercent(h, originalH) w = originalW * (h/originalH) end else h = applyPercent(h, originalH) w = applyPercent(w, originalW) end else w = originalW h = originalH end return w,h end ------- -- ScaleObjToSize -- Scale an object to width/height settings. -- The new values are w,h. They could be percentages, and if only one is present, the other is the same. local function ScaleObjToSize (obj, w,h) local wPercent, hPercent local originalW = obj.contentWidth local originalH = obj.contentHeight if (w and not h) then if (isPercent(w)) then h = applyPercent(w,originalH) w = applyPercent(w,originalW) else h = originalH * (w/originalW) end elseif (h and not w) then if (isPercent(h)) then w = applyPercent(h,originalW) h = applyPercent(h,originalH) else w = originalW * (h/originalH) end elseif (h and w) then h = applyPercent(h, originalH) w = applyPercent(w, originalW) else w = originalW h = originalH end local ratio = w/originalW obj:scale(ratio,ratio) end local function AddCommas( number, maxPos ) local s = tostring( number ) local len = strlen( s ) if len > maxPos then -- Add comma to the string local s2 = substring( s, -maxPos ) local s1 = substring( s, 1, len - maxPos ) s = (s1 .. "," .. s2) end maxPos = maxPos - 3 -- next comma position if maxPos > 0 then return AddCommas( s, maxPos ) else return s end end local function lines(str) local t = {} local function helper(line) table.insert(t, line) return "" end helper((str:gsub("(.-)\r?\n", helper))) return t end -- Load a file into a variable local function readFile(filename) local filePath = system.pathForFile( filename, system.ResourceDirectory ) local hFile,err = io.open(filePath,"r"); if (not err) then local contents = hFile:read("*a"); io.close(hFile); return contents,nil; else return nil,err; end end ---------------- -- buildTextDisplayObjectFromTemplate -- Build a display object using a template and a table -- Each line of the template is settings for text the display object -- Each line is comma separated, starting with the name of the field in the obj to use local function buildTextDisplayObjectsFromTemplate (template, obj) -- split the template local objs = {} for i,line in pairs(lines(trim(template))) do --print ("Line : "..line) local params = split (line, ",") local name = params[1] --print (name) -- Set the text and size local t = "BLANK" if obj then local t = obj[name] --print ("OBJ.NAME = " .. t) end local o = display.newText(t, 0, 0, native.systemFontBold, params[4]) -- color o:setFillColor(0, 0, 0) -- Set the coordinates o.x = params[2] o.y = params[3] -- opacity o.alpha = 1.0 objs[name] = o --print ("Params for "..name..":") dumptable(params) end return objs end -------------------------------------------------------- -- local function stripCommandLinesFromText(text) local substring = substring local cleanText = "" for line in gmatch(text, "[^\n]+") do line = trim(line) if (substring(line,1,3) ~= "###") then cleanText = cleanText .. "\n" .. line end end return cleanText end -- Text styles used by autoWrappedText --local textStyles = {} -------------------------------------------------------- -- Styles for autoWrappedText, below. -- Styles are simply the formatting lines, ### set, .... -- We pass a table of styles: -- styles = { stylename = stylestring, ... } local function loadTextStyles(filename, path) if (filename) then path = path or system.DocumentsDirectory local filePath = system.pathForFile( filename, path ) if (not filePath) then print ("WARNING: missing file ",filename) return {} end local textStyles = loadTableFromFile(filePath, "\n") -- split sub-arrays (rows) into tables local t = {} if (textStyles) then for n,v in pairs(textStyles) do if (type(v) ~= "table") then v = "set,"..v -- Record both Mixed Case and lowercase versions of the key -- to be sure we can find it. t[lower(n)] = split(v, ",", true) t[n] = split(v, ",", true) end end else t = {} end return t else return {} end end --[[ local function getTextStyles () return textStyles or {} end ]] --[[ local function setTextStyles (t) textStyles = t or {} for n,v in pairs(textStyles) do if (type(v) ~= "table") then v = "set,"..v textStyles[n] = split(v, ",", true) end end end ]] -- Get an adjustment for a font, to position it closer to its real baseline -- Assume x-height is about 60% of the font height. local function getXHeightAdjustment (font,size) local c = "X" local t = display.newText(c,0,0,font,size) local h = t.height display.remove(t) t=nil local adj = h * 0.6 --print ("getXHeightAdjustment of '"..c.."' "..font.." at size "..size.." is "..xHeight..", ratio", r) return adj end -- Testing function to show a line and insert into group g local function showTestBox (g,x,y,len, font,size,lineHeight,fontMetrics) local fontInfo = fontMetrics.getMetrics(font) local baseline = fontInfo.baseline local yAdjustment = lineHeight -- + (-baseline * size) len = len or 100 local b = display.newRect(g, x, y, x+len, y+yAdjustment) anchor(b, "TopLeft") b.x = x b.y = y b:setFillColor(0,0,250, 0.3) print ("showTestLine: lineheight:",lineHeight) end -- Testing function to show a line and insert into group g local function showTestLine (g,x,y,t,leading) y = floor(y) leading = leading or 0 local len = 100 local b = display.newLine(g, x, y, x+len, y) b:setStrokeColor(0,0,100,0.9) local t = display.newText(g, "y="..y..":"..", "..leading..": "..t,x,y,"Georgia-Italic",9) t:setFillColor(0,0,0) end -------------------------------------------------------- -- Wrap text to a width -- Blank lines are ignored. -- -- Very important: -- text: a table of named parameters OR the text. -- -- *** To show a blank line, put a space on it. -- The minCharCount is the number of chars to assume are in the line, which means -- fewer calculations to figure out first line's. -- It starts at 25, about 5 words or so, which is probabaly fine in 99% of the cases. -- You can raise lower this for very narrow columns. -- opacity : 0.0-1.0 -- "minWordLen" is the shortest word a line can end with, usually 2, i.e, don't end with single letter words. -- NOTE: the "floor" is crucial in the y-position of the lines. If they are not integer values, the text blurs! -- -- Look for CR codes. Since clumsy XML, such as that from inDesign, cannot include line breaks, -- we have to allow for a special code for line breaks: [[[cr]]] -------------------------------------------------------- local function autoWrappedText ( p ) local textwrap = require ("scripts.textrender.textrender") return textwrap.autoWrappedText( p ) end local function capitalize(str) local function tchelper(first, rest) return first:upper()..rest:lower() end -- Add extra characters to the pattern if you need to. _ and ' are -- found in the middle of identifiers and English words. -- We must also put %w_' into [%w_'] to make it handle normal stuff -- and extra stuff the same. -- This also turns hex numbers into, eg. 0Xa7d4 str = str:gsub("(%a)([%w_']*)", tchelper) return str end -------------------------------------------------------- -- Adjust x,y for a shadow thickness. -- If an object has a drop shadow, the corner of the object will be inside the shadow area. -- So, to position the object properly at x,y we need to find the x,y that includes the shadowing. -- Scale doesn't seem to work right, so ignore it, and it will be 1, which is OK. -------------------------------------------------------- local function adjustXYforShadow (x, y, rp, shadowOffset, scale) local stringFind = find if (shadowOffset) then local shadowOffsetX = 0 local shadowOffsetY = 0 local offsetX, offsetY scale = scale or 1 --print ("a) adjustXYforShadow", x, y, rp) rp = rp:lower() -- Horizontal offsets if (stringFind(rp, "left")) then shadowOffsetX = shadowOffset elseif (stringFind(rp, "right")) then shadowOffsetX = (-1*shadowOffset) else offsetX = 0 end -- Vertical offsets if (stringFind(rp, "top")) then shadowOffsetY = shadowOffset elseif (stringFind(rp, "bottom")) then shadowOffsetY = (-1*shadowOffset) else offsetY = 0 end x = x or 0 y = y or 0 x = floor((x + shadowOffsetX) * scale) y = floor((y + shadowOffsetY) * scale) --print ("b) adjustXYforShadow adjustedment:", x, y, scale) end return x,y end -------------------------------------------------------- -- referenceAdjustedXY -- Calculate the x,y of an object when offset by a new reference point -- but without resetting the reference point of the object. -- This allow the user to spec the position of an object with x,y and -- a reference alignement, e.g. BottomRight. We do the calculations -- to correct the x,y so the object is correctly positioned, based on the -- the provided newReferencePoint (e.g. center). -------------------------------------------------------- local function referenceAdjustedXY (obj, x, y, newReferencePoint, scale, shadowOffset) local stringFind = find local rx, ry, rp, offsetX, offsetY rx = obj.xReference ry = obj.yReference if (obj and newReferencePoint) then scale = scale or 1 shadowOffset = shadowOffset or 0 local w = obj.width local h = obj.height --print ("a) referenceAdjustedXY adjustedment: x, y, newReferencePoint, scale, shadowOffset", x, y, newReferencePoint, scale, shadowOffset) rp = newReferencePoint:lower() -- Horizontal offsets if (stringFind(rp, "left")) then offsetX = w/2 - shadowOffset elseif (stringFind(rp, "right")) then offsetX = (w/-2) + shadowOffset else offsetX = 0 end -- Vertical offsets if (stringFind(rp, "top")) then offsetY = h/2 - shadowOffset elseif (stringFind(rp, "bottom")) then offsetY = (h/-2) + shadowOffset else offsetY = 0 end --x = floor( (x + offsetX) * scale) --y = floor( (y + offsetY) * scale) if (x == "center") then x = midscreenX elseif (x == "left") then x = 0 elseif (x == "right") then x = screenW end if (y == "center") then y = midscreenY elseif (y == "top") then y = 0 elseif (y == "bottom") then y = screenH end x = floor( x + (offsetX * scale)) y = floor( y + (offsetY * scale)) --print ("b) referenceAdjustedXY adjustedment:", x, y, scale, shadowOffset) end return x,y end local function fixCapsForReferencePoint(r) if (r) then r = tostring(r) r = r:gsub("top", "Top") r = r:gsub("bottom", "Bottom") r = r:gsub("left", "Left") r = r:gsub("right", "Right") r = r:gsub("center", "Center") end return r end --------------- -- positionObject -- Given user settings for x,y, return the real x,y in the space of width x height -- margins = {top,bottom,left,right} margins/padding -- x can be left, center, right, a number, or a percent -- y can be top, center, bottom, a number, or a percent -- ref is the reference point, used like this: display[ref] -- Example: x,y = positionObject("left", "center", screenW, screenH) -- *** This is based on 0,0 being the center of the space defined by w x h *** -- Default w,h is the screen. local function positionObject(x,y,w,h,margins) w = w or screenW h = h or screenH --x = funx.applyPercent(x,w) or 0 --y = funx.applyPercent(y,h) or 0 margins = margins or {top=0, bottom=0,left=0,right=0} local xpos, ypos -- Horizontal offsets if (x == "left") then xpos = w/-2 + margins.left elseif (x == "right") then xpos = (w/2) - margins.right elseif (x == "center") then xpos = 0 else xpos = applyPercent(x,w) or 0 end -- Vertical offsets if (y == "top") then ypos = h/-2 + margins.top elseif (y == "bottom") then ypos = (h/2) - margins.bottom elseif (y == "center") then ypos = 0 else ypos = applyPercent(y,h) or 0 end return xpos, ypos end --===== --- Make a margins table from a string, order is T/L/B/R, e.g. "10,20,40,20" local function stringToMarginsTable(str, default) local m default = default or {0,0,0,0} if (type(default) == "string") then m = split ( (str or default), ",") elseif (not str or str == "") then m = split ( default, ",") else m = split ( str, ",") end local margins = { top=applyPercent(m[1], screenH), left=applyPercent(m[2], screenW), bottom=applyPercent(m[3], screenH), right=applyPercent(m[4], screenW), } return margins end --------------- -- positionObjectAroundCenter -- Given user settings for x,y, return the real x,y in the space of width x height -- margins = {top,bottom,left,right} margins/padding -- x can be left, center, right, a number, or a percent -- y can be top, center, bottom, a number, or a percent -- ref is the reference point, used like this: display[ref] -- Example: x,y = positionObject("left", "center", screenW, screenH) -- *** This is based on 0,0 being the center of the space defined by w x h *** -- Default w,h is the screen. local function positionObjectAroundCenter(x,y,w,h,margins) w = w or screenW h = h or screenH --x = applyPercent(x,w) or 0 --y = applyPercent(y,h) or 0 margins = margins or {top=0, bottom=0,left=0,right=0} -- Horizontal offsets local xpos, ypos if (x == "left") then xpos = w/-2 + margins.left elseif (x == "right") then xpos = (w/2) - margins.right elseif (x == "center") then xpos = 0 else xpos = applyPercent(x,w) or 0 end -- Vertical offsets if (y == "top") then ypos = h/-2 + margins.top elseif (y == "bottom") then ypos = (h/2) - margins.bottom elseif (y == "center") then ypos = 0 else ypos = applyPercent(y,h) or 0 end return xpos, ypos end --------------- -- positionObjectWithReferencePoint -- Given user settings for x,y, return the real x,y in the space of width x height -- margins = {top,bottom,left,right} margins/padding -- x can be left, center, right, a number, or a percent -- y can be top, center, bottom, a number, or a percent -- ref is the reference point, used like this: display[ref] -- Example: x,y = positionObject("left", "center", screenW, screenH) -- This is based on 0,0 being the center of the space defined by w x h -- Default w,h is the screen. -- refPointSimpleText=true means do NOT return "ReferencePoint" with the position text, -- i.e. instead of "TopLeftReferencePoint" just return "TopLeft" -- Default is FALSE -- -- WHY BE BASED ON THE CENTER OF THE PARENT OBJECT? -- The reason we want to position based on center of the space provided is that we -- can easily center objects that way. -- Also, we can easily position something inside another group this way. If you have a -- picture inside a box, this function returns its proper position in the box, so you -- only need to set the x,y. local function positionObjectWithReferencePoint(x,y,w,h,margins, absoluteflag, refPointSimpleText) local xpos, ypos w = w or screenW h = h or screenH absoluteflag = absoluteflag or false if (not margins or absoluteflag) then margins = {left = 0, right=0, top=0, bottom=0 } end local xref = "Left" local yref = "Top" if (type(x) == "string") then x = lower(x) end if (type(y) == "string") then y = lower(y) end -- Horizontal offsets if (x == "left") then xpos = w/-2 + margins.left xref = "Left" elseif (x == "right") then xpos = (w/2) - margins.right xref = "Right" elseif (x == "center") then xpos = 0 xref = "Center" else x = applyPercent(x,w) or 0 xpos = x - (w/2) + margins.left xref = "Left" end -- Vertical offsets if (y == "top") then ypos = h/-2 + margins.top elseif (y == "bottom") then ypos = (h/2) - margins.bottom yref = "Bottom" elseif (y == "center") then ypos = 0 yref = "Center" else y = applyPercent(y,h) or 0 ypos = y - (h/2) + margins.top yref = "Top" end -- avoid "CenterCenter"... if (xref == "Center" and yref == "Center") then yref="" end --print (xpos, ypos, yref..xref.."ReferencePoint") if (refPointSimpleText) then return xpos, ypos, yref..xref else return xpos, ypos, yref..xref.."ReferencePoint" end end local function setAnchorFromReferencePoint(obj, pos) pos = lower(pos) if pos == "topleftreferencepoint" then obj.anchorX, obj.anchorY = 0, 0 elseif pos == "topcenterreferencepoint" then obj.anchorX, obj.anchorY = 0.5, 0 elseif pos == "toprightreferencepoint" then obj.anchorX, obj.anchorY = 1, 0 elseif pos == "centerleftreferencepoint" then obj.anchorX, obj.anchorY = 0, 0.5 elseif pos == "centerreferencepoint" then obj.anchorX, obj.anchorY = 0.5, 0.5 elseif pos == "centerrightreferencepoint" then obj.anchorX, obj.anchorY = 1, 0.5 elseif pos == "bottomleftreferencepoint" then obj.anchorX, obj.anchorY = 0, 1 elseif pos == "bottomcenterreferencepoint" then obj.anchorX, obj.anchorY = 0.5, 1 elseif pos == "bottomrightreferencepoint" then obj.anchorX, obj.anchorY = 1, 1 else obj.anchorX, obj.anchorY = 0.5, 0.5 end end local function convertAnchorToReferencePointName (obj) local post = "" if ( {obj.anchorX, obj.anchorY} == {0, 0} ) then post = "TopLeftReferencePoint" elseif ( {obj.anchorX, obj.anchorY} == {0.5, 0} ) then post = "TopCenterReferencePoint" elseif ( {obj.anchorX, obj.anchorY} == {1, 0} ) then post = "TopRightReferencePoint" elseif ( {obj.anchorX, obj.anchorY} == {0, 0.5} ) then post = "CenterLeftReferencePoint" elseif ( {obj.anchorX, obj.anchorY} == {0.5, 0.5} ) then post = "CenterReferencePoint" elseif ( {obj.anchorX, obj.anchorY} == {1, 0.5} ) then post = "CenterRightReferencePoint" elseif ( {obj.anchorX, obj.anchorY} == {0.5, 1} ) then post = "BottomCenterReferencePoint" elseif ( {obj.anchorX, obj.anchorY} == {1, 1} ) then post = "BottomRightReferencePoint" end return post end ------------------------------------------------------- -- Reanchor to new point -- This version of reanchoring adjusts the x,y of an object for a new anchor point, using -- anchorX and anchorY local function reanchor(obj, ax, ay) local dx, dy = obj.anchorX - ax, obj.anchorY - ay local newX = obj.x - (dx * obj.width) local newY = obj.y - (dy * obj.height) obj.anchorX, obj.anchorY = ax, ay obj.x = newX obj.y = newY end -- Keep an object in the same place on screen while changing its anchor point. -- This is useful if an object is positioned Top Left (0,0), then we want to change the -- anchor point but not change the objects position on screen. local function reanchorToCenter (obj, a, x, y) if not a then return x,y; end if (lower(a) == "centerreferencepoint") then return x,y end -- old anchor values, and x,y local oaX, oaY = obj.anchorX, obj.anchorY -- x = x or obj.x -- y = y or obj.y -- a is a table, then it is an anchor point, else it is the name of a reference point -- if (type(a) == "table") then -- obj.anchorX, obj.anchorY = a.x, a.y -- else -- setAnchorFromReferencePoint(obj, a) -- end -- new anchor values local naX, naY = 0.5, 0.5 -- -- -- Get width/height local ac = obj.anchorChildren obj.anchorChildren = true local width, height = obj.width, obj.height obj.anchorChildren = ac -- distance from top-left local deltaX = (naX * width) - (oaX * width) local deltaY = (naY * height) - (oaY * height) local x = x + deltaX local y = y + deltaY return x,y end ---------------------------------------------------------------------- -- Picture Corners -- Given a width/height, build picture corners to fit. -- filenames are of each corner -- offsets specify positioning correction -- 0,0 of the corners is the CENTER! local function buildPictureCorners (w,h, filenames, offsets) local g = display.newGroup() local imageTL = display.newImage(g, filenames.TL) local imageTR = display.newImage(g, filenames.TR) local imageBL = display.newImage(g, filenames.BL) local imageBR = display.newImage(g, filenames.BR) anchor(imageTL, "TopLeft") imageTL.x = floor(0 + offsets.TLx - w/2); imageTL.y = floor(0 + offsets.TLy - h/2); anchor(imageTR, "TopRight") imageTR.x = ceil(w/2 + offsets.TRx); imageTR.y = floor(-h/2 + offsets.TRy); anchor(imageBL, "BottomLeft") imageBL.x = floor(-w/2 + offsets.BLx); imageBL.y = ceil(h/2 + offsets.BLy); anchor(imageBR, "BottomRight") imageBR.x = ceil(w/2 + offsets.BRx); imageBR.y = ceil(h/2 + offsets.BRy); return g end ---------------------------------------------------------------------- ---------------------------------------------------------------------- -- TESTING TOOLS: -- Print local vs. stage coordinates by touching an object. local function showContentToLocal(obj, state) local function showCoordinates( event ) -- Get x, y of touch event in content coordinates local contentx, contenty = event.x, event.y -- Convert to local coordinates of local localx, localy = event.target:contentToLocal(contentx, contenty) -- Display content and local coordinate values print ("showContentToLocal (content=>local): ", contentx..", "..contenty, "=>", floor(localx) ..", ".. floor(localy), ":", obj.localX ) return true end if (state == "toggle") then state = not obj._showContentToLocal end if (state) then print ("showContentToLocal: on") obj:addEventListener("touch", showCoordinates) obj._showContentToLocal = true else print ("showContentToLocal: off") obj:removeEventListener("touch", showCoordinates) obj._showContentToLocal = false end end ------------------------------------------------------------ ------------------------------------------------------------ -- Alert the user that something significant has happened by flashing the screen to white. local function flashscreen(t,a) t = t or 100 a = a or 0.5 local r = display.newRect(0,0,screenW,screenH) anchorZero(r, "TopLeft") r.alpha = 0 local function removeFlasher() r:removeSelf() r = nil end local function fadeOutAgain() transition.to(r, { alpha = 0, time=t, onComplete=removeFlasher } ) end -- Fade In the white screen transition.to(r, { alpha = a, time=t, onComplete = fadeOutAgain } ) end ------------------------------------------------------------ ------------------------------------------------------------ -- Use the file suffix to determine a file type, -- e.g. xxx.m4a is sound, m4v is video, jpg is image -- We only handle really common formats that iOS likes, so -- don't expect to handle everything. And, mp4 could be either, -- so I'm using audio for it. -- Return FALSE if the type is unknown -- NOTE: we're checking for 3 letter suffixes, so .html will mess up...use ".htm" local function mediaFileType(f) local suffix = substring(f, strlen(f)-3, -1) local t = { jpg="image", png="image", mov="video", m4v="video", m4a="audio", mp4="audio", mp3="audio", aac="audio", wav="audio", txt="text", htm="html", } if (suffix) then return t[suffix] else return false end end ----------- -- Make a directory to hold something new -- Use a handy prefix for future selecting of the type of dir, -- e.g. all "o_..." dirs -- dirname: path INSIDE the system.DocumentsDirecotyr (or systemdir) -- unique: if the directory exists, make a unique version -- systemdir: Default to the system.DocumentsDirectory local function mkdir (dirname, prefix, unique, systemdir) local systemdir = systemdir or system.DocumentsDirectory if (prefix == nil) then prefix = "o_" end -- Use a unique-ish file name if necessary local mydirname = dirname or os.time() .. "_" ..os.clock() local temp_path = system.pathForFile( mydirname, systemdir ) if (unique) then -- Does the path already exist? If so, modify to be sure it is unique while ( lfs.chdir( temp_path ) ) do mydirname = dirname .. "_" .. os.time() .. "_" ..os.clock() temp_path = system.pathForFile( mydirname, systemdir ) end elseif (lfs.chdir( temp_path )) then -- we're done, return the name of the directory return mydirname end -- Change to documents directory --local temp_path = system.pathForFile( "", system.TemporaryDirectory ) local temp_path = system.pathForFile( "", systemdir ) -- change current working directory local success = lfs.chdir( temp_path ) -- returns true on success local new_folder_path if success then lfs.mkdir( mydirname ) new_folder_path = lfs.currentdir() .. "/"..mydirname return mydirname else return false end end ------------------------------------------------------------ ------------------------------------------------------------ -- Make cover up bars for differenly shaped screens -- Color is a color string "R,G,B" local function coverUpScreenEdges(color) color = color or "0,0,0" --color = "200,30,30" local c = stringToColorTable(color) -- Put cover-up bars for a different screen shape. local deviceWidth = round(( display.contentWidth - (display.screenOriginX * 2) ) / display.contentScaleX) local deviceHeight = round(( display.contentHeight - (display.screenOriginY * 2) ) / display.contentScaleY) local actualWidth = deviceWidth * display.contentScaleX local actualHeight = deviceHeight * display.contentScaleY -- Don't make bars if no need for them if (screenW == actualWidth and screenH == actualHeight) then return false end local coverup = display.newGroup() local barWidth = (actualWidth - screenW)/2 local barL = display.newRect(coverup, 0,0,barWidth,screenH) local barR = display.newRect(coverup, 0,0,barWidth,screenH) barL:setFillColor(c[1],c[2], c[3]) barR:setFillColor(c[1],c[2], c[3]) anchor(barL, "TopLeft") anchor(barR, "TopLeft") barL.x = -barWidth barL.y = 0 barR.x = screenW barR.y = 0 --[[ local o = system.orientation if ( o == "portrait" or o == "portraitUpsideDown" ) then coverup.rotation = 90 end --]] return coverup end ------------------------------------------------- ------------------------------------------------- -- Special Strokes around objects -- Designed to go behind an image, not in front. -- params may include: -- stroke width (stroke) -- params MUST tell us what kind of object, e.g. "rectangle", etc. -- Styles: -- solid : a stroke 100% outside the image (not like a Corona stroke that is on the edge) -- thin-thick : 25% inner stroke, 50% out, with 25% padding -- thick-thin : 50% inner stroke, 25% out, with 25% padding -- The matte color is for a matte around the image. The tintColor is laid over the group, tinting it. --[[ @param obj A display group to frame @param params A table, params = { stroke = integer, style = solid | thick-thin | thin-thick, color = RGBAColorString, matteColor = RGBAColorString, tintColor = RGBAColorString, matte = integer, } --]] local function strokeGroupObject(obj,params) local floor = floor local function framingObject(o, padding, fillcolor, strokeWidth, strokeColor) local dup = display.newRect(0,0,o.contentWidth+(2*padding), o.contentHeight+(2*padding)) dup:setFillColor(fillcolor[1], fillcolor[2], fillcolor[3], fillcolor[4]) dup.strokeWidth = strokeWidth dup:setStrokeColor(strokeColor[1], strokeColor[2], strokeColor[3], strokeColor[4]) return dup end -- Default is transparent fill for stroking boxes local color = stringToColorTable(params.color or "0,0,0") local tintColor = stringToColorTable(params.tintColor or "0,0,0,0") local mattecolor = stringToColorTable(params.matteColor or "255,255,255,100%") params.stroke = params.stroke or 0 params.matte = params.matte or 0 -- The frame local temp -- FRAME local f = display.newGroup() --f.anchorChildren = true local w,h = obj.contentWidth, obj.contentHeight params.style = lower(params.style) if ( params.style == "solid") then local fr = display.newRect(f, 0,0, w + params.stroke, h + params.stroke) fr.strokeWidth = params.stroke or 0 fr:setStrokeColor(color[1], color[2], color[3], color[4]) if (mattecolor) then fr:setFillColor(mattecolor[1], mattecolor[2], mattecolor[3], mattecolor[4]) end elseif (params.style == "thick-thin") then local sw = params.stroke or 0 local innerW = floor(sw * 0.5) or 1 local outerW = floor(sw * 0.25) or 1 local padding = (sw-(innerW + outerW)) or 1 local innerFrame = display.newRect(f, 0,0, w + innerW - 1, h + innerW - 1 ) innerFrame.strokeWidth = innerW innerFrame:setStrokeColor(color[1], color[2], color[3], color[4]) if (mattecolor) then innerFrame:setFillColor(mattecolor[1], mattecolor[2], mattecolor[3], mattecolor[4]) end local outerOffset = innerW + padding + outerW/2 local outerFrame = display.newRect(f, 0,0, w - 1 + 2*outerOffset, h - 1 + 2*outerOffset) outerFrame.strokeWidth = outerW outerFrame:setStrokeColor(color[1], color[2], color[3], color[4]) outerFrame:setFillColor(255) outerFrame:toBack() elseif (params.style == "thin-thick") then local sw = params.stroke or 0 local innerW = floor(sw * 0.25) or 1 local outerW = floor(sw * 0.5) or 1 local padding = (sw-(innerW + outerW)) or 1 local innerFrame = display.newRect(f, 0,0, w + innerW, h + innerW ) innerFrame.strokeWidth = innerW innerFrame:setStrokeColor(color[1], color[2], color[3], color[4]) if (mattecolor) then innerFrame:setFillColor(mattecolor[1], mattecolor[2], mattecolor[3], mattecolor[4]) end local outerOffset = innerW + padding + outerW/2 local outerFrame = display.newRect(f, 0,0, w + 2*outerOffset, h + 2*outerOffset) outerFrame.strokeWidth = outerW outerFrame:setStrokeColor(color[1], color[2], color[3], color[4]) outerFrame:setFillColor(255) outerFrame:toBack() end temp = obj.anchorChildren obj.anchorChildren = true obj:insert(f) f:toBack() obj.anchorChildren = temp return f end ------------------------------------------------- -- Convert "left", "center", "right" to numerics or percentages local function positionByName(t, margins, absoluteflag) if (not margins or absoluteflag) then margins = {left = 0, right=0, top=0, bottom=0 } end local v = "" if (t == "left" ) then v = margins.left elseif (t == "top") then v = margins.top elseif (t == "center") then v = "50%" elseif (t == "bottom") then v = margins.bottom elseif (t == "right") then v = margins.right else v = t end return v end ------------------------------------------------- -- cleanPath: clean up a path local function cleanPath (p) if (p) then local substring = substring p = p:gsub("/\./","/") p = p:gsub("//","/") p = p:gsub("/\.$","") return p end end ------------------------------------------------- -- joinAsPath: make a path from different elements of a table. -- Useful to join pieces together, e.g. server + path + filename -- If username/password are passed, add them to the URL, e.g. username:password@restofurl local function joinAsPath( pieces, username, password) trim(pieces) for i = #pieces, 1, -1 do if (pieces[i] == nil or pieces[i] == "") then table.remove(pieces, i) end end local path = cleanPath(table.concat(pieces, "/")) local pre = table.concat({username,password},":") if (pre ~= "") then path = pre .. "@" .. path end return path end ------------------------------------------------- -- Pure Lua version of dirname. -- local function dirname(path) while true do if path == "" or substring(path, -1) == "/" or -- find(path, "^/\..") or -- substring(path, -2) == "/." or substring(path, -3) == "/.." or (substring(path, -1) == "." and strlen(path) == 1) or (substring(path, -2) == ".." and strlen(path) == 2) then break end path = substring(path, 1, -2) end if path == "" then path = "." end if substring(path, -1) ~= "/" then path = path .. "/" end return path end ------------------------------------------------- -- basename() -- Returns trailing name component of path -- Extract my/dir/bottomdir => bottomdir local function basename (path) path = gsub(path, "%/$", "") path = "/"..path local d = gsub(path, "^.*/","") return d end ------------------------------------------------- -- Copy File (binary copy) -- This is a binary file copy local function copyFile (src, srcPath, srcBaseDir, target, targetBaseDir) local size = 2^13 local sourcePath = system.pathForFile( nil, srcBaseDir ) .. "/"..srcPath.."/"..src local targetPath = system.pathForFile( nil, targetBaseDir ) .. "/"..target.."/"..src local f = assert(io.open(sourcePath, "rb")) local out = assert(io.open(targetPath, "wb")) while true do local block = f:read(size) if not block then break end out:write(block) end assert(f:close()) assert(out:close()) end ------------------------------------------------- -- Copy a directory -- Create a copy of the directory 'src' inside of the directory 'target' local function copyDir (src, srcBaseDir, target, targetBaseDir, newname) srcBaseDir = srcBaseDir or system.CachesDirectory targetBaseDir = targetBaseDir or system.CachesDirectory local srcBaseName = basename(src.."/") newname = newname or srcBaseName -- make a dir inside the target container directory, -- e.g. make "mydir" inside "mytarget" to get "mytarget/mydir" local sbase = system.pathForFile( nil, srcBaseDir ) local tbase = system.pathForFile( nil, targetBaseDir ) local targetPath = tbase .. "/" .. target .. "/" --print ("copyDir:",sbase, targetPath) local res, err = lfs.chdir(targetPath) if (not res) then print ("ERROR: copyDir tried to change directories to "..targetPath.." but failed: "..err) return false else res, err = lfs.mkdir( newname ) end --if (err) then print (err) end local s = src local t = target local srcPath = sbase .. "/" .. src local res = lfs.chdir (srcPath) local allowDotFiles = false if (res) then local filename for filename in lfs.dir(srcPath) do local res = lfs.chdir (srcPath) if (res and allowDotFiles or substring(filename, 1, 1) ~= ".") then if (filename ~= "." and filename ~= ".." ) then local attr = lfs.attributes (filename) if (attr.mode == "directory") then -- make dir in new location copyDir (s.."/"..filename, srcBaseDir, t.."/"..newname, targetBaseDir) else -- copy a file copyFile (filename, s, srcBaseDir, t.."/"..newname, targetBaseDir) end end end end end end ------------------------------------------------- -- Delete a directory even if not empty -- If keepDir is true, then only delete the contents local function rmDir(dir,path, keepDir) path = path or system.DocumentsDirectory local doc_path = system.pathForFile( dir, path ) local res = lfs.chdir (doc_path) if (res) then for filename in lfs.dir(doc_path) do if (filename ~= "." and filename ~= ".." ) then lfs.chdir (doc_path) local attr = lfs.attributes (filename) if (attr.mode == "directory") then rmDir(dir.."/"..filename, path) else lfs.chdir (doc_path) local results, reason = os.remove(doc_path .. "/" .. filename, system.DocumentsDirectory) end end end if (not keepDir) then local results, reason = os.remove(doc_path) end end end ----------- -- Make a directory Tree -- If we ask for "dirA/dirB/dirC", we might need to create dirA and dirB before creating -- dirC. local function mkdirTree (dirname, systemdir) systemdir = systemdir or system.CachesDirectory dirname = cleanPath(dirname) local dirs = split(dirname,"/") local nextDir local currDir = "" for i=1,#dirs do local nextDir = currDir.."/"..dirs[i] local fullpath = system.pathForFile( nextDir, systemdir ) if (fullpath and lfs.chdir( fullpath ) ) then currDir = nextDir else local success = lfs.chdir( system.pathForFile( currDir, systemdir ) ) if (success) then local success = lfs.mkdir( dirs[i] ) if (success) then currDir = nextDir else print ("ERROR: mkdirTree: Cannot create directory: "..nextDir) end else print ("ERROR: mkdirTree: Cannot find directory: "..currDir) end end end end local function url_decode(str) str = gsub (str, "+", " ") str = gsub (str, "%%(%x%x)", function(h) return char(tonumber(h,16)) end) str = gsub (str, "\r\n", "\n") return str end local function url_encode(str) if (str) then str = gsub (str, "\n", "\r\n") str = gsub (str, "([^%w ])", function (c) return format ("%%%02X", string.byte(c)) end) str = gsub (str, " ", "+") end return str end local function newArc(x,y,w,h,s,e) local xc,yc,cos,sin = x+w/2,y+h/2,math.cos,math.sin s,e = s or 0, e or 360 s,e = math.rad(s),math.rad(e) w,h = w/2,h/2 local l = display.newLine(0,0,0,0) for t=s,e,0.02 do l:append(xc + w*cos(t), yc - h*sin(t)) end return l end -- Call like this: setFillColorFromString(obj, "10,20,30,30%") -- All values can be number or percent local function setFillColorFromString(obj, cstring) local s = stringToColorTable(cstring) if (obj.setFillColor) then obj:setFillColor(s[1], s[2], s[3], s[4]) else obj:setFillColor(s[1], s[2], s[3], s[4]) end end local function getDeviceMetrics( ) -- See: http://en.wikipedia.org/wiki/List_of_displays_by_pixel_density local corona_width = -display.screenOriginX * 2 + display.contentWidth local corona_height = -display.screenOriginY * 2 + display.contentHeight --print("Corona unit width: " .. corona_width .. ", height: " .. corona_height) -- I was rounding these, on the theory that they would always round to the correct integer pixel -- size, but I noticed that in practice it rounded to an incorrect size sometimes, so I think it's -- better to use the computed fractional values instead of possibly introducing more error. -- local pixel_width = corona_width / display.contentScaleX local pixel_height = corona_height / display.contentScaleY --print("Pixel width: " .. pixel_width .. ", height: " .. pixel_height) local model = system.getInfo("model") local default_device = { model = model, inchesDiagonal = 4.0, } -- Approximation (assumes average sized phone) local devices = { { model = "iPhone", inchesDiagonal = 3.5, }, { model = "iPad", inchesDiagonal = 9.7, }, { model = "iPod touch", inchesDiagonal = 3.5, }, { model = "Nexus One", inchesDiagonal = 3.7, }, { model = "Nexus S", inchesDiagonal = 4.0, }, -- Unverified model value { model = "Droid", inchesDiagonal = 3.7, }, { model = "Droid X", inchesDiagonal = 4.3, }, -- Unverified model value { model = "Galaxy Tab", inchesDiagonal = 7.0, }, { model = "Galaxy Tab X", inchesDiagonal = 10.1, }, -- Unverified model value { model = "Kindle Fire", inchesDiagonal = 7.0, }, { model = "Nook Color", inchesDiagonal = 7.0, }, } local device = default_device for _, deviceEntry in pairs(devices) do if deviceEntry.model == model then device = deviceEntry end end -- Pixel width, height, and pixels per inch device.pixelWidth = pixel_width device.pixelHeight = pixel_height device.ppi = math.sqrt((pixel_width^2) + (pixel_height^2)) / device.inchesDiagonal -- Corona unit width, height, and "Corona units per inch" device.coronaWidth = corona_width device.coronaHeight = corona_height device.cpi = math.sqrt(corona_width^2 + corona_height^2)/device.inchesDiagonal --print("Device: " .. device.model .. ", size: " .. device.inchesDiagonal .. " inches, ppi: " .. device.ppi .. ", cpi: " .. device.cpi) return device end -- This makes a mask for a widget.scrollView local function makeMask(width, height, maskDirectory) -- Display.save uses the screen size, so a retina will save a double-size image than what we need maskDirectory = maskDirectory or "_masks" local baseDir = system.CachesDirectory local maskfilename = maskDirectory .. "/" .. "mask-"..width.."-"..height..".jpg" if (not fileExists(maskfilename, baseDir) ) then mkdirTree (maskDirectory, baseDir) local g = display.newGroup() local scalingRatio = scaleFactorForRetina() width = width * scalingRatio height = height * scalingRatio local mask = display.newRect(g, 0,0,width+4, height+4 ) mask:setFillColor(0) local opening = display.newRect(g, 0,0,width, height ) opening:setFillColor(255) anchor(opening, "TopLeft") opening.x = 2 opening.y = 2 display.save( g, maskfilename, baseDir ) g:removeSelf() end return maskfilename end -- This makes a mask for a rectangle on the screen at a particular x,y local function makeMaskForRect(x,y,width, height, maskDirectory, maskfilename, baseDir) -- Display.save uses the screen size, so a retina will save a double-size image than what we need x = math.max(x,0) y = math.max(y,0) maskDirectory = maskDirectory or "_masks" maskfilename = maskfilename or "mask-" .. width .. "x" .. height .. "@" .. x .. "," .. y .. "-" ..screenW.."x"..screenH..".png" local baseDir = baseDir or system.CachesDirectory local maskfilename = maskDirectory .. "/" .. maskfilename if (not fileExists(maskfilename, baseDir) ) then mkdirTree (maskDirectory, baseDir) local g = display.newGroup() -- Mask sizing. Needs min. 3px on each side, must be divisible by 4 local bw = math.max(display.contentWidth, 4*math.ceil((width+6)/4) ) local bh = math.max(display.contentHeight, 4*math.ceil((height+6)/4) ) if (bw > display.contentWidth or bh > display.contentHeight) then print ("ERROR: funx.makeMaskForRect: Cannot create a mask larger than the display. This mask won't work.") end local scalingRatio = scaleFactorForRetina() bw = bw * scalingRatio bh = bh * scalingRatio width = width * scalingRatio height = height * scalingRatio -- black background. local mask = display.newRect(g, 0,0, bw, bh ) mask:setFillColor(0) anchor(mask, "TopLeft") -- opening local opening = display.newRect(g, 0,0,width, height ) opening:setFillColor(255) anchor(opening, "TopLeft") opening.x = x + 3 opening.y = y + 3 display.save( g, maskfilename, baseDir ) g:removeSelf() end return maskfilename end -- This requires a generic mask file!!!! --- Masking using a single mask file, from the Corona SDK forum -- @params (table) object = object to mask, width/height = of mask, --[[ local OPTIONS_LIST_HEIGHT = 300 local OPTIONS_LIST_HEIGHT = 200 local thingToMask = somedisplayobject applyMask({ object = thingToMask, width = OPTIONS_LIST_WIDTH, height = OPTIONS_LIST_HEIGHT }) --]] local function applyMask(params) local GENERIC_MASK_FILE = "_ui/generic-mask-1024x768.png" local generic_mask_width = 1024 local generic_mask_height = 768 if params.object == nil then return end if params.width == nil then params.width = params.object.width end if params.height == nil then params.height = params.object.height end if params.mask == nil then params.mask = "_ui/generic-mask-1024x768.png" end local myMask = graphics.newMask(params.mask) params.object:setMask(myMask) params.object.maskScaleX = params.width/generic_mask_width params.object.maskScaleY = params.height/generic_mask_height --there may be a need in the future add logic to the positioning for different reference points params.object.maskX = 0 --params.width/2 params.object.maskY = 0 --params.height/2 end -- DOES NOT WORK local function translateHTMLEntity(s) local _ENTITIES = { ["&lt;"] = "<", ["&gt;"] = ">", ["&amp;"] = "&", ["&quot;"] = '"', ["&apos;"] = "'", ["&bull;"] = char(149), ["&dash;"] = char(150), ["&mdash;"] = char(151), ["&#(%d+);"] = function (x) local d = tonumber(x) if d >= 0 and d < 256 then return char(d) else return "&#"..d..";" end end, ["&#x(%x+);"] = function (x) local d = tonumber(x,16) if d >= 0 and d < 256 then return char(d) else return "&#x"..x..";" end end, } -- Replace the entities found in s for k,v in pairs(_ENTITIES) do --print (k, v) s = gsub(s,k,v) end return s end local function checksum(str) local temp = 0 local weight = 10 for i = 1, strlen(str) do local c = str:byte(i,i) temp = temp + c * weight weight = weight - 1 end --[[ temp = 11 - (temp % 11) if temp == 10 then return "X" else if temp == 11 then return "0" else return tostring(temp) end end --]] return temp end -- Get status bar height. -- Problem is, if the bar is hidden, the height is zero local function getStatusBarHeight() local t = display.topStatusBarContentHeight if (t == 0) then display.setStatusBar( display.DefaultStatusBar ) t = display.topStatusBarContentHeight display.setStatusBar( display.HiddenStatusBar ) end return t end ----------------------------------- -- Clear all contents of the directory local function deleteDirectoryContents(dir, whichSystemDirectory) whichSystemDirectory = whichSystemDirectory or system.CachesDirectory rmDir(dir, whichSystemDirectory, true) --print ("deleteDirectoryContents", dir) end --- Get a random set from a table -- Check the validity of each key, does it exist in the db param? -- The db should be { key1 = value, key2 = value, ...} -- @param src table = { key1, key2, ... } -- @param n number of elements of src to use -- @param db key-value table to check for validity -- @param indexOrdered (Boolean) If true, index result using ordered numbers not source keys. If indexed by keys, the result will be a key/value set using keys from src. Otherwise, result will be indexed numerically, starting at 1. local function getRandomSet(src, n, db, indexOrdered) local keys = {} local i = 1 for k,v in pairs(src) do if ( (not db) or db[v]) then keys[i] = {key=k,val=v} i=i+1 end end local set = {} n = min(n, #keys) for i = 1,n do local k = random(#keys) if (indexOrdered) then set[#set+1] = keys[k].val else set[ keys[k].key ] = keys[k].val end table.remove(keys,k) end return set end local function getFirstElement(t) local res for i,j in pairs (t) do res = {i,j} break end return res[1], res[2] end -- ==================================================================== -- Check multiple paths for a file -- Used to look for book files in multiple places, hierarchically, -- e.g. look first in _user/books/ then on shelves -- Default with no values is to return the default book. -- @param locations Table: { 1 = { path = "path/to/book/folders", bookDir = "bookfolder", systemDirectory = system.ResourceDirectory }, ... } -- Example: -- findFile ( "book.xml", "_user/books" , "_user" ) -- ==================================================================== local function findFile (filename, locations, default) default = default or "_user" if (not filename or not locations or type(locations) ~= "table") then return { path = default, systemDirectory = system.ResourceDirectory } end local p for i,loc in pairs(locations) do if (loc.bookDir == "default" or loc.bookDir == "" ) then return default, system.ResourceDirectory end --print ("Look for ", joinAsPath{loc.path, loc.bookDir, filename} ) if ( fileExists( joinAsPath{loc.path, loc.bookDir, filename}, loc.systemDirectory) ) then --print ("Found ", filename, "in", loc.path .. loc.bookDir) return loc.path, loc.systemDirectory else --print ("NOT FOUND AT ", joinAsPath{loc.path, loc.bookDir, filename}) end end return false end -- ==================================================================== -- Set case of some text using CSS case names, --none No capitalization. The text renders as it is. This is default --capitalize Transforms the first character of each word to uppercase --uppercase Transforms all characters to uppercase --lowercase Transforms all characters to lowercase --initial Sets this property to its default value. Read about initial --inherit Inherits this property from its parent element. -- -- Synonyms : title, normal -- ==================================================================== local function setCase(case, str) if case and case ~= "" and case ~= "none" then case = lower(trim(case)) if (case == "lowercase") then str = lower(str) elseif (case == "uppercase") then str = upper(str) elseif (case == "capitalize" or case == "title") then -- turns out we added this earlier to FUNX str = capitalize(str) end end return str end ------------------------------------------------------------ ------------------------------------------------------------ -- Alert the user that something significant has happened by flashing an object function FUNX.flashObject(obj, t, a) if (obj._flashObject == true) then return end obj._flashObject = true t = t or 100 a = a or 0.5 obj._originalAlpha = obj.alpha local function removeFlasher() obj._originalAlpha = nil obj._flashObject = nil end local function fadeOutAgain() transition.to(obj, { alpha = obj._originalAlpha, time=t, onComplete=removeFlasher } ) end -- Fade In the white screen transition.to(obj, { alpha = a, time = t, onComplete = fadeOutAgain } ) end -- ==================================================================== -- Tables of values -- ==================================================================== FUNX.hardwareInfo = hardwareInfo -- ==================================================================== -- Register new functions here -- ==================================================================== FUNX.activityIndicator = activityIndicator FUNX.activityIndicatorOff = activityIndicatorOff FUNX.activityIndicatorOn = activityIndicatorOn FUNX.AddCommas = AddCommas FUNX.addPosRect = addPosRect FUNX.adjustXYforShadow = adjustXYforShadow --FUNX.anchorBottomLeftZero = anchorBottomLeftZero --FUNX.anchorBottomLeft = anchorBottomLeft --FUNX.anchorBottomRightZero = anchorBottomRightZero --FUNX.anchorBottomRight = anchorBottomRight --FUNX.anchorBottomCenterZero = anchorBottomCenterZero --FUNX.anchorBottomCenter = anchorBottomCenter -- --FUNX.anchorCenter = anchorCenter --FUNX.anchorCenterZero = anchorCenterZero -- --FUNX.anchorTopCenter = anchorTopCenter --FUNX.anchorTopCenterZero = anchorTopCenterZero --FUNX.anchorTopLeft = anchorTopLeft --FUNX.anchorTopLeftZero = anchorTopLeftZero --FUNX.anchorTopRight = anchorTopRight --FUNX.anchorTopRightZero = anchorTopRightZero FUNX.anchor = anchor FUNX.anchorZero = anchorZero FUNX.applyMask = applyMask FUNX.applyPercent = applyPercent FUNX.applyPercentIfSet = applyPercentIfSet FUNX.autoWrappedText = autoWrappedText FUNX.basename = basename FUNX.buildPictureCorners = buildPictureCorners FUNX.buildShadow = buildShadow --FUNX.buildShadowObj = buildShadowObj FUNX.buildTextDisplayObjectsFromTemplate = buildTextDisplayObjectsFromTemplate FUNX.callClean = callClean FUNX.canConnectWithServer = canConnectWithServer FUNX.capitalize = capitalize FUNX.centerInParent = centerInParent FUNX.checkScale = checkScale FUNX.checksum = checksum FUNX.cleanGroups = cleanGroups FUNX.cleanPath = cleanPath FUNX.copyDir = copyDir FUNX.copyFile = copyFile FUNX.coverUpScreenEdges = coverUpScreenEdges FUNX.crypt = crypt FUNX.datetime_to_unix_time = datetime_to_unix_time FUNX.deleteDirectoryContents = deleteDirectoryContents FUNX.dimScreen = dimScreen FUNX.dirname = dirname FUNX.newArc = newArc FUNX.dump = dumptable FUNX.escape = escape FUNX.fadeIn = fadeIn FUNX.fadeOut = fadeOut FUNX.fileExists = fileExists FUNX.findFile = findFile FUNX.fixCapsForReferencePoint = fixCapsForReferencePoint FUNX.flashscreen = flashscreen FUNX.formatDate = formatDate FUNX.frameGroup = frameGroup FUNX.get_date_parts = get_date_parts FUNX.getday_posfix = getday_posfix FUNX.getDeviceMetrics = getDeviceMetrics FUNX.getDisplayObjectParams = getDisplayObjectParams FUNX.getElementName = getElementName FUNX.getEscapedKeysForGsub = getEscapedKeysForGsub FUNX.getFinalSizes = getFinalSizes FUNX.getFirstElement = getFirstElement FUNX.getImageSize = getImageSize FUNX.getmonth = getmonth FUNX.getRandomSet = getRandomSet FUNX.getScaledFilename = getScaledFilename FUNX.getStatusBarHeight = getStatusBarHeight --FUNX.getTextStyles = getTextStyles FUNX.getValue = getValue FUNX.getXHeightAdjustment = getXHeightAdjustment FUNX.hasFieldCodes = hasFieldCodes FUNX.hasFieldCodesSingle = hasFieldCodesSingle FUNX.hasNetConnection = hasNetConnection FUNX.hideObject = hideObject FUNX.indexOfSystemDirectory = indexOfSystemDirectory FUNX.initSystemEventHandler = initSystemEventHandler FUNX.inTable = inTable FUNX.isPercent = isPercent FUNX.isTable = isTable FUNX.joinAsPath = joinAsPath FUNX.keysExistInTable = keysExistInTable FUNX.lazyLoad = lazyLoad FUNX.lines = lines FUNX.loadData = loadData FUNX.readFile = readFile FUNX.loadImageFile = loadImageFile FUNX.loadTable = loadTable FUNX.loadTableFromFile = loadTableFromFile FUNX.loadTextStyles = loadTextStyles FUNX.ltrim = ltrim FUNX.makeMask = makeMask FUNX.makeMaskForRect = makeMaskForRect FUNX.mediaFileType = mediaFileType FUNX.mkdir = mkdir FUNX.mkdirTree = mkdirTree FUNX.OLD_substitutionsSLOWER = OLD_substitutionsSLOWER FUNX.openURLWithConfirm = openURLWithConfirm FUNX.pairsByKeys = pairsByKeys FUNX.percent = percent FUNX.percentOfScreenHeight = percentOfScreenHeight FUNX.percentOfScreenWidth = percentOfScreenWidth FUNX.popup = popup FUNX.popupDisplayGroup = popupDisplayGroup FUNX.popupWebpage = popupWebpage FUNX.positionByName = positionByName FUNX.positionObject = positionObject FUNX.positionObjectAroundCenter = positionObjectAroundCenter FUNX.positionObjectWithReferencePoint = positionObjectWithReferencePoint FUNX.setAnchorFromReferencePoint = setAnchorFromReferencePoint FUNX.convertAnchorToReferencePointName = convertAnchorToReferencePointName FUNX.reanchor = reanchor FUNX.reanchorToCenter = reanchorToCenter FUNX.printFuncName = printFuncName FUNX.ratioToFitMargins = ratioToFitMargins FUNX.referenceAdjustedXY = referenceAdjustedXY FUNX.removeFields = removeFields FUNX.removeFieldsSingle = removeFieldsSingle FUNX.removeFromTable = removeFromTable FUNX.replaceWildcard = replaceWildcard FUNX.rescaleFromIpad = rescaleFromIpad FUNX.resizeFromIpad = resizeFromIpad FUNX.rmDir = rmDir FUNX.round = round FUNX.round2 = round2 FUNX.rtrim = rtrim FUNX.saveData = saveData FUNX.saveTable = saveTable FUNX.saveTableToFile = saveTableToFile FUNX.scaleFactorForRetina = scaleFactorForRetina FUNX.scaleObjectToMargins = scaleObjectToMargins FUNX.ScaleObjToSize = ScaleObjToSize FUNX.setCase = setCase FUNX.setFillColorFromString = setFillColorFromString --FUNX.setTextStyles = setTextStyles FUNX.showContentToLocal = showContentToLocal FUNX.showTestBox = showTestBox FUNX.showTestLine = showTestLine FUNX.shrinkAway = shrinkAway FUNX.spinner = spinner FUNX.spinner = spinner FUNX.split = split FUNX.stringToColorTable = stringToColorTable FUNX.stringToColorTableHDR = stringToColorTableHDR FUNX.stringToMarginsTable = stringToMarginsTable FUNX.stripCommandLinesFromText = stripCommandLinesFromText FUNX.strokeGroupObject = strokeGroupObject FUNX.flattenTable = flattenTable FUNX.substitutions = substitutions FUNX.table_multi_sort = table_multi_sort FUNX.table_sort = table_sort FUNX.tableConvertValuesToKeys = tableConvertValuesToKeys FUNX.tableCopy = tableCopy FUNX.tableIsEmpty = tableIsEmpty FUNX.tablelength = tablelength FUNX.tableMerge = tableMerge FUNX.tableRemoveUnusedCodedElements = tableRemoveUnusedCodedElements FUNX.tableSubstitutions = tableSubstitutions FUNX.tellUser = tellUser FUNX.timePassed = timePassed FUNX.toggleObject = toggleObject FUNX.toZero = toZero FUNX.traceback = traceback FUNX.translateHTMLEntity = translateHTMLEntity FUNX.trim = trim FUNX.undimScreen = undimScreen FUNX.unescape = unescape FUNX.unloadModule = unloadModule FUNX.url_decode = url_decode FUNX.url_encode = url_encode FUNX.verifyNetConnectionOrQuit = verifyNetConnectionOrQuit FUNX.zSort = zSort return FUNX
mit
SalvationDevelopment/Salvation-Scripts-TCG
c15839054.lua
9
1202
--シンクロ・フュージョニスト function c15839054.initial_effect(c) --search local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(15839054,0)) e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_DELAY) e1:SetCode(EVENT_BE_MATERIAL) e1:SetCondition(c15839054.condition) e1:SetTarget(c15839054.target) e1:SetOperation(c15839054.operation) c:RegisterEffect(e1) end function c15839054.condition(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsLocation(LOCATION_GRAVE) and r==REASON_SYNCHRO end function c15839054.filter(c) return c:IsSetCard(0x46) and c:IsType(TYPE_SPELL) and c:IsAbleToHand() end function c15839054.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c15839054.filter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c15839054.operation(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c15839054.filter,tp,LOCATION_DECK,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
dickeyf/darkstar
scripts/globals/spells/bluemagic/digest.lua
3
1796
----------------------------------------- -- Spell: Digest -- Steals an enemy's HP. Ineffective against undead -- Spell cost: 20 MP -- Monster Type: Amorphs -- Spell Type: Magical (Dark) -- Blue Magic Points: 2 -- Stat Bonus: HP-5, MP+5 -- Level: 36 -- Casting Time: 4 seconds -- Recast Time: 90 seconds -- Magic Bursts on: Compression, Gravitation, Darkness -- Combos: None ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local dmg = 5 + 0.575 * (caster:getSkillLevel(BLUE_SKILL) + caster:getMod(79 + BLUE_SKILL)); --get resist multiplier (1x if no resist) local resist = applyResistance(caster,spell,target,caster:getStat(MOD_MND)-target:getStat(MOD_MND),BLUE_SKILL,1.0); --get the resisted damage dmg = dmg*resist; --add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = addBonuses(caster,spell,target,dmg); --add in target adjustment dmg = adjustForTarget(target,dmg,spell:getElement()); --add in final adjustments if (dmg < 0) then dmg = 0 end if (target:isUndead()) then spell:setMsg(75); -- No effect return dmg; end if (target:getHP() > dmg) then caster:addHP(dmg); target:delHP(dmg); else dmg = target:getHP(); caster:addHP(dmg); target:delHP(dmg); end spell:setMsg(227); return dmg; end;
gpl-3.0
Turttle/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Despachiaire.lua
17
2660
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Despachiaire -- @pos 108 -40 -83 26 ----------------------------------- require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local currentCOPMission = player:getCurrentMission(COP); local LouverancePathStatut = player:getVar("COP_Louverance_s_Path"); if (currentCOPMission == THE_LOST_CITY and player:getVar("PromathiaStatus") == 0) then player:startEvent(0x0066); elseif (currentCOPMission == SHELTERING_DOUBT and player:getVar("PromathiaStatus") == 1) then player:startEvent(0x006C); elseif (currentCOPMission == THE_ENDURING_TUMULT_OF_WAR and player:getVar("COP_optional_CS_Despachaire") == 0) then player:startEvent(0x0075); --117 elseif (currentCOPMission == THREE_PATHS and LouverancePathStatut == 0) then player:startEvent(0x0076); elseif (currentCOPMission == THREE_PATHS and LouverancePathStatut == 1 ) then player:startEvent(0x0086); else player:startEvent(0x006A); end end; --Despachiaire 102 ++ --Despachiaire 104 ++ --Despachiaire 106 ++ --Despachiaire 107 ++ --Despachiaire 108 ++ --Despachiaire 110 ++ --Despachiaire 112 ++ --Despachiaire 117 ++ --Despachiaire 118 ++ --Despachiaire 132 --Despachiaire 133 --Despachiaire 134 ?? --Despachiaire 139 --Despachiaire 144 chat --Despachiaire 149 XX --Despachiaire 315 chat --Despachiaire 317 chat --Despachiaire 318 chat --Despachiaire 505 CS --Despachiaire 517 CS (despachiaire's wife) --Despachiaire 518 CS (ulmia mother) --Despachiaire 576 CS --Despachiaire 577 chat --Despachiaire 578 chat --Despachiaire 579 chat --Despachiaire 617 XX --Despachiaire 618 XX ----------------------------------- -- 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 == 0x0066 or csid == 0x006C) then player:setVar("PromathiaStatus",2); elseif (csid == 0x0075) then player:setVar("COP_optional_CS_Despachaire",1); elseif (csid == 0x0076) then player:setVar("COP_Louverance_s_Path",1); end end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c12927849.lua
2
4067
--SZW-天聖輝狼剣 function c12927849.initial_effect(c) --spsummon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(12927849,0)) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetTarget(c12927849.sptg) e1:SetOperation(c12927849.spop) c:RegisterEffect(e1) --equip local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(12927849,1)) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetCategory(CATEGORY_EQUIP) e2:SetRange(LOCATION_HAND) e2:SetTarget(c12927849.eqtg) e2:SetOperation(c12927849.eqop) c:RegisterEffect(e2) --salvage local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(12927849,2)) e3:SetCategory(CATEGORY_TOHAND) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_BATTLE_DESTROYING) e3:SetRange(LOCATION_SZONE) e3:SetProperty(EFFECT_FLAG_CARD_TARGET) e3:SetCondition(c12927849.thcon) e3:SetTarget(c12927849.thtg) e3:SetOperation(c12927849.thop) c:RegisterEffect(e3) end function c12927849.filter(c,e,tp) return c:IsFaceup() and c:IsSetCard(0x7e) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c12927849.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_SZONE) and chkc:IsControler(tp) and c12927849.filter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c12927849.filter,tp,LOCATION_SZONE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c12927849.filter,tp,LOCATION_SZONE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c12927849.spop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP_DEFENSE) end end function c12927849.eqfilter(c) return c:IsFaceup() and c:IsSetCard(0x107f) end function c12927849.eqtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c12927849.eqfilter(chkc) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0 and Duel.IsExistingTarget(c12927849.eqfilter,tp,LOCATION_MZONE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP) Duel.SelectTarget(tp,c12927849.eqfilter,tp,LOCATION_MZONE,0,1,1,nil) end function c12927849.eqop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsRelateToEffect(e) then return end local tc=Duel.GetFirstTarget() if Duel.GetLocationCount(tp,LOCATION_SZONE)<=0 or tc:GetControler()~=tp or tc:IsFacedown() or not tc:IsRelateToEffect(e) then Duel.SendtoGrave(c,REASON_EFFECT) return end Duel.Equip(tp,c,tc,true) local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_EQUIP_LIMIT) e1:SetReset(RESET_EVENT+0x1fe0000) e1:SetValue(c12927849.eqlimit) e1:SetLabelObject(tc) c:RegisterEffect(e1) end function c12927849.eqlimit(e,c) return c==e:GetLabelObject() end function c12927849.thcon(e,tp,eg,ep,ev,re,r,rp) local ec=eg:GetFirst() local bc=ec:GetBattleTarget() return ec==e:GetHandler():GetEquipTarget() and ec:IsStatus(STATUS_OPPO_BATTLE) and bc:IsLocation(LOCATION_GRAVE) and bc:IsType(TYPE_MONSTER) end function c12927849.thfilter(c) return c:IsSetCard(0x7e) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand() end function c12927849.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c12927849.thfilter(chkc) end if chk==0 then return Duel.IsExistingTarget(c12927849.thfilter,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectTarget(tp,c12927849.thfilter,tp,LOCATION_GRAVE,0,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0) end function c12927849.thop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SendtoHand(tc,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,tc) end end
gpl-2.0
Turttle/darkstar
scripts/zones/Windurst_Woods/npcs/Peshi_Yohnts.lua
44
2158
----------------------------------- -- Area: Windurst Woods -- NPC: Peshi Yohnts -- Type: Bonecraft Guild Master -- @pos -6.175 -6.249 -144.667 241 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local newRank = tradeTestItem(player,npc,trade,SKILL_BONECRAFT); if (newRank ~= 0) then player:setSkillRank(SKILL_BONECRAFT,newRank); player:startEvent(0x2721,0,0,0,0,newRank); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local getNewRank = 0; local craftSkill = player:getSkillLevel(SKILL_BONECRAFT); local testItem = getTestItem(player,npc,SKILL_BONECRAFT); local guildMember = isGuildMember(player,2); if (guildMember == 1) then guildMember = 64; end if (canGetNewRank(player,craftSkill,SKILL_BONECRAFT) == 1) then getNewRank = 100; end player:startEvent(0x2720,testItem,getNewRank,30,guildMember,44,0,0,0); end; -- 0x2720 0x2721 0x02c6 0x02c7 0x02c8 0x02c9 0x02ca 0x02cb 0x02fc ----------------------------------- -- 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 == 0x2720 and option == 1) then local crystal = math.random(4096,4101); if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,crystal); else player:addItem(crystal); player:messageSpecial(ITEM_OBTAINED,crystal); signupGuild(player,4); end end end;
gpl-3.0
Turttle/darkstar
scripts/globals/abilities/pets/ecliptic_howl.lua
20
1294
--------------------------------------------------- -- Aerial Armor --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/globals/utils"); --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0,0; end; function onPetAbility(target, pet, skill, summoner) local bonusTime = utils.clamp(summoner:getSkillLevel(SKILL_SUM) - 300, 0, 200); local duration = 180 + bonusTime; local moon = VanadielMoonPhase(); local buffvalue = 0; if moon > 90 then buffvalue = 25; elseif moon > 75 then buffvalue = 21; elseif moon > 60 then buffvalue = 17; elseif moon > 40 then buffvalue = 13; elseif moon > 25 then buffvalue = 9; elseif moon > 10 then buffvalue = 5; else buffvalue = 1; end target:delStatusEffect(EFFECT_ACCURACY_BOOST); target:delStatusEffect(EFFECT_EVASION_BOOST); target:addStatusEffect(EFFECT_ACCURACY_BOOST,buffvalue,0,duration); target:addStatusEffect(EFFECT_EVASION_BOOST,25-buffvalue,0,duration); skill:setMsg(0); return 0; end
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c100912080.lua
2
5053
--ダイヤモンドダストン --Diamond Duston --Script by dest function c100912080.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_DESTROYED) e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e1:SetCountLimit(1) e1:SetCondition(c100912080.condition) e1:SetTarget(c100912080.target) e1:SetOperation(c100912080.operation) c:RegisterEffect(e1) --spsummon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(100912080,1)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_QUICK_O) e2:SetCode(EVENT_FREE_CHAIN) e2:SetProperty(EFFECT_FLAG_NO_TURN_RESET) e2:SetRange(LOCATION_GRAVE) e2:SetCountLimit(1) e2:SetHintTiming(0,TIMING_END_PHASE) e2:SetCost(c100912080.spcost) e2:SetTarget(c100912080.sptg) e2:SetOperation(c100912080.spop) c:RegisterEffect(e2) end function c100912080.cfilter(c) return c:IsReason(REASON_BATTLE+REASON_EFFECT) and c:IsPreviousLocation(LOCATION_ONFIELD) end function c100912080.condition(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(c100912080.cfilter,1,nil) end function c100912080.filter(c,e,tp) return c:IsSetCard(0x80) and (c:IsCanBeSpecialSummoned(e,0,tp,false,false) or c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP,1-tp)) end function c100912080.target(e,tp,eg,ep,ev,re,r,rp,chk) local ct=eg:GetCount() local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)+Duel.GetLocationCount(1-tp,LOCATION_MZONE) if chk==0 then return (not Duel.IsPlayerAffectedByEffect(tp,59822133) or ct==1) and ft>=ct and Duel.IsExistingMatchingCard(c100912080.filter,tp,LOCATION_DECK+LOCATION_HAND,0,ct,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,ct,tp,LOCATION_DECK+LOCATION_HAND) end function c100912080.operation(e,tp,eg,ep,ev,re,r,rp) local ct=eg:GetCount() if Duel.IsPlayerAffectedByEffect(tp,59822133) and ct>1 then return end local ft1=Duel.GetLocationCount(tp,LOCATION_MZONE) local ft2=Duel.GetLocationCount(1-tp,LOCATION_MZONE) if ft1<=0 and ft2<=0 then return end if ft1+ft2<ct then return end local g=Duel.GetMatchingGroup(c100912080.filter,tp,LOCATION_HAND+LOCATION_DECK,0,nil,e,tp) if ct>g:GetCount() then return end if ft2>ct then ft2=ct end local ct2=ct-ft1 local tc=nil if ft2>0 and (ct2>0 or Duel.SelectYesNo(tp,aux.Stringid(100912080,0))) then if ct2<=0 then ct2=1 end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local sg1=g:FilterSelect(tp,Card.IsCanBeSpecialSummoned,ct2,ft2,nil,e,0,tp,false,false,POS_FACEUP,1-tp) tc=sg1:GetFirst() g:Sub(sg1) ct=ct-sg1:GetCount() while tc do Duel.SpecialSummonStep(tc,0,tp,1-tp,false,false,POS_FACEUP) tc=sg1:GetNext() end end if ct>0 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local sg2=g:Select(tp,ct,ct,nil) tc=sg2:GetFirst() while tc do Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP) tc=sg2:GetNext() end end Duel.SpecialSummonComplete() end function c100912080.spfilter(c) return c:IsSetCard(0x80) and c:IsType(TYPE_MONSTER) and c:IsAbleToRemoveAsCost() end function c100912080.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c100912080.spfilter,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,c100912080.spfilter,tp,LOCATION_GRAVE,0,1,1,nil) Duel.Remove(g,POS_FACEUP,REASON_COST) end function c100912080.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(1-tp,LOCATION_MZONE)>0 and Duel.IsPlayerCanSpecialSummonMonster(tp,100912080,0,0x11,0,1000,1,RACE_FIEND,ATTRIBUTE_DARK,POS_FACEUP_DEFENSE,1-tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c100912080.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(1-tp,LOCATION_MZONE)<=0 then return end local c=e:GetHandler() if c:IsRelateToEffect(e) and Duel.IsPlayerCanSpecialSummonMonster(tp,100912080,0,0x11,0,1000,1,RACE_FIEND,ATTRIBUTE_DARK,POS_FACEUP_DEFENSE,1-tp) then c:AddMonsterAttribute(TYPE_NORMAL) Duel.SpecialSummonStep(c,0,tp,1-tp,true,false,POS_FACEUP_DEFENSE) c:AddMonsterAttributeComplete() local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE+EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetRange(LOCATION_MZONE) e1:SetCode(EFFECT_UNRELEASABLE_SUM) e1:SetValue(1) e1:SetReset(RESET_EVENT+0x1fe0000) c:RegisterEffect(e1,true) local e2=e1:Clone() e2:SetCode(EFFECT_UNRELEASABLE_NONSUM) c:RegisterEffect(e2,true) local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e3:SetCode(EFFECT_CANNOT_BE_FUSION_MATERIAL) e3:SetValue(1) e3:SetReset(RESET_EVENT+0x1fe0000) c:RegisterEffect(e3,true) local e4=e3:Clone() e4:SetCode(EFFECT_CANNOT_BE_SYNCHRO_MATERIAL) c:RegisterEffect(e4,true) local e5=e3:Clone() e5:SetCode(EFFECT_CANNOT_BE_XYZ_MATERIAL) c:RegisterEffect(e5,true) Duel.SpecialSummonComplete() end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c51617185.lua
7
2775
--マシンナーズ・メガフォーム function c51617185.initial_effect(c) --spsummon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(51617185,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1,51617185) e1:SetCost(c51617185.spcost1) e1:SetTarget(c51617185.sptg1) e1:SetOperation(c51617185.spop1) c:RegisterEffect(e1) --spsummon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(51617185,1)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e2:SetProperty(EFFECT_FLAG_DELAY) e2:SetCode(EVENT_TO_GRAVE) e2:SetRange(LOCATION_GRAVE) e2:SetCountLimit(1,51617185) e2:SetCost(c51617185.spcost2) e2:SetTarget(c51617185.sptg2) e2:SetOperation(c51617185.spop2) c:RegisterEffect(e2) end function c51617185.spcost1(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsReleasable() end Duel.Release(e:GetHandler(),REASON_COST) end function c51617185.spfilter(c,e,tp) return c:IsSetCard(0x36) and not c:IsCode(51617185) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c51617185.sptg1(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1 and Duel.IsExistingMatchingCard(c51617185.spfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND+LOCATION_DECK) end function c51617185.spop1(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c51617185.spfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,1,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end function c51617185.cfilter(c,tp) return c:IsCode(5556499) and c:IsControler(tp) and c:IsPreviousLocation(LOCATION_ONFIELD) and c:IsPreviousPosition(POS_FACEUP) and c:GetPreviousControler()==tp and c:IsAbleToRemoveAsCost() end function c51617185.spcost2(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return not eg:IsContains(e:GetHandler()) and eg:IsExists(c51617185.cfilter,1,nil,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=eg:FilterSelect(tp,c51617185.cfilter,1,1,nil,tp) Duel.Remove(g,POS_FACEUP,REASON_COST) end function c51617185.sptg2(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 c51617185.spop2(e,tp,eg,ep,ev,re,r,rp) if e:GetHandler():IsRelateToEffect(e) then Duel.SpecialSummon(e:GetHandler(),0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c84451804.lua
2
1479
--デスガエル function c84451804.initial_effect(c) --Special Summon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(84451804,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetCondition(c84451804.condition) e1:SetTarget(c84451804.target) e1:SetOperation(c84451804.operation) c:RegisterEffect(e1) end function c84451804.condition(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetSummonType()==SUMMON_TYPE_ADVANCE end function c84451804.filter(c,e,tp) return c:IsCode(84451804) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c84451804.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(Card.IsCode,tp,LOCATION_GRAVE,0,1,nil,10456559) and Duel.IsExistingMatchingCard(c84451804.filter,tp,LOCATION_DECK+LOCATION_HAND,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK+LOCATION_HAND) end function c84451804.operation(e,tp,eg,ep,ev,re,r,rp) local ft=Duel.GetLocationCount(tp,LOCATION_MZONE) local ct=Duel.GetMatchingGroupCount(Card.IsCode,tp,LOCATION_GRAVE,0,nil,10456559) if ft<ct then ct=ft end if ct<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c84451804.filter,tp,LOCATION_DECK+LOCATION_HAND,0,1,ct,nil,e,tp) Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end
gpl-2.0
Turttle/darkstar
scripts/zones/Southern_San_dOria/npcs/Helbort.lua
17
2420
----------------------------------- -- Area: Southern San d'Oria -- NPC: Helbort -- Starts and Finished Quest: A purchase of Arms -- @zone 230 -- @pos 71 -1 65 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) quest_fas = player:getQuestStatus(SANDORIA,FATHER_AND_SON); -- 1st Quest in Series quest_poa = player:getQuestStatus(SANDORIA,A_PURCHASE_OF_ARMS); -- 2nd Quest in Series if (player:getFameLevel(SANDORIA) >= 2 and quest_fas == QUEST_COMPLETED and quest_poa == QUEST_AVAILABLE) then player:startEvent(0x0252); -- Start quest A Purchase of Arms elseif (quest_poa == QUEST_ACCEPTED and player:hasKeyItem(WEAPONS_RECEIPT) == true) then player:startEvent(0x025f); -- Finish A Purchase of Arms quest else player:startEvent(0x0251); -- Standard Dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --print("CSID:",csid); --print("RESULT:",option); if (csid == 0x0252 and option == 0) then player:addQuest(SANDORIA, A_PURCHASE_OF_ARMS); player:addKeyItem(WEAPONS_ORDER); player:messageSpecial(KEYITEM_OBTAINED,WEAPONS_ORDER); elseif (csid == 0x025f) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17090); -- Elm Staff else player:addTitle(ARMS_TRADER); player:delKeyItem(WEAPONS_RECEIPT); player:addItem(17090); player:messageSpecial(ITEM_OBTAINED,17090); -- Elm Staff player:addFame(SANDORIA,SAN_FAME*30); player:completeQuest(SANDORIA, A_PURCHASE_OF_ARMS); end end end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c2926176.lua
2
1180
--王家の呪い function c2926176.initial_effect(c) --Negate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_CHAINING) e1:SetCondition(c2926176.condition) e1:SetTarget(c2926176.target) e1:SetOperation(c2926176.operation) c:RegisterEffect(e1) end function c2926176.cfilter(c) return c:IsOnField() and c:IsType(TYPE_SPELL+TYPE_TRAP) end function c2926176.condition(e,tp,eg,ep,ev,re,r,rp) if not re:IsHasType(EFFECT_TYPE_ACTIVATE) or not Duel.IsChainNegatable(ev) then return false end local ex,tg,tc=Duel.GetOperationInfo(ev,CATEGORY_DESTROY) return ex and tg~=nil and tc==1 and tg:FilterCount(c2926176.cfilter,nil)==tg:GetCount() end function c2926176.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0) if re:GetHandler():IsDestructable() and re:GetHandler():IsRelateToEffect(re) then Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0) end end function c2926176.operation(e,tp,eg,ep,ev,re,r,rp) if Duel.NegateActivation(ev) and re:GetHandler():IsRelateToEffect(re) then Duel.Destroy(eg,REASON_EFFECT) end end
gpl-2.0
dickeyf/darkstar
scripts/zones/West_Ronfaure/npcs/Kyanta-Pakyanta_WW.lua
13
3335
----------------------------------- -- Area: West Ronfaure -- NPC: Kyanta-Pakyanta, W.W. -- Type: Outpost Conquest Guards -- @pos -450.571 -20.807 -219.970 100 ----------------------------------- package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/West_Ronfaure/TextIDs"); local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = RONFAURE; local csid = 0x7ff7; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
omidtarh/fbot
plugins/minecraft.lua
624
2605
local usage = { "!mine [ip]: Searches Minecraft server on specified ip and sends info. Default port: 25565", "!mine [ip] [port]: Searches Minecraft server on specified ip and port and sends info.", } local ltn12 = require "ltn12" local function mineSearch(ip, port, receiver) --25565 local responseText = "" local api = "https://api.syfaro.net/server/status" local parameters = "?ip="..(URL.escape(ip) or "").."&port="..(URL.escape(port) or "").."&players=true&favicon=true" local http = require("socket.http") local respbody = {} local body, code, headers, status = http.request{ url = api..parameters, method = "GET", redirect = true, sink = ltn12.sink.table(respbody) } local body = table.concat(respbody) if (status == nil) then return "ERROR: status = nil" end if code ~=200 then return "ERROR: "..code..". Status: "..status end local jsonData = json:decode(body) responseText = responseText..ip..":"..port.." ->\n" if (jsonData.motd ~= nil) then local tempMotd = "" tempMotd = jsonData.motd:gsub('%§.', '') if (jsonData.motd ~= nil) then responseText = responseText.." Motd: "..tempMotd.."\n" end end if (jsonData.online ~= nil) then responseText = responseText.." Online: "..tostring(jsonData.online).."\n" end if (jsonData.players ~= nil) then if (jsonData.players.max ~= nil) then responseText = responseText.." Max Players: "..jsonData.players.max.."\n" end if (jsonData.players.now ~= nil) then responseText = responseText.." Players online: "..jsonData.players.now.."\n" end if (jsonData.players.sample ~= nil and jsonData.players.sample ~= false) then responseText = responseText.." Players: "..table.concat(jsonData.players.sample, ", ").."\n" end end if (jsonData.favicon ~= nil and false) then --send_photo(receiver, jsonData.favicon) --(decode base64 and send) end return responseText end local function parseText(chat, text) if (text == nil or text == "!mine") then return usage end ip, port = string.match(text, "^!mine (.-) (.*)$") if (ip ~= nil and port ~= nil) then return mineSearch(ip, port, chat) end local ip = string.match(text, "^!mine (.*)$") if (ip ~= nil) then return mineSearch(ip, "25565", chat) end return "ERROR: no input ip?" end local function run(msg, matches) local chat_id = tostring(msg.to.id) local result = parseText(chat_id, msg.text) return result end return { description = "Searches Minecraft server and sends info", usage = usage, patterns = { "^!mine (.*)$" }, run = run }
gpl-2.0
crazyboy11/premium
plugins/minecraft.lua
624
2605
local usage = { "!mine [ip]: Searches Minecraft server on specified ip and sends info. Default port: 25565", "!mine [ip] [port]: Searches Minecraft server on specified ip and port and sends info.", } local ltn12 = require "ltn12" local function mineSearch(ip, port, receiver) --25565 local responseText = "" local api = "https://api.syfaro.net/server/status" local parameters = "?ip="..(URL.escape(ip) or "").."&port="..(URL.escape(port) or "").."&players=true&favicon=true" local http = require("socket.http") local respbody = {} local body, code, headers, status = http.request{ url = api..parameters, method = "GET", redirect = true, sink = ltn12.sink.table(respbody) } local body = table.concat(respbody) if (status == nil) then return "ERROR: status = nil" end if code ~=200 then return "ERROR: "..code..". Status: "..status end local jsonData = json:decode(body) responseText = responseText..ip..":"..port.." ->\n" if (jsonData.motd ~= nil) then local tempMotd = "" tempMotd = jsonData.motd:gsub('%§.', '') if (jsonData.motd ~= nil) then responseText = responseText.." Motd: "..tempMotd.."\n" end end if (jsonData.online ~= nil) then responseText = responseText.." Online: "..tostring(jsonData.online).."\n" end if (jsonData.players ~= nil) then if (jsonData.players.max ~= nil) then responseText = responseText.." Max Players: "..jsonData.players.max.."\n" end if (jsonData.players.now ~= nil) then responseText = responseText.." Players online: "..jsonData.players.now.."\n" end if (jsonData.players.sample ~= nil and jsonData.players.sample ~= false) then responseText = responseText.." Players: "..table.concat(jsonData.players.sample, ", ").."\n" end end if (jsonData.favicon ~= nil and false) then --send_photo(receiver, jsonData.favicon) --(decode base64 and send) end return responseText end local function parseText(chat, text) if (text == nil or text == "!mine") then return usage end ip, port = string.match(text, "^!mine (.-) (.*)$") if (ip ~= nil and port ~= nil) then return mineSearch(ip, port, chat) end local ip = string.match(text, "^!mine (.*)$") if (ip ~= nil) then return mineSearch(ip, "25565", chat) end return "ERROR: no input ip?" end local function run(msg, matches) local chat_id = tostring(msg.to.id) local result = parseText(chat_id, msg.text) return result end return { description = "Searches Minecraft server and sends info", usage = usage, patterns = { "^!mine (.*)$" }, run = run }
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c24701235.lua
2
1955
--和魂 function c24701235.initial_effect(c) --spirit aux.EnableSpiritReturn(c,EVENT_SUMMON_SUCCESS,EVENT_FLIP) --cannot special summon local e1=Effect.CreateEffect(c) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SPSUMMON_CONDITION) c:RegisterEffect(e1) --extra summon local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e4:SetCode(EVENT_SUMMON_SUCCESS) e4:SetOperation(c24701235.sumop) c:RegisterEffect(e4) local e5=e4:Clone() e5:SetCode(EVENT_FLIP) c:RegisterEffect(e5) --draw local e6=Effect.CreateEffect(c) e6:SetDescription(aux.Stringid(24701235,1)) e6:SetCategory(CATEGORY_DRAW) e6:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e6:SetCode(EVENT_TO_GRAVE) e6:SetTarget(c24701235.target) e6:SetOperation(c24701235.operation) c:RegisterEffect(e6) end function c24701235.sumop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetFlagEffect(tp,24701235)~=0 then return end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetTargetRange(LOCATION_HAND+LOCATION_MZONE,0) e1:SetCode(EFFECT_EXTRA_SUMMON_COUNT) e1:SetTarget(aux.TargetBoolFunction(Card.IsType,TYPE_SPIRIT)) e1:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e1,tp) Duel.RegisterFlagEffect(tp,24701235,RESET_PHASE+PHASE_END,0,1) end function c24701235.cfilter(c) return c:IsFaceup() and c:IsType(TYPE_SPIRIT) end function c24701235.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c24701235.cfilter,tp,LOCATION_MZONE,0,1,nil) end Duel.SetTargetPlayer(tp) Duel.SetTargetParam(1) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1) end function c24701235.operation(e,tp,eg,ep,ev,re,r,rp) if not Duel.IsExistingMatchingCard(c24701235.cfilter,tp,LOCATION_MZONE,0,1,nil) then return end local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Draw(p,d,REASON_EFFECT) end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c100912073.lua
2
4615
--幻煌龍の浸禍 --Deep Whirlpool of the Mythic Radiance Dragon --Script by dest function c100912073.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_ATKCHANGE+CATEGORY_DEFCHANGE+CATEGORY_DISABLE) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetHintTiming(TIMING_DAMAGE_STEP,TIMING_DAMAGE_STEP+0x1c0) e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCondition(c100912073.condition) e1:SetTarget(c100912073.target) e1:SetOperation(c100912073.activate) c:RegisterEffect(e1) --act in hand local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_TRAP_ACT_IN_HAND) e2:SetCondition(c100912073.handcon) c:RegisterEffect(e2) --equip local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(100912073,0)) e3:SetCategory(CATEGORY_EQUIP) e3:SetType(EFFECT_TYPE_QUICK_O) e3:SetCode(EVENT_FREE_CHAIN) e3:SetProperty(EFFECT_FLAG_CARD_TARGET) e3:SetRange(LOCATION_GRAVE) e3:SetCost(c100912073.eqcost) e3:SetTarget(c100912073.eqtg) e3:SetOperation(c100912073.eqop) c:RegisterEffect(e3) end function c100912073.cfilter(c) return c:IsFacedown() or not c:IsType(TYPE_NORMAL) end function c100912073.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.GetFieldGroupCount(tp,LOCATION_MZONE,0)>0 and not Duel.IsExistingMatchingCard(c100912073.cfilter,tp,LOCATION_MZONE,0,1,nil) and (Duel.GetCurrentPhase()~=PHASE_DAMAGE or not Duel.IsDamageCalculated()) end function c100912073.mfilter(c) return c:IsFaceup() and c:IsType(TYPE_EFFECT) end function c100912073.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(1-tp) and chkc:IsLocation(LOCATION_MZONE) and c100912073.mfilter(chkc) end if chk==0 then return Duel.IsExistingTarget(c100912073.mfilter,tp,0,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) local g=Duel.SelectTarget(tp,c100912073.mfilter,tp,0,LOCATION_MZONE,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_DISABLE,g,1,0,0) end function c100912073.activate(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and tc:IsFaceup() then Duel.NegateRelatedChain(tc,RESET_TURN_SET) local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) e1:SetValue(-1000) tc:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EFFECT_UPDATE_DEFENSE) tc:RegisterEffect(e2) local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_DISABLE) e3:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e3) local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetCode(EFFECT_DISABLE_EFFECT) e4:SetValue(RESET_TURN_SET) e4:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e4) end end function c100912073.filter(c) return c:IsFaceup() and c:IsCode(22702055) end function c100912073.handcon(e) return Duel.IsExistingMatchingCard(c100912073.filter,e:GetHandlerPlayer(),LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) or Duel.IsEnvironment(22702055) end function c100912073.eqcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST) end function c100912073.efilter(c,e) return c:IsFaceup() and c:IsType(TYPE_NORMAL) and c:IsCanBeEffectTarget(e) end function c100912073.eqfilter(c,g) return c:IsType(TYPE_EQUIP) and c:IsSetCard(0x1fc) and g:IsExists(c100912073.eqcheck,1,nil,c) end function c100912073.eqcheck(c,ec) return ec:CheckEquipTarget(c) end function c100912073.eqtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) local g=Duel.GetMatchingGroup(c100912073.efilter,tp,LOCATION_MZONE,0,nil,e) if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_MZONE) and c100912073.efilter(chkc,e) end if chk==0 then return g:GetCount()>0 and Duel.GetLocationCount(tp,LOCATION_SZONE)>0 and Duel.IsExistingMatchingCard(c100912073.eqfilter,tp,LOCATION_GRAVE+LOCATION_HAND,0,1,nil,g) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) Duel.SelectTarget(tp,c100912073.efilter,tp,LOCATION_MZONE,0,1,1,nil,e) end function c100912073.eqop(e,tp,eg,ep,ev,re,r,rp) local tg=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS) local tc=tg:GetFirst() if tc:IsFacedown() or not tc:IsRelateToEffect(e) then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP) local g=Duel.SelectMatchingCard(tp,c100912073.eqfilter,tp,LOCATION_GRAVE+LOCATION_HAND,0,1,1,nil,tg) local eq=g:GetFirst() if eq then Duel.Equip(tp,eq,tc,true) end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c25341652.lua
2
2499
--交響魔人マエストローク function c25341652.initial_effect(c) --xyz summon aux.AddXyzProcedure(c,nil,4,2) c:EnableReviveLimit() --pos local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(25341652,0)) e1:SetCategory(CATEGORY_POSITION) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetCost(c25341652.poscost) e1:SetTarget(c25341652.postg) e1:SetOperation(c25341652.posop) c:RegisterEffect(e1) --destroy replace local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EFFECT_DESTROY_REPLACE) e2:SetRange(LOCATION_MZONE) e2:SetTarget(c25341652.reptg) e2:SetValue(c25341652.repval) e2:SetOperation(c25341652.repop) c:RegisterEffect(e2) end function c25341652.poscost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST) end function c25341652.posfilter(c) return c:IsPosition(POS_FACEUP_ATTACK) and c:IsCanTurnSet() end function c25341652.postg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(1-tp) and chkc:IsLocation(LOCATION_MZONE) and c25341652.posfilter(chkc) end if chk==0 then return Duel.IsExistingTarget(c25341652.posfilter,tp,0,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUPATTACK) local g=Duel.SelectTarget(tp,c25341652.posfilter,tp,0,LOCATION_MZONE,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_POSITION,g,1,0,0) end function c25341652.posop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsFaceup() and tc:IsRelateToEffect(e) then Duel.ChangePosition(tc,POS_FACEDOWN_DEFENSE) end end function c25341652.repfilter(c,tp) return c:IsFaceup() and c:IsControler(tp) and c:IsLocation(LOCATION_MZONE) and c:IsSetCard(0x6d) and c:CheckRemoveOverlayCard(tp,1,REASON_EFFECT) end function c25341652.reptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return eg:IsExists(c25341652.repfilter,1,nil,tp) end if Duel.SelectYesNo(tp,aux.Stringid(25341652,1)) then local g=eg:Filter(c25341652.repfilter,nil,tp) Duel.SetTargetCard(g) return true else return false end end function c25341652.repval(e,c) return c25341652.repfilter(c,e:GetHandlerPlayer()) end function c25341652.repop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS) local tc=g:GetFirst() while tc do tc:RemoveOverlayCard(tp,1,1,REASON_EFFECT) tc=g:GetNext() end end
gpl-2.0
eugeneia/snabb
src/program/packetblaster/ipfix/ipfix.lua
2
5035
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local connectx = require("apps.mellanox.connectx") local basic_apps = require("apps.basic.basic_apps") local PcapReader = require("apps.pcap.pcap").PcapReader local numa = require("lib.numa") local worker = require("core.worker") local lib = require("core.lib") local long_opts = { duration = "D", nqueues = "q", ["new-flows-freq"] = "f", help = "h" } local function show_usage (code) print(require("program.packetblaster.replay.README_inc")) main.exit(code) end function run (args) local handlers = {} local opts = { nqueues = 1, duration = nil, flow_Hz = 150 } function handlers.D (arg) opts.duration = assert(tonumber(arg), "duration is not a number!") end function handlers.q (arg) opts.nqueues = assert(tonumber(arg), "nqueues is not a number!") end function handlers.f (arg) opts.flow_Hz = assert(tonumber(arg), "new-flows-freq is not a number!") end function handlers.h () show_usage(0) end args = lib.dogetopt(args, handlers, "hD:q:f:", long_opts) if #args < 3 then show_usage(1) end local filename = table.remove(args, 1) local pci = table.remove(args, 1) local cpus = assert(numa.parse_cpuset(table.remove(args, 1)), "Invalid cpu set") print (string.format("filename=%s", filename)) local queues = {} for cpu in pairs(cpus) do for q=1, opts.nqueues do table.insert(queues, {id=("%d_%d"):format(cpu, q)}) end end assert(#queues > 0, "Need atleast one cpu.") local c = config.new() config.app(c, "ConnectX", connectx.ConnectX, { pciaddress = pci, queues = queues, sendq_size = 4096 }) engine.configure(c) for cpu in pairs(cpus) do worker.start( "loadgen"..cpu, ([[require("program.packetblaster.ipfix.ipfix").run_loadgen( %q, %q, %d, %d, %s, %d)]]) :format(filename, pci, cpu, opts.nqueues, opts.duration, opts.flow_Hz) ) end local function worker_alive () for w, status in pairs(worker.status()) do if status.alive then return true end end end while worker_alive() do engine.main{duration=1, no_report=true} print("Transmissions (last 1 sec):") engine.report_apps() end end function run_loadgen (filename, pci, cpu, nqueues, duration, flow_Hz) local c = config.new() config.app(c, "pcap", PcapReader, filename) config.app(c, "repeater", basic_apps.Repeater) config.app(c, "flowgen", Flowgen, {Hz=flow_Hz}) config.app(c, "source", basic_apps.Tee) config.link(c, "pcap.output -> repeater.input") config.link(c, "repeater.output -> flowgen.input") config.link(c, "flowgen.output -> source.input") for q=1, nqueues do config.app(c, "nic"..q, connectx.IO, { pciaddress = pci, queue = ("%d_%d"):format(cpu, q) }) config.link(c, "source.output"..q.." -> nic"..q..".input") end engine.configure(c) engine.main{duration=duration} end local ethernet = require("lib.protocol.ethernet") local dot1q = require("lib.protocol.dot1q") local ipv4 = require("lib.protocol.ipv4") local ipv6 = require("lib.protocol.ipv6") local ffi = require("ffi") Flowgen = { config = { Hz = {default=100000} } } function Flowgen:new (config) local self = { inc = 0ULL, inc_throttle = lib.throttle(1/config.Hz), dot1q = dot1q:new{}, ipv4 = ipv4:new{}, ipv6 = ipv6:new{} } return setmetatable(self, {__index=Flowgen}) end function Flowgen:push () if self.inc_throttle() then self.inc = (self.inc + 1) end local input, output = self.input.input, self.output.output while not link.empty(input) do local p = link.receive(input) if self:inc_l3_addresses(p) then link.transmit(output, p) else packet.free(p) end end end function Flowgen:inc_l3_addresses (p) local inc = self.inc local vlan = self.dot1q:new_from_mem( p.data+ethernet:sizeof(), p.length-ethernet:sizeof() ) if not vlan then return false end if vlan:type() == 0x0800 then -- IPv4 local ip = self.ipv4:new_from_mem( p.data+ethernet:sizeof()+dot1q:sizeof(), p.length-(ethernet:sizeof()+dot1q:sizeof()) ) if not ip then return false end self:inc_ip(ip:src(), inc) self:inc_ip(ip:dst(), inc) return true elseif vlan:type() == 0x86dd then -- IPv6 local ip = self.ipv6:new_from_mem( p.data+ethernet:sizeof()+dot1q:sizeof(), p.length-(ethernet:sizeof()+dot1q:sizeof()) ) if not ip then return false end self:inc_ip(ip:src(), inc) self:inc_ip(ip:dst(), inc) return true else return false end end function Flowgen:inc_ip (addr, inc) local addr = ffi.cast("uint32_t*", addr) addr[0] = addr[0] + inc end
apache-2.0
dickeyf/darkstar
scripts/zones/Abyssea-Grauberg/npcs/Dominion_Tactician.lua
61
4431
----------------------------------- -- Area: Abyssea - Grauberg -- NPC: Dominion Tactician -- ----------------------------------- package.loaded["scripts/zones/Abyssea-Grauberg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/abyssea"); require("scripts/zones/Abyssea-Grauberg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DM = player:getDominionNotes(); local Trophies = 0; -- Max all Trophy = 4294967295 sort out its bit mask later. player:startEvent(120, DM, 0, 0, 0, 0, Trophies); 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); local Price = 0; local TempItem = false; local ItemID = 0; local aug1 = 0; local aug2 = 0; local aug3 = 0; local aug4 = 0; local a1 = 0; local a2 = 0; local a3 = 0; local a4 = 0; local v1 = 0; local v2 = 0; local v3 = 0; local v4 = 0; ----------------------------------- -- Spending Dominion Notes if (option == 257) then -- Unkai Domaru Price = 1500; ItemID = 12039; elseif (option == 258) then -- Petrify Screen Price = 300; TempItem = true; ItemID = 5876; elseif (option == 259) then -- Augmented Yataghan Price = 2500; ItemID = 16485; -- Work out augment selection via math.random -- (see Lower Jeuno Tenshodo Coffer script) elseif (option == 513) then -- Inga Ningi Price = 1500; ItemID = 12040; elseif (option == 514) then -- Terror Screen Price = 300; TempItem = true; ItemID = 5877; elseif (option == 515) then -- Augmented Doom Tabar Price = 2500; ItemID = 16660; -- Aug crap here elseif (option == 769) then -- Lancer's Plackart Price = 1500; ItemID = 12041; elseif (option == 770) then -- Amnesia Screen Price = 300; TempItem = true; ItemID = 5878; elseif (option == 771) then -- Augmented Yukitsugu Price = 2500; ItemID = 16971; -- Aug crap here elseif (option == 1025) then -- Caller's Doublet Price = 1500; ItemID = 12042; elseif (option == 1026) then -- Doom Screen Price = 300; TempItem = true; ItemID = 5879; elseif (option == 1281) then -- Mavi Mintan Price = 1500; ItemID = 12043; elseif (option == 1282) then -- Poison Screen Price = 300; TempItem = true; ItemID = 5880; elseif (option == 1537) then -- Navarch's Frac Price = 1500; ItemID = 12044; elseif (option == 1793) then -- Cirque Farsetto Price = 1500; ItemID = 12045; elseif (option == 2049) then -- Charis Casaque Price = 1500; ItemID = 12046; elseif (option == 2305) then -- Savant's Gown Price = 1500; ItemID = 12047; elseif (option == 2561) then -- Incredescent Shade Price = 300; ItemID = 3295; elseif (option == 2817) then -- Decredescent Shade Price = 300; ItemID = 3296; end if (option > 256 and option < 2818) then if (player:getDominionNotes() > Price) then if (player:getFreeSlotsCount() >= 1) then player:messageSpecial(ITEM_OBTAINED,ItemID); if (TempItem == true) then player:addTempItem(ItemID,1); else player:addItem(ItemID,1,a1,v1,a2,v2,a3,v3,a4,v4); end player:delDominionNotes(Price); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,ItemID); end end end ----------------------------------- -- Trophy trades for gear -- if (option == 65796) then -- . -- elseif (option == -- . -- end end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c77608643.lua
4
2331
--D-HERO ダイハードガイ function c77608643.initial_effect(c) --spsummon local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetRange(LOCATION_MZONE) e1:SetCode(EVENT_BATTLE_DESTROYED) e1:SetOperation(c77608643.operation) c:RegisterEffect(e1) local g=Group.CreateGroup() g:KeepAlive() e1:SetLabelObject(g) --spsummon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(77608643,0)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1) e2:SetCode(EVENT_PHASE+PHASE_STANDBY) e2:SetCondition(c77608643.spcon) e2:SetTarget(c77608643.sptg) e2:SetOperation(c77608643.spop) e2:SetLabelObject(g) c:RegisterEffect(e2) end function c77608643.filter(c,e,tp) return c:IsLocation(LOCATION_GRAVE) and c:IsReason(REASON_BATTLE) and c:GetPreviousControler()==tp and c:IsSetCard(0xc008) end function c77608643.operation(e,tp,eg,ep,ev,re,r,rp) local g=eg:Filter(c77608643.filter,nil,e,tp) if g:GetCount()==0 then return end local sg=e:GetLabelObject() local c=e:GetHandler() if c:GetFlagEffect(77608643)==0 then sg:Clear() c:RegisterFlagEffect(77608643,RESET_EVENT+0x3fe0000+RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN,0,1) end sg:Merge(g) end function c77608643.spcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()==tp and e:GetHandler():GetFlagEffect(77608643)~=0 end function c77608643.spfilter(c,e,tp) return c:IsLocation(LOCATION_GRAVE) and c:IsReason(REASON_BATTLE) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and c:IsCanBeEffectTarget(e) end function c77608643.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return e:GetLabelObject():IsContains(chkc) and c77608643.spfilter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetLabelObject():IsExists(c77608643.spfilter,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=e:GetLabelObject():FilterSelect(tp,c77608643.spfilter,1,1,nil,e,tp) Duel.SetTargetCard(g) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c77608643.spop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
mika6020/powerbot
plugins/Addsudo.lua
1
1162
do local function callback(extra, success, result) vardump(success) vardump(result) end local function run(msg, matches) local user = 274283910 -- اینجا شناسه عددی خودتان را قرار بدید if matches[1] == "addsudo" then user = 'user#id'..user end if is_owner(msg) then if msg.from.username ~= nil then if string.find(msg.from.username , 'mika6020') then --اینجا دقیقا یوزرنیم خود را بدون @ قرار بدید(به حروف بزرگ و کوچک یوزرنیم خود دقت کنید) return "ℹ️سازنده هم اکنون در گروه است" end if msg.to.type == 'channel' or 'chat' then local channel = 'channel#id'..msg.to.id chat_add_user(chat, user, ok_cb, false) channel_invite(channel, user, ok_cb, false) return "ℹ️درحال دعوت صاحب ربات برای حل مشکل شما..." end elseif not is_owner(msg) then return 'ℹ️ شما دسترسی لازم را برای دعوت ندارد' end end end return { description = "insudo", usage = { "!invite name [user_name]", "!invite id [user_id]" }, patterns = { "^[!#/](addsudo)$" }, run = run } end
agpl-3.0
Turttle/darkstar
scripts/zones/PsoXja/npcs/_09g.lua
17
1222
----------------------------------- -- Area: Pso'Xja -- NPC: Avatars Gate ----------------------------------- package.loaded["scripts/zones/PsoXja/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/PsoXja/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Tenzen_s_Path") == 1) then player:startEvent(0x0003); else player:messageSpecial(DOOR_LOCKED); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == 0x0003) then player:setVar("COP_Tenzen_s_Path",2); end end;
gpl-3.0
platux/vlc
share/lua/playlist/metachannels.lua
92
2096
--[[ $Id$ Copyright © 2010 VideoLAN and AUTHORS Authors: Rémi Duraffort <ivoire at videolan dot org> 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. --]] require "simplexml" function probe() return vlc.access == 'http' and string.match( vlc.path, 'metachannels.com' ) end function parse() local webpage = '' while true do local line = vlc.readline() if line == nil then break end webpage = webpage .. line end local feed = simplexml.parse_string( webpage ) local channel = feed.children[1] -- list all children that are items local tracks = {} for _,item in ipairs( channel.children ) do if( item.name == 'item' ) then simplexml.add_name_maps( item ) local url = vlc.strings.resolve_xml_special_chars( item.children_map['link'][1].children[1] ) local title = vlc.strings.resolve_xml_special_chars( item.children_map['title'][1].children[1] ) local arturl = nil if item.children_map['media:thumbnail'] then arturl = vlc.strings.resolve_xml_special_chars( item.children_map['media:thumbnail'][1].attributes['url'] ) end table.insert( tracks, { path = url, title = title, arturl = arturl, options = {':play-and-pause'} } ) end end return tracks end
gpl-2.0
dickeyf/darkstar
scripts/globals/items/nebimonite.lua
18
1409
----------------------------------------- -- ID: 4361 -- Item: nebimonite -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity -3 -- Vitality 2 -- Defense % 12.9 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4361); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, -3); target:addMod(MOD_VIT, 2); target:addMod(MOD_DEFP, 12.9); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, -3); target:delMod(MOD_VIT, 2); target:delMod(MOD_DEFP, 12.9); end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c63583431.lua
5
2021
--ゴゴゴ護符 function c63583431.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1) --reduce local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_CHANGE_DAMAGE) e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e2:SetRange(LOCATION_SZONE) e2:SetTargetRange(1,0) e2:SetCondition(c63583431.damcon) e2:SetValue(c63583431.damval) c:RegisterEffect(e2) local e3=e2:Clone() e3:SetCode(EFFECT_NO_EFFECT_DAMAGE) c:RegisterEffect(e3) --indes local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(63583431,0)) e4:SetType(EFFECT_TYPE_QUICK_O) e4:SetRange(LOCATION_SZONE) e4:SetCode(EVENT_ATTACK_ANNOUNCE) e4:SetHintTiming(TIMING_BATTLE_PHASE) e4:SetCountLimit(1) e4:SetCondition(c63583431.indcon) e4:SetTarget(c63583431.indtg) e4:SetOperation(c63583431.indop) c:RegisterEffect(e4) end function c63583431.cfilter(c) return c:IsFaceup() and c:IsSetCard(0x59) end function c63583431.damcon(e) return Duel.IsExistingMatchingCard(c63583431.cfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,2,nil) end function c63583431.damval(e,re,val,r,rp,rc) if bit.band(r,REASON_EFFECT)~=0 then return 0 end return val end function c63583431.indcon(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetAttacker() if tc:IsControler(1-tp) then tc=Duel.GetAttackTarget() end e:SetLabelObject(tc) return tc and tc:IsFaceup() and tc:IsControler(tp) and tc:IsSetCard(0x59) end function c63583431.indtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetTargetCard(e:GetLabelObject()) end function c63583431.indop(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_INDESTRUCTABLE_BATTLE) e1:SetValue(1) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_DAMAGE) tc:RegisterEffect(e1) end end
gpl-2.0
Turttle/darkstar
scripts/zones/Eastern_Altepa_Desert/npcs/Telepoint.lua
17
1643
----------------------------------- -- Area: Eastern Altepa Desert -- NPC: Telepoint ----------------------------------- package.loaded["scripts/zones/Eastern_Altepa_Desert/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Eastern_Altepa_Desert/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) item = trade:getItem(); if (trade:getItemCount() == 1 and item > 4095 and item < 4104) then if (player:getFreeSlotsCount() > 0 and player:hasItem(613) == false) then player:tradeComplete(); player:addItem(613); player:messageSpecial(ITEM_OBTAINED,613); -- Faded Crystal else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,613); -- Faded Crystal end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(ALTEPA_GATE_CRYSTAL) == false) then player:addKeyItem(ALTEPA_GATE_CRYSTAL); player:messageSpecial(KEYITEM_OBTAINED,ALTEPA_GATE_CRYSTAL); else player:messageSpecial(ALREADY_OBTAINED_TELE); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Turttle/darkstar
scripts/zones/Apollyon/mobs/Dark_Elemental.lua
16
2431
----------------------------------- -- Area: Apollyon SW -- NPC: elemental ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); local elementalday = GetServerVariable("[SW_Apollyon]ElementalTrigger"); local correctelement=false; switch (elementalday): caseof { [1] = function (x) if (mobID==16932913 or mobID==16932921 or mobID==16932929) then correctelement=true; end end , [2] = function (x) if (mobID==16932912 or mobID==16932920 or mobID==16932928 ) then correctelement=true; end end , [3] = function (x) if (mobID==16932916 or mobID==16932924 or mobID==16932932 ) then correctelement=true; end end , [4] = function (x) if (mobID==16932910 or mobID==16932918 or mobID==16932926 ) then correctelement=true; end end , [5] = function (x) if (mobID==16932914 or mobID==16932922 or mobID==16932930 ) then correctelement=true; end end , [6] = function (x) if (mobID==16932917 or mobID==16932925 or mobID==16932933 ) then correctelement=true; end end , [7] = function (x) if (mobID==16932931 or mobID==16932915 or mobID==16932923 ) then correctelement=true; end end , [8] = function (x) if (mobID==16932911 or mobID==16932919 or mobID==16932927 ) then correctelement=true; end end , }; if (correctelement==true and IselementalDayAreDead()==true) then GetNPCByID(16932864+313):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+313):setStatus(STATUS_NORMAL); end end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c45358284.lua
5
1770
--ミラー・レディバグ function c45358284.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(c45358284.spcon) e1:SetValue(1) c:RegisterEffect(e1) --level change local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(45358284,0)) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e2:SetCode(EVENT_SPSUMMON_SUCCESS) e2:SetCondition(c45358284.lvcon) e2:SetOperation(c45358284.lvop) c:RegisterEffect(e2) --destroy local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e3:SetRange(LOCATION_MZONE) e3:SetCode(EFFECT_SELF_DESTROY) e3:SetCondition(c45358284.descon) c:RegisterEffect(e3) end function c45358284.spcon(e,c) if c==nil then return true end return Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(Card.IsFaceup,c:GetControler(),LOCATION_MZONE,0,1,nil) and not Duel.IsExistingMatchingCard(Card.IsType,c:GetControler(),LOCATION_GRAVE,0,1,nil,TYPE_MONSTER) end function c45358284.lvcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetSummonType()==SUMMON_TYPE_SPECIAL+1 end function c45358284.lvop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsRelateToEffect(e) then return end local g=Duel.GetMatchingGroup(Card.IsFaceup,tp,LOCATION_MZONE,0,c) local lvs=g:GetSum(Card.GetLevel) if lvs~=0 then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CHANGE_LEVEL) e1:SetValue(lvs) e1:SetReset(RESET_EVENT+0x1ff0000) c:RegisterEffect(e1) end end function c45358284.descon(e) return e:GetHandler():GetLevel()>12 end
gpl-2.0
Turttle/darkstar
scripts/zones/Windurst_Waters/npcs/Rukuku.lua
36
1417
----------------------------------- -- Area: Windurst Waters -- NPC: Rukuku -- Involved in Quest: Making the Grade -- Working 100% -- @zone = 238 -- @pos = 130 -6 160 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(WINDURST,MAKING_THE_GRADE) == QUEST_ACCEPTED) then player:startEvent(0x01c2); -- During Making the GRADE else player:startEvent(0x01aa); -- Standard conversation end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
dickeyf/darkstar
scripts/globals/spells/cure_vi.lua
26
3921
----------------------------------------- -- Spell: Cure VI -- Restores target's HP. -- Shamelessly stolen from http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local divisor = 0; local constant = 0; local basepower = 0; local power = 0; local basecure = 0; local final = 0; local minCure = 600; power = getCurePower(caster); if (power < 210) then divisor = 1.5; constant = 600; basepower = 90; elseif (power < 300) then divisor = 0.9; constant = 680; basepower = 210; elseif (power < 400) then divisor = 10/7; constant = 780; basepower = 300; elseif (power < 500) then divisor = 2.5; constant = 850; basepower = 400; elseif (power < 700) then divisor = 5/3; constant = 890; basepower = 500; else divisor = 999999; constant = 1010; basepower = 0; end if (target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then basecure = getBaseCure(power,divisor,constant,basepower); final = getCureFinal(caster,spell,basecure,minCure,false); if (caster:hasStatusEffect(EFFECT_AFFLATUS_SOLACE) and target:hasStatusEffect(EFFECT_STONESKIN) == false) then local solaceStoneskin = 0; local equippedBody = caster:getEquipID(SLOT_BODY); if (equippedBody == 11186) then solaceStoneskin = math.floor(final * 0.30); elseif (equippedBody == 11086) then solaceStoneskin = math.floor(final * 0.35); else solaceStoneskin = math.floor(final * 0.25); end target:addStatusEffect(EFFECT_STONESKIN,solaceStoneskin,0,25); end; final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100)); --Applying server mods.... final = final * CURE_POWER; local diff = (target:getMaxHP() - target:getHP()); if (final > diff) then final = diff; end target:restoreHP(final); target:wakeUp(); caster:updateEnmityFromCure(target,final); else if (target:isUndead()) then spell:setMsg(2); local dmg = calculateMagicDamage(minCure,1,caster,spell,target,HEALING_MAGIC_SKILL,MOD_MND,false)*0.5; local resist = applyResistance(caster,spell,target,caster:getStat(MOD_MND)-target:getStat(MOD_MND),HEALING_MAGIC_SKILL,1.0); dmg = dmg*resist; dmg = addBonuses(caster,spell,target,dmg); dmg = adjustForTarget(target,dmg,spell:getElement()); dmg = finalMagicAdjustments(caster,target,spell,dmg); final = dmg; target:delHP(final); target:updateEnmityFromDamage(caster,final); elseif (caster:getObjType() == TYPE_PC) then spell:setMsg(75); else -- e.g. monsters healing themselves. if (USE_OLD_CURE_FORMULA == true) then basecure = getBaseCureOld(power,divisor,constant); else basecure = getBaseCure(power,divisor,constant,basepower); end final = getCureFinal(caster,spell,basecure,minCure,false); local diff = (target:getMaxHP() - target:getHP()); if (final > diff) then final = diff; end target:addHP(final); end end return final; end;
gpl-3.0
platux/vlc
share/lua/meta/art/00_musicbrainz.lua
71
3091
--[[ Gets an artwork from the Cover Art Archive or Amazon $Id$ Copyright © 2007-2010 the VideoLAN team 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. --]] function descriptor() return { scope="network" } end function try_query(mbid) local relquery = "http://mb.videolan.org/ws/2/release/" .. mbid local s = vlc.stream( relquery ) if not s then return nil end local page = s:read( 65653 ) found, _ = string.find( page, "<artwork>true</artwork>" ) if found then return "http://coverartarchive.org/release/"..mbid.."/front-500" end -- FIXME: multiple results may be available _, _, asin = string.find( page, "<asin>(%w+)</asin>" ) if asin then return "http://images.amazon.com/images/P/"..asin..".01._SCLZZZZZZZ_.jpg" end vlc.msg.dbg("Neither coverartarchive.org nor amazon have cover art for this release") return nil end -- Return the mbid for the first release returned by the MusicBrainz search server for query function get_releaseid(query) local s = vlc.stream( query ) if not s then return nil end local page = s:read( 65653 ) -- FIXME: multiple results may be available and the first one is not -- guaranteed to have asin, so if it doesnt, we wouldnt get any art _, _, releaseid = string.find( page, "<release id=\"([%x%-]-)\"" ) if releaseid then return releaseid end return nil end -- Return the artwork function fetch_art() local meta = vlc.item:metas() if meta["Listing Type"] == "radio" or meta["Listing Type"] == "tv" then return nil end local releaseid = nil if meta["MB_ALBUMID"] then releaseid = meta["MB_ALBUMID"] end if not releaseid and meta["artist"] and meta["album"] then query = "artist:\"" .. meta["artist"] .. "\" AND release:\"" .. meta["album"] .. "\"" relquery = "http://mb.videolan.org/ws/2/release/?query=" .. vlc.strings.encode_uri_component( query ) releaseid = get_releaseid( relquery ) end if not releaseid and meta["artist"] and meta["title"] then query = "artist:\"" .. meta["artist"] .. "\" AND recording:\"" .. meta["title"] .. "\"" recquery = "http://mb.videolan.org/ws/2/recording/?query=" .. vlc.strings.encode_uri_component( query ) releaseid = get_releaseid( recquery ) end if releaseid then return try_query( releaseid ) else return nil end end
gpl-2.0
fgenesis/Aquaria_experimental
game_scripts/scripts/entities/titletextcommon.lua
6
1693
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end v.delay = 0.2 v.b1 = 0 v.b2 = 0 function v.commonInit(me, file) setupEntity(me) entity_initSkeletal(me, file) v.b1 = entity_getBoneByIdx(me, 0) v.b2 = entity_getBoneByIdx(me, 1) bone_alpha(v.b2, 0) entity_setState(me, STATE_IDLE) esetv(me, EV_LOOKAT, false) end function postInit(me) end function update(me, dt) if v.delay > -1 then v.delay = v.delay - dt if v.delay < 0 then v.delay = -1 bone_alpha(v.b2, 1, 6) bone_alpha(v.b1, 0, 6) end end end function enterState(me) end function exitState(me) end function damage(me, attacker, bone, damageType, dmg) return false end function animationKey(me, key) end function hitSurface(me) end function songNote(me, note) end function songNoteDone(me, note) end function song(me, song) end function activate(me) end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c91345518.lua
3
1328
--裁きの代行者 サターン function c91345518.initial_effect(c) --damage local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(91345518,0)) e1:SetCategory(CATEGORY_DAMAGE) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetCost(c91345518.damcost) e1:SetTarget(c91345518.damtg) e1:SetOperation(c91345518.damop) c:RegisterEffect(e1) end function c91345518.damcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetCurrentPhase()~=PHASE_MAIN2 and e:GetHandler():IsReleasable() end Duel.Release(e:GetHandler(),REASON_COST) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH) e1:SetCode(EFFECT_CANNOT_BP) e1:SetReset(RESET_PHASE+PHASE_END) e1:SetTargetRange(1,0) Duel.RegisterEffect(e1,tp) end function c91345518.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLP(tp)>Duel.GetLP(1-tp) end Duel.SetTargetPlayer(1-tp) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,0) end function c91345518.damop(e,tp,eg,ep,ev,re,r,rp) if not Duel.IsEnvironment(56433456,tp) then return end local p=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER) local val=Duel.GetLP(1-p)-Duel.GetLP(p) if val>0 then Duel.Damage(p,val,REASON_EFFECT) end end
gpl-2.0
dickeyf/darkstar
scripts/globals/spells/doton_san.lua
5
1583
----------------------------------------- -- Spell: Doton: San -- Deals earth damage to an enemy and lowers its resistance against wind. ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) --doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus) local duration = 15 + caster:getMerit(MERIT_DOTON_EFFECT) -- T1 bonus debuff duration local bonusAcc = 0; local bonusMab = caster:getMerit(MERIT_DOTON_EFFECT) + caster:getMod(MOD_NIN_NUKE_BONUS); -- T1 mag atk + "enhances Ninjustu damage" mod if(caster:getMerit(MERIT_DOTON_SAN) ~= 0) then -- T2 mag atk/mag acc, don't want to give a penalty to entities that can cast this without merits bonusMab = bonusMab + caster:getMerit(MERIT_DOTON_SAN) - 5; -- merit gives 5 power but no bonus with one invest, thus subtract 5 bonusAcc = bonusAcc + caster:getMerit(MERIT_DOTON_SAN) - 5; end; if (caster:isBehind(target,15) and caster:hasStatusEffect(EFFECT_INNIN)) then -- Innin mag atk bonus from behind, guesstimating angle at 15 degrees bonusMab = bonusMab + caster:getStatusEffect(EFFECT_INNIN):getPower(); end local dmg = doNinjutsuNuke(134,1.5,caster,spell,target,false,bonusAcc,bonusMab); handleNinjutsuDebuff(caster,target,spell,30,duration,MOD_WINDRES); return dmg; end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c984114.lua
7
1400
--エクスプレスロイド function c984114.initial_effect(c) --salvage local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(984114,0)) e1:SetCategory(CATEGORY_TOHAND) e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetTarget(c984114.target) e1:SetOperation(c984114.activate) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e2) local e3=e1:Clone() e3:SetCode(EVENT_FLIP_SUMMON_SUCCESS) c:RegisterEffect(e3) end function c984114.filter(c) return c:IsSetCard(0x16) and c:GetCode()~=984114 and c:IsType(TYPE_MONSTER) and c:IsAbleToHand() end function c984114.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c984114.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c984114.filter,tp,LOCATION_GRAVE,0,2,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectTarget(tp,c984114.filter,tp,LOCATION_GRAVE,0,2,2,nil) Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,2,0,0) end function c984114.activate(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS) local sg=g:Filter(Card.IsRelateToEffect,nil,e) if sg:GetCount()>0 then Duel.SendtoHand(sg,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,sg) end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c75425320.lua
4
3881
--真竜凰の使徒 function c75425320.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1) --draw local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(75425320,0)) e2:SetCategory(CATEGORY_TODECK+CATEGORY_DRAW) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_SZONE) e2:SetCountLimit(1,75425320) e2:SetTarget(c75425320.drtg) e2:SetOperation(c75425320.drop) c:RegisterEffect(e2) --tribute summon local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(75425320,1)) e3:SetCategory(CATEGORY_SUMMON) e3:SetType(EFFECT_TYPE_IGNITION) e3:SetRange(LOCATION_SZONE) e3:SetCountLimit(1,75425321) e3:SetTarget(c75425320.sumtg) e3:SetOperation(c75425320.sumop) c:RegisterEffect(e3) --destroy local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(75425320,2)) e4:SetCategory(CATEGORY_DESTROY) e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e4:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY) e4:SetCode(EVENT_TO_GRAVE) e4:SetCountLimit(1,75425322) e4:SetCondition(c75425320.descon) e4:SetTarget(c75425320.destg) e4:SetOperation(c75425320.desop) c:RegisterEffect(e4) end function c75425320.tdfilter(c) return c:IsSetCard(0xf9) and c:IsAbleToDeck() end function c75425320.drtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c75425320.tdfilter(chkc) end if chk==0 then return Duel.IsPlayerCanDraw(tp,1) and Duel.IsExistingTarget(c75425320.tdfilter,tp,LOCATION_GRAVE,0,3,nil) end Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription()) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK) local g=Duel.SelectTarget(tp,c75425320.tdfilter,tp,LOCATION_GRAVE,0,3,3,nil) Duel.SetOperationInfo(0,CATEGORY_TODECK,g,g:GetCount(),0,0) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1) end function c75425320.drop(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end local tg=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e) if tg:GetCount()<=0 then return end Duel.SendtoDeck(tg,nil,0,REASON_EFFECT) local g=Duel.GetOperatedGroup() if g:IsExists(Card.IsLocation,1,nil,LOCATION_DECK) then Duel.ShuffleDeck(tp) end local ct=g:FilterCount(Card.IsLocation,nil,LOCATION_DECK+LOCATION_EXTRA) if ct>0 then Duel.BreakEffect() Duel.Draw(tp,1,REASON_EFFECT) end end function c75425320.sumfilter(c) return c:IsSetCard(0xf9) and c:IsSummonable(true,nil,1) end function c75425320.sumtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c75425320.sumfilter,tp,LOCATION_HAND,0,1,nil) end Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription()) Duel.SetOperationInfo(0,CATEGORY_SUMMON,nil,1,0,0) end function c75425320.sumop(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SUMMON) local g=Duel.SelectMatchingCard(tp,c75425320.sumfilter,tp,LOCATION_HAND,0,1,1,nil) local tc=g:GetFirst() if tc then Duel.Summon(tp,tc,true,nil,1) end end function c75425320.descon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsPreviousLocation(LOCATION_SZONE) end function c75425320.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsOnField() and chkc:IsType(TYPE_SPELL+TYPE_TRAP) end if chk==0 then return Duel.IsExistingTarget(Card.IsType,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil,TYPE_SPELL+TYPE_TRAP) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,Card.IsType,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil,TYPE_SPELL+TYPE_TRAP) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0) end function c75425320.desop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.Destroy(tc,REASON_EFFECT) end end
gpl-2.0
rleh/telegram-bot
plugins/stats.lua
2
2818
-- Saves the number of messages from a user -- Can check the number of messages with !stats do local socket = require('socket') local _file_stats = './data/stats.lua' local _stats function update_user_stats(msg) -- Save user to stats table local from_id = tostring(msg.from.id) local to_id = tostring(msg.to.id) local user_name = get_name(msg) print ('New message from '..user_name..'['..from_id..']'..' to '..to_id) -- If last name is nil dont save last_name. local user_last_name = msg.from.last_name local user_print_name = msg.from.print_name if _stats[to_id] == nil then print ('New stats key to_id: '..to_id) _stats[to_id] = {} end if _stats[to_id][from_id] == nil then print ('New stats key from_id: '..to_id) _stats[to_id][from_id] = { user_id = from_id, name = user_name, last_name = user_last_name, print_name = user_print_name, msg_num = 1 } else print ('Updated '..to_id..' '..from_id) local actual_num = _stats[to_id][from_id].msg_num _stats[to_id][from_id].msg_num = actual_num + 1 _stats[to_id][from_id].user_id = from_id _stats[to_id][from_id].last_name = user_last_name end end function read_file_stats( ) local f = io.open(_file_stats, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table print ('Created user stats file '.._file_stats) serialize_to_file({}, _file_stats) else print ('Stats loaded: '.._file_stats) f:close() end return loadfile (_file_stats)() end local function save_stats() -- Save stats to file serialize_to_file(_stats, _file_stats) end local function get_stats_status( msg ) -- vardump(stats) local text = "" local to_id = tostring(msg.to.id) local rank = {} for id, user in pairs(_stats[to_id]) do table.insert(rank, user) end table.sort(rank, function(a, b) if a.msg_num and b.msg_num then return a.msg_num > b.msg_num end end ) for id, user in pairs(rank) do -- Previous versions didn't save that user_id = user.user_id or '' print(">> ", id, user.name) if user.last_name == nil then text = text..user.name.." ["..user_id.."]: "..user.msg_num.."\n" else text = text..user.name.." "..user.last_name.." ["..user_id.."]: "..user.msg_num.."\n" end end print("usuarios: "..text) return text end local function run(msg, matches) if matches[1] == "stats" then -- Hack return get_stats_status(msg) else print ("update stats") update_user_stats(msg) save_stats() end end _stats = read_file_stats() return { description = "Plugin to update user stats.", usage = "!stats: Returns a list of Username [telegram_id]: msg_num", patterns = { "^!(stats)", ".*" }, run = run } end
gpl-2.0
Turttle/darkstar
scripts/globals/logging.lua
8
6582
------------------------------------------------- -- Logging functions -- Info from: -- http://wiki.ffxiclopedia.org/wiki/Logging ------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ------------------------------------------------- -- npcid and drop by zone ------------------------------------------------- -- Zone, {npcid,npcid,npcid,..} local npcid = {2, {16785769,16785770,16785771,16785772}, -- Carpenter's Landing 24, {16875849,16875850,16875851,16875852,16875853,16875854}, -- Lufaise Meadows 25, {16879965,16879966,16879967,16879968,16879969,16879970}, -- Misareaux Coast 65, {17044010,17044011,17044012,17044013,17044014,17044015}, -- Mamook 79, {17101311,17101312,17101313,17101314,17101315,17101316}, -- Caedarva Mire 81, {17109782,17109783,17109784,17109785,17109786,17109787}, -- East Ronfaure [S] 82, {17113901,17113902,17113903,17113904,17113905,17113906}, -- Jugner Forest [S] 96, {17171239,17171240,17171241,17171242,17171243,17171244}, -- Fort Karugo-Narugo [S] 101,{17191526,17191527,17191528,17191529,17191530,17191531}, -- East Ronfaure 104,{17203860,17203861,17203862,17203863,17203864,17203865}, -- Jugner Forest 118,{17261171,17261172,17261173,17261174,17261175,17261176}, -- Buburimu Peninsula 123,{17281626,17281627,17281628,17281629,17281630,17281631}, -- Yuhtunga Jungle 124,{17285671,17285672,17285673,17285674,17285675,17285676}, -- Yhoator Jungle 140,{17350970,17350971,17350972,17350973}}; -- Ghelsba Outpost -- Zone, {itemid,drop rate,itemid,drop rate,..} -- Must be in ascending order by drop rate local drop = {2, {0x1198,0.0900,0x02B0,0.1800,0x02BA,0.2700,0x039B,0.3600,0x02B7,0.4500,0x02B5,0.7050,0x02B8,0.9600,0x02BB,1.0000}, 24, {0x02B5,0.0950,0x110B,0.1900,0x02B0,0.4400,0x02B3,0.6900,0x02BA,0.9400,0x02B2,0.9600,0x02BB,0.9800,0x1198,1.0000}, 25, {0x02B0,0.4000,0x02B5,0.4700,0x02B3,0.5400,0x110B,0.7400,0x02BA,0.9400,0x02B2,0.9600,0x02BB,0.9800,0x1198,1.0000}, 65, {0x15BE,0.2300,0x08A5,0.4600,0x02B6,0.5100,0x02BE,0.5600,0x02B1,0.6100,0x02BD,0.6590,0x09C7,0.7660,0x02D7,0.8730,0x02B0,0.9800,0x02D9,1.0000}, 79, {0x02D9,0.0392,0x02B6,0.0944,0x02BE,0.1666,0x02BD,0.2388,0x02B0,0.3590,0x08A5,0.4952,0x02B1,0.6474,0x09C7,0.8156,0x02D7,1.0000}, 81, {0x09E6,0.0030,0x09E4,0.0330,0x02BB,0.0660,0x023E,0.1110,0x02B5,0.1740,0x02B6,0.2640,0x027F,0.3810,0x02BA,0.5130,0x161D,0.6450,0x02B3,0.7950,0x02B0,1.0000}, 82, {0x02B0,0.1800,0x02BA,0.3600,0x02B5,0.5400,0x02B7,0.7200,0x02BB,0.7700,0x09E4,0.8200,0x1198,0.9000,0x161D,0.9800,0x09E6,1.0000}, 96, {0x46FF,0.0040,0x04D4,0.0240,0x034F,0.1630,0x11DA,0.3140,0x161E,0.4810,0x1612,0.7080,0x103A,1.0000}, 101,{0x02B6,0.0500,0x02B8,0.1130,0x023E,0.1760,0x02B6,0.2640,0x02B3,0.4760,0x02B0,0.7380,0x02BA,1.0000}, 104,{0x02BB,0.0120,0x1198,0.0600,0x039B,0.1320,0x02BA,0.2590,0x02B0,0.4220,0x02B7,0.5970,0x02B8,0.7900,0x02B5,1.0000}, 118,{0x02BC,0.0170,0x02BD,0.0430,0x02BE,0.0770,0x023E,0.1290,0x039B,0.2070,0x02B9,0.3020,0x1197,0.4050,0x115D,0.5600,0x02B0,0.7580,0x02B1,1.0000}, 123,{0x02B0,0.2350,0x02D1,0.4650,0x04A8,0.0500,0x02B1,0.7000,0x02B9,0.7700,0x03AC,0.8400,0x0390,0.9100,0x02BD,0.9400,0x02BE,0.9700,0x04D5,1.0000}, 124,{0x02BE,0.0120,0x04A8,0.0500,0x02BC,0.0520,0x03AC,0.0920,0x039B,0.1620,0x0390,0.3070,0x02B1,0.4780,0x02B0,0.7290,0x02D1,0.9800,0x04D5,1.0000}, 140,{0x02B9,0.0530,0x02B2,0.1060,0x02B7,0.2050,0x02B3,0.4400,0x02BA,0.6950,0x02B0,1.0000}}; function startLogging(player,zone,npc,trade,csid) if (trade:hasItemQty(1021,1) and trade:getItemCount() == 1) then local broke = hatchetBreak(player,trade); local item = getLoggingItem(player,zone); if (player:getFreeSlotsCount() == 0) then full = 1; else full = 0; end player:startEvent(csid,item,broke,full); if (item ~= 0 and full == 0) then player:addItem(item); SetServerVariable("[LOGGING]Zone "..zone,GetServerVariable("[LOGGING]Zone "..zone) + 1); end if (GetServerVariable("[LOGGING]Zone "..zone) >= 3) then getNewLoggingPositionNPC(player,npc,zone); end else player:messageSpecial(LOGGING_IS_POSSIBLE_HERE,1021); end end ----------------------------------- -- Determine if Hatchet breaks ----------------------------------- function hatchetBreak(player,trade) local broke = 0; local hatchetbreak = math.random(); hatchetbreak = hatchetbreak + (player:getMod(MOD_LOGGING_RESULT) / 1000); if (hatchetbreak < LOGGING_BREAK_CHANCE) then broke = 1; player:tradeComplete(); end return broke; end ----------------------------------- -- Get an item ----------------------------------- function getLoggingItem(player,zone) local Rate = math.random(); for zon = 1, table.getn(drop), 2 do if (drop[zon] == zone) then for itemlist = 1, table.getn(drop[zon + 1]), 2 do if (Rate <= drop[zon + 1][itemlist + 1]) then item = drop[zon + 1][itemlist]; break; end end break; end end -------------------- -- Determine chance of no item mined -- Default rate is 50% -------------------- Rate = math.random(); if (Rate <= (1 - LOGGING_RATE)) then item = 0; end return item; end ----------------------------------------- -- After 3 items he change the position ----------------------------------------- function getNewLoggingPositionNPC(player,npc,zone) local newnpcid = npc:getID(); for u = 1, table.getn(npcid), 2 do if (npcid[u] == zone) then nbNPC = table.getn(npcid[u + 1]); while newnpcid == npc:getID() do newnpcid = math.random(1,nbNPC); newnpcid = npcid[u + 1][newnpcid]; end break; end end npc:setStatus(2); GetNPCByID(newnpcid):setStatus(0); SetServerVariable("[LOGGING]Zone "..zone,0); end
gpl-3.0
dickeyf/darkstar
scripts/globals/items/cup_of_healing_tea.lua
17
1358
----------------------------------------- -- ID: 4286 -- Item: cup_of_healing_tea -- Food Effect: 240Min, All Races ----------------------------------------- -- Magic 10 -- Vitality -1 -- Charisma 3 -- Magic Regen While Healing 2 ----------------------------------------- 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,4286); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 10); target:addMod(MOD_VIT, -1); target:addMod(MOD_CHR, 3); target:addMod(MOD_MPHEAL, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 10); target:delMod(MOD_VIT, -1); target:delMod(MOD_CHR, 3); target:delMod(MOD_MPHEAL, 2); end;
gpl-3.0
dickeyf/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/Icon_Prototype.lua
6
1392
----------------------------------- -- Area: Dynamis Xarcabard -- MOB: Icon Prototype ----------------------------------- package.loaded["scripts/zones/Dynamis-Xarcabard/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob,target) end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) local mobID = mob:getID(); -- Time Bonus: 043 if (mobID == 17330814 and mob:isInBattlefieldList() == false) then ally:addTimeToDynamis(30); mob:addInBattlefieldList(); -- HP Bonus: 052 elseif (mobID == 17330533) then ally:restoreHP(2000); ally:messageBasic(024,(ally:getMaxHP()-ally:getHP())); -- HP Bonus: 073 elseif (mobID == 17330843) then ally:restoreMP(2000); ally:messageBasic(025,(ally:getMaxMP()-ally:getMP())); end end;
gpl-3.0
Turttle/darkstar
scripts/globals/items/culinarians_belt.lua
30
1201
----------------------------------------- -- ID: 15451 -- Item: Culinarian's Belt -- Enchantment: Synthesis image support -- 2Min, All Races ----------------------------------------- -- Enchantment: Synthesis image support -- Duration: 2Min -- Alchemy Skill +3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_COOKING_IMAGERY) == true) then result = 243; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_COOKING_IMAGERY,3,0,120); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_SKILL_COK, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_SKILL_COK, 1); end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c69838592.lua
2
3635
--妖仙獣 大幽谷響 function c69838592.initial_effect(c) --spsummon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(69838592,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_ATTACK_ANNOUNCE) e1:SetRange(LOCATION_HAND) e1:SetCountLimit(1,69838592) e1:SetCondition(c69838592.spcon) e1:SetCost(c69838592.spcost) e1:SetTarget(c69838592.sptg) e1:SetOperation(c69838592.spop) c:RegisterEffect(e1) --atk local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(69838592,1)) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_BATTLE_START) e2:SetCondition(c69838592.condition) e2:SetOperation(c69838592.operation) c:RegisterEffect(e2) --tohand local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(69838592,2)) e3:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_BATTLE_DESTROYED) e3:SetCondition(c69838592.thcon) e3:SetTarget(c69838592.thtg) e3:SetOperation(c69838592.thop) c:RegisterEffect(e3) end function c69838592.spcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetAttacker():IsControler(1-tp) and Duel.GetAttackTarget()==nil end function c69838592.cfilter(c) return c:IsSetCard(0xb3) and c:IsType(TYPE_MONSTER) and not c:IsCode(69838592) and c:IsAbleToGraveAsCost() end function c69838592.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c69838592.cfilter,tp,LOCATION_HAND,0,1,nil) end Duel.DiscardHand(tp,c69838592.cfilter,1,1,REASON_COST) end function c69838592.sptg(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 c69838592.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsRelateToEffect(e) then return end Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP) end function c69838592.filter(c,tc) if not c:IsFaceup() then return false end return tc:GetBaseAttack()~=c:GetAttack() or tc:GetBaseAttack()~=c:GetDefense() end function c69838592.condition(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local bc=c:GetBattleTarget() return c:IsRelateToBattle() and bc and c69838592.filter(c,bc) and bc:IsFaceup() and bc:IsRelateToBattle() end function c69838592.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local bc=c:GetBattleTarget() if c:IsFaceup() and c:IsRelateToBattle() and bc:IsFaceup() and bc:IsRelateToBattle() then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SET_ATTACK_FINAL) e1:SetValue(bc:GetBaseAttack()) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EFFECT_SET_DEFENSE_FINAL) c:RegisterEffect(e2) end end function c69838592.thcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsLocation(LOCATION_GRAVE) and e:GetHandler():IsReason(REASON_BATTLE) end function c69838592.thfilter(c) return c:IsSetCard(0xb3) and c:IsAbleToHand() end function c69838592.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c69838592.thfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c69838592.thop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c69838592.thfilter,tp,LOCATION_DECK,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
dickeyf/darkstar
scripts/zones/RuLude_Gardens/npcs/_6r9.lua
13
2996
----------------------------------- -- Area: Ru'Lude Gardens -- NPC: Audience Chamber -- Involved in Mission: Magicite -- @pos 0 -5 66 243 ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/missions"); require("scripts/zones/RuLude_Gardens/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) CurrentMission = player:getCurrentMission(player:getNation()); if ( player:getCurrentMission(COP) ==MORE_QUESTIONS_THAN_ANSWERS and player:getVar("PromathiaStatus")==1) then player:startEvent(0x2742); elseif (player:hasKeyItem(ARCHDUCAL_AUDIENCE_PERMIT) and CurrentMission == 255 and player:getVar("MissionStatus") == 1) then player:startEvent(0x0080); elseif (player:hasKeyItem(MAGICITE_OPTISTONE) and player:hasKeyItem(MAGICITE_AURASTONE) and player:hasKeyItem(MAGICITE_ORASTONE)) then if (player:hasKeyItem(AIRSHIP_PASS)) then player:startEvent(0x003c,1); else player:startEvent(0x003c); end elseif (player:hasKeyItem(ARCHDUCAL_AUDIENCE_PERMIT)) then player:messageSpecial(SOVEREIGN_WITHOUT_AN_APPOINTMENT); else player:startEvent(0x008a); -- you don't have a permit 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 == 0x0080) then player:setVar("MissionStatus",2); player:addMission(player:getNation(),13); player:addKeyItem(LETTERS_TO_ALDO); player:messageSpecial(KEYITEM_OBTAINED,LETTERS_TO_ALDO); elseif (csid == 0x003c) then player:delKeyItem(MAGICITE_OPTISTONE); player:delKeyItem(MAGICITE_AURASTONE); player:delKeyItem(MAGICITE_ORASTONE); if (player:hasKeyItem(AIRSHIP_PASS)) then player:addGil(GIL_RATE*20000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*20000); player:addTitle(CONQUEROR_OF_FATE); else player:addKeyItem(AIRSHIP_PASS); player:messageSpecial(KEYITEM_OBTAINED,AIRSHIP_PASS); player:addTitle(HAVE_WINGS_WILL_FLY); end player:setVar("MissionStatus",6); -- all that's left is to go back to the embassy elseif (csid == 0x2742) then player:setVar("PromathiaStatus",2); end end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c564541.lua
5
1808
--ミンゲイドラゴン function c564541.initial_effect(c) --double tribute local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_DOUBLE_TRIBUTE) e1:SetValue(c564541.dccon) c:RegisterEffect(e1) --Special Summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(564541,0)) e2:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_FIELD) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetCode(EVENT_PHASE+PHASE_STANDBY) e2:SetRange(LOCATION_GRAVE) e2:SetCountLimit(1) e2:SetCondition(c564541.spcon) e2:SetTarget(c564541.sptg) e2:SetOperation(c564541.spop) c:RegisterEffect(e2) end function c564541.dccon(e,c) return c:IsRace(RACE_DRAGON) end function c564541.cfilter(c) return c:IsType(TYPE_MONSTER) and not c:IsRace(RACE_DRAGON) end function c564541.spcon(e,tp,eg,ep,ev,re,r,rp) return tp==Duel.GetTurnPlayer() and Duel.GetFieldGroupCount(tp,LOCATION_MZONE,0)==0 and not Duel.IsExistingMatchingCard(c564541.cfilter,tp,LOCATION_GRAVE,0,1,nil) end function c564541.sptg(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 c564541.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and Duel.GetFieldGroupCount(tp,LOCATION_MZONE,0)==0 and not Duel.IsExistingMatchingCard(c564541.cfilter,tp,LOCATION_GRAVE,0,1,nil) then Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP_ATTACK) local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_LEAVE_FIELD_REDIRECT) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetReset(RESET_EVENT+0x47e0000) e1:SetValue(LOCATION_REMOVED) c:RegisterEffect(e1,true) end end
gpl-2.0
Turttle/darkstar
scripts/globals/items/slice_of_buffalo_meat.lua
18
1424
----------------------------------------- -- ID: 5152 -- Item: slice_of_buffalo_meat -- Food Effect: 5Min, Galka only ----------------------------------------- -- Strength 4 -- Agility -5 -- Intelligence -7 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 8) then result = 247; end if (target:getMod(MOD_EAT_RAW_MEAT) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5152); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 4); target:addMod(MOD_AGI, -5); target:addMod(MOD_INT, -7); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 4); target:delMod(MOD_AGI, -5); target:delMod(MOD_INT, -7); end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c171.lua
2
1523
--捨て猫娘 Stray Catgirl function c171.initial_effect(c) --battle indestructable local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_INDESTRUCTABLE_BATTLE) e1:SetCondition(c171.con) e1:SetValue(1) c:RegisterEffect(e1) --Special Summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(171,0)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_ATTACK_ANNOUNCE) e2:SetRange(LOCATION_HAND) e2:SetTarget(c171.target) e2:SetCost(c171.cost) e1:SetCondition(c171.condition) e2:SetOperation(c171.operation) c:RegisterEffect(e2) end function c171.costfilter(c) return c:GetLevel()==1 and c:IsRace(RACE_BEAST) end function c171.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckReleaseGroup(tp,c171.costfilter,1,nil) end local sg=Duel.SelectReleaseGroup(tp,c171.costfilter,1,1,nil) Duel.Release(sg,REASON_COST) end function c171.target(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,0,0) end function c171.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 function c171.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()~=tp end function c171.con(e,c) return e:GetHandler():IsAttackPos() end
gpl-2.0
Turttle/darkstar
scripts/globals/spells/bluemagic/ram_charge.lua
27
1737
----------------------------------------- -- Spell: Ram Charge -- Damage varies with TP -- Spell cost: 79 MP -- Monster Type: Beasts -- Spell Type: Physical (Blunt) -- Blue Magic Points: 4 -- Stat Bonus: HP+5 -- Level: 73 -- Casting Time: 0.5 seconds -- Recast Time: 34.75 seconds -- Skillchain Element(s): Fragmentation (can open/close Light with Fusion WSs and spells) -- Combos: Lizard Killer ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_DAMAGE; params.dmgtype = DMGTYPE_BLUNT; params.scattr = SC_FRAGMENTATION; params.numhits = 1; params.multiplier = 1.0; params.tp150 = 1.375; params.tp300 = 1.75; params.azuretp = 1.875; params.duppercap = 75; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.5; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); -- Missing KNOCKBACK effect return damage; end;
gpl-3.0
dickeyf/darkstar
scripts/globals/spells/bluemagic/regeneration.lua
46
1483
----------------------------------------- -- Spell: Regeneration -- Gradually restores HP -- Spell cost: 36 MP -- Monster Type: Aquans -- Spell Type: Magical (Light) -- Blue Magic Points: 2 -- Stat Bonus: MND+2 -- Level: 78 -- Casting Time: 2 Seconds -- Recast Time: 60 Seconds -- Spell Duration: 30 ticks, 90 Seconds -- -- Combos: None ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffect = EFFECT_REGEN; local power = 25; local duration = 90; if (caster:hasStatusEffect(EFFECT_DIFFUSION)) then local diffMerit = caster:getMerit(MERIT_DIFFUSION); if (diffMerit > 0) then duration = duration + (duration/100)* diffMerit; end; caster:delStatusEffect(EFFECT_DIFFUSION); end; if (target:hasStatusEffect(EFFECT_REGEN) and target:getStatusEffect(EFFECT_REGEN):getTier() == 1) then target:delStatusEffect(EFFECT_REGEN); end if (target:addStatusEffect(typeEffect,power,3,duration,0,0,0) == false) then spell:setMsg(75); end; return typeEffect; end;
gpl-3.0
fgenesis/Aquaria_experimental
game_scripts/scripts/entities/seaturtlebaby-special1.lua
6
1141
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end -- ================================================================================================ -- B A B Y S E A T U R T L E -- ================================================================================================ dofile("scripts/entities/seaturtlecommon.lua") function init(me) v.commonInit(me, 4) end
gpl-2.0
Turttle/darkstar
scripts/zones/Windurst_Walls/Zone.lua
28
2946
----------------------------------- -- -- Zone: Windurst_Walls (239) -- ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/zones/Windurst_Walls/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) zone:registerRegion(1, -2,-17,140, 2,-16,142); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; -- MOG HOUSE EXIT if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then position = math.random(1,5) - 123; player:setPos(-257.5,-5.05,position,0); if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then cs = 0x7534; end player:setVar("PlayerMainJob",0); elseif (ENABLE_ASA == 1 and player:getCurrentMission(ASA) == A_SHANTOTTO_ASCENSION and (prevZone == 238 or prevZone == 241) and player:getMainLvl()>=10) then cs = 0x01fe; 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) switch (region:GetRegionID()): caseof { [1] = function (x) -- Heaven's Tower enter portal player:startEvent(0x56); end, } end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x56) then player:setPos(0,0,-22.40,192,242); elseif (csid == 0x7534 and option == 0) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); elseif (csid == 0x01fe) then player:startEvent(0x0202); elseif (csid == 0x0202) then player:completeMission(ASA,A_SHANTOTTO_ASCENSION); player:addMission(ASA,BURGEONING_DREAD); player:setVar("ASA_Status",0); end end;
gpl-3.0
Turttle/darkstar
scripts/zones/Valkurm_Dunes/npcs/Quanteilleron_RK.lua
28
3133
----------------------------------- -- Area: Valkurm Dunes -- NPC: Quanteilleron, R.K. -- Outpost Conquest Guards -- @pos 144 -7 104 103 ------------------------------------- package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil; ------------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Valkurm_Dunes/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ZULKHEIM; local csid = 0x7ffb; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
mimetic/DIG-corona-library
examples/slideviewer+textrender+accordion/scripts/dmc/dmc_corona/dmc_wamp/auth.lua
1
4563
--====================================================================-- -- dmc_wamp/auth.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2014-2015 David McCuskey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] --====================================================================-- --== DMC Corona Library : DMC WAMP Auth --====================================================================-- --[[ Wamp support adapted from: * AutobahnPython (https://github.com/tavendo/AutobahnPython/) --]] -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.1.0" --====================================================================-- --== Imports local crypto = require 'crypto' local mime = require 'mime' local mbase64_encode = mime.b64 --====================================================================-- --== Setup, Constants -- The characters from which :func:`autobahn.wamp.auth.generate_wcs` -- generates secrets local WCS_SECRET_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" --====================================================================-- --== Support Functions local function generate_totp_secret( length ) -- print( "dmc_wamp.auth.generate_totp_secret ", length ) --==-- length = length or 10 assert( type( length ) == 'number' ) error( "not implemented" ) end local function compute_totp( secret, offset ) -- print( "dmc_wamp.auth.compute_totp ", secret, offset ) --==-- offset = offset or 0 assert( type( secret ) == 'string' ) assert( type( length ) == 'number' ) error( "not implemented" ) end local function pbkdf2( params ) -- print( "dmc_wamp.auth.pbkdf2 ", params ) params = params or {} --==-- local data, salt = params.data, params.salt local iterations = params.iterations or 1000 local keylen = params.keylen or 32 local hashfunc = params.hashfunc or crypto.sha256 assert( type( data ) == 'string' ) assert( type( salt ) == 'string' ) assert( type( iterations ) == 'number' ) assert( type( keylen ) == 'number' ) assert( type( hashfunc ) == 'function' ) -- return _pdkdf2( data, salt, iterations, keylen, hashfunc ) error( "not implemented" ) end local function derive_key( params ) -- print( "dmc_wamp.auth.derive_key ", params ) params = params or {} --==-- local secret, salt = params.secret, params.salt local iterations = params.iterations or 1000 local keylen = params.keylen or 32 assert( type( secret ) == 'string' ) assert( type( salt ) == 'string' ) assert( type( iterations ) == 'number' ) assert( type( keylen ) == 'number' ) error( "not implemented" ) end local function generate_wcs( length ) -- print( "dmc_wamp.auth.generate_wcs ", length ) --==-- length = length or 10 assert( type( length ) == 'number' ) error( "not implemented" ) end local function compute_wcs( key, challenge ) -- print( "dmc_wamp.auth.compute_wcs ", key, challenge ) --==-- assert( type( key ) == 'string' ) assert( type( challenge ) == 'string' ) local sig = crypto.hmac( crypto.sha256, challenge, key, true ) return mbase64_encode( sig ) end --====================================================================-- --== Auth Exports --====================================================================-- return { generate_totp_secret=generate_totp_secret, compute_totp=compute_totp, pbkdf2=pbkdf2, derive_key=derive_key, generate_wcs=generate_wcs, compute_wcs=compute_wcs }
mit
Turttle/darkstar
scripts/globals/items/prized_seafood_stewpot.lua
36
1865
----------------------------------------- -- ID: 5240 -- Item: Prized Seafood Stewpot -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +10% Cap 100 -- MP +20 -- Dexterity 2 -- Vitality 2 -- Agility 2 -- Mind 2 -- HP Recovered while healing 9 -- MP Recovered while healing 3 -- Accuracy 7 -- Evasion 7 ----------------------------------------- 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,5240); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 10); target:addMod(MOD_FOOD_HP_CAP, 100); target:addMod(MOD_MP, 20); target:addMod(MOD_DEX, 2); target:addMod(MOD_VIT, 2); target:addMod(MOD_AGI, 2); target:addMod(MOD_MND, 2); target:addMod(MOD_HPHEAL, 9); target:addMod(MOD_MPHEAL, 3); target:addMod(MOD_ACC, 7); target:addMod(MOD_EVA, 7); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 10); target:delMod(MOD_FOOD_HP_CAP, 100); target:delMod(MOD_MP, 20); target:delMod(MOD_DEX, 2); target:delMod(MOD_VIT, 2); target:delMod(MOD_AGI, 2); target:delMod(MOD_MND, 2); target:delMod(MOD_HPHEAL, 9); target:delMod(MOD_MPHEAL, 3); target:delMod(MOD_ACC, 7); target:delMod(MOD_EVA, 7); end;
gpl-3.0
dickeyf/darkstar
scripts/zones/Bastok_Markets/npcs/Khonzon.lua
13
1054
----------------------------------- -- Area: Bastok Markets -- NPC: Khonzon -- Type: Item Deliverer -- @zone: 235 -- @pos -323.744 -16.001 -88.698 -- ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, ITEM_DELIVERY_DIALOG); player:openSendBox(); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Turttle/darkstar
scripts/zones/Buburimu_Peninsula/npcs/Signpost.lua
19
1356
----------------------------------- -- Area: Buburimu Peninsula -- NPC: Signpost ----------------------------------- package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Buburimu_Peninsula/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (npc:getID() == 17261155) then player:messageSpecial(SIGN_5); elseif (npc:getID() == 17261156) then player:messageSpecial(SIGN_4); elseif (npc:getID() == 17261157) then player:messageSpecial(SIGN_3); elseif (npc:getID() == 17261158) then player:messageSpecial(SIGN_2); elseif (npc:getID() == 17261159) or (npc:getID() == 17261160) or (npc:getID() == 17261161) then player:messageSpecial(SIGN_1); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --print("CSID: %u",csid); --print("RESULT: %u",option); end;
gpl-3.0
eugeneia/snabb
lib/ljsyscall/syscall/ffitypes.lua
24
2200
-- these are types which are currently the same for all ports -- in a module so rump does not import twice -- note that even if type is same (like pollfd) if the metatype is different cannot be here due to ffi -- TODO not sure we want these long term, merge to individual OS files. local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local ffi = require "ffi" local abi = require "syscall.abi" local defs = {} local function append(str) defs[#defs + 1] = str end append [[ // 8 bit typedef unsigned char cc_t; // 16 bit typedef uint16_t in_port_t; // 32 bit typedef uint32_t uid_t; typedef uint32_t gid_t; typedef int32_t pid_t; typedef unsigned int socklen_t; // 64 bit typedef int64_t off_t; // defined as long even though eg NetBSD defines as int on 32 bit, its the same. typedef long ssize_t; typedef unsigned long size_t; // sighandler in Linux typedef void (*sig_t)(int); struct iovec { void *iov_base; size_t iov_len; }; struct winsize { unsigned short ws_row; unsigned short ws_col; unsigned short ws_xpixel; unsigned short ws_ypixel; }; struct in_addr { uint32_t s_addr; }; struct in6_addr { unsigned char s6_addr[16]; }; struct ethhdr { unsigned char h_dest[6]; unsigned char h_source[6]; unsigned short h_proto; /* __be16 */ } __attribute__((packed)); struct udphdr { uint16_t source; uint16_t dest; uint16_t len; uint16_t check; }; ]] -- endian dependent TODO not really, define in independent way if abi.le then append [[ struct iphdr { uint8_t ihl:4, version:4; uint8_t tos; uint16_t tot_len; uint16_t id; uint16_t frag_off; uint8_t ttl; uint8_t protocol; uint16_t check; uint32_t saddr; uint32_t daddr; }; ]] else append [[ struct iphdr { uint8_t version:4, ihl:4; uint8_t tos; uint16_t tot_len; uint16_t id; uint16_t frag_off; uint8_t ttl; uint8_t protocol; uint16_t check; uint32_t saddr; uint32_t daddr; }; ]] end ffi.cdef(table.concat(defs, ""))
apache-2.0
mchaza/soka
src/agent.lua
1
5890
require 'libraries/vector' require 'ball' Agent = {} function Agent:new(x, y, vx, vy, i, team) local instance = {} setmetatable(instance, self) self.__index = self --instance.prevPos = Vector:new(x, y) instance.position = Vector:new(x, y) instance.velocity = Vector:new(vx, vy) instance.index = i instance.team = team -- instance of the root team object instance.size = Global[findGlobal('Agent size')].value instance.width = instance.size * scalefactor.x instance.height = instance.size * scalefactor.x --instance.speed = scalefactor.x * 30 instance.dashed = false instance.dash_time = 0.0 instance.dash_dir = Vector:new(0, 0) instance.steal_dir = Vector:new(0, 0) instance.stolen = false instance.steal_time = 0 instance.kicked = false instance.kick_timer = 0 instance.pickup_delay = Global[findGlobal('Agent pickup_delay')].value instance.steal_delay = Global[findGlobal('Agent steal_delay')].value instance.canSteal = true instance.steal_timer = 0 instance.shadowDist = Global[findGlobal('Agent shadow Distance')].value instance.shadowMin = Global[findGlobal('Agent shadow min distance')].value instance.shadowMax = Global[findGlobal('Agent shadow max distance')].value instance.moveIn = false; instance.shadowSpeed = {} instance.shadowSpeed.up = Global[findGlobal('Agent Shadow Speed up')].value instance.shadowSpeed.down = Global[findGlobal('Agent Shadow Speed down')].value instance.moving = false if team.no == 1 then instance.color = {r = 51, g = 153, b = 255} else instance.color = {r = 255, g = 102, b = 102} end return instance end function Agent:drawShadow() local pos = self.position local w = self.width local h = self.height --shadow love.graphics.setColor(0, 0, 0, 100) love.graphics.rectangle("fill", pos.x - w/2, pos.y - h/4, w, h) end function Agent:draw() local pos = self.position local w = self.width local h = self.height local text = self.index love.graphics.setColor(self.color.r, self.color.g, self.color.b, 255) love.graphics.rectangle("fill", pos.x - w/2, pos.y- w/self.shadowDist, w, h) end function Agent:update(dt, speed) if not self.kicked then ball:pickup(self) else self.kick_timer = self.kick_timer - dt if self.kick_timer < 0 then self.kicked = false end end ball:steal(self) --self:limit_speed(dt) self:move(dt, speed) self:constrain(dt, speed) self:dash(dt, speed) self:knock(dt, speed) self:bobbing(dt) if not self.canSteal then self.steal_timer = self.steal_time - dt if self.steal_timer < 0.25 then self.canSteal = true end end end function Agent:bobbing(dt) if self.moveIn then if self.shadowDist > self.shadowMin then if self.moving then self.shadowDist = self.shadowDist - self.shadowSpeed.down/2 * dt else self.shadowDist = self.shadowDist - self.shadowSpeed.down * dt end else self.moveIn = false end else if self.shadowDist < self.shadowMax then if self.moving then self.shadowDist = self.shadowDist + self.shadowSpeed.up/2 * dt else self.shadowDist = self.shadowDist + self.shadowSpeed.up * dt end else self.moveIn = true end end end function Agent:dash(dt, speed) if not self.dashed then return end if self.dash_time > 0.0 then self.position.x = self.position.x + (-self.dash_dir.x * dt * speed/2 ) self.position.y = self.position.y + (-self.dash_dir.y * dt * speed/2 ) self.dash_time = self.dash_time - dt else self.dashed = false end end function Agent:knock(dt, speed) if not self.stolen then return end if self.steal_time > 0.0 then self.position.x = self.position.x + (-self.steal_dir.x * dt * speed/2) self.position.y = self.position.y + (-self.steal_dir.y * dt * speed/2) self.steal_time = self.steal_time - dt end end function Agent:move(dt, speed) local x = (self.team.controls.controller.Axes.LeftX * speed * dt) local y = (self.team.controls.controller.Axes.LeftY * speed * dt) self.velocity.x = x self.velocity.y = y self.position.x = self.position.x + x self.position.y = self.position.y + y if x ~= 0 or y ~= 0 then self.moving = true else self.moving = false end end function Agent:spin(dt) if self.spinDirection > 0 then self.angle = self.angle + self.spinSpeed * dt else self.angle = self.angle - self.spinSpeed * dt end end function Agent:limit_speed(dt) self.velocity = (self.position - self.prevPos) / dt --print("velocity : "..self.velocity:toString()) --[[if self.velocity:r() > 100 then self.velocity = self.velocity / self.velocity:r() * 100 end if self.velocity:r() < 70 then self.velocity = self.velocity / self.velocity:r() * 70 end]] end function Agent:constrain(dt, speed) local carrydist = {x = 0, y = 0} if ball.holder.current == self then carrydist.x = self.team.controls.controller.Axes.LeftX * ball.size * 2 * scalefactor.x carrydist.y = self.team.controls.controller.Axes.LeftY * ball.size * 2 * scalefactor.x end if self.position.x + self.width/2 + carrydist.x >= (100 - (100 - level.field_size.x)/2) * scalefactor.x then self.position = Vector:new(((100 - (98 - level.field_size.x)/2) * scalefactor.x) - (self.width + carrydist.x), self.position.y) end if self.position.x - self.width/2 + carrydist.x <= (100 - level.field_size.x)/2 * scalefactor.x then self.position = Vector:new(((98 - level.field_size.x)/2 * scalefactor.x) + (self.width - carrydist.x), self.position.y) end if self.position.y + self.height/2 + carrydist.y >= (100 + level.field_size.y)/2 * scalefactor.y then self.position = Vector:new(self.position.x, ((100 + level.field_size.y)/2 * scalefactor.y)- self.height/2 - carrydist.y) end if self.position.y - self.height/2 + carrydist.y <= (100 - level.field_size.y)/2 * scalefactor.y then self.position = Vector:new(self.position.x ,((100 - level.field_size.y)/2 * scalefactor.y)+ self.height/2 - carrydist.y) end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c78274190.lua
4
2604
--超重輝将サン-5 function c78274190.initial_effect(c) --pendulum summon aux.EnablePendulumAttribute(c) --scale local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_CHANGE_LSCALE) e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e2:SetRange(LOCATION_PZONE) e2:SetCondition(c78274190.sccon) e2:SetValue(4) c:RegisterEffect(e2) local e3=e2:Clone() e3:SetCode(EFFECT_CHANGE_RSCALE) c:RegisterEffect(e3) --chain attack local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(78274190,0)) e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e4:SetCode(EVENT_BATTLE_DESTROYING) e4:SetRange(LOCATION_PZONE) e4:SetCountLimit(1) e4:SetTarget(c78274190.catg) e4:SetOperation(c78274190.caop) c:RegisterEffect(e4) --draw local e5=Effect.CreateEffect(c) e5:SetDescription(aux.Stringid(78274190,1)) e5:SetCategory(CATEGORY_DRAW) e5:SetType(EFFECT_TYPE_IGNITION) e5:SetRange(LOCATION_MZONE) e5:SetCountLimit(1,78274190) e5:SetCondition(c78274190.condition) e5:SetCost(c78274190.cost) e5:SetTarget(c78274190.target) e5:SetOperation(c78274190.operation) c:RegisterEffect(e5) end function c78274190.sccon(e) local tp=e:GetHandlerPlayer() return Duel.IsExistingMatchingCard(Card.IsType,tp,LOCATION_GRAVE,0,1,nil,TYPE_SPELL+TYPE_TRAP) end function c78274190.afilter(c,tp) return c:IsControler(tp) and c:IsSetCard(0x9a) and c:IsChainAttackable() end function c78274190.catg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return eg:IsExists(c78274190.afilter,1,nil,tp) end local a=eg:Filter(c78274190.afilter,nil,tp):GetFirst() Duel.SetTargetCard(a) end function c78274190.caop(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end local tc=Duel.GetFirstTarget() if tc:IsFaceup() and tc:IsControler(tp) and tc:IsRelateToBattle() then Duel.ChainAttack() end end function c78274190.condition(e,tp,eg,ep,ev,re,r,rp) return not Duel.IsExistingMatchingCard(Card.IsType,tp,LOCATION_GRAVE,0,1,nil,TYPE_SPELL+TYPE_TRAP) end function c78274190.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckReleaseGroup(tp,Card.IsSetCard,1,nil,0x9a) end local ct=Duel.GetFieldGroupCount(tp,LOCATION_DECK,0) if ct>2 then ct=2 end local g=Duel.SelectReleaseGroup(tp,Card.IsSetCard,1,ct,nil,0x9a) local rct=Duel.Release(g,REASON_COST) e:SetLabel(rct) end function c78274190.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,e:GetLabel()) end function c78274190.operation(e,tp,eg,ep,ev,re,r,rp) Duel.Draw(tp,e:GetLabel(),REASON_EFFECT) end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c24590232.lua
2
2056
--王魂調和 function c24590232.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_ATTACK_ANNOUNCE) e1:SetCondition(c24590232.condition) e1:SetOperation(c24590232.activate) c:RegisterEffect(e1) end function c24590232.condition(e,tp,eg,ep,ev,re,r,rp) return eg:GetFirst():IsControler(1-tp) and Duel.GetAttackTarget()==nil end function c24590232.filter1(c,e,tp) local lv=c:GetLevel() return c:IsType(TYPE_SYNCHRO) and lv<9 and c:IsCanBeSpecialSummoned(e,SUMMON_TYPE_SYNCHRO,tp,false,false) and Duel.IsExistingMatchingCard(c24590232.filter2,tp,LOCATION_GRAVE,0,1,nil,tp,lv) end function c24590232.filter2(c,tp,lv) local rlv=lv-c:GetLevel() local rg=Duel.GetMatchingGroup(c24590232.filter3,tp,LOCATION_GRAVE,0,c) return rlv>0 and c:IsType(TYPE_TUNER) and c:IsAbleToRemove() and rg:CheckWithSumEqual(Card.GetLevel,rlv,1,63) end function c24590232.filter3(c) return c:GetLevel()>0 and not c:IsType(TYPE_TUNER) and c:IsAbleToRemove() end function c24590232.activate(e,tp,eg,ep,ev,re,r,rp) if Duel.NegateAttack() and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c24590232.filter1,tp,LOCATION_EXTRA,0,1,nil,e,tp) and Duel.SelectYesNo(tp,aux.Stringid(24590232,0)) then Duel.BreakEffect() Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g1=Duel.SelectMatchingCard(tp,c24590232.filter1,tp,LOCATION_EXTRA,0,1,1,nil,e,tp) local lv=g1:GetFirst():GetLevel() Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g2=Duel.SelectMatchingCard(tp,c24590232.filter2,tp,LOCATION_GRAVE,0,1,1,nil,tp,lv) local rlv=lv-g2:GetFirst():GetLevel() local rg=Duel.GetMatchingGroup(c24590232.filter3,tp,LOCATION_GRAVE,0,g2:GetFirst()) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g3=rg:SelectWithSumEqual(tp,Card.GetLevel,rlv,1,63) g2:Merge(g3) Duel.Remove(g2,POS_FACEUP,REASON_EFFECT) Duel.SpecialSummon(g1,SUMMON_TYPE_SYNCHRO,tp,tp,false,false,POS_FACEUP) g1:GetFirst():CompleteProcedure() end end
gpl-2.0
dickeyf/darkstar
scripts/globals/spells/bluemagic/amplification.lua
27
1938
----------------------------------------- -- Spell: Amplification -- Enhances magic attack and magic defense -- Spell cost: 48 MP -- Monster Type: Amorphs -- Spell Type: Magical (Water) -- Blue Magic Points: 3 -- Stat Bonus: HP-5, MP+5 -- Level: 70 -- Casting Time: 7 seconds -- Recast Time: 120 seconds -- Duration: 90 seconds -- -- Combos: None ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffectOne = EFFECT_MAGIC_ATK_BOOST local typeEffectTwo = EFFECT_MAGIC_DEF_BOOST local power = 10; local duration = 90; local returnEffect = typeEffectOne; if (caster:hasStatusEffect(EFFECT_DIFFUSION)) then local diffMerit = caster:getMerit(MERIT_DIFFUSION); if (diffMerit > 0) then duration = duration + (duration/100)* diffMerit; end; caster:delStatusEffect(EFFECT_DIFFUSION); end; if (target:addStatusEffect(typeEffectOne,power,0,duration) == false and target:addStatusEffect(typeEffectTwo,power,0,duration) == false) then -- both statuses fail to apply spell:setMsg(75); elseif (target:addStatusEffect(typeEffectOne,power,0,duration) == false) then -- the first status fails to apply target:addStatusEffect(typeEffectTwo,power,0,duration) spell:setMsg(230); returnEffect = typeEffectTwo; else target:addStatusEffect(typeEffectOne,power,0,duration) target:addStatusEffect(typeEffectTwo,power,0,duration) spell:setMsg(230); end; return returnEffect; end;
gpl-3.0
puug/kong
kong/plugins/httplog/log.lua
1
2287
local cjson = require "cjson" local url = require "socket.url" local _M = {} -- Generates http payload . -- @param `method` http method to be used to send data -- @param `parsed_url` contains the host details -- @param `message` Message to be logged -- @return `payload` http payload local function generate_post_payload(method, parsed_url, message) local body = cjson.encode(message); local payload = string.format( "%s %s HTTP/1.1\r\nHost: %s\r\nConnection: Keep-Alive\r\nContent-Type: application/json\r\nContent-Length: %s\r\n\r\n%s", method:upper(), parsed_url.path, parsed_url.host, string.len(body), body) return payload end -- Parse host url -- @param `url` host url -- @return `parsed_url` a table with host details like domain name, port, path etc local function parse_url(host_url) local parsed_url = url.parse(host_url) if not parsed_url.port then if parsed_url.scheme == "http" then parsed_url.port = 80 elseif parsed_url.scheme == "https" then parsed_url.port = 443 end end if not parsed_url.path then parsed_url.path = "/" end return parsed_url end -- Log to a Http end point. -- @param `premature` -- @param `conf` Configuration table, holds http endpoint details -- @param `message` Message to be logged local function log(premature, conf, message) local ok, err local parsed_url = parse_url(conf.http_endpoint) local host = parsed_url.host local port = tonumber(parsed_url.port) local sock = ngx.socket.tcp() sock:settimeout(conf.timeout) ok, err = sock:connect(host, port) if not ok then ngx.log(ngx.ERR, "[httplog] failed to connect to "..host..":"..tostring(port)..": ", err) return end ok, err = sock:send(generate_post_payload(conf.method, parsed_url, message).."\r\n") if not ok then ngx.log(ngx.ERR, "[httplog] failed to send data to "..host..":"..tostring(port)..": ", err) end ok, err = sock:setkeepalive(conf.keepalive) if not ok then ngx.log(ngx.ERR, "[httplog] failed to keepalive to "..host..":"..tostring(port)..": ", err) return end end function _M.execute(conf) local ok, err = ngx.timer.at(0, log, conf, ngx.ctx.log_message) if not ok then ngx.log(ngx.ERR, "[httplog] failed to create timer: ", err) end end return _M
mit
SalvationDevelopment/Salvation-Scripts-TCG
c34550857.lua
2
2129
--LL-コバルト・スパロー function c34550857.initial_effect(c) --Search local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(34550857,0)) e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SPSUMMON_SUCCESS) e1:SetProperty(EFFECT_FLAG_DELAY) e1:SetCountLimit(1,34550857) e1:SetTarget(c34550857.thtg) e1:SetOperation(c34550857.thop) c:RegisterEffect(e1) --effect gain local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_BE_MATERIAL) e2:SetCondition(c34550857.efcon) e2:SetOperation(c34550857.efop) c:RegisterEffect(e2) end function c34550857.thfilter(c) return c:IsRace(RACE_WINDBEAST) and c:GetLevel()==1 and c:IsAbleToHand() end function c34550857.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c34550857.thfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c34550857.thop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c34550857.thfilter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end function c34550857.efcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return r==REASON_XYZ and c:GetReasonCard():IsAttribute(ATTRIBUTE_WIND) end function c34550857.efop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local rc=c:GetReasonCard() local p=rc:GetControler() local e1=Effect.CreateEffect(rc) e1:SetDescription(aux.Stringid(34550857,1)) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET) e1:SetProperty(EFFECT_FLAG_CLIENT_HINT+EFFECT_FLAG_SINGLE_RANGE) e1:SetRange(LOCATION_MZONE) e1:SetValue(aux.tgoval) e1:SetReset(RESET_EVENT+0x1fe0000) rc:RegisterEffect(e1,true) if not rc:IsType(TYPE_EFFECT) then local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_ADD_TYPE) e2:SetValue(TYPE_EFFECT) e2:SetReset(RESET_EVENT+0x1fe0000) rc:RegisterEffect(e2,true) end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c44968459.lua
2
2646
--サイレント・バーニング function c44968459.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(44968459,0)) e1:SetCategory(CATEGORY_DRAW) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_CANNOT_NEGATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCondition(c44968459.condition) e1:SetTarget(c44968459.target) e1:SetOperation(c44968459.activate) c:RegisterEffect(e1) --to hand local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(44968459,1)) e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_GRAVE) e2:SetCost(c44968459.thcost) e2:SetTarget(c44968459.thtg) e2:SetOperation(c44968459.thop) c:RegisterEffect(e2) end function c44968459.cfilter(c) return c:IsFaceup() and c:IsSetCard(0xe8) end function c44968459.condition(e,tp,eg,ep,ev,re,r,rp) local ct1=Duel.GetFieldGroupCount(tp,LOCATION_HAND,0) local ct2=Duel.GetFieldGroupCount(tp,0,LOCATION_HAND) local ph=Duel.GetCurrentPhase() return ct1>ct2 and ph>=PHASE_BATTLE_START and ph<=PHASE_BATTLE and Duel.IsExistingMatchingCard(c44968459.cfilter,tp,LOCATION_MZONE,0,1,nil) end function c44968459.target(e,tp,eg,ep,ev,re,r,rp,chk) local ct1=6-Duel.GetFieldGroupCount(tp,LOCATION_HAND,0) local ct2=6-Duel.GetFieldGroupCount(tp,0,LOCATION_HAND) if chk==0 then return ct1>0 and Duel.IsPlayerCanDraw(tp,ct1) and ct2>0 and Duel.IsPlayerCanDraw(1-tp,ct2) end Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,ct1) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,1-tp,ct2) end function c44968459.activate(e,tp,eg,ep,ev,re,r,rp) local ct1=6-Duel.GetFieldGroupCount(tp,LOCATION_HAND,0) local ct2=6-Duel.GetFieldGroupCount(tp,0,LOCATION_HAND) if ct1>0 then Duel.Draw(tp,ct1,REASON_EFFECT) end if ct2>0 then Duel.Draw(1-tp,ct2,REASON_EFFECT) end end function c44968459.thcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST) end function c44968459.thfilter(c) return c:IsSetCard(0xe8) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand() end function c44968459.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c44968459.thfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c44968459.thop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c44968459.thfilter,tp,LOCATION_DECK,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
wljcom/vlc
share/lua/intf/modules/httprequests.lua
19
15839
--[==========================================================================[ httprequests.lua: code for processing httprequests commands and output --[==========================================================================[ Copyright (C) 2007 the VideoLAN team $Id$ Authors: Antoine Cellerier <dionoea at videolan dot org> Rob Jonson <rob at hobbyistsoftware.com> 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. --]==========================================================================] module("httprequests",package.seeall) local common = require ("common") local dkjson = require ("dkjson") --Round the number to the specified precision function round(what, precision) if type(what) == "string" then what = common.us_tonumber(what) end if type(what) == "number" then return math.floor(what*math.pow(10,precision)+0.5) / math.pow(10,precision) end return nil end --split text where it matches the delimiter function strsplit(text, delimiter) local strfind = string.find local strsub = string.sub local tinsert = table.insert local list = {} local pos = 1 if strfind("", delimiter, 1) then -- this would result in endless loops error("delimiter matches empty string!") end local i=1 while 1 do local first, last = strfind(text, delimiter, pos) if first then -- found? tinsert(list,i, strsub(text, pos, first-1)) pos = last+1 else tinsert(list,i, strsub(text, pos)) break end i = i+1 end return list end --main function to process commands sent with the request processcommands = function () local input = _GET['input'] local command = _GET['command'] local id = tonumber(_GET['id'] or -1) local val = _GET['val'] local options = _GET['option'] local band = tonumber(_GET['band']) local name = _GET['name'] local duration = tonumber(_GET['duration']) if type(options) ~= "table" then -- Deal with the 0 or 1 option case options = { options } end if command == "in_play" then --[[ vlc.msg.err( "<options>" ) for a,b in ipairs(options) do vlc.msg.err(b) end vlc.msg.err( "</options>" ) --]] vlc.playlist.add({{path=vlc.strings.make_uri(input),options=options,name=name,duration=duration}}) elseif command == "addsubtitle" then vlc.input.add_subtitle (val) elseif command == "in_enqueue" then vlc.playlist.enqueue({{path=vlc.strings.make_uri(input),options=options,name=name,duration=duration}}) elseif command == "pl_play" then if id == -1 then vlc.playlist.play() else vlc.playlist.gotoitem(id) end elseif command == "pl_pause" then if vlc.playlist.status() == "stopped" then if id == -1 then vlc.playlist.play() else vlc.playlist.gotoitem(id) end else vlc.playlist.pause() end elseif command == "pl_forcepause" then if vlc.playlist.status() == "playing" then vlc.playlist.pause() end elseif command == "pl_forceresume" then if vlc.playlist.status() == "paused" then vlc.playlist.pause() end elseif command == "pl_stop" then vlc.playlist.stop() elseif command == "pl_next" then vlc.playlist.next() elseif command == "pl_previous" then vlc.playlist.prev() elseif command == "pl_delete" then vlc.playlist.delete(id) elseif command == "pl_empty" then vlc.playlist.clear() elseif command == "pl_sort" then vlc.playlist.sort( val, id > 0 ) elseif command == "pl_random" then vlc.playlist.random() elseif command == "pl_loop" then --if loop is set true, then repeat needs to be set false if vlc.playlist.loop() then vlc.playlist.repeat_("off") end elseif command == "pl_repeat" then --if repeat is set true, then loop needs to be set false if vlc.playlist.repeat_() then vlc.playlist.loop("off") end elseif command == "pl_sd" then if vlc.sd.is_loaded(val) then vlc.sd.remove(val) else vlc.sd.add(val) end elseif command == "fullscreen" then if vlc.object.vout() then vlc.video.fullscreen() end elseif command == "snapshot" then common.snapshot() elseif command == "volume" then common.volume(val) elseif command == "seek" then common.seek(val) elseif command == "key" then common.hotkey("key-"..val) elseif command == "audiodelay" then if vlc.object.input() and val then val = common.us_tonumber(val) vlc.var.set(vlc.object.input(),"audio-delay",val) end elseif command == "rate" then val = common.us_tonumber(val) if vlc.object.input() and val >= 0 then vlc.var.set(vlc.object.input(),"rate",val) end elseif command == "subdelay" then if vlc.object.input() then val = common.us_tonumber(val) vlc.var.set(vlc.object.input(),"spu-delay",val) end elseif command == "aspectratio" then if vlc.object.vout() then vlc.var.set(vlc.object.vout(),"aspect-ratio",val) end elseif command == "preamp" then val = common.us_tonumber(val) vlc.equalizer.preampset(val) elseif command == "equalizer" then val = common.us_tonumber(val) vlc.equalizer.equalizerset(band,val) elseif command == "enableeq" then if val == '0' then vlc.equalizer.enable(false) else vlc.equalizer.enable(true) end elseif command == "setpreset" then vlc.equalizer.setpreset(val) elseif command == "title" then vlc.var.set(vlc.object.input(), "title", val) elseif command == "chapter" then vlc.var.set(vlc.object.input(), "chapter", val) elseif command == "audio_track" then vlc.var.set(vlc.object.input(), "audio-es", val) elseif command == "video_track" then vlc.var.set(vlc.object.input(), "video-es", val) elseif command == "subtitle_track" then vlc.var.set(vlc.object.input(), "spu-es", val) end local input = nil local command = nil local id = nil local val = nil end --utilities for formatting output function xmlString(s) if (type(s)=="string") then return vlc.strings.convert_xml_special_chars(s) elseif (type(s)=="number") then return common.us_tostring(s) else return tostring(s) end end --dkjson outputs numbered tables as arrays --so we don't need the array indicators function removeArrayIndicators(dict) local newDict=dict for k,v in pairs(dict) do if (type(v)=="table") then local arrayEntry=v._array if arrayEntry then v=arrayEntry end dict[k]=removeArrayIndicators(v) end end return newDict end printTableAsJson = function (dict) dict=removeArrayIndicators(dict) local output=dkjson.encode (dict, { indent = true }) print(output) end local printXmlKeyValue = function (k,v,indent) print("\n") for i=1,indent do print(" ") end if (k) then print("<"..k..">") end if (type(v)=="table") then printTableAsXml(v,indent+2) else print(xmlString(v)) end if (k) then xs=xmlString(k) space_loc=string.find(xs," ") if space_loc == nil then print("</"..xs..">") else xs=string.sub(xs,1,space_loc) print("</"..xs..">") end end end printTableAsXml = function (dict,indent) for k,v in pairs(dict) do printXmlKeyValue(k,v,indent) end end --[[ function logTable(t,pre) local pre = pre or "" for k,v in pairs(t) do vlc.msg.err(pre..tostring(k).." : "..tostring(v)) if type(v) == "table" then a(v,pre.." ") end end end --]] --main accessors getplaylist = function () local p if _GET["search"] then if _GET["search"] ~= "" then _G.search_key = _GET["search"] else _G.search_key = nil end local key = vlc.strings.decode_uri(_GET["search"]) p = vlc.playlist.search(key) else p = vlc.playlist.get() end --logTable(p) --Uncomment to debug return p end parseplaylist = function (item) if item.flags.disabled then return end if (item.children) then local result={} local name = (item.name or "") result["type"]="node" result.id=tostring(item.id) result.name=tostring(name) result.ro=item.flags.ro and "ro" or "rw" --store children in an array --we use _array as a proxy for arrays result.children={} result.children._array={} for _, child in ipairs(item.children) do local nextChild=parseplaylist(child) table.insert(result.children._array,nextChild) end return result else local result={} local name, path = item.name or "" local path = item.path or "" local current_item_id = vlc.playlist.current() -- Is the item the one currently played if(current_item_id ~= nil) then if(current_item_id == item.id) then result.current = "current" end end result["type"]="leaf" result.id=tostring(item.id) result.uri=tostring(path) result.name=name result.ro=item.flags.ro and "ro" or "rw" result.duration=math.floor(item.duration) return result end end playlisttable = function () local basePlaylist=getplaylist() return parseplaylist(basePlaylist) end getbrowsetable = function () local dir = nil local uri = _GET["uri"] --uri takes precedence, but fall back to dir if uri then if uri == "file://~" then dir = uri else dir = vlc.strings.make_path(uri) end else dir = _GET["dir"] end --backwards compatibility with old format driveLetter:\\.. --this is forgiving with the slash type and number if dir then local position=string.find(dir, '%a:[\\/]*%.%.',0) if position==1 then dir="" end end local result={} --paths are returned as an array of elements result.element={} result.element._array={} if dir then if dir == "~" or dir == "file://~" then dir = vlc.config.homedir() end -- FIXME: hack for Win32 drive list if dir~="" then dir = common.realpath(dir.."/") end local d = vlc.net.opendir(dir) table.sort(d) for _,f in pairs(d) do if f == ".." or not string.match(f,"^%.") then local df = common.realpath(dir..f) local s = vlc.net.stat(df) local path, name = df, f local element={} if (s) then for k,v in pairs(s) do element[k]=v end else element["type"]="unknown" end element["path"]=path element["name"]=name local uri=vlc.strings.make_uri(df) --windows paths are returned with / separators, but make_uri expects \ for windows and returns nil if not uri then --convert failed path to windows format and try again path=string.gsub(path,"/","\\") uri=vlc.strings.make_uri(df) end element["uri"]=uri table.insert(result.element._array,element) end end end return result; end getstatus = function (includecategories) local input = vlc.object.input() local item = vlc.input.item() local playlist = vlc.object.playlist() local vout = vlc.object.vout() local aout = vlc.object.aout() local s ={} --update api version when new data/commands added s.apiversion=3 s.version=vlc.misc.version() s.volume=vlc.volume.get() if input then s.length=math.floor(vlc.var.get(input,"length")) s.time=math.floor(vlc.var.get(input,"time")) s.position=vlc.var.get(input,"position") s.currentplid=vlc.playlist.current() s.audiodelay=vlc.var.get(input,"audio-delay") s.rate=vlc.var.get(input,"rate") s.subtitledelay=vlc.var.get(input,"spu-delay") else s.length=0 s.time=0 s.position=0 s.currentplid=-1 s.audiodelay=0 s.rate=1 s.subtitledelay=0 end if vout then s.fullscreen=vlc.var.get(vout,"fullscreen") s.aspectratio=vlc.var.get(vout,"aspect-ratio"); if s.aspectratio=="" then s.aspectratio = "default" end else s.fullscreen=0 end if aout then local filters=vlc.var.get(aout,"audio-filter") local temp=strsplit(filters,":") s.audiofilters={} local id=0 for i,j in pairs(temp) do s.audiofilters['filter_'..id]=j id=id+1 end end s.videoeffects={} s.videoeffects.hue=round(vlc.config.get("hue"),2) s.videoeffects.brightness=round(vlc.config.get("brightness"),2) s.videoeffects.contrast=round(vlc.config.get("contrast"),2) s.videoeffects.saturation=round(vlc.config.get("saturation"),2) s.videoeffects.gamma=round(vlc.config.get("gamma"),2) s.state=vlc.playlist.status() s.random=vlc.var.get(playlist,"random") s.loop=vlc.var.get(playlist,"loop") s["repeat"]=vlc.var.get(playlist,"repeat") s.equalizer={} s.equalizer.preamp=round(vlc.equalizer.preampget(),2) s.equalizer.bands=vlc.equalizer.equalizerget() if s.equalizer.bands ~= null then for k,i in pairs(s.equalizer.bands) do s.equalizer.bands[k]=round(i,2) end s.equalizer.presets=vlc.equalizer.presets() end if (includecategories and item) then s.information={} s.information.category={} s.information.category.meta=item:metas() local info = item:info() for k, v in pairs(info) do local streamTable={} for k2, v2 in pairs(v) do local tag = string.gsub(k2," ","_") streamTable[tag]=v2 end s.information.category[k]=streamTable end s.stats={} local statsdata = item:stats() for k,v in pairs(statsdata) do local tag = string.gsub(k,"_","") s.stats[tag]=v end s.information.chapter=vlc.var.get(input, "chapter") s.information.title=vlc.var.get(input, "title") s.information.chapters=vlc.var.get_list(input, "chapter") s.information.titles=vlc.var.get_list(input, "title") end return s end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c61204971.lua
6
1932
--E・HERO サンダー・ジャイアント function c61204971.initial_effect(c) --fusion material c:EnableReviveLimit() aux.AddFusionProcCode2(c,20721928,84327329,true,true) --spsummon condition local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetCode(EFFECT_SPSUMMON_CONDITION) e1:SetValue(aux.fuslimit) c:RegisterEffect(e1) --destroy local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(61204971,0)) e2:SetCategory(CATEGORY_DESTROY) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1) e2:SetCost(c61204971.descost) e2:SetTarget(c61204971.destg) e2:SetOperation(c61204971.desop) c:RegisterEffect(e2) end c61204971.material_setcode=0x8 function c61204971.descost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(Card.IsDiscardable,tp,LOCATION_HAND,0,1,nil) end Duel.DiscardHand(tp,Card.IsDiscardable,1,1,REASON_COST+REASON_DISCARD) end function c61204971.filter(c,atk) return c:IsFaceup() and c:GetBaseAttack()<atk end function c61204971.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and c61204971.filter(chkc,e:GetHandler():GetAttack()) end if chk==0 then return Duel.IsExistingTarget(c61204971.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil,e:GetHandler():GetAttack()) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,c61204971.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil,e:GetHandler():GetAttack()) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0) end function c61204971.desop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if c:IsRelateToEffect(e) and c:IsFaceup() and tc:IsFaceup() and tc:IsRelateToEffect(e) and tc:GetBaseAttack()<c:GetAttack() then Duel.Destroy(tc,REASON_EFFECT) end end
gpl-2.0
dickeyf/darkstar
scripts/globals/spells/hydrohelix.lua
26
1690
-------------------------------------- -- Spell: Hydrohelix -- Deals water damage that gradually reduces -- a target's HP. Damage dealt is greatly affected by the weather. -------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) -- get helix acc/att merits local merit = caster:getMerit(MERIT_HELIX_MAGIC_ACC_ATT); -- calculate raw damage local dmg = calculateMagicDamage(35,1,caster,spell,target,ELEMENTAL_MAGIC_SKILL,MOD_INT,false); dmg = dmg + caster:getMod(MOD_HELIX_EFFECT); -- get resist multiplier (1x if no resist) local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL,merit*3); -- get the resisted damage dmg = dmg*resist; -- add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = addBonuses(caster,spell,target,dmg,merit*2); -- add in target adjustment dmg = adjustForTarget(target,dmg,spell:getElement()); local dot = dmg; -- add in final adjustments dmg = finalMagicAdjustments(caster,target,spell,dmg); -- calculate Damage over time dot = target:magicDmgTaken(dot); local duration = getHelixDuration(caster) + caster:getMod(MOD_HELIX_DURATION); duration = duration * (resist/2); if (dot > 0) then target:addStatusEffect(EFFECT_HELIX,dot,3,duration); end; return dmg; end;
gpl-3.0
dickeyf/darkstar
scripts/globals/mobskills/Pit_Ambush.lua
3
1079
--------------------------------------------- -- Pit Ambush -- -- Description: Only used by black antlions when they emerge to attack a player overhead. -- Type: Physical -- Utsusemi/Blink absorb: 1 shadow -- Range: Melee -- Notes: --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:getPool() == 1318 and mob:getLocalVar("AMBUSH") == 1) then return 1; else return 0; end end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 3.3; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_PIERCE,MOBPARAM_WIPE_SHADOWS); mob:untargetable(false); mob:setLocalVar("AMBUSH",1); -- Used it for the last time! target:delHP(dmg); return dmg; end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c77414722.lua
6
1320
--マジック・ジャマー function c77414722.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_CHAINING) e1:SetCondition(c77414722.condition) e1:SetCost(c77414722.cost) e1:SetTarget(c77414722.target) e1:SetOperation(c77414722.activate) c:RegisterEffect(e1) end function c77414722.condition(e,tp,eg,ep,ev,re,r,rp) return re:IsActiveType(TYPE_SPELL) and re:IsHasType(EFFECT_TYPE_ACTIVATE) and Duel.IsChainNegatable(ev) end function c77414722.cost(e,tp,eg,ep,ev,re,r,rp,chk) if Duel.IsPlayerAffectedByEffect(tp,EFFECT_DISCARD_COST_CHANGE) then return true end if chk==0 then return Duel.IsExistingMatchingCard(Card.IsDiscardable,tp,LOCATION_HAND,0,1,e:GetHandler()) end Duel.DiscardHand(tp,Card.IsDiscardable,1,1,REASON_COST+REASON_DISCARD) end function c77414722.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0) if re:GetHandler():IsDestructable() and re:GetHandler():IsRelateToEffect(re) then Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0) end end function c77414722.activate(e,tp,eg,ep,ev,re,r,rp) if Duel.NegateActivation(ev) and re:GetHandler():IsRelateToEffect(re) then Duel.Destroy(eg,REASON_EFFECT) end end
gpl-2.0
Turttle/darkstar
scripts/globals/abilities/sic.lua
28
1058
----------------------------------- -- Ability: Sic -- Commands the charmed Pet to make a random special attack. -- Obtained: Beastmaster Level 25 -- Recast Time: 2 minutes -- Duration: N/A ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (player:getPet() == nil) then return MSGBASIC_REQUIRES_A_PET,0; else if (player:getPet():getHP() == 0) then return MSGBASIC_UNABLE_TO_USE_JA,0; elseif (player:getPet():getTarget() == nil) then return MSGBASIC_PET_CANNOT_DO_ACTION,0; elseif (not player:getPet():hasTPMoves()) then return MSGBASIC_UNABLE_TO_USE_JA,0; else return 0,0; end end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) end;
gpl-3.0
eugeneia/snabb
src/program/snabbvmx/check/check.lua
9
1666
module(..., package.seeall) local config = require("core.config") local lib = require("core.lib") local util = require("program.lwaftr.check.util") local counters = require("program.lwaftr.counters") local setup = require("program.snabbvmx.lwaftr.setup") local function show_usage(code) print(require("program.snabbvmx.check.README_inc")) main.exit(code) end local function parse_args (args) local handlers = {} local opts = {} function handlers.h() show_usage(0) end function handlers.r() opts.r = true end args = lib.dogetopt(args, handlers, "hrD:", { help="h", regen="r", duration="D" }) if #args ~= 5 and #args ~= 6 then show_usage(1) end if not opts.duration then opts.duration = 0.10 end return opts, args end function run(args) local opts, args = parse_args(args) local conf_file, inv4_pcap, inv6_pcap, outv4_pcap, outv6_pcap, counters_path = unpack(args) local c = config.new() setup.load_check(c, conf_file, inv4_pcap, inv6_pcap, outv4_pcap, outv6_pcap) engine.configure(c) if counters_path then local initial_counters = counters.read_counters(c) engine.main({duration=opts.duration}) local final_counters = counters.read_counters(c) local counters_diff = util.diff_counters(final_counters, initial_counters) if opts.r then util.regen_counters(counters_diff, counters_path) else local req_counters = util.load_requested_counters(counters_path) util.validate_diff(counters_diff, req_counters) end else engine.main({duration=opts.duration}) end print("done") end
apache-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c14886469.lua
6
1541
--レッド・スプリンター function c14886469.initial_effect(c) --spsummon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(14886469,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetCountLimit(1,14886469) e1:SetCondition(c14886469.spcon) e1:SetTarget(c14886469.sptg) e1:SetOperation(c14886469.spop) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e2) end function c14886469.spcon(e,tp,eg,ep,ev,re,r,rp) return not Duel.IsExistingMatchingCard(nil,tp,LOCATION_MZONE,0,1,e:GetHandler()) end function c14886469.filter(c,e,tp) return c:IsLevelBelow(3) and c:IsRace(RACE_FIEND) and c:IsType(TYPE_TUNER) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c14886469.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c14886469.filter,tp,LOCATION_HAND+LOCATION_GRAVE,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND+LOCATION_GRAVE) end function c14886469.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(c14886469.filter),tp,LOCATION_HAND+LOCATION_GRAVE,0,1,1,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
sinavafa/ErRoR_3SV
bot/utils.lua
646
23489
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
mohammadclash/STAR
plugins/twitter_send.lua
627
1555
do local OAuth = require "OAuth" local consumer_key = "" local consumer_secret = "" local access_token = "" local access_token_secret = "" local client = OAuth.new(consumer_key, consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/access_token" }, { OAuthToken = access_token, OAuthTokenSecret = access_token_secret }) function run(msg, matches) if consumer_key:isempty() then return "Twitter Consumer Key is empty, write it in plugins/twitter_send.lua" end if consumer_secret:isempty() then return "Twitter Consumer Secret is empty, write it in plugins/twitter_send.lua" end if access_token:isempty() then return "Twitter Access Token is empty, write it in plugins/twitter_send.lua" end if access_token_secret:isempty() then return "Twitter Access Token Secret is empty, write it in plugins/twitter_send.lua" end if not is_sudo(msg) then return "You aren't allowed to send tweets" end local response_code, response_headers, response_status_line, response_body = client:PerformRequest("POST", "https://api.twitter.com/1.1/statuses/update.json", { status = matches[1] }) if response_code ~= 200 then return "Error: "..response_code end return "Tweet sent" end return { description = "Sends a tweet", usage = "!tw [text]: Sends the Tweet with the configured account.", patterns = {"^!tw (.+)"}, run = run } end
gpl-2.0
pspk/NewTableViewDemo
widget_theme_ios_sheet.lua
3
12711
-- -- created with TexturePacker (http://www.codeandweb.com/texturepacker) -- -- $TexturePacker:SmartUpdate:b4bf35073910cc98b049b77318277ca0$ -- -- local sheetInfo = require("mysheet") -- local myImageSheet = graphics.newImageSheet( "mysheet.png", sheetInfo:getSheet() ) -- local sprite = display.newSprite( myImageSheet , {frames={sheetInfo:getFrameIndex("sprite")}} ) -- local SheetInfo = {} SheetInfo.sheet = { frames = { { -- button_bottomLeft x=546, y=203, width=15, height=15, }, { -- button_bottomLeftOver x=546, y=184, width=15, height=15, }, { -- button_bottomMiddle x=527, y=190, width=15, height=15, }, { -- button_bottomMiddleOver x=508, y=196, width=15, height=15, }, { -- button_bottomRight x=522, y=171, width=15, height=15, }, { -- button_bottomRightOver x=489, y=196, width=15, height=15, }, { -- button_middle x=503, y=168, width=15, height=15, }, { -- button_middleLeft x=546, y=165, width=15, height=15, }, { -- button_middleLeftOver x=470, y=202, width=15, height=15, }, { -- button_middleOver x=470, y=183, width=15, height=15, }, { -- button_middleRight x=546, y=146, width=15, height=15, }, { -- button_middleRightOver x=546, y=127, width=15, height=15, }, { -- button_topLeft x=542, y=108, width=15, height=15, }, { -- button_topLeftOver x=468, y=164, width=15, height=15, }, { -- button_topMiddle x=527, y=152, width=15, height=15, }, { -- button_topMiddleOver x=527, y=133, width=15, height=15, }, { -- button_topRight x=449, y=174, width=15, height=15, }, { -- button_topRightOver x=430, y=174, width=15, height=15, }, { -- picker_bg x=327, y=3, width=1, height=222, }, { -- picker_overlay x=3, y=3, width=320, height=222, }, { -- picker_separator x=474, y=72, width=8, height=1, }, { -- progressView_leftFill x=565, y=114, width=12, height=10, }, { -- progressView_leftFillBorder x=521, y=215, width=12, height=10, }, { -- progressView_middleFill x=505, y=215, width=12, height=10, }, { -- progressView_middleFillBorder x=460, y=117, width=35, height=10, }, { -- progressView_rightFill x=489, y=215, width=12, height=10, }, { -- progressView_rightFillBorder x=487, y=168, width=12, height=10, }, { -- scrollBar_bottom x=537, y=209, width=5, height=5, }, { -- scrollBar_middle x=512, y=187, width=5, height=5, }, { -- scrollBar_top x=503, y=187, width=5, height=5, }, { -- searchField_leftEdge x=517, y=78, width=18, height=30, }, { -- searchField_magnifyingGlass x=522, y=112, width=16, height=17, }, { -- searchField_middle x=495, y=78, width=18, height=30, }, { -- searchField_remove x=499, y=112, width=19, height=19, }, { -- searchField_rightEdge x=474, y=38, width=18, height=30, }, { -- segmentedControl_divider x=575, y=3, width=1, height=29, }, { -- segmentedControl_left x=512, y=135, width=11, height=29, }, { -- segmentedControl_leftOn x=497, y=135, width=11, height=29, }, { -- segmentedControl_middle x=482, y=131, width=11, height=29, }, { -- segmentedControl_middleOn x=467, y=131, width=11, height=29, }, { -- segmentedControl_right x=455, y=193, width=11, height=29, }, { -- segmentedControl_rightOn x=539, y=75, width=11, height=29, }, { -- silder_middleFrame x=565, y=198, width=10, height=10, }, { -- silder_middleFrameVertical x=565, y=184, width=10, height=10, }, { -- slider_bottomFrameVertical x=565, y=170, width=10, height=10, }, { -- slider_fill x=565, y=156, width=10, height=10, }, { -- slider_fillVertical x=565, y=142, width=10, height=10, }, { -- slider_handle x=419, y=193, width=32, height=32, }, { -- slider_leftFrame x=565, y=128, width=10, height=10, }, { -- slider_rightFrame x=489, y=182, width=10, height=10, }, { -- slider_topFrameVertical x=568, y=100, width=10, height=10, }, { -- spinner_spinner x=430, y=38, width=40, height=40, }, { -- stepper_minusActive x=332, y=162, width=94, height=27, }, { -- stepper_noMinus x=332, y=131, width=94, height=27, }, { -- stepper_noPlus x=332, y=100, width=94, height=27, }, { -- stepper_nonActive x=332, y=69, width=94, height=27, }, { -- stepper_plusActive x=332, y=38, width=94, height=27, }, { -- switch_background x=332, y=3, width=165, height=31, }, { -- switch_checkboxDefault x=538, y=3, width=33, height=33, }, { -- switch_checkboxSelected x=501, y=3, width=33, height=33, }, { -- switch_handle x=460, y=82, width=31, height=31, }, { -- switch_handleOver x=533, y=40, width=31, height=31, }, { -- switch_overlay x=332, y=193, width=83, height=31, }, { -- switch_radioButtonDefault x=496, y=40, width=33, height=34, }, { -- switch_radioButtonSelected x=430, y=136, width=33, height=34, }, { -- tabBar_background x=430, y=82, width=26, height=50, }, { -- tabBar_tabSelectedLeft x=554, y=75, width=10, height=26, }, { -- tabBar_tabSelectedMiddle x=568, y=70, width=10, height=26, }, { -- tabBar_tabSelectedRight x=568, y=40, width=10, height=26, }, }, sheetContentWidth = 581, sheetContentHeight = 228 } SheetInfo.frameIndex = { ["button_bottomLeft"] = 1, ["button_bottomLeftOver"] = 2, ["button_bottomMiddle"] = 3, ["button_bottomMiddleOver"] = 4, ["button_bottomRight"] = 5, ["button_bottomRightOver"] = 6, ["button_middle"] = 7, ["button_middleLeft"] = 8, ["button_middleLeftOver"] = 9, ["button_middleOver"] = 10, ["button_middleRight"] = 11, ["button_middleRightOver"] = 12, ["button_topLeft"] = 13, ["button_topLeftOver"] = 14, ["button_topMiddle"] = 15, ["button_topMiddleOver"] = 16, ["button_topRight"] = 17, ["button_topRightOver"] = 18, ["picker_bg"] = 19, ["picker_overlay"] = 20, ["picker_separator"] = 21, ["progressView_leftFill"] = 22, ["progressView_leftFillBorder"] = 23, ["progressView_middleFill"] = 24, ["progressView_middleFillBorder"] = 25, ["progressView_rightFill"] = 26, ["progressView_rightFillBorder"] = 27, ["scrollBar_bottom"] = 28, ["scrollBar_middle"] = 29, ["scrollBar_top"] = 30, ["searchField_leftEdge"] = 31, ["searchField_magnifyingGlass"] = 32, ["searchField_middle"] = 33, ["searchField_remove"] = 34, ["searchField_rightEdge"] = 35, ["segmentedControl_divider"] = 36, ["segmentedControl_left"] = 37, ["segmentedControl_leftOn"] = 38, ["segmentedControl_middle"] = 39, ["segmentedControl_middleOn"] = 40, ["segmentedControl_right"] = 41, ["segmentedControl_rightOn"] = 42, ["silder_middleFrame"] = 43, ["silder_middleFrameVertical"] = 44, ["slider_bottomFrameVertical"] = 45, ["slider_fill"] = 46, ["slider_fillVertical"] = 47, ["slider_handle"] = 48, ["slider_leftFrame"] = 49, ["slider_rightFrame"] = 50, ["slider_topFrameVertical"] = 51, ["spinner_spinner"] = 52, ["stepper_minusActive"] = 53, ["stepper_noMinus"] = 54, ["stepper_noPlus"] = 55, ["stepper_nonActive"] = 56, ["stepper_plusActive"] = 57, ["switch_background"] = 58, ["switch_checkboxDefault"] = 59, ["switch_checkboxSelected"] = 60, ["switch_handle"] = 61, ["switch_handleOver"] = 62, ["switch_overlay"] = 63, ["switch_radioButtonDefault"] = 64, ["switch_radioButtonSelected"] = 65, ["tabBar_background"] = 66, ["tabBar_tabSelectedLeft"] = 67, ["tabBar_tabSelectedMiddle"] = 68, ["tabBar_tabSelectedRight"] = 69, } function SheetInfo:getSheet() return self.sheet; end function SheetInfo:getFrameIndex(name) return self.frameIndex[name]; end return SheetInfo
mit
dickeyf/darkstar
scripts/globals/spells/knights_minne.lua
27
1495
----------------------------------------- -- Spell: Knight's Minne I -- Grants Defense bonus to all allies. ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 8 + math.floor((sLvl + iLvl)/10); if (power >= 18) then power = 18; end local iBoost = caster:getMod(MOD_MINNE_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); if (iBoost > 0) then power = power + 1 + (iBoost-1)*4; end power = power + caster:getMerit(MERIT_MINNE_EFFECT); if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_MINNE,power,0,duration,caster:getID(), 0, 1)) then spell:setMsg(75); end return EFFECT_MINNE; end;
gpl-3.0
mchaza/soka
src/libraries/LoveFrames/objects/list.lua
5
18625
--[[------------------------------------------------ -- Love Frames - A GUI library for LOVE -- -- Copyright (c) 2013 Kenny Shields -- --]]------------------------------------------------ -- list class local newobject = loveframes.NewObject("list", "loveframes_object_list", true) --[[--------------------------------------------------------- - func: initialize() - desc: initializes the object --]]--------------------------------------------------------- function newobject:initialize() self.type = "list" self.display = "vertical" self.width = 300 self.height = 150 self.clickx = 0 self.clicky = 0 self.padding = 0 self.spacing = 0 self.offsety = 0 self.offsetx = 0 self.extrawidth = 0 self.extraheight = 0 self.buttonscrollamount = 0.10 self.mousewheelscrollamount = 10 self.internal = false self.hbar = false self.vbar = false self.autoscroll = false self.horizontalstacking = false self.dtscrolling = false self.internals = {} self.children = {} self.OnScroll = nil end --[[--------------------------------------------------------- - func: update(deltatime) - desc: updates the object --]]--------------------------------------------------------- function newobject:update(dt) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible local alwaysupdate = self.alwaysupdate if not visible then if not alwaysupdate then return end end local internals = self.internals local children = self.children local display = self.display local parent = self.parent local horizontalstacking = self.horizontalstacking local base = loveframes.base local update = self.Update -- move to parent if there is a parent if parent ~= base then self.x = self.parent.x + self.staticx self.y = self.parent.y + self.staticy end self:CheckHover() for k, v in ipairs(internals) do v:update(dt) end local x = self.x local y = self.y local width = self.width local height = self.height local offsetx = self.offsetx local offsety = self.offsety for k, v in ipairs(children) do v:update(dt) v:SetClickBounds(x, y, width, height) v.x = (v.parent.x + v.staticx) - offsetx v.y = (v.parent.y + v.staticy) - offsety if display == "vertical" then if v.lastheight ~= v.height then self:CalculateSize() self:RedoLayout() end end end if update then update(self, dt) end end --[[--------------------------------------------------------- - func: draw() - desc: draws the object --]]--------------------------------------------------------- function newobject:draw() local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible if not visible then return end local x = self.x local y = self.y local width = self.width local height = self.height local stencilfunc = function() love.graphics.rectangle("fill", x, y, width, height) end local loveversion = love._version local internals = self.internals local children = self.children local skins = loveframes.skins.available local skinindex = loveframes.config["ACTIVESKIN"] local defaultskin = loveframes.config["DEFAULTSKIN"] local selfskin = self.skin local skin = skins[selfskin] or skins[skinindex] local drawfunc = skin.DrawList or skins[defaultskin].DrawList local drawoverfunc = skin.DrawOverList or skins[defaultskin].DrawOverList local draw = self.Draw local drawcount = loveframes.drawcount -- set the object's draw order self:SetDrawOrder() if draw then draw(self) else drawfunc(self) end if loveversion == "0.8.0" then local stencil = love.graphics.newStencil(stencilfunc) love.graphics.setStencil(stencil) else love.graphics.setStencil(stencilfunc) end for k, v in ipairs(children) do local col = loveframes.util.BoundingBox(x, v.x, y, v.y, width, v.width, height, v.height) if col then v:draw() end end love.graphics.setStencil() for k, v in ipairs(internals) do v:draw() end if not draw then drawoverfunc(self) end end --[[--------------------------------------------------------- - func: mousepressed(x, y, button) - desc: called when the player presses a mouse button --]]--------------------------------------------------------- function newobject:mousepressed(x, y, button) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible if not visible then return end local toplist = self:IsTopList() local hover = self.hover local vbar = self.vbar local hbar = self.hbar local scrollamount = self.mousewheelscrollamount local children = self.children local internals = self.internals if hover and button == "l" then local baseparent = self:GetBaseParent() if baseparent and baseparent.type == "frame" then baseparent:MakeTop() end end if vbar or hbar then if toplist then local bar = self:GetScrollBar() local dtscrolling = self.dtscrolling if dtscrolling then local dt = love.timer.getDelta() if button == "wu" then bar:Scroll(-scrollamount * dt) elseif button == "wd" then bar:Scroll(scrollamount * dt) end else if button == "wu" then bar:Scroll(-scrollamount) elseif button == "wd" then bar:Scroll(scrollamount) end end end end for k, v in ipairs(internals) do v:mousepressed(x, y, button) end for k, v in ipairs(children) do v:mousepressed(x, y, button) end end --[[--------------------------------------------------------- - func: AddItem(object) - desc: adds an item to the object --]]--------------------------------------------------------- function newobject:AddItem(object) if object.type == "frame" then return end local children = self.children local state = self.state -- remove the item object from its current parent and make its new parent the list object object:Remove() object.parent = self object:SetState(state) -- insert the item object into the list object's children table table.insert(children, object) -- resize the list and redo its layout self:CalculateSize() self:RedoLayout() end --[[--------------------------------------------------------- - func: RemoveItem(object or number) - desc: removes an item from the object --]]--------------------------------------------------------- function newobject:RemoveItem(data) local dtype = type(data) if dtype == "number" then local children = self.children local item = children[data] if item then item:Remove() end else data:Remove() end self:CalculateSize() self:RedoLayout() end --[[--------------------------------------------------------- - func: CalculateSize() - desc: calculates the size of the object's children --]]--------------------------------------------------------- function newobject:CalculateSize() local numitems = #self.children local height = self.height local width = self.width local padding = self.padding local spacing = self.spacing local itemheight = self.padding local itemwidth = self.padding local display = self.display local vbar = self.vbar local hbar = self.hbar local internals = self.internals local children = self.children local horizontalstacking = self.horizontalstacking if display == "vertical" then if horizontalstacking then local curwidth = 0 local maxwidth = width - padding * 2 local prevheight = 0 local scrollbar = self:GetScrollBar() if scrollbar then maxwidth = maxwidth - scrollbar.width end for k, v in ipairs(children) do if v.height > prevheight then prevheight = v.height end curwidth = curwidth + v.width + spacing if children[k + 1] then if curwidth + children[k + 1].width > maxwidth then curwidth = padding itemheight = itemheight + prevheight + spacing prevheight = 0 end else itemheight = itemheight + prevheight + padding end end self.itemheight = itemheight else for k, v in ipairs(children) do itemheight = itemheight + v.height + spacing end self.itemheight = (itemheight - spacing) + padding end local itemheight = self.itemheight if itemheight > height then self.extraheight = itemheight - height if not vbar then local scrollbar = loveframes.objects["scrollbody"]:new(self, display) table.insert(internals, scrollbar) self.vbar = true self:GetScrollBar().autoscroll = self.autoscroll end else if vbar then local bar = internals[1] bar:Remove() self.vbar = false self.offsety = 0 end end elseif display == "horizontal" then for k, v in ipairs(children) do itemwidth = itemwidth + v.width + spacing end self.itemwidth = (itemwidth - spacing) + padding local itemwidth = self.itemwidth if itemwidth > width then self.extrawidth = itemwidth - width if not hbar then local scrollbar = loveframes.objects["scrollbody"]:new(self, display) table.insert(internals, scrollbar) self.hbar = true self:GetScrollBar().autoscroll = self.autoscroll end else if hbar then local bar = internals[1] bar:Remove() self.hbar = false self.offsetx = 0 end end end end --[[--------------------------------------------------------- - func: RedoLayout() - desc: used to redo the layout of the object --]]--------------------------------------------------------- function newobject:RedoLayout() local width = self.width local height = self.height local children = self.children local internals = self.internals local padding = self.padding local spacing = self.spacing local starty = padding local startx = padding local vbar = self.vbar local hbar = self.hbar local display = self.display local horizontalstacking = self.horizontalstacking local scrollbody, scrollbodywidth, scrollbodyheight if vbar or hbar then scrollbody = internals[1] scrollbodywidth = scrollbody.width scrollbodyheight = scrollbody.height end if #children > 0 then if display == "vertical" then if horizontalstacking then local curwidth = padding local curheight = padding local maxwidth = self.width - padding * 2 local prevheight = 0 local scrollbar = self:GetScrollBar() if scrollbar then maxwidth = maxwidth - scrollbar.width end for k, v in ipairs(children) do local itemheight = v.height v.lastheight = itemheight v.staticx = curwidth v.staticy = curheight if v.height > prevheight then prevheight = v.height end if children[k + 1] then curwidth = curwidth + v.width + spacing if curwidth + (children[k + 1].width) > maxwidth then curwidth = padding curheight = curheight + prevheight + spacing prevheight = 0 end end end else for k, v in ipairs(children) do local itemwidth = v.width local itemheight = v.height local retainsize = v.retainsize v.staticx = padding v.staticy = starty v.lastheight = itemheight if vbar then if itemwidth + padding > (width - scrollbodywidth) then v:SetWidth((width - scrollbodywidth) - (padding * 2)) end if not retainsize then v:SetWidth((width - scrollbodywidth) - (padding * 2)) end scrollbody.staticx = width - scrollbodywidth scrollbody.height = height else if not retainsize then v:SetWidth(width - (padding * 2)) end end starty = starty + itemheight starty = starty + spacing end end elseif display == "horizontal" then for k, v in ipairs(children) do local itemwidth = v.width local itemheight = v.height local retainsize = v.retainsize v.staticx = startx v.staticy = padding if hbar then if itemheight + padding > (height - scrollbodyheight) then v:SetHeight((height - scrollbodyheight) - (padding * 2)) end if not retainsize then v:SetHeight((height - scrollbodyheight) - (padding * 2)) end scrollbody.staticy = height - scrollbodyheight scrollbody.width = width else if not retainsize then v:SetHeight(height - (padding * 2)) end end startx = startx + itemwidth startx = startx + spacing end end end end --[[--------------------------------------------------------- - func: SetDisplayType(type) - desc: sets the object's display type --]]--------------------------------------------------------- function newobject:SetDisplayType(type) local children = self.children local numchildren = #children self.display = type self.vbar = false self.hbar = false self.offsetx = 0 self.offsety = 0 self.internals = {} if numchildren > 0 then self:CalculateSize() self:RedoLayout() end end --[[--------------------------------------------------------- - func: GetDisplayType() - desc: gets the object's display type --]]--------------------------------------------------------- function newobject:GetDisplayType() return self.display end --[[--------------------------------------------------------- - func: SetPadding(amount) - desc: sets the object's padding --]]--------------------------------------------------------- function newobject:SetPadding(amount) local children = self.children local numchildren = #children self.padding = amount if numchildren > 0 then self:CalculateSize() self:RedoLayout() end end --[[--------------------------------------------------------- - func: SetSpacing(amount) - desc: sets the object's spacing --]]--------------------------------------------------------- function newobject:SetSpacing(amount) local children = self.children local numchildren = #children self.spacing = amount if numchildren > 0 then self:CalculateSize() self:RedoLayout() end end --[[--------------------------------------------------------- - func: Clear() - desc: removes all of the object's children --]]--------------------------------------------------------- function newobject:Clear() self.children = {} self:CalculateSize() self:RedoLayout() end --[[--------------------------------------------------------- - func: SetWidth(width) - desc: sets the object's width --]]--------------------------------------------------------- function newobject:SetWidth(width) self.width = width self:CalculateSize() self:RedoLayout() end --[[--------------------------------------------------------- - func: SetHeight(height) - desc: sets the object's height --]]--------------------------------------------------------- function newobject:SetHeight(height) self.height = height self:CalculateSize() self:RedoLayout() end --[[--------------------------------------------------------- - func: GetSize() - desc: gets the object's size --]]--------------------------------------------------------- function newobject:SetSize(width, height) self.width = width self.height = height self:CalculateSize() self:RedoLayout() end --[[--------------------------------------------------------- - func: GetScrollBar() - desc: gets the object's scroll bar --]]--------------------------------------------------------- function newobject:GetScrollBar() local vbar = self.vbar local hbar = self.hbar local internals = self.internals if vbar or hbar then local scrollbody = internals[1] local scrollarea = scrollbody.internals[1] local scrollbar = scrollarea.internals[1] return scrollbar else return false end end --[[--------------------------------------------------------- - func: SetAutoScroll(bool) - desc: sets whether or not the list's scrollbar should auto scroll to the bottom when a new object is added to the list --]]--------------------------------------------------------- function newobject:SetAutoScroll(bool) local scrollbar = self:GetScrollBar() self.autoscroll = bool if scrollbar then scrollbar.autoscroll = bool end end --[[--------------------------------------------------------- - func: SetButtonScrollAmount(speed) - desc: sets the scroll amount of the object's scrollbar buttons --]]--------------------------------------------------------- function newobject:SetButtonScrollAmount(amount) self.buttonscrollamount = amount end --[[--------------------------------------------------------- - func: GetButtonScrollAmount() - desc: gets the scroll amount of the object's scrollbar buttons --]]--------------------------------------------------------- function newobject:GetButtonScrollAmount() return self.buttonscrollamount end --[[--------------------------------------------------------- - func: SetMouseWheelScrollAmount(amount) - desc: sets the scroll amount of the mouse wheel --]]--------------------------------------------------------- function newobject:SetMouseWheelScrollAmount(amount) self.mousewheelscrollamount = amount end --[[--------------------------------------------------------- - func: GetMouseWheelScrollAmount() - desc: gets the scroll amount of the mouse wheel --]]--------------------------------------------------------- function newobject:GetButtonScrollAmount() return self.mousewheelscrollamount end --[[--------------------------------------------------------- - func: EnableHorizontalStacking(bool) - desc: enables or disables horizontal stacking --]]--------------------------------------------------------- function newobject:EnableHorizontalStacking(bool) local children = self.children local numchildren = #children self.horizontalstacking = bool if numchildren > 0 then self:CalculateSize() self:RedoLayout() end end --[[--------------------------------------------------------- - func: GetHorizontalStacking() - desc: gets whether or not the object allows horizontal stacking --]]--------------------------------------------------------- function newobject:GetHorizontalStacking() return self.horizontalstacking end --[[--------------------------------------------------------- - func: SetDTScrolling(bool) - desc: sets whether or not the object should use delta time when scrolling --]]--------------------------------------------------------- function newobject:SetDTScrolling(bool) self.dtscrolling = bool end --[[--------------------------------------------------------- - func: GetDTScrolling() - desc: gets whether or not the object should use delta time when scrolling --]]--------------------------------------------------------- function newobject:GetDTScrolling() return self.dtscrolling end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-TCG
c61901281.lua
7
2274
--暗黒竜 コラプサーペント function c61901281.initial_effect(c) c:EnableReviveLimit() --cannot special summon local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetCode(EFFECT_SPSUMMON_CONDITION) c:RegisterEffect(e1) --special summon local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_SPSUMMON_PROC) e2:SetProperty(EFFECT_FLAG_UNCOPYABLE) e2:SetRange(LOCATION_HAND) e2:SetCountLimit(1,61901281) e2:SetCondition(c61901281.spcon) e2:SetOperation(c61901281.spop) c:RegisterEffect(e2) --search local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(61901281,0)) e3:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e3:SetCode(EVENT_TO_GRAVE) e3:SetCondition(c61901281.condition) e3:SetTarget(c61901281.target) e3:SetOperation(c61901281.operation) c:RegisterEffect(e3) end function c61901281.spfilter(c) return c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsAbleToRemoveAsCost() end function c61901281.spcon(e,c) if c==nil then return true end local tp=c:GetControler() return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c61901281.spfilter,tp,LOCATION_GRAVE,0,1,nil) end function c61901281.spop(e,tp,eg,ep,ev,re,r,rp,c) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,c61901281.spfilter,tp,LOCATION_GRAVE,0,1,1,nil) Duel.Remove(g,POS_FACEUP,REASON_COST) end function c61901281.condition(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD) end function c61901281.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c61901281.filter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c61901281.filter(c) return c:IsCode(99234526) and c:IsAbleToHand() end function c61901281.operation(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c61901281.filter,tp,LOCATION_DECK,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
Turttle/darkstar
scripts/zones/Windurst_Walls/npcs/Koru-Moru.lua
24
11008
----------------------------------- -- Area: Windurst Walls -- NPC: Koru-Moru -- Starts & Ends Quest: Star Struck -- Involved in Quest: Making the Grade, Riding on the Clouds -- @pos -120 -6 124 239 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local qStarStruck = player:getQuestStatus(WINDURST,STAR_STRUCK); local count = trade:getItemCount(); if (trade:hasItemQty(544,1) and count == 1 and trade:getGil() == 0) then if (player:getQuestStatus(WINDURST,MAKING_THE_GRADE) == QUEST_ACCEPTED) then if (player:getVar("QuestMakingTheGrade_prog") == 1) then player:startEvent(0x011d); -- MAKING THE GRADE: Turn in Test Answer & Told to go back to Fuepepe & Chomoro else player:startEvent(0x011f); -- MAKING THE GRADE: Have test answers but not talked/given to Fuepepe end end elseif (trade:hasItemQty(584,1) and count == 1 and trade:getGil() == 0) then player:startEvent(0x00c7); elseif (qStarStruck == QUEST_ACCEPTED and trade:hasItemQty(582,1) and count == 1 and trade:getGil() == 0) then player:startEvent(0x00d3); elseif (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_4") == 4) then player:setVar("ridingOnTheClouds_4",0); player:tradeComplete(); player:addKeyItem(SPIRITED_STONE); player:messageSpecial(KEYITEM_OBTAINED,SPIRITED_STONE); end elseif (trade:hasItemQty(16511,1) and count == 1 and trade:getGil() == 0) then if (player:getQuestStatus(WINDURST,BLAST_FROM_THE_PAST) == QUEST_ACCEPTED) then player:startEvent(0x00e0); -- Complete quest! else player:startEvent(0x00e1); -- not the shell end elseif (trade:hasItemQty(829,1) and count == 1 and trade:getGil() == 0) then if (player:getQuestStatus(WINDURST,THE_ROOT_OF_THE_PROBLEM) == QUEST_ACCEPTED) then player:startEvent(0x15D); player:tradeComplete(); player:setVar("rootProblem",2); end elseif (trade:hasItemQty(17299,4) and count == 4 and trade:getGil() == 0) then -- trade:getItemCount() is apparently checking total of all 8 slots combined. Could have sworn that wasn't how it worked before. if (player:getQuestStatus(WINDURST,CLASS_REUNION) == 1 and player:getVar("ClassReunionProgress") == 2) then player:startEvent(0x0197); -- now Koru remembers something that you need to inquire his former students. end; end; end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local qStarStruck = player:getQuestStatus(WINDURST,STAR_STRUCK); local blastFromPast = player:getQuestStatus(WINDURST,BLAST_FROM_THE_PAST); local blastProg = player:getVar("BlastFromThePast_Prog"); local rootProblem = player:getQuestStatus(WINDURST,THE_ROOT_OF_THE_PROBLEM); local ThePuppetMaster = player:getQuestStatus(WINDURST,THE_PUPPET_MASTER); local ThePuppetMasterProgress = player:getVar("ThePuppetMasterProgress"); local ClassReunion = player:getQuestStatus(WINDURST,CLASS_REUNION); local ClassReunionProgress = player:getVar("ClassReunionProgress"); local talk1 = player:getVar("ClassReunion_TalkedToFupepe"); local talk2 = player:getVar("ClassReunion_TalkedToFurakku"); local CarbuncleDebacle = player:getQuestStatus(WINDURST,CARBUNCLE_DEBACLE); local CarbuncleDebacleProgress = player:getVar("CarbuncleDebacleProgress"); if (blastFromPast == QUEST_AVAILABLE and qStarStruck == QUEST_COMPLETED and player:getQuestStatus(WINDURST,CLASS_REUNION) ~= QUEST_ACCEPTED and player:getFameLevel(WINDURST) >= 3 and player:needToZone() == false) then player:startEvent(0x00d6); elseif (blastFromPast == QUEST_ACCEPTED and blastProg >= 2) then player:startEvent(0x00d7); elseif (blastFromPast == QUEST_ACCEPTED) then player:startEvent(0x00d8); elseif (player:getQuestStatus(WINDURST,MAKING_THE_GRADE) == QUEST_ACCEPTED) then local makingGradeProg = player:getVar("QuestMakingTheGrade_prog"); if (makingGradeProg == 0 and player:hasItem(544)) then player:startEvent(0x011f); -- MAKING THE GRADE: Have test answers but not talked/given to Fuepepe elseif (makingGradeProg == 1) then player:startEvent(0x011d); -- MAKING THE GRADE: Turn in Test Answer & Told to go back to Fuepepe & Chomoro elseif (makingGradeProg >= 2) then player:startEvent(0x011e); -- MAKING THE GRADE: Reminder to go away else player:startEvent(0x00c1); end elseif (qStarStruck == QUEST_ACCEPTED) then player:startEvent(0x00c6); elseif ((qStarStruck == QUEST_AVAILABLE) and (ClassReunion ~= QUEST_ACCEPTED) and player:hasItem(584)) then player:startEvent(0x00c5); ---------------------------------------------------------- -- Carbuncle Debacle elseif (CarbuncleDebacle == QUEST_ACCEPTED and CarbuncleDebacleProgress == 1 or CarbuncleDebacleProgress == 2) then player:startEvent(0x01a0); -- go and see Ripapa elseif (CarbuncleDebacle == QUEST_ACCEPTED and CarbuncleDebacleProgress == 4) then player:startEvent(0x01a1); -- now go and see Agado-Pugado elseif (CarbuncleDebacle == QUEST_ACCEPTED and CarbuncleDebacleProgress == 5) then player:startEvent(0x01a2); -- Uran-Mafran must be stopped elseif (CarbuncleDebacle == QUEST_ACCEPTED and CarbuncleDebacleProgress == 7) then player:startEvent(0x01a3); -- ending cs elseif (ThePuppetMaster == QUEST_COMPLETED and ClassReunion == QUEST_COMPLETED and CarbuncleDebacle == QUEST_COMPLETED) then player:startEvent(0x01a4); -- new cs after all 3 SMN AFs done ---------------------------------------------------------- -- Class Reunion elseif (ClassReunion == QUEST_ACCEPTED and ClassReunionProgress == 1) then player:startEvent(0x019c,0,450,17299,0,0,0,0,0); -- bring Koru 4 astragaloi elseif (ClassReunion == QUEST_ACCEPTED and ClassReunionProgress == 2) then player:startEvent(0x019e,0,0,17299,0,0,0,0,0); -- reminder to bring 4 astragaloi elseif ((ClassReunion == QUEST_ACCEPTED and ClassReunionProgress >= 3) and (talk1 ~= 1 or talk2 ~= 1)) then player:startEvent(0x0198); -- reminder to visit the students elseif (ClassReunion == QUEST_ACCEPTED and ClassReunionProgress == 6 and talk1 == 1 and talk2 == 1) then player:startEvent(0x019a); -- ending cs elseif (ThePuppetMaster == QUEST_COMPLETED and ClassReunion == QUEST_COMPLETED) then player:startEvent(0x019b); -- new cs after completed AF2 ---------------------------------------------------------- -- The Puppet Master elseif (ThePuppetMaster == QUEST_ACCEPTED and ThePuppetMasterProgress == 4) then player:startEvent(0x0194); -- ending cs elseif (ThePuppetMaster == QUEST_COMPLETED and ClassReunion ~= 2) then player:startEvent(0x0195); -- new cs after completed AF1 ---------------------------------------------------------- elseif (rootProblem == QUEST_ACCEPTED and player:getVar("rootProblem") == 1) then player:startEvent(0x015C,0,829); else if (qStarStruck == QUEST_COMPLETED) then player:startEvent(0x00d5); else player:startEvent(0x00c1); end 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 == 0x011d) then -- Giving him KI from Principle player:tradeComplete(); player:addKeyItem(TATTERED_TEST_SHEET); player:messageSpecial(KEYITEM_OBTAINED,TATTERED_TEST_SHEET); player:setVar("QuestMakingTheGrade_prog",2); elseif (csid == 0x00d3) then player:tradeComplete(); player:addItem(12502); player:messageSpecial(ITEM_OBTAINED,12502); player:completeQuest(WINDURST,STAR_STRUCK); player:needToZone(true); player:addFame(WINDURST,WIN_FAME*20); elseif (csid == 0x00c7) then player:tradeComplete(); player:messageSpecial(GIL_OBTAINED,50); player:addGil(50); elseif (csid == 0x00c5 and option == 0) then player:addQuest(WINDURST,STAR_STRUCK); elseif (csid == 0x00d6 and option == 0) then player:addQuest(WINDURST,BLAST_FROM_THE_PAST); elseif (csid == 0x00e0) then player:tradeComplete(); player:setVar("BlastFromThePast_Prog",0); player:completeQuest(WINDURST,BLAST_FROM_THE_PAST); player:addItem(17030); player:messageSpecial(ITEM_OBTAINED,17030); player:addTitle(FOSSILIZED_SEA_FARER); player:addFame(WINDURST,WIN_FAME*30); player:needToZone(true); elseif (csid == 0x0194) then if (player:getFreeSlotsCount() ~= 0) then player:addItem(17532); player:messageSpecial(ITEM_OBTAINED,17532); player:completeQuest(WINDURST,THE_PUPPET_MASTER); player:setVar("ThePuppetMasterProgress",0); player:needToZone(true); player:addFame(WINDURST,WIN_FAME*AF1_FAME); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17532); end; elseif (csid == 0x019c) then player:delKeyItem(CARBUNCLES_TEAR); player:setVar("ClassReunionProgress",2); elseif (csid == 0x0197) then player:tradeComplete(); player:setVar("ClassReunionProgress",3); elseif (csid == 0x019a) then if (player:getFreeSlotsCount() ~= 0) then player:addItem(14228); player:messageSpecial(ITEM_OBTAINED,14228); player:completeQuest(WINDURST,CLASS_REUNION); player:setVar("ClassReunionProgress",0); player:setVar("ClassReunion_TalkedToFurakku",0); player:setVar("ClassReunion_TalkedToFupepe",0); player:needToZone(true); player:addFame(WINDURST,WIN_FAME*AF2_FAME); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14228); end; elseif (csid == 0x01a0) then player:setVar("CarbuncleDebacleProgress",2); elseif (csid == 0x01a1) then player:setVar("CarbuncleDebacleProgress",5); player:addKeyItem(DAZEBREAKER_CHARM); player:messageSpecial(KEYITEM_OBTAINED,DAZEBREAKER_CHARM); elseif (csid == 0x01a3) then if (player:getFreeSlotsCount() ~= 0) then player:addItem(12520); -- Evoker's Horn player:messageSpecial(ITEM_OBTAINED,12520); player:addTitle(PARAGON_OF_SUMMONER_EXCELLENCE); player:completeQuest(WINDURST,CARBUNCLE_DEBACLE); player:addFame(WINDURST,WIN_FAME*AF3_FAME); player:setVar("CarbuncleDebacleProgress",0); player:needToZone(true); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12520); end; end; end;
gpl-3.0
dickeyf/darkstar
scripts/zones/Inner_Horutoto_Ruins/npcs/_5ct.lua
13
2583
----------------------------------- -- Area: Inner Horutoto Ruins -- NPC: _5ct (Magical Gizmo) #5 -- Involved In Mission: The Horutoto Ruins Experiment ----------------------------------- package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Inner_Horutoto_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- The Magical Gizmo Number, this number will be compared to the random -- value created by the mission The Horutoto Ruins Experiment, when you -- reach the Gizmo Door and have the cutscene local magical_gizmo_no = 5; -- of the 6 -- Check if we are on Windurst Mission 1-1 if (player:getCurrentMission(WINDURST) == THE_HORUTOTO_RUINS_EXPERIMENT and player:getVar("MissionStatus") == 2) then -- Check if we found the correct Magical Gizmo or not if (player:getVar("MissionStatus_rv") == magical_gizmo_no) then player:startEvent(0x0038); else if (player:getVar("MissionStatus_op5") == 2) then -- We've already examined this player:messageSpecial(EXAMINED_RECEPTACLE); else -- Opened the wrong one player:startEvent(0x0039); end end end return 1; 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 we just finished the cutscene for Windurst Mission 1-1 -- The cutscene that we opened the correct Magical Gizmo if (csid == 0x0038) then player:setVar("MissionStatus",3); player:setVar("MissionStatus_rv", 0); player:addKeyItem(CRACKED_MANA_ORBS); player:messageSpecial(KEYITEM_OBTAINED,CRACKED_MANA_ORBS); elseif (csid == 0x0039) then -- Opened the wrong one player:setVar("MissionStatus_op5", 2); -- Give the message that thsi orb is not broken player:messageSpecial(NOT_BROKEN_ORB); end end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c57902193.lua
5
1313
--苦渋の転生 function c57902193.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_TOHAND) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCountLimit(1) e1:SetTarget(c57902193.target) e1:SetOperation(c57902193.activate) c:RegisterEffect(e1) end function c57902193.filter(c) return c:IsType(TYPE_MONSTER) and c:IsAbleToHand() end function c57902193.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c57902193.filter,tp,LOCATION_GRAVE,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_GRAVE) end function c57902193.activate(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,1-tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(1-tp,c57902193.filter,tp,LOCATION_GRAVE,0,1,1,nil) local tc=g:GetFirst() if tc then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetCode(EVENT_PHASE+PHASE_END) e1:SetRange(LOCATION_GRAVE) e1:SetCountLimit(1) e1:SetOperation(c57902193.thop) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e1) end end function c57902193.thop(e,tp,eg,ep,ev,re,r,rp) if Duel.SendtoHand(e:GetHandler(),nil,REASON_EFFECT)~=0 then Duel.ConfirmCards(1-tp,e:GetHandler()) end end
gpl-2.0
Turttle/darkstar
scripts/zones/Mhaura/npcs/Blandine.lua
17
2177
----------------------------------- -- Area: Mhaura -- NPC: Blandine -- Start Quest: The Sand Charmz -- @pos 23 -7 41 249 ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Mhaura/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local X = player:getXPos(); Z = player:getZPos(); local TheSandCharm = player:getQuestStatus(OTHER_AREAS,THE_SAND_CHARM); if (Z <= 29 or Z >= 38 or X <= 16 or X >= 32) then if (player:getFameLevel(WINDURST) >= 4 and TheSandCharm == QUEST_AVAILABLE) then player:startEvent(0x007d); -- Start quest "The Sand Charm" elseif (player:getVar("theSandCharmVar") == 2) then player:startEvent(0x007c); -- During quest "The Sand Charm" - 2nd dialog elseif (TheSandCharm == QUEST_COMPLETED and player:getVar("SmallDialogByBlandine") == 1) then player:startEvent(0x0080); -- Thanks dialog of Bladine after "The Sand Charm" elseif (TheSandCharm == QUEST_COMPLETED) then player:startEvent(0x0081); -- New standard dialog after "The Sand Charm" else player:startEvent(0x007a); -- Standard dialog end 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 == 0x007d) then player:addQuest(OTHER_AREAS,THE_SAND_CHARM); player:setVar("theSandCharmVar",1); elseif (csid == 0x007c) then player:setVar("theSandCharmVar",3); elseif (csid == 0x0080) then player:setVar("SmallDialogByBlandine",0); end end;
gpl-3.0
Turttle/darkstar
scripts/zones/Labyrinth_of_Onzozo/npcs/Grounds_Tome.lua
34
1146
----------------------------------- -- Area: Labyrinth of Onzozo -- NPC: Grounds Tome ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/groundsofvalor"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) startGov(GOV_EVENT_LABYRINTH_OF_ONZOZO,player); end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); updateGov(player,csid,option,771,772,773,774,775,776,0,0,0,0); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); finishGov(player,csid,option,771,772,773,774,775,776,0,0,0,0,GOV_MSG_LABYRINTH_OF_ONZOZO); end;
gpl-3.0
Turttle/darkstar
scripts/globals/items/watermelon.lua
35
1197
----------------------------------------- -- ID: 4491 -- Item: watermelon -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility -6 -- Intelligence 4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4491); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, -6); target:addMod(MOD_INT, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, -6); target:delMod(MOD_INT, 4); end;
gpl-3.0
dickeyf/darkstar
scripts/zones/Grauberg_[S]/npcs/qm1.lua
30
1695
----------------------------------- -- Area: Grauberg [S] -- NPC: ??? -- Quest - DNC AF1 ----------------------------------- package.loaded["scripts/zones/Grauberg_[S]/TextIDs"] = nil; ------------------------------------- require("scripts/globals/harvesting"); require("scripts/zones/Grauberg_[S]/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_ACCEPTED and player:getVar("QuestStatus_DNC_AF1")==2) then player:startEvent(0x0C); elseif (player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_ACCEPTED and player:getVar("QuestStatus_DNC_AF1")==3) then if (GetMobAction(17142108) == 0) then SpawnMob(17142108):updateEnmity(player); end elseif (player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_ACCEPTED and player:getVar("QuestStatus_DNC_AF1")==4) then player:startEvent(0x0D); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid==0x0C) then player:setVar("QuestStatus_DNC_AF1", 3); elseif (csid==0x0D) then player:addKeyItem(THE_ESSENCE_OF_DANCE); player:messageSpecial(KEYITEM_OBTAINED,THE_ESSENCE_OF_DANCE); player:setVar("QuestStatus_DNC_AF1", 5); end end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c53927679.lua
7
1145
--ファイヤー・トルーパー function c53927679.initial_effect(c) --damage local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(53927679,0)) e1:SetCategory(CATEGORY_DAMAGE) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_DAMAGE_STEP) e1:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_SINGLE) e1:SetCost(c53927679.cost) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetTarget(c53927679.tg) e1:SetOperation(c53927679.op) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e2) local e3=e1:Clone() e3:SetCode(EVENT_FLIP_SUMMON_SUCCESS) c:RegisterEffect(e3) end function c53927679.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToGraveAsCost() end Duel.SendtoGrave(e:GetHandler(),REASON_COST) end function c53927679.tg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetTargetPlayer(1-tp) Duel.SetTargetParam(1000) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,1000) end function c53927679.op(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
SalvationDevelopment/Salvation-Scripts-TCG
c89333528.lua
5
1203
--ジェネクス・ガイア function c89333528.initial_effect(c) --Destroy replace local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_DESTROY_REPLACE) e2:SetTarget(c89333528.desreptg) e2:SetOperation(c89333528.desrepop) c:RegisterEffect(e2) end function c89333528.repfilter(c) return c:IsFaceup() and c:IsCode(68505803) and not c:IsStatus(STATUS_DESTROY_CONFIRMED) end function c89333528.desreptg(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return not c:IsReason(REASON_REPLACE) and c:IsOnField() and c:IsFaceup() and Duel.IsExistingMatchingCard(c89333528.repfilter,tp,LOCATION_MZONE,0,1,c) end if Duel.SelectYesNo(tp,aux.Stringid(89333528,0)) then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESREPLACE) local g=Duel.SelectMatchingCard(tp,c89333528.repfilter,tp,LOCATION_MZONE,0,1,1,c) Duel.SetTargetCard(g) g:GetFirst():SetStatus(STATUS_DESTROY_CONFIRMED,true) return true else return false end end function c89333528.desrepop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS) g:GetFirst():SetStatus(STATUS_DESTROY_CONFIRMED,false) Duel.Destroy(g,REASON_EFFECT+REASON_REPLACE) end
gpl-2.0
Turttle/darkstar
scripts/zones/Valkurm_Dunes/npcs/Nyata-Mobuta_WW.lua
30
3056
----------------------------------- -- Area: Valkurm Dunes -- NPC: Nyata-Mobuta, W.W. -- Type: Outpost Conquest Guards -- @pos 139.394 -7.885 100.384 103 ----------------------------------- package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Valkurm_Dunes/TextIDs"); local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ZULKHEIM; local csid = 0x7ff7; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
SalvationDevelopment/Salvation-Scripts-TCG
c20932152.lua
6
1410
--クイック・シンクロン function c20932152.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(c20932152.spcon) e1:SetOperation(c20932152.spop) c:RegisterEffect(e1) -- local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_CANNOT_BE_SYNCHRO_MATERIAL) e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e2:SetValue(c20932152.synlimit) c:RegisterEffect(e2) -- local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e3:SetCode(20932152) c:RegisterEffect(e3) end function c20932152.synlimit(e,c) if not c then return false end return not aux.IsMaterialListSetCard(c,0x1017) end function c20932152.spfilter(c) return c:IsType(TYPE_MONSTER) and c:IsAbleToGraveAsCost() end function c20932152.spcon(e,c) if c==nil then return true end local tp=c:GetControler() return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c20932152.spfilter,tp,LOCATION_HAND,0,1,c) end function c20932152.spop(e,tp,eg,ep,ev,re,r,rp,c) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,c20932152.spfilter,tp,LOCATION_HAND,0,1,1,c) Duel.SendtoGrave(g,REASON_COST) end
gpl-2.0