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 |
|---|---|---|---|---|---|
l33tRS/E2Power | lua/entities/gmod_wire_expression2/core/custom/health.lua | 1 | 12164 |
__e2setcost(20)
local fl = math.floor
local cl = math.Clamp
e2function void entity:setHealth(number Health)
if !IsValid(this) then return end
if tostring(Health) == "nan" then return end
if !isOwner(self, this) then return end
if this:Health()==0 then return end
Health=cl(Health,0, 1000000000)
this:SetHealth(Health)
end
e2function void entity:setArmor(number Armor)
if !IsValid(this) then return end
if tostring(Armor) == "nan" then return end
if !isOwner(self, this) then return end
if !this:IsPlayer() then return end
Armor=cl(Armor, 0, 1000000000)
this:SetArmor(Armor)
end
e2function void entity:heal(number Health)
if !IsValid(this) then return end
if !isOwner(self, this) then return end
if this:Health()==0 then return end
if tostring(Health) == "nan" then return end
Health=this:Health()+Health
Health=cl(Health,0, 1000000000)
this:SetHealth(Health)
end
e2function void entity:extinguish()
if !IsValid(this) then return end
if !isOwner(self,this) then return end
this:Extinguish()
end
e2function void entity:ignite(number l)
if !IsValid(this) then return end
if !isOwner(self,this) then return end
local _length = math.Max( l , 2 )
this:Ignite( _length, 0 )
end
e2function void entity:setMaxHealth(number Health)
if !IsValid(this) then return end
if !isOwner(self,this) then return end
if tostring(Health) == "nan" then return end
if this:Health()==0 then return end
this:SetMaxHealth(Health)
this:SetHealth(Health)
end
e2function number entity:maxHealth()
if !IsValid(this) then return 0 end
return this:GetMaxHealth() or 0
end
__e2setcost(250)
e2function void entity:shootTo(vector start,vector dir,number spread,number force,number damage,string effect)
local BlEff = {"dof_node","smoke","hl1gaussbeam"}
if !IsValid(this) then return end
for _, i in pairs(BlEff) do
if effect:lower() == i then error("Effect "..effect.." is blocked!") return end
end
if !isOwner(self,this) then return end
local bullet = {}
bullet.Num = 1
bullet.Src = Vector(start[1],start[2],start[3])
bullet.Dir = Vector(dir[1],dir[2],dir[3])
bullet.Spread = Vector( spread, spread, 0 )
bullet.Tracer = 1
bullet.TracerName = effect
bullet.Force = math.Clamp(force, 0 , 10000 )
bullet.Damage = damage
bullet.Attacker = self.player
this:FireBullets( bullet )
end
e2function void shake(vector pos, amplitude, frequency, duration, radius)
if not hasAccess(self) then return end
util.ScreenShake( Vector(pos[1],pos[2],pos[3]), amplitude, frequency, duration, radius)
end
e2function void explosion(number damage, number radius, vector pos)
if not hasAccess(self) then return end
util.BlastDamage( self.player, self.player, Vector(pos[1],pos[2],pos[3]), cl(radius,0,10000), damage )
end
e2function void entity:explosion(number damage, number radius)
if not hasAccess(self) then return end
if !IsValid(this) then return end
util.BlastDamage( this, self.player, this:GetPos(), cl(radius,0,10000), damage )
end
e2function void entity:explosion()
if !IsValid(this) then return end
if !isOwner(self, this) then return end
local radius=(this:OBBMaxs() - this:OBBMins())
radius = (radius.x^2 + radius.y^2 + radius.z^2) ^ 0.5
local pos=this:GetPos()
util.BlastDamage( this, self.player, this:GetPos(), radius*10, radius*3 )
local effectdata = EffectData()
effectdata:SetOrigin( pos )
util.Effect( "explosion" , effectdata )
end
e2function void explosion(number damage, number radius, vector pos, entity attacker, entity inflictor)
if not hasAccess(self) then return end
util.BlastDamage( inflictor, attacker, Vector(pos[1],pos[2],pos[3]), cl(radius,0,10000), damage )
end
e2function void explosion(vector pos)
if not hasAccess(self) then return end
local pos=Vector(pos[1],pos[2],pos[3])
util.BlastDamage( self.player, self.player, pos, 150, 100)
local effectdata = EffectData()
effectdata:SetOrigin( pos )
util.Effect( "explosion" , effectdata )
end
local dmgEffect = {
[0] = function(ent,d,h) end,
[1] = function(ent,d,h)
local c = ent:GetColor()
ent:SetColor(Color( cl(c.r-fl((c.r/h)*d),0,255) , cl(c.g-fl((c.g/h)*d),0,255) , cl(c.b-fl((c.g/h)*d),0,255) ,c.a))
end,
}
local dstrEffect = {
[0] = function(ent) ent:Remove() end,
[1] = function(ent)
ent.hasHP=nil
ent:SetColor(Color(0,0,0,0))
ent:SetRenderMode(RENDERMODE_TRANSALPHA)
local effectdata = EffectData()
effectdata:SetEntity( ent )
util.Effect( "entity_remove" , effectdata )
ent:SetNotSolid(true)
ent:Fire("Kill","1",0.2)
end,
[2] = function(ent)
local effectdata = EffectData()
effectdata:SetOrigin( ent:GetPos() )
util.Effect( "explosion" , effectdata )
ent:Remove()
end,
[3] = function(ent)
ent.hasHP=nil
local c = ent:GetColor()
ent:SetColor(Color(0,0,0,c.a))
constraint.RemoveAll(ent)
ent:SetNotSolid(true)
local phys = ent:GetPhysicsObject()
phys:Wake()
phys:EnableMotion(true)
phys:EnableGravity(false)
ent:Fire("Kill","1",10)
end,
["explo"] = function(ent)
local radius=(ent:OBBMaxs() - ent:OBBMins())
radius = (radius.x^2 + radius.y^2 + radius.z^2) ^ 0.5
local pos = ent:GetPos()
ent.hasHP=nil
util.BlastDamage( ent, ent.owner , pos, radius*10, radius*3)
local effectdata = EffectData()
effectdata:SetOrigin( pos )
util.Effect( "explosion" , effectdata )
ent:Remove()
end,
}
local dmgType1 = {
["DMG_ACID"]=1048576,
["DMG_AIRBOAT"]=33554432,
["DMG_ALWAYSGIB"]=8192,
["DMG_BLAST"]=64,
["DMG_BLAST_SURFACE"]=134217728,
["DMG_BUCKSHOT"]=536870912,
["DMG_BULLET"]=2,
["DMG_BURN"]=8,
["DMG_CLUB"]=128,
["DMG_CRUSH"]=1,
["DMG_DIRECT"]=268435456,
["DMG_DISSOLVE"]=67108864,
["DMG_DROWN"]=16384,
["DMG_DROWNRECOVER"]=524288,
["DMG_ENERGYBEAM"]=1024,
["DMG_FALL"]=32,
["DMG_GENERIC"]=0,
["DMG_NERVEGAS"]=65536,
["DMG_NEVERGIB"]=4096,
["DMG_PARALYZE"]=32768,
["DMG_PHYSGUN"]=8388608,
["DMG_PLASMA"]=16777216,
["DMG_POISON"]=131072,
["DMG_PREVENT_PHYSICS_FORCE"]=2048,
["DMG_RADIATION"]=262144,
["DMG_REMOVENORAGDOLL"]=4194304,
["DMG_SHOCK"]=256,
["DMG_SLASH"]=4,
["DMG_SLOWBURN"]=2097152,
["DMG_SONIC"]=512,
["DMG_VEHICLE"]=16,
}
local dmgType = {}
for v,k in pairs(dmgType1) do
local s = v:Right(v:len()-4):lower()
dmgType[s]=k
dmgType[k]=s
end
local dmgType1 = nil
__e2setcost(50)
local function takeDmg(Ent, Ply, Amount, Type, Force, Attacker, Inflictor)
local dmgInfo = DamageInfo()
dmgInfo:AddDamage(Amount)
dmgInfo:SetDamageType( dmgType[Type:lower()] or 0 )
dmgInfo:SetAttacker(Attacker or Ply)
dmgInfo:SetInflictor(Inflictor or Ply)
dmgInfo:SetDamageForce( Force or Vector(0,0,0) )
Ent:TakeDamageInfo(dmgInfo)
end
e2function void entity:takeDamage(number Amount,string Type)
if !IsValid(this) then return end
if !isOwner(self, this) then return end
takeDmg(this, self.player, Amount, Type)
end
e2function void entity:takeDamage(number Amount, string Type, vector Force)
if !IsValid(this) then return end
if !isOwner(self, this) then return end
takeDmg(this, self.player, Amount, Type, Vector(Force[1],Force[2],Force[3]))
end
e2function void entity:takeDamage(number Amount, string Type, vector Force, entity Attacker, entity Inflictor)
if !IsValid(this) then return end
if !isOwner(self, this) then return end
takeDmg(this, self.player, Amount, Type, Vector(Force[1],Force[2],Force[3]), Attacker, Inflictor)
end
e2function void entity:takeDamage(number Amount, entity Attacker, entity Inflictor)
if !IsValid(this) then return end
if !isOwner(self, this) then return end
this:TakeDamage(Amount, Attacker, Inflictor)
end
e2function void entity:takeDamage(number Amount)
if !IsValid(this) then return end
if !isOwner(self, this) then return end
this:TakeDamage(Amount,self.player,self.player)
end
hook.Add("EntityTakeDamage", "CheckE2Dmg", function( ent, dmginfo )
if ent.e2DmgDebag then
ent.e2DmgInf = {}
ent.e2DmgInf["damage"] = dmginfo:GetDamage()
ent.e2DmgInf["attacker"] = dmginfo:GetAttacker()
ent.e2DmgInf["inflictor"] = dmginfo:GetInflictor()
ent.e2DmgInf["dmgtype"] = dmginfo:GetDamageType()
ent.e2DmgInf["pos"] = dmginfo:GetDamagePosition()
ent.e2DmgCheck = {}
if ent.e2DmgEx!=nil then
for k,v in pairs(ent.e2DmgEx) do
if !IsValid(k) then ent.e2DmgEx[k]=nil continue end
if k.DmgClkEnt==nil then k.DmgClkEnt=ent k:Execute() k.DmgClkEnt=nil end
end
end
end
if ent.hasHP then
local H = ent:Health()
local D = dmginfo:GetDamage()
if H>D then ent:SetHealth(H-D) dmgEffect[ent.dmgEff](ent,D,H)
else dstrEffect[ent.dstrEff](ent)
end
end
end)
local function e2DmgValid(param, e2 , ent)
if !IsValid(ent) then return false end
if !ent.e2DmgDebag then ent.e2DmgDebag=true ent.e2DmgCheck={} ent.e2DmgInf={} return false end
if ent.e2DmgCheck[e2]==nil then
ent.e2DmgCheck[e2] = {}
ent.e2DmgCheck[e2][param] = false
end
if ent.e2DmgCheck[e2][param] then return false end
ent.e2DmgCheck[e2][param]=true
return true
end
__e2setcost(20)
e2function number entity:getDamage()
if !e2DmgValid("damage",self.entity,this) then return 0 end
return this.e2DmgInf["damage"] or 0
end
e2function entity entity:getAttacker()
if !e2DmgValid("attacker",self.entity,this) then return nil end
return this.e2DmgInf["attacker"] or nil
end
e2function entity entity:getInflictor()
if !e2DmgValid("inflictor",self.entity,this) then return nil end
return this.e2DmgInf["inflictor"] or nil
end
e2function vector entity:getDamagePos()
if !e2DmgValid("pos",self.entity,this) then return {0,0,0} end
return this.e2DmgInf["pos"] or {0,0,0}
end
e2function string entity:getDamageType()
if !e2DmgValid("dmgtype",self.entity,this) then return "" end
return dmgType[this.e2DmgInf["dmgtype"]] or ""
end
e2function void runOnDamage(active,entity ent)
if !IsValid(ent) then return end
if ent==self.entity then return end
if ent.e2DmgEx == nil then ent.e2DmgDebag=true ent.e2DmgEx={} ent.e2DmgCheck={} ent.e2DmgInf={} end
ent.e2DmgEx[self.entity]= tobool(active) and true or nil
end
e2function void runOnDamage(number active)
if active!=0 then
self.entity.OnTakeDamage = function(dmgInf)
if self.entity.DmgClkEnt==nil then self.entity.DmgClkEnt=self.entity self.entity:Execute() self.entity.DmgClkEnt=nil end
end
else
self.entity.OnTakeDamage = nil
end
end
__e2setcost(5)
e2function entity damageEntClk()
return self.entity.DmgClkEnt
end
__e2setcost(70)
local function MakeHealth(ent,dmgeff,dstreff,health)
if ent:Health()!=0 then return end
if ent:IsPlayerHolding() then return end
if !validPhysics(ent) then return end
if health==nil then
health=ent:GetPhysicsObject():GetMass()*10
end
health = math.Clamp(health,0, 1000000000)
ent:SetMaxHealth(health)
ent:SetHealth(health)
ent.hasHP=true
ent.dmgEff=dmgEffect[dmgeff] and dmgeff or 0
ent.dstrEff=dstrEffect[dstreff] and dstreff or 0
end
e2function void entity:makeHealth()
if !IsValid(this) then return end
if !isOwner(self, this) then return end
MakeHealth(this,1,1)
end
e2function void entity:makeHealth(damageEffect,destroyEffect)
if !IsValid(this) then return end
if !isOwner(self, this) then return end
MakeHealth(this,damageEffect,destroyEffect)
end
e2function void entity:makeHealth(damageEffect,destroyEffect,Health)
if !IsValid(this) then return end
if !isOwner(self, this) then return end
MakeHealth(this,damageEffect,destroyEffect,Health)
end
e2function void entity:makeNoHealth()
if !IsValid(this) then return end
if !isOwner(self, this) then return end
this:SetMaxHealth(0)
this:SetHealth(0)
this.hasHP=nil
this.dmgEff=nil
this.dstrEff=nil
end
e2function void entity:makeVolatile()
if !IsValid(this) then return end
if !isOwner(self, this) then return end
MakeHealth(this,0,0,25)
this.dstrEff= "explo"
this.owner = self.player
end
concommand.Add( "props_health", function(ply,cmd,argm)
if IsValid(ply) then if !ply:IsSuperAdmin() and !ply:IsAdmin() then return end end
if tobool(argm[1]) then
hook.Add("EntityTakeDamage", "E2AllDmg", function( ent )
if !ent.hasHP then if ent:Health()==0 then if validPhysics(ent) then MakeHealth(ent, tonumber(argm[2]) or 1 ,tonumber(argm[3]) or 1) end end end
end)
else
hook.Remove("EntityTakeDamage", "E2AllDmg")
end
end) | gpl-3.0 |
Zenny89/darkstar | scripts/globals/mobskills/Bai_Wing.lua | 25 | 1095 | ---------------------------------------------
-- Bai Wing
--
-- Description: A hot wind deals Fire damage to enemies within a very wide area of effect. Additional effect: Plague
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes shadows
-- Range: 30' radial.
-- Notes: Used only by Ouryu and Cuelebre while flying.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:AnimationSub() ~= 1) then
return 1;
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_SLOW;
MobStatusEffectMove(mob, target, typeEffect, 300, 0, 120);
local dmgmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_EARTH,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_EARTH,MOBPARAM_WIPE_SHADOWS);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
mercury233/ygopro-scripts | c66226132.lua | 2 | 1839 | --トラックブラック
function c66226132.initial_effect(c)
--link summon
aux.AddLinkProcedure(c,aux.FilterBoolFunction(Card.IsLinkType,TYPE_EFFECT),2,2)
c:EnableReviveLimit()
--Draw
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(66226132,0))
e1:SetCategory(CATEGORY_DRAW)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1,66226132)
e1:SetTarget(c66226132.target)
e1:SetOperation(c66226132.operation)
c:RegisterEffect(e1)
end
function c66226132.tgfilter(c,lg)
return lg:IsContains(c)
end
function c66226132.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local lg=e:GetHandler():GetLinkedGroup()
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c66226132.tgfilter(chkc,lg) end
if chk==0 then return Duel.IsExistingTarget(c66226132.tgfilter,tp,LOCATION_MZONE,0,1,nil,lg) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
Duel.SelectTarget(tp,c66226132.tgfilter,tp,LOCATION_MZONE,0,1,1,nil,lg)
end
function c66226132.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if not tc:IsRelateToEffect(e) then return end
tc:RegisterFlagEffect(66226132,RESET_EVENT+0x1220000+RESET_PHASE+PHASE_END,EFFECT_FLAG_CLIENT_HINT,1,0,aux.Stringid(66226132,1))
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_BATTLE_DESTROYING)
e1:SetLabelObject(tc)
e1:SetCondition(c66226132.drcon)
e1:SetOperation(c66226132.drop)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c66226132.drcon(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
return eg:IsContains(tc) and tc:GetFlagEffect(66226132)~=0
end
function c66226132.drop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_CARD,0,66226132)
Duel.Draw(tp,1,REASON_EFFECT)
end
| gpl-2.0 |
Zenny89/darkstar | scripts/zones/Ordelles_Caves/npcs/qm4.lua | 17 | 1419 | -----------------------------------
-- Area: Ordelles Caves
-- NPC: ??? (qm4)
-- Involved In Quest: Dark Puppet
-- @pos -52 27 -85 193
-----------------------------------
package.loaded["scripts/zones/Ordelles_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Ordelles_Caves/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getVar("darkPuppetCS") >= 2 and player:hasItem(16681) == false) then
if (trade:hasItemQty(654,1) and trade:getItemCount() == 1) then -- Trade Darksteel Ingot
player:tradeComplete();
player:messageSpecial(GERWITZS_AXE_DIALOG);
SpawnMob(17568135,180):updateClaim(player);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
mercury233/ygopro-scripts | c62070231.lua | 2 | 1771 | --No.94 極氷姫クリスタル・ゼロ
function c62070231.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.FilterBoolFunction(Card.IsAttribute,ATTRIBUTE_WATER),5,2)
c:EnableReviveLimit()
--atk down
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(62070231,0))
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetRange(LOCATION_MZONE)
e1:SetHintTiming(TIMING_DAMAGE_STEP)
e1:SetCondition(aux.dscon)
e1:SetCost(c62070231.cost)
e1:SetTarget(c62070231.target)
e1:SetOperation(c62070231.operation)
c:RegisterEffect(e1)
end
aux.xyz_number[62070231]=94
function c62070231.cost(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 c62070231.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsFaceup() end
if chk==0 then return Duel.IsExistingTarget(Card.IsFaceup,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,Card.IsFaceup,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
end
function c62070231.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFaceup() then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SET_ATTACK_FINAL)
e1:SetValue(math.ceil(tc:GetAttack()/2))
if Duel.GetTurnPlayer()~=tp then
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END,2)
else
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END,1)
end
tc:RegisterEffect(e1)
end
end
| gpl-2.0 |
omid4631aghaz/xy | plugins/yid.lua | 2 | 1135 | do
local function run(msg, matches)
local bot_id = 0
local x = 192916039
local y = 180239388
local z = 179783031
local w = 158135400
if matches[1] == 'bye' and is_admin(msg) or msg.action.type == "chat_add_user" and msg.action.user.id == tonumber(bot_id) and not is_sudo(msg) then
chat_del_user("chat#id"..msg.to.id, 'user#id'..bot_id, ok_cb, false)
elseif msg.action.type == "chat_del_user" and msg.action.user.id == tonumber(x) then
chat_add_user("chat#id"..msg.to.id, 'user#id'..x, ok_cb, false)
end
elseif msg.action.type == "chat_del_user" and msg.action.user.id == tonumber(y) then
chat_add_user("chat#id"..msg.to.id, 'user#id'..y, ok_cb, false)
end
elseif msg.action.type == "chat_del_user" and msg.action.user.id == tonumber(z) then
chat_add_user("chat#id"..msg.to.id, 'user#id'..z, ok_cb, false)
end
elseif msg.action.type == "chat_del_user" and msg.action.user.id == tonumber(w) then
chat_add_user("chat#id"..msg.to.id, 'user#id'..w, ok_cb, false)
end
end
return {
patterns = {
"^[!/](bye)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
focusworld/telemamal | 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 |
mercury233/ygopro-scripts | c81825063.lua | 2 | 2657 | --氷結界の虎将 ウェイン
function c81825063.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(81825063,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_HAND)
e1:SetCountLimit(1,81825063)
e1:SetCondition(c81825063.spcon)
e1:SetTarget(c81825063.sptg)
e1:SetOperation(c81825063.spop)
c:RegisterEffect(e1)
--search
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(81825063,1))
e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e2:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_SINGLE)
e2:SetCode(EVENT_SUMMON_SUCCESS)
e2:SetProperty(EFFECT_FLAG_DELAY)
e2:SetCountLimit(1,81825064)
e2:SetTarget(c81825063.thtg)
e2:SetOperation(c81825063.thop)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e3)
--
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD)
e4:SetProperty(EFFECT_FLAG_SET_AVAILABLE+EFFECT_FLAG_IGNORE_IMMUNE)
e4:SetCode(EFFECT_TO_GRAVE_REDIRECT)
e4:SetRange(LOCATION_MZONE)
e4:SetTarget(c81825063.rmtarget)
e4:SetTargetRange(LOCATION_ONFIELD,LOCATION_ONFIELD)
e4:SetValue(LOCATION_REMOVED)
c:RegisterEffect(e4)
end
function c81825063.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0x2f)
end
function c81825063.spcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetFieldGroupCount(tp,0,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c81825063.cfilter,tp,LOCATION_MZONE,0,1,nil)
end
function c81825063.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 c81825063.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 c81825063.thfilter(c)
return c:IsSetCard(0x2f) and c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsAbleToHand()
end
function c81825063.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c81825063.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c81825063.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c81825063.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 c81825063.rmtarget(e,c)
return c:GetOriginalType()&(TYPE_SPELL+TYPE_TRAP)~=0 and c:GetOwner()~=e:GetHandlerPlayer()
end
| gpl-2.0 |
ZeroK-RTS/SpringRTS-Tools | aoplate baker/plateplane.lua | 1 | 3130 | return { plateplane = {
unitname = [[plateplane]],
name = [[Airplane Plate]],
description = [[Augments Production]],
acceleration = 0,
activateWhenBuilt = false,
brakeRate = 0,
buildCostMetal = Shared.FACTORY_PLATE_COST,
builder = true,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 10,
buildingGroundDecalSizeY = 10,
buildingGroundDecalType = [[pad_decal_square.dds]],
buildoptions = {
[[planecon]],
[[planefighter]],
[[planeheavyfighter]],
[[bomberprec]],
[[bomberriot]],
[[bomberdisarm]],
[[bomberheavy]],
[[planescout]],
[[planelightscout]],
},
buildPic = [[plateplane.png]],
canMove = true,
canPatrol = true,
category = [[FLOAT UNARMED]],
corpse = [[DEAD]],
customParams = {
landflystate = [[0]],
sortName = [[4]],
modelradius = [[51]], -- at 50 planefighter won't respond to Bugger Off calls
midposoffset = [[0 20 0]],
nongroundfac = [[1]],
default_spacing = 4,
child_of_factory = [[factoryplane]],
},
energyUse = 0,
explodeAs = [[FAC_PLATEEX]],
fireState = 0,
footprintX = 6,
footprintZ = 7,
iconType = [[padair]],
idleAutoHeal = 5,
idleTime = 1800,
maxDamage = Shared.FACTORY_PLATE_HEALTH,
maxSlope = 15,
maxVelocity = 0,
maxWaterDepth = 0,
minCloakDistance = 150,
moveState = 2,
noAutoFire = false,
objectName = [[plate_plane.s3o]],
script = [[plateplane.lua]],
selfDestructAs = [[FAC_PLATEEX]],
showNanoSpray = false,
sightDistance = 273,
turnRate = 0,
useBuildingGroundDecal = true,
workerTime = Shared.FACTORY_BUILDPOWER,
yardMap = [[oooooo oooooo oooooo oooooo oooooo oooooo oooooo]],
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 6,
footprintZ = 7,
object = [[plate_plane_dead.s3o]],
},
HEAP = {
blocking = false,
footprintX = 6,
footprintZ = 7,
object = [[debris4x4c.s3o]],
},
},
buildingGroundDecalDecaySpeed=30,
buildingGroundDecalSizeX=10,
buildingGroundDecalSizeY=10,
useBuildingGroundDecal = true,
buildingGroundDecalType=[[plateplane_aoplane.dds]],
}
| gpl-2.0 |
mercury233/ygopro-scripts | c46173679.lua | 1 | 2612 | --終焉の焔
function c46173679.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,TIMING_END_PHASE)
e1:SetCost(c46173679.cost)
e1:SetTarget(c46173679.target)
e1:SetOperation(c46173679.activate)
c:RegisterEffect(e1)
end
function c46173679.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetActivityCount(tp,ACTIVITY_SUMMON)==0
and Duel.GetActivityCount(tp,ACTIVITY_FLIPSUMMON)==0 and Duel.GetActivityCount(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:SetLabelObject(e)
e1:SetTargetRange(1,0)
e1:SetTarget(c46173679.sumlimit)
Duel.RegisterEffect(e1,tp)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH)
e2:SetCode(EFFECT_CANNOT_SUMMON)
e2:SetReset(RESET_PHASE+PHASE_END)
e2:SetTargetRange(1,0)
Duel.RegisterEffect(e2,tp)
local e3=e2:Clone()
e3:SetCode(EFFECT_CANNOT_FLIP_SUMMON)
Duel.RegisterEffect(e3,tp)
end
function c46173679.sumlimit(e,c,sump,sumtype,sumpos,targetp,se)
return e:GetLabelObject()~=se
end
function c46173679.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return not Duel.IsPlayerAffectedByEffect(tp,59822133)
and Duel.GetLocationCount(tp,LOCATION_MZONE)>1
and Duel.IsPlayerCanSpecialSummonMonster(tp,46173680,0,TYPES_TOKEN_MONSTER,0,0,1,RACE_FIEND,ATTRIBUTE_DARK,POS_FACEUP_DEFENSE) end
Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,2,0,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,0,0)
end
function c46173679.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.IsPlayerAffectedByEffect(tp,59822133) then return end
if Duel.GetLocationCount(tp,LOCATION_MZONE)>1
and Duel.IsPlayerCanSpecialSummonMonster(tp,46173680,0,TYPES_TOKEN_MONSTER,0,0,1,RACE_FIEND,ATTRIBUTE_DARK,POS_FACEUP_DEFENSE) then
for i=1,2 do
local token=Duel.CreateToken(tp,46173679+i)
Duel.SpecialSummonStep(token,0,tp,tp,false,false,POS_FACEUP_DEFENSE)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UNRELEASABLE_SUM)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetValue(c46173679.recon)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
token:RegisterEffect(e1,true)
end
Duel.SpecialSummonComplete()
end
end
function c46173679.recon(e,c)
return not c:IsAttribute(ATTRIBUTE_DARK)
end
| gpl-2.0 |
honzahovorka/dotfiles | nvim/lua/settings/hop.lua | 1 | 1434 | require('hop').setup()
local opts = { noremap = true, silent = true }
local keymap = vim.api.nvim_set_keymap
keymap('o', 'f',
':lua require("hop").hint_char1({ direction = require("hop.hint").HintDirection.AFTER_CURSOR, current_line_only = true })<CR>'
, opts)
keymap('o', 'F',
':lua require("hop").hint_char1({ direction = require("hop.hint").HintDirection.BEFORE_CURSOR, current_line_only = true })<CR>'
, opts)
keymap('o', 't',
':lua require("hop").hint_char1({ direction = require("hop.hint").HintDirection.AFTER_CURSOR, current_line_only = true, hint_offset = -1 })<CR>'
, opts)
keymap('o', 'T',
':lua require("hop").hint_char1({ direction = require("hop.hint").HintDirection.BEFORE_CURSOR, current_line_only = true, hint_offset = 1 })<CR>'
, opts)
keymap('n', 'f',
':lua require("hop").hint_char1({ direction = require("hop.hint").HintDirection.AFTER_CURSOR, current_line_only = true })<CR>'
, opts)
keymap('n', 'F',
':lua require("hop").hint_char1({ direction = require("hop.hint").HintDirection.BEFORE_CURSOR, current_line_only = true })<CR>'
, opts)
keymap('n', 't',
':lua require("hop").hint_char1({ direction = require("hop.hint").HintDirection.AFTER_CURSOR, current_line_only = true, hint_offset = -1 })<CR>'
, opts)
keymap('n', 'T',
':lua require("hop").hint_char1({ direction = require("hop.hint").HintDirection.BEFORE_CURSOR, current_line_only = true, hint_offset = 1 })<CR>'
, opts)
| mit |
ESMAILESMAIL/gladiator2 | plugins/location.lua | 93 | 1704 | -- Implement a command !loc [area] which uses
-- the static map API to get a location image
-- Not sure if this is the proper way
-- Intent: get_latlong is in time.lua, we need it here
-- loadfile "time.lua"
-- Globals
-- If you have a google api key for the geocoding/timezone api
do
local api_key = nil
local base_api = "https://maps.googleapis.com/maps/api"
function get_staticmap(area)
local api = base_api .. "/staticmap?"
-- Get a sense of scale
local lat,lng,acc,types = get_latlong(area)
local scale = types[1]
if scale=="locality" then zoom=8
elseif scale=="country" then zoom=4
else zoom = 13 end
local parameters =
"size=600x300" ..
"&zoom=" .. zoom ..
"¢er=" .. URL.escape(area) ..
"&markers=color:red"..URL.escape("|"..area)
if api_key ~=nil and api_key ~= "" then
parameters = parameters .. "&key="..api_key
end
return lat, lng, api..parameters
end
function run(msg, matches)
local receiver = get_receiver(msg)
local lat,lng,url = get_staticmap(matches[1])
-- Send the actual location, is a google maps link
send_location(receiver, lat, lng, ok_cb, false)
-- Send a picture of the map, which takes scale into account
send_photo_from_url(receiver, url)
-- Return a link to the google maps stuff is now not needed anymore
return nil
end
return {
description = "Gets information about a location, maplink and overview",
usage = "!loc (location): Gets information about a location, maplink and overview",
patterns = {"^!loc (.*)$"},
run = run
}
end
--Copyright and edit; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
notcake/gcompute | lua/gcompute/ast/memberfunctioncall.lua | 1 | 3438 | local self = {}
self.__Type = "MemberFunctionCall"
GCompute.AST.MemberFunctionCall = GCompute.AST.MakeConstructor (self, GCompute.AST.Expression)
function self:ctor ()
self.LeftExpression = nil
self.Identifier = nil
self.TypeArgumentList = nil
self.ArgumentList = GCompute.AST.ArgumentList ()
self.FunctionCall = nil
end
function self:ComputeMemoryUsage (memoryUsageReport)
memoryUsageReport = memoryUsageReport or GCompute.MemoryUsageReport ()
if memoryUsageReport:IsCounted (self) then return end
memoryUsageReport:CreditTableStructure ("Syntax Trees", self)
memoryUsageReport:CreditString ("Syntax Trees", self.Identifier)
if self.Identifier then
self.Identifier:ComputeMemoryUsage (memoryUsageReport)
end
if self.LeftExpression then
self.LeftExpression:ComputeMemoryUsage (memoryUsageReport)
end
if self.ArgumentList then
self.ArgumentList:ComputeMemoryUsage (memoryUsageReport)
end
return memoryUsageReport
end
function self:ExecuteAsAST (astRunner, state)
self.FunctionCall:ExecuteAsAST (astRunner, state)
end
function self:GetArgumentList ()
return self.ArgumentList
end
function self:GetArgumentTypes (includeLeft)
if includeLeft == nil then includeLeft = true end
local argumentTypes = self.ArgumentList:GetArgumentTypes ()
if includeLeft then
table.insert (argumentTypes, 1, self.LeftExpression:GetType ())
end
return argumentTypes
end
function self:GetChildEnumerator ()
local i = 0
return function ()
i = i + 1
if i == 1 then
return self.LeftExpression
elseif i == 2 then
return self.ArgumentList
end
return nil
end
end
function self:GetLeftExpression ()
return self.LeftExpression
end
function self:GetIdentifier ()
return self.Identifier
end
function self:GetTypeArgumentList ()
return self.TypeArgumentList
end
function self:SetArgumentList (argumentList)
self.ArgumentList = argumentList
if self.ArgumentList then self.ArgumentList:SetParent (self) end
end
function self:SetIdentifier (identifier)
self.Identifier = identifier
end
function self:SetLeftExpression (leftExpression)
self.LeftExpression = leftExpression
if self.LeftExpression then self.LeftExpression:SetParent (self) end
end
function self:SetTypeArgumentList (typeArgumentList)
self.TypeArgumentList = typeArgumentList
if self.TypeArgumentList then self.TypeArgumentList:SetParent (self) end
end
function self:ToString ()
local leftExpression = self.LeftExpression and self.LeftExpression:ToString () or "[Nothing]"
local identifier = self.Identifier and self.Identifier:ToString () or "[Nothing]"
local argumentList = self.ArgumentList and self.ArgumentList:ToString () or "([Nothing])"
local typeArgumentList = self.TypeArgumentList and self.TypeArgumentList:ToString () or nil
return leftExpression .. ":" .. identifier .. (typeArgumentList and (" " .. typeArgumentList) or "") .. " " .. argumentList
end
function self:Visit (astVisitor, ...)
self:SetLeftExpression (self:GetLeftExpression ():Visit (astVisitor, ...) or self:GetLeftExpression ())
if self.TypeArgumentList then
self:SetTypeArgumentList (self:GetTypeArgumentList ():Visit (astVisitor, ...) or self:GetTypeArgumentList ())
end
self:SetArgumentList (self:GetArgumentList ():Visit (astVisitor, ...) or self:GetArgumentList ())
return astVisitor:VisitExpression (self, ...)
end | gpl-3.0 |
mercury233/ygopro-scripts | c59042331.lua | 2 | 1378 | --ガード・ヘッジ
function c59042331.initial_effect(c)
--atkdown
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(59042331,0))
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_PRE_DAMAGE_CALCULATE)
e1:SetRange(LOCATION_HAND)
e1:SetCondition(c59042331.atkcon)
e1:SetCost(c59042331.atkcost)
e1:SetOperation(c59042331.atkop)
c:RegisterEffect(e1)
end
function c59042331.atkcon(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:IsControler(tp)
end
function c59042331.atkcost(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 c59042331.atkop(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
if tc:IsRelateToBattle() then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_DAMAGE)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_SET_ATTACK_FINAL)
e2:SetValue(math.ceil(tc:GetAttack()/2))
e2:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e2)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c57246528.lua | 2 | 1966 | --シンクロ・トランセンド
function c57246528.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCountLimit(1,57246528+EFFECT_COUNT_CODE_OATH)
e1:SetTarget(c57246528.target)
e1:SetOperation(c57246528.activate)
c:RegisterEffect(e1)
end
function c57246528.opfilter(c,e,tp)
return c:IsFaceup() and c:IsType(TYPE_SYNCHRO) and Duel.IsExistingMatchingCard(c57246528.tpfilter,tp,LOCATION_EXTRA,0,1,nil,c:GetLevel(),e,tp)
end
function c57246528.tpfilter(c,lv,e,tp)
return c:IsType(TYPE_SYNCHRO) and c:IsLevel(lv+1) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and Duel.GetLocationCountFromEx(tp,tp,nil,c)>0
end
function c57246528.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 c57246528.opfilter(chkc,e,tp) end
if chk==0 then return Duel.IsExistingTarget(c57246528.opfilter,tp,0,LOCATION_MZONE,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
local g=Duel.SelectTarget(tp,c57246528.opfilter,tp,0,LOCATION_MZONE,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA)
end
function c57246528.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if not tc:IsRelateToEffect(e) then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sg=Duel.SelectMatchingCard(tp,c57246528.tpfilter,tp,LOCATION_EXTRA,0,1,1,nil,tc:GetLevel(),e,tp):GetFirst()
if sg and Duel.SpecialSummonStep(sg,0,tp,tp,false,false,POS_FACEUP) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetDescription(aux.Stringid(57246528,0))
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_TRIGGER)
e1:SetProperty(EFFECT_FLAG_CLIENT_HINT)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
sg:RegisterEffect(e1)
end
Duel.SpecialSummonComplete()
end
| gpl-2.0 |
mercury233/ygopro-scripts | c83135907.lua | 2 | 2666 | --スクラップ・ゴブリン
function c83135907.initial_effect(c)
--destroy
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EVENT_BE_BATTLE_TARGET)
e1:SetOperation(c83135907.regop)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(83135907,0))
e2:SetCategory(CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EVENT_PHASE+PHASE_BATTLE)
e2:SetCountLimit(1)
e2:SetTarget(c83135907.destg)
e2:SetOperation(c83135907.desop)
c:RegisterEffect(e2)
--to hand
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(83135907,1))
e3:SetCategory(CATEGORY_TOHAND)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_TO_GRAVE)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY)
e3:SetCondition(c83135907.thcon)
e3:SetTarget(c83135907.thtg)
e3:SetOperation(c83135907.thop)
c:RegisterEffect(e3)
--indes
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e4:SetValue(1)
c:RegisterEffect(e4)
end
function c83135907.regop(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsDefensePos() and e:GetHandler():IsFaceup() then
e:GetHandler():RegisterFlagEffect(83135907,RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_BATTLE,0,1)
end
end
function c83135907.destg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():GetFlagEffect(83135907)~=0 end
Duel.SetOperationInfo(0,CATEGORY_DESTROY,e:GetHandler(),1,0,0)
end
function c83135907.desop(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsRelateToEffect(e) then
Duel.Destroy(e:GetHandler(),REASON_EFFECT)
end
end
function c83135907.thcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return bit.band(c:GetReason(),0x41)==0x41 and re and re:GetOwner():IsSetCard(0x24)
end
function c83135907.filter(c)
return c:IsSetCard(0x24) and c:IsType(TYPE_MONSTER) and not c:IsCode(83135907) and c:IsAbleToHand()
end
function c83135907.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c83135907.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c83135907.filter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectTarget(tp,c83135907.filter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0)
end
function c83135907.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 |
SharpWoW/Command | InviteManager.lua | 1 | 10441 | --[[
* Copyright (c) 2011-2012 by Adam Hellberg.
*
* This file is part of Command.
*
* Command is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Command 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 Command. If not, see <http://www.gnu.org/licenses/>.
--]]
-- Upvalues
local type = type
local ceil = math.ceil
-- API Upvalues
local CreateFrame = CreateFrame
local AcceptGroup = AcceptGroup
local AcceptGuild = AcceptGuild
local DeclineGroup = DeclineGroup
local DeclineGuild = DeclineGuild
local StaticPopup_Show = StaticPopup_Show
local StaticPopup_Hide = StaticPopup_Hide
local StaticPopup_Visible = StaticPopup_Visible
local GetGuildFactionInfo = GetGuildFactionInfo
local C = Command
C.InviteManager = {
Dialogs = {
ConfirmGuildOverride = "COMMAND_GUILD_CONFIRM_OVERRIDE"
}
}
local L = C.LocaleManager
local IM = C.InviteManager
local GT = C.GroupTools
local CM
local PM
local log = C.Logger
local DEFAULT_GROUP_DELAY = 5
local DEFAULT_GUILD_DELAY = 5
local GROUP_MAX_DELAY = 50
local GUILD_MAX_DELAY = 50
-- Static Popup Dialogs
StaticPopupDialogs[IM.Dialogs.ConfirmGuildOverride] = {
text = "IM_GUILD_CONFIRM_OVERRIDE_POPUP",
button1 = "YES",
button2 = "NO",
OnAccept = function() log:Normal(L(IM:EnableGuildOverride(true))) end,
OnCancel = function() log:Normal(L(IM:DisableGuildOverride())) end,
timeout = 20,
whileDead = true,
hideOnEscape = false
}
local function CloseGuildInvite()
local frame = CreateFrame("Frame")
frame.Time = 0
frame:SetScript("OnUpdate", function(self, elapsed)
self.Time = self.Time + elapsed
if self.Time >= 0.5 then
self:SetScript("OnUpdate", nil)
if GuildInviteFrame and GuildInviteFrame:IsShown() then
GuildInviteFrame:Hide()
end
end
end)
end
function IM:Init()
CM = C.ChatManager
PM = C.PlayerManager
self:LoadSavedVars()
end
function IM:LoadSavedVars()
if type(C.Global["INVITE_MANAGER"]) ~= "table" then
C.Global["INVITE_MANAGER"] = {}
end
self.Settings = C.Global["INVITE_MANAGER"]
if type(self.Settings.ENABLED) ~= "boolean" then
self.Settings.ENABLED = true
end
if type(self.Settings.GROUP) ~= "table" then
self.Settings.GROUP = {}
end
if type(self.Settings.GROUP.ENABLED) ~= "boolean" then
self.Settings.GROUP.ENABLED = true
end
if type(self.Settings.GROUP.ANNOUNCE) ~= "boolean" then
self.Settings.GROUP.ANNOUNCE = true
end
if type(self.Settings.GROUP.DELAY) ~= "number" then
self.Settings.GROUP.DELAY = DEFAULT_GROUP_DELAY
end
if type(self.Settings.GUILD) ~= "table" then
self.Settings.GUILD = {}
end
if type(self.Settings.GUILD.ENABLED) ~= "boolean" then
self.Settings.GUILD.ENABLED = true
end
if type(self.Settings.GUILD.ANNOUNCE) ~= "boolean" then
self.Settings.GUILD.ANNOUNCE = true
end
if type(self.Settings.GUILD.DELAY) ~= "number" then
self.Settings.GUILD.DELAY = DEFAULT_GUILD_DELAY
end
if type(self.Settings.GUILD.OVERRIDE) ~= "boolean" then
self.Settings.GUILD.OVERRIDE = false
end
end
function IM:OnGroupInvite(sender)
if self.Settings.GROUP.DELAY > 0 then
local frame = CreateFrame("Frame")
frame.Time = 0
frame.Delay = self.Settings.GROUP.DELAY
frame.Sender = sender
frame:SetScript("OnUpdate", function(self, elapsed)
self.Time = self.Time + elapsed
if self.Time >= self.Delay then
self:SetScript("OnUpdate", nil)
IM:AnnounceGroupInvite(self.Sender)
end
end)
else
self:AnnounceGroupInvite(sender)
end
end
function IM:OnGuildInvite(sender)
if self.Settings.GROUP.DELAY > 0 then
local frame = CreateFrame("Frame")
frame.Time = 0
frame.Delay = self.Settings.GUILD.DELAY
frame.Sender = sender
frame:SetScript("OnUpdate", function(self, elapsed)
self.Time = self.Time + elapsed
if self.Time >= self.Delay then
self:SetScript("OnUpdate", nil)
IM:AnnounceGuildInvite(self.Sender)
end
end)
else
self:AnnounceGuildInvite(sender)
end
end
function IM:AnnounceGroupInvite(sender)
if not self:HasGroupInvite() then return end
local locale = PM:GetOrCreatePlayer(sender).Settings.Locale
local msg = L(locale, "IM_GROUP_ANNOUNCE", true)
CM:SendMessage(msg, "WHISPER", sender)
end
function IM:AnnounceGuildInvite(sender)
if not self:HasGuildInvite() then return end
local locale = PM:GetOrCreatePlayer(sender).Settings.Locale
local msg = L(locale, "IM_GUILD_ANNOUNCE", true)
CM:SendMessage(msg, "WHISPER", sender)
end
function IM:AcceptGroupInvite()
if not self:HasGroupInvite() then
return false, "IM_GROUP_NOINVITE"
end
AcceptGroup()
if StaticPopup_Visible("PARTY_INVTIE") then
StaticPopup_Hide("PARTY_INVITE")
end
return "IM_GROUP_ACCEPTED"
end
function IM:DeclineGroupInvite()
if not self:HasGroupInvite() then
return false, "IM_GROUP_NOINVITE"
end
DeclineGroup()
if StaticPopup_Visible("PARTY_INVTIE") then
StaticPopup_Hide("PARTY_INVITE")
end
return "IM_GROUP_DECLINED"
end
function IM:AcceptGuildInvite()
if not self:HasGuildInvite() then
return false, "IM_GUILD_NOINVITE"
elseif self:HasGuildRep() and not self:IsGuildOverrideEnabled() then
return false, "IM_GUILD_HASREP"
end
AcceptGuild()
CloseGuildInvite()
return "IM_GUILD_ACCEPTED"
end
function IM:DeclineGuildInvite()
if not self:HasGuildInvite() then
return false, "IM_GUILD_NOINVITE"
end
DeclineGuild()
CloseGuildInvite()
return "IM_GUILD_DECLINED"
end
function IM:HasGroupInvite()
return StaticPopup_Visible("PARTY_INVITE")
end
function IM:HasGuildInvite()
return GuildInviteFrame and GuildInviteFrame:IsShown()
end
function IM:HasGuildRep()
local _, _, standingID, _, _, value = GetGuildFactionInfo()
if value > 0 or standingID ~= 4 then -- More than 0 rep or higher than Neutral status
return true
end
return false
end
function IM:Enable()
self.Settings.ENABLED = true
return "IM_ENABLED"
end
function IM:Disable()
self.Settings.ENABLED = false
return "IM_DISABLED"
end
function IM:Toggle()
if self:IsEnabled() then
return self:Disable()
end
return self:Enable()
end
function IM:IsEnabled()
return self.Settings.ENABLED
end
function IM:EnableGroup()
self.Settings.GROUP.ENABLED = true
return "IM_GROUP_ENABLED"
end
function IM:DisableGroup()
self.Settings.GROUP.ENABLED = false
return "IM_GROUP_DISABLED"
end
function IM:ToggleGroup()
if self:IsGroupEnabled() then
return self:DisableGroup()
end
return self:EnableGroup()
end
function IM:IsGroupEnabled()
return self.Settings.GROUP.ENABLED
end
function IM:EnableGroupAnnounce()
self.Settings.GROUP.ANNOUNCE = true
return "IM_GROUPANNOUNCE_ENABLED"
end
function IM:DisableGroupAnnounce()
self.Settings.GROUP.ANNOUNCE = false
return "IM_GROUPANNOUNCE_DISABLED"
end
function IM:ToggleGroupAnnounce()
if self:IsGroupAnnounceEnabled() then
return self:DisableGroupAnnounce()
end
return self:EnableGroupAnnounce()
end
function IM:IsGroupAnnounceEnabled()
return self.Settings.GROUP.ANNOUNCE
end
function IM:SetGroupDelay(delay)
if type(delay) ~= "number" then
return false, "IM_GROUPDELAY_NUM"
end
delay = ceil(delay)
if delay < 0 or delay > GROUP_MAX_DELAY then
return false, "IM_GROUPDELAY_OUTOFRANGE", {GROUP_MAX_DELAY}
end
self.Settings.GROUP.DELAY = delay
if self.Settings.GROUP.DELAY > 0 then
return "IM_GROUPDELAY_SET", {self.Settings.GROUP.DELAY}
end
return "IM_GROUPDELAY_DISABLED"
end
function IM:GetGroupDelay()
return self.Settings.GROUP.DELAY
end
function IM:DisableGroupDelay()
return self:SetGroupDelay(0)
end
function IM:EnableGuild()
self.Settings.GUILD.ENABLED = true
return "IM_GUILD_ENABLED"
end
function IM:DisableGuild()
self.Settings.GUILD.ENABLED = false
return "IM_GUILD_DISABLED"
end
function IM:ToggleGuild()
if self:IsGuildEnabled() then
return self:DisableGuild()
end
return self:EnableGuild()
end
function IM:IsGuildEnabled()
return self.Settings.GUILD.ENABLED
end
function IM:EnableGuildAnnounce()
self.Settings.GUILD.ANNOUNCE = true
return "IM_GUILDANNOUNCE_ENABLED"
end
function IM:DisableGuildAnnounce()
self.Settings.GUILD.ANNOUNCE = false
return "IM_GUILDANNOUNCE_DISABLED"
end
function IM:ToggleGuildAnnounce()
if self:IsGuildAnnounceEnabled() then
return self:DisableGuildAnnounce()
end
return self.EnableGuildAnnounce()
end
function IM:IsGuildAnnounceEnabled()
return self.Settings.GUILD.ANNOUNCE
end
function IM:EnableGuildOverride(confirm)
if StaticPopup_Visible(self.Dialogs.ConfirmGuildOverride) and not confirm then
return false, "IM_GUILDOVERRIDE_PENDING"
end
if not confirm then
StaticPopupDialogs[self.Dialogs.ConfirmGuildOverride].text = L("IM_GUILD_CONFIRM_OVERRIDE_POPUP")
StaticPopupDialogs[self.Dialogs.ConfirmGuildOverride].button1 = L("YES")
StaticPopupDialogs[self.Dialogs.ConfirmGuildOverride].button2 = L("NO")
StaticPopup_Show(self.Dialogs.ConfirmGuildOverride)
return "IM_GUILDOVERRIDE_WAITING"
end
if StaticPopup_Visible(self.Dialogs.ConfirmGuildOverride) then
StaticPopup_Hide(self.Dialogs.ConfirmGuildOverride)
end
self.Settings.GUILD.OVERRIDE = true
return "IM_GUILDOVERRIDE_ENABLED"
end
function IM:DisableGuildOverride()
if StaticPopup_Visible(self.Dialogs.ConfirmGuildOverride) then
return false, "IM_GUILDOVERRIDE_PENDING"
end
self.Settings.GUILD.OVERRIDE = false
return "IM_GUILDOVERRIDE_DISABLED"
end
function IM:ToggleGuildOverride()
if self:IsGuildOverrideEnabled() then
return self:DisableGuildOverride()
end
return self:EnableGuildOverride()
end
function IM:IsGuildOverrideEnabled()
return self.Settings.GUILD.OVERRIDE
end
function IM:SetGuildDelay(delay)
if type(delay) ~= "number" then
return false, "IM_GUILDDELAY_NUM"
end
delay = ceil(delay)
if delay < 0 or delay > GUILD_MAX_DELAY then
return false, "IM_GUILDDELAY_OUTOFRANGE", {GUILD_MAX_DELAY}
end
self.Settings.GUILD.DELAY = delay
if self.Settings.GUILD.DELAY > 0 then
return "IM_GUILDDELAY_SET", {self.Settings.GUILD.DELAY}
end
return "IM_GUILDDELAY_DISABLED"
end
function IM:GetGuildDelay()
return self.Settings.GUILD.DELAY
end
function IM:DisableGuildDelay()
return self:SetGuildDelay(0)
end
| gpl-3.0 |
linushsao/marsu_game-linus-v0.2 | mods/mars_pack/mars_mobs_redo/mobs_redo/api.lua | 1 | 73200 |
-- Mobs Api (28th May 2017)
mobs = {}
mobs.mod = "redo"
mobs.version = "20170528"
-- Intllib
local S
if minetest.get_modpath("intllib") then
S = intllib.Getter()
else
S = function(s, a, ...) a = {a, ...}
return s:gsub("@(%d+)", function(n)
return a[tonumber(n)]
end)
end
end
mobs.intllib = S
-- Invisibility mod check
mobs.invis = {}
if rawget(_G, "invisibility") then
mobs.invis = invisibility
end
-- localize math functions
local pi = math.pi
local square = math.sqrt
local sin = math.sin
local cos = math.cos
local abs = math.abs
local min = math.min
local max = math.max
local atann = math.atan
local random = math.random
local floor = math.floor
local atan = function(x)
if not x or x ~= x then
--error("atan bassed NaN")
return 0
else
return atann(x)
end
end
-- Load settings
local damage_enabled = minetest.settings:get_bool("enable_damage")
local peaceful_only = minetest.settings:get_bool("only_peaceful_mobs")
local disable_blood = minetest.settings:get_bool("mobs_disable_blood")
local creative = minetest.settings:get_bool("creative_mode")
local spawn_protected = tonumber(minetest.settings:get("mobs_spawn_protected")) or 1
local remove_far = minetest.settings:get_bool("remove_far_mobs")
local difficulty = tonumber(minetest.settings:get("mob_difficulty")) or 1.0
local show_health = minetest.settings:get_bool("mob_show_health") ~= false
local max_per_block = tonumber(minetest.settings:get("max_objects_per_block") or 99)
-- calculate aoc range for mob count
local aosrb = tonumber(minetest.settings:get("active_object_send_range_blocks"))
local abr = tonumber(minetest.settings:get("active_block_range"))
local aoc_range = max(aosrb, abr) * 16
-- pathfinding settings
local enable_pathfinding = true
local stuck_timeout = 3 -- how long before mob gets stuck in place and starts searching
local stuck_path_timeout = 10 -- how long will mob follow path before giving up
-- play sound
local mob_sound = function(self, sound)
if sound then
minetest.sound_play(sound, {
object = self.object,
gain = 1.0,
max_hear_distance = self.sounds.distance
})
end
end
-- attack player/mob
local do_attack = function(self, player)
if self.state == "attack" then
return
end
self.attack = player
self.state = "attack"
if random(0, 100) < 90 then
mob_sound(self, self.sounds.war_cry)
end
end
-- move mob in facing direction
local set_velocity = function(self, v)
local yaw = (self.object:getyaw() or 0) + self.rotate
self.object:setvelocity({
x = sin(yaw) * -v,
y = self.object:getvelocity().y,
z = cos(yaw) * v
})
end
-- get overall speed of mob
local get_velocity = function(self)
local v = self.object:getvelocity()
return (v.x * v.x + v.z * v.z) ^ 0.5
end
-- set yaw
local set_yaw = function(self, yaw)
if not yaw or yaw ~= yaw then
yaw = 0
end
self:setyaw(yaw)
return yaw
end
-- set defined animation
local set_animation = function(self, anim)
if not self.animation then return end
self.animation.current = self.animation.current or ""
if anim == self.animation.current
or not self.animation[anim .. "_start"]
or not self.animation[anim .. "_end"] then
return
end
self.animation.current = anim
self.object:set_animation({
x = self.animation[anim .. "_start"],
y = self.animation[anim .. "_end"]
}, self.animation[anim .. "_speed"] or self.animation.speed_normal or 15)
end
-- above function exported for mount.lua
function mobs:set_animation(anim)
set_animation(self, anim)
end
-- this is a faster way to calculate distance
local get_distance = function(a, b)
local x, y, z = a.x - b.x, a.y - b.y, a.z - b.z
return square(x * x + y * y + z * z)
end
-- check line of sight (BrunoMine)
local line_of_sight = function(self, pos1, pos2, stepsize)
stepsize = stepsize or 1
local s, pos = minetest.line_of_sight(pos1, pos2, stepsize)
-- normal walking and flying mobs can see you through air
if s == true then
return true
end
-- New pos1 to be analyzed
local npos1 = {x = pos1.x, y = pos1.y, z = pos1.z}
local r, pos = minetest.line_of_sight(npos1, pos2, stepsize)
-- Checks the return
if r == true then return true end
-- Nodename found
local nn = minetest.get_node(pos).name
-- Target Distance (td) to travel
local td = get_distance(pos1, pos2)
-- Actual Distance (ad) traveled
local ad = 0
-- It continues to advance in the line of sight in search of a real
-- obstruction which counts as 'normal' nodebox.
while minetest.registered_nodes[nn]
and (minetest.registered_nodes[nn].walkable == false
or minetest.registered_nodes[nn].drawtype == "nodebox") do
-- Check if you can still move forward
if td < ad + stepsize then
return true -- Reached the target
end
-- Moves the analyzed pos
local d = get_distance(pos1, pos2)
npos1.x = ((pos2.x - pos1.x) / d * stepsize) + pos1.x
npos1.y = ((pos2.y - pos1.y) / d * stepsize) + pos1.y
npos1.z = ((pos2.z - pos1.z) / d * stepsize) + pos1.z
-- NaN checks
if d == 0
or npos1.x ~= npos1.x
or npos1.y ~= npos1.y
or npos1.z ~= npos1.z then
return false
end
ad = ad + stepsize
-- scan again
r, pos = minetest.line_of_sight(npos1, pos2, stepsize)
if r == true then return true end
-- New Nodename found
nn = minetest.get_node(pos).name
end
return false
end
-- are we flying in what we are suppose to? (taikedz)
local flight_check = function(self, pos_w)
local nod = self.standing_in
if type(self.fly_in) == "string"
and (nod == self.fly_in or nod == self.fly_in:gsub("_source", "_flowing")) then
return true
elseif type(self.fly_in) == "table" then
for _,fly_in in pairs(self.fly_in) do
if nod == fly_in or nod == fly_in:gsub("_source", "_flowing") then
return true
end
end
end
return false
end
-- particle effects
local effect = function(pos, amount, texture, min_size, max_size, radius, gravity)
radius = radius or 2
min_size = min_size or 0.5
max_size = max_size or 1
gravity = gravity or -10
minetest.add_particlespawner({
amount = amount,
time = 0.25,
minpos = pos,
maxpos = pos,
minvel = {x = -radius, y = -radius, z = -radius},
maxvel = {x = radius, y = radius, z = radius},
minacc = {x = 0, y = gravity, z = 0},
maxacc = {x = 0, y = gravity, z = 0},
minexptime = 0.1,
maxexptime = 1,
minsize = min_size,
maxsize = max_size,
texture = texture,
})
end
-- update nametag colour
local update_tag = function(self)
local col = "#00FF00"
local qua = self.hp_max / 4
if self.health <= floor(qua * 3) then
col = "#FFFF00"
end
if self.health <= floor(qua * 2) then
col = "#FF6600"
end
if self.health <= floor(qua) then
col = "#FF0000"
end
self.object:set_properties({
nametag = self.nametag,
nametag_color = col
})
end
-- drop items
local item_drop = function(self, cooked)
local obj, item, num
local pos = self.object:getpos()
if not pos then return end -- sometimes its nil idk why
self.drops = self.drops or {} -- nil check
for n = 1, #self.drops do
if random(1, self.drops[n].chance) == 1 then
num = random(self.drops[n].min, self.drops[n].max)
item = self.drops[n].name
-- cook items when true
if cooked then
local output = minetest.get_craft_result({
method = "cooking", width = 1, items = {item}})
if output and output.item and not output.item:is_empty() then
item = output.item:get_name()
end
end
-- add item if it exists
obj = minetest.add_item(pos, ItemStack(item .. " " .. num))
if obj and obj:get_luaentity() then
obj:setvelocity({
x = random(-10, 10) / 9,
y = 6,
z = random(-10, 10) / 9,
})
else
obj:remove() -- item does not exist
end
end
end
self.drops = {}
end
-- check if mob is dead or only hurt
local check_for_death = function(self, cause)
-- has health actually changed?
if self.health == self.old_health and self.health > 0 then
return
end
self.old_health = self.health
-- still got some health? play hurt sound
if self.health > 0 then
mob_sound(self, self.sounds.damage)
-- make sure health isn't higher than max
if self.health > self.hp_max then
self.health = self.hp_max
end
-- backup nametag so we can show health stats
if not self.nametag2 then
self.nametag2 = self.nametag or ""
end
if show_health then
self.htimer = 2
self.nametag = "♥ " .. self.health .. " / " .. self.hp_max
update_tag(self)
end
return false
end
if cause == "lava" then
item_drop(self, true)
else
item_drop(self, nil)
end
mob_sound(self, self.sounds.death)
local pos = self.object:getpos()
-- execute custom death function
if self.on_die then
self.on_die(self, pos)
self.object:remove()
return true
end
-- default death function and die animation (if defined)
if self.animation
and self.animation.die_start
and self.animation.die_end then
self.attack = nil
self.v_start = false
self.timer = 0
self.blinktimer = 0
self.passive = true
self.state = "die"
set_velocity(self, 0)
set_animation(self, "die")
minetest.after(2, function(self)
self.object:remove()
end, self)
else
self.object:remove()
end
effect(pos, 20, "tnt_smoke.png")
return true
end
-- check if within physical map limits (-30911 to 30927)
local within_limits = function(pos, radius)
if (pos.x - radius) > -30913
and (pos.x + radius) < 30928
and (pos.y - radius) > -30913
and (pos.y + radius) < 30928
and (pos.z - radius) > -30913
and (pos.z + radius) < 30928 then
return true -- within limits
end
return false -- beyond limits
end
-- is mob facing a cliff
local is_at_cliff = function(self)
if self.fear_height == 0 then -- 0 for no falling protection!
return false
end
local yaw = self.object:getyaw()
local dir_x = -sin(yaw) * (self.collisionbox[4] + 0.5)
local dir_z = cos(yaw) * (self.collisionbox[4] + 0.5)
local pos = self.object:getpos()
local ypos = pos.y + self.collisionbox[2] -- just above floor
if minetest.line_of_sight(
{x = pos.x + dir_x, y = ypos, z = pos.z + dir_z},
{x = pos.x + dir_x, y = ypos - self.fear_height, z = pos.z + dir_z}
, 1) then
return true
end
return false
end
-- get node but use fallback for nil or unknown
local node_ok = function(pos, fallback)
fallback = fallback or "default:dirt"
local node = minetest.get_node_or_nil(pos)
if not node then
return minetest.registered_nodes[fallback]
end
if minetest.registered_nodes[node.name] then
return node
end
return minetest.registered_nodes[fallback]
end
-- environmental damage (water, lava, fire, light)
local do_env_damage = function(self)
-- feed/tame text timer (so mob 'full' messages dont spam chat)
if self.htimer > 0 then
self.htimer = self.htimer - 1
end
-- reset nametag after showing health stats
if self.htimer < 1 and self.nametag2 then
self.nametag = self.nametag2
self.nametag2 = nil
update_tag(self)
end
local pos = self.object:getpos()
self.time_of_day = minetest.get_timeofday()
-- remove mob if beyond map limits
if not within_limits(pos, 0) then
self.object:remove()
return
end
-- daylight above ground
if self.light_damage ~= 0
and pos.y > 0
and self.time_of_day > 0.2
and self.time_of_day < 0.8
and (minetest.get_node_light(pos) or 0) > 12 then
self.health = self.health - self.light_damage
effect(pos, 5, "tnt_smoke.png")
if check_for_death(self, "light") then return end
end
-- what is mob standing in?
pos.y = pos.y + self.collisionbox[2] + 0.1 -- foot level
self.standing_in = node_ok(pos, "air").name
-- print ("standing in " .. self.standing_in)
-- don't fall when on ignore, just stand still
if self.standing_in == "ignore" then
self.object:setvelocity({x = 0, y = 0, z = 0})
--print ("--- stopping on ignore")
end
if self.water_damage ~= 0
or self.lava_damage ~= 0 then
local nodef = minetest.registered_nodes[self.standing_in]
pos.y = pos.y + 1
-- water
if nodef.groups.water then
if self.water_damage ~= 0 then
self.health = self.health - self.water_damage
effect(pos, 5, "bubble.png", nil, nil, 1, nil)
if check_for_death(self, "water") then return end
end
-- lava or fire
elseif (nodef.groups.lava
or self.standing_in == "fire:basic_flame"
or self.standing_in == "fire:permanent_flame") then
if self.lava_damage ~= 0 then
self.health = self.health - self.lava_damage
effect(pos, 5, "fire_basic_flame.png", nil, nil, 1, nil)
if check_for_death(self, "lava") then return end
end
-- damage_per_second node check
elseif minetest.registered_nodes[self.standing_in].damage_per_second ~= 0 then
local dps = minetest.registered_nodes[self.standing_in].damage_per_second
self.health = self.health - dps
effect(pos, 5, "tnt_smoke.png")
end
end
if self.standing_in == "air" then
if not self.no_air_damage then
minetest.after(5, function(pos)
if node_ok(pos, "air").name ~= "air" then return end
self.health = self.health - 4
check_for_death(self, "vacuum")
end, pos)
end
end
check_for_death(self, "")
end
-- jump if facing a solid node (not fences or gates)
local do_jump = function(self)
if not self.jump
or self.jump_height == 0
or self.fly
or self.child then
return false
end
-- something stopping us while moving?
if self.state ~= "stand"
and get_velocity(self) > 0.5
and self.object:getvelocity().y ~= 0 then
return false
end
local pos = self.object:getpos()
local yaw = self.object:getyaw()
-- what is mob standing on?
pos.y = pos.y + self.collisionbox[2] - 0.2
local nod = node_ok(pos)
--print ("standing on:", nod.name, pos.y)
if minetest.registered_nodes[nod.name].walkable == false then
return false
end
-- where is front
local dir_x = -sin(yaw) * (self.collisionbox[4] + 0.5)
local dir_z = cos(yaw) * (self.collisionbox[4] + 0.5)
-- what is in front of mob?
local nod = node_ok({
x = pos.x + dir_x,
y = pos.y + 0.5,
z = pos.z + dir_z
})
-- thin blocks that do not need to be jumped
if nod.name == "default:snow" then
return false
end
--print ("in front:", nod.name, pos.y + 0.5)
if (minetest.registered_items[nod.name].walkable
and not nod.name:find("fence")
and not nod.name:find("gate"))
or self.walk_chance == 0 then
local v = self.object:getvelocity()
v.y = self.jump_height -- + 1
set_animation(self, "jump") -- only when defined
self.object:setvelocity(v)
mob_sound(self, self.sounds.jump)
return true
end
return false
end
-- blast damage to entities nearby (modified from TNT mod)
local entity_physics = function(pos, radius)
radius = radius * 2
local objs = minetest.get_objects_inside_radius(pos, radius)
local obj_pos, dist
for n = 1, #objs do
obj_pos = objs[n]:getpos()
dist = get_distance(pos, obj_pos)
if dist < 1 then dist = 1 end
local damage = floor((4 / dist) * radius)
local ent = objs[n]:get_luaentity()
-- punches work on entities AND players
objs[n]:punch(objs[n], 1.0, {
full_punch_interval = 1.0,
damage_groups = {fleshy = damage},
}, nil)
end
end
-- should mob follow what I'm holding ?
local follow_holding = function(self, clicker)
if mobs.invis[clicker:get_player_name()] then
return false
end
local item = clicker:get_wielded_item()
local t = type(self.follow)
-- single item
if t == "string"
and item:get_name() == self.follow then
return true
-- multiple items
elseif t == "table" then
for no = 1, #self.follow do
if self.follow[no] == item:get_name() then
return true
end
end
end
return false
end
-- find two animals of same type and breed if nearby and horny
local breed = function(self)
-- child takes 240 seconds before growing into adult
if self.child == true then
self.hornytimer = self.hornytimer + 1
if self.hornytimer > 240 then
self.child = false
self.hornytimer = 0
self.object:set_properties({
textures = self.base_texture,
mesh = self.base_mesh,
visual_size = self.base_size,
collisionbox = self.base_colbox,
})
-- jump when fully grown so not to fall into ground
self.object:setvelocity({
x = 0,
y = self.jump_height,
z = 0
})
end
return
end
-- horny animal can mate for 40 seconds,
-- afterwards horny animal cannot mate again for 200 seconds
if self.horny == true
and self.hornytimer < 240 then
self.hornytimer = self.hornytimer + 1
if self.hornytimer >= 240 then
self.hornytimer = 0
self.horny = false
end
end
-- find another same animal who is also horny and mate if close enough
if self.horny == true
and self.hornytimer <= 40 then
local pos = self.object:getpos()
effect({x = pos.x, y = pos.y + 1, z = pos.z}, 8, "heart.png", 3, 4, 1, 0.1)
local objs = minetest.get_objects_inside_radius(pos, 3)
local num = 0
local ent = nil
for n = 1, #objs do
ent = objs[n]:get_luaentity()
-- check for same animal with different colour
local canmate = false
if ent then
if ent.name == self.name then
canmate = true
else
local entname = string.split(ent.name,":")
local selfname = string.split(self.name,":")
if entname[1] == selfname[1] then
entname = string.split(entname[2],"_")
selfname = string.split(selfname[2],"_")
if entname[1] == selfname[1] then
canmate = true
end
end
end
end
if ent
and canmate == true
and ent.horny == true
and ent.hornytimer <= 40 then
num = num + 1
end
-- found your mate? then have a baby
if num > 1 then
self.hornytimer = 41
ent.hornytimer = 41
-- spawn baby
minetest.after(5, function()
local mob = minetest.add_entity(pos, self.name)
local ent2 = mob:get_luaentity()
local textures = self.base_texture
if self.child_texture then
textures = self.child_texture[1]
end
mob:set_properties({
textures = textures,
visual_size = {
x = self.base_size.x * .5,
y = self.base_size.y * .5,
},
collisionbox = {
self.base_colbox[1] * .5,
self.base_colbox[2] * .5,
self.base_colbox[3] * .5,
self.base_colbox[4] * .5,
self.base_colbox[5] * .5,
self.base_colbox[6] * .5,
},
})
ent2.child = true
ent2.tamed = true
ent2.owner = self.owner
end)
num = 0
break
end
end
end
end
-- find and replace what mob is looking for (grass, wheat etc.)
local replace = function(self, pos)
if not self.replace_rate
or not self.replace_what
or self.child == true
or self.object:getvelocity().y ~= 0
or random(1, self.replace_rate) > 1 then
return
end
local what, with, y_offset
if type(self.replace_what[1]) == "table" then
local num = random(#self.replace_what)
what = self.replace_what[num][1] or ""
with = self.replace_what[num][2] or ""
y_offset = self.replace_what[num][3] or 0
else
what = self.replace_what
with = self.replace_with or ""
y_offset = self.replace_offset or 0
end
pos.y = pos.y + y_offset
if #minetest.find_nodes_in_area(pos, pos, what) > 0 then
-- print ("replace node = ".. minetest.get_node(pos).name, pos.y)
minetest.set_node(pos, {name = with})
-- when cow/sheep eats grass, replace wool and milk
if self.gotten == true then
self.gotten = false
self.object:set_properties(self)
end
end
end
-- check if daytime and also if mob is docile during daylight hours
local day_docile = function(self)
if self.docile_by_day == false then
return false
elseif self.docile_by_day == true
and self.time_of_day > 0.2
and self.time_of_day < 0.8 then
return true
end
end
-- path finding and smart mob routine by rnd
local smart_mobs = function(self, s, p, dist, dtime)
local s1 = self.path.lastpos
-- is it becoming stuck?
if abs(s1.x - s.x) + abs(s1.z - s.z) < 1.5 then
self.path.stuck_timer = self.path.stuck_timer + dtime
else
self.path.stuck_timer = 0
end
self.path.lastpos = {x = s.x, y = s.y, z = s.z}
-- im stuck, search for path
if (self.path.stuck_timer > stuck_timeout and not self.path.following)
or (self.path.stuck_timer > stuck_path_timeout and self.path.following) then
self.path.stuck_timer = 0
-- lets try find a path, first take care of positions
-- since pathfinder is very sensitive
local sheight = self.collisionbox[5] - self.collisionbox[2]
-- round position to center of node to avoid stuck in walls
-- also adjust height for player models!
s.x = floor(s.x + 0.5)
s.y = floor(s.y + 0.5) - sheight
s.z = floor(s.z + 0.5)
local ssight, sground = minetest.line_of_sight(s, {
x = s.x, y = s.y - 4, z = s.z}, 1)
-- determine node above ground
if not ssight then
s.y = sground.y + 1
end
local p1 = self.attack:getpos()
p1.x = floor(p1.x + 0.5)
p1.y = floor(p1.y + 0.5)
p1.z = floor(p1.z + 0.5)
self.path.way = minetest.find_path(s, p1, 16, 2, 6, "Dijkstra")
-- attempt to unstick mob that is "daydreaming"
self.object:setpos({
x = s.x + 0.1 * (random() * 2 - 1),
y = s.y + 1,
z = s.z + 0.1 * (random() * 2 - 1)
})
self.state = ""
do_attack(self, self.attack)
-- no path found, try something else
if not self.path.way then
self.path.following = false
-- lets make way by digging/building if not accessible
if self.pathfinding == 2 then
-- is player higher than mob?
if s.y < p1.y then
-- build upwards
if not minetest.is_protected(s, "") then
local ndef1 = minetest.registered_nodes[self.standing_in]
if ndef1 and (ndef1.buildable_to or ndef1.groups.liquid) then
minetest.set_node(s, {name = "default:dirt"})
end
end
local sheight = math.ceil(self.collisionbox[5]) + 1
-- assume mob is 2 blocks high so it digs above its head
s.y = s.y + sheight
-- remove one block above to make room to jump
if not minetest.is_protected(s, "") then
local node1 = node_ok(s, "air").name
local ndef1 = minetest.registered_nodes[node1]
if node1 ~= "air"
and node1 ~= "ignore"
and ndef1
and not ndef1.groups.level
and not ndef1.groups.unbreakable then
minetest.set_node(s, {name = "air"})
minetest.add_item(s, ItemStack(node1))
end
end
s.y = s.y - sheight
self.object:setpos({x = s.x, y = s.y + 2, z = s.z})
else -- dig 2 blocks to make door toward player direction
local yaw1 = self.object:getyaw() + pi / 2
local p1 = {
x = s.x + cos(yaw1),
y = s.y,
z = s.z + sin(yaw1)
}
if not minetest.is_protected(p1, "") then
local node1 = node_ok(p1, "air").name
local ndef1 = minetest.registered_nodes[node1]
if node1 ~= "air"
and node1 ~= "ignore"
and ndef1
and not ndef1.groups.level
and not ndef1.groups.unbreakable then
minetest.add_item(p1, ItemStack(node1))
minetest.set_node(p1, {name = "air"})
end
p1.y = p1.y + 1
node1 = node_ok(p1, "air").name
ndef1 = minetest.registered_nodes[node1]
if node1 ~= "air"
and node1 ~= "ignore"
and ndef1
and not ndef1.groups.level
and not ndef1.groups.unbreakable then
minetest.add_item(p1, ItemStack(node1))
minetest.set_node(p1, {name = "air"})
end
end
end
end
-- will try again in 2 second
self.path.stuck_timer = stuck_timeout - 2
-- frustration! cant find the damn path :(
mob_sound(self, self.sounds.random)
else
-- yay i found path
mob_sound(self, self.sounds.attack)
set_velocity(self, self.walk_velocity)
-- follow path now that it has it
self.path.following = true
end
end
end
-- specific attacks
local specific_attack = function(list, what)
-- no list so attack default (player, animals etc.)
if list == nil then
return true
end
-- is found entity on list to attack?
for no = 1, #list do
if list[no] == what then
return true
end
end
return false
end
-- monster find someone to attack
local monster_attack = function(self)
if self.type ~= "monster"
or not damage_enabled
or self.state == "attack"
or day_docile(self) then
return
end
local s = self.object:getpos()
local p, sp, dist
local player, obj, min_player
local type, name = "", ""
local min_dist = self.view_range + 1
local objs = minetest.get_objects_inside_radius(s, self.view_range)
for n = 1, #objs do
if objs[n]:is_player() then
if mobs.invis[ objs[n]:get_player_name() ] then
type = ""
else
player = objs[n]
type = "player"
name = "player"
end
else
obj = objs[n]:get_luaentity()
if obj then
player = obj.object
type = obj.type
name = obj.name or ""
end
end
-- find specific mob to attack, failing that attack player/npc/animal
if specific_attack(self.specific_attack, name)
and (type == "player" or type == "npc"
or (type == "animal" and self.attack_animals == true)) then
s = self.object:getpos()
p = player:getpos()
sp = s
-- aim higher to make looking up hills more realistic
p.y = p.y + 1
sp.y = sp.y + 1
dist = get_distance(p, s)
if dist < self.view_range then
-- field of view check goes here
-- choose closest player to attack
if line_of_sight(self, sp, p, 2) == true
and dist < min_dist then
min_dist = dist
min_player = player
end
end
end
end
-- attack player
if min_player then
do_attack(self, min_player)
end
end
-- npc, find closest monster to attack
local npc_attack = function(self)
if self.type ~= "npc"
or not self.attacks_monsters
or self.state == "attack" then
return
end
local s = self.object:getpos()
local min_dist = self.view_range + 1
local obj, min_player = nil, nil
local objs = minetest.get_objects_inside_radius(s, self.view_range)
for n = 1, #objs do
obj = objs[n]:get_luaentity()
if obj and obj.type == "monster" then
local p = obj.object:getpos()
dist = get_distance(p, s)
if dist < min_dist then
min_dist = dist
min_player = obj.object
end
end
end
if min_player then
do_attack(self, min_player)
end
end
-- follow player if owner or holding item, if fish outta water then flop
local follow_flop = function(self)
-- find player to follow
if (self.follow ~= ""
or self.order == "follow")
and not self.following
and self.state ~= "attack"
and self.state ~= "runaway" then
local s = self.object:getpos()
local players = minetest.get_connected_players()
for n = 1, #players do
if get_distance(players[n]:getpos(), s) < self.view_range
and not mobs.invis[ players[n]:get_player_name() ] then
self.following = players[n]
break
end
end
end
if self.type == "npc"
and self.order == "follow"
and self.state ~= "attack"
and self.owner ~= "" then
-- npc stop following player if not owner
if self.following
and self.owner
and self.owner ~= self.following:get_player_name() then
self.following = nil
end
else
-- stop following player if not holding specific item
if self.following
and self.following:is_player()
and follow_holding(self, self.following) == false then
self.following = nil
end
end
-- follow that thing
if self.following then
local s = self.object:getpos()
local p
if self.following:is_player() then
p = self.following:getpos()
elseif self.following.object then
p = self.following.object:getpos()
end
if p then
local dist = get_distance(p, s)
-- dont follow if out of range
if dist > self.view_range then
self.following = nil
else
local vec = {
x = p.x - s.x,
z = p.z - s.z
}
local yaw = (atan(vec.z / vec.x) + pi / 2) - self.rotate
if p.x > s.x then yaw = yaw + pi end
yaw = set_yaw(self.object, yaw)
-- anyone but standing npc's can move along
if dist > self.reach
and self.order ~= "stand" then
set_velocity(self, self.walk_velocity)
if self.walk_chance ~= 0 then
set_animation(self, "walk")
end
else
set_velocity(self, 0)
set_animation(self, "stand")
end
return
end
end
end
-- swimmers flop when out of their element, and swim again when back in
if self.fly then
local s = self.object:getpos()
if not flight_check(self, s) then
self.state = "flop"
self.object:setvelocity({x = 0, y = -5, z = 0})
set_animation(self, "stand")
return
elseif self.state == "flop" then
self.state = "stand"
end
end
end
-- dogshoot attack switch and counter function
local dogswitch = function(self, dtime)
-- switch mode not activated
if not self.dogshoot_switch
or not dtime then
return 0
end
self.dogshoot_count = self.dogshoot_count + dtime
if (self.dogshoot_switch == 1
and self.dogshoot_count > self.dogshoot_count_max)
or (self.dogshoot_switch == 2
and self.dogshoot_count > self.dogshoot_count2_max) then
self.dogshoot_count = 0
if self.dogshoot_switch == 1 then
self.dogshoot_switch = 2
else
self.dogshoot_switch = 1
end
end
return self.dogshoot_switch
end
-- execute current state (stand, walk, run, attacks)
local do_states = function(self, dtime)
local yaw = 0
local rnd_v = math.random(5,10)/10
if (math.random(100) < 20) then
rnd_v = math.random(1,10)/10
end
if self.state == "stand" then
if random(1, 4) == 1 then
local lp = nil
local s = self.object:getpos()
local objs = minetest.get_objects_inside_radius(s, 3)
for n = 1, #objs do
if objs[n]:is_player() then
lp = objs[n]:getpos()
break
end
end
-- look at any players nearby, otherwise turn randomly
if lp then
local vec = {
x = lp.x - s.x,
z = lp.z - s.z
}
yaw = (atan(vec.z / vec.x) + pi / 2) - self.rotate
if lp.x > s.x then yaw = yaw + pi end
else
yaw = (random(0, 360) - 180) / 180 * pi
end
yaw = set_yaw(self.object, yaw)
end
set_velocity(self, 0)
set_animation(self, "stand")
-- npc's ordered to stand stay standing
if self.type ~= "npc"
or self.order ~= "stand" then
if self.walk_chance ~= 0
and random(1, 100) <= self.walk_chance
and is_at_cliff(self) == false then
set_velocity(self, self.walk_velocity*rnd_v)
self.state = "walk"
set_animation(self, "walk")
-- fly up/down randombly for flying mobs
if self.fly and random(1, 100) <= self.walk_chance then
local v = self.object:getvelocity()
local ud = random(-1, 2) / 9
self.object:setvelocity({x = v.x, y = ud, z = v.z})
end
end
end
elseif self.state == "walk" then
local s = self.object:getpos()
-- mars part:
lp = minetest.find_node_near(s, 5, "marsair:air_stable")
if lp then
lp.x = lp.x+math.random(-3,3)/10
lp.z = lp.z+math.random(-3,3)/10
local vec = {
x = lp.x - s.x,
z = lp.z - s.z
}
yaw = (atan(vec.z / vec.x) + pi / 2) - self.rotate
if lp.x > s.x then yaw = yaw + pi end
-- look towards land and jump/move in that direction
yaw = set_yaw(self.object, yaw)
do_jump(self)
set_velocity(self, self.walk_velocity*rnd_v)
end
--[[if random(1, 100) <= 30 then
set_velocity(self, 0)
yaw = random() * 2 * pi
yaw = set_yaw(self.object, yaw)
end]]--
-- stand for great fall in front
local temp_is_cliff = is_at_cliff(self)
if temp_is_cliff
or random(1, 100) <= 30 then
set_velocity(self, 0)
self.state = "stand"
set_animation(self, "stand")
else
set_velocity(self, self.walk_velocity*rnd_v)
if flight_check(self)
and self.animation
and self.animation.fly_start
and self.animation.fly_end then
set_animation(self, "fly")
else
set_animation(self, "walk")
end
end
-- runaway when punched
elseif self.state == "runaway" then
self.runaway_timer = self.runaway_timer + 1
-- stop after 5 seconds or when at cliff
if self.runaway_timer > 5
or is_at_cliff(self) then
self.runaway_timer = 0
set_velocity(self, 0)
self.state = "stand"
set_animation(self, "stand")
else
set_velocity(self, self.run_velocity)
set_animation(self, "walk")
end
-- attack routines (explode, dogfight, shoot, dogshoot)
elseif self.state == "attack" then
-- calculate distance from mob and enemy
local s = self.object:getpos()
local p = self.attack:getpos() or s
local dist = get_distance(p, s)
-- stop attacking if player or out of range
if dist > self.view_range
or not self.attack
or not self.attack:getpos()
or self.attack:get_hp() <= 0
or (self.attack:is_player() and mobs.invis[ self.attack:get_player_name() ]) then
--print(" ** stop attacking **", dist, self.view_range)
self.state = "stand"
set_velocity(self, 0)
set_animation(self, "stand")
self.attack = nil
self.v_start = false
self.timer = 0
self.blinktimer = 0
return
end
if self.attack_type == "explode" then
local vec = {
x = p.x - s.x,
z = p.z - s.z
}
yaw = (atan(vec.z / vec.x) + pi / 2) - self.rotate
if p.x > s.x then yaw = yaw + pi end
yaw = set_yaw(self.object, yaw)
if dist > self.reach then
if not self.v_start then
self.v_start = true
set_velocity(self, self.run_velocity)
self.timer = 0
self.blinktimer = 0
else
self.timer = 0
self.blinktimer = 0
set_velocity(self, self.run_velocity)
end
set_animation(self, "run")
else
set_velocity(self, 0)
set_animation(self, "punch")
self.timer = self.timer + dtime
self.blinktimer = (self.blinktimer or 0) + dtime
if self.blinktimer > 0.2 then
self.blinktimer = 0
if self.blinkstatus then
self.object:settexturemod("")
else
self.object:settexturemod("^[brighten")
end
self.blinkstatus = not self.blinkstatus
end
if self.timer > 3 then
local pos = self.object:getpos()
local radius = self.explosion_radius or 1
-- dont damage anything if area protected or next to water
if minetest.find_node_near(pos, 1, {"group:water"})
or minetest.is_protected(pos, "") then
mob_sound(self, self.sounds.explode)
self.object:remove()
effect(pos, 15, "tnt_smoke.png")
-- hurt player/mobs caught in blast area
entity_physics(pos, radius)
return
end
pos.y = pos.y - 1
mobs:explosion(pos, radius, 1, 1, self.sounds.explode)
self.object:remove()
entity_physics(pos, radius)
return
end
end
elseif self.attack_type == "dogfight"
or (self.attack_type == "dogshoot" and dogswitch(self, dtime) == 2)
or (self.attack_type == "dogshoot" and dist <= self.reach and dogswitch(self) == 0) then
if self.fly
and dist > self.reach then
local p1 = s
local me_y = floor(p1.y)
local p2 = p
local p_y = floor(p2.y + 1)
local v = self.object:getvelocity()
if flight_check(self, s) then
if me_y < p_y then
self.object:setvelocity({
x = v.x,
y = 1 * self.walk_velocity,
z = v.z
})
elseif me_y > p_y then
self.object:setvelocity({
x = v.x,
y = -1 * self.walk_velocity,
z = v.z
})
end
else
if me_y < p_y then
self.object:setvelocity({
x = v.x,
y = 0.01,
z = v.z
})
elseif me_y > p_y then
self.object:setvelocity({
x = v.x,
y = -0.01,
z = v.z
})
end
end
end
-- rnd: new movement direction
if self.path.following
and self.path.way
and self.attack_type ~= "dogshoot" then
-- no paths longer than 50
if #self.path.way > 50
or dist < self.reach then
self.path.following = false
return
end
local p1 = self.path.way[1]
if not p1 then
self.path.following = false
return
end
if abs(p1.x-s.x) + abs(p1.z - s.z) < 0.6 then
-- reached waypoint, remove it from queue
table.remove(self.path.way, 1)
end
-- set new temporary target
p = {x = p1.x, y = p1.y, z = p1.z}
end
local vec = {
x = p.x - s.x,
z = p.z - s.z
}
yaw = (atan(vec.z / vec.x) + pi / 2) - self.rotate
if p.x > s.x then yaw = yaw + pi end
yaw = set_yaw(self.object, yaw)
-- move towards enemy if beyond mob reach
if dist > self.reach then
-- path finding by rnd
if self.pathfinding -- only if mob has pathfinding enabled
and enable_pathfinding then
smart_mobs(self, s, p, dist, dtime)
end
if is_at_cliff(self) then
set_velocity(self, 0)
set_animation(self, "stand")
else
if self.path.stuck then
set_velocity(self, self.walk_velocity)
else
set_velocity(self, self.run_velocity)
end
set_animation(self, "run")
end
else -- rnd: if inside reach range
self.path.stuck = false
self.path.stuck_timer = 0
self.path.following = false -- not stuck anymore
set_velocity(self, 0)
if not self.custom_attack then
if self.timer > 1 then
self.timer = 0
if self.double_melee_attack
and random(1, 2) == 1 then
set_animation(self, "punch2")
else
set_animation(self, "punch")
end
local p2 = p
local s2 = s
p2.y = p2.y + .5
s2.y = s2.y + .5
if line_of_sight(self, p2, s2) == true then
-- play attack sound
mob_sound(self, self.sounds.attack)
-- punch player (or what player is attached to)
local attached = self.attack:get_attach()
if attached then
self.attack = attached
end
self.attack:punch(self.object, 1.0, {
full_punch_interval = 1.0,
damage_groups = {fleshy = self.damage}
}, nil)
end
end
else -- call custom attack every second
if self.custom_attack
and self.timer > 1 then
self.timer = 0
self.custom_attack(self, p)
end
end
end
elseif self.attack_type == "shoot"
or (self.attack_type == "dogshoot" and dogswitch(self, dtime) == 1)
or (self.attack_type == "dogshoot" and dist > self.reach and dogswitch(self) == 0) then
p.y = p.y - .5
s.y = s.y + .5
local dist = get_distance(p, s)
local vec = {
x = p.x - s.x,
y = p.y - s.y,
z = p.z - s.z
}
yaw = (atan(vec.z / vec.x) + pi / 2) - self.rotate
if p.x > s.x then yaw = yaw + pi end
yaw = set_yaw(self.object, yaw)
set_velocity(self, 0)
if self.shoot_interval
and self.timer > self.shoot_interval
and random(1, 100) <= 60 then
self.timer = 0
set_animation(self, "shoot")
-- play shoot attack sound
mob_sound(self, self.sounds.shoot_attack)
local p = self.object:getpos()
p.y = p.y + (self.collisionbox[2] + self.collisionbox[5]) / 2
local obj = minetest.add_entity(p, self.arrow)
local ent = obj:get_luaentity()
if ent then
local amount = (vec.x * vec.x + vec.y * vec.y + vec.z * vec.z) ^ 0.5
local v = ent.velocity or 1 -- or set to default
ent.switch = 1
ent.owner_id = tostring(self.object) -- add unique owner id to arrow
-- offset makes shoot aim accurate
vec.y = vec.y + self.shoot_offset
vec.x = vec.x * (v / amount)
vec.y = vec.y * (v / amount)
vec.z = vec.z * (v / amount)
obj:setvelocity(vec)
else
obj:remove() -- arrow entity does not exist
end
end
end
end
end
-- falling and fall damage
local falling = function(self, pos)
if self.fly then
return
end
-- floating in water (or falling)
local v = self.object:getvelocity()
-- going up then apply gravity
if v.y > 0.1 then
self.object:setacceleration({
x = 0,
y = self.fall_speed,
z = 0
})
end
-- in water then float up
-- if minetest.registered_nodes[node_ok(pos).name].groups.liquid then
if minetest.registered_nodes[node_ok(pos).name].groups.water then
if self.floats == 1 then
self.object:setacceleration({
x = 0,
y = -self.fall_speed / (max(1, v.y) ^ 2),
z = 0
})
end
else
-- fall downwards
self.object:setacceleration({
x = 0,
y = self.fall_speed,
z = 0
})
-- fall damage
if self.fall_damage == 1
and self.object:getvelocity().y == 0 then
local d = (self.old_y or 0) - self.object:getpos().y
if d > 5 then
self.health = self.health - floor(d - 5)
effect(pos, 5, "tnt_smoke.png", 1, 2, 2, nil)
if check_for_death(self, "fall") then
return
end
end
self.old_y = self.object:getpos().y
end
end
end
-- deal damage and effects when mob punched
local mob_punch = function(self, hitter, tflp, tool_capabilities, dir)
-- mob health check
if self.health <= 0 then
return
end
-- error checking when mod profiling is enabled
if not tool_capabilities then
print (S("[MOBS] mod profiling enabled, damage not enabled"))
return
end
-- is mob protected?
if self.protected and hitter:is_player()
and minetest.is_protected(self.object:getpos(), hitter:get_player_name()) then
minetest.chat_send_player(hitter:get_player_name(), "Mob has been protected!")
return
end
-- weapon wear
local weapon = hitter:get_wielded_item()
local punch_interval = 1.4
-- calculate mob damage
local damage = 0
local armor = self.object:get_armor_groups() or {}
local tmp
-- quick error check incase it ends up 0 (serialize.h check test)
if tflp == 0 then
tflp = 0.2
end
for group,_ in pairs( (tool_capabilities.damage_groups or {}) ) do
tmp = tflp / (tool_capabilities.full_punch_interval or 1.4)
if tmp < 0 then
tmp = 0.0
elseif tmp > 1 then
tmp = 1.0
end
damage = damage + (tool_capabilities.damage_groups[group] or 0)
* tmp * ((armor[group] or 0) / 100.0)
end
-- check for tool immunity or special damage
for n = 1, #self.immune_to do
if self.immune_to[n][1] == weapon:get_name() then
damage = self.immune_to[n][2] or 0
break
end
end
-- healing
if damage <= -1 then
self.health = self.health - floor(damage)
return
end
-- print ("Mob Damage is", damage)
-- add weapon wear
if tool_capabilities then
punch_interval = tool_capabilities.full_punch_interval or 1.4
end
if weapon:get_definition()
and weapon:get_definition().tool_capabilities then
weapon:add_wear(floor((punch_interval / 75) * 9000))
hitter:set_wielded_item(weapon)
end
-- only play hit sound and show blood effects if damage is 1 or over
if damage >= 1 then
-- weapon sounds
if weapon:get_definition().sounds ~= nil then
local s = random(0, #weapon:get_definition().sounds)
minetest.sound_play(weapon:get_definition().sounds[s], {
object = hitter,
max_hear_distance = 8
})
else
minetest.sound_play("default_punch", {
object = hitter,
max_hear_distance = 5
})
end
-- blood_particles
if self.blood_amount > 0
and not disable_blood then
local pos = self.object:getpos()
pos.y = pos.y + (-self.collisionbox[2] + self.collisionbox[5]) * .5
effect(pos, self.blood_amount, self.blood_texture, nil, nil, 1, nil)
end
-- do damage
self.health = self.health - floor(damage)
-- exit here if dead, special item check
if weapon:get_name() == "mobs:pick_lava" then
if check_for_death(self, "lava") then
return
end
else
if check_for_death(self, "hit") then
return
end
end
--[[ add healthy afterglow when hit (can cause hit lag with larger textures)
core.after(0.1, function()
self.object:settexturemod("^[colorize:#c9900070")
core.after(0.3, function()
self.object:settexturemod("")
end)
end) ]]
-- knock back effect (only on full punch)
if self.knock_back > 0
and tflp >= punch_interval then
local v = self.object:getvelocity()
local r = 1.4 - min(punch_interval, 1.4)
local kb = r * 5
local up = 2
-- if already in air then dont go up anymore when hit
if v.y > 0
or self.fly then
up = 0
end
-- direction error check
dir = dir or {x = 0, y = 0, z = 0}
self.object:setvelocity({
x = dir.x * kb,
y = up,
z = dir.z * kb
})
self.pause_timer = r
end
end -- END if damage
-- if skittish then run away
if self.runaway == true then
local lp = hitter:getpos()
local s = self.object:getpos()
local vec = {
x = lp.x - s.x,
y = lp.y - s.y,
z = lp.z - s.z
}
local yaw = atan(vec.z / vec.x) + 3 * pi / 2
if lp.x > s.x then
yaw = yaw + pi
end
yaw = set_yaw(self.object, yaw)
self.state = "runaway"
self.runaway_timer = 0
self.following = nil
end
local name = hitter:get_player_name() or ""
-- attack puncher and call other mobs for help
if self.passive == false
and self.state ~= "flop"
and self.child == false
and hitter:get_player_name() ~= self.owner
and not mobs.invis[ name ] then
-- attack whoever punched mob
self.state = ""
do_attack(self, hitter)
-- alert others to the attack
local objs = minetest.get_objects_inside_radius(hitter:getpos(), self.view_range)
local obj = nil
for n = 1, #objs do
obj = objs[n]:get_luaentity()
if obj then
-- only alert members of same mob
if obj.group_attack == true
and obj.state ~= "attack"
and obj.owner ~= name
and obj.name == self.name then
do_attack(obj, hitter)
end
-- have owned mobs attack player threat
if obj.owner == name and obj.owner_loyal then
do_attack(obj, self.object)
end
end
end
end
end
-- get entity staticdata
local mob_staticdata = function(self)
-- remove mob when out of range unless tamed
if remove_far
and self.remove_ok
and not self.tamed
and self.lifetimer < 20000 then
--print ("REMOVED " .. self.name)
self.object:remove()
return ""-- nil
end
self.remove_ok = true
self.attack = nil
self.following = nil
self.state = "stand"
-- used to rotate older mobs
if self.drawtype
and self.drawtype == "side" then
self.rotate = math.rad(90)
end
local tmp = {}
for _,stat in pairs(self) do
local t = type(stat)
if t ~= "function"
and t ~= "nil"
and t ~= "userdata" then
tmp[_] = self[_]
end
end
--print('===== '..self.name..'\n'.. dump(tmp)..'\n=====\n')
return minetest.serialize(tmp)
end
-- activate mob and reload settings
local mob_activate = function(self, staticdata, def)
-- remove monsters in peaceful mode, or when no data
if (self.type == "monster" and peaceful_only) then
self.object:remove()
return
end
-- load entity variables
local tmp = minetest.deserialize(staticdata)
if tmp then
for _,stat in pairs(tmp) do
self[_] = stat
end
end
-- select random texture, set model and size
if not self.base_texture then
-- compatiblity with old simple mobs textures
if type(def.textures[1]) == "string" then
def.textures = {def.textures}
end
self.base_texture = def.textures[random(1, #def.textures)]
self.base_mesh = def.mesh
self.base_size = self.visual_size
self.base_colbox = self.collisionbox
end
-- set texture, model and size
local textures = self.base_texture
local mesh = self.base_mesh
local vis_size = self.base_size
local colbox = self.base_colbox
-- specific texture if gotten
if self.gotten == true
and def.gotten_texture then
textures = def.gotten_texture
end
-- specific mesh if gotten
if self.gotten == true
and def.gotten_mesh then
mesh = def.gotten_mesh
end
-- set child objects to half size
if self.child == true then
vis_size = {
x = self.base_size.x * .5,
y = self.base_size.y * .5,
}
if def.child_texture then
textures = def.child_texture[1]
end
colbox = {
self.base_colbox[1] * .5,
self.base_colbox[2] * .5,
self.base_colbox[3] * .5,
self.base_colbox[4] * .5,
self.base_colbox[5] * .5,
self.base_colbox[6] * .5
}
end
if self.health == 0 then
self.health = random (self.hp_min, self.hp_max)
end
-- rnd: pathfinding init
self.path = {}
self.path.way = {} -- path to follow, table of positions
self.path.lastpos = {x = 0, y = 0, z = 0}
self.path.stuck = false
self.path.following = false -- currently following path?
self.path.stuck_timer = 0 -- if stuck for too long search for path
-- end init
self.object:set_armor_groups({immortal = 1, fleshy = self.armor})
self.old_y = self.object:getpos().y
self.old_health = self.health
self.sounds.distance = self.sounds.distance or 10
self.textures = textures
self.mesh = mesh
self.collisionbox = colbox
self.visual_size = vis_size
self.standing_in = ""
-- set anything changed above
self.object:set_properties(self)
set_yaw(self.object, (random(0, 360) - 180) / 180 * pi)
update_tag(self)
end
-- main mob function
local mob_step = function(self, dtime)
local pos = self.object:getpos()
local yaw = 0
-- when lifetimer expires remove mob (except npc and tamed)
if self.type ~= "npc"
and not self.tamed
and self.state ~= "attack"
and remove_far ~= true
and self.lifetimer < 20000 then
self.lifetimer = self.lifetimer - dtime
if self.lifetimer <= 0 then
-- only despawn away from player
local objs = minetest.get_objects_inside_radius(pos, 15)
for n = 1, #objs do
if objs[n]:is_player() then
self.lifetimer = 20
return
end
end
-- minetest.log("action",
-- S("lifetimer expired, removed @1", self.name))
effect(pos, 15, "tnt_smoke.png", 2, 4, 2, 0)
self.object:remove()
return
end
end
falling(self, pos)
-- knockback timer
if self.pause_timer > 0 then
self.pause_timer = self.pause_timer - dtime
if self.pause_timer < 1 then
self.pause_timer = 0
end
return
end
-- run custom function (defined in mob lua file)
if self.do_custom then
-- when false skip going any further
if self.do_custom(self, dtime) == false then
return
end
end
-- attack timer
self.timer = self.timer + dtime
if self.state ~= "attack" then
if self.timer < 1 then
return
end
self.timer = 0
end
-- never go over 100
if self.timer > 100 then
self.timer = 1
end
-- node replace check (cow eats grass etc.)
replace(self, pos)
-- mob plays random sound at times
if random(1, 100) == 1 then
mob_sound(self, self.sounds.random)
end
-- environmental damage timer (every 1 second)
self.env_damage_timer = self.env_damage_timer + dtime
if (self.state == "attack" and self.env_damage_timer > 1)
or self.state ~= "attack" then
self.env_damage_timer = 0
do_env_damage(self)
end
monster_attack(self)
npc_attack(self)
breed(self)
follow_flop(self)
do_states(self, dtime)
do_jump(self)
end
-- default function when mobs are blown up with TNT
local do_tnt = function(obj, damage)
--print ("----- Damage", damage)
obj.object:punch(obj.object, 1.0, {
full_punch_interval = 1.0,
damage_groups = {fleshy = damage},
}, nil)
return false, true, {}
end
mobs.spawning_mobs = {}
-- register mob entity
function mobs:register_mob(name, def)
mobs.spawning_mobs[name] = true
minetest.register_entity(name, {
stepheight = def.stepheight or 1.1, -- was 0.6
name = name,
type = def.type,
attack_type = def.attack_type,
fly = def.fly,
fly_in = def.fly_in or "air",
owner = def.owner or "",
order = def.order or "",
on_die = def.on_die,
do_custom = def.do_custom,
jump_height = def.jump_height or 4, -- was 6
drawtype = def.drawtype, -- DEPRECATED, use rotate instead
rotate = math.rad(def.rotate or 0), -- 0=front, 90=side, 180=back, 270=side2
lifetimer = def.lifetimer or 180, -- 3 minutes
hp_min = max(1, (def.hp_min or 5) * difficulty),
hp_max = max(1, (def.hp_max or 10) * difficulty),
physical = true,
collisionbox = def.collisionbox,
visual = def.visual,
visual_size = def.visual_size or {x = 1, y = 1},
mesh = def.mesh,
makes_footstep_sound = def.makes_footstep_sound or false,
view_range = def.view_range or 5,
walk_velocity = def.walk_velocity or 1,
run_velocity = def.run_velocity or 2,
damage = max(1, (def.damage or 0) * difficulty),
light_damage = def.light_damage or 0,
water_damage = def.water_damage or 0,
lava_damage = def.lava_damage or 0,
no_air_damage= def.no_air_damage or false,
fall_damage = def.fall_damage or 1,
fall_speed = def.fall_speed or -10, -- must be lower than -2 (default: -10)
drops = def.drops or {},
armor = def.armor or 100,
on_rightclick = def.on_rightclick,
arrow = def.arrow,
shoot_interval = def.shoot_interval,
sounds = def.sounds or {},
animation = def.animation,
follow = def.follow,
jump = def.jump ~= false,
walk_chance = def.walk_chance or 50,
attacks_monsters = def.attacks_monsters or false,
group_attack = def.group_attack or false,
passive = def.passive or false,
recovery_time = def.recovery_time or 0.5,
knock_back = def.knock_back or 3,
blood_amount = def.blood_amount or 5,
blood_texture = def.blood_texture or "mobs_blood.png",
shoot_offset = def.shoot_offset or 0,
floats = def.floats or 1, -- floats in water by default
replace_rate = def.replace_rate,
replace_what = def.replace_what,
replace_with = def.replace_with,
replace_offset = def.replace_offset or 0,
timer = 0,
env_damage_timer = 0, -- only used when state = "attack"
tamed = false,
pause_timer = 0,
horny = false,
hornytimer = 0,
child = false,
gotten = false,
health = 0,
reach = def.reach or 3,
htimer = 0,
texture_list = def.textures,
child_texture = def.child_texture,
docile_by_day = def.docile_by_day or false,
time_of_day = 0.5,
fear_height = def.fear_height or 0,
runaway = def.runaway,
runaway_timer = 0,
pathfinding = def.pathfinding,
immune_to = def.immune_to or {},
explosion_radius = def.explosion_radius,
custom_attack = def.custom_attack,
double_melee_attack = def.double_melee_attack,
dogshoot_switch = def.dogshoot_switch,
dogshoot_count = 0,
dogshoot_count_max = def.dogshoot_count_max or 5,
dogshoot_count2_max = def.dogshoot_count2_max or (def.dogshoot_count_max or 5),
attack_animals = def.attack_animals or false,
specific_attack = def.specific_attack,
owner_loyal = def.owner_loyal,
on_blast = def.on_blast or do_tnt,
on_step = mob_step,
on_punch = mob_punch,
on_activate = function(self, staticdata)
return mob_activate(self, staticdata, def)
end,
get_staticdata = function(self)
return mob_staticdata(self)
end,
})
end -- END mobs:register_mob function
-- count how many mobs of one type are inside an area
local count_mobs = function(pos, type)
local num_type = 0
local num_total = 0
local objs = minetest.get_objects_inside_radius(pos, aoc_range)
for n = 1, #objs do
if not objs[n]:is_player() then
local obj = objs[n]:get_luaentity()
-- count mob type and add to total also
if obj and obj.name and obj.name == type then
num_type = num_type + 1
num_total = num_total + 1
-- add to total mobs
elseif obj and obj.name and obj.health ~= nil then
num_total = num_total + 1
end
end
end
return num_type, num_total
end
-- global functions
function mobs:spawn_specific(name, nodes, neighbors, min_light, max_light,
interval, chance, aoc, min_height, max_height, day_toggle, on_spawn)
-- chance/spawn number override in minetest.conf for registered mob
local numbers = minetest.settings:get(name)
if numbers then
numbers = numbers:split(",")
chance = tonumber(numbers[1]) or chance
aoc = tonumber(numbers[2]) or aoc
if chance == 0 then
print(S("[Mobs Redo] @1 has spawning disabled", name))
return
end
print (S("[Mobs Redo] Chance setting for @1 changed to @2", name, chance)
.. " (total: " .. aoc .. ")")
end
minetest.register_abm({
label = name .. " spawning",
nodenames = nodes,
neighbors = neighbors,
interval = interval,
chance = chance,
catch_up = false,
action = function(pos, node, active_object_count, active_object_count_wider)
-- is mob actually registered?
if not mobs.spawning_mobs[name] then
--print ("--- mob doesn't exist", name)
return
end
-- do not spawn if too many of same mob in area
if active_object_count_wider >= max_per_block
or count_mobs(pos, name) >= aoc then
--print ("--- too many entities", name, aoc, active_object_count_wider)
return
end
-- if toggle set to nil then ignore day/night check
if day_toggle ~= nil then
local tod = (minetest.get_timeofday() or 0) * 24000
if tod > 4500 and tod < 19500 then
-- daylight, but mob wants night
if day_toggle == false then
--print ("--- mob needs night", name)
return
end
else
-- night time but mob wants day
if day_toggle == true then
--print ("--- mob needs day", name)
return
end
end
end
-- spawn above node
pos.y = pos.y + 1
-- only spawn away from player
local objs = minetest.get_objects_inside_radius(pos, 10)
for n = 1, #objs do
if objs[n]:is_player() then
--print ("--- player too close", name)
return
end
end
-- mobs cannot spawn in protected areas when enabled
if spawn_protected == 1
and minetest.is_protected(pos, "") then
--print ("--- inside protected area", name)
return
end
-- are we spawning within height limits?
if pos.y > max_height
or pos.y < min_height then
--print ("--- height limits not met", name, pos.y)
return
end
-- are light levels ok?
local light = minetest.get_node_light(pos)
if not light
or light > max_light
or light < min_light then
--print ("--- light limits not met", name, light)
return
end
-- are we spawning inside solid nodes?
if minetest.registered_nodes[node_ok(pos).name].walkable == true then
--print ("--- feet in block", name, node_ok(pos).name)
return
end
pos.y = pos.y + 1
if minetest.registered_nodes[node_ok(pos).name].walkable == true then
--print ("--- head in block", name, node_ok(pos).name)
return
end
-- spawn mob half block higher than ground
pos.y = pos.y - 0.5
local mob = minetest.add_entity(pos, name)
if mob and mob:get_luaentity() then
-- print ("[mobs] Spawned " .. name .. " at "
-- .. minetest.pos_to_string(pos) .. " on "
-- .. node.name .. " near " .. neighbors[1])
if on_spawn and not on_spawn(mob, pos) then
return
end
else
print (S("[mobs] @1 failed to spawn at @2",
name, minetest.pos_to_string(pos)))
end
end
})
end
-- compatibility with older mob registration
function mobs:register_spawn(name, nodes, max_light, min_light, chance, active_object_count, max_height, day_toggle)
mobs:spawn_specific(name, nodes, {"air"}, min_light, max_light, 30,
chance, active_object_count, -31000, max_height, day_toggle)
end
-- MarkBu's spawn function
function mobs:spawn(def)
local name = def.name
local nodes = def.nodes or {"group:soil", "group:stone"}
local neighbors = def.neighbors or {"air"}
local min_light = def.min_light or 0
local max_light = def.max_light or 15
local interval = def.interval or 30
local chance = def.chance or 5000
local active_object_count = def.active_object_count or 1
local min_height = def.min_height or -31000
local max_height = def.max_height or 31000
local day_toggle = def.day_toggle
local on_spawn = def.on_spawn
mobs:spawn_specific(name, nodes, neighbors, min_light, max_light, interval,
chance, active_object_count, min_height, max_height, day_toggle, on_spawn)
end
-- set content id's
local c_air = minetest.get_content_id("air")
local c_ignore = minetest.get_content_id("ignore")
local c_obsidian = minetest.get_content_id("default:obsidian")
local c_brick = minetest.get_content_id("default:obsidianbrick")
local c_chest = minetest.get_content_id("default:chest_locked")
local c_fire = minetest.get_content_id("fire:basic_flame")
-- explosion (cannot break protected or unbreakable nodes)
function mobs:explosion(pos, radius, fire, smoke, sound)
radius = radius or 0
fire = fire or 0
smoke = smoke or 0
-- if area protected or near map limits then no blast damage
if minetest.is_protected(pos, "")
or not within_limits(pos, radius) then
return
end
-- explosion sound
if sound
and sound ~= "" then
minetest.sound_play(sound, {
pos = pos,
gain = 1.0,
max_hear_distance = 16
})
end
pos = vector.round(pos) -- voxelmanip doesn't work properly unless pos is rounded ?!?!
local vm = VoxelManip()
local minp, maxp = vm:read_from_map(vector.subtract(pos, radius), vector.add(pos, radius))
local a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp})
local data = vm:get_data()
local p = {}
local pr = PseudoRandom(os.time())
for z = -radius, radius do
for y = -radius, radius do
local vi = a:index(pos.x + (-radius), pos.y + y, pos.z + z)
for x = -radius, radius do
p.x = pos.x + x
p.y = pos.y + y
p.z = pos.z + z
if (x * x) + (y * y) + (z * z) <= (radius * radius) + pr:next(-radius, radius)
and data[vi] ~= c_air
and data[vi] ~= c_ignore
and data[vi] ~= c_obsidian
and data[vi] ~= c_brick
and data[vi] ~= c_chest
and data[vi] ~= c_fire then
local n = node_ok(p).name
local on_blast = minetest.registered_nodes[n].on_blast
if on_blast then
return on_blast(p)
elseif minetest.registered_nodes[n].groups.unbreakable == 1 then
-- do nothing
else
-- after effects
if fire > 0
and (minetest.registered_nodes[n].groups.flammable
or random(1, 100) <= 30) then
minetest.set_node(p, {name = "fire:basic_flame"})
else
minetest.set_node(p, {name = "air"})
if smoke > 0 then
effect(p, 2, "tnt_smoke.png")
end
end
end
end
vi = vi + 1
end
end
end
end
-- register arrow for shoot attack
function mobs:register_arrow(name, def)
if not name or not def then return end -- errorcheck
minetest.register_entity(name, {
physical = false,
visual = def.visual,
visual_size = def.visual_size,
textures = def.textures,
velocity = def.velocity,
hit_player = def.hit_player,
hit_node = def.hit_node,
hit_mob = def.hit_mob,
drop = def.drop or false, -- drops arrow as registered item when true
collisionbox = {0, 0, 0, 0, 0, 0}, -- remove box around arrows
timer = 0,
switch = 0,
owner_id = def.owner_id,
rotate = def.rotate,
automatic_face_movement_dir = def.rotate
and (def.rotate - (pi / 180)) or false,
on_activate = def.on_activate or nil,
on_step = def.on_step or function(self, dtime)
self.timer = self.timer + 1
local pos = self.object:getpos()
if self.switch == 0
or self.timer > 150
or not within_limits(pos, 0) then
self.object:remove() ; -- print ("removed arrow")
return
end
-- does arrow have a tail (fireball)
if def.tail
and def.tail == 1
and def.tail_texture then
minetest.add_particle({
pos = pos,
velocity = {x = 0, y = 0, z = 0},
acceleration = {x = 0, y = 0, z = 0},
expirationtime = def.expire or 0.25,
collisiondetection = false,
texture = def.tail_texture,
size = def.tail_size or 5,
glow = def.glow or 0,
})
end
if self.hit_node then
local node = node_ok(pos).name
if minetest.registered_nodes[node].walkable then
self.hit_node(self, pos, node)
if self.drop == true then
pos.y = pos.y + 1
self.lastpos = (self.lastpos or pos)
minetest.add_item(self.lastpos, self.object:get_luaentity().name)
end
self.object:remove() ; -- print ("hit node")
return
end
end
if self.hit_player or self.hit_mob then
for _,player in pairs(minetest.get_objects_inside_radius(pos, 1.0)) do
if self.hit_player
and player:is_player() then
self.hit_player(self, player)
self.object:remove() ; -- print ("hit player")
return
end
local entity = player:get_luaentity()
and player:get_luaentity().name or ""
if self.hit_mob
and tostring(player) ~= self.owner_id
and entity ~= self.object:get_luaentity().name
and entity ~= "__builtin:item"
and entity ~= "__builtin:falling_node"
and entity ~= "gauges:hp_bar"
and entity ~= "signs:text"
and entity ~= "itemframes:item" then
self.hit_mob(self, player)
self.object:remove() ; --print ("hit mob")
return
end
end
end
self.lastpos = pos
end
})
end
-- register spawn eggs
function mobs:register_egg(mob, desc, background, addegg, no_creative)
local grp = {}
-- do NOT add this egg to creative inventory (e.g. dungeon master)
if creative and no_creative == true then
grp = {not_in_creative_inventory = 1}
end
local invimg = background
if addegg == 1 then
invimg = "mobs_chicken_egg.png^(" .. invimg ..
"^[mask:mobs_chicken_egg_overlay.png)"
end
-- register new spawn egg containing mob information
minetest.register_craftitem(mob .. "_set", {
description = desc .. " (Tamed)",
inventory_image = invimg,
groups = {not_in_creative_inventory = 1},
stack_max = 1,
on_place = function(itemstack, placer, pointed_thing)
local pos = pointed_thing.above
-- am I clicking on something with existing on_rightclick function?
local under = minetest.get_node(pointed_thing.under)
local def = minetest.registered_nodes[under.name]
if def and def.on_rightclick then
return def.on_rightclick(pointed_thing.under, under, placer, itemstack)
end
if pos
and within_limits(pos, 0)
and not minetest.is_protected(pos, placer:get_player_name()) then
pos.y = pos.y + 1
local data = itemstack:get_metadata()
local mob = minetest.add_entity(pos, mob, data)
local ent = mob:get_luaentity()
if not ent then
mob:remove()
return
end
if ent.type ~= "monster" then
-- set owner and tame if not monster
ent.owner = placer:get_player_name()
ent.tamed = true
end
-- since mob is unique we remove egg once spawned
itemstack:take_item()
end
return itemstack
end,
})
-- register old stackable mob egg
minetest.register_craftitem(mob, {
description = desc,
inventory_image = invimg,
groups = grp,
on_place = function(itemstack, placer, pointed_thing)
local pos = pointed_thing.above
-- am I clicking on something with existing on_rightclick function?
local under = minetest.get_node(pointed_thing.under)
local def = minetest.registered_nodes[under.name]
if def and def.on_rightclick then
return def.on_rightclick(pointed_thing.under, under, placer, itemstack)
end
if pos
and within_limits(pos, 0)
and not minetest.is_protected(pos, placer:get_player_name()) then
pos.y = pos.y + 1
local mob = minetest.add_entity(pos, mob)
local ent = mob:get_luaentity()
if not ent then
mob:remove()
return
end
if ent.type ~= "monster" then
-- set owner and tame if not monster
ent.owner = placer:get_player_name()
ent.tamed = true
end
-- if not in creative then take item
if not creative then
itemstack:take_item()
end
end
return itemstack
end,
})
end
-- capture critter (thanks to blert2112 for idea)
function mobs:capture_mob(self, clicker, chance_hand, chance_net, chance_lasso, force_take, replacewith)
if self.child
or not clicker:is_player()
or not clicker:get_inventory() then
return false
end
-- get name of clicked mob
local mobname = self.name
-- if not nil change what will be added to inventory
if replacewith then
mobname = replacewith
end
local name = clicker:get_player_name()
local tool = clicker:get_wielded_item()
-- are we using hand, net or lasso to pick up mob?
if tool:get_name() ~= ""
and tool:get_name() ~= "mobs:net"
and tool:get_name() ~= "mobs:magic_lasso" then
return false
end
-- is mob tamed?
if self.tamed == false
and force_take == false then
minetest.chat_send_player(name, S("Not tamed!"))
return true -- false
end
-- cannot pick up if not owner
if self.owner ~= name
and force_take == false then
minetest.chat_send_player(name, S("@1 is owner!", self.owner))
return true -- false
end
if clicker:get_inventory():room_for_item("main", mobname) then
-- was mob clicked with hand, net, or lasso?
local chance = 0
if tool:get_name() == "" then
chance = chance_hand
elseif tool:get_name() == "mobs:net" then
chance = chance_net
tool:add_wear(4000) -- 17 uses
clicker:set_wielded_item(tool)
elseif tool:get_name() == "mobs:magic_lasso" then
chance = chance_lasso
tool:add_wear(650) -- 100 uses
clicker:set_wielded_item(tool)
end
-- calculate chance.. add to inventory if successful?
if chance > 0 and random(1, 100) <= chance then
-- default mob egg
local new_stack = ItemStack(mobname)
-- add special mob egg with all mob information
-- unless 'replacewith' contains new item to use
if not replacewith then
new_stack = ItemStack(mobname .. "_set")
local tmp = {}
for _,stat in pairs(self) do
local t = type(stat)
if t ~= "function"
and t ~= "nil"
and t ~= "userdata" then
tmp[_] = self[_]
end
end
local data_str = minetest.serialize(tmp)
new_stack:set_metadata(data_str)
end
local inv = clicker:get_inventory()
if inv:room_for_item("main", new_stack) then
inv:add_item("main", new_stack)
else
minetest.add_item(clicker:getpos(), new_stack)
end
self.object:remove()
else
minetest.chat_send_player(name, S("Missed!"))
end
end
return true
end
-- protect tamed mob with rune item
function mobs:protect(self, clicker)
local name = clicker:get_player_name()
local tool = clicker:get_wielded_item()
if tool:get_name() ~= "mobs:protector" then
return false
end
if self.tamed == false then
minetest.chat_send_player(name, S("Not tamed!"))
return true -- false
end
if self.protected == true then
minetest.chat_send_player(name, S("Already protected!"))
return true -- false
end
tool:take_item() -- take 1 protection rune
clicker:set_wielded_item(tool)
self.protected = true
minetest.chat_send_player(name, S("Protected!"))
return true
end
local mob_obj = {}
local mob_sta = {}
-- feeding, taming and breeding (thanks blert2112)
function mobs:feed_tame(self, clicker, feed_count, breed, tame)
if not self.follow then
return false
end
-- can eat/tame with item in hand
if follow_holding(self, clicker) then
-- if not in creative then take item
if not creative then
local item = clicker:get_wielded_item()
item:take_item()
clicker:set_wielded_item(item)
end
-- increase health
self.health = self.health + 4
if self.health >= self.hp_max then
self.health = self.hp_max
if self.htimer < 1 then
minetest.chat_send_player(clicker:get_player_name(),
S("@1 at full health (@2)",
self.name:split(":")[2], tostring(self.health)))
self.htimer = 5
end
end
self.object:set_hp(self.health)
update_tag(self)
-- make children grow quicker
if self.child == true then
self.hornytimer = self.hornytimer + 20
return true
end
-- feed and tame
self.food = (self.food or 0) + 1
if self.food >= feed_count then
self.food = 0
if breed and self.hornytimer == 0 then
self.horny = true
end
self.gotten = false
if tame then
if self.tamed == false then
minetest.chat_send_player(clicker:get_player_name(),
S("@1 has been tamed!",
self.name:split(":")[2]))
end
self.tamed = true
if not self.owner or self.owner == "" then
self.owner = clicker:get_player_name()
end
end
-- make sound when fed so many times
mob_sound(self, self.sounds.random)
end
return true
end
local item = clicker:get_wielded_item()
-- if mob has been tamed you can name it with a nametag
if item:get_name() == "mobs:nametag"
and clicker:get_player_name() == self.owner then
local name = clicker:get_player_name()
-- store mob and nametag stack in external variables
mob_obj[name] = self
mob_sta[name] = item
local tag = self.nametag or ""
minetest.show_formspec(name, "mobs_nametag", "size[8,4]"
.. default.gui_bg
.. default.gui_bg_img
.. "field[0.5,1;7.5,0;name;" .. S("Enter name:") .. ";" .. tag .. "]"
.. "button_exit[2.5,3.5;3,1;mob_rename;" .. S("Rename") .. "]")
end
return false
end
-- inspired by blockmen's nametag mod
minetest.register_on_player_receive_fields(function(player, formname, fields)
-- right-clicked with nametag and name entered?
if formname == "mobs_nametag"
and fields.name
and fields.name ~= "" then
local name = player:get_player_name()
if not mob_obj[name]
or not mob_obj[name].object then
return
end
-- limit name entered to 64 characters long
if string.len(fields.name) > 64 then
fields.name = string.sub(fields.name, 1, 64)
end
-- update nametag
mob_obj[name].nametag = fields.name
update_tag(mob_obj[name])
-- if not in creative then take item
if not creative then
mob_sta[name]:take_item()
player:set_wielded_item(mob_sta[name])
end
-- reset external variables
mob_obj[name] = nil
mob_sta[name] = nil
end
end)
-- compatibility function for old entities to new modpack entities
function mobs:alias_mob(old_name, new_name)
-- spawn egg
minetest.register_alias(old_name, new_name)
-- entity
minetest.register_entity(":" .. old_name, {
physical = false,
on_step = function(self)
local pos = self.object:getpos()
minetest.add_entity(pos, new_name)
self.object:remove()
end
})
end
| gpl-3.0 |
mercury233/ygopro-scripts | c74009824.lua | 4 | 2787 | --エルシャドール・ウェンディゴ
function c74009824.initial_effect(c)
--fusion material
c:EnableReviveLimit()
aux.AddFusionProcShaddoll(c,ATTRIBUTE_WIND)
--cannot spsummon
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE+EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e2:SetCode(EFFECT_SPSUMMON_CONDITION)
e2:SetRange(LOCATION_EXTRA)
e2:SetValue(c74009824.splimit)
c:RegisterEffect(e2)
--indes
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(74009824,0))
e3:SetType(EFFECT_TYPE_QUICK_O)
e3:SetCode(EVENT_FREE_CHAIN)
e3:SetRange(LOCATION_MZONE)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET)
e3:SetCountLimit(1,74009824)
e3:SetTarget(c74009824.indtg)
e3:SetOperation(c74009824.indop)
c:RegisterEffect(e3)
--tohand
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(74009824,1))
e4:SetCategory(CATEGORY_TOHAND)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e4:SetCode(EVENT_TO_GRAVE)
e4:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY)
e4:SetTarget(c74009824.thtg)
e4:SetOperation(c74009824.thop)
c:RegisterEffect(e4)
end
function c74009824.splimit(e,se,sp,st)
return bit.band(st,SUMMON_TYPE_FUSION)==SUMMON_TYPE_FUSION
end
function c74009824.indtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) end
if chk==0 then return Duel.IsExistingTarget(nil,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
Duel.SelectTarget(tp,nil,tp,LOCATION_MZONE,0,1,1,nil)
end
function c74009824.indop(e,tp,eg,ep,ev,re,r,rp)
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:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetValue(c74009824.indval)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
end
end
function c74009824.indval(e,c)
return c:IsSummonType(SUMMON_TYPE_SPECIAL)
end
function c74009824.thfilter(c)
return c:IsSetCard(0x9d) and c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsAbleToHand()
end
function c74009824.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c74009824.thfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c74009824.thfilter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectTarget(tp,c74009824.thfilter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0)
end
function c74009824.thop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c71541986.lua | 2 | 2544 | --エクシーズ・ディメンション・スプラッシュ
function c71541986.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(71541986,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetCode(EVENT_REMOVE)
e1:SetCondition(c71541986.spcon)
e1:SetTarget(c71541986.sptg)
e1:SetOperation(c71541986.spop)
c:RegisterEffect(e1)
end
function c71541986.spcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsPreviousLocation(LOCATION_ONFIELD) and c:IsPreviousPosition(POS_FACEDOWN)
end
function c71541986.spfilter(c,e,tp)
return c:IsAttribute(ATTRIBUTE_WATER) and c:IsLevel(8) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c71541986.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return not Duel.IsPlayerAffectedByEffect(tp,59822133)
and Duel.GetLocationCount(tp,LOCATION_MZONE)>1
and Duel.IsExistingMatchingCard(c71541986.spfilter,tp,LOCATION_DECK,0,2,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,tp,LOCATION_DECK)
end
function c71541986.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.IsPlayerAffectedByEffect(tp,59822133) then return end
if Duel.GetLocationCount(tp,LOCATION_MZONE)<2 then return end
local g=Duel.GetMatchingGroup(c71541986.spfilter,tp,LOCATION_DECK,0,nil,e,tp)
if g:GetCount()<2 then return end
local c=e:GetHandler()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sg=g:Select(tp,2,2,nil)
local tc=sg:GetFirst()
while tc do
Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_ATTACK_ANNOUNCE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE)
e2:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e2)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_DISABLE_EFFECT)
e3:SetValue(RESET_TURN_SET)
e3:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e3)
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e4:SetRange(LOCATION_MZONE)
e4:SetCode(EFFECT_UNRELEASABLE_SUM)
e4:SetValue(1)
e4:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e4)
local e5=e4:Clone()
e5:SetCode(EFFECT_UNRELEASABLE_NONSUM)
tc:RegisterEffect(e5)
tc=sg:GetNext()
end
Duel.SpecialSummonComplete()
end
| gpl-2.0 |
mercury233/ygopro-scripts | c94079037.lua | 2 | 1702 | --マイン・モール
function c94079037.initial_effect(c)
--battle indes
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EFFECT_INDESTRUCTABLE_COUNT)
e1:SetCountLimit(1)
e1:SetValue(c94079037.valcon)
c:RegisterEffect(e1)
--draw
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(94079037,0))
e2:SetCategory(CATEGORY_DRAW)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetCode(EVENT_BE_MATERIAL)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e2:SetCondition(c94079037.drcon)
e2:SetTarget(c94079037.drtg)
e2:SetOperation(c94079037.drop)
c:RegisterEffect(e2)
--redirect
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_LEAVE_FIELD_REDIRECT)
e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e3:SetCondition(c94079037.rmcon)
e3:SetValue(LOCATION_REMOVED)
c:RegisterEffect(e3)
end
function c94079037.valcon(e,re,r,rp)
return bit.band(r,REASON_BATTLE)~=0
end
function c94079037.drcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsLocation(LOCATION_GRAVE) and r==REASON_SYNCHRO
and e:GetHandler():GetReasonCard():IsRace(RACE_BEAST)
end
function c94079037.drtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(1)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c94079037.drop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Draw(p,d,REASON_EFFECT)
end
function c94079037.rmcon(e)
local c=e:GetHandler()
return c:IsFaceup() and c:IsReason(REASON_EFFECT) and c:GetReasonPlayer()==1-c:GetControler()
end
| gpl-2.0 |
ESMAILESMAIL/gladiator2 | plugins/boobs.lua | 90 | 1731 | do
-- Recursive function
local function getRandomButts(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.obutts.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt <= 3 then
print('Cannot get that butts, trying another one...')
return getRandomButts(attempt)
end
return 'http://media.obutts.ru/' .. data.preview
end
local function getRandomBoobs(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.oboobs.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt < 10 then
print('Cannot get that boobs, trying another one...')
return getRandomBoobs(attempt)
end
return 'http://media.oboobs.ru/' .. data.preview
end
local function run(msg, matches)
local url = nil
if matches[1] == "!boobs" then
url = getRandomBoobs()
end
if matches[1] == "!butts" then
url = getRandomButts()
end
if url ~= nil then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, url)
else
return 'Error getting boobs/butts for you, please try again later.'
end
end
return {
description = "Gets a random boobs or butts pic",
usage = {
"!boobs: Get a boobs NSFW image. 🔞",
"!butts: Get a butts NSFW image. 🔞"
},
patterns = {
"^!boobs$",
"^!butts$"
},
run = run
}
end
--Copyright; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
notcake/gcompute | lua/gcompute/ui/codeeditor/selection/selectionsnapshot.lua | 1 | 1317 | local self = {}
GCompute.CodeEditor.SelectionSnapshot = GCompute.MakeConstructor (self)
function self:ctor ()
self.Selection = GCompute.CodeEditor.TextSelection ()
self.CaretPosition = GCompute.CodeEditor.LineColumnLocation ()
self.PreferredCaretPosition = GCompute.CodeEditor.LineColumnLocation ()
end
function self:GetCaretPosition ()
return self.CaretPosition
end
function self:GetPreferredCaretPosition ()
return self.PreferredCaretPosition
end
function self:GetSelection ()
return self.Selection
end
function self:GetSelectionEnd ()
return self.Selection:GetSelectionEnd ()
end
function self:GetSelectionEndPoints ()
return self.Selection:GetSelectionEndPoints ()
end
function self:GetSelectionEnumerator ()
return self.Selection:GetSpanEnumerator ()
end
function self:GetSelectionLineSpan ()
return self.Selection:GetLineSpan ()
end
function self:GetSelectionMode ()
return self.Selection:GetSelectionMode ()
end
function self:GetSelectionStart ()
return self.Selection:GetSelectionStart ()
end
function self:SetCaretPosition (caretPosition)
self.CaretPosition:Copy (caretPosition)
end
function self:SetPreferredCaretPosition (preferredCaretPosition)
self.PreferredCaretPosition:Copy (preferredCaretPosition)
end | gpl-3.0 |
mercury233/ygopro-scripts | c80887714.lua | 4 | 1129 | --ギャラクシー・ストーム
function c80887714.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,TIMINGS_CHECK_MONSTER+TIMING_END_PHASE)
e1:SetTarget(c80887714.target)
e1:SetOperation(c80887714.activate)
c:RegisterEffect(e1)
end
function c80887714.filter(c)
return c:IsFaceup() and c:IsType(TYPE_XYZ) and c:GetOverlayCount()==0
end
function c80887714.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c80887714.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c80887714.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,c80887714.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c80887714.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| gpl-2.0 |
Zenny89/darkstar | scripts/globals/mobskills/Cryo_Jet.lua | 18 | 1243 | ---------------------------------------------------
-- Cryo_Jet
-- Description:
-- Type: Magical
-- additional effect : Paralyze
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
local mobID = mob:getID(); --(16908295 ,16908302 ,16908309 =omega , 16928966=proto-ultima )
local mobhp = mob:getHPP();
if (mobID == 16928966) then
if (mobhp < 70 and mobhp > 40) then
return 0;
end
elseif (mobID == 16908295 or mobID == 16908302 or mobID == 16908309) then
if (mobhp < 80 and mobhp > 40) then
return 0;
end
end
return 1;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_PARALYSIS;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 3, 60);
local dmgmod = 2;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_ICE,dmgmod,TP_MAB_BONUS,1);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_ICE,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
return dmg;
end
| gpl-3.0 |
mercury233/ygopro-scripts | c7198399.lua | 4 | 2770 | --チョコ・マジシャン・ガール
function c7198399.initial_effect(c)
--draw
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(7198399,0))
e1:SetCategory(CATEGORY_DRAW)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCost(c7198399.drcost)
e1:SetTarget(c7198399.drtg)
e1:SetOperation(c7198399.drop)
c:RegisterEffect(e1)
--change battle target
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(7198399,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_ATKCHANGE)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY)
e2:SetCode(EVENT_BE_BATTLE_TARGET)
e2:SetCountLimit(1)
e2:SetTarget(c7198399.sptg)
e2:SetOperation(c7198399.spop)
c:RegisterEffect(e2)
end
function c7198399.costfilter(c)
return c:IsRace(RACE_SPELLCASTER) and c:IsDiscardable()
end
function c7198399.drcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c7198399.costfilter,tp,LOCATION_HAND,0,1,nil) end
Duel.DiscardHand(tp,c7198399.costfilter,1,1,REASON_DISCARD+REASON_COST)
end
function c7198399.drtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(1)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c7198399.drop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Draw(p,d,REASON_EFFECT)
end
function c7198399.spfilter(c,e,tp)
return c:IsRace(RACE_SPELLCASTER) and not c:IsCode(7198399) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c7198399.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c7198399.spfilter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c7198399.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c7198399.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c7198399.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)>0 then
local a=Duel.GetAttacker()
local ag=a:GetAttackableTarget()
if a:IsAttackable() and not a:IsImmuneToEffect(e) and ag:IsContains(tc) then
Duel.BreakEffect()
Duel.ChangeAttackTarget(tc)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SET_ATTACK_FINAL)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
e1:SetValue(math.ceil(a:GetAttack()/2))
a:RegisterEffect(e1)
end
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c42338879.lua | 6 | 1291 | --こけコッコ
function c42338879.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(c42338879.spcon)
e1:SetOperation(c42338879.spop)
c:RegisterEffect(e1)
--redirect
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_LEAVE_FIELD_REDIRECT)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e2:SetCondition(c42338879.recon)
e2:SetValue(LOCATION_REMOVED)
c:RegisterEffect(e2)
end
function c42338879.spcon(e,c)
if c==nil then return true end
local tp=c:GetControler()
return (Duel.GetFieldGroupCount(tp,LOCATION_MZONE,LOCATION_MZONE)==0
or (Duel.GetFieldGroupCount(tp,LOCATION_ONFIELD,0)==0 and Duel.GetFieldGroupCount(tp,0,LOCATION_MZONE)>0))
and Duel.GetLocationCount(tp,LOCATION_MZONE)>0
end
function c42338879.spop(e,tp,eg,ep,ev,re,r,rp,c)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LEVEL)
if Duel.GetFieldGroupCount(tp,LOCATION_MZONE,LOCATION_MZONE)==0 then
e1:SetValue(3)
else
e1:SetValue(4)
end
e1:SetReset(RESET_EVENT+0xff0000)
c:RegisterEffect(e1)
end
function c42338879.recon(e)
return e:GetHandler():IsFaceup()
end
| gpl-2.0 |
mercury233/ygopro-scripts | c85758066.lua | 2 | 3759 | --機械じかけのマジックミラー
function c85758066.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_ATTACK_ANNOUNCE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCondition(c85758066.condition)
e1:SetTarget(c85758066.target)
e1:SetOperation(c85758066.activate)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetRange(LOCATION_GRAVE)
e2:SetHintTiming(0,TIMINGS_CHECK_MONSTER)
e2:SetCost(c85758066.spcost)
e2:SetTarget(c85758066.sptg)
e2:SetOperation(c85758066.spop)
c:RegisterEffect(e2)
end
function c85758066.condition(e,tp,eg,ep,ev,re,r,rp)
return tp~=Duel.GetTurnPlayer()
end
function c85758066.filter(c,tp,ft)
return c:IsType(TYPE_SPELL) and c:IsSSetable(true) and (c:IsType(TYPE_FIELD) or Duel.GetLocationCount(tp,LOCATION_SZONE)>ft)
end
function c85758066.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local ft=0
if e:GetHandler():IsLocation(LOCATION_HAND) then ft=1 end
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(1-tp) and c85758066.filter(chkc,tp,ft) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>ft
and Duel.IsExistingTarget(c85758066.filter,tp,0,LOCATION_GRAVE,1,nil,tp,ft) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SET)
local g=Duel.SelectTarget(tp,c85758066.filter,tp,0,LOCATION_GRAVE,1,1,nil,tp,ft)
Duel.SetOperationInfo(0,CATEGORY_LEAVE_GRAVE,g,1,0,0)
end
function c85758066.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SSet(tp,tc)
end
end
function c85758066.costfilter(c)
return c:IsCode(83764718) and c:IsAbleToGraveAsCost()
and (c:IsLocation(LOCATION_HAND) or (c:IsLocation(LOCATION_SZONE) and c:IsFacedown()))
end
function c85758066.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost()
and Duel.IsExistingMatchingCard(c85758066.costfilter,tp,LOCATION_HAND+LOCATION_SZONE,0,1,nil) end
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c85758066.costfilter,tp,LOCATION_HAND+LOCATION_SZONE,0,1,1,nil)
Duel.SendtoGrave(g,REASON_COST)
end
function c85758066.spfilter(c,e,tp)
return c:IsCode(10000000) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP_DEFENSE)
end
function c85758066.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c85758066.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_GRAVE)
end
function c85758066.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 tc=Duel.SelectMatchingCard(tp,c85758066.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp):GetFirst()
if tc and Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP_DEFENSE)>0
and Duel.GetTurnPlayer()==1-tp then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_SELECT_BATTLE_TARGET)
e1:SetRange(LOCATION_MZONE)
e1:SetTargetRange(0,LOCATION_MZONE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
e1:SetValue(c85758066.atklimit)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_MUST_ATTACK)
e2:SetRange(LOCATION_MZONE)
e2:SetTargetRange(0,LOCATION_MZONE)
e2:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e2)
end
end
function c85758066.atklimit(e,c)
return c~=e:GetHandler()
end
| gpl-2.0 |
Zenny89/darkstar | scripts/zones/Nashmau/npcs/Awaheen.lua | 17 | 1932 | -----------------------------------
-- Area: Nashmau
-- NPC: Awaheen
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Nashmau/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Nashmau/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Trade: Receive:
-- 1 x Imperial Gold Piece (2187) 5 x Imperial Mythril Piece(2186)
-- 1 x Imperial Mythril Piece(2186) 2 x Imperial Silver Piece(2185)
-- 1 x Imperial Silver Piece (2185) 5 x Imperial Bronze Piece(2184)
local nbr = 0;
local reward = 0;
if (trade:getItemCount() == 1) then
if (trade:hasItemQty(2187,1)) then nbr = 5 ; reward = 2186;
elseif (trade:hasItemQty(2186,1)) then nbr = 2 ; reward = 2185;
elseif (trade:hasItemQty(2185,1)) then nbr = 5 ; reward = 2184;
end
end
if (reward > 0) then
local boucle;
if (player:getFreeSlotsCount() >= 1) then
player:tradeComplete();
player:addItem(reward,nbr);
for boucle=1,nbr,1 do player:messageSpecial(ITEM_OBTAINED,reward);
end
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,reward);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00F0);
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 |
Zenny89/darkstar | scripts/zones/East_Ronfaure/npcs/Rayochindot.lua | 38 | 1028 | -----------------------------------
-- Area: East Ronfaure
-- NPC: Rayochindot
-- Type: Gate Guard
-- @pos 93.159 -62.999 272.601 101
-----------------------------------
package.loaded["scripts/zones/East_Ronfaure/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/East_Ronfaure/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, RAYOCHINDOT_DIALOG);
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 |
mercury233/ygopro-scripts | c69680031.lua | 2 | 3542 | --教導の騎士フルルドリス
function c69680031.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(69680031,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_DISABLE)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetRange(LOCATION_HAND)
e1:SetHintTiming(0,TIMINGS_CHECK_MONSTER+TIMING_MAIN_END)
e1:SetCountLimit(1,69680031)
e1:SetCondition(c69680031.spcon)
e1:SetTarget(c69680031.sptg)
e1:SetOperation(c69680031.spop)
c:RegisterEffect(e1)
--atk
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(69680031,1))
e2:SetCategory(CATEGORY_ATKCHANGE)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_ATTACK_ANNOUNCE)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,69680032)
e2:SetCondition(c69680031.atkcon)
e2:SetTarget(c69680031.atktg)
e2:SetOperation(c69680031.atkop)
c:RegisterEffect(e2)
end
function c69680031.cfilter(c)
return c:IsSummonLocation(LOCATION_EXTRA)
end
function c69680031.spcon(e,tp,eg,ep,ev,re,r,rp)
local ph=Duel.GetCurrentPhase()
return (ph==PHASE_MAIN1 or ph==PHASE_MAIN2)
and Duel.IsExistingMatchingCard(c69680031.cfilter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil)
end
function c69680031.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 c69680031.ofilter(c)
return c:IsFaceup() and c:IsSetCard(0x145)
end
function c69680031.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)~=0
and Duel.IsExistingMatchingCard(c69680031.ofilter,tp,LOCATION_MZONE,0,1,c)
and Duel.IsExistingMatchingCard(aux.NegateMonsterFilter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil)
and Duel.SelectYesNo(tp,aux.Stringid(69680031,2)) then
Duel.BreakEffect()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DISABLE)
local g=Duel.SelectMatchingCard(tp,aux.NegateMonsterFilter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.HintSelection(g)
local tc=g:GetFirst()
Duel.NegateRelatedChain(tc,RESET_TURN_SET)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e2:SetValue(RESET_TURN_SET)
e2:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e2)
end
end
function c69680031.atkcon(e,tp,eg,ep,ev,re,r,rp)
local ac=Duel.GetAttacker()
return ac:IsFaceup() and ac:IsControler(tp) and ac:IsSetCard(0x145)
end
function c69680031.atkfilter(c)
return c:IsFaceup() and c:IsSetCard(0x145)
end
function c69680031.atktg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c69680031.atkfilter,tp,LOCATION_MZONE,0,1,nil) end
end
function c69680031.atkop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local g=Duel.GetMatchingGroup(c69680031.atkfilter,tp,LOCATION_MZONE,0,nil)
local tc=g:GetFirst()
while tc do
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
e1:SetValue(500)
tc:RegisterEffect(e1)
tc=g:GetNext()
end
end
| gpl-2.0 |
qq779089973/my_openwrt_mod | luci/protocols/ipv6/luasrc/model/cbi/admin_network/proto_6rd.lua | 53 | 2242 | --[[
LuCI - Lua Configuration Interface
Copyright 2011-2012 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local ipaddr, peeraddr, ip6addr, tunnelid, username, password
local defaultroute, metric, ttl, mtu
ipaddr = s:taboption("general", Value, "ipaddr",
translate("Local IPv4 address"),
translate("Leave empty to use the current WAN address"))
ipaddr.datatype = "ip4addr"
peeraddr = s:taboption("general", Value, "peeraddr",
translate("Remote IPv4 address"),
translate("This IPv4 address of the relay"))
peeraddr.rmempty = false
peeraddr.datatype = "ip4addr"
ip6addr = s:taboption("general", Value, "ip6prefix",
translate("IPv6 prefix"),
translate("The IPv6 prefix assigned to the provider, usually ends with <code>::</code>"))
ip6addr.rmempty = false
ip6addr.datatype = "ip6addr"
ip6prefixlen = s:taboption("general", Value, "ip6prefixlen",
translate("IPv6 prefix length"),
translate("The length of the IPv6 prefix in bits"))
ip6prefixlen.placeholder = "16"
ip6prefixlen.datatype = "range(0,128)"
ip6prefixlen = s:taboption("general", Value, "ip4prefixlen",
translate("IPv4 prefix length"),
translate("The length of the IPv4 prefix in bits, the remainder is used in the IPv6 addresses."))
ip6prefixlen.placeholder = "0"
ip6prefixlen.datatype = "range(0,32)"
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface"))
ttl.placeholder = "64"
ttl.datatype = "range(1,255)"
mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface"))
mtu.placeholder = "1280"
mtu.datatype = "max(9200)"
| mit |
noname007/koreader | frontend/ui/wikipedia.lua | 3 | 2599 | local JSON = require("json")
local DEBUG = require("dbg")
--[[
-- Query wikipedia using Wikimedia Web API.
-- http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&explaintext=&redirects=&titles=hello
--]]
local Wikipedia = {
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_params = {
action = "query",
prop = "extracts",
format = "json",
exintro = "",
explaintext = "",
redirects = "",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain)
local socket = require('socket')
local url = require('socket.url')
local http = require('socket.http')
local https = require('ssl.https')
local ltn12 = require('ltn12')
local request, sink = {}, {}
local query = ""
self.wiki_params.exintro = intro and "" or nil
self.wiki_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_params) do
query = query .. k .. '=' .. v .. '&'
end
local parsed = url.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. url.escape(text)
-- HTTP request
request['url'] = url.build(parsed)
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
DEBUG("request", request)
http.TIMEOUT, https.TIMEOUT = 10, 10
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
-- raise error message when network is unavailable
if headers == nil then
error("Network is unreachable")
end
if status ~= "HTTP/1.1 200 OK" then
DEBUG("HTTP status not okay:", status)
return
end
local content = table.concat(sink)
if content ~= "" and string.sub(content, 1,1) == "{" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
DEBUG("wiki result", result)
return result
else
DEBUG("error:", result)
end
else
DEBUG("not JSON:", content)
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result then
local query = result.query
if query then
return query.pages
end
end
end
return Wikipedia
| agpl-3.0 |
Zenny89/darkstar | scripts/zones/Windurst_Waters/npcs/HomePoint#1.lua | 17 | 1266 | -----------------------------------
-- Area: Windurst Waters
-- NPC: HomePoint#1
-- @pos -32.022 -5.000 131.741 238
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Windurst_Waters/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 17);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
mercury233/ygopro-scripts | c61156777.lua | 4 | 2435 | --BOXサー
function c61156777.initial_effect(c)
c:EnableCounterPermit(0x34)
--Add counter
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(61156777,0))
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_BATTLE_DESTROYING)
e1:SetCondition(aux.bdogcon)
e1:SetOperation(c61156777.ctop)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(61156777,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetCost(c61156777.spcost)
e2:SetTarget(c61156777.sptg)
e2:SetOperation(c61156777.spop)
c:RegisterEffect(e2)
--destroy replace
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_SINGLE)
e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e3:SetRange(LOCATION_MZONE)
e3:SetCode(EFFECT_DESTROY_REPLACE)
e3:SetTarget(c61156777.reptg)
e3:SetOperation(c61156777.repop)
c:RegisterEffect(e3)
end
function c61156777.ctop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsFaceup() and c:IsRelateToEffect(e) then
c:AddCounter(0x34,1)
end
end
function c61156777.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToGraveAsCost() and e:GetHandler():GetCounter(0x34)>1 end
Duel.SendtoGrave(e:GetHandler(),REASON_COST)
end
function c61156777.filter(c,e,tp)
return c:IsAttribute(ATTRIBUTE_EARTH) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c61156777.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1
and Duel.IsExistingMatchingCard(c61156777.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c61156777.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,c61156777.filter,tp,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 c61156777.reptg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return c:IsReason(REASON_BATTLE+REASON_EFFECT) and not c:IsReason(REASON_REPLACE) and c:IsCanRemoveCounter(tp,0x34,1,REASON_EFFECT) end
return Duel.SelectEffectYesNo(tp,c,96)
end
function c61156777.repop(e,tp,eg,ep,ev,re,r,rp)
e:GetHandler():RemoveCounter(tp,0x34,1,REASON_EFFECT)
end
| gpl-2.0 |
mercury233/ygopro-scripts | c11264180.lua | 2 | 2021 | --TGX1-HL
function c11264180.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_ATKCHANGE+CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(TIMING_DAMAGE_STEP)
e1:SetCondition(aux.dscon)
e1:SetTarget(c11264180.target)
e1:SetOperation(c11264180.activate)
c:RegisterEffect(e1)
end
function c11264180.filter(c)
return c:IsFaceup() and c:IsSetCard(0x27)
end
function c11264180.dfilter(c)
return c:IsType(TYPE_SPELL+TYPE_TRAP)
end
function c11264180.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c11264180.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c11264180.filter,tp,LOCATION_MZONE,0,1,nil)
and Duel.IsExistingMatchingCard(c11264180.dfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,e:GetHandler()) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,c11264180.filter,tp,LOCATION_MZONE,0,1,1,nil)
local dg=Duel.GetMatchingGroup(c11264180.dfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,e:GetHandler())
Duel.SetOperationInfo(0,CATEGORY_DESTROY,dg,1,0,0)
end
function c11264180.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if not tc:IsRelateToEffect(e) or tc:IsFacedown() then return end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SET_ATTACK_FINAL)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
e1:SetValue(math.ceil(tc:GetAttack()/2))
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_SET_DEFENSE_FINAL)
e2:SetReset(RESET_EVENT+RESETS_STANDARD)
e2:SetValue(math.ceil(tc:GetDefense()/2))
tc:RegisterEffect(e2)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local dg=Duel.SelectMatchingCard(tp,c11264180.dfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,aux.ExceptThisCard(e))
Duel.Destroy(dg,REASON_EFFECT)
end
| gpl-2.0 |
Zenny89/darkstar | scripts/globals/items/cup_of_chocomilk.lua | 35 | 1163 | -----------------------------------------
-- ID: 4498
-- Item: cup_of_chocomilk
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Magic Regen While Healing 3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4498);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MPHEAL, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MPHEAL, 3);
end;
| gpl-3.0 |
Zenny89/darkstar | scripts/zones/Windurst_Woods/npcs/HomePoint#2.lua | 17 | 1251 | -----------------------------------
-- Area: Windurst Woods
-- NPC: HomePoint#2
-- @pos 107 -5 -56 241
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Windurst_Woods/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fd, 26);
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 == 0x21fd) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
mercury233/ygopro-scripts | c79613121.lua | 3 | 2140 | --マジシャン・オブ・ブラックカオス・MAX
function c79613121.initial_effect(c)
c:EnableReviveLimit()
--act limit
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(79613121,0))
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCountLimit(1,79613121)
e1:SetCost(c79613121.cost)
e1:SetOperation(c79613121.sumsuc)
c:RegisterEffect(e1)
--tohand
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(79613121,1))
e2:SetCategory(CATEGORY_TOHAND)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_BATTLE_DESTROYING)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCountLimit(1,79613122)
e2:SetCondition(aux.bdocon)
e2:SetTarget(c79613121.thtg)
e2:SetOperation(c79613121.thop)
c:RegisterEffect(e2)
end
function c79613121.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckReleaseGroup(tp,nil,1,nil) end
local g=Duel.SelectReleaseGroup(tp,nil,1,1,nil)
Duel.Release(g,REASON_COST)
end
function c79613121.sumsuc(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(0,1)
e1:SetValue(c79613121.actlimit)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c79613121.actlimit(e,re,tp)
return re:IsActiveType(TYPE_MONSTER)
end
function c79613121.thfilter(c)
return c:IsType(TYPE_SPELL) and c:IsAbleToHand()
end
function c79613121.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c79613121.thfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c79613121.thfilter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectTarget(tp,c79613121.thfilter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0)
end
function c79613121.thop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
end
end
| gpl-2.0 |
guillaume144/jeu-rp | gamemode/modules/doorsystem/cl_doors.lua | 3 | 4946 | local meta = FindMetaTable("Entity")
local black = Color(0, 0, 0, 255)
local white = Color(255, 255, 255, 200)
local red = Color(128, 30, 30, 255)
function meta:drawOwnableInfo()
if LocalPlayer():InVehicle() then return end
-- Look, if you want to change the way door ownership is drawn, don't edit this file, use the hook instead!
local doorDrawing = hook.Call("HUDDrawDoorData", nil, self)
if doorDrawing == true then return end
local blocked = self:getKeysNonOwnable()
local superadmin = LocalPlayer():IsSuperAdmin()
local doorTeams = self:getKeysDoorTeams()
local doorGroup = self:getKeysDoorGroup()
local playerOwned = self:isKeysOwned() or table.GetFirstValue(self:getKeysCoOwners() or {}) ~= nil
local owned = playerOwned or doorGroup or doorTeams
local doorInfo = {}
local title = self:getKeysTitle()
if title then table.insert(doorInfo, title) end
if owned then
table.insert(doorInfo, DarkRP.getPhrase("keys_owned_by"))
end
if playerOwned then
if self:isKeysOwned() then table.insert(doorInfo, self:getDoorOwner():Nick()) end
for k,v in pairs(self:getKeysCoOwners() or {}) do
local ent = Player(k)
if not IsValid(ent) or not ent:IsPlayer() then continue end
table.insert(doorInfo, ent:Nick())
end
local allowedCoOwn = self:getKeysAllowedToOwn()
if allowedCoOwn and not fn.Null(allowedCoOwn) then
table.insert(doorInfo, DarkRP.getPhrase("keys_other_allowed"))
for k,v in pairs(allowedCoOwn) do
local ent = Player(k)
if not IsValid(ent) or not ent:IsPlayer() then continue end
table.insert(doorInfo, ent:Nick())
end
end
elseif doorGroup then
table.insert(doorInfo, doorGroup)
elseif doorTeams then
for k, v in pairs(doorTeams) do
if not v or not RPExtraTeams[k] then continue end
table.insert(doorInfo, RPExtraTeams[k].name)
end
elseif blocked and superadmin then
table.insert(doorInfo, DarkRP.getPhrase("keys_allow_ownership"))
elseif not blocked then
table.insert(doorInfo, DarkRP.getPhrase("keys_unowned"))
if superadmin then
table.insert(doorInfo, DarkRP.getPhrase("keys_disallow_ownership"))
end
end
if self:IsVehicle() then
for k,v in pairs(player.GetAll()) do
if v:GetVehicle() ~= self then continue end
table.insert(doorInfo, DarkRP.getPhrase("driver", v:Nick()))
break
end
end
local x, y = ScrW() / 2, ScrH() / 2
draw.DrawNonParsedText(table.concat(doorInfo, "\n"), "TargetID", x , y + 1 , black, 1)
draw.DrawNonParsedText(table.concat(doorInfo, "\n"), "TargetID", x, y, (blocked or owned) and white or red, 1)
end
/*---------------------------------------------------------------------------
Door data
---------------------------------------------------------------------------*/
DarkRP.doorData = DarkRP.doorData or {}
/*---------------------------------------------------------------------------
Interface functions
---------------------------------------------------------------------------*/
function meta:getDoorData()
local doorData = DarkRP.doorData[self:EntIndex()] or {}
self.DoorData = doorData -- Backwards compatibility
return doorData
end
/*---------------------------------------------------------------------------
Networking
---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------
Retrieve all the data for all doors
---------------------------------------------------------------------------*/
local receivedDoorData = false
local function retrieveAllDoorData(len)
receivedDoorData = true
local data = net.ReadTable()
DarkRP.doorData = data
end
net.Receive("DarkRP_AllDoorData", retrieveAllDoorData)
hook.Add("InitPostEntity", "DoorData", fp{RunConsoleCommand, "_sendAllDoorData"})
/*---------------------------------------------------------------------------
Update changed variables
---------------------------------------------------------------------------*/
local function updateDoorData()
local door = net.ReadUInt(32)
DarkRP.doorData[door] = DarkRP.doorData[door] or {}
local var = net.ReadString()
local valueType = net.ReadUInt(8)
local value = net.ReadType(valueType)
DarkRP.doorData[door][var] = value
end
net.Receive("DarkRP_UpdateDoorData", updateDoorData)
/*---------------------------------------------------------------------------
Remove doordata of removed entity
---------------------------------------------------------------------------*/
local function removeDoorData()
local door = net.ReadUInt(32)
DarkRP.doorData[door] = nil
end
net.Receive("DarkRP_RemoveDoorData", removeDoorData)
| mit |
mercury233/ygopro-scripts | c19355597.lua | 2 | 2030 | --ジェムナイトレディ・ブリリアント・ダイヤ
function c19355597.initial_effect(c)
c:SetSPSummonOnce(19355597)
--fusion material
c:EnableReviveLimit()
aux.AddFusionProcFunRep(c,aux.FilterBoolFunction(Card.IsFusionSetCard,0x1047),3,false)
--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(c19355597.splimit)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TOGRAVE)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1)
e2:SetTarget(c19355597.sptg)
e2:SetOperation(c19355597.spop)
c:RegisterEffect(e2)
end
function c19355597.splimit(e,se,sp,st)
return not e:GetHandler():IsLocation(LOCATION_EXTRA) or bit.band(st,SUMMON_TYPE_FUSION)==SUMMON_TYPE_FUSION
end
function c19355597.tgfilter(c,e,tp)
return c:IsFaceup() and c:IsSetCard(0x1047)
and Duel.IsExistingMatchingCard(c19355597.spfilter,tp,LOCATION_EXTRA,0,1,nil,e,tp,c)
end
function c19355597.spfilter(c,e,tp,tc)
return c:IsSetCard(0x1047) and c:IsType(TYPE_FUSION)
and c:IsCanBeSpecialSummoned(e,0,tp,true,false) and Duel.GetLocationCountFromEx(tp,tp,tc,c)>0
end
function c19355597.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c19355597.tgfilter,tp,LOCATION_MZONE,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA)
end
function c19355597.spop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local tg=Duel.SelectMatchingCard(tp,c19355597.tgfilter,tp,LOCATION_MZONE,0,1,1,nil,e,tp)
local tc=tg:GetFirst()
if tc and Duel.SendtoGrave(tc,REASON_EFFECT)~=0 and tc:IsLocation(LOCATION_GRAVE) then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c19355597.spfilter,tp,LOCATION_EXTRA,0,1,1,nil,e,tp)
Duel.SpecialSummon(g,0,tp,tp,true,false,POS_FACEUP)
end
end
| gpl-2.0 |
dailin/wesnoth | data/ai/micro_ais/cas/ca_messenger_f_next_waypoint.lua | 25 | 2603 | local H = wesnoth.require "lua/helper.lua"
local AH = wesnoth.require "ai/lua/ai_helper.lua"
local MAIUV = wesnoth.require "ai/micro_ais/micro_ai_unit_variables.lua"
return function(cfg)
-- Calculate next waypoint and rating for all messengers
-- Return next messenger to move and waypoint toward which it should move
-- Also return the array of all messengers (for escort move evaluation,
-- so that it only needs to be done in one place, in case the syntax is changed some more)
-- Returns nil for first 3 arguments if no messenger has moves left
-- Returns nil for all arguments if there are no messengers on the map
local filter = cfg.filter or { id = cfg.id }
local messengers = wesnoth.get_units { side = wesnoth.current.side, { "and", filter } }
if (not messengers[1]) then return end
local waypoint_x = AH.split(cfg.waypoint_x, ",")
local waypoint_y = AH.split(cfg.waypoint_y, ",")
for i,_ in ipairs(waypoint_x) do
waypoint_x[i] = tonumber(waypoint_x[i])
waypoint_y[i] = tonumber(waypoint_y[i])
end
-- Set the next waypoint for all messengers
-- Also find those with MP left and return the one to next move, together with the WP to move toward
local max_rating, best_messenger, x, y = -9e99
for _,messenger in ipairs(messengers) do
-- To avoid code duplication and ensure consistency, we store some pieces of
-- information in the messenger units, even though it could be calculated each time it is needed
local wp_i = MAIUV.get_mai_unit_variables(messenger, cfg.ai_id, "wp_i") or 1
local wp_x, wp_y = waypoint_x[wp_i], waypoint_y[wp_i]
-- If this messenger is within 3 hexes of the next waypoint, we go on to the one after that
-- except if it's the last one
local dist_wp = H.distance_between(messenger.x, messenger.y, wp_x, wp_y)
if (dist_wp <= 3) and (wp_i < #waypoint_x) then wp_i = wp_i + 1 end
-- Also store the rating for each messenger
-- For now, this is simply a "forward rating"
local rating = wp_i - dist_wp / 1000.
-- If invert_order= key is set, we want to move the rearmost messenger first.
if cfg.invert_order then rating = - rating end
MAIUV.set_mai_unit_variables(messenger, cfg.ai_id, { wp_i = wp_i, wp_x = wp_x, wp_y = wp_y, wp_rating = rating })
if (messenger.moves > 0) and (rating > max_rating) then
best_messenger, max_rating = messenger, rating
x, y = wp_x, wp_y
end
end
return best_messenger, x, y, messengers
end
| gpl-2.0 |
Zenny89/darkstar | scripts/zones/Southern_San_dOria/npcs/Balasiel.lua | 17 | 6074 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Balasiel
-- Starts and Finishes: A Squire's Test, A Squire's Test II, A Knight's Test
-- @zone 230
-- @pos -136 -11 64
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,A_SQUIRE_S_TEST) == QUEST_ACCEPTED) then
if (trade:hasItemQty(940,1) and trade:getItemCount() == 1) then
player:startEvent(0x0269);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local LvL = player:getMainLvl();
local ASquiresTest = player:getQuestStatus(SANDORIA, A_SQUIRE_S_TEST);
local ASquiresTestII = player:getQuestStatus(SANDORIA,A_SQUIRE_S_TEST_II);
local AKnightsTest = player:getQuestStatus(SANDORIA, A_KNIGHT_S_TEST);
if (player:getQuestStatus(SANDORIA,KNIGHT_STALKER) == QUEST_ACCEPTED and player:getVar("KnightStalker_Progress") == 2) then
player:startEvent(63); -- DRG AF3 cutscene, doesn't appear to have a follow up.
elseif (LvL < 7) then
player:startEvent(0x029c);
elseif (LvL >= 7 and ASquiresTest ~= QUEST_COMPLETED) then
if (ASquiresTest == 0) then
if (player:getVar("SquiresTest") == 1) then
player:startEvent(0x0277);
else
player:startEvent(0x0268);
end
elseif (ASquiresTest == QUEST_ACCEPTED) then
player:startEvent(0x029b);
end
elseif (LvL >= 7 and LvL < 15) then
player:startEvent(0x029f);
elseif (LvL >= 15 and ASquiresTestII ~= QUEST_COMPLETED) then
local StalactiteDew = player:hasKeyItem(STALACTITE_DEW)
if (ASquiresTestII == QUEST_AVAILABLE) then
player:startEvent(0x0271);
elseif (ASquiresTestII == QUEST_ACCEPTED and StalactiteDew == false) then
player:startEvent(0x0276);
elseif (StalactiteDew) then
player:startEvent(0x0272);
else
player:startEvent(0x029b);
end
elseif (LvL >= 15 and LvL < 30) then
player:startEvent(0x029e);
elseif (LvL >= 30 and AKnightsTest ~= QUEST_COMPLETED) then
if (AKnightsTest == 0) then
if (player:getVar("KnightsTest_Event") == 1) then
player:startEvent(0x027b);
else
player:startEvent(0x0273);
end
elseif (player:hasKeyItem(KNIGHTS_SOUL)) then
player:startEvent(0x0274);
else
player:startEvent(0x029d);
end
else
player:startEvent(0x029b);
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 == 0x0268) then
if (option == 0) then
player:addQuest(SANDORIA,A_SQUIRE_S_TEST);
else
player:setVar("SquiresTest_Event",1);
end
elseif (csid == 0x0277 and option == 0) then
player:addQuest(SANDORIA,A_SQUIRE_S_TEST);
player:setVar("SquiresTest_Event",0);
elseif (csid == 0x0269) then
if (player:getFreeSlotsCount(0) >= 1) then
player:tradeComplete();
player:addTitle(KNIGHT_IN_TRAINING);
player:addItem(16565);
player:messageSpecial(ITEM_OBTAINED, 16565); -- Spatha
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA,A_SQUIRE_S_TEST);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 16565); -- Spatha
end
elseif (csid == 0x0271 or csid == 0x0276) then
player:addQuest(SANDORIA,A_SQUIRE_S_TEST_II);
elseif (csid == 0x0272) then
player:tradeComplete();
player:addTitle(SPELUNKER);
player:delKeyItem(STALACTITE_DEW);
player:addKeyItem(SQUIRE_CERTIFICATE);
player:messageSpecial(KEYITEM_OBTAINED, SQUIRE_CERTIFICATE);
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA,A_SQUIRE_S_TEST_II);
elseif (csid == 0x0273) then
if (option == 0) then
player:addQuest(SANDORIA,A_KNIGHT_S_TEST);
player:addKeyItem(BOOK_OF_TASKS);
player:messageSpecial(KEYITEM_OBTAINED, BOOK_OF_TASKS);
else
player:setVar("KnightsTest_Event",1);
end
elseif (csid == 0x027b and option == 0) then
player:addQuest(SANDORIA,A_KNIGHT_S_TEST);
player:addKeyItem(BOOK_OF_TASKS);
player:messageSpecial(KEYITEM_OBTAINED, BOOK_OF_TASKS);
player:setVar("KnightsTest_Event",0);
elseif (csid == 0x0274) then
if (player:getFreeSlotsCount(0) >= 1) then
player:addTitle(TRIED_AND_TESTED_KNIGHT);
player:delKeyItem(KNIGHTS_SOUL);
player:delKeyItem(BOOK_OF_TASKS);
player:delKeyItem(BOOK_OF_THE_WEST);
player:delKeyItem(BOOK_OF_THE_EAST);
player:addItem(12306);
player:messageSpecial(ITEM_OBTAINED, 12306); -- Kite Shield
player:unlockJob(7); --Paladin
player:messageSpecial(UNLOCK_PALADIN);
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA,A_KNIGHT_S_TEST);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 12306); -- Kite Shield
end
elseif (csid == 63) then
player:setVar("KnightStalker_Progress",3);
end
end;
-- player:startEvent(0x7fb2) -- starlight celebration
-- player:startEvent(0x000a) -- methods create madness you havent used the weapon to full extent
-- player:startEvent(0x0008) -- methods create madness start
-- player:startEvent(0x000b) -- methods create nadness menu
-- player:startEvent(0x0009) -- methods create madness map
-- player:startEvent(0x000c) -- methods create madness map reminder
-- player:startEvent(0x000d) -- methods create madness end | gpl-3.0 |
Zenny89/darkstar | scripts/globals/spells/ionohelix.lua | 22 | 1721 | --------------------------------------
-- Spell: Ionohelix
-- Deals lightning 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);
utils.clamp(dot, 0, 99999);
local duration = getHelixDuration(caster) + caster:getMod(MOD_HELIX_DURATION);
duration = duration * (resist/2);
target:addStatusEffect(EFFECT_HELIX,dot,3,duration);
return dmg;
end; | gpl-3.0 |
openwrt-stuff/openwrt-extra | luci/applications/luci-rtorrent/luasrc/model/cbi/rtorrent/torrent/peers.lua | 2 | 4356 | -- Copyright 2014-2016 Sandor Balazsi <sandor.balazsi@gmail.com>
-- Licensed to the public under the Apache License 2.0.
local rtorrent = require "rtorrent"
local http = require "socket.http"
local common = require "luci.model.cbi.rtorrent.common"
local hash = arg[1]
local details = rtorrent.batchcall({"name"}, hash, "d.")
local format, total, map = {}, {}, {}
local geoplugin_net = {
address = "http://www.geoplugin.net/json.gp?ip=%s",
fields = { geoplugin_countryCode = "country_code", geoplugin_countryName = "country", geoplugin_region = "region",
geoplugin_city = "city", geoplugin_latitude = "latitude", geoplugin_longitude = "longitude"
}}
local ip2geo = geoplugin_net
function map.googlemap(latitude, longitude, zoom)
return "https://google.com/maps/place/%s,%s/@%s,%s,%sz" % {latitude, longitude, latitude, longitude, zoom}
end
function map.openstreetmap(latitude, longitude, zoom)
return "http://www.openstreetmap.org/?mlat=%s&mlon=%s#map=%s/%s/%s/m" % {latitude, longitude, zoom, latitude, longitude}
end
function format.address(r, v)
total["address"] = (total["address"] or 0) + 1
local map = map.googlemap(r.latitude, r.longitude, 11)
-- local map = map.openstreetmap(r.latitude, r.longitude, 11)
-- local flag = "<img src=\"http://www.iplocation.net/images/flags/%s.gif\" />" % r.country_code:lower()
local flag = "<img src=\"http://static.hltv.org/images/flag/%s.gif\" />" % r.country_code:lower()
return "%s <a href=\"%s\" target=\"_blank\">%s</a>" % {flag, map, v}
end
function format.completed_percent(r, v)
return string.format("%.1f%%", v)
end
function format.down_rate(d, v)
total["down_rate"] = (total["down_rate"] or 0) + v
return string.format("%.2f", v / 1000)
end
function format.up_rate(d, v)
total["up_rate"] = (total["up_rate"] or 0) + v
return string.format("%.2f", v / 1000)
end
function format.down_total(d, v)
return "<div title=\"%s B\">%s</div>" % {v, common.human_size(v)}
end
function format.up_total(d, v)
return format.down_total(d, v)
end
function json2table(json)
loadstring("j2t = " .. string.gsub(string.gsub(json, '([,%{])%s*\n?%s*"', '%1["'), '"%s*:%s*', '"]='))()
return j2t
end
function add_location(r)
for i, j in pairs(json2table(http.request(ip2geo.address % r.address))) do
if ip2geo.fields[i] then r[ip2geo.fields[i]] = j end
end
local location = {}
for _, k in ipairs({"country", "region", "city"}) do
if r[k] ~= "" and not tonumber(r[k]) then
table.insert(location, (r[k]:gsub("\u(%x%x%x%x)", "&#x%1")))
end
end
r["location"] = table.concat(location, "/")
end
function add_summary(list)
table.insert(list, {
["address"] = "TOTAL: " .. total["address"] .. " pcs.",
["down_rate"] = string.format("%.2f", total["down_rate"] / 1000),
["up_rate"] = string.format("%.2f", total["up_rate"] / 1000)
})
end
local list = rtorrent.multicall("p.", hash, 0, "address", "completed_percent", "client_version",
"down_rate", "up_rate", "up_total", "down_total")
for _, r in ipairs(list) do
add_location(r)
for k, v in pairs(r) do
r[k] = format[k] and format[k](r, v) or tostring(v)
end
end
f = SimpleForm("rtorrent", details["name"])
f.redirect = luci.dispatcher.build_url("admin/rtorrent/main")
f.reset = false
f.submit = false
if #list > 1 then add_summary(list) end
t = f:section(Table, list)
t.template = "rtorrent/list"
t.pages = common.get_torrent_pages(hash)
t.page = "Peer List"
AbstractValue.tooltip = function(self, s) self.hint = s return self end
t:option(DummyValue, "address", translate("Address")):tooltip(translate("Peer IP address")).rawhtml = true
t:option(DummyValue, "client_version", translate("Client")):tooltip(translate("Client version"))
t:option(DummyValue, "location", translate("Location")):tooltip(translate("Location: country/region/city")).rawhtml = true
t:option(DummyValue, "completed_percent", translate("Done")):tooltip(translate("Download done percent"))
t:option(DummyValue, "down_rate", translate("Down<br />Speed")):tooltip(translate("Download speed in kb/s"))
t:option(DummyValue, "up_rate", translate("Up<br />Speed")):tooltip(translate("Upload speed in kb/s"))
t:option(DummyValue, "down_total", translate("Downloaded")):tooltip(translate("Total downloaded")).rawhtml = true
t:option(DummyValue, "up_total", translate("Uploaded")):tooltip(translate("Total uploaded")).rawhtml = true
return f
| gpl-2.0 |
danielkitta/sigrok-util | debug/sysclk-lwla/sysclk-lwla-dissector.lua | 1 | 10456 | -- SysClk LWLA protocol dissector for Wireshark
--
-- Copyright (c) 2014,2015 Daniel Elstner <daniel.kitta@gmail.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 3 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, see <http://www.gnu.org/licenses/>.
-- Usage: wireshark -X lua_script:sysclk-lwla-dissector.lua
--
-- It is not advisable to install this dissector globally, since
-- it will try to interpret the communication of any USB device
-- using the vendor-specific interface class.
-- Create custom protocol for the LWLA logic analyzer.
p_lwla = Proto("lwla", "LWLA USB Protocol")
-- LWLA message type. For simplicity, the numerical value is the same
-- as the USB end point number the message is sent to or comes from.
local message_types = {
[2] = "Control command",
[4] = "Firmware transfer",
[6] = "Control response"
}
-- Known IDs of LWLA control commands.
local control_commands = {
[1] = "Read register",
[2] = "Write register",
[3] = "Read memory",
[5] = "Write ???",
[6] = "Read memory",
[7] = "Capture setup",
[8] = "Capture status"
}
-- Create the fields exhibited by the protocol.
p_lwla.fields.msgtype = ProtoField.uint8("lwla.msgtype", "Message Type", base.DEC, message_types)
p_lwla.fields.command = ProtoField.uint16("lwla.cmd", "Command ID", base.DEC, control_commands)
p_lwla.fields.memaddr = ProtoField.uint32("lwla.memaddr", "Memory Address", base.HEX_DEC)
p_lwla.fields.memlen = ProtoField.uint32("lwla.memlen", "Memory Read Length", base.HEX_DEC)
p_lwla.fields.regaddr = ProtoField.uint16("lwla.regaddr", "Register Address", base.HEX)
p_lwla.fields.regdata = ProtoField.uint32("lwla.regdata", "Register Value", base.HEX_DEC)
p_lwla.fields.stataddr = ProtoField.uint16("lwla.stataddr", "Status Memory Address", base.HEX)
p_lwla.fields.statlen = ProtoField.uint16("lwla.statlen", "Status Memory Read/Write Length", base.HEX_DEC)
p_lwla.fields.statdata = ProtoField.bytes("lwla.statdata", "Status Word")
p_lwla.fields.secdata = ProtoField.uint32("lwla.secdata", "Security Hash", base.HEX_DEC)
p_lwla.fields.unknown = ProtoField.bytes("lwla.unknown", "Unidentified message data")
-- Referenced USB URB dissector fields.
local f_urb_type = Field.new("usb.urb_type")
local f_transfer_type = Field.new("usb.transfer_type")
local f_endpoint = Field.new("usb.endpoint_number.endpoint")
-- Insert warning for undecoded leftover data.
local function warn_undecoded(tree, range)
local item = tree:add(p_lwla.fields.unknown, range)
item:add_expert_info(PI_UNDECODED, PI_WARN, "Leftover data")
end
-- Extract a 32-bit mixed endian word.
local function read_mixed_endian(range)
return range(0,2):le_uint() * 65536 + range(2,2):le_uint()
end
-- Un-shuffle the bytes of a 64-bit stat field.
local function read_stat_field(range)
return string.char(range(5,1):uint(), range(4,1):uint(), range(7,1):uint(), range(6,1):uint(),
range(1,1):uint(), range(0,1):uint(), range(3,1):uint(), range(2,1):uint())
end
-- Dissect LWLA1034 capture state.
local function dissect_capture_state(range, tree)
for i = 0, range:len() - 8, 8 do
tree:add(p_lwla.fields.statdata, range(i,8), read_stat_field(range(i,8)))
end
end
-- Dissect LWLA control command messages.
local function dissect_command(range, pinfo, tree)
if range:len() < 4 then
return 0
end
tree:add_le(p_lwla.fields.command, range(0,2))
local command = range(0,2):le_uint()
if command == 1 then -- read register
if range:len() == 4 then
tree:add_le(p_lwla.fields.regaddr, range(2,2))
pinfo.cols.info = string.format("Cmd %d: read reg 0x%04X",
command, range(2,2):le_uint())
return 4
end
elseif command == 2 then -- write register
if range:len() == 8 then
tree:add_le(p_lwla.fields.regaddr, range(2,2))
local regval = read_mixed_endian(range(4,4))
tree:add(p_lwla.fields.regdata, range(4,4), regval)
pinfo.cols.info = string.format("Cmd %d: write reg 0x%04X value 0x%08X",
command, range(2,2):le_uint(), regval)
return 8
end
elseif command == 5 then -- write security hash?
if range:len() == 66 then
local infotext = string.format("Cmd %d: write security hash?", command)
for i = 2, 62, 4 do
local value = read_mixed_endian(range(i,4))
tree:add(p_lwla.fields.secdata, range(i,4), value)
infotext = string.format("%s %02X", infotext, value)
end
pinfo.cols.info = infotext
return 66
end
elseif command == 3 or command == 6 then -- read memory at address
if range:len() == 10 then
local memaddr = read_mixed_endian(range(2,4))
local memlen = read_mixed_endian(range(6,4))
tree:add(p_lwla.fields.memaddr, range(2,4), memaddr)
tree:add(p_lwla.fields.memlen, range(6,4), memlen)
pinfo.cols.info = string.format("Cmd %d: read mem 0x%06X length %d",
command, memaddr, memlen)
return 10
end
elseif command == 7 then -- capture setup (LWLA1034)
if range:len() >= 6 then
tree:add_le(p_lwla.fields.stataddr, range(2,2))
tree:add_le(p_lwla.fields.statlen, range(4,2))
local len = 8 * range(4,2):le_uint()
if range:len() ~= len + 6 then
warn_undecoded(tree, range(6))
return 6
end
dissect_capture_state(range(6,len), tree)
pinfo.cols.info = string.format("Cmd %d: setup 0x%X length %d",
command, range(2,2):le_uint(), range(4,2):le_uint())
return 6 + len
end
elseif command == 8 then -- capture status (LWLA1034)
if range:len() == 6 then
tree:add_le(p_lwla.fields.stataddr, range(2,2))
tree:add_le(p_lwla.fields.statlen, range(4,2))
pinfo.cols.info = string.format("Cmd %d: state 0x%X length %d",
command, range(2,2):le_uint(), range(4,2):le_uint())
return 6
end
end
warn_undecoded(tree, range(2))
return 2
end
-- Dissect LWLA control response messages.
local function dissect_response(range, pinfo, tree)
-- The heuristics below are ugly and prone to fail, but they do the job
-- for the purposes this dissector was written.
if range:len() == 40 or range:len() == 80 then -- heuristic: response to command 8
dissect_capture_state(range, tree)
pinfo.cols.info = string.format("Ret 8: state length %d", range:len() / 8)
return range:len()
elseif range:len() == 4 then -- heuristic: response to command 1
local value = read_mixed_endian(range(0,4))
tree:add(p_lwla.fields.regdata, range(0,4), value)
pinfo.cols.info = string.format("Ret 1: reg value 0x%08X", value)
return 4
elseif range:len() == 1000 or range:len() == 552 then -- heuristic: response to command 3
pinfo.cols.info = string.format("Ret 3: mem data length %d", range:len() / 4)
return 0
elseif range:len() >= 18 and range:len() % 18 == 0 then -- heuristic: response to command 6
pinfo.cols.info = string.format("Ret 6: mem data length %d", range:len() * 2 / 9)
return 0
else
return 0
end
end
-- Main LWLA dissector function.
function p_lwla.dissector(tvb, pinfo, tree)
local transfer_type = tonumber(tostring(f_transfer_type()))
-- Bulk transfers only.
if transfer_type == 3 then
local urb_type = tonumber(tostring(f_urb_type()))
local endpoint = tonumber(tostring(f_endpoint()))
-- Payload-carrying packets only.
if (urb_type == 83 and (endpoint == 2 or endpoint == 4))
or (urb_type == 67 and endpoint == 6)
then
pinfo.cols.protocol = p_lwla.name
local subtree = tree:add(p_lwla, tvb(), "LWLA")
subtree:add(p_lwla.fields.msgtype, endpoint):set_generated()
-- Dispatch to message-specific dissection handler.
if endpoint == 2 then
return dissect_command(tvb, pinfo, subtree)
elseif endpoint == 4 then
pinfo.cols.info = "FPGA bitstream"
return 0
elseif endpoint == 6 then
return dissect_response(tvb, pinfo, subtree)
end
end
end
return 0
end
-- Register LWLA protocol dissector during initialization.
function p_lwla.init()
-- local usb_product_dissectors = DissectorTable.get("usb.product")
-- Dissection by vendor+product ID requires that Wireshark can get the
-- the device descriptor. Making a USB device available inside VirtualBox
-- will make it inaccessible from Linux, so Wireshark cannot fetch the
-- descriptor by itself. However, it is sufficient if the VirtualBox
-- guest requests the descriptor once while Wireshark is capturing.
-- usb_product_dissectors:add(0x29616688, p_lwla) -- SysClk LWLA1016
-- usb_product_dissectors:add(0x29616689, p_lwla) -- SysClk LWLA1034
-- Addendum: Protocol registration based on product ID does not always
-- work as desired. Register the protocol on the interface class instead.
-- The downside is that it would be a bad idea to put this into the global
-- configuration, so one has to make do with -X lua_script: for now.
local usb_bulk_dissectors = DissectorTable.get("usb.bulk")
-- For some reason the "unknown" class ID is sometimes 0xFF and sometimes
-- 0xFFFF. Register both to make it work all the time.
usb_bulk_dissectors:add(0xFF, p_lwla)
usb_bulk_dissectors:add(0xFFFF, p_lwla)
end
| gpl-3.0 |
mercury233/ygopro-scripts | c90812044.lua | 2 | 2565 | --連鎖召喚
function c90812044.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c90812044.target)
e1:SetOperation(c90812044.activate)
c:RegisterEffect(e1)
end
function c90812044.cfilter(c)
return c:IsFaceup() and c:IsType(TYPE_XYZ)
end
function c90812044.filter(c,e,tp,rk)
return c:IsType(TYPE_XYZ) and c:GetRank()<rk
and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and Duel.GetLocationCountFromEx(tp,tp,nil,c)>0
end
function c90812044.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local g=Duel.GetMatchingGroup(c90812044.cfilter,tp,LOCATION_MZONE,0,nil)
local rg,rk=g:GetMinGroup(Card.GetRank)
if chkc then return rg:IsContains(chkc) end
if chk==0 then return g:GetCount()>=2 and rg:IsExists(Card.IsCanBeEffectTarget,1,nil,e)
and Duel.IsExistingMatchingCard(c90812044.filter,tp,LOCATION_EXTRA,0,1,nil,e,tp,rk) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
local sg=rg:FilterSelect(tp,Card.IsCanBeEffectTarget,1,1,nil,e)
Duel.SetTargetCard(sg)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA)
end
function c90812044.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if not tc:IsRelateToEffect(e) or tc:IsFacedown() then return end
local rk=tc:GetRank()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c90812044.filter,tp,LOCATION_EXTRA,0,1,1,nil,e,tp,rk)
local sc=g:GetFirst()
if sc and Duel.SpecialSummon(sc,0,tp,tp,false,false,POS_FACEUP)~=0 then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_DIRECT_ATTACK)
e1:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
sc:RegisterEffect(e1,true)
sc:RegisterFlagEffect(90812044,RESET_EVENT+RESETS_STANDARD,0,1)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_PHASE+PHASE_END)
e2:SetCountLimit(1)
e2:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e2:SetLabelObject(sc)
e2:SetCondition(c90812044.retcon)
e2:SetOperation(c90812044.retop)
Duel.RegisterEffect(e2,tp)
end
end
function c90812044.retcon(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
if tc:GetFlagEffect(90812044)~=0 then
return true
else
e:Reset()
return false
end
end
function c90812044.retop(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
Duel.SendtoDeck(tc,nil,SEQ_DECKSHUFFLE,REASON_EFFECT)
end
| gpl-2.0 |
linushsao/marsu_game-linus-v0.2 | server_side/irc/callback.lua | 2 | 1043 | -- This file is licensed under the terms of the BSD 2-clause license.
-- See LICENSE.txt for details.
minetest.register_on_joinplayer(function(player)
local name = player:get_player_name()
if irc.connected and irc.config.send_join_part then
irc:say("*** "..name.." joined the game")
end
end)
minetest.register_on_leaveplayer(function(player, timed_out)
local name = player:get_player_name()
if irc.connected and irc.config.send_join_part then
irc:say("*** "..name.." left the game"..
(timed_out and " (Timed out)" or ""))
end
end)
minetest.register_on_chat_message(function(name, message)
if not irc.connected
or message:sub(1, 1) == "/"
or message:sub(1, 5) == "[off]"
or not irc.joined_players[name]
or (not minetest.check_player_privs(name, {shout=true})) then
return
end
local nl = message:find("\n", 1, true)
if nl then
message = message:sub(1, nl - 1)
end
irc:say(irc:playerMessage(name, message))
end)
minetest.register_on_shutdown(function()
irc:disconnect("Game shutting down.")
end)
| gpl-3.0 |
mercury233/ygopro-scripts | c74311226.lua | 2 | 1472 | --海皇の竜騎隊
function c74311226.initial_effect(c)
--direct attack
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_DIRECT_ATTACK)
e1:SetRange(LOCATION_MZONE)
e1:SetTargetRange(LOCATION_MZONE,0)
e1:SetTarget(c74311226.datg)
c:RegisterEffect(e1)
--search
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(74311226,0))
e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetCode(EVENT_TO_GRAVE)
e2:SetCondition(c74311226.thcon)
e2:SetTarget(c74311226.thtg)
e2:SetOperation(c74311226.thop)
c:RegisterEffect(e2)
end
function c74311226.datg(e,c)
return c:IsLevelBelow(3) and c:IsRace(RACE_SEASERPENT)
end
function c74311226.thcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsReason(REASON_COST) and re:IsActivated() and re:IsActiveType(TYPE_MONSTER)
and re:GetHandler():IsAttribute(ATTRIBUTE_WATER)
end
function c74311226.thfilter(c)
return not c:IsCode(74311226) and c:IsRace(RACE_SEASERPENT) and c:IsAbleToHand()
end
function c74311226.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c74311226.thop(e,tp,eg,ep,ev,re,r,rp,c)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c74311226.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 |
notcake/gcompute | lua/gcompute/sourcefile.lua | 1 | 3788 | local self = {}
GCompute.SourceFile = GCompute.MakeConstructor (self)
local nextAnonymousId = 0
--[[
SourceFile
SourceFiles have a one to one relationship with CompilationUnits.
A SourceFile will create a CompilationUnit if it doesn't already have one
when GetCompilationUnit is called.
]]
--[[
Events:
CacheableChanged (cacheable)
Fired when this source file's cacheability has changed.
CompilationUnitCreated (CompilataionUnit compilationUnit)
Fired when this source file has created a compilation unit for itself.
IdChanged (oldId, newId)
Fired when this source file's id has changed.
PathChanged (oldPath, newPath)
Fired when this source file's path has changed.
]]
function self:ctor ()
self.Id = ""
self.Path = ""
self.Code = ""
self.CodeHash = 0
self.CompilationUnit = nil
self.Cacheable = true
self.ExpiryTime = 0
GCompute.EventProvider (self)
self:AssignId ()
self:ResetExpiryTime ()
GCompute.SourceFileCache:Add (self)
end
function self:AssignId ()
local id = "@dynamic_" .. tostring (nextAnonymousId)
nextAnonymousId = nextAnonymousId + 1
self:SetId (id)
end
function self:CanCache ()
return self.Cacheable
end
function self:ComputeCodeHash ()
self.CodeHash = tonumber (util.CRC (self.Code))
end
function self:ComputeMemoryUsage (memoryUsageReport)
memoryUsageReport = memoryUsageReport or GCompute.MemoryUsageReport ()
if memoryUsageReport:IsCounted (self) then return end
memoryUsageReport:CreditTableStructure ("Source Files", self)
memoryUsageReport:CreditString ("Source Files", self.Path)
memoryUsageReport:CreditString ("Source Code", self.Code)
if self.CompilationUnit then
self.CompilationUnit:ComputeMemoryUsage (memoryUsageReport)
end
return memoryUsageReport
end
function self:dtor ()
GCompute.SourceFileCache:Remove (self)
end
function self:GetCode ()
return self.Code
end
function self:GetCodeHash ()
return self.CodeHash
end
--- Returns the CompilationUnit associated with this SourceFile and creates one if it doesn't already exist
-- @return The CompilationUnit associated with this SourceFile
function self:GetCompilationUnit ()
if not self.CompilationUnit then
self.CompilationUnit = GCompute.CompilationUnit (self)
self:DispatchEvent ("CompilationUnitCreated", self.CompilationUnit)
end
return self.CompilationUnit
end
function self:GetExpiryTime ()
return self.ExpiryTime
end
function self:GetId ()
return self.Id
end
function self:GetPath ()
return self.Path
end
function self:HasCompilationUnit ()
return self.CompilationUnit and true or false
end
function self:HasExpired ()
return SysTime () >= self.ExpiryTime
end
function self:HasPath ()
return self.Path and self.Path ~= nil or false
end
function self:ResetExpiryTime (timespan)
timespan = timespan or 300 -- Default expiry time is 5 minutes
self.ExpiryTime = SysTime () + timespan
end
function self:SetCacheable (cacheable)
if self.Cacheable == cacheable then return end
self.Cacheable = cacheable
self:DispatchEvent ("CacheableChanged", cacheable)
end
function self:SetCode (code)
self.Code = code
self:ComputeCodeHash ()
end
function self:SetId (id)
if not id or id == "" then self:AssignId () return end
if self.Id == id then return end
local oldId = self.Id
self.Id = id
self:DispatchEvent ("IdChanged", oldId, self.Id)
end
function self:SetPath (path)
path = path or ""
if self.Path == path then return end
local oldPath = self.Path
self.Path = path
self:DispatchEvent ("PathChanged", oldPath, self.Path)
if self:HasPath () then
self:SetId (path)
else
self:AssignId ()
end
end | gpl-3.0 |
mercury233/ygopro-scripts | c46435376.lua | 2 | 1852 | --インフェルニティ・セイジ
function c46435376.initial_effect(c)
--Discard
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(46435376,0))
e1:SetCategory(CATEGORY_HANDES)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1,46435376)
e1:SetTarget(c46435376.hdtg)
e1:SetOperation(c46435376.hdop)
c:RegisterEffect(e1)
--To GY
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(46435376,1))
e2:SetCategory(CATEGORY_TOGRAVE)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_DELAY)
e2:SetCode(EVENT_TO_GRAVE)
e2:SetCountLimit(1,46435377)
e2:SetTarget(c46435376.tgtg)
e2:SetOperation(c46435376.tgop)
c:RegisterEffect(e2)
end
function c46435376.hdtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFieldGroupCount(tp,LOCATION_HAND,0)>0 end
local g=Duel.GetFieldGroup(tp,LOCATION_HAND,0)
Duel.SetOperationInfo(0,CATEGORY_HANDES,nil,0,tp,g:GetCount())
end
function c46435376.hdop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetFieldGroup(tp,LOCATION_HAND,0)
if g:GetCount()==0 then return end
Duel.SendtoGrave(g,REASON_EFFECT+REASON_DISCARD)
end
function c46435376.tgfilter(c)
return c:IsSetCard(0xb) and c:IsType(TYPE_MONSTER) and c:IsAbleToGrave()
end
function c46435376.tgtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFieldGroupCount(tp,LOCATION_HAND,0)==0
and Duel.IsExistingMatchingCard(c46435376.tgfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_DECK)
end
function c46435376.tgop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetFieldGroupCount(tp,LOCATION_HAND,0)==0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c46435376.tgfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoGrave(g,REASON_EFFECT)
end
end
end
| gpl-2.0 |
Zenny89/darkstar | scripts/zones/Dangruf_Wadi/npcs/qm4.lua | 17 | 1905 | -----------------------------------
-- NPC: ??? (QM4)
-- Type: Grasswix dice roll game part 2
-- @zone: 191
-- Involved in quest "As Thick As Thieves"
-----------------------------------
package.loaded["scripts/zones/Dangruf_Wadi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Dangruf_Wadi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local thickAsThievesGamblingCS = player:getVar("thickAsThievesGamblingCS");
if (thickAsThievesGamblingCS == 3) then
if (trade:hasItemQty(534,1) and trade:getItemCount() == 1) then -- Trade 1x gaussbit wildgrass
local rand1 = math.random(1,999);
local rand2 = math.random(1,999);
if (rand1 > rand2) then
player:startEvent(0x0089,1092,0,rand1,rand2); -- complete 2/3 gamble mini quest
else
player:startEvent(0x008c,0,0,rand1,rand2); -- player looses
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
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 == 0x008c and option == 1) then -- player looses dice game
player:tradeComplete();
player:setVar("thickAsThievesGamblingCS",2);
elseif (csid == 0x0089 and option == 0) then -- player wins dice game
player:tradeComplete();
player:setVar("thickAsThievesGamblingCS",4);
end
end;
| gpl-3.0 |
mercury233/ygopro-scripts | c69436288.lua | 2 | 3083 | --デス・クラーケン
function c69436288.initial_effect(c)
aux.AddCodeList(c,22702055)
--SpecialSummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(69436288,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TOHAND+CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetRange(LOCATION_HAND)
e1:SetHintTiming(0,TIMINGS_CHECK_MONSTER+TIMING_END_PHASE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCountLimit(1,69436288)
e1:SetCondition(c69436288.spcon)
e1:SetTarget(c69436288.sptg)
e1:SetOperation(c69436288.spop)
c:RegisterEffect(e1)
--NegateAttack
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(69436288,1))
e2:SetCategory(CATEGORY_TOHAND)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EVENT_ATTACK_ANNOUNCE)
e2:SetCountLimit(1,69436289)
e2:SetCondition(c69436288.thcon)
e2:SetTarget(c69436288.thtg)
e2:SetOperation(c69436288.thop)
c:RegisterEffect(e2)
end
function c69436288.spcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsEnvironment(22702055)
end
function c69436288.thfilter(c)
return c:IsFaceup() and not c:IsCode(69436288) and c:IsAttribute(ATTRIBUTE_WATER) and c:IsAbleToHand()
end
function c69436288.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return false end
if chk==0 then return Duel.IsExistingTarget(c69436288.thfilter,tp,LOCATION_MZONE,0,1,nil)
and Duel.IsExistingTarget(aux.TRUE,tp,0,LOCATION_MZONE,1,nil)
and Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND)
local g1=Duel.SelectTarget(tp,c69436288.thfilter,tp,LOCATION_MZONE,0,1,1,nil)
e:SetLabelObject(g1:GetFirst())
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g2=Duel.SelectTarget(tp,aux.TRUE,tp,0,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g1,1,0,0)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g2,1,0,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c69436288.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
local hc=e:GetLabelObject()
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
if Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)~=0 then
local tc=g:GetFirst()
if tc==hc then tc=g:GetNext() end
if hc:IsRelateToEffect(e) and hc:IsControler(tp)
and Duel.SendtoHand(hc,nil,REASON_EFFECT)~=0 and hc:IsLocation(LOCATION_HAND)
and tc:IsRelateToEffect(e) and tc:IsControler(1-tp) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
end
function c69436288.thcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetAttacker():IsControler(1-tp)
end
function c69436288.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToHand() end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,e:GetHandler(),1,0,0)
end
function c69436288.thop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and Duel.SendtoHand(c,nil,REASON_EFFECT)>0 and c:IsLocation(LOCATION_HAND) then
Duel.NegateAttack()
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c41767843.lua | 4 | 1401 | --幻奏の音女スコア
function c41767843.initial_effect(c)
--atkdef 0
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(41767843,0))
e1:SetCategory(CATEGORY_ATKCHANGE+CATEGORY_DEFCHANGE)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_PRE_DAMAGE_CALCULATE)
e1:SetRange(LOCATION_HAND)
e1:SetCondition(c41767843.condition)
e1:SetCost(c41767843.cost)
e1:SetOperation(c41767843.operation)
c:RegisterEffect(e1)
end
function c41767843.condition(e,tp,eg,ep,ev,re,r,rp)
local a=Duel.GetAttacker()
local d=Duel.GetAttackTarget()
if not d then return false end
if a:IsControler(1-tp) then a,d=d,a end
return a:IsSetCard(0x9b) and a:IsRelateToBattle() and (d:GetAttack()>0 or d:GetDefense()>0)
end
function c41767843.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 c41767843.operation(e,tp,eg,ep,ev,re,r,rp)
local a=Duel.GetAttacker()
local d=Duel.GetAttackTarget()
if a:IsControler(1-tp) then d=a end
if not d:IsRelateToBattle() or d:IsFacedown() then return end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SET_ATTACK_FINAL)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
e1:SetValue(0)
d:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_SET_DEFENSE_FINAL)
d:RegisterEffect(e2)
end
| gpl-2.0 |
lex128/mtasa-blue | Server/mods/deathmatch/premake5.lua | 2 | 1942 | project "Deathmatch"
language "C++"
kind "SharedLib"
targetname "deathmatch"
targetdir(buildpath("server/mods/deathmatch"))
pchheader "StdInc.h"
pchsource "StdInc.cpp"
filter "system:windows"
includedirs { "../../../vendor/sparsehash/src/windows" }
filter {}
includedirs {
"../../sdk",
"../../../vendor/bochs",
"../../../vendor/pme",
"../../../vendor/zip",
"../../../vendor/zlib",
"../../../vendor/pcre",
"../../../vendor/json-c",
"../../../vendor/bob_withers",
"../../../vendor/lua/src",
"../../../Shared/mods/deathmatch/logic",
"../../../Shared/animation",
"../../../Shared/publicsdk/include",
"../../../vendor/sparsehash/src/",
"logic",
"utils",
"."
}
defines { "SDK_WITH_BCRYPT" }
links {
"Lua_Server", "sqlite", "ehs", "cryptopp", "pme", "pcre", "json-c", "zip", "zlib", "blowfish_bcrypt",
}
vpaths {
["Headers/*"] = {"**.h", "../../../Shared/mods/deathmatch/**.h", "../../**.h"},
["Sources/*"] = {"**.cpp", "../../../Shared/mods/deathmatch/**.cpp", "../../../Shared/**.cpp", "../../../vendor/**.cpp", "../../**.cpp"},
["*"] = "premake5.lua"
}
files {
"premake5.lua",
"**.h",
"**.cpp",
"../../../Shared/mods/deathmatch/logic/**.cpp",
"../../../Shared/mods/deathmatch/logic/**.h",
"../../../Shared/animation/CEasingCurve.cpp",
"../../../Shared/animation/CPositionRotationAnimation.cpp",
"../../version.h",
-- Todo: Replace these two by using the CryptoPP functions instead
"../../../vendor/bochs/bochs_internal/crc32.cpp",
}
filter "system:windows"
includedirs { "../../../vendor/pthreads/include" }
buildoptions { "-Zm130" }
links { "ws2_32", "pthread" }
filter "system:not windows"
buildoptions { "-Wno-narrowing" } -- We should fix the warnings at some point
links { "rt" }
buildoptions { "-pthread" }
linkoptions { "-pthread" }
filter "platforms:x64"
targetdir(buildpath("server/x64"))
| gpl-3.0 |
AntonioModer/fuccboiGDX | fuccboi/resources/particles/sperm/loveframes/objects/columnlist.lua | 3 | 17109 | --[[------------------------------------------------
-- Love Frames - A GUI library for LOVE --
-- Copyright (c) 2013 Kenny Shields --
--]]------------------------------------------------
-- columnlist object
local newobject = loveframes.NewObject("columnlist", "loveframes_object_columnlist", true)
--[[---------------------------------------------------------
- func: initialize()
- desc: intializes the element
--]]---------------------------------------------------------
function newobject:initialize()
self.type = "columnlist"
self.width = 300
self.height = 100
self.columnheight = 16
self.buttonscrollamount = 200
self.mousewheelscrollamount = 1500
self.autoscroll = false
self.dtscrolling = true
self.internal = false
self.selectionenabled = true
self.multiselect = false
self.children = {}
self.internals = {}
self.OnRowClicked = nil
self.OnRowRightClicked = nil
self.OnRowSelected = nil
self.OnScroll = nil
local list = loveframes.objects["columnlistarea"]:new(self)
table.insert(self.internals, list)
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 parent = self.parent
local base = loveframes.base
local children = self.children
local internals = self.internals
local update = self.Update
self:CheckHover()
-- 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
for k, v in ipairs(internals) do
v:update(dt)
end
for k, v in ipairs(children) do
v:update(dt)
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 children = self.children
local internals = self.internals
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.DrawColumnList or skins[defaultskin].DrawColumnList
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
for k, v in ipairs(internals) do
v:draw()
end
for k, v in ipairs(children) do
v:draw()
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 hover = self.hover
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
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: mousereleased(x, y, button)
- desc: called when the player releases a mouse button
--]]---------------------------------------------------------
function newobject:mousereleased(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 children = self.children
local internals = self.internals
for k, v in ipairs(internals) do
v:mousereleased(x, y, button)
end
for k, v in ipairs(children) do
v:mousereleased(x, y, button)
end
end
--[[---------------------------------------------------------
- func: Adjustchildren()
- desc: adjusts the width of the object's children
--]]---------------------------------------------------------
function newobject:AdjustColumns()
local width = self.width
local bar = self.internals[1].bar
if bar then
width = width - self.internals[1].internals[1].width
end
local children = self.children
local numchildren = #children
local columnwidth = width/numchildren
local x = 0
for k, v in ipairs(children) do
if bar then
v:SetWidth(columnwidth)
else
v:SetWidth(columnwidth)
end
v:SetPos(x, 0)
x = x + columnwidth
end
end
--[[---------------------------------------------------------
- func: AddColumn(name)
- desc: gives the object a new column with the specified
name
--]]---------------------------------------------------------
function newobject:AddColumn(name)
local internals = self.internals
local list = internals[1]
local width = self.width
local height = self.height
loveframes.objects["columnlistheader"]:new(name, self)
self:AdjustColumns()
list:SetSize(width, height)
list:SetPos(0, 0)
end
--[[---------------------------------------------------------
- func: AddRow(...)
- desc: adds a row of data to the object's list
--]]---------------------------------------------------------
function newobject:AddRow(...)
local arg = {...}
local internals = self.internals
local list = internals[1]
list:AddRow(arg)
end
--[[---------------------------------------------------------
- func: Getchildrenize()
- desc: gets the size of the object's children
--]]---------------------------------------------------------
function newobject:GetColumnSize()
local children = self.children
local numchildren = #self.children
if numchildren > 0 then
local column = self.children[1]
local colwidth = column.width
local colheight = column.height
return colwidth, colheight
else
return 0, 0
end
end
--[[---------------------------------------------------------
- func: SetSize(width, height)
- desc: sets the object's size
--]]---------------------------------------------------------
function newobject:SetSize(width, height)
local internals = self.internals
local list = internals[1]
self.width = width
self.height = height
self:AdjustColumns()
list:SetSize(width, height)
list:SetPos(0, 0)
list:CalculateSize()
list:RedoLayout()
end
--[[---------------------------------------------------------
- func: SetWidth(width)
- desc: sets the object's width
--]]---------------------------------------------------------
function newobject:SetWidth(width)
local internals = self.internals
local list = internals[1]
self.width = width
self:AdjustColumns()
list:SetSize(width)
list:SetPos(0, 0)
list:CalculateSize()
list:RedoLayout()
end
--[[---------------------------------------------------------
- func: SetHeight(height)
- desc: sets the object's height
--]]---------------------------------------------------------
function newobject:SetHeight(height)
local internals = self.internals
local list = internals[1]
self.height = height
self:AdjustColumns()
list:SetSize(height)
list:SetPos(0, 0)
list:CalculateSize()
list:RedoLayout()
end
--[[---------------------------------------------------------
- func: SetMaxColorIndex(num)
- desc: sets the object's max color index for
alternating row colors
--]]---------------------------------------------------------
function newobject:SetMaxColorIndex(num)
local internals = self.internals
local list = internals[1]
list.colorindexmax = num
end
--[[---------------------------------------------------------
- func: Clear()
- desc: removes all items from the object's list
--]]---------------------------------------------------------
function newobject:Clear()
local internals = self.internals
local list = internals[1]
list:Clear()
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 internals = self.internals
local list = internals[1]
local scrollbar = list:GetScrollBar()
self.autoscroll = bool
if list then
if scrollbar then
scrollbar.autoscroll = bool
end
end
end
--[[---------------------------------------------------------
- func: SetButtonScrollAmount(speed)
- desc: sets the scroll amount of the object's scrollbar
buttons
--]]---------------------------------------------------------
function newobject:SetButtonScrollAmount(amount)
self.buttonscrollamount = amount
self.internals[1].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
self.internals[1].mousewheelscrollamount = amount
end
--[[---------------------------------------------------------
- func: GetMouseWheelScrollAmount()
- desc: gets the scroll amount of the mouse wheel
--]]---------------------------------------------------------
function newobject:GetButtonScrollAmount()
return self.mousewheelscrollamount
end
--[[---------------------------------------------------------
- func: SetColumnHeight(height)
- desc: sets the height of the object's columns
--]]---------------------------------------------------------
function newobject:SetColumnHeight(height)
local children = self.children
local internals = self.internals
local list = internals[1]
self.columnheight = height
for k, v in ipairs(children) do
v:SetHeight(height)
end
list:CalculateSize()
list:RedoLayout()
end
--[[---------------------------------------------------------
- func: SetDTScrolling(bool)
- desc: sets whether or not the object should use delta
time when scrolling
--]]---------------------------------------------------------
function newobject:SetDTScrolling(bool)
self.dtscrolling = bool
self.internals[1].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
--[[---------------------------------------------------------
- func: SelectRow(row, ctrl)
- desc: selects the specfied row in the object's list
of rows
--]]---------------------------------------------------------
function newobject:SelectRow(row, ctrl)
local selectionenabled = self.selectionenabled
if not selectionenabled then
return
end
local list = self.internals[1]
local children = list.children
local multiselect = self.multiselect
local onrowselected = self.OnRowSelected
for k, v in ipairs(children) do
if v == row then
if v.selected and ctrl then
v.selected = false
else
v.selected = true
if onrowselected then
onrowselected(self, row, row:GetColumnData())
end
end
elseif v ~= row then
if not (multiselect and ctrl) then
v.selected = false
end
end
end
end
--[[---------------------------------------------------------
- func: DeselectRow(row)
- desc: deselects the specfied row in the object's list
of rows
--]]---------------------------------------------------------
function newobject:DeselectRow(row)
row.selected = false
end
--[[---------------------------------------------------------
- func: GetSelectedRows()
- desc: gets the object's selected rows
--]]---------------------------------------------------------
function newobject:GetSelectedRows()
local rows = {}
local list = self.internals[1]
local children = list.children
for k, v in ipairs(children) do
if v.selected then
table.insert(rows, v)
end
end
return rows
end
--[[---------------------------------------------------------
- func: SetSelectionEnabled(bool)
- desc: sets whether or not the object's rows can be
selected
--]]---------------------------------------------------------
function newobject:SetSelectionEnabled(bool)
self.selectionenabled = bool
end
--[[---------------------------------------------------------
- func: GetSelectionEnabled()
- desc: gets whether or not the object's rows can be
selected
--]]---------------------------------------------------------
function newobject:GetSelectionEnabled()
return self.selectionenabled
end
--[[---------------------------------------------------------
- func: SetMultiselectEnabled(bool)
- desc: sets whether or not the object can have more
than one row selected
--]]---------------------------------------------------------
function newobject:SetMultiselectEnabled(bool)
self.multiselect = bool
end
--[[---------------------------------------------------------
- func: GetMultiselectEnabled()
- desc: gets whether or not the object can have more
than one row selected
--]]---------------------------------------------------------
function newobject:GetMultiselectEnabled()
return self.multiselect
end
--[[---------------------------------------------------------
- func: RemoveColumn(id)
- desc: removes a column
--]]---------------------------------------------------------
function newobject:RemoveColumn(id)
local children = self.children
for k, v in ipairs(children) do
if k == id then
v:Remove()
end
end
end
--[[---------------------------------------------------------
- func: SetColumnName(id, name)
- desc: sets a column's name
--]]---------------------------------------------------------
function newobject:SetColumnName(id, name)
local children = self.children
for k, v in ipairs(children) do
if k == id then
v.name = name
end
end
end
--[[---------------------------------------------------------
- func: SizeToChildren(max)
- desc: sizes the object to match the combined height
of its children
- note: Credit to retupmoc258, the original author of
this method. This version has a few slight
modifications.
--]]---------------------------------------------------------
function newobject:SizeToChildren(max)
local oldheight = self.height
local list = self.internals[1]
local listchildren = list.children
local children = self.children
local width = self.width
local buf = children[1].height
local h = listchildren[1].height
local c = #listchildren
local height = buf + h*c
if max then
height = math.min(max, oldheight)
end
self:SetSize(width, height)
self:AdjustColumns()
end
--[[---------------------------------------------------------
- func: RemoveRow(id)
- desc: removes a row from the object's list
--]]---------------------------------------------------------
function newobject:RemoveRow(id)
local list = self.internals[1]
local listchildren = list.children
local row = listchildren[id]
if row then
row:Remove()
end
list:CalculateSize()
list:RedoLayout()
end
--[[---------------------------------------------------------
- func: SetRowColumnText(text, rowid, columnid)
- desc: sets the text of the of specific column in the
specified row
--]]---------------------------------------------------------
function newobject:SetRowColumnText(text, rowid, columnid)
local list = self.internals[1]
local listchildren = list.children
local row = listchildren[rowid]
if row and row.columndata[columnid]then
row.columndata[columnid] = text
end
end
--[[---------------------------------------------------------
- func: SetRowColumnData(rowid, columndata)
- desc: sets the columndata of the specified row
--]]---------------------------------------------------------
function newobject:SetRowColumnData(rowid, columndata)
local list = self.internals[1]
local listchildren = list.children
local row = listchildren[rowid]
if row then
for k, v in ipairs(columndata) do
row.columndata[k] = tostring(v)
end
end
end | mit |
mercury233/ygopro-scripts | c83027236.lua | 2 | 1137 | --ライト・オブ・デストラクション
function c83027236.initial_effect(c)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--discard deck
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(83027236,0))
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e2:SetCategory(CATEGORY_DECKDES)
e2:SetCode(EVENT_TO_GRAVE)
e2:SetRange(LOCATION_SZONE)
e2:SetCondition(c83027236.condtion)
e2:SetTarget(c83027236.target)
e2:SetOperation(c83027236.operation)
c:RegisterEffect(e2)
end
function c83027236.cfilter(c,tp)
return c:IsPreviousLocation(LOCATION_DECK) and c:IsPreviousControler(tp)
end
function c83027236.condtion(e,tp,eg,ep,ev,re,r,rp)
if not re then return false end
local rc=re:GetHandler()
return rp==1-tp and bit.band(r,REASON_EFFECT)~=0 and eg:IsExists(c83027236.cfilter,1,nil,1-tp)
end
function c83027236.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DECKDES,nil,0,1-tp,3)
end
function c83027236.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.DiscardDeck(1-tp,3,REASON_EFFECT)
end
| gpl-2.0 |
mercury233/ygopro-scripts | c65626958.lua | 2 | 2433 | --極星獣グリンブルスティ
function c65626958.initial_effect(c)
--substitute
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(61777313)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_SUMMON_SUCCESS)
e2:SetProperty(EFFECT_FLAG_DELAY)
e2:SetCountLimit(1,65626958)
e2:SetTarget(c65626958.sptg)
e2:SetOperation(c65626958.spop)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e3)
--to hand
local e4=Effect.CreateEffect(c)
e4:SetCategory(CATEGORY_TOHAND)
e4:SetType(EFFECT_TYPE_IGNITION)
e4:SetProperty(EFFECT_FLAG_CARD_TARGET)
e4:SetRange(LOCATION_MZONE)
e4:SetCountLimit(1,65626959)
e4:SetTarget(c65626958.thtg)
e4:SetOperation(c65626958.thop)
c:RegisterEffect(e4)
end
function c65626958.spfilter(c,e,tp)
return c:IsSetCard(0x42) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c65626958.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c65626958.spfilter,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c65626958.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,c65626958.spfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
function c65626958.thfilter(c)
return c:IsSetCard(0x42) and c:IsType(TYPE_MONSTER) and not c:IsCode(65626958) and c:IsAbleToHand()
end
function c65626958.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c65626958.thfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c65626958.thfilter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectTarget(tp,c65626958.thfilter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0)
end
function c65626958.thop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
end
end
| gpl-2.0 |
cbeck88/cegui-mirror | cegui/src/ScriptModules/Lua/support/tolua++bin/lua/define.lua | 14 | 1749 | -- tolua: define class
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- $Id$
-- This code is free software; you can redistribute it and/or modify it.
-- The software provided hereunder is on an "as is" basis, and
-- the author has no obligation to provide maintenance, support, updates,
-- enhancements, or modifications.
-- Define class
-- Represents a numeric const definition
-- The following filds are stored:
-- name = constant name
classDefine = {
name = '',
}
classDefine.__index = classDefine
setmetatable(classDefine,classFeature)
-- register define
function classDefine:register (pre)
if not self:check_public_access() then
return
end
pre = pre or ''
output(pre..'tolua_constant(tolua_S,"'..self.lname..'",'..self.name..');')
end
---
-- LuaDoc Patch
-- outputs an empty(without documentation) LuaDoc interface
-- by klapeto (http://cegui.org.uk/forum/viewtopic.php?f=7&t=6784)
function classDefine:output_luadoc()
if not self:check_public_access() then
return
end
if (self.parent~=nil) then
output('---\n')
output('-- @field [parent=#'..cleanseType(self.parent.name)..'] #string '..self.lname..'\n')
else
output('---\n')
output('-- @field [parent=#global] #string '..self.lname..'\n')
end
end
-- Print method
function classDefine:print (ident,close)
print(ident.."Define{")
print(ident.." name = '"..self.name.."',")
print(ident.." lname = '"..self.lname.."',")
print(ident.."}"..close)
end
-- Internal constructor
function _Define (t)
setmetatable(t,classDefine)
t:buildnames()
if t.name == '' then
error("#invalid define")
end
append(t)
return t
end
-- Constructor
-- Expects a string representing the constant name
function Define (n)
return _Define{
name = n
}
end
| mit |
mercury233/ygopro-scripts | c47349310.lua | 4 | 1927 | --スカイオニヒトクイエイ
function c47349310.initial_effect(c)
--reg
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_DAMAGE_STEP_END)
e1:SetOperation(c47349310.regop)
c:RegisterEffect(e1)
--pierce
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DIRECT_ATTACK)
c:RegisterEffect(e2)
--remove
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(47349310,0))
e3:SetCategory(CATEGORY_REMOVE)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e3:SetRange(LOCATION_MZONE)
e3:SetCode(EVENT_PHASE+PHASE_BATTLE)
e3:SetCountLimit(1)
e3:SetCondition(c47349310.rmcon)
e3:SetTarget(c47349310.rmtg)
e3:SetOperation(c47349310.rmop)
c:RegisterEffect(e3)
end
function c47349310.regop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if Duel.GetAttackTarget() then return end
c:RegisterFlagEffect(47349310,RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_BATTLE,0,1)
end
function c47349310.rmcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetFlagEffect(47349310)~=0
end
function c47349310.rmtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_REMOVE,e:GetHandler(),1,0,0)
end
function c47349310.rmop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
if Duel.Remove(c,0,REASON_EFFECT+REASON_TEMPORARY)==0 then return end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_STANDBY)
e1:SetCountLimit(1)
e1:SetLabelObject(c)
e1:SetCondition(c47349310.retcon)
e1:SetOperation(c47349310.retop)
e1:SetReset(RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN)
Duel.RegisterEffect(e1,tp)
end
end
function c47349310.retcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp
end
function c47349310.retop(e,tp,eg,ep,ev,re,r,rp)
Duel.ReturnToField(e:GetLabelObject())
end
| gpl-2.0 |
mercury233/ygopro-scripts | c42006475.lua | 3 | 2965 | --守護神官マナ
function c42006475.initial_effect(c)
aux.AddCodeList(c,38033121)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(42006475,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_CHAINING)
e1:SetRange(LOCATION_HAND+LOCATION_GRAVE)
e1:SetCountLimit(1,42006475)
e1:SetCondition(c42006475.spcon)
e1:SetTarget(c42006475.sptg)
e1:SetOperation(c42006475.spop)
c:RegisterEffect(e1)
--indes
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
e2:SetRange(LOCATION_MZONE)
e2:SetTargetRange(LOCATION_MZONE,0)
e2:SetTarget(c42006475.indtg)
e2:SetValue(1)
c:RegisterEffect(e2)
--special summon
local e3=Effect.CreateEffect(c)
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetProperty(EFFECT_FLAG_DELAY)
e3:SetCode(EVENT_DESTROYED)
e3:SetCondition(c42006475.spcon2)
e3:SetTarget(c42006475.sptg2)
e3:SetOperation(c42006475.spop2)
c:RegisterEffect(e3)
end
function c42006475.tfilter(c,tp)
return c:IsFaceup() and c:IsControler(tp) and c:IsLocation(LOCATION_MZONE) and c:IsRace(RACE_SPELLCASTER)
end
function c42006475.spcon(e,tp,eg,ep,ev,re,r,rp)
if rp==tp then return false end
if not re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then return false end
local g=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS)
return g and g:GetCount()==1 and g:IsExists(c42006475.tfilter,1,nil,tp)
end
function c42006475.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 c42006475.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 c42006475.indtg(e,c)
return c:IsRace(RACE_SPELLCASTER) and c:IsLevelAbove(7)
end
function c42006475.spcon2(e,tp,eg,ep,ev,re,r,rp)
return bit.band(r,REASON_EFFECT+REASON_BATTLE)~=0
end
function c42006475.spfilter(c,e,tp)
return c:IsCode(38033121) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c42006475.sptg2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c42006475.spfilter,tp,LOCATION_HAND+LOCATION_DECK+LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND+LOCATION_DECK+LOCATION_GRAVE)
end
function c42006475.spop2(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(c42006475.spfilter),tp,LOCATION_HAND+LOCATION_DECK+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 |
Zenny89/darkstar | scripts/zones/Leafallia/npcs/HomePoint#1.lua | 17 | 1169 | -----------------------------------
-- Area: Leafallia
-- NPC: HomePoint#1
-- @pos
-----------------------------------
package.loaded["scripts/zones/Leafallia/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Leafallia/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 112);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
mercury233/ygopro-scripts | c81192859.lua | 2 | 2387 | --Ga-P.U.N.K.ワイルド・ピッキング
function c81192859.initial_effect(c)
--ACT
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--destroy
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(81192859,0))
e2:SetCategory(CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_BATTLE_START)
e2:SetRange(LOCATION_SZONE)
e2:SetCountLimit(1,81192859)
e2:SetCondition(c81192859.descon)
e2:SetTarget(c81192859.destg)
e2:SetOperation(c81192859.desop)
c:RegisterEffect(e2)
--Cannot Break
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(81192859,1))
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetProperty(EFFECT_FLAG_DELAY)
e3:SetCode(EVENT_DESTROYED)
e3:SetCondition(c81192859.limcon)
e3:SetOperation(c81192859.limop)
c:RegisterEffect(e3)
end
function c81192859.descon(e,tp,eg,ep,ev,re,r,rp)
local ac=Duel.GetBattleMonster(tp)
if not (ac and ac:IsFaceup() and ac:IsSetCard(0x171)) then return false end
local bc=ac:GetBattleTarget()
e:SetLabelObject(bc)
return bc and bc:IsControler(1-tp) and bc:IsRelateToBattle()
end
function c81192859.destg(e,tp,eg,ep,ev,re,r,rp,chk)
local bc=e:GetLabelObject()
if chk==0 then return bc end
Duel.SetOperationInfo(0,CATEGORY_DESTROY,bc,1,0,0)
end
function c81192859.desop(e,tp,eg,ep,ev,re,r,rp)
local bc=e:GetLabelObject()
if bc and bc:IsControler(1-tp) and bc:IsRelateToBattle() then
Duel.Destroy(bc,REASON_EFFECT)
end
end
function c81192859.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0x171)
end
function c81192859.limcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return rp==1-tp and c:IsReason(REASON_EFFECT) and c:IsPreviousControler(tp) and c:IsPreviousLocation(LOCATION_SZONE)
and Duel.GetMatchingGroupCount(c81192859.cfilter,tp,LOCATION_MZONE,0,nil)>0
end
function c81192859.limop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c81192859.cfilter,tp,LOCATION_MZONE,0,nil)
local tc=g:GetFirst()
while tc do
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetDescription(aux.Stringid(81192859,2))
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e1:SetProperty(EFFECT_FLAG_CLIENT_HINT)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
tc=g:GetNext()
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c69724380.lua | 9 | 1033 | --魔の取引
function c69724380.initial_effect(c)
--handes
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_HANDES)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_CHAINING)
e1:SetCondition(c69724380.condition)
e1:SetCost(c69724380.cost)
e1:SetTarget(c69724380.target)
e1:SetOperation(c69724380.activate)
c:RegisterEffect(e1)
end
function c69724380.condition(e,tp,eg,ep,ev,re,r,rp)
return ep~=tp and re:IsActiveType(TYPE_SPELL) and re:IsHasType(EFFECT_TYPE_ACTIVATE)
end
function c69724380.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,1000) end
Duel.PayLPCost(tp,1000)
end
function c69724380.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFieldGroupCount(tp,0,LOCATION_HAND)>0 end
Duel.SetOperationInfo(0,CATEGORY_HANDES,nil,0,1-tp,1)
end
function c69724380.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetFieldGroup(tp,0,LOCATION_HAND)
if g:GetCount()>0 then
local sg=g:RandomSelect(1-tp,1,nil)
Duel.SendtoGrave(sg,REASON_EFFECT+REASON_DISCARD)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c89312388.lua | 2 | 2158 | --E・HERO プリズマー
function c89312388.initial_effect(c)
--cos
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(89312388,0))
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_MZONE)
e1:SetCost(c89312388.coscost)
e1:SetOperation(c89312388.cosoperation)
c:RegisterEffect(e1)
end
function c89312388.filter2(c,fc)
return aux.IsMaterialListCode(fc,c:GetCode()) and c:IsAbleToGraveAsCost()
end
function c89312388.filter1(c,tp)
return c:IsType(TYPE_FUSION) and Duel.IsExistingMatchingCard(c89312388.filter2,tp,LOCATION_DECK,0,1,nil,c)
end
function c89312388.coscost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c89312388.filter1,tp,LOCATION_EXTRA,0,1,nil,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CONFIRM)
local g=Duel.SelectMatchingCard(tp,c89312388.filter1,tp,LOCATION_EXTRA,0,1,1,nil,tp)
Duel.ConfirmCards(1-tp,g)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local cg=Duel.SelectMatchingCard(tp,c89312388.filter2,tp,LOCATION_DECK,0,1,1,nil,g:GetFirst())
Duel.SendtoGrave(cg,REASON_COST)
e:SetLabel(cg:GetFirst():GetCode())
end
function c89312388.cosoperation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) or c:IsFacedown() then return end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_CODE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
e1:SetValue(e:GetLabel())
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(89312388,1))
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_PHASE+PHASE_END)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e2:SetCountLimit(1)
e2:SetRange(LOCATION_MZONE)
e2:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
e2:SetLabelObject(e1)
e2:SetOperation(c89312388.rstop)
c:RegisterEffect(e2)
end
function c89312388.rstop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=e:GetLabelObject()
e1:Reset()
Duel.HintSelection(Group.FromCards(c))
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
end
| gpl-2.0 |
Zenny89/darkstar | scripts/zones/West_Ronfaure/npcs/Palcomondau.lua | 35 | 12378 | -----------------------------------
-- Area: West Ronfaure
-- NPC: Palcomondau
-- Type: Patrol
-- @pos -349.796 -45.345 344.733 100
-----------------------------------
package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/pathfind");
-----------------------------------
local path = {
-373.096863, -45.742077, 340.182159,
-361.441864, -46.052444, 340.367371,
-360.358276, -46.063702, 340.457428,
-359.297211, -46.093231, 340.693817,
-358.264465, -46.285988, 341.032928,
-357.301941, -45.966343, 341.412994,
-356.365295, -45.641331, 341.804657,
-353.933533, -45.161453, 342.873901,
-346.744659, -45.006634, 346.113251,
-345.843506, -44.973419, 346.716309,
-345.138519, -44.939915, 347.540436,
-344.564056, -44.925575, 348.463470,
-344.069366, -44.945713, 349.431824,
-343.621704, -45.004826, 350.421936,
-343.194946, -45.062874, 351.421173,
-342.118958, -45.391632, 354.047485,
-334.448578, -44.964996, 373.198242,
-333.936615, -45.028484, 374.152283,
-333.189636, -45.068111, 374.939209,
-332.252838, -45.073158, 375.488129,
-331.241516, -45.065205, 375.888031,
-330.207855, -45.043056, 376.226532,
-329.165100, -45.022049, 376.536011,
-328.118622, -45.000935, 376.832428,
-323.437805, -45.726982, 378.101166,
-305.333038, -49.030193, 382.936646,
-304.308228, -49.435581, 383.130188,
-303.259979, -49.765697, 383.194305,
-302.209290, -50.104950, 383.175659,
-301.161774, -50.446033, 383.117767,
-300.114624, -50.787590, 383.041473,
-298.422943, -51.390713, 382.898590,
-281.798126, -56.178822, 381.370544,
-280.718414, -56.161697, 381.241425,
-279.641785, -56.142433, 381.087341,
-278.567627, -56.121262, 380.917938,
-261.485809, -55.875919, 378.010284,
-260.404205, -55.893314, 377.898254,
-259.317078, -55.908813, 377.861389,
-258.229248, -55.923473, 377.879669,
-257.142151, -55.938625, 377.919037,
-254.834976, -55.888081, 378.032623,
-224.857941, -56.603645, 379.721832,
-194.892044, -59.911034, 381.416382,
-178.437729, -61.500011, 382.347656,-- report?
-179.524124, -61.500011, 382.285919,
-209.530518, -58.837189, 380.588806,
-239.543137, -56.145073, 378.891602,
-257.769012, -55.930656, 377.861328,
-258.856445, -55.915405, 377.839905,
-259.943420, -55.900009, 377.884918,
-261.025116, -55.882565, 377.999329,
-262.102173, -55.864536, 378.151794,
-263.193237, -55.845242, 378.320587,
-279.088043, -56.134182, 381.021332,
-280.165344, -56.153133, 381.172882,
-281.246033, -56.168983, 381.299683,
-282.302917, -56.181866, 381.408691,
-301.977173, -50.175457, 383.230652,
-302.993134, -49.847698, 383.246735,
-303.998260, -49.580284, 383.147003,
-305.083649, -49.109840, 382.933411,
-306.061432, -48.755005, 382.706818,
-307.152679, -48.355675, 382.435608,
-327.497711, -45.027401, 377.016663,
-328.548553, -45.009663, 376.735291,
-331.569672, -45.071396, 375.927429,
-332.566711, -45.084835, 375.500153,
-333.347351, -45.055779, 374.749634,
-333.952423, -44.990082, 373.848999,
-334.454071, -44.958176, 372.884399,
-334.909607, -44.930862, 371.896698,
-335.338989, -44.939476, 370.897034,
-336.319305, -45.033978, 368.508484,
-344.092773, -44.934128, 349.103394,
-344.599304, -44.920494, 348.142578,
-345.289124, -44.948330, 347.305328,
-346.152740, -44.981884, 346.646881,
-347.087494, -45.014847, 346.091278,
-348.052368, -45.047348, 345.589172,
-349.030975, -45.039383, 345.114044,
-350.016052, -45.036438, 344.652252,
-357.274414, -45.947830, 341.359833,
-358.277222, -46.126381, 340.958984,
-359.326965, -46.091412, 340.679291,
-360.404205, -46.072746, 340.529785,
-361.488525, -46.061684, 340.441284,
-362.575226, -46.055046, 340.388184,
-363.662323, -46.050694, 340.353088,
-367.288086, -45.562141, 340.276978,
-397.408386, -46.031933, 339.796722,
-427.522491, -45.366581, 339.319641,
-457.651947, -45.910805, 338.841827,
-463.498932, -45.831551, 338.757111,
-464.580750, -45.752060, 338.776215,
-465.656433, -45.603558, 338.822693,
-467.953491, -45.463387, 338.967407,
-494.403381, -45.661190, 340.958710,
-495.442017, -45.667831, 341.254303,
-496.256042, -45.713417, 341.966400,
-496.865723, -45.720673, 342.866852,
-497.385132, -45.755371, 343.821838,
-498.376312, -45.856812, 345.908539,
-498.820007, -45.996841, 346.899353,
-499.174530, -46.197227, 347.923767,
-499.352539, -46.093906, 348.989563,
-499.416016, -46.074814, 350.073944,
-499.423279, -46.070366, 351.161072,
-499.397400, -46.084679, 352.248505,
-499.358795, -46.133957, 353.335815,
-498.771545, -46.025249, 365.000885,
-498.687347, -45.804886, 366.615082,
-498.166779, -45.846115, 376.640106,
-498.109924, -45.862961, 377.726410,
-497.697968, -45.951462, 385.738007,
-497.694122, -46.004673, 386.825317,
-497.737915, -46.056293, 387.912231,
-497.809082, -46.020039, 388.997162,
-498.192322, -46.074364, 393.595886,
-499.513733, -47.018887, 408.449036,
-499.682556, -47.223618, 409.509949,
-499.959503, -47.415245, 410.549194,
-500.307434, -47.595810, 411.566589,
-500.686859, -48.017868, 412.545349,
-501.077026, -48.478256, 413.506836,
-501.873901, -49.394321, 415.425659,
-502.207245, -49.737534, 416.425812,
-502.382660, -50.058594, 417.464630,
-502.406891, -50.394829, 418.516327,
-502.342438, -50.724243, 419.565948,
-502.251190, -51.088074, 420.607056,
-502.139435, -51.460213, 421.645935,
-501.954468, -52.022106, 423.198792,
-500.171021, -55.784023, 437.153931,
-500.033447, -56.010731, 438.356873,
-499.879120, -56.021641, 439.981689,
-499.679840, -55.963177, 442.392639,
-499.790558, -55.536102, 443.497894,
-500.205383, -55.237358, 444.453308,
-500.785736, -55.148598, 445.369598,
-501.427277, -55.099243, 446.246521,
-502.103760, -55.051254, 447.097015,
-502.791046, -55.003696, 447.939423,
-503.574524, -55.015862, 448.879730,
-510.872284, -55.089428, 457.484222,
-511.691742, -55.159729, 458.188812,
-512.678040, -55.280975, 458.628448,
-513.720825, -55.419674, 458.910309,
-514.785461, -55.554832, 459.097260,
-515.851929, -55.741619, 459.240265,
-516.923096, -55.906597, 459.366913,
-517.998413, -56.087105, 459.482513,
-521.921387, -56.035919, 459.879913,
-522.965271, -55.886223, 460.131927,
-523.947327, -55.785652, 460.568665,
-524.886719, -55.581245, 461.082581,
-525.805237, -55.438984, 461.645203,
-526.824829, -55.279068, 462.300720,
-531.560181, -54.945484, 465.464722,
-532.406555, -54.961479, 466.143524,
-533.060120, -54.995003, 467.010559,
-533.618408, -55.030079, 467.943695,
-534.158691, -55.026203, 468.887848,
-538.343323, -55.609158, 476.336639,
-538.852539, -55.920918, 477.273773,
-539.335510, -56.089600, 478.277985,
-539.767029, -56.035652, 479.274902,
-540.283997, -56.042004, 480.532135,
-544.975769, -55.047729, 492.510040,
-545.471375, -55.034317, 493.475891,
-546.206604, -55.009632, 494.270599,
-547.121643, -54.949020, 494.853882,
-548.100342, -54.921333, 495.329163,
-549.105103, -54.930302, 495.747131,
-550.121033, -54.979893, 496.133270,
-551.140991, -55.035213, 496.507385,
-556.089600, -55.924522, 498.256134,
-557.125793, -56.028824, 498.568329,
-558.182983, -56.208153, 498.806641,
-559.256592, -56.133862, 498.981354,
-560.335327, -56.116646, 499.118896,
-562.091736, -56.104050, 499.314911,
-574.530396, -56.559124, 500.553680,
-575.606262, -56.603722, 500.706024,
-576.649963, -56.813107, 500.963989,
-577.670288, -57.037365, 501.291138,
-578.679321, -57.266209, 501.647278,
-579.683105, -57.510010, 502.019379,
-581.321777, -57.800549, 502.643463,
-608.199463, -60.061394, 513.086548, -- turn around
-607.195618, -59.956524, 512.696411,
-579.141602, -57.367210, 501.788940,
-578.157959, -57.136345, 501.407318,
-577.150146, -56.915344, 501.086304,
-576.116089, -56.711021, 500.848358,
-575.049622, -56.572414, 500.676178,
-573.971497, -56.540531, 500.535004,
-572.891418, -56.511803, 500.410767,
-571.541260, -56.454227, 500.267334,
-559.917480, -56.117676, 499.110870,
-558.841248, -56.137356, 498.953400,
-557.782593, -56.166878, 498.714447,
-556.750061, -55.982758, 498.415985,
-555.608704, -55.807209, 498.053894,
-553.104614, -55.239231, 497.204651,
-547.725464, -54.925472, 495.326019,
-546.765625, -54.984024, 494.821899,
-546.022339, -55.011047, 494.032928,
-545.445923, -55.024132, 493.110931,
-544.951660, -55.061985, 492.142212,
-544.503357, -55.055382, 491.151031,
-544.083557, -55.041119, 490.147827,
-543.675354, -55.021049, 489.139801,
-540.065735, -56.014805, 479.933258,
-539.634155, -56.052246, 478.935516,
-539.166565, -56.161896, 477.960266,
-538.697327, -55.847233, 477.044403,
-538.208557, -55.557598, 476.136658,
-537.436646, -55.298710, 474.733032,
-533.392761, -55.013466, 467.513885,
-532.726868, -54.979912, 466.657013,
-531.930054, -54.948929, 465.917389,
-531.075134, -54.949390, 465.244354,
-530.197693, -54.950920, 464.600464,
-529.308838, -54.990524, 463.974792,
-525.172791, -55.543240, 461.159485,
-524.214478, -55.720425, 460.668243,
-523.196838, -55.850220, 460.304413,
-522.141357, -56.015007, 460.066986,
-521.068726, -56.020702, 459.886475,
-519.991577, -56.039570, 459.735687,
-518.911011, -56.055336, 459.609558,
-517.433777, -55.982838, 459.449738,
-513.966614, -55.460213, 459.099396,
-512.921997, -55.323360, 458.849701,
-512.001587, -55.181244, 458.291351,
-511.179230, -55.105251, 457.583893,
-510.412476, -55.032543, 456.816132,
-509.680267, -54.958725, 456.014191,
-508.602783, -54.942749, 454.788452,
-500.669189, -55.143158, 445.473999,
-500.128296, -55.247131, 444.541412,
-499.898651, -55.518276, 443.507935,
-499.821869, -55.910942, 442.468292,
-499.832764, -56.027439, 441.384308,
-499.881256, -56.021374, 440.297485,
-499.962463, -56.011227, 439.212982,
-500.072205, -56.031265, 438.133789,
-500.329163, -55.395157, 435.970062,
-502.441742, -50.690495, 419.476440,
-502.485474, -50.371307, 418.460999,
-502.368835, -50.054039, 417.447144,
-502.131531, -49.750740, 416.450317,
-501.775696, -49.393009, 415.406342,
-501.394318, -48.913757, 414.410278,
-500.999023, -48.445408, 413.431396,
-500.303253, -47.637516, 411.756561,
-499.980103, -47.454823, 410.747284,
-499.763947, -47.256901, 409.705627,
-499.603699, -47.051754, 408.654358,
-499.474274, -46.886150, 407.591583,
-499.360931, -46.714558, 406.528320,
-497.842590, -45.999271, 389.667542,
-497.735077, -46.047218, 388.312012,
-497.702972, -46.022728, 387.226166,
-497.717407, -45.968018, 386.140686,
-497.752014, -45.910450, 385.054596,
-498.532532, -45.704178, 369.587616,
-498.589294, -45.753151, 368.501129,
-499.547089, -46.040310, 350.040375,
-499.412354, -46.078503, 348.964417,
-499.099609, -46.221172, 347.926239,
-498.741913, -46.030338, 346.926208,
-498.351959, -45.860306, 345.923828,
-497.941467, -45.805256, 344.918884,
-497.518524, -45.751751, 343.918427,
-497.074768, -45.707314, 342.926636,
-496.434631, -45.690395, 342.056549,
-495.518555, -45.685642, 341.481903,
-494.478638, -45.677624, 341.169525,
-493.406281, -45.681431, 340.990509,
-492.333801, -46.148170, 340.858154,
-491.272858, -45.972626, 340.751801,
-490.196564, -45.903652, 340.655212,
-466.653748, -45.466057, 338.859863,
-465.575256, -45.615093, 338.803314,
-464.496521, -45.763508, 338.779785,
-463.410126, -45.832458, 338.774506,
-433.375122, -45.735828, 339.226624,
-403.243805, -46.015915, 339.704468,
};
-----------------------------------
-- onSpawn Action
-----------------------------------
function onSpawn(npc)
npc:initNpcAi();
npc:setPos(pathfind.first(path));
onPath(npc);
end;
-----------------------------------
-- onPath Action
-----------------------------------
function onPath(npc)
if (npc:atPoint(pathfind.get(path, 45))) then
local Gachemage = GetNPCByID(npc:getID() + 3);
Gachemage:showText(npc, PALCOMONDAU_REPORT);
-- small delay after path finish
npc:wait(8000);
end
pathfind.patrol(npc, path);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, PALCOMONDAU_DIALOG);
--npc:wait(1500);
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 |
Zenny89/darkstar | scripts/globals/mobskills/Light_Blade.lua | 21 | 1350 | ---------------------------------------------
-- Light Blade
-- Description: Deals very high physical damage to a single player.
-- Type: Ranged
-- Damage decreases the farther away the target is from him.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 1;
local dmgmod = 8;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_RANGED,MOBPARAM_SLASH,info.hitslanded);
-- TODO: There's no MOBPARAM_RANGED, but MOBPARAM doesn't appear to do anything?
-- Guessing ~40-100% damage based on range (20/50+). TODO: Find better data?
-- ~400-450ish at tanking/melee range for a PLD with defender up and earth staff.
-- ~750 for a DRG/BLU w/o Cocoon up at melee range.
-- Wiki says 1k, videos were actually less, so trusting videos.
local distance = mob:checkDistance(target)
utils.clamp(distance, 0, 40)
dmg = dmg * ((50 - distance) / 50);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
Zenny89/darkstar | scripts/zones/Gusgen_Mines/npcs/_5gd.lua | 34 | 1341 | -----------------------------------
-- Area: Gusgen Mines
-- NPC: _5gd (Lever F)
-- @pos 44 -20.56 143.802 196
-----------------------------------
package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Gusgen_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--local nID = npc:getID();
--printf("id: %u", nID);
local Lever = npc:getID();
npc:openDoor(2); -- Lever animation
if (GetNPCByID(Lever-6):getAnimation() == 9) then
GetNPCByID(Lever-6):setAnimation(8);--open door F
GetNPCByID(Lever-5):setAnimation(9);--close door E
GetNPCByID(Lever-4):setAnimation(9);--close door D
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 |
mercury233/ygopro-scripts | c31629407.lua | 2 | 1772 | --魔弾の射手 スター
function c31629407.initial_effect(c)
--activate from hand
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_QP_ACT_IN_NTPHAND)
e1:SetRange(LOCATION_MZONE)
e1:SetTarget(aux.TargetBoolFunction(Card.IsSetCard,0x108))
e1:SetTargetRange(LOCATION_HAND,0)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_TRAP_ACT_IN_HAND)
c:RegisterEffect(e2)
--special summon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(31629407,0))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e3:SetProperty(EFFECT_FLAG_DELAY)
e3:SetCode(EVENT_CHAINING)
e3:SetRange(LOCATION_MZONE)
e3:SetCountLimit(1,31629407)
e3:SetCondition(c31629407.spcon)
e3:SetTarget(c31629407.sptg)
e3:SetOperation(c31629407.spop)
c:RegisterEffect(e3)
end
function c31629407.spcon(e,tp,eg,ep,ev,re,r,rp)
return re:IsHasType(EFFECT_TYPE_ACTIVATE) and e:GetHandler():GetColumnGroup():IsContains(re:GetHandler())
end
function c31629407.spfilter(c,e,tp)
return c:IsLevelBelow(4) and c:IsSetCard(0x108) and not c:IsCode(31629407) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP_DEFENSE)
end
function c31629407.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c31629407.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c31629407.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
local tg=Duel.SelectMatchingCard(tp,c31629407.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp):GetFirst()
if tg then
Duel.SpecialSummon(tg,0,tp,tp,false,false,POS_FACEUP_DEFENSE)
end
end
| gpl-2.0 |
qq779089973/my_openwrt_mod | luci/libs/core/luasrc/ltn12.lua | 83 | 11303 | --[[
LuaSocket 2.0.2 license
Copyright � 2004-2007 Diego Nehab
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.
]]--
--[[
Changes made by LuCI project:
* Renamed to luci.ltn12 to avoid collisions with luasocket
* Added inline documentation
]]--
-----------------------------------------------------------------------------
-- LTN12 - Filters, sources, sinks and pumps.
-- LuaSocket toolkit.
-- Author: Diego Nehab
-- RCS ID: $Id$
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module
-----------------------------------------------------------------------------
local string = require("string")
local table = require("table")
local base = _G
--- Diego Nehab's LTN12 - Filters, sources, sinks and pumps.
-- See http://lua-users.org/wiki/FiltersSourcesAndSinks for design concepts
module("luci.ltn12")
filter = {}
source = {}
sink = {}
pump = {}
-- 2048 seems to be better in windows...
BLOCKSIZE = 2048
_VERSION = "LTN12 1.0.1"
-----------------------------------------------------------------------------
-- Filter stuff
-----------------------------------------------------------------------------
--- LTN12 Filter constructors
-- @class module
-- @name luci.ltn12.filter
--- Return a high level filter that cycles a low-level filter
-- by passing it each chunk and updating a context between calls.
-- @param low Low-level filter
-- @param ctx Context
-- @param extra Extra argument passed to the low-level filter
-- @return LTN12 filter
function filter.cycle(low, ctx, extra)
base.assert(low)
return function(chunk)
local ret
ret, ctx = low(ctx, chunk, extra)
return ret
end
end
--- Chain a bunch of filters together.
-- (thanks to Wim Couwenberg)
-- @param ... filters to be chained
-- @return LTN12 filter
function filter.chain(...)
local n = table.getn(arg)
local top, index = 1, 1
local retry = ""
return function(chunk)
retry = chunk and retry
while true do
if index == top then
chunk = arg[index](chunk)
if chunk == "" or top == n then return chunk
elseif chunk then index = index + 1
else
top = top+1
index = top
end
else
chunk = arg[index](chunk or "")
if chunk == "" then
index = index - 1
chunk = retry
elseif chunk then
if index == n then return chunk
else index = index + 1 end
else base.error("filter returned inappropriate nil") end
end
end
end
end
-----------------------------------------------------------------------------
-- Source stuff
-----------------------------------------------------------------------------
--- LTN12 Source constructors
-- @class module
-- @name luci.ltn12.source
-- create an empty source
local function empty()
return nil
end
--- Create an empty source.
-- @return LTN12 source
function source.empty()
return empty
end
--- Return a source that just outputs an error.
-- @param err Error object
-- @return LTN12 source
function source.error(err)
return function()
return nil, err
end
end
--- Create a file source.
-- @param handle File handle ready for reading
-- @param io_err IO error object
-- @return LTN12 source
function source.file(handle, io_err)
if handle then
return function()
local chunk = handle:read(BLOCKSIZE)
if not chunk then handle:close() end
return chunk
end
else return source.error(io_err or "unable to open file") end
end
--- Turn a fancy source into a simple source.
-- @param src fancy source
-- @return LTN12 source
function source.simplify(src)
base.assert(src)
return function()
local chunk, err_or_new = src()
src = err_or_new or src
if not chunk then return nil, err_or_new
else return chunk end
end
end
--- Create a string source.
-- @param s Data
-- @return LTN12 source
function source.string(s)
if s then
local i = 1
return function()
local chunk = string.sub(s, i, i+BLOCKSIZE-1)
i = i + BLOCKSIZE
if chunk ~= "" then return chunk
else return nil end
end
else return source.empty() end
end
--- Creates rewindable source.
-- @param src LTN12 source to be made rewindable
-- @return LTN12 source
function source.rewind(src)
base.assert(src)
local t = {}
return function(chunk)
if not chunk then
chunk = table.remove(t)
if not chunk then return src()
else return chunk end
else
t[#t+1] = chunk
end
end
end
--- Chain a source and a filter together.
-- @param src LTN12 source
-- @param f LTN12 filter
-- @return LTN12 source
function source.chain(src, f)
base.assert(src and f)
local last_in, last_out = "", ""
local state = "feeding"
local err
return function()
if not last_out then
base.error('source is empty!', 2)
end
while true do
if state == "feeding" then
last_in, err = src()
if err then return nil, err end
last_out = f(last_in)
if not last_out then
if last_in then
base.error('filter returned inappropriate nil')
else
return nil
end
elseif last_out ~= "" then
state = "eating"
if last_in then last_in = "" end
return last_out
end
else
last_out = f(last_in)
if last_out == "" then
if last_in == "" then
state = "feeding"
else
base.error('filter returned ""')
end
elseif not last_out then
if last_in then
base.error('filter returned inappropriate nil')
else
return nil
end
else
return last_out
end
end
end
end
end
--- Create a source that produces contents of several sources.
-- Sources will be used one after the other, as if they were concatenated
-- (thanks to Wim Couwenberg)
-- @param ... LTN12 sources
-- @return LTN12 source
function source.cat(...)
local src = table.remove(arg, 1)
return function()
while src do
local chunk, err = src()
if chunk then return chunk end
if err then return nil, err end
src = table.remove(arg, 1)
end
end
end
-----------------------------------------------------------------------------
-- Sink stuff
-----------------------------------------------------------------------------
--- LTN12 sink constructors
-- @class module
-- @name luci.ltn12.sink
--- Create a sink that stores into a table.
-- @param t output table to store into
-- @return LTN12 sink
function sink.table(t)
t = t or {}
local f = function(chunk, err)
if chunk then t[#t+1] = chunk end
return 1
end
return f, t
end
--- Turn a fancy sink into a simple sink.
-- @param snk fancy sink
-- @return LTN12 sink
function sink.simplify(snk)
base.assert(snk)
return function(chunk, err)
local ret, err_or_new = snk(chunk, err)
if not ret then return nil, err_or_new end
snk = err_or_new or snk
return 1
end
end
--- Create a file sink.
-- @param handle file handle to write to
-- @param io_err IO error
-- @return LTN12 sink
function sink.file(handle, io_err)
if handle then
return function(chunk, err)
if not chunk then
handle:close()
return 1
else return handle:write(chunk) end
end
else return sink.error(io_err or "unable to open file") end
end
-- creates a sink that discards data
local function null()
return 1
end
--- Create a sink that discards data.
-- @return LTN12 sink
function sink.null()
return null
end
--- Create a sink that just returns an error.
-- @param err Error object
-- @return LTN12 sink
function sink.error(err)
return function()
return nil, err
end
end
--- Chain a sink with a filter.
-- @param f LTN12 filter
-- @param snk LTN12 sink
-- @return LTN12 sink
function sink.chain(f, snk)
base.assert(f and snk)
return function(chunk, err)
if chunk ~= "" then
local filtered = f(chunk)
local done = chunk and ""
while true do
local ret, snkerr = snk(filtered, err)
if not ret then return nil, snkerr end
if filtered == done then return 1 end
filtered = f(done)
end
else return 1 end
end
end
-----------------------------------------------------------------------------
-- Pump stuff
-----------------------------------------------------------------------------
--- LTN12 pump functions
-- @class module
-- @name luci.ltn12.pump
--- Pump one chunk from the source to the sink.
-- @param src LTN12 source
-- @param snk LTN12 sink
-- @return Chunk of data or nil if an error occured
-- @return Error object
function pump.step(src, snk)
local chunk, src_err = src()
local ret, snk_err = snk(chunk, src_err)
if chunk and ret then return 1
else return nil, src_err or snk_err end
end
--- Pump all data from a source to a sink, using a step function.
-- @param src LTN12 source
-- @param snk LTN12 sink
-- @param step step function (optional)
-- @return 1 if the operation succeeded otherwise nil
-- @return Error object
function pump.all(src, snk, step)
base.assert(src and snk)
step = step or pump.step
while true do
local ret, err = step(src, snk)
if not ret then
if err then return nil, err
else return 1 end
end
end
end
| mit |
mercury233/ygopro-scripts | c90590303.lua | 2 | 2329 | --No.41 泥睡魔獣バグースカ
function c90590303.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,nil,4,2)
c:EnableReviveLimit()
--maintain
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EVENT_PHASE+PHASE_STANDBY)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCondition(c90590303.mtcon)
e1:SetOperation(c90590303.mtop)
c:RegisterEffect(e1)
--indes/cannot target
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET)
e2:SetRange(LOCATION_MZONE)
e2:SetCondition(c90590303.tgcon)
e2:SetValue(aux.tgoval)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
e3:SetValue(aux.indoval)
c:RegisterEffect(e3)
--pos
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD)
e4:SetCode(EFFECT_SET_POSITION)
e4:SetRange(LOCATION_MZONE)
e4:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE)
e4:SetCondition(c90590303.poscon)
e4:SetTarget(c90590303.postg)
e4:SetValue(POS_FACEUP_DEFENSE)
c:RegisterEffect(e4)
--disable
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e5:SetCode(EVENT_CHAIN_SOLVING)
e5:SetRange(LOCATION_MZONE)
e5:SetCondition(c90590303.discon)
e5:SetOperation(c90590303.disop)
c:RegisterEffect(e5)
end
aux.xyz_number[90590303]=41
function c90590303.mtcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp
end
function c90590303.mtop(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) then
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
else
Duel.Destroy(e:GetHandler(),REASON_COST)
end
end
function c90590303.tgcon(e)
return e:GetHandler():IsAttackPos()
end
function c90590303.poscon(e)
return e:GetHandler():IsDefensePos()
end
function c90590303.postg(e,c)
return c:IsFaceup()
end
function c90590303.discon(e,tp,eg,ep,ev,re,r,rp)
local loc,pos=Duel.GetChainInfo(ev,CHAININFO_TRIGGERING_LOCATION,CHAININFO_TRIGGERING_POSITION)
return e:GetHandler():IsDefensePos()
and re:IsActiveType(TYPE_MONSTER) and loc==LOCATION_MZONE and bit.band(pos,POS_DEFENSE)~=0
end
function c90590303.disop(e,tp,eg,ep,ev,re,r,rp)
Duel.NegateEffect(ev)
end
| gpl-2.0 |
rouing/FHLG-BW | entities/entities/item_antidote/init.lua | 1 | 1025 |
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include('shared.lua')
function ENT:SpawnFunction( ply, tr )
if ( !tr.Hit ) then return end
local SpawnPos = tr.HitPos + tr.HitNormal * 20
local ent = ents.Create( "item_antidote" )
ent:SetPos( SpawnPos )
ent:Spawn()
ent:Activate()
return ent
end
function ENT:Initialize()
self.Entity:SetModel( "models/props_lab/jar01a.mdl")
self.Entity:PhysicsInit(SOLID_VPHYSICS)
self.Entity:SetMoveType(MOVETYPE_VPHYSICS)
self.Entity:SetSolid(SOLID_VPHYSICS)
self.Entity:SetColor(Color(50, 150, 150, 255))
local phys = self.Entity:GetPhysicsObject()
if(phys:IsValid()) then phys:Wake() end
self.Entity:SetVar("damage",20)
self.Time = CurTime()
end
function ENT:Use(activator,caller)
// lol.
if (caller:GetTable().Antidoted != true) then
Antidoteup(caller)
self.Entity:Remove()
end
end
function ENT:Think()
end
function ENT:OnRemove()
local ply = self.Entity:GetNWEntity("owner")
ply:GetTable().maxDrugs = ply:GetTable().maxDrugs - 1
end
| unlicense |
ajayk/kong | kong/plugins/basic-auth/access.lua | 2 | 4068 | local cache = require "kong.tools.database_cache"
local stringy = require "stringy"
local responses = require "kong.tools.responses"
local constants = require "kong.constants"
local crypto = require "kong.plugins.basic-auth.crypto"
local AUTHORIZATION = "authorization"
local PROXY_AUTHORIZATION = "proxy-authorization"
local _M = {}
-- Fast lookup for credential retrieval depending on the type of the authentication
--
-- All methods must respect:
--
-- @param request ngx request object
-- @param {table} conf Plugin config
-- @return {string} public_key
-- @return {string} private_key
local function retrieve_credentials(request, header_name, conf)
local username, password
local authorization_header = request.get_headers()[header_name]
if authorization_header then
local iterator, iter_err = ngx.re.gmatch(authorization_header, "\\s*[Bb]asic\\s*(.+)")
if not iterator then
ngx.log(ngx.ERR, iter_err)
return
end
local m, err = iterator()
if err then
ngx.log(ngx.ERR, err)
return
end
if m and table.getn(m) > 0 then
local decoded_basic = ngx.decode_base64(m[1])
if decoded_basic then
local basic_parts = stringy.split(decoded_basic, ":")
username = basic_parts[1]
password = basic_parts[2]
end
end
end
if conf.hide_credentials then
request.clear_header(header_name)
end
return username, password
end
--- Validate a credential in the Authorization header against one fetched from the database.
-- @param credential The retrieved credential from the username passed in the request
-- @param given_password The password as given in the Authorization header
-- @return Success of authentication
local function validate_credentials(credential, given_password)
local digest, err = crypto.encrypt({consumer_id = credential.consumer_id, password = given_password})
if err then
ngx.log(ngx.ERR, "[basic-auth] "..err)
end
return credential.password == digest
end
local function load_credential_from_db(username)
local credential
if username then
credential = cache.get_or_set(cache.basicauth_credential_key(username), function()
local credentials, err = dao.basicauth_credentials:find_by_keys {username = username}
local result
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
elseif #credentials > 0 then
result = credentials[1]
end
return result
end)
end
return credential
end
function _M.execute(conf)
-- If both headers are missing, return 401
if not (ngx.req.get_headers()[AUTHORIZATION] or ngx.req.get_headers()[PROXY_AUTHORIZATION]) then
ngx.header["WWW-Authenticate"] = "Basic realm=\""..constants.NAME.."\""
return responses.send_HTTP_UNAUTHORIZED()
end
local credential
local given_username, given_password = retrieve_credentials(ngx.req, PROXY_AUTHORIZATION, conf)
if given_username then
credential = load_credential_from_db(given_username)
end
-- Try with the authorization header
if not credential then
given_username, given_password = retrieve_credentials(ngx.req, AUTHORIZATION, conf)
credential = load_credential_from_db(given_username)
end
if not credential or not validate_credentials(credential, given_password) then
return responses.send_HTTP_FORBIDDEN("Invalid authentication credentials")
end
-- Retrieve consumer
local consumer = cache.get_or_set(cache.consumer_key(credential.consumer_id), function()
local result, err = dao.consumers:find_by_primary_key({ id = credential.consumer_id })
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
return result
end)
ngx.req.set_header(constants.HEADERS.CONSUMER_ID, consumer.id)
ngx.req.set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id)
ngx.req.set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username)
ngx.req.set_header(constants.HEADERS.CREDENTIAL_USERNAME, credential.username)
ngx.ctx.authenticated_credential = credential
end
return _M
| apache-2.0 |
Disslove77777/mmm | 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 |
mercury233/ygopro-scripts | c21293424.lua | 2 | 2934 | --空母軍貫-しらうお型特務艦
function c21293424.initial_effect(c)
aux.AddCodeList(c,24639891,78362751)
--xyz summon
aux.AddXyzProcedure(c,nil,4,2)
c:EnableReviveLimit()
--apply the effect
local e0=Effect.CreateEffect(c)
e0:SetType(EFFECT_TYPE_SINGLE)
e0:SetCode(EFFECT_MATERIAL_CHECK)
e0:SetValue(c21293424.valcheck)
c:RegisterEffect(e0)
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(21293424,0))
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCountLimit(1,21293424)
e1:SetCondition(c21293424.effcon)
e1:SetTarget(c21293424.efftg)
e1:SetOperation(c21293424.effop)
c:RegisterEffect(e1)
e0:SetLabelObject(e1)
--protection
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
e2:SetRange(LOCATION_MZONE)
e2:SetTargetRange(LOCATION_MZONE,0)
e2:SetCondition(c21293424.indescon)
e2:SetTarget(c21293424.indestg)
e2:SetValue(aux.indoval)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EFFECT_UPDATE_ATTACK)
e3:SetValue(c21293424.atkval)
c:RegisterEffect(e3)
end
function c21293424.valcheck(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local flag=0
if c:GetMaterial():FilterCount(Card.IsCode,nil,24639891)>0 then flag=flag|1 end
if c:GetMaterial():FilterCount(Card.IsCode,nil,78362751)>0 then flag=flag|2 end
e:GetLabelObject():SetLabel(flag)
end
function c21293424.effcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsSummonType(SUMMON_TYPE_XYZ)
end
function c21293424.thfilter(c)
return c:IsSetCard(0x166) and c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsAbleToHand()
end
function c21293424.efftg(e,tp,eg,ep,ev,re,r,rp,chk)
local chk1=e:GetLabel()&1>0
local chk2=e:GetLabel()&2>0
if chk==0 then return chk1 and Duel.IsPlayerCanDraw(tp,1)
or chk2 and Duel.IsExistingMatchingCard(c21293424.thfilter,tp,LOCATION_DECK,0,1,nil) end
e:SetCategory(0)
if chk1 then
e:SetCategory(CATEGORY_DRAW)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
if chk2 then
e:SetCategory(e:GetCategory()|(CATEGORY_TOHAND+CATEGORY_SEARCH))
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
end
function c21293424.effop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local chk1=e:GetLabel()&1>0
local chk2=e:GetLabel()&2>0
if chk1 then
Duel.Draw(tp,1,REASON_EFFECT)
end
if chk2 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c21293424.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.BreakEffect()
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
end
function c21293424.indescon(e)
return Duel.IsExistingMatchingCard(Card.IsFaceup,e:GetHandlerPlayer(),LOCATION_FZONE,LOCATION_FZONE,1,nil)
end
function c21293424.indestg(e,c)
return c:IsSummonLocation(LOCATION_EXTRA) and c:IsSetCard(0x166)
end
function c21293424.atkval(e,c)
return c:GetBaseDefense()
end
| gpl-2.0 |
mercury233/ygopro-scripts | c67926903.lua | 2 | 2919 | --CX 冀望皇バリアン
function c67926903.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,nil,7,3,c67926903.ovfilter,aux.Stringid(67926903,0),99)
c:EnableReviveLimit()
--atk
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetValue(c67926903.atkval)
c:RegisterEffect(e1)
--copy
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(67926903,1))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCountLimit(1,67926903)
e2:SetTarget(c67926903.copytg)
e2:SetOperation(c67926903.copyop)
c:RegisterEffect(e2)
end
function c67926903.ovfilter(c)
local no=aux.GetXyzNumber(c)
return c:IsFaceup() and no and no>=101 and no<=107 and c:IsSetCard(0x1048)
end
function c67926903.atkval(e,c)
return c:GetOverlayCount()*1000
end
function c67926903.filter(c)
return c:IsSetCard(0x48) and c:IsType(TYPE_EFFECT)
end
function c67926903.copytg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c67926903.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c67926903.filter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
Duel.SelectTarget(tp,c67926903.filter,tp,LOCATION_GRAVE,0,1,1,nil)
end
function c67926903.copyop(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:IsRelateToEffect(e) then
local code=tc:GetOriginalCode()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_CODE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetValue(code)
e1:SetLabel(tp)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END+RESET_OPPO_TURN)
c:RegisterEffect(e1)
local cid=c:CopyEffect(code,RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END+RESET_OPPO_TURN)
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(67926903,2))
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_PHASE+PHASE_END)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e2:SetCountLimit(1)
e2:SetRange(LOCATION_MZONE)
e2:SetCondition(c67926903.rstcon)
e2:SetOperation(c67926903.rstop)
e2:SetLabel(cid)
e2:SetLabelObject(e1)
e2:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END+RESET_OPPO_TURN)
c:RegisterEffect(e2)
end
end
function c67926903.rstcon(e,tp,eg,ep,ev,re,r,rp)
local e1=e:GetLabelObject()
return Duel.GetTurnPlayer()~=e1:GetLabel()
end
function c67926903.rstop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local cid=e:GetLabel()
c:ResetEffect(cid,RESET_COPY)
c:ResetEffect(RESET_DISABLE,RESET_EVENT)
local e1=e:GetLabelObject()
e1:Reset()
Duel.HintSelection(Group.FromCards(c))
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
end
| gpl-2.0 |
mercury233/ygopro-scripts | c44341034.lua | 2 | 1656 | --ダーク・バグ
function c44341034.initial_effect(c)
--summon success
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(44341034,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetTarget(c44341034.sumtg)
e1:SetOperation(c44341034.sumop)
c:RegisterEffect(e1)
end
function c44341034.filter(c,e,tp)
return c:IsLevel(3) and c:IsType(TYPE_TUNER) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c44341034.sumtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c44341034.filter(chkc,e,tp) end
if chk==0 then return Duel.IsExistingTarget(c44341034.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp)
and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c44341034.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c44341034.sumop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetValue(RESET_TURN_SET)
e2:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e2)
end
Duel.SpecialSummonComplete()
end
| gpl-2.0 |
fusijie/cocos2d-x-samples | samples/KillBug/src/cocos/cocos2d/DrawPrimitives.lua | 98 | 12024 |
local dp_initialized = false
local dp_shader = nil
local dp_colorLocation = -1
local dp_color = { 1.0, 1.0, 1.0, 1.0 }
local dp_pointSizeLocation = -1
local dp_pointSize = 1.0
local SHADER_NAME_POSITION_U_COLOR = "ShaderPosition_uColor"
local targetPlatform = cc.Application:getInstance():getTargetPlatform()
local function lazy_init()
if not dp_initialized then
dp_shader = cc.ShaderCache:getInstance():getProgram(SHADER_NAME_POSITION_U_COLOR)
--dp_shader:retain()
if nil ~= dp_shader then
dp_colorLocation = gl.getUniformLocation( dp_shader:getProgram(), "u_color")
dp_pointSizeLocation = gl.getUniformLocation( dp_shader:getProgram(), "u_pointSize")
dp_Initialized = true
end
end
if nil == dp_shader then
print("Error:dp_shader is nil!")
return false
end
return true
end
local function setDrawProperty()
gl.glEnableVertexAttribs( CCConstants.VERTEX_ATTRIB_FLAG_POSITION )
dp_shader:use()
dp_shader:setUniformsForBuiltins()
dp_shader:setUniformLocationWith4fv(dp_colorLocation, dp_color, 1)
end
function ccDrawInit()
lazy_init()
end
function ccDrawFree()
dp_initialized = false
end
function ccDrawColor4f(r,g,b,a)
dp_color[1] = r
dp_color[2] = g
dp_color[3] = b
dp_color[4] = a
end
function ccPointSize(pointSize)
dp_pointSize = pointSize * cc.Director:getInstance():getContentScaleFactor()
end
function ccDrawColor4B(r,g,b,a)
dp_color[1] = r / 255.0
dp_color[2] = g / 255.0
dp_color[3] = b / 255.0
dp_color[4] = a / 255.0
end
function ccDrawPoint(point)
if not lazy_init() then
return
end
local vertexBuffer = { }
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
local vertices = { point.x,point.y}
gl.bufferData(gl.ARRAY_BUFFER,2,vertices,gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
dp_shader:setUniformLocationWith1f(dp_pointSizeLocation, dp_pointSize)
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.POINTS,0,1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawPoints(points,numOfPoint)
if not lazy_init() then
return
end
local vertexBuffer = {}
local i = 1
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = {}
for i = 1, numOfPoint do
vertices[2 * i - 1] = points[i].x
vertices[2 * i] = points[i].y
end
gl.bufferData(gl.ARRAY_BUFFER, numOfPoint * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
dp_shader:setUniformLocationWith1f(dp_pointSizeLocation, dp_pointSize)
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.POINTS,0,numOfPoint)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawLine(origin,destination)
if not lazy_init() then
return
end
local vertexBuffer = {}
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = { origin.x, origin.y, destination.x, destination.y}
gl.bufferData(gl.ARRAY_BUFFER,4,vertices,gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINES ,0,2)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawPoly(points,numOfPoints,closePolygon)
if not lazy_init() then
return
end
local vertexBuffer = {}
local i = 1
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = {}
for i = 1, numOfPoints do
vertices[2 * i - 1] = points[i].x
vertices[2 * i] = points[i].y
end
gl.bufferData(gl.ARRAY_BUFFER, numOfPoints * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
if closePolygon then
gl.drawArrays(gl.LINE_LOOP , 0, numOfPoints)
else
gl.drawArrays(gl.LINE_STRIP, 0, numOfPoints)
end
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawSolidPoly(points,numOfPoints,color)
if not lazy_init() then
return
end
local vertexBuffer = {}
local i = 1
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = {}
for i = 1, numOfPoints do
vertices[2 * i - 1] = points[i].x
vertices[2 * i] = points[i].y
end
gl.bufferData(gl.ARRAY_BUFFER, numOfPoints * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
gl.glEnableVertexAttribs( CCConstants.VERTEX_ATTRIB_FLAG_POSITION )
dp_shader:use()
dp_shader:setUniformsForBuiltins()
dp_shader:setUniformLocationWith4fv(dp_colorLocation, color, 1)
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_FAN , 0, numOfPoints)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawRect(origin,destination)
ccDrawLine(CCPoint:__call(origin.x, origin.y), CCPoint:__call(destination.x, origin.y))
ccDrawLine(CCPoint:__call(destination.x, origin.y), CCPoint:__call(destination.x, destination.y))
ccDrawLine(CCPoint:__call(destination.x, destination.y), CCPoint:__call(origin.x, destination.y))
ccDrawLine(CCPoint:__call(origin.x, destination.y), CCPoint:__call(origin.x, origin.y))
end
function ccDrawSolidRect( origin,destination,color )
local vertices = { origin, CCPoint:__call(destination.x, origin.y) , destination, CCPoint:__call(origin.x, destination.y) }
ccDrawSolidPoly(vertices,4,color)
end
function ccDrawCircleScale( center, radius, angle, segments,drawLineToCenter,scaleX,scaleY)
if not lazy_init() then
return
end
local additionalSegment = 1
if drawLineToCenter then
additionalSegment = additionalSegment + 1
end
local vertexBuffer = { }
local function initBuffer()
local coef = 2.0 * math.pi / segments
local i = 1
local vertices = {}
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
for i = 1, segments + 1 do
local rads = (i - 1) * coef
local j = radius * math.cos(rads + angle) * scaleX + center.x
local k = radius * math.sin(rads + angle) * scaleY + center.y
vertices[i * 2 - 1] = j
vertices[i * 2] = k
end
vertices[(segments + 2) * 2 - 1] = center.x
vertices[(segments + 2) * 2] = center.y
gl.bufferData(gl.ARRAY_BUFFER, (segments + 2) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINE_STRIP , 0, segments + additionalSegment)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawCircle(center, radius, angle, segments, drawLineToCenter)
ccDrawCircleScale(center, radius, angle, segments, drawLineToCenter, 1.0, 1.0)
end
function ccDrawSolidCircle(center, radius, angle, segments,scaleX,scaleY)
if not lazy_init() then
return
end
local vertexBuffer = { }
local function initBuffer()
local coef = 2.0 * math.pi / segments
local i = 1
local vertices = {}
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
for i = 1, segments + 1 do
local rads = (i - 1) * coef
local j = radius * math.cos(rads + angle) * scaleX + center.x
local k = radius * math.sin(rads + angle) * scaleY + center.y
vertices[i * 2 - 1] = j
vertices[i * 2] = k
end
vertices[(segments + 2) * 2 - 1] = center.x
vertices[(segments + 2) * 2] = center.y
gl.bufferData(gl.ARRAY_BUFFER, (segments + 2) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_FAN , 0, segments + 1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawQuadBezier(origin, control, destination, segments)
if not lazy_init() then
return
end
local vertexBuffer = { }
local function initBuffer()
local vertices = { }
local i = 1
local t = 0.0
for i = 1, segments do
vertices[2 * i - 1] = math.pow(1 - t,2) * origin.x + 2.0 * (1 - t) * t * control.x + t * t * destination.x
vertices[2 * i] = math.pow(1 - t,2) * origin.y + 2.0 * (1 - t) * t * control.y + t * t * destination.y
t = t + 1.0 / segments
end
vertices[2 * (segments + 1) - 1] = destination.x
vertices[2 * (segments + 1)] = destination.y
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
gl.bufferData(gl.ARRAY_BUFFER, (segments + 1) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINE_STRIP , 0, segments + 1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawCubicBezier(origin, control1, control2, destination, segments)
if not lazy_init then
return
end
local vertexBuffer = { }
local function initBuffer()
local vertices = { }
local t = 0
local i = 1
for i = 1, segments do
vertices[2 * i - 1] = math.pow(1 - t,3) * origin.x + 3.0 * math.pow(1 - t, 2) * t * control1.x + 3.0 * (1 - t) * t * t * control2.x + t * t * t * destination.x
vertices[2 * i] = math.pow(1 - t,3) * origin.y + 3.0 * math.pow(1 - t, 2) * t * control1.y + 3.0 * (1 - t) * t * t * control2.y + t * t * t * destination.y
t = t + 1.0 / segments
end
vertices[2 * (segments + 1) - 1] = destination.x
vertices[2 * (segments + 1)] = destination.y
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
gl.bufferData(gl.ARRAY_BUFFER, (segments + 1) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINE_STRIP , 0, segments + 1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
| mit |
mercury233/ygopro-scripts | c21351206.lua | 2 | 2846 | --焔聖騎士-オジエ
function c21351206.initial_effect(c)
--tograve
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(21351206,0))
e1:SetCategory(CATEGORY_TOGRAVE)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetCountLimit(1,21351206)
e1:SetTarget(c21351206.tgtg)
e1:SetOperation(c21351206.tgop)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e2)
--equip
local e3=Effect.CreateEffect(c)
e3:SetCategory(CATEGORY_EQUIP)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET)
e3:SetRange(LOCATION_GRAVE)
e3:SetCountLimit(1,21351207)
e3:SetTarget(c21351206.eqtg)
e3:SetOperation(c21351206.eqop)
c:RegisterEffect(e3)
--indes
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_EQUIP)
e4:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
e4:SetValue(1)
c:RegisterEffect(e4)
end
function c21351206.tgfilter(c)
return ((c:IsRace(RACE_WARRIOR) and c:IsAttribute(ATTRIBUTE_FIRE)) or c:IsSetCard(0x207a)) and not c:IsCode(21351206)
and c:IsAbleToGrave()
end
function c21351206.tgtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c21351206.tgfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_DECK)
end
function c21351206.tgop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c21351206.tgfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoGrave(g,REASON_EFFECT)
end
end
function c21351206.eqfilter(c)
return c:IsFaceup() and c:IsRace(RACE_WARRIOR)
end
function c21351206.eqtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c21351206.eqfilter(chkc) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0
and Duel.IsExistingTarget(c21351206.eqfilter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,c21351206.eqfilter,tp,LOCATION_MZONE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0)
Duel.SetOperationInfo(0,CATEGORY_LEAVE_GRAVE,e:GetHandler(),1,0,0)
end
function c21351206.eqop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and tc:IsFaceup() and tc:IsControler(tp) and tc:IsRelateToEffect(e) then
if not Duel.Equip(tp,c,tc) then return end
--equip limit
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_EQUIP_LIMIT)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetLabelObject(tc)
e1:SetValue(c21351206.eqlimit)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
c:RegisterEffect(e1)
end
end
function c21351206.eqlimit(e,c)
return c==e:GetLabelObject()
end
| gpl-2.0 |
AlmightyLaxz/gmRPG | entities/weapons/weapon_gmrpg_pot/shared.lua | 1 | 1674 | if ( SERVER ) then
AddCSLuaFile( "shared.lua" )
SWEP.HoldType = "melee"
end
SWEP.ViewModel = "models/weapons/c_crowbar.mdl"
SWEP.WorldModel = "models/props_interiors/pot02a.mdl"
SWEP.VElements = {
["frypan"] = { type = "Model", model = "models/props_interiors/pot02a.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(2.596, 0.4, -5.715), angle = Angle(0, -180, -80), size = Vector(1, 1, 1), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}
SWEP.WElements = {
["frypan"] = { type = "Model", model = "models/props_interiors/pot02a.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(3.635, 0.518, -5.715), angle = Angle(0, -180, -80), size = Vector(1, 1, 1), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}
SWEP.Base = "weapon_gmrpg_melee_base"
SWEP.HoldType = "melee"
SWEP.ViewModelFOV = 55
SWEP.ViewModelFlip = false
SWEP.UseHands = true
SWEP.ShowViewModel = false
SWEP.ShowWorldModel = false
SWEP.ViewModelBoneMods = {}
SWEP.Primary.Delay = 0.4
SWEP.Primary.Damage = 20
SWEP.Primary.ClipSize = -1
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "none"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.PrintName = "Pot"
SWEP.Category = "gmRPG"
SWEP.Author = "Almighty Laxz";
SWEP.Contact = "";
SWEP.Purpose = "slap people";
SWEP.Instructions = "Left click to slap";
SWEP.Slot = 0 | gpl-3.0 |
Zenny89/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 |
dyhpoon/Attack-on-Pirates | AttackOnPirates/home-scene.lua | 1 | 20709 | local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local energy = require 'gameLogic.energy'
local gameCoins = require 'gameLogic.gameCoins'
local gameDiamonds = require 'gameLogic.gameDiamonds'
local gameKeys = require 'gameLogic.gameKeys'
local experience = require 'gameLogic.experience'
local localStorage = require 'gameLogic.localStorage'
local mainSoundEffect = require 'gameLogic.mainSoundEffect'
local toast = require 'gameLogic.toast'
local widget = require 'widget'
local luckyDraw = require 'gameLogic.luckyDraw'
local levelSetting = require 'gameLogic.levelSetting'
local statTable = levelSetting.getTable("mainCharStat")
local energyTable
local buttonIsPressed
local unfreezeButtonTimer
local buttonPressTimeDelay = 500
local menuXPosn = 400
local chestXPosn = -400
local menuLayout
local chestLayout
local gameKeysText
local energyBottleText
local itemStat
local soundEffect
local mapPopup
local function unfreezeButton()
buttonIsPressed = false
end
local function drawUpperLayout()
local group = display.newGroup()
local energy = energyTable["screen"]
group:insert(energy)
local function onComplete(event)
if "clicked" == event.action then
local i = event.index
if 1 == i then
-- do nothin (cancel)
elseif 2 == i then
local currentEnergyBottle = localStorage.get("energyBottle") - 1
localStorage.saveWithKey("energyBottle", currentEnergyBottle)
energyBottleText.text = currentEnergyBottle
energyTable["screen"]:restoreEnergy()
toast.new("Entirely recovered energy.", 3000)
end
end
end
local function energyButtonListener(event)
local currentEnergyBottle = localStorage.get("energyBottle")
if event.phase == "began" and currentEnergyBottle > 0 then
soundEffect:play("button")
local alert = native.showAlert( "Energy Potion", "Are you sure?", { "No", "Yes" }, onComplete )
end
end
local energyButton = widget.newButton{
defaultFile = "images/buttons/buttonUseenergy.png",
onEvent = energyButtonListener
}
energyButton.x = 190
energyButton.y = 38
group:insert(energyButton)
local gameCoins = gameCoins.new(275, 34)
gameCoins.y = gameCoins.y
itemStat["coins"] = gameCoins
group:insert(gameCoins)
local gameDiamonds = gameDiamonds.new(275, 11)
itemStat["diamonds"] = gameDiamonds
group:insert(gameDiamonds)
local function IAPButtonListener( event )
if event.phase == "began" and not buttonIsPressed then
soundEffect:play("button")
buttonIsPressed = true
unfreezeButtonTimer = timer.performWithDelay(buttonPressTimeDelay, unfreezeButton)
storyboard.gotoScene("IAP-scene", "fade", 800)
end
end
local iapButton = display.newImage("images/buttons/buttonIapmainmenu.png")
iapButton.anchorX, iapButton.anchorY = .5, .5
iapButton.x = 304
iapButton.y = 12
iapButton:addEventListener("touch", IAPButtonListener)
group:insert(iapButton)
local facebookLike = require 'gameLogic.facebookLike'
local facebookLikeButton = facebookLike.new(soundEffect)
group:insert(facebookLikeButton)
gameKeysText = gameKeys.new()
itemStat["keys"] = gameKeysText
group:insert(gameKeysText)
local expBonus = localStorage.get("expBonus")
local doubleExpImage
if expBonus > 0 then
doubleExpImage = display.newImage("images/calendar/calendarExp.png")
doubleExpImage.anchorX, doubleExpImage.anchorY = .5, .5
doubleExpImage.x = 135
doubleExpImage.y = 58
group:insert(doubleExpImage)
else
--do nothing
end
local storyModeScore = math.max(localStorage.get("storyLevel"), 0)
local storyModeText = display.newText("", 283, 127, native.systemFont, 9)
storyModeText.text = storyModeScore
group:insert(storyModeText)
local survivalTimeRecord = localStorage.get("survivalRecord")
local survivalTimeMins = math.floor(survivalTimeRecord/60)
local survivalTimeSecs = tostring(math.floor(survivalTimeRecord - (survivalTimeMins*60)))
if (string.len(survivalTimeSecs)) == 1 then survivalTimeSecs = "0" .. survivalTimeSecs end
local recordText = display.newText("", 285, 155, native.systemFont, 9)
recordText.text = survivalTimeMins .. ":" .. survivalTimeSecs
group:insert(recordText)
local experienceBar = experience.new()
group:insert(experienceBar)
local baseDamage = statTable[localStorage.get("charLevel")][3]
local baseDamageText = display.newText("", 58, 156, native.systemFont, 9)
baseDamageText.text = baseDamage
group:insert(baseDamageText)
local health = statTable[localStorage.get("charLevel")][2]
local healthText = display.newText("", 219, 100, native.systemFont, 9)
healthText.text = health
group:insert(healthText)
local energyBottle = localStorage.get("energyBottle")
energyBottleText = display.newText("", 52, 205, native.systemFont, 9)
energyBottleText.text = energyBottle
group:insert(energyBottleText)
local redPot1 = localStorage.get("redPot1")
local redPot1Text = display.newText("", 98, 205, native.systemFont, 9)
redPot1Text.text = redPot1
itemStat["redPot1"] = redPot1Text
group:insert(redPot1Text)
local redPot2 = localStorage.get("redPot2")
local redPot2Text = display.newText("", 145, 205, native.systemFont, 9)
redPot2Text.text = redPot2
itemStat["redPot2"] = redPot2Text
group:insert(redPot2Text)
local redPot3 = localStorage.get("redPot3")
local redPot3Text = display.newText("", 191, 205, native.systemFont, 9)
redPot3Text.text = redPot3
itemStat["redPot3"] = redPot3Text
group:insert(redPot3Text)
local redPot4 = localStorage.get("redPot4")
local redPot4Text = display.newText("", 238, 205, native.systemFont, 9)
redPot4Text.text = redPot4
itemStat["redPot4"] = redPot4Text
group:insert(redPot4Text)
local bluePot = localStorage.get("bluePot")
local bluePotText = display.newText("", 285, 205, native.systemFont, 9)
bluePotText.text = bluePot
itemStat["bluePot"] = bluePotText
group:insert(bluePotText)
return group
end
local function closePopupListener(event)
if event.phase == "began" then
soundEffect:play("back")
if mapPopup then
mapPopup:removeSelf()
mapPopup = nil
end
end
end
local function showPopUp()
if mapPopup then
mapPopup:removeSelf()
mapPopup = nil
end
mapPopup = display.newGroup()
local function popupListener(event)
return true
end
local popUp = display.newImageRect("images/survivalpopup.png", display.contentWidth, display.contentHeight)
popUp.anchorX, popUp.anchorY = .5, .5
popUp.x = display.contentCenterX
popUp.y = display.contentCenterY
mapPopup:insert(popUp)
popUp:addEventListener("touch", popupListener)
local closeButton = display.newImageRect("images/buttons/buttonExit.png", 30, 30)
closeButton.x = 275
closeButton.y = 45
closeButton.xScale = 1.3
closeButton.yScale = 1.3
closeButton:addEventListener("touch", closePopupListener)
mapPopup:insert(closeButton)
local survivalTimeRecord = localStorage.get("survivalRecord")
local survivalTimeMins = math.floor(survivalTimeRecord/60)
local survivalTimeSecs = tostring(math.floor(survivalTimeRecord - (survivalTimeMins*60)))
if (string.len(survivalTimeSecs)) == 1 then survivalTimeSecs = "0" .. survivalTimeSecs end
local highScore = survivalTimeMins .. ":" .. survivalTimeSecs
local highScoreText = display.newText("", 242, 255, "impact", 26)
highScoreText.text = highScore
mapPopup:insert(highScoreText)
local function playButtonListener(event)
if event.phase == "ended" then
soundEffect:play("button")
local options = {
effect = "fade",
time = 1000,
params = {mode="survival"}
}
storyboard.gotoScene( "game-scene", options )
if mapPopup then
mapPopup:removeSelf()
mapPopup = nil
end
end
end
local playButton = widget.newButton{
defaultFile = "images/buttons/buttonPlay.png",
overFile = "images/buttons/buttonPlayonclick.png",
onEvent = playButtonListener
}
playButton.xScale = 1.3
playButton.yScale = 1.3
playButton.x = display.contentCenterX
playButton.y = 440
playButton.level = level
mapPopup:insert(playButton)
mapPopup.alpha = 0
transition.to(mapPopup, {time=400, alpha=0.8})
end
local function drawMenuLayout()
local group = display.newGroup()
local buttonYTable = {250, 300, 350, 400, 450}
local function storyButtonListener( event )
if event.phase == "began" and not buttonIsPressed then
soundEffect:play("button")
buttonIsPressed = true
unfreezeButtonTimer = timer.performWithDelay(buttonPressTimeDelay, unfreezeButton)
storyboard.gotoScene("story-scene", "fade", 800)
end
end
local storyButton = widget.newButton{
defaultFile = "images/buttons/buttonStory.png",
overFile = "images/buttons/buttonStoryonclick.png",
onEvent = storyButtonListener
}
storyButton.x = display.contentCenterX
storyButton.y = buttonYTable[1]
group:insert(storyButton)
local function survivalButtonListener( event )
if event.phase == "began" and not buttonIsPressed then
soundEffect:play("button")
buttonIsPressed = true
unfreezeButtonTimer = timer.performWithDelay(buttonPressTimeDelay, unfreezeButton)
showPopUp()
end
end
local survivalButton = widget.newButton{
defaultFile = "images/buttons/buttonSurvival.png",
overFile = "images/buttons/buttonSurvivalonclick.png",
onEvent = survivalButtonListener
}
survivalButton.x = display.contentCenterX
survivalButton.y = buttonYTable[2]
group:insert(survivalButton)
local function shopButtonListener(event)
if event.phase == "began" and not buttonIsPressed then
soundEffect:play("button")
buttonIsPressed = true
unfreezeButtonTimer = timer.performWithDelay(buttonPressTimeDelay, unfreezeButton)
storyboard.gotoScene("shop-scene", "fade", 800)
end
end
local shopButton = widget.newButton{
defaultFile = "images/buttons/buttonShop.png",
overFile = "images/buttons/buttonShoponclick.png",
onEvent = shopButtonListener,
}
shopButton.x = display.contentCenterX
shopButton.y = buttonYTable[3]
group:insert(shopButton)
-- local function leaderboardButtonListener( event )
-- if event.phase == "began" and not buttonIsPressed then
-- soundEffect:play("button")
-- buttonIsPressed = true
-- unfreezeButtonTimer = timer.performWithDelay(buttonPressTimeDelay, unfreezeButton)
-- toast.new("Deprecated.", 3000)
-- --storyboard.gotoScene("leaderboard-scene", "fade", 800)
-- end
-- end
-- local leaderboardButton = widget.newButton{
-- defaultFile = "images/buttons/buttonLeaderbd.png",
-- overFile = "images/buttons/buttonLeaderbdonclick.png",
-- onEvent = leaderboardButtonListener
-- }
-- leaderboardButton.x = display.contentCenterX
-- leaderboardButton.y = buttonYTable[4]
-- group:insert(leaderboardButton)
local function luckyDrawButtonListener( event )
if event.phase == "began" and not buttonIsPressed then
soundEffect:play("button")
buttonIsPressed = true
unfreezeButtonTimer = timer.performWithDelay(buttonPressTimeDelay, unfreezeButton)
transition.to(menuLayout, {time=600, x=menuXPosn})
transition.to(chestLayout, {time=600, x=0})
end
end
local luckyDrawButton = widget.newButton{
defaultFile = "images/buttons/buttonLucky.png",
overFile = "images/buttons/buttonLuckyonclick.png",
onEvent = luckyDrawButtonListener
}
luckyDrawButton.x = display.contentCenterX
luckyDrawButton.y = buttonYTable[4]
group:insert(luckyDrawButton)
local function tutorialButtonListener(event)
if event.phase == "began" and not buttonIsPressed then
soundEffect:play("button")
buttonIsPressed = true
unfreezeButtonTimer = timer.performWithDelay(buttonPressTimeDelay, unfreezeButton)
storyboard.gotoScene("tutorial-scene", "slideLeft", 800)
end
end
local tutorialButton = widget.newButton{
defaultFile = "images/buttons/buttonTutorial.png",
onEvent = tutorialButtonListener
}
tutorialButton.anchorX, tutorialButton.anchorY = .5, .5
tutorialButton.y = 460
group:insert(tutorialButton)
return group
end
local function drawLuckyDrawLayout()
local group = display.newGroup()
-- draw three chests and background, then position it
local background = display.newImageRect("images/drawBox.png", 290, 190)
background.anchorX, background.anchorY = .5, .5
background.x = display.contentCenterX
background.y = 320
group:insert(background)
local keysNeededTable = {20, 40, 60}
local keysNeededIndex = 1
local keysNeededText = display.newText(keysNeededTable[keysNeededIndex], 0, 0, native.systemFont, 9)
keysNeededText.anchorX, keysNeededText.anchorY = .5, .5
keysNeededText.x = display.contentCenterX
keysNeededText.y = 280
keysNeededText:setTextColor(255/255, 255/255, 255/255)
group:insert(keysNeededText)
local function leftArrowListener(event)
if event.phase == "began" then
soundEffect:play("button")
keysNeededIndex = math.max(1, keysNeededIndex - 1)
keysNeededText.text = keysNeededTable[keysNeededIndex]
keysNeededText.anchorX, keysNeededText.anchorY = .5, .5
keysNeededText.x = display.contentCenterX
keysNeededText.y = 280
end
end
local leftArrow = display.newImageRect("images/drawArrow.png", 35, 35)
leftArrow.anchorX, leftArrow.anchorY = .5, .5
leftArrow.xScale = 1.3
leftArrow.x = 61
leftArrow.y = 280
leftArrow:rotate(180)
leftArrow:addEventListener("touch", leftArrowListener)
group:insert(leftArrow)
local function rightArrowListener(event)
if event.phase == "began" then
soundEffect:play("button")
keysNeededIndex = math.min(#keysNeededTable, keysNeededIndex + 1)
keysNeededText.text = keysNeededTable[keysNeededIndex]
keysNeededText.anchorX, keysNeededText.anchorY = .5, .5
keysNeededText.x = display.contentCenterX
keysNeededText.y = 280
end
end
local rightArrow = display.newImageRect("images/drawArrow.png", 35, 35)
rightArrow.anchorX, rightArrow.anchorY = .5, .5
rightArrow.xScale = 1.3
rightArrow.x = 260
rightArrow.y = 280
rightArrow:addEventListener("touch", rightArrowListener)
group:insert(rightArrow)
local threeChests = luckyDraw.new(gameKeysText, keysNeededText, itemStat, soundEffect)
group:insert(threeChests)
local function againButtonListener(event)
if event.phase == "began" and not buttonIsPressed then
soundEffect:play("button")
buttonIsPressed = true
unfreezeButtonTimer = timer.performWithDelay(buttonPressTimeDelay, unfreezeButton)
threeChests:reset()
end
end
local againButton = widget.newButton{
defaultFile = "images/buttons/buttonAgain.png",
onEvent = againButtonListener,
}
againButton.x = display.contentCenterX
againButton.y = 400
group:insert(againButton)
local function backButtonListener(event)
if event.phase == "began" and not buttonIsPressed then
soundEffect:play("back")
buttonIsPressed = true
unfreezeButtonTimer = timer.performWithDelay(buttonPressTimeDelay, unfreezeButton)
transition.to(menuLayout, {time=600, x=0})
transition.to(chestLayout, {time=600, x=chestXPosn})
end
end
local backButton = widget.newButton{
defaultFile = "images/buttons/buttonBack.png",
overFile = "images/buttons/buttonBackonclick.png",
onEvent = backButtonListener,
}
backButton.x = 160
backButton.y = 450
group:insert(backButton)
return group
end
-- Called when the scene's view does not exist:
function scene:createScene(event)
local group = self.view
soundEffect = mainSoundEffect.new()
itemStat = {}
local mainImage = display.newImageRect("images/mainmenu.png", display.contentWidth, display.contentHeight)
mainImage.anchorX, mainImage.anchorY = .5, .5
mainImage.x = display.contentCenterX
mainImage.y = display.contentCenterY
group:insert(mainImage)
energyTable = energy.new()
buttonIsPressed = false
local topLayout = drawUpperLayout()
menuLayout = drawMenuLayout()
chestLayout = drawLuckyDrawLayout()
--menuLayout:translate(menuXPosn, 0)
chestLayout:translate(chestXPosn, 0)
group:insert(menuLayout)
group:insert(topLayout)
group:insert(chestLayout)
end
-- Called BEFORE scene has moved onscreen:
function scene:willEnterScene( event )
local group = self.view
end
-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
local group = self.view
local BGM = require 'gameLogic.backgroundMusic'
BGM.play("main")
end
-- Called when scene is about to move offscreen:
function scene:exitScene( event )
local group = self.view
timer.cancel(energyTable["timer"])
timer.cancel(unfreezeButtonTimer)
unfreezeButtonTimer = nil
end
-- Called AFTER scene has finished moving offscreen:
function scene:didExitScene( event )
local group = self.view
end
-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
local group = self.view
soundEffect:dispose()
soundEffect = nil
itemStat = nil
energyBottleText = nil
gameKeysText = nil
buttonIsPressed = nil
chestLayout:removeSelf()
chestLayout = nil
menuLayout:removeSelf()
menuLayout = nil
group:removeSelf()
energyTable = nil
group = nil
self.view = nil
if mapPopup then
mapPopup:removeSelf()
mapPopup = nil
end
end
-- Called if/when overlay scene is displayed via storyboard.showOverlay()
function scene:overlayBegan( event )
local group = self.view
local overlay_name = event.sceneName -- name of the overlay scene
end
-- Called if/when overlay scene is hidden/removed via storyboard.hideOverlay()
function scene:overlayEnded( event )
local group = self.view
local overlay_name = event.sceneName -- name of the overlay scene
end
---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )
-- "willEnterScene" event is dispatched before scene transition begins
scene:addEventListener( "willEnterScene", scene )
-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )
-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )
-- "didExitScene" event is dispatched after scene has finished transitioning out
scene:addEventListener( "didExitScene", scene )
-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )
-- "overlayBegan" event is dispatched when an overlay scene is shown
scene:addEventListener( "overlayBegan", scene )
-- "overlayEnded" event is dispatched when an overlay scene is hidden/removed
scene:addEventListener( "overlayEnded", scene )
---------------------------------------------------------------------------------
return scene | apache-2.0 |
mercury233/ygopro-scripts | c73891874.lua | 3 | 1496 | --ホワイト・ホーンズ・ドラゴン
function c73891874.initial_effect(c)
--atk
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(73891874,0))
e1:SetCategory(CATEGORY_ATKCHANGE+CATEGORY_REMOVE)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetTarget(c73891874.target)
e1:SetOperation(c73891874.operation)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e2)
end
function c73891874.filter(c)
return c:IsType(TYPE_SPELL) and c:IsAbleToRemove()
end
function c73891874.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(1-tp) and c73891874.filter(chkc) end
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectTarget(tp,c73891874.filter,tp,0,LOCATION_GRAVE,1,5,nil)
Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,g:GetCount(),1-tp,LOCATION_GRAVE)
end
function c73891874.operation(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e)
local ct=Duel.Remove(g,POS_FACEUP,REASON_EFFECT)
local c=e:GetHandler()
if ct>0 and c:IsFaceup() and c:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_DISABLE)
e1:SetValue(ct*300)
c:RegisterEffect(e1)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c37491810.lua | 2 | 4033 | --パラメタルフォーゼ・アゾートレス
function c37491810.initial_effect(c)
--fusion material
c:EnableReviveLimit()
aux.EnablePendulumAttribute(c,false)
aux.AddFusionProcFun2(c,aux.FilterBoolFunction(Card.IsFusionSetCard,0xe1),aux.FilterBoolFunction(Card.IsFusionType,TYPE_FUSION),true)
--Pendulum destroy
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(37491810,0))
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY)
e1:SetCode(EVENT_DESTROYED)
e1:SetRange(LOCATION_PZONE)
e1:SetCountLimit(1,37491810)
e1:SetCondition(c37491810.despcon)
e1:SetTarget(c37491810.desptg)
e1:SetOperation(c37491810.despop)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(37491810,1))
e2:SetCategory(CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetCountLimit(1,37491811)
e2:SetCondition(c37491810.desmcon)
e2:SetTarget(c37491810.desmtg)
e2:SetOperation(c37491810.desmop)
c:RegisterEffect(e2)
--pendulum
local e5=Effect.CreateEffect(c)
e5:SetDescription(aux.Stringid(98452268,2))
e5:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e5:SetCode(EVENT_DESTROYED)
e5:SetProperty(EFFECT_FLAG_DELAY)
e5:SetCondition(c37491810.pencon)
e5:SetTarget(c37491810.pentg)
e5:SetOperation(c37491810.penop)
c:RegisterEffect(e5)
end
function c37491810.filter(c,tp)
return c:IsReason(REASON_EFFECT) and c:IsPreviousSetCard(0xe1)
and c:IsPreviousControler(tp) and c:IsPreviousLocation(LOCATION_ONFIELD) and c:IsPreviousPosition(POS_FACEUP)
end
function c37491810.despcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c37491810.filter,1,nil,tp)
end
function c37491810.desptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and chkc:IsFaceup() end
if chk==0 then return Duel.IsExistingTarget(Card.IsFaceup,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,Card.IsFaceup,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c37491810.despop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
function c37491810.desmcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsSummonLocation(LOCATION_EXTRA)
end
function c37491810.desmfilter(c)
return c:IsFaceup() and c:IsType(TYPE_PENDULUM) and c:IsAbleToDeck()
end
function c37491810.desmtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(1-tp) and chkc:IsOnField() end
if chk==0 then return Duel.IsExistingTarget(aux.TRUE,tp,0,LOCATION_ONFIELD,1,nil) and Duel.IsExistingMatchingCard(c37491810.desmfilter,tp,LOCATION_EXTRA,0,2,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,aux.TRUE,tp,0,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TODECK,nil,2,tp,LOCATION_EXTRA)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c37491810.desmop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectMatchingCard(tp,c37491810.desmfilter,tp,LOCATION_EXTRA,0,2,2,nil)
if Duel.SendtoDeck(g,nil,SEQ_DECKSHUFFLE,REASON_EFFECT)~=0 and g:IsExists(Card.IsLocation,1,nil,LOCATION_DECK+LOCATION_EXTRA) and tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
function c37491810.pencon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsPreviousLocation(LOCATION_MZONE) and c:IsFaceup()
end
function c37491810.pentg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLocation(tp,LOCATION_PZONE,0) or Duel.CheckLocation(tp,LOCATION_PZONE,1) end
end
function c37491810.penop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.MoveToField(c,tp,tp,LOCATION_PZONE,POS_FACEUP,true)
end
end
| gpl-2.0 |
Zenny89/darkstar | scripts/zones/Mhaura/npcs/Felisa.lua | 17 | 1188 | -----------------------------------
-- Area: Mhaura
-- NPC: Felisa
-- Admits players to the dock in Mhaura.
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Mhaura/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getZPos() > 38.5) then
player:startEvent(0x00dd,player:getGil(),100);
else
player:startEvent(0x00eb);
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 == 0x00dd and option == 333) then
player:delGil(100);
end
end; | gpl-3.0 |
Zenny89/darkstar | scripts/globals/items/bowl_of_seafood_stew.lua | 35 | 1467 | -----------------------------------------
-- ID: 4561
-- Item: Bowl of Seafood Stew
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Health 20
-- Dexterity 1
-- Vitality 5
-- Defense % 25
-- Defense Cap 120
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4561);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 20);
target:addMod(MOD_DEX, 1);
target:addMod(MOD_VIT, 5);
target:addMod(MOD_FOOD_DEFP, 25);
target:addMod(MOD_FOOD_DEF_CAP, 120);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 20);
target:delMod(MOD_DEX, 1);
target:delMod(MOD_VIT, 5);
target:delMod(MOD_FOOD_DEFP, 25);
target:delMod(MOD_FOOD_DEF_CAP, 120);
end;
| gpl-3.0 |
mercury233/ygopro-scripts | c36405256.lua | 2 | 2430 | --時花の魔女-フルール・ド・ソルシエール
function c36405256.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(36405256,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetCountLimit(1,36405256)
e1:SetTarget(c36405256.sptg)
e1:SetOperation(c36405256.spop)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e2)
end
function c36405256.filter(c,e,tp)
return c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c36405256.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(1-tp) and c36405256.filter(chkc,e,tp) end
if chk==0 then return e:GetHandler():IsRelateToEffect(e) and e:GetHandler():IsFaceup() end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c36405256.filter,tp,0,LOCATION_GRAVE,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c36405256.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) and Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)~=0 then
local fid=e:GetHandler():GetFieldID()
tc:RegisterFlagEffect(36405256,RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END,0,1,fid)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e1:SetLabel(fid)
e1:SetLabelObject(tc)
e1:SetCondition(c36405256.descon)
e1:SetOperation(c36405256.desop)
e1:SetReset(RESET_PHASE+PHASE_END)
e1:SetCountLimit(1)
Duel.RegisterEffect(e1,tp)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_CANNOT_DIRECT_ATTACK)
e2:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e2:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e2)
end
end
function c36405256.descon(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
return tc:GetFlagEffectLabel(36405256)==e:GetLabel()
end
function c36405256.desop(e,tp,eg,ep,ev,re,r,rp)
Duel.Destroy(e:GetLabelObject(),REASON_EFFECT)
end
| gpl-2.0 |
jefferyto/packages | utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/ltq-dsl.lua | 26 | 3991 | local ubus = require "ubus"
local function scrape()
local dsl_line_attenuation = metric("dsl_line_attenuation_db", "gauge")
local dsl_signal_attenuation = metric("dsl_signal_attenuation_db", "gauge")
local dsl_snr = metric("dsl_signal_to_noise_margin_db", "gauge")
local dsl_aggregated_transmit_power = metric("dsl_aggregated_transmit_power_db", "gauge")
local dsl_latency = metric("dsl_latency_seconds", "gauge")
local dsl_datarate = metric("dsl_datarate", "gauge")
local dsl_max_datarate = metric("dsl_max_datarate", "gauge")
local dsl_error_seconds_total = metric("dsl_error_seconds_total", "counter")
local dsl_errors_total = metric("dsl_errors_total", "counter")
local dsl_erb_total = metric("dsl_erb_total", "counter")
local u = ubus.connect()
local m = u:call("dsl", "metrics", {})
-- dsl hardware/firmware information
metric("dsl_info", "gauge", {
atuc_vendor = m.atu_c.vendor,
atuc_system_vendor = m.atu_c.system_vendor,
chipset = m.chipset,
firmware_version = m.firmware_version,
api_version = m.api_version,
driver_version = m.driver_version,
}, 1)
-- dsl line settings information
metric("dsl_line_info", "gauge", {
annex = m.annex,
standard = m.standard,
mode = m.mode,
profile = m.profile,
}, 1)
local dsl_up
if m.up then
dsl_up = 1
else
dsl_up = 0
end
metric("dsl_up", "gauge", {
detail = m.state,
}, dsl_up)
-- dsl line status data
metric("dsl_uptime_seconds", "gauge", {}, m.uptime)
-- dsl db measurements
dsl_line_attenuation({direction="down"}, m.downstream.latn)
dsl_line_attenuation({direction="up"}, m.upstream.latn)
dsl_signal_attenuation({direction="down"}, m.downstream.satn)
dsl_signal_attenuation({direction="up"}, m.upstream.satn)
dsl_snr({direction="down"}, m.downstream.snr)
dsl_snr({direction="up"}, m.upstream.snr)
dsl_aggregated_transmit_power({direction="down"}, m.downstream.actatp)
dsl_aggregated_transmit_power({direction="up"}, m.upstream.actatp)
-- dsl performance data
if m.downstream.interleave_delay ~= nil then
dsl_latency({direction="down"}, m.downstream.interleave_delay / 1000000)
dsl_latency({direction="up"}, m.upstream.interleave_delay / 1000000)
end
dsl_datarate({direction="down"}, m.downstream.data_rate)
dsl_datarate({direction="up"}, m.upstream.data_rate)
dsl_max_datarate({direction="down"}, m.downstream.attndr)
dsl_max_datarate({direction="up"}, m.upstream.attndr)
-- dsl errors
dsl_error_seconds_total({err="forward error correction", loc="near"}, m.errors.near.fecs)
dsl_error_seconds_total({err="forward error correction", loc="far"}, m.errors.far.fecs)
dsl_error_seconds_total({err="errored", loc="near"}, m.errors.near.es)
dsl_error_seconds_total({err="errored", loc="far"}, m.errors.far.es)
dsl_error_seconds_total({err="severely errored", loc="near"}, m.errors.near.ses)
dsl_error_seconds_total({err="severely errored", loc="far"}, m.errors.far.ses)
dsl_error_seconds_total({err="loss of signal", loc="near"}, m.errors.near.loss)
dsl_error_seconds_total({err="loss of signal", loc="far"}, m.errors.far.loss)
dsl_error_seconds_total({err="unavailable", loc="near"}, m.errors.near.uas)
dsl_error_seconds_total({err="unavailable", loc="far"}, m.errors.far.uas)
dsl_errors_total({err="header error code error", loc="near"}, m.errors.near.hec)
dsl_errors_total({err="header error code error", loc="far"}, m.errors.far.hec)
dsl_errors_total({err="non pre-emptive crc error", loc="near"}, m.errors.near.crc_p)
dsl_errors_total({err="non pre-emptive crc error", loc="far"}, m.errors.far.crc_p)
dsl_errors_total({err="pre-emptive crc error", loc="near"}, m.errors.near.crcp_p)
dsl_errors_total({err="pre-emptive crc error", loc="far"}, m.errors.far.crcp_p)
-- dsl error vectors
if m.erb ~= nil then
dsl_erb_total({counter="sent"}, m.erb.sent)
dsl_erb_total({counter="discarded"}, m.erb.discarded)
end
end
return { scrape = scrape }
| gpl-2.0 |
mercury233/ygopro-scripts | c66309175.lua | 2 | 3211 | --捕食植物アンブロメリドゥス
local s,id,o=GetID()
function c66309175.initial_effect(c)
--Fusion Material
c:EnableReviveLimit()
aux.AddFusionProcFunRep(c,aux.FilterBoolFunction(Card.IsFusionSetCard,0x10f3),2,true)
--To Hand
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(66309175,0))
e1:SetCategory(CATEGORY_SEARCH+CATEGORY_TOHAND)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCountLimit(1,66309175)
e1:SetCondition(c66309175.thcon)
e1:SetTarget(c66309175.thtg)
e1:SetOperation(c66309175.thop)
c:RegisterEffect(e1)
--Special Summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(66309175,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_RELEASE)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,66309175+o)
e2:SetTarget(c66309175.sptg)
e2:SetOperation(c66309175.spop)
c:RegisterEffect(e2)
end
function c66309175.thcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsSummonType(SUMMON_TYPE_FUSION)
end
function c66309175.thfilter(c)
return c:IsAbleToHand() and c:IsSetCard(0xf3) and (not c:IsType(TYPE_MONSTER) or c:IsSetCard(0x10f3)) and (c:IsFaceup() or not c:IsLocation(LOCATION_EXTRA))
end
function c66309175.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c66309175.thfilter,tp,LOCATION_DECK+LOCATION_GRAVE+LOCATION_EXTRA,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK+LOCATION_GRAVE+LOCATION_EXTRA)
end
function c66309175.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(c66309175.thfilter),tp,LOCATION_DECK+LOCATION_GRAVE+LOCATION_EXTRA,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
function c66309175.relfilter(c,tp)
return c:IsReleasableByEffect() and (c:GetCounter(0x1041)>0 or c:IsControler(tp)) and Duel.GetMZoneCount(tp,c)>0
end
function c66309175.spfilter(c,e,tp)
return c:IsSetCard(0x10f3) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c66309175.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c66309175.relfilter(chkc,tp) end
if chk==0 then return Duel.IsExistingTarget(c66309175.relfilter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil,tp)
and Duel.IsExistingMatchingCard(c66309175.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RELEASE)
local g=Duel.SelectTarget(tp,c66309175.relfilter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c66309175.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and not tc:IsImmuneToEffect(e)
and Duel.Release(tc,REASON_EFFECT)>0 and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c66309175.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if #g>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c23147658.lua | 2 | 2093 | --風化戦士
function c23147658.initial_effect(c)
aux.AddCodeList(c,59419719)
--search
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(23147658,0))
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetCode(EVENT_BATTLE_DESTROYED)
e1:SetCountLimit(1,23147658)
e1:SetTarget(c23147658.thtg)
e1:SetOperation(c23147658.thop)
c:RegisterEffect(e1)
local e1x=e1:Clone()
e1x:SetCode(EVENT_TO_GRAVE)
e1x:SetCondition(c23147658.thcon)
c:RegisterEffect(e1x)
--reduce atk
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(23147658,1))
e2:SetCategory(CATEGORY_ATKCHANGE)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EVENT_PHASE+PHASE_END)
e2:SetCountLimit(1)
e2:SetCondition(c23147658.atkcon)
e2:SetOperation(c23147658.atkop)
c:RegisterEffect(e2)
end
function c23147658.thfilter(c)
if not c:IsAbleToHand() or c:IsCode(23147658) then return false end
return c:IsCode(59419719) or aux.IsCodeListed(c,59419719)
end
function c23147658.thcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsReason(REASON_EFFECT)
end
function c23147658.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c23147658.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c23147658.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c23147658.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if #g>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
function c23147658.atkcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp
end
function c23147658.atkop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and c:IsFaceup() then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(-600)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_DISABLE)
c:RegisterEffect(e1)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c30353551.lua | 2 | 2661 | --人海戦術
function c30353551.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(TIMING_END_PHASE)
c:RegisterEffect(e1)
--special summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(30353551,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e2:SetRange(LOCATION_SZONE)
e2:SetCode(EVENT_PHASE+PHASE_END)
e2:SetCountLimit(1)
e2:SetTarget(c30353551.target)
e2:SetOperation(c30353551.operation)
c:RegisterEffect(e2)
if not c30353551.global_check then
c30353551.global_check=true
local ge1=Effect.CreateEffect(c)
ge1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
ge1:SetCode(EVENT_BATTLED)
ge1:SetOperation(c30353551.checkop)
Duel.RegisterEffect(ge1,0)
local ge2=Effect.CreateEffect(c)
ge2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
ge2:SetCode(EVENT_PHASE_START+PHASE_DRAW)
ge2:SetOperation(c30353551.clear)
Duel.RegisterEffect(ge2,0)
end
end
function c30353551.checkop(e,tp,eg,ep,ev,re,r,rp)
local a=Duel.GetAttacker()
local d=Duel.GetAttackTarget()
if a:IsStatus(STATUS_BATTLE_DESTROYED) and a:IsType(TYPE_NORMAL) and a:IsLevelBelow(2) then
c30353551[a:GetControler()]=c30353551[a:GetControler()]+1
end
if d and d:IsStatus(STATUS_BATTLE_DESTROYED) and d:IsType(TYPE_NORMAL) and d:IsLevelBelow(2) then
c30353551[d:GetControler()]=c30353551[d:GetControler()]+1
end
end
function c30353551.clear(e,tp,eg,ep,ev,re,r,rp)
c30353551[0]=0
c30353551[1]=0
end
function c30353551.filter(c,e,tp)
return c:IsType(TYPE_NORMAL) and c:IsLevelBelow(2) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c30353551.target(e,tp,eg,ep,ev,re,r,rp,chk)
local ct=c30353551[tp]
if chk==0 then return ct>0 and (ct==1 or not Duel.IsPlayerAffectedByEffect(tp,59822133)) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,ct,tp,LOCATION_DECK)
end
function c30353551.operation(e,tp,eg,ep,ev,re,r,rp)
local ct=c30353551[tp]
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c30353551.filter,tp,LOCATION_DECK,0,ct,ct,nil,e,tp)
if g:GetCount()==0 then return end
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if ft>1 and Duel.IsPlayerAffectedByEffect(tp,59822133) then ft=1 end
if ft<=0 then
Duel.SendtoGrave(g,REASON_EFFECT)
elseif ft>=g:GetCount() then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
else
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sg=g:Select(tp,ft,ft,nil)
Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEUP)
g:Sub(sg)
Duel.SendtoGrave(g,REASON_EFFECT)
end
end
| gpl-2.0 |
Zenny89/darkstar | scripts/zones/Southern_San_dOria/npcs/Hinaree.lua | 19 | 1923 | -----------------------------------
-- Area: Southern San d'Oria@
-- NPC: Hinaree
-- Type: Standard NPC
-- @zone: 230
-- @pos -301.535 -10.199 97.698
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local currentday = tonumber(os.date("%j"));
if (player:getCurrentMission(COP) == THE_ROAD_FORKS and player:getVar("EMERALD_WATERS_Status")==6 ) then
player:startEvent(0x0017);
elseif (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path")== 0 ) then
player:startEvent(0x0016);
elseif (player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus")==3 and player:getVar("Promathia_kill_day") ~= currentday and player:getVar("COP_louverance_story")== 0 ) then
player:startEvent(0x02F5);
else
player:startEvent(0x0244);
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 == 0x0017) then
player:setVar("EMERALD_WATERS_Status",7); --end 3-3A: San d'Oria Route: "Emerald Waters"
elseif (csid == 0x0016) then
player:setVar("COP_Ulmia_s_Path",1);
elseif (csid == 0x02F5) then
player:setVar("COP_louverance_story",1);
end
end;
| gpl-3.0 |
goblinor/BomBus | bot/bot.lua | 2 | 17199 | tdcli = dofile('./tg/tdcli.lua')
serpent = (loadfile "./libs/serpent.lua")()
feedparser = (loadfile "./libs/feedparser.lua")()
our_id = 328448596 -- Put Here Your Bot ID
--ایدی رباتتونو اینجا بزارید
URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
local lgi = require ('lgi')
local notify = lgi.require('Notify')
notify.init ("Telegram updates")
chats = {}
function do_notify (user, msg)
local n = notify.Notification.new(user, msg)
n:show ()
end
function dl_cb (arg, data)
end
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
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"banhammer",
"groupmanager",
"msg-checks",
"plugins",
"tools"
},
sudo_users = {133362226,259616749},
admins = {},
disabled_channels = {},
moderation = {data = './data/moderation.json'},
info_text = [[<code>http://Anony-sec.ir</code>]],
}
serialize_to_file(config, './data/config.lua')
print ('saved config into conf.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: ./data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
plugins = {}
_config = load_config()
function load_plugins()
local config = loadfile ("./data/config.lua")()
for k, v in pairs(config.enabled_plugins) do
print("Loading Plugins", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugins '..v..'\27[39m')
print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all')))
print('\27[31m'..err..'\27[39m')
end
end
end
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
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
function gp_type(chat_id)
local gp_type = "pv"
local id = tostring(chat_id)
if id:match("^-100") then
gp_type = "channel"
elseif id:match("-") then
gp_type = "chat"
end
return gp_type
end
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.sender_user_id_ then
var = true
end
end
return var
end
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.sender_user_id_
if data[tostring(msg.chat_id_)] then
if data[tostring(msg.chat_id_)]['owners'] then
if data[tostring(msg.chat_id_)]['owners'][tostring(user)] then
var = true
end
end
end
for v,user in pairs(_config.admins) do
if user[1] == msg.sender_user_id_ then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.sender_user_id_ then
var = true
end
end
return var
end
function is_admin(msg)
local var = false
local user = msg.sender_user_id_
for v,user in pairs(_config.admins) do
if user[1] == msg.sender_user_id_ then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.sender_user_id_ then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_mod(msg)
local var = false
local data = load_data(_config.moderation.data)
local usert = msg.sender_user_id_
if data[tostring(msg.chat_id_)] then
if data[tostring(msg.chat_id_)]['mods'] then
if data[tostring(msg.chat_id_)]['mods'][tostring(usert)] then
var = true
end
end
end
if data[tostring(msg.chat_id_)] then
if data[tostring(msg.chat_id_)]['owners'] then
if data[tostring(msg.chat_id_)]['owners'][tostring(usert)] then
var = true
end
end
end
for v,user in pairs(_config.admins) do
if user[1] == msg.sender_user_id_ then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.sender_user_id_ then
var = true
end
end
return var
end
function is_owner1(chat_id, user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
if data[tostring(chat_id)] then
if data[tostring(chat_id)]['owners'] then
if data[tostring(chat_id)]['owners'][tostring(user)] then
var = true
end
end
end
for v,user in pairs(_config.admins) do
if user[1] == 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
function is_admin1(user_id)
local var = false
local user = user_id
for v,user in pairs(_config.admins) do
if user[1] == 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 the mod of that group or not
function is_mod1(chat_id, user_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(chat_id)] then
if data[tostring(chat_id)]['mods'] then
if data[tostring(chat_id)]['mods'][tostring(usert)] then
var = true
end
end
end
if data[tostring(chat_id)] then
if data[tostring(chat_id)]['owners'] then
if data[tostring(chat_id)]['owners'][tostring(usert)] then
var = true
end
end
end
for v,user in pairs(_config.admins) do
if user[1] == 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
function is_banned(user_id, chat_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(chat_id)] then
if data[tostring(chat_id)]['banned'] then
if data[tostring(chat_id)]['banned'][tostring(user_id)] then
var = true
end
end
end
return var
end
function is_silent_user(user_id, chat_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(chat_id)] then
if data[tostring(chat_id)]['is_silent_users'] then
if data[tostring(chat_id)]['is_silent_users'][tostring(user_id)] then
var = true
end
end
end
return var
end
function is_gbanned(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local gban_users = 'gban_users'
if data[tostring(gban_users)] then
if data[tostring(gban_users)][tostring(user)] then
var = true
end
end
return var
end
function kick_user(user_id, chat_id)
if not tonumber(user_id) then
return false
end
tdcli.changeChatMemberStatus(chat_id, user_id, 'Kicked', dl_cb, nil)
end
function del_msg(chat_id, message_ids)
local msgid = {[0] = message_ids}
tdcli.deleteMessages(chat_id, msgid, dl_cb, nil)
end
function banned_list(chat_id)
local data = load_data(_config.moderation.data)
local i = 1
if not data[tostring(chat_id)] then
return "_Group is not added_"
end
-- determine if table is empty
if next(data[tostring(chat_id)]['banned']) == nil then --fix way
return "_No banned users in this group_"
end
local message = 'List of banned users :\n'
for k,v in pairs(data[tostring(chat_id)]['banned']) do
message = message ..i.. '- '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
function silent_users_list(chat_id)
local data = load_data(_config.moderation.data)
local i = 1
if not data[tostring(chat_id)] then
return "_Group is not added_"
end
-- determine if table is empty
if next(data[tostring(chat_id)]['is_silent_users']) == nil then --fix way
return "_No silent users in this group_"
end
local message = 'List of silent users :\n'
for k,v in pairs(data[tostring(chat_id)]['is_silent_users']) do
message = message ..i.. '- '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
function gbanned_list()
local data = load_data(_config.moderation.data)
local i = 1
if not data['gban_users'] then
data['gban_users'] = {}
save_data(_config.moderation.data, data)
end
if next(data['gban_users']) == nil then --fix way
return "_No globally banned users available_"
end
local message = '_List of globally banned users :_\n'
for k,v in pairs(data['gban_users']) do
message = message ..i.. '- '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
function msg_valid(msg)
if msg.date_ < os.time() - 60 then
print('\27[36mOld msg\27[39m')
return false
end
return true
end
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 match_plugin(plugin, plugin_name, msg)
if plugin.pre_process then
-- If plugin is for privileged users only
local result = plugin.pre_process(msg)
if result then
print("pre process: ", plugin.plugin_name)
tdcli.sendMessage(receiver, msg.id_, 0, result, 0, "md")
end
end
for k, pattern in pairs(plugin.patterns) do
matches = match_pattern(pattern, msg.content_.text_)
if matches then
print("Message matches: ", pattern)
if plugin.run then
local result = plugin.run(msg, matches)
if result then
tdcli.sendMessage(msg.chat_id_, msg.id_, 0, result, 0, "md")
end
end
return
end
end
end
_config = load_config()
load_plugins()
function tdcli_update_callback (data)
if (data.ID == "UpdateNewMessage") then
--print(serpent.block(msg))
local msg = data.message_
local d = data.disable_notification_
local chat = chats[msg.chat_id_]
if redis:get('markread') == 'on' then
tdcli.viewMessages(msg.chat_id_, {[0] = msg.id_}, dl_cb, nil)
end
if ((not d) and chat) then
if msg.content_.ID == "MessageText" then
do_notify (chat.title_, msg.content_.text_)
else
do_notify (chat.title_, msg.content_.ID)
end
end
if msg.content_.ID == "MessageText" then
if msg_valid(msg) then
msg.edited = false
msg.pinned = false
match_plugins(msg)
end
elseif msg.content_.ID == "MessagePinMessage" then
local function pinned_cb(arg, data)
msg = data
msg.pinned = true
match_plugins(msg)
end
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.id_
}, pinned_cb, nil)
elseif msg.content_.ID == "MessagePhoto" then
local function photo_cb(arg, data)
msg = data
msg.photo_ = true
match_plugins(msg)
end
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.id_
}, photo_cb, nil)
elseif msg.content_.ID == "MessageVideo" then
local function video_cb(arg, data)
msg = data
msg.video_ = true
match_plugins(msg)
end
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.id_
}, video_cb, nil)
elseif msg.content_.ID == "MessageAnimation" then
local function gif_cb(arg, data)
msg = data
msg.animation_ = true
match_plugins(msg)
end
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.id_
}, gif_cb, nil)
elseif msg.content_.ID == "MessageVoice" then
local function voice_cb(arg, data)
msg = data
msg.voice_ = true
match_plugins(msg)
end
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.id_
}, voice_cb, nil)
elseif msg.content_.ID == "MessageAudio" then
local function audio_cb(arg, data)
msg = data
msg.audio_ = true
match_plugins(msg)
end
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.id_
}, audio_cb, nil)
elseif msg.content_.ID == "MessageForwardedFromUser" then
local function forward_cb(arg, data)
msg = data
msg.forward_info_ = true
match_plugins(msg)
end
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.id_
}, forward_cb, nil)
elseif msg.content_.ID == "MessageSticker" then
local function sticker_cb(arg, data)
msg = data
msg.sticker_ = true
match_plugins(msg)
end
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.id_
}, sticker_cb, nil)
elseif msg.content_.ID == "MessageContact" then
local function contact_cb(arg, data)
msg = data
msg.contact_ = true
match_plugins(msg)
end
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.id_
}, contact_cb, nil)
elseif msg.content_.ID == "MessageDocument" then
local function doc_cb(arg, data)
msg = data
msg.document_ = true
match_plugins(msg)
end
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.id_
}, doc_cb, nil)
elseif msg.content_.ID == "MessageLocation" then
local function loc_cb(arg, data)
msg = data
msg.location_ = true
match_plugins(msg)
end
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.id_
}, loc_cb, nil)
elseif msg.content_.ID == "MessageGame" then
local function game_cb(arg, data)
msg = data
msg.game_ = true
match_plugins(msg)
end
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.id_
}, game_cb, nil)
elseif msg.content_.ID == "MessageChatAddMembers" then
if msg_valid(msg) then
for i=0,#msg.content_.members_ do
msg.adduser = msg.content_.members_[i].id_
match_plugins(msg)
end
end
elseif msg.content_.ID == "MessageChatJoinByLink" then
if msg_valid(msg) then
msg.joinuser = msg.sender_user_id_
match_plugins(msg)
end
elseif msg.content_.ID == "MessageChatDeleteMember" then
if msg_valid(msg) then
msg.deluser = true
match_plugins(msg)
end
end
if msg.content_.photo_ then
--write_file("test.txt", vardump(msg))
return false
end
elseif data.ID == "UpdateMessageEdited" then
local function edited_cb(arg, data)
msg = data
msg.edited = true
match_plugins(msg)
end
tdcli_function ({
ID = "GetMessage",
chat_id_ = data.chat_id_,
message_id_ = data.message_id_
}, edited_cb, nil)
elseif (data.ID == "UpdateChat") then
chat = data.chat_
chats[chat.id_] = chat
elseif (data.ID == "UpdateOption" and data.name_ == "my_id") then
tdcli_function ({ID="GetChats", offset_order_="9223372036854775807", offset_chat_id_=0, limit_=20}, dl_cb, nil)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c27551.lua | 2 | 2751 | --リミット・リバース
function c27551.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,TIMING_END_PHASE+TIMING_ATTACK)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetTarget(c27551.target)
e1:SetOperation(c27551.operation)
c:RegisterEffect(e1)
--Destroy
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_SINGLE)
e2:SetCode(EVENT_LEAVE_FIELD)
e2:SetOperation(c27551.desop)
c:RegisterEffect(e2)
--Destroy2
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD)
e3:SetRange(LOCATION_SZONE)
e3:SetCode(EVENT_LEAVE_FIELD)
e3:SetCondition(c27551.descon2)
e3:SetOperation(c27551.desop2)
c:RegisterEffect(e3)
--Destroy3
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD)
e4:SetRange(LOCATION_SZONE)
e4:SetCode(EVENT_CHANGE_POS)
e4:SetCondition(c27551.descon3)
e4:SetOperation(c27551.desop3)
c:RegisterEffect(e4)
end
function c27551.filter(c,e,tp)
return c:IsAttackBelow(1000) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP_ATTACK)
end
function c27551.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c27551.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c27551.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c27551.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c27551.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e)
and Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP_ATTACK) then
c:SetCardTarget(tc)
end
Duel.SpecialSummonComplete()
end
function c27551.desop(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetHandler():GetFirstCardTarget()
if tc and tc:IsLocation(LOCATION_MZONE) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
function c27551.descon2(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetHandler():GetFirstCardTarget()
return tc and eg:IsContains(tc) and tc:IsReason(REASON_DESTROY)
end
function c27551.desop2(e,tp,eg,ep,ev,re,r,rp)
Duel.Destroy(e:GetHandler(),REASON_EFFECT)
end
function c27551.descon3(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetHandler():GetFirstCardTarget()
return tc and eg:IsContains(tc) and tc:IsDefensePos()
end
function c27551.desop3(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=c:GetFirstCardTarget()
local g=Group.FromCards(tc,c)
Duel.Destroy(g,REASON_EFFECT)
end
| gpl-2.0 |
Zenny89/darkstar | scripts/zones/Southern_San_dOria_[S]/npcs/Areuhat1.lua | 36 | 1069 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Areuhat
-- @zone 80
-- @pos 21 0 22
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, 13454); -- (Couldn't find default dialogue) How very good to see you again!
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 |
mercury233/ygopro-scripts | c43140791.lua | 2 | 2363 | --ワーム・ベイト
function c43140791.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCondition(c43140791.condition)
e1:SetCost(c43140791.cost)
e1:SetTarget(c43140791.target)
e1:SetOperation(c43140791.activate)
c:RegisterEffect(e1)
Duel.AddCustomActivityCounter(43140791,ACTIVITY_SUMMON,c43140791.counterfilter)
Duel.AddCustomActivityCounter(43140791,ACTIVITY_SPSUMMON,c43140791.counterfilter)
end
function c43140791.counterfilter(c)
return not c:IsLevel(3,4)
end
function c43140791.cfilter(c)
return c:IsFaceup() and c:IsRace(RACE_INSECT)
end
function c43140791.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c43140791.cfilter,tp,LOCATION_MZONE,0,1,nil)
end
function c43140791.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetCustomActivityCount(43140791,tp,ACTIVITY_SUMMON)==0
and Duel.GetCustomActivityCount(43140791,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(c43140791.sumlimit)
Duel.RegisterEffect(e1,tp)
local e2=e1:Clone()
e2:SetCode(EFFECT_CANNOT_SUMMON)
Duel.RegisterEffect(e2,tp)
end
function c43140791.sumlimit(e,c,sump,sumtype,sumpos,targetp,se)
return c:IsLevel(3,4)
end
function c43140791.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return not Duel.IsPlayerAffectedByEffect(tp,59822133)
and Duel.GetLocationCount(tp,LOCATION_MZONE)>1
and Duel.IsPlayerCanSpecialSummonMonster(tp,43140792,0x3e,TYPES_TOKEN_MONSTER,0,0,1,RACE_INSECT,ATTRIBUTE_EARTH) end
Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,2,0,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,0,0)
end
function c43140791.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.IsPlayerAffectedByEffect(tp,59822133) then return end
if Duel.GetLocationCount(tp,LOCATION_MZONE)>1
and Duel.IsPlayerCanSpecialSummonMonster(tp,43140792,0x3e,TYPES_TOKEN_MONSTER,0,0,1,RACE_INSECT,ATTRIBUTE_EARTH) then
for i=1,2 do
local token=Duel.CreateToken(tp,43140792)
Duel.SpecialSummonStep(token,0,tp,tp,false,false,POS_FACEUP)
end
Duel.SpecialSummonComplete()
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c67113830.lua | 2 | 1126 | --墓地墓地の恨み
function c67113830.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetHintTiming(TIMING_DAMAGE_STEP)
e1:SetCondition(c67113830.condition)
e1:SetTarget(c67113830.target)
e1:SetOperation(c67113830.activate)
c:RegisterEffect(e1)
end
function c67113830.condition(e,tp,eg,ep,ev,re,r,rp)
return aux.dscon()
and Duel.GetFieldGroupCount(tp,0,LOCATION_GRAVE)>7
end
function c67113830.filter(c)
return c:IsFaceup() and c:GetAttack()>0
end
function c67113830.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c67113830.filter,tp,0,LOCATION_MZONE,1,nil) end
end
function c67113830.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(Card.IsFaceup,tp,0,LOCATION_MZONE,nil)
local tc=g:GetFirst()
while tc do
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SET_ATTACK_FINAL)
e1:SetValue(0)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e1)
tc=g:GetNext()
end
end
| gpl-2.0 |
Zenny89/darkstar | scripts/zones/Waughroon_Shrine/bcnms/prehistoric_pigeons.lua | 17 | 1788 | -----------------------------------
-- Area: Waughroon_Shrine
-- Name: Prehistoric Pigeons
-- KSNM30
-----------------------------------
package.loaded["scripts/zones/Waughroon_Shrine/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/zones/Waughroon_Shrine/TextIDs");
-----------------------------------
-- EXAMPLE SCRIPT
--
-- What should go here:
-- giving key items, playing ENDING cutscenes
--
-- What should NOT go here:
-- Handling of "battlefield" status, spawning of monsters,
-- putting loot into treasure pool,
-- enforcing ANY rules (SJ/number of people/etc), moving
-- chars around, playing entrance CSes (entrance CSes go in bcnm.lua)
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0);
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
end;
| gpl-3.0 |
Zenny89/darkstar | scripts/zones/AlTaieu/mobs/Jailer_of_Love.lua | 23 | 5580 | -----------------------------------
-- Area: Al'Taieu
-- NM: Jailer of Love
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob, target)
mob:hideName(false);
mob:untargetable(false);
mob:AnimationSub(2);
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob, target)
-- Only 9 Qn'xzomit and 9 Qn'hpemde can be summoned. Ru'phuabo (Sharks) are unlimited.
local XZOMITS = mob:getLocalVar("JoL_Qn_xzomit_Killed");
local HPEMDES = mob:getLocalVar("JoL_Qn_hpemde_Killed");
-- Increment these by 1 each time they are slain, in that mobs onMobDeath() script.
if (mob:getLocalVar("JoL_Regen_Reduction") == 0) then
if (mob:getLocalVar("JoL_Qn_xzomit_Killed") == 9
and mob:getLocalVar("JoL_Qn_hpemde_Killed") == 9) then
mob:setLocalVar("JoL_Regen_Reduction", 1);
mob:addMod(MOD_REGEN, -260)
end
end
local lastPop = mob:getLocalVar("pop_pets");
if (os.time() - lastPop > 150) then
local SPAWNS = mob:getLocalVar("SPAWNS");
local phuabo1 = GetMobAction(16912849);
local phuabo2 = GetMobAction(16912852);
local phuabo3 = GetMobAction(16912855);
if (SPAWNS == 0) then -- Spawns first 3 xzomit
SpawnMob(16912858, 300):updateEnmity(target);
SpawnMob(16912859, 300):updateEnmity(target);
SpawnMob(16912860, 300):updateEnmity(target);
mob:setLocalVar("pop_pets", os.time());
mob:setLocalVar("SPAWNS", 1);
elseif (SPAWNS == 1) then -- spawns first 3 hpemde
SpawnMob(16912867, 300):updateEnmity(target);
SpawnMob(16912868, 300):updateEnmity(target);
SpawnMob(16912869, 300):updateEnmity(target);
mob:setLocalVar("pop_pets", os.time());
mob:setLocalVar("SPAWNS", 2);
elseif (SPAWNS == 2) then -- spawns first 3 phuabo
SpawnMob(16912849, 300):updateEnmity(target);
SpawnMob(16912850, 300):updateEnmity(target);
SpawnMob(16912851, 300):updateEnmity(target);
mob:setLocalVar("pop_pets", os.time());
mob:setLocalVar("SPAWNS", 3);
elseif (SPAWNS == 3) then -- Spawns second 3 xzomit
SpawnMob(16912861, 300):updateEnmity(target);
SpawnMob(16912862, 300):updateEnmity(target);
SpawnMob(16912863, 300):updateEnmity(target);
mob:setLocalVar("pop_pets", os.time());
mob:setLocalVar("SPAWNS", 4);
elseif (SPAWNS == 4) then -- spawns second 3 hpemde
SpawnMob(16912870, 300):updateEnmity(target);
SpawnMob(16912871, 300):updateEnmity(target);
SpawnMob(16912872, 300):updateEnmity(target);
mob:setLocalVar("pop_pets", os.time());
mob:setLocalVar("SPAWNS", 5);
elseif (SPAWNS == 5) then -- spawns second 3 phuabo
SpawnMob(16912852, 300):updateEnmity(target);
SpawnMob(16912853, 300):updateEnmity(target);
SpawnMob(16912854, 300):updateEnmity(target);
mob:setLocalVar("pop_pets", os.time());
mob:setLocalVar("SPAWNS", 6);
elseif (SPAWNS == 6) then -- Spawns last 3 xzomit
SpawnMob(16912864, 300):updateEnmity(target);
SpawnMob(16912865, 300):updateEnmity(target);
SpawnMob(16912866, 300):updateEnmity(target);
mob:setLocalVar("pop_pets", os.time());
mob:setLocalVar("SPAWNS", 7);
elseif (SPAWNS == 7) then -- spawns last 3 hpemde
SpawnMob(16912873, 300):updateEnmity(target);
SpawnMob(16912874, 300):updateEnmity(target);
SpawnMob(16912875, 300):updateEnmity(target);
mob:setLocalVar("pop_pets", os.time());
mob:setLocalVar("SPAWNS", 8);
elseif (SPAWNS >= 8) then -- switch to ONLY popping phuabo (still up to 3 at a time)
if (phuabo1 == ACTION_NONE or phuabo1 == ACTION_SPAWN) then
SpawnMob(16912849, 300):updateEnmity(target);
SpawnMob(16912850, 300):updateEnmity(target);
SpawnMob(16912851, 300):updateEnmity(target);
mob:setLocalVar("pop_pets", os.time());
elseif (phuabo2 == ACTION_NONE or phuabo2 == ACTION_SPAWN) then
SpawnMob(16912852, 300):updateEnmity(target);
SpawnMob(16912853, 300):updateEnmity(target);
SpawnMob(16912854, 300):updateEnmity(target);
mob:setLocalVar("pop_pets", os.time());
elseif (phuabo3 == ACTION_NONE or phuabo3 == ACTION_SPAWN) then
SpawnMob(16912855, 300):updateEnmity(target);
SpawnMob(16912856, 300):updateEnmity(target);
SpawnMob(16912857, 300):updateEnmity(target);
mob:setLocalVar("pop_pets", os.time());
end
end
end
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
local AV_CHANCE = 25;
if (AV_CHANCE > math.random(0,99)) then
SpawnMob(16912876, 180);
end
end; | gpl-3.0 |
kui-jia/svb | main.lua | 1 | 6328 | --[[
The entry code, change parameter settings in 'optsArgParse.lua'
Kui Jia, Dacheng Tao, Shenghua Gao, and Xiangmin Xu, "Improving training of deep neural networks via Singular Value Bounding", CVPR 2017.
http://www.aperture-lab.net/research/svb
This code is based on the fb.resnet.torch package (https://github.com/facebook/fb.resnet.torch)
Copyright (c) 2016, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
--]]
local initTimer = torch.Timer()
initTimer:reset()
require 'torch'
require 'cutorch'
require 'paths'
require 'optim'
require 'nn'
print(('The time of requring torch packages is: %.3f'):format(initTimer:time().real))
local optsArgParse = require 'optsArgParse'
local opts = optsArgParse.parse(arg)
print(opts)
initTimer:reset()
local dataLoader = require 'dataLoader' -- cifar10Init is called inside
local netBuilder = require(opts.dataset .. '_' .. opts.netType)
local cnnTrainer = require 'cnnTrain'
local checkpoint = require 'checkpoint'
local utils = require('Utils/' .. 'utilFuncs')
print(('The time of requring project packages is: %.3f'):format(initTimer:time().real))
----------------------------------------------------------------------------------
torch.setdefaulttensortype('torch.FloatTensor')
torch.setnumthreads(1)
torch.manualSeed(opts.manualSeed)
cutorch.manualSeedAll(opts.manualSeed)
local prefix
if opts.netType == 'PreActResNet' then
if opts.lrDecayMethod == 'exp' then
prefix = opts.netType .. opts.ensembleID .. '_nRecur' .. opts.nBaseRecur .. '_kWRN' .. opts.kWRN .. '_BN_' .. tostring(opts.BN) ..
'_lr_' .. opts.lrDecayMethod .. '_base' .. opts.lrBase .. '_end' .. opts.lrEnd .. '_wDecay' .. opts.weightDecay ..
'_batch' .. opts.batchSize .. '_nEpoch' .. opts.nEpoch .. '_nStage' .. opts.nLRDecayStage ..
'_svBFlag_' .. tostring(opts.svBFlag) .. '_factor' .. opts.svBFactor .. '_iter' .. opts.svBIter ..
'_bnsBFlag_' .. tostring(opts.bnsBFlag) .. '_factor' .. opts.bnsBFactor .. '_' .. opts.bnsBType
end
end
print(prefix)
-- creating callback multi-threaded data loading functions
initTimer:reset()
local trnLoader, valLoader = dataLoader.create(opts)
print(('The time of creating dataLoader is: %.3f'):format(initTimer:time().real))
-- loading the latest training checkpoint if it exists
initTimer:reset()
local latestpoint, optimState = checkpoint.latest(prefix, opts) -- returning nil if not existing
print(('The time of loading latest checkpoint is: %.3f'):format(initTimer:time().real))
-- loading the latest or create a new network model
initTimer:reset()
local net, criterion = netBuilder.netInit(opts, latestpoint)
print(('The time of initializing network model is: %.3f'):format(initTimer:time().real))
-- initialize the trainer, which handles training loop and evaluation on the validation set
initTimer:reset()
local trainer = cnnTrainer(net, criterion, optimState, opts)
print(('The time of initializing the trainer is: %.3f'):format(initTimer:time().real))
-- do testing only if true
if opts.testFlag then
local bestpoint = checkpoint.best(prefix, opts) -- returning nil if not existing
net, criterion = netBuilder.netInit(opts, bestpoint) -- loading the best model
trainer = cnnTrainer(net, criterion, nil, opts) -- initialize the trainer with the best model
local top1Err, top5Err = trainer:test(0, valLoader)
print(string.format(' * Results top1: %6.3f top5: %6.3f', top1Err, top5Err))
return
end
-- start training
local startEpoch = latestpoint and latestpoint.epoch + 1 or opts.startEpoch
local nTrnIterPerEpoch = trnLoader:epochIterNum()
local bestTop1Err = math.huge
local bestTop5Err = math.huge
local trnTimer = torch.Timer()
local testTimer = torch.Timer()
local svbTimer = torch.Timer()
local statsFPath = paths.concat(opts.expFolder, 'stats_' .. prefix .. '.txt')
if not paths.filep(statsFPath) then
local statsFile = io.open(statsFPath, 'w') -- create a new one
statsFile:close()
end
for epoch = startEpoch, opts.nEpoch do
-- Train for a single epoch
trnTimer:reset()
local iter = (epoch-1) * nTrnIterPerEpoch -- the total number of iterations trained so far
local trnTop1Err, trnTop5Err, trnLoss = trainer:epochTrain(epoch, iter, trnLoader)
print(('| Training | Epoch: [%d] Time %.3f top1 %7.3f top5 %7.3f Loss %1.4f'):format(
epoch, trnTimer:time().real, trnTop1Err, trnTop5Err, trnLoss))
utils.writeErrsToFile(statsFPath, epoch, trnTop1Err, trnTop5Err, 'train')
-- Run model on validation set
testTimer:reset()
local testTop1Err, testTop5Err = trainer:test(epoch, valLoader)
print((' | Testing | Epoch [%d] Time %.3f top1 %7.3f top5 %7.3f'):format(
epoch, testTimer:time().real, testTop1Err, testTop5Err))
utils.writeErrsToFile(statsFPath, epoch, testTop1Err, testTop5Err, 'val')
-- Save the best model and other statistics/results
local bestModelFlag = false
if testTop1Err < bestTop1Err then
bestModelFlag = true -- true to save the up to now best model
bestTop1Err = testTop1Err
bestTop5Err = testTop5Err
print(' * Best model ', testTop1Err, testTop5Err)
utils.writeErrsToFile(statsFPath, '', testTop1Err, testTop5Err, 'best')
end
checkpoint.save(net, trainer.optimState, epoch, bestModelFlag, prefix, opts)
-- Applying Singular Value Bounding (and Bounded Batch Normalization) to (conv and fc) layer weights
-- at the end of each epoch, but not for the last epoch
svbTimer:reset()
if opts.svBFlag and epoch ~= opts.nEpoch then
trainer:fcConvWeightReguViaSVB()
if opts.bnsBFlag then -- optionally do scaling bounding of BN layers
trainer:BNScalingRegu()
end
end
print(('The time of SVB operation at the end of each epoch: %.3f'):format(svbTimer:time().real))
end
trnTimer:reset()
testTimer:reset()
svbTimer:reset()
print(string.format(' * Finished top1: %6.3f top5: %6.3f', bestTop1Err, bestTop5Err))
utils.writeErrsToFile(statsFPath, '', bestTop1Err, bestTop5Err, 'final')
| bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.