repo_name
stringlengths
6
78
path
stringlengths
4
206
copies
stringclasses
281 values
size
stringlengths
4
7
content
stringlengths
625
1.05M
license
stringclasses
15 values
BinChengfei/openwrt-3.10.14
package/ramips/ui/luci-mtk/src/applications/luci-pbx/luasrc/model/cbi/pbx-voip.lua
128
4540
--[[ Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com> This file is part of luci-pbx. luci-pbx is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. luci-pbx is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with luci-pbx. If not, see <http://www.gnu.org/licenses/>. ]]-- if nixio.fs.access("/etc/init.d/asterisk") then server = "asterisk" elseif nixio.fs.access("/etc/init.d/freeswitch") then server = "freeswitch" else server = "" end modulename = "pbx-voip" m = Map (modulename, translate("SIP Accounts"), translate("This is where you set up your SIP (VoIP) accounts ts like Sipgate, SipSorcery, \ the popular Betamax providers, and any other providers with SIP settings in order to start \ using them for dialing and receiving calls (SIP uri and real phone calls). Click \"Add\" to \ add as many accounts as you wish.")) -- Recreate the config, and restart services after changes are commited to the configuration. function m.on_after_commit(self) commit = false -- Create a field "name" for each account that identifies the account in the backend. m.uci:foreach(modulename, "voip_provider", function(s1) if s1.defaultuser ~= nil and s1.host ~= nil then name=string.gsub(s1.defaultuser.."_"..s1.host, "%W", "_") if s1.name ~= name then m.uci:set(modulename, s1['.name'], "name", name) commit = true end end end) if commit == true then m.uci:commit(modulename) end luci.sys.call("/etc/init.d/pbx-" .. server .. " restart 1\>/dev/null 2\>/dev/null") luci.sys.call("/etc/init.d/" .. server .. " restart 1\>/dev/null 2\>/dev/null") end ----------------------------------------------------------------------------- s = m:section(TypedSection, "voip_provider", translate("SIP Provider Accounts")) s.anonymous = true s.addremove = true s:option(Value, "defaultuser", translate("User Name")) pwd = s:option(Value, "secret", translate("Password"), translate("When your password is saved, it disappears from this field and is not displayed \ for your protection. The previously saved password will be changed only when you \ enter a value different from the saved one.")) pwd.password = true pwd.rmempty = false -- We skip reading off the saved value and return nothing. function pwd.cfgvalue(self, section) return "" end -- We check the entered value against the saved one, and only write if the entered value is -- something other than the empty string, and it differes from the saved value. function pwd.write(self, section, value) local orig_pwd = m:get(section, self.option) if value and #value > 0 and orig_pwd ~= value then Value.write(self, section, value) end end h = s:option(Value, "host", translate("SIP Server/Registrar")) h.datatype = "host" p = s:option(ListValue, "register", translate("Enable Incoming Calls (Register via SIP)"), translate("This option should be set to \"Yes\" if you have a DID \(real telephone number\) \ associated with this SIP account or want to receive SIP uri calls through this \ provider.")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" p = s:option(ListValue, "make_outgoing_calls", translate("Enable Outgoing Calls"), translate("Use this account to make outgoing calls.")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" from = s:option(Value, "fromdomain", translate("SIP Realm (needed by some providers)")) from.optional = true from.datatype = "host" port = s:option(Value, "port", translate("SIP Server/Registrar Port")) port.optional = true port.datatype = "port" op = s:option(Value, "outboundproxy", translate("Outbound Proxy")) op.optional = true op.datatype = "host" return m
gpl-2.0
ld-test/lzmq-ffi
test/lunit/console.lua
19
3798
--[[-------------------------------------------------------------------------- This file is part of lunit 0.6. For Details about lunit look at: http://www.mroth.net/lunit/ Author: Michael Roth <mroth@nessie.de> Copyright (c) 2006-2008 Michael Roth <mroth@nessie.de> 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. --]]-------------------------------------------------------------------------- --[[ begin() run(testcasename, testname) err(fullname, message, traceback) fail(fullname, where, message, usermessage) pass(testcasename, testname) done() Fullname: testcase.testname testcase.testname:setupname testcase.testname:teardownname --]] local lunit = require "lunit" local string = require "string" local io = require "io" local table = require "table" local _M = {} local function rfill(str, wdt, ch) if wdt > #str then str = str .. (ch or ' '):rep(wdt - #str) end return str end local function printformat(format, ...) io.write( string.format(format, ...) ) end local columns_printed = 0 local function writestatus(char) if columns_printed == 0 then io.write(" ") end if columns_printed == 60 then io.write("\n ") columns_printed = 0 end io.write(char) io.flush() columns_printed = columns_printed + 1 end local msgs = {} function _M.begin() local total_tc = 0 local total_tests = 0 msgs = {} -- e for tcname in lunit.testcases() do total_tc = total_tc + 1 for testname, test in lunit.tests(tcname) do total_tests = total_tests + 1 end end printformat("Loaded testsuite with %d tests in %d testcases.\n\n", total_tests, total_tc) end function _M.run(testcasename, testname) io.write(rfill(testcasename .. '.' .. testname, 70)) io.flush() end function _M.err(fullname, message, traceback) io.write(" - error!\n") io.write("Error! ("..fullname.."):\n"..message.."\n\t"..table.concat(traceback, "\n\t"), "\n") end function _M.fail(fullname, where, message, usermessage) io.write(" - fail!\n") io.write(string.format("Failure (%s): %s\n%s: %s", fullname, usermessage or "", where, message), "\n") end function _M.skip(fullname, where, message, usermessage) io.write(" - skip!\n") io.write(string.format("Skip (%s): %s\n%s: %s", fullname, usermessage or "", where, message), "\n") end function _M.pass(testcasename, testname) io.write(" - pass!\n") end function _M.done() printformat("\n\n%d Assertions checked.\n", lunit.stats.assertions ) print() printformat("Testsuite finished (%d passed, %d failed, %d errors, %d skipped).\n", lunit.stats.passed, lunit.stats.failed, lunit.stats.errors, lunit.stats.skipped ) end return _M
mit
nyczducky/darkstar
scripts/zones/Garlaige_Citadel/npcs/qm13.lua
14
1384
----------------------------------- -- Area: Garlaige Citadel -- NPC: qm13 (???) -- Involved in Quest: Hitting the Marquisate (THF AF3) -- @pos -194.166 -5.500 139.969 200 ----------------------------------- package.loaded["scripts/zones/Garlaige_Citadel/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Garlaige_Citadel/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local hittingTheMarquisateHagainCS = player:getVar("hittingTheMarquisateHagainCS"); if (hittingTheMarquisateHagainCS == 5) then player:messageSpecial(PRESENCE_FROM_CEILING); player:setVar("hittingTheMarquisateHagainCS",6); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Northern_San_dOria/npcs/Giaunne.lua
14
1746
----------------------------------- -- Area: Northern San d'Oria -- NPC: Giaunne -- Involved in Quest: Lure of the Wildcat (San d'Oria) -- @pos -13 0 36 231 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatSandy = player:getVar("WildcatSandy"); if (player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,5) == false) then player:startEvent(0x0325); 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 == 0x0325) then player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",5,true); end end;
gpl-3.0
AquariaOSE/Aquaria
files/scripts/maps/map_mithalas02.lua
6
2008
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end v.leave = true function init() if isFlag(FLAG_ENDING, ENDING_NAIJACAVE) then local e1 = getNode("end1") local e2 = getNode("end2") local e3 = getNode("end3") local e4 = getNode("end4") local e5 = getNode("end5") local sn = getNode("spirit") overrideZoom(0.8) fade2(1, 0) local spirit = createEntity("drask", "", node_x(sn), node_y(sn)) entity_animate(spirit, "sit", -1) local cam = createEntity("empty", "", node_x(e1), node_y(e1)) cam_toEntity(cam) watch(0.5) entity_setPosition(cam, node_x(e2), node_y(e2), 8, 0, 0, 1) fade2(0, 3) fadeIn(0) watch(5) fade2(1, 3) watch(3) overrideZoom(0.65, 20) entity_warpToNode(cam, e3) watch(0.5) entity_setPosition(cam, node_x(e4), node_y(e4), 5, 0, 0, 1) fade2(0, 3) watch(5) entity_setPosition(cam, node_x(e5), node_y(e5), 5, 0, 0, 1) watch(5) fade2(1, 3) watch(3) overrideZoom(0) if v.leave then loadMap("forest04") else watch(1) fade2(0, 0) cam_toEntity(getNaija()) end --fade2(0,4) --loadMap("energytemple") end end
gpl-2.0
SamOatesPlugins/cuberite
Server/Plugins/APIDump/Hooks/OnChunkGenerated.lua
36
2855
return { HOOK_CHUNK_GENERATED = { CalledWhen = "After a chunk was generated. Notification only.", DefaultFnName = "OnChunkGenerated", -- also used as pagename Desc = [[ This hook is called when world generator finished its work on a chunk. The chunk data has already been generated and is about to be stored in the {{cWorld|world}}. A plugin may provide some last-minute finishing touches to the generated data. Note that the chunk is not yet stored in the world, so regular {{cWorld}} block API will not work! Instead, use the {{cChunkDesc}} object received as the parameter.</p> <p> See also the {{OnChunkGenerating|HOOK_CHUNK_GENERATING}} hook. ]], Params = { { Name = "World", Type = "{{cWorld}}", Notes = "The world to which the chunk will be added" }, { Name = "ChunkX", Type = "number", Notes = "X-coord of the chunk" }, { Name = "ChunkZ", Type = "number", Notes = "Z-coord of the chunk" }, { Name = "ChunkDesc", Type = "{{cChunkDesc}}", Notes = "Generated chunk data. Plugins may still modify the chunk data contained." }, }, Returns = [[ If the plugin returns false or no value, Cuberite will call other plugins' callbacks for this event. If a plugin returns true, no other callback is called for this event.</p> <p> In either case, Cuberite will then store the data from ChunkDesc as the chunk's contents in the world. ]], CodeExamples = { { Title = "Generate emerald ore", Desc = "This example callback function generates one block of emerald ore in each chunk, under the condition that the randomly chosen location is in an ExtremeHills biome.", Code = [[ function OnChunkGenerated(a_World, a_ChunkX, a_ChunkZ, a_ChunkDesc) -- Generate a psaudorandom value that is always the same for the same X/Z pair, but is otherwise random enough: -- This is actually similar to how Cuberite does its noise functions local PseudoRandom = (a_ChunkX * 57 + a_ChunkZ) * 57 + 19785486 PseudoRandom = PseudoRandom * 8192 + PseudoRandom; PseudoRandom = ((PseudoRandom * (PseudoRandom * PseudoRandom * 15731 + 789221) + 1376312589) % 0x7fffffff; PseudoRandom = PseudoRandom / 7; -- Based on the PseudoRandom value, choose a location for the ore: local OreX = PseudoRandom % 16; local OreY = 2 + ((PseudoRandom / 16) % 20); local OreZ = (PseudoRandom / 320) % 16; -- Check if the location is in ExtremeHills: if (a_ChunkDesc:GetBiome(OreX, OreZ) ~= biExtremeHills) then return false; end -- Only replace allowed blocks with the ore: local CurrBlock = a_ChunDesc:GetBlockType(OreX, OreY, OreZ); if ( (CurrBlock == E_BLOCK_STONE) or (CurrBlock == E_BLOCK_DIRT) or (CurrBlock == E_BLOCK_GRAVEL) ) then a_ChunkDesc:SetBlockTypeMeta(OreX, OreY, OreZ, E_BLOCK_EMERALD_ORE, 0); end end; ]], }, } , -- CodeExamples }, -- HOOK_CHUNK_GENERATED }
apache-2.0
sjznxd/lc-20121231
applications/luci-splash/luasrc/model/cbi/splash/splashtext.lua
23
1170
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Copyright 2010 Manuel Munz <freifunk@somakoma.de> 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 fs = require "nixio.fs" local splashtextfile = "/usr/lib/luci-splash/splashtext.html" f = SimpleForm("splashtext", translate("Edit Splash text"), translate("You can enter your own text that is displayed to clients here.<br />" .. "It is possible to use the following markers: " .. "###COMMUNITY###, ###COMMUNITY_URL###, ###CONTACTURL###, ###LEASETIME###, ###LIMIT### and ###ACCEPT###.")) t = f:field(TextValue, "text") t.rmempty = true t.rows = 30 function t.cfgvalue() return fs.readfile(splashtextfile) or "" end function f.handle(self, state, data) if state == FORM_VALID then if data.text then fs.writefile(splashtextfile, data.text:gsub("\r\n", "\n")) else fs.unlink(splashtextfile) end end return true end return f
apache-2.0
jbeich/Aquaria
files/scripts/entities/collectibleturtleegg.lua
6
1374
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end -- song cave collectible dofile("scripts/include/collectibletemplate.lua") function init(me) v.commonInit(me, "Collectibles/turtle-egg", FLAG_COLLECTIBLE_TURTLEEGG) end function update(me, dt) v.commonUpdate(me, dt) end function enterState(me, state) v.commonEnterState(me, state) if entity_isState(me, STATE_COLLECTEDINHOUSE) then createEntity("SeaTurtleBaby", "", entity_x(me)-100, entity_y(me)-50) createEntity("SeaTurtleBaby", "", entity_x(me)-50, entity_y(me)-100) end end function exitState(me, state) v.commonExitState(me, state) end
gpl-2.0
nyczducky/darkstar
scripts/globals/mobskills/Corrosive_ooze.lua
34
1192
--------------------------------------------------- -- Corrosive Ooze -- Family: Slugs -- Description: Deals water damage to an enemy. Additional Effect: Attack Down and Defense Down. -- Type: Magical -- Utsusemi/Blink absorb: Ignores shadows -- Range: Radial -- Notes: --------------------------------------------------- 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 typeEffectOne = EFFECT_ATTACK_DOWN; local typeEffectTwo = EFFECT_DEFENSE_DOWN; local duration = 120; MobStatusEffectMove(mob, target, typeEffectOne, 15, 0, duration); MobStatusEffectMove(mob, target, typeEffectTwo, 15, 0, duration); local dmgmod = 1; local baseDamage = mob:getWeaponDmg()*4.2; local info = MobMagicalMove(mob,target,skill,baseDamage,ELE_WATER,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WATER,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
AquariaOSE/Aquaria
game_scripts/_mods/guert_mod/tempo/nauplius.lua
12
6551
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end -- ================================================================================================ -- N A U P L I U S -- ================================================================================================ -- ================================================================================================ -- S T A T E S -- ================================================================================================ local MOVE_STATE_UP = 0 local MOVE_STATE_DOWN = 1 -- ================================================================================================ -- L O C A L V A R I A B L E S -- ================================================================================================ v.blupTimer = 0 v.dirTimer = 0 v.blupTime = 3.0 v.fireDelay = 2 v.moveTimer = 0 v.maxShots = 3 v.lastShot = v.maxShots -- ================================================================================================ -- F U N C T I O N S -- ================================================================================================ v.sz = 1.0 v.dir = 0 v.moveState = 0 v.moveTimer = 0 v.velx = 0 v.soundDelay = 0 v.dir = ORIENT_UP local function doIdleScale(me) entity_scale(me, 1.0*v.sz, 0.80*v.sz, v.blupTime, -1, 1, 1) end function init(me) setupBasicEntity( me, "nauplius", -- texture 4, -- health 2, -- manaballamount 2, -- exp 10, -- money 32, -- collideRadius (for hitting entities + spells) STATE_IDLE, -- initState 128, -- sprite width 128, -- sprite height 1, -- particle "explosion" type, 0 = none 0, -- 0/1 hit other entities off/on (uses collideRadius) 4000, -- updateCull -1: disabled, default: 4000 1 ) entity_setEntityType(me, ET_ENEMY) entity_setDeathParticleEffect(me, "PurpleExplode") entity_setDropChance(me, 5) entity_setEatType(me, EAT_FILE, "Jelly") entity_initHair(me, 40, 5, 30, "nauplius-tentacles") entity_scale(me, 0.75*v.sz, 1*v.sz) doIdleScale(me) entity_exertHairForce(me, 0, 400, 1) entity_setState(me, STATE_IDLE) end function update(me, dt) dt = dt * 1.5 if avatar_isBursting() or entity_getRiding(getNaija())~=0 then local e = entity_getRiding(getNaija()) if entity_touchAvatarDamage(me, 32, 0, 400) then if e~=0 then local x,y = entity_getVectorToEntity(me, e) x,y = vector_setLength(x, y, 500) entity_addVel(e, x, y) end local len = 500 local x,y = entity_getVectorToEntity(getNaija(), me) x,y = vector_setLength(x, y, len) entity_push(me, x, y, 0.2, len, 0) entity_sound(me, "JellyBlup", 800) end else if entity_touchAvatarDamage(me, 32, 0, 1000) then entity_sound(me, "JellyBlup", 800) end end entity_handleShotCollisions(me) v.sx,v.sy = entity_getScale(me) -- Quick HACK to handle getting bumped out of the water. --achurch if not entity_isUnderWater(me) then v.moveState = MOVE_STATE_DOWN v.moveTimer = 5 + math.random(200)/100.0 + math.random(3) entity_setMaxSpeed(me, 500) entity_setMaxSpeedLerp(me, 1, 0) entity_addVel(me, 0, 500*dt) entity_updateMovement(me, dt) entity_setHairHeadPosition(me, entity_x(me), entity_y(me)) entity_updateHair(me, dt) return elseif not entity_isState(me, STATE_PUSH) then entity_setMaxSpeed(me, 50) end v.moveTimer = v.moveTimer - dt if v.moveTimer < 0 then if v.moveState == MOVE_STATE_DOWN then v.moveState = MOVE_STATE_UP v.fireDelay = 0.5 entity_setMaxSpeedLerp(me, 1.5, 0.2) entity_scale(me, 0.80, 1, 1, 1, 1) v.moveTimer = 3 + math.random(200)/100.0 entity_sound(me, "JellyBlup") elseif v.moveState == MOVE_STATE_UP then v.moveState = MOVE_STATE_DOWN doIdleScale(me) entity_setMaxSpeedLerp(me, 1, 1) v.moveTimer = math.random(4) + math.random(200)/100.0 end end if v.moveState == MOVE_STATE_UP then if v.dir == ORIENT_UP then entity_addVel(me, 0, -4000*dt) if isObstructed(entity_x(me), entity_y(me)-40) then v.dir = ORIENT_DOWN end elseif v.dir == ORIENT_DOWN then entity_addVel(me, 0, 4000*dt) if isObstructed(entity_x(me), entity_y(me)+40) then v.dir = ORIENT_UP end end --entity_rotateToVel(me, 1) if not(entity_hasTarget(me)) then entity_findTarget(me, 1200) else if v.fireDelay > 0 then v.fireDelay = v.fireDelay - dt if v.fireDelay < 0 then spawnParticleEffect("ArmaShot", entity_x(me), entity_y(me) - 80) local s = createShot("Raspberry", me, entity_getTarget(me), entity_x(me), entity_y(me) - 20) shot_setAimVector(s, entity_getNormal(me)) shot_setOut(s, 64) if v.lastShot <= 1 then v.fireDelay = 4 v.lastShot = v.maxShots else v.fireDelay = 0.5 v.lastShot = v.lastShot - 1 end end end end elseif v.moveState == MOVE_STATE_DOWN then entity_addVel(me, 0, 50*dt) --entity_rotateTo(me, 0, 3) entity_exertHairForce(me, 0, 200, dt*0.6, -1) end entity_doEntityAvoidance(me, dt, 32, 1.0) entity_doCollisionAvoidance(me, 1.0, 8, 1.0) entity_updateCurrents(me, dt) entity_updateMovement(me, dt) entity_setHairHeadPosition(me, entity_x(me), entity_y(me)) entity_updateHair(me, dt) end function hitSurface(me) end function dieNormal(me) end function enterState(me) if entity_isState(me, STATE_IDLE) then entity_setMaxSpeed(me, 50) elseif entity_isState(me, STATE_DEAD) then end end function damage(me, attacker, bone, damageType, dmg) if entity_isName(attacker, "Nauplius") then return false end if damageType == DT_AVATAR_BITE then entity_changeHealth(me, -dmg) end return true end function exitState(me) end
gpl-2.0
nyczducky/darkstar
scripts/zones/Mount_Zhayolm/mobs/Brass_Borer.lua
29
1544
----------------------------------- -- Area: Mount Zhayolm -- MOB: Brass Borer ----------------------------------- require("scripts/globals/status"); -- TODO: Damage resistances in streched and curled stances. Halting movement during stance change. ----------------------------------- -- OnMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setLocalVar("formTime", os.time() + math.random(43,47)); end; ----------------------------------- -- onMobRoam Action -- Autochange stance ----------------------------------- function onMobRoam(mob) local roamTime = mob:getLocalVar("formTime"); if (mob:AnimationSub() == 0 and os.time() > roamTime) then mob:AnimationSub(1); mob:setLocalVar("formTime", os.time() + math.random(43,47)); elseif (mob:AnimationSub() == 1 and os.time() > roamTime) then mob:AnimationSub(0); mob:setLocalVar("formTime", os.time() + math.random(43,47)); end end; ----------------------------------- -- OnMobFight Action -- Stance change in battle ----------------------------------- function onMobFight(mob,target) local fightTime = mob:getLocalVar("formTime"); if (mob:AnimationSub() == 0 and os.time() > fightTime) then mob:AnimationSub(1); mob:setLocalVar("formTime", os.time() + math.random(43,47)); elseif (mob:AnimationSub() == 1 and os.time() > fightTime) then mob:AnimationSub(0); mob:setLocalVar("formTime", os.time() + math.random(43,47)); end end; function onMobDeath(mob) end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Southern_San_dOria/npcs/Ullasa.lua
17
1699
----------------------------------- -- Area: Southern San d'Oria -- NPC: Ullasa -- General Info NPC ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Southern_San_dOria/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if player:getVar("UnderOathCS") == 2 then -- Quest: Under Oath - PLD AF3 player:startEvent(0x028); else player:startEvent(0x027); 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 == 0x028) then player:setVar("UnderOathCS", 3) -- Quest: Under Oath - PLD AF3 end end;
gpl-3.0
ld-test/lzmq-ffi
examples/perf2/lat_nomsg/remote_lat.lua
15
1289
local ZMQ_NAME = "lzmq" local argc = select("#", ...) local argv = {...} if (argc < 3) or (argc > 4)then print("usage: local_lat <bind-to> <message-size> <roundtrip-count> [ffi]") return 1 end local connect_to = argv [1] local message_size = assert(tonumber(argv [2])) local roundtrip_count = assert(tonumber(argv [3])) if argv [4] then assert(argv [4] == 'ffi') ZMQ_NAME = "lzmq.ffi" end local zmq = require(ZMQ_NAME) local ztimer = require(ZMQ_NAME .. ".timer") local zthreads = require(ZMQ_NAME .. ".threads") local zassert = zmq.assert local ctx = zthreads.context() local s = zassert(ctx:socket{zmq.REQ, connect = connect_to; }) local msg = ("0"):rep(message_size) -- local watch, us = ztimer.monotonic():start(), 1000 local watch, us = zmq.utils.stopwatch():start(), 1 for i = 1, roundtrip_count do zassert(s:send(msg)) msg = zassert(s:recv()) if #msg ~= message_size then printf ("message of incorrect size received\n"); return -1; end end local elapsed = watch:stop() local latency = (elapsed * us) / (roundtrip_count * 2) print(string.format("message size: %d [B]", message_size )) print(string.format("roundtrip count: %d", roundtrip_count)) print(string.format("average latency: %.3f [us]", latency ))
mit
nyczducky/darkstar
scripts/globals/items/yellow_curry_bun_+1.lua
12
2179
----------------------------------------- -- ID: 5763 -- Item: yellow_curry_bun_+1 -- Food Effect: 60 min, All Races ----------------------------------------- -- TODO: Group effects -- Health Points 30 -- Strength 5 -- Vitality 2 -- Agility 3 -- Intelligence -2 -- Attack 22% (caps @ 85) -- Ranged Attack 22% (caps @ 85) -- Resist Sleep +5 -- Resist Stun +6 -- hHP +6 -- hMP +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,3600,5763); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 30); target:addMod(MOD_STR, 5); target:addMod(MOD_VIT, 2); target:addMod(MOD_AGI, 3); target:addMod(MOD_INT, -2); target:addMod(MOD_FOOD_ATTP, 22); target:addMod(MOD_FOOD_ATT_CAP, 85); target:addMod(MOD_FOOD_RATTP, 22); target:addMod(MOD_FOOD_RATT_CAP, 85); target:addMod(MOD_SLEEPRES, 5); target:addMod(MOD_STUNRES, 6); target:addMod(MOD_HPHEAL, 6); target:addMod(MOD_MPHEAL, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 30); target:delMod(MOD_STR, 5); target:delMod(MOD_VIT, 2); target:delMod(MOD_AGI, 3); target:delMod(MOD_INT, -2); target:delMod(MOD_FOOD_ATTP, 22); target:delMod(MOD_FOOD_ATT_CAP, 85); target:delMod(MOD_FOOD_RATTP, 22); target:delMod(MOD_FOOD_RATT_CAP, 85); target:delMod(MOD_SLEEPRES, 5); target:delMod(MOD_STUNRES, 6); target:delMod(MOD_HPHEAL, 6); target:delMod(MOD_MPHEAL, 3); end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Arrapago_Reef/npcs/_jic.lua
27
3547
----------------------------------- -- Area: Arrapago Reef -- Door: Runic Seal -- @pos 36 -10 620 54 ----------------------------------- package.loaded["scripts/zones/Arrapago_Reef/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/besieged"); require("scripts/zones/Arrapago_Reef/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(ILRUSI_ASSAULT_ORDERS)) then local assaultid = player:getCurrentAssault(); local recommendedLevel = getRecommendedAssaultLevel(assaultid); local armband = 0; if (player:hasKeyItem(ASSAULT_ARMBAND)) then armband = 1; end player:startEvent(0x00DB, assaultid, -4, 0, recommendedLevel, 2, armband); else player:messageSpecial(NOTHING_HAPPENS); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option,target) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local assaultid = player:getCurrentAssault(); local cap = bit.band(option, 0x03); if (cap == 0) then cap = 99; elseif (cap == 1) then cap = 70; elseif (cap == 2) then cap = 60; else cap = 50; end player:setVar("AssaultCap", cap); local party = player:getParty(); if (party ~= nil) then for i,v in ipairs(party) do if (not (v:hasKeyItem(ILRUSI_ASSAULT_ORDERS) and v:getCurrentAssault() == assaultid)) then player:messageText(target,MEMBER_NO_REQS, false); player:instanceEntry(target,1); return; elseif (v:getZone() == player:getZone() and v:checkDistance(player) > 50) then player:messageText(target,MEMBER_TOO_FAR, false); player:instanceEntry(target,1); return; end end end player:createInstance(player:getCurrentAssault(), 55); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,target) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x6C or (csid == 0xDB and option == 4)) then player:setPos(0,0,0,0,55); end end; ----------------------------------- -- onInstanceLoaded ----------------------------------- function onInstanceCreated(player,target,instance) if (instance) then instance:setLevelCap(player:getVar("AssaultCap")); player:setVar("AssaultCap", 0); player:setInstance(instance); player:instanceEntry(target,4); player:delKeyItem(ILRUSI_ASSAULT_ORDERS); player:delKeyItem(ASSAULT_ARMBAND); if (party ~= nil) then for i,v in ipairs(party) do if v:getID() ~= player:getID() and v:getZone() == player:getZone() then v:setInstance(instance); v:startEvent(0x6C, 2); v:delKeyItem(ILRUSI_ASSAULT_ORDERS); end end end else player:messageText(target,CANNOT_ENTER, false); player:instanceEntry(target,3); end end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/Dynamis_Lord.lua
23
2056
----------------------------------- -- Area: Dynamis Xarcabard -- NM: Dynamis_Lord -- -- In OLD Dynamis, he is spawned by killing 15 Kindred NMs.. -- ..NOT by killing Ying and Yang. -- -- In Neo Dynamis, he is spawned by trading -- a Shrouded Bijou to the ??? in front of Castle Zvahl. ----------------------------------- require("scripts/globals/status"); require("scripts/globals/titles"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) local YingID = 17330183; local YangID = 17330184; if (mob:getBattleTime() % 90 == 0 and mob:getBattleTime() >= 90) then if (GetMobAction(YingID) == ACTION_NONE and GetMobAction(YangID) == ACTION_NONE) then GetMobByID(YingID):setSpawn(-414.282,-44,20.427); -- These come from DL's spawn point when he spawns them. GetMobByID(YangID):setSpawn(-414.282,-44,20.427); SpawnMob(YingID):updateEnmity(target); -- Respawn the dragons after 90sec SpawnMob(YangID):updateEnmity(target); end end if (GetMobAction(YingID) == ACTION_ROAMING) then -- ensure that it's always going after someone, can't kite it away! GetMobByID(YingID):updateEnmity(target); end if (GetMobAction(YangID) == ACTION_ROAMING) then GetMobByID(YangID):updateEnmity(target); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) local npc = GetNPCByID(17330781); -- ID of the '???' target. player:addTitle(LIFTER_OF_SHADOWS); npc:setPos(mob:getXPos(),mob:getYPos(),mob:getZPos()); npc:setStatus(0); -- Spawn the '???' DespawnMob(17330183); -- despawn dragons DespawnMob(17330184); end;
gpl-3.0
nyczducky/darkstar
scripts/globals/items/slice_of_giant_sheep_meat.lua
12
1358
----------------------------------------- -- ID: 4372 -- Item: slice_of_giant_sheep_meat -- Food Effect: 5Min, Galka only ----------------------------------------- -- Strength 2 -- Intelligence -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 8) then result = 247; end if (target:getMod(MOD_EAT_RAW_MEAT) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4372); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 2); target:addMod(MOD_INT, -4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 2); target:delMod(MOD_INT, -4); end;
gpl-3.0
HalosGhost/irc_bot
src/plugins/isup.lua
1
1117
local modules = modules local https = require("ssl.https") local plugin = {} local messages = { "The webserver hasn't sent a final response, status %s", "The website is up status %s", "The website is up with a %s redirect", "Client error, webserver returned status %s", "Server returning error %s" } plugin.help = 'Usage: isup <website>' plugin.main = function(args) local website = args.message if args.conf.debug then print(website) end if not website then modules.irc.privmsg(args.target, 'Give me a website or hostname to check') return end local address = website:find('^https?://') and website or ('http://%s'):format(website) local response, httpcode = https.request(address) if response then local code = string.sub(tostring(httpcode), 1, 1) local reply = messages[tonumber(code)]:format(httpcode) modules.irc.privmsg(args.target, reply) else modules.irc.privmsg(args.target, "The website is currently down") end end return plugin
gpl-2.0
abosalah22/memo
plugins/time.lua
3
2836
--[[ $ :) -- - ( #ابو_شهوده ) - -- $ :) -- - ( @abo_shosho98 ) - -- $ :) --Channel-( @aboaloshbot )-- $ :) ]]-- api_key = nil base_api = "https://maps.googleapis.com/maps/api" dateFormat = "%A %d %B - %H:%M:%S" -- Need the utc time for the google api function utctime() return os.time(os.date("!*t")) end -- Use the geocoding api to get the lattitude and longitude with accuracy specifier -- CHECKME: this seems to work without a key?? function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Get the data lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end -- Use timezone api to get the time in the lat, -- Note: this needs an API key function get_time(lat,lng) local api = base_api .. "/timezone/json?" -- Get a timestamp (server time is relevant here) local timestamp = utctime() local parameters = "location=" .. URL.escape(lat) .. "," .. URL.escape(lng) .. "&timestamp="..URL.escape(timestamp) if api_key ~=nil then parameters = parameters .. "&key="..api_key end local res,code = https.request(api..parameters) if code ~= 200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Construct what we want -- The local time in the location is: -- timestamp + rawOffset + dstOffset local localTime = timestamp + data.rawOffset + data.dstOffset return localTime, data.timeZoneId end return localTime end function getformattedLocalTime(area) if area == nil then return "The time in nowhere is never" end lat,lng,acc = get_latlong(area) if lat == nil and lng == nil then return 'It seems that in "'..area..'" they do not have a concept of time.' end local localTime, timeZoneId = get_time(lat,lng) return "The local time in "..timeZoneId.." is: ".. os.date(dateFormat,localTime) end function run(msg, matches) local a = msg['id'] local b = getformattedLocalTime(matches[1]) reply_msg(a,b,ok_cb,true) end return { description = "Displays the local time in an area", usage = "/time [area]: Displays the local time in that area", patterns = {"^/time (.*)$"}, run = run }
gpl-2.0
nyczducky/darkstar
scripts/zones/Abyssea-Altepa/npcs/Cavernous_Maw.lua
29
1099
----------------------------------- -- Area: Abyssea Altepa -- NPC: Cavernous Maw -- @pos 444.000 -0.500 320.000 218 -- Notes Teleports Players to South Gustaberg ----------------------------------- package.loaded["scripts/zones/Abyssea-Altepa/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00C8); 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 == 0x00C8 and option == 1) then player:setPos(343,0,-679,199,107) end end;
gpl-3.0
SamOatesPlugins/cuberite
Server/Plugins/APIDump/Hooks/OnPlayerBreakingBlock.lua
44
1596
return { HOOK_PLAYER_BREAKING_BLOCK = { CalledWhen = "Just before a player breaks a block. Plugin may override / refuse. ", DefaultFnName = "OnPlayerBreakingBlock", -- also used as pagename Desc = [[ This hook is called when a {{cPlayer|player}} breaks a block, before the block is actually broken in the {{cWorld|World}}. Plugins may refuse the breaking.</p> <p> See also the {{OnPlayerBrokenBlock|HOOK_PLAYER_BROKEN_BLOCK}} hook for a similar hook called after the block is broken. ]], Params = { { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who is digging the block" }, { Name = "BlockX", Type = "number", Notes = "X-coord of the block" }, { Name = "BlockY", Type = "number", Notes = "Y-coord of the block" }, { Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" }, { Name = "BlockFace", Type = "number", Notes = "Face of the block upon which the player is acting. One of the BLOCK_FACE_ constants" }, { Name = "BlockType", Type = "BLOCKTYPE", Notes = "The block type of the block being broken" }, { Name = "BlockMeta", Type = "NIBBLETYPE", Notes = "The block meta of the block being broken " }, }, Returns = [[ If the function returns false or no value, other plugins' callbacks are called, and then the block is broken. If the function returns true, no other plugin's callback is called and the block breaking is cancelled. The server re-sends the block back to the player to replace it (the player's client already thinks the block was broken). ]], }, -- HOOK_PLAYER_BREAKING_BLOCK }
apache-2.0
ameenetemady/DeepPep
app/app8_18mix/experiment_3_multiArch.lua
1
1030
--[[ variations: 1) number of convolutional[+dropout,maxpooling,relu] layers: a: dropout rate, b: nChannels(input/output), c: nKwSize, d: nPoolingWindowSize --]] torch.manualSeed(1) require('../../CExperimentSparseBlockFlex.lua') require('../../CDataLoader.lua') local exprSetting = require('./lSettings.lua') local archFactory = require('../../deposArchFactory.lua') local trainerPool = trainerPool or require('../../deposTrainerPool.lua') -- 1) initialize local nExprId = tonumber(arg[1]) exprSetting.setExprId(nExprId) local fuArchBuilder = archFactory.getArchBuilder(nExprId) local oDataLoader = CDataLoader.new(exprSetting) oExperiment = CExperimentSparseBlockFlex.new(oDataLoader, fuArchBuilder) oExperiment:buildArch() -- 2) train oExperiment:roundTrip() local taTrainParams = trainerPool.getDefaultTrainParams(nil, "SGD", 2500) taTrainParams.taOptimParams.learningRate = 2.0 oExperiment:train(taTrainParams) -- 3) predict local taProtInfo = oExperiment:getConfidenceRange() oExperiment:saveResult(taProtInfo)
apache-2.0
hanikk/tele-you
plugins/danbooru.lua
616
1750
do local URL = "http://danbooru.donmai.us" local URL_NEW = "/posts.json" local URL_POP = "/explore/posts/popular.json" local scale_day = "?scale=day" local scale_week = "?scale=week" local scale_month = "?scale=month" local function get_post(url) local b, c, h = http.request(url) if c ~= 200 then return nil end local posts = json:decode(b) return posts[math.random(#posts)] end local function run(msg, matches) local url = URL if matches[1] == "!danbooru" then url = url .. URL_NEW else url = url .. URL_POP if matches[1] == "d" then url = url .. scale_day elseif matches[1] == "w" then url = url .. scale_week elseif matches[1] == "m" then url = url .. scale_month end end local post = get_post(url) if post then vardump(post) local img = URL .. post.large_file_url send_photo_from_url(get_receiver(msg), img) local txt = '' if post.tag_string_artist ~= '' then txt = 'Artist: ' .. post.tag_string_artist .. '\n' end if post.tag_string_character ~= '' then txt = txt .. 'Character: ' .. post.tag_string_character .. '\n' end if post.file_size ~= '' then txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url end return txt end end return { description = "Gets a random fresh or popular image from Danbooru", usage = { "!danbooru - gets a random fresh image from Danbooru 🔞", "!danboorud - random daily popular image 🔞", "!danbooruw - random weekly popular image 🔞", "!danboorum - random monthly popular image 🔞" }, patterns = { "^!danbooru$", "^!danbooru ?(d)$", "^!danbooru ?(w)$", "^!danbooru ?(m)$" }, run = run } end
gpl-2.0
nyczducky/darkstar
scripts/zones/Windurst_Waters/npcs/Panna-Donna.lua
14
1051
----------------------------------- -- Area: Windurst Waters -- NPC: Panna-Donna -- Type: Mission NPC -- @zone 238 -- @pos -57.502 -6 229.571 -- -- Auto-Script: Requires Verification (Verfied By Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0069); 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
Ikesters/ArcPro
src/scripts/lua/Lua/Stable Scripts/Azeroth/Karazhan/BOSS_Karazhan_Kilrek.lua
30
1152
function Kilrek_Broken_Pact(Unit, event, miscunit, misc) if Unit:GetHealthPct() < 2 and Didthat == 0 then Unit:FullCastSpellOnTarget(30065,Unit:GetUnitBySqlId(15688)) Unit:SendChatMessage(11, 0, "You let me down Terestian, you will pay for this...") Didthat = 1 else end end function Kilrek_FireBolt(Unit, event, miscunit, misc) print "Kilrek FireBolt" Unit:FullCastSpellOnTarget(15592,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "Take that...") end function Kilrek_Summon_Imps(Unit, event, miscunit, misc) print "Kilrek Summon Imps" Unit:FullCastSpell(34237) Unit:SendChatMessage(11, 0, "Help me...") end function Kilrek_Amplify_Flames(Unit, event, miscunit, misc) print "Kilrek Amplify Flames" Unit:FullCastSpellOnTarget(30053,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "Take fire will hurt you more...") end function Kilrek(unit, event, miscunit, misc) print "Kilrek" unit:RegisterEvent("Kilrek_Broken_Pact",1000,1) unit:RegisterEvent("Kilrek_FireBolt",8000,0) unit:RegisterEvent("Kilrek_Summon_Imps",30000,0) unit:RegisterEvent("Kilrek_Amplify_Flames",45000,0) end RegisterUnitEvent(17229,1,"Kilrek")
agpl-3.0
naxiwer/Atlas
lib/proxy/balance.lua
41
2807
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] module("proxy.balance", package.seeall) function idle_failsafe_rw() local backend_ndx = 0 for i = 1, #proxy.global.backends do local s = proxy.global.backends[i] local conns = s.pool.users[proxy.connection.client.username] if conns.cur_idle_connections > 0 and s.state ~= proxy.BACKEND_STATE_DOWN and s.state ~= proxy.BACKEND_STATE_OFFLINE and s.type == proxy.BACKEND_TYPE_RW then backend_ndx = i break end end return backend_ndx end function idle_ro() local max_conns = -1 local max_conns_ndx = 0 for i = 1, #proxy.global.backends do local s = proxy.global.backends[i] local conns = s.pool.users[proxy.connection.client.username] -- pick a slave which has some idling connections if s.type == proxy.BACKEND_TYPE_RO and s.state ~= proxy.BACKEND_STATE_DOWN and s.state ~= proxy.BACKEND_STATE_OFFLINE and conns.cur_idle_connections > 0 then if max_conns == -1 or s.connected_clients < max_conns then max_conns = s.connected_clients max_conns_ndx = i end end end return max_conns_ndx end function cycle_read_ro() local backends = proxy.global.backends local rwsplit = proxy.global.config.rwsplit local max_weight = rwsplit.max_weight local cur_weight = rwsplit.cur_weight local next_ndx = rwsplit.next_ndx local ndx_num = rwsplit.ndx_num local ndx = 0 for i = 1, ndx_num do --ÿ¸öquery×î¶àÂÖѯndx_num´Î local s = backends[next_ndx] if s.type == proxy.BACKEND_TYPE_RO and s.weight >= cur_weight and s.state ~= proxy.BACKEND_STATE_DOWN and s.state ~= proxy.BACKEND_STATE_OFFLINE and s.pool.users[proxy.connection.client.username].cur_idle_connections > 0 then ndx = next_ndx end if next_ndx == ndx_num then --ÂÖѯÍêÁË×îºóÒ»¸öndx£¬È¨Öµ¼õÒ» cur_weight = cur_weight - 1 if cur_weight == 0 then cur_weight = max_weight end next_ndx = 1 else --·ñÔòÖ¸Ïòϸöndx next_ndx = next_ndx + 1 end if ndx ~= 0 then break end end rwsplit.cur_weight = cur_weight rwsplit.next_ndx = next_ndx return ndx end
gpl-2.0
pombredanne/splash
splash/tests/lua_modules/emulation.lua
4
3462
-- -- This module provides render_har, render_html and render_png methods -- which emulate render.har, render.html and render.png endpoints. -- They are used in tests; behaviour is not 100% the same. -- local Splash = require("splash") -- -- A method with a common workflow: go to a page, wait for some time. -- splash.qtrender.DefaultRenderScript implements a similar logic in Python. -- function Splash:go_and_wait(args) -- content-type for error messages. Callers should set their -- own content-type before returning the result. self:set_result_content_type("text/plain; charset=utf-8") -- prepare & validate arguments local args = args or self.args local url = args.url if not url then error("'url' argument is required") end local wait = tonumber(args.wait) if not wait and (self.args.render_all or self.args.viewport == "full") then error("non-zero 'wait' is required when rendering whole page") end self.images_enabled = self.args.images -- if viewport is 'full' it should be set only after waiting if args.viewport ~= nil and args.viewport ~= "full" then local w, h = string.match(args.viewport, '^(%d+)x(%d+)') if w == nil or h == nil then error('Invalid viewport size format: ' .. args.viewport) end self:set_viewport_size(tonumber(w), tonumber(h)) end -- set a resource timeout self.resource_timeout = args.resource_timeout local ok, reason = self:go{url=url, baseurl=args.baseurl} if not ok then -- render.xxx endpoints don't return HTTP errors as errors, -- so here we also only raising an exception is an error is not -- caused by a 4xx or 5xx HTTP response. if reason == 'render_error' or reason == 'error' then self:set_result_status_code(502) elseif string.sub(reason, 0,4) ~= 'http' then error(reason) end end assert(self:_wait_restart_on_redirects(wait, 10)) end function Splash:_wait_restart_on_redirects(time, max_redirects) if not time then return true end local redirects_remaining = max_redirects while redirects_remaining do local ok, reason = self:wait{time, cancel_on_redirect=true} if reason ~= 'redirect' then return ok, reason end redirects_remaining = redirects_remaining - 1 end error("Maximum number of redirects happen") end -- -- "Endpoints" -- local emulation = {} function emulation.render_har(splash) splash:go_and_wait(splash.args) return splash:har() end function emulation.render_html(splash) splash:go_and_wait(splash.args) splash:set_result_content_type("text/html; charset=utf-8") return splash:html() end function emulation.render_png(splash) splash:go_and_wait(splash.args) splash:set_result_content_type("image/png") local render_all = (splash.args.render_all or splash.args.viewport == "full") return splash:png{ width=splash.args.width, height=splash.args.height, render_all=render_all, scale_method=splash.args.scale_method, } end function emulation.render_jpeg(splash) splash:go_and_wait(splash.args) splash:set_result_content_type("image/jpeg") local render_all = (splash.args.render_all or splash.args.viewport == "full") return splash:jpeg{ width=splash.args.width, height=splash.args.height, render_all=render_all, scale_method=splash.args.scale_method, quality=splash.args.quality, } end return emulation
bsd-3-clause
AquariaOSE/Aquaria
files/scripts/maps/_unused/node_vision_energytemple.lua
6
1209
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end function init(me) end function update(me, dt) if isFlag(FLAG_VISION_ENERGYTEMPLE, 0) then if node_isEntityIn(me, getNaija()) then setFlag(FLAG_VISION_ENERGYTEMPLE, 1) vision("EnergyTemple", 3) playMusic("OpenWaters") setMusicToPlay("OpenWaters") voice("Naija_FirstVision") end end end
gpl-2.0
nyczducky/darkstar
scripts/globals/items/serving_of_flounder_meuniere_+1.lua
12
1659
----------------------------------------- -- ID: 4345 -- Item: serving_of_flounder_meuniere_+1 -- Food Effect: 240Min, All Races ----------------------------------------- -- Dexterity 6 -- Vitality 1 -- Mind -1 -- Ranged ACC 15 -- Ranged ATT % 14 -- Ranged ATT Cap 30 -- Enmity -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,4345); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 6); target:addMod(MOD_VIT, 1); target:addMod(MOD_MND, -1); target:addMod(MOD_RACC, 15); target:addMod(MOD_FOOD_RATTP, 14); target:addMod(MOD_FOOD_RATT_CAP, 30); target:addMod(MOD_ENMITY, -4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 6); target:delMod(MOD_VIT, 1); target:delMod(MOD_MND, -1); target:delMod(MOD_RACC, 15); target:delMod(MOD_FOOD_RATTP, 14); target:delMod(MOD_FOOD_RATT_CAP, 30); target:delMod(MOD_ENMITY, -4); end;
gpl-3.0
nyczducky/darkstar
scripts/globals/items/bowl_of_quadav_stew.lua
12
1385
----------------------------------------- -- ID: 4569 -- Item: Bowl of Quadav Stew -- Food Effect: 180Min, All Races ----------------------------------------- -- Agility -4 -- Vitality 2 -- Defense % 17 -- Defense Cap 60 ----------------------------------------- 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,4569); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, -4); target:addMod(MOD_VIT, 2); target:addMod(MOD_FOOD_DEFP, 17); target:addMod(MOD_FOOD_DEF_CAP, 60); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, -4); target:delMod(MOD_VIT, 2); target:delMod(MOD_FOOD_DEFP, 17); target:delMod(MOD_FOOD_DEF_CAP, 60); end;
gpl-3.0
nyczducky/darkstar
scripts/zones/La_Theine_Plateau/mobs/Poison_Funguar.lua
12
1099
----------------------------------- -- Area: La Theine Plateau -- MOB: Poison Funguar ----------------------------------- require("scripts/zones/La_Theine_Plateau/MobIDs"); require("scripts/globals/fieldsofvalor"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) checkRegime(player,mob,71,2); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) local mobID = mob:getID(); if (Tumbling_Truffle_PH[mobID] ~= nil) then -- printf("%u is a PH",mob); local TT_ToD = GetServerVariable("[POP]Tumbling_Truffle"); if (TT_ToD <= os.time(t) and GetMobAction(Tumbling_Truffle) == 0) then if (math.random(1,20) == 5) then UpdateNMSpawnPoint(Tumbling_Truffle); GetMobByID(Tumbling_Truffle):setRespawnTime(GetMobRespawnTime(mobID)); SetServerVariable("[PH]Tumbling_Truffle", mobID); DeterMob(mobID, true); end end end end;
gpl-3.0
AquariaOSE/Aquaria
files/scripts/maps/map_forestvision.lua
6
3437
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end function init() setCutscene(1,1) toggleDamageSprite(false) fade2(0, 1, 1, 1, 1) --return setOverrideVoiceFader(0.6) entity_setPosition(getNaija(), 0, 0) local camDummy = createEntity("Empty") local cam1 = getNode("CAM1") local cam2 = getNode("CAM2") local cam3 = getNode("CAM3") local campan1 = getNode("CAMPAN1") local campan2 = getNode("CAMPAN2") local campan3 = getNode("CAMPAN3") local camdestroy1 = getNode("CAMDESTROY1") local camdestroy2 = getNode("CAMDESTROY2") -- 1 overrideZoom(1) entity_warpToNode(camDummy, cam1) cam_toEntity(camDummy) watch(0.5) fade2(0, 0, 1, 1, 1) fadeIn(1) watch(1) local n = getNaija() entity_setPosition(n, 0, 0) playMusicOnce("DruniadDance") entity_setPosition(camDummy, node_x(cam2), node_y(cam2), 10, 0, 0, 1) overrideZoom(0.8, 10.1) watch(4) while entity_isInterpolating(camDummy) do watch(FRAME_TIME) end entity_setPosition(camDummy, node_x(cam3), node_y(cam3), 5, 0, 0, 1) overrideZoom(0.5, 11) while entity_isInterpolating(camDummy) do watch(FRAME_TIME) end fade2(1, 1, 1, 1, 1) watch(1) --2 overrideZoom(1) entity_warpToNode(camDummy, campan1) cam_toEntity(camDummy) watch(0.5) entity_setPosition(camDummy, node_x(campan2), node_y(campan2), 16, 0, 0, 1) overrideZoom(0.5, 21) fade2(0, 1, 1, 1, 1) watch(1) watch(7) voice("Naija_Vision_Forest") watch(8) entity_setPosition(camDummy, node_x(campan3), node_y(campan3), 11, 0, 0, 1) watch(10) fade2(1, 1) watch(1) --3 overrideZoom(1) entity_warpToNode(camDummy, camdestroy1) cam_toEntity(camDummy) watch(0.5) entity_setPosition(camDummy, node_x(camdestroy2), node_y(camdestroy2), 10, 0, 0, 0) overrideZoom(0.5, 8) fade2(0, 1) watch(1) shakeCamera(20, 10) for i = 1,(8/FRAME_TIME) do local x, y = getScreenCenter() local node = getNode("DESTROY") local ent = getFirstEntity() while ent ~= 0 do if not entity_isState(ent, STATE_DONE) and node_isEntityIn(node, ent) and entity_x(ent) < x+200 then entity_setState(ent, STATE_DONE) end ent = getNextEntity() end watch(FRAME_TIME) end fade2(1, 4) watch(4) fade2(0, 0.1) toggleBlackBars(1) showImage("Visions/Forest/00") --[[ voice("") watchForVoice() ]]-- watch(10) hideImage() overrideZoom(1, 7) watch(4) changeForm(FORM_NATURE) watch(3) setOverrideVoiceFader(-1) setCutscene(0) voice("Naija_Song_NatureForm") loadMap("Tree02", "NAIJADONE") --[[ fade2(0, 0.5, 1, 1, 1) cam_toEntity(n) ]]-- end
gpl-2.0
nyczducky/darkstar
scripts/globals/weaponskills/guillotine.lua
18
1964
----------------------------------- -- Guillotine -- Scythe weapon skill -- Skill level: 200 -- Delivers a four-hit attack. Duration varies with TP. -- Modifiers: STR:25% ; MND:25% -- 100%TP 200%TP 300%TP -- 0.875 0.875 0.875 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 4; -- ftp damage mods (for Damage Varies with TP; lines are calculated in the function params.ftp100 = 0.875; params.ftp200 = 0.875; params.ftp300 = 0.875; -- wscs are in % so 0.2=20% params.str_wsc = 0.25; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.25; params.chr_wsc = 0.0; -- critical mods, again in % (ONLY USE FOR critICAL HIT VARIES WITH TP) params.crit100 = 0.0; params.crit200=0.0; params.crit300=0.0; params.canCrit = false; -- accuracy mods (ONLY USE FOR accURACY VARIES WITH TP) , should be the params.acc at those %s NOT the penalty values. Leave 0 if acc doesnt vary with tp. params.acc100 = 0; params.acc200=0; params.acc300=0; -- attack multiplier (only some WSes use this, this varies the actual ratio value, see Tachi: Kasha) 1 is default. params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.3; params.mnd_wsc = 0.5; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); if (damage > 0) then local duration = (tp/1000 * 30) + 30; if (target:hasStatusEffect(EFFECT_SILENCE) == false) then target:addStatusEffect(EFFECT_SILENCE, 1, 0, duration); end end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
nyczducky/darkstar
scripts/globals/spells/bluemagic/hecatomb_wave.lua
25
1913
----------------------------------------- -- Spell: Hecatomb Wave -- Deals wind damage to enemies within a fan-shaped area originating from the caster. Additional effect: Blindness -- Spell cost: 116 MP -- Monster Type: Demons -- Spell Type: Magical (Wind) -- Blue Magic Points: 3 -- Stat Bonus: AGI+1 -- Level: 54 -- Casting Time: 5.25 seconds -- Recast Time: 33.75 seconds -- Magic Bursts on: Detonation, Fragmentation, Light -- Combos: Max MP Boost ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT) - target:getStat(MOD_INT),BLUE_SKILL,1.0); local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.multiplier = 1.375; params.tMultiplier = 1.0; params.duppercap = 54; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.3; params.chr_wsc = 0.0; damage = BlueMagicalSpell(caster, target, spell, params, MND_BASED); damage = BlueFinalAdjustments(caster, target, spell, damage, params); if (damage > 0 and resist > 0.125) then local typeEffect = EFFECT_BLINDNESS; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,5,0,getBlueEffectDuration(caster,resist,typeEffect)); end return damage; end;
gpl-3.0
nyczducky/darkstar
scripts/globals/items/mithran_tomato.lua
12
1188
----------------------------------------- -- ID: 4390 -- Item: mithran_tomato -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility -3 -- Intelligence 1 ----------------------------------------- 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,4390); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, -3); target:addMod(MOD_INT, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, -3); target:delMod(MOD_INT, 1); end;
gpl-3.0
sevu/wesnoth
data/ai/micro_ais/micro_ai_self_data.lua
15
3878
-- This set of functions provides a consistent way of storing Micro AI variables -- in the AI's persistent data variable. These need to be stored inside -- a [micro_ai] tag, so that they are bundled together for a given Micro AI -- together with an ai_id= key. Their existence can then be checked when setting -- up another MAI. Otherwise other Micro AIs used in the same scenario might -- work incorrectly or not at all. -- Note that, ideally, we would delete these [micro_ai] tags when a Micro AI is -- deleted, but that that is not always possible as deletion can happen on -- another side's turn, while the data variable is only accessible during -- the AI turn. -- Note that, with this method, there can only ever be one of these tags for each -- Micro AI (but of course several when there are several Micro AIs for the -- same side). -- For the time being, we only allow key=value style variables. local micro_ai_self_data = {} function micro_ai_self_data.modify_mai_self_data(self_data, ai_id, action, vars_table) -- Modify data [micro_ai] tags -- @ai_id (string): the id of the Micro AI -- @action (string): "delete", "set" or "insert" -- @vars_table: table of key=value pairs with the variables to be set or inserted -- if this is set for @action="delete", then only the keys in @vars_table are deleted, -- otherwise the entire [micro_ai] tag is deleted -- Always delete the respective [micro_ai] tag, if it exists local existing_table for i,mai in ipairs(self_data, "micro_ai") do if (mai[1] == "micro_ai") and (mai[2].ai_id == ai_id) then if (action == "delete") and vars_table then for k,_ in pairs(vars_table) do mai[2][k] = nil end return end existing_table = mai[2] table.remove(self_data, i) break end end -- Then replace it, if the "set" action is selected -- or add the new keys to it, overwriting old ones with the same name, if action == "insert" if (action == "set") or (action == "insert") then local tag = { "micro_ai" } if (not existing_table) or (action == "set") then -- Important: we need to make a copy of the input table, not use it! tag[2] = {} for k,v in pairs(vars_table) do tag[2][k] = v end tag[2].ai_id = ai_id else for k,v in pairs(vars_table) do existing_table[k] = v end tag[2] = existing_table end table.insert(self_data, tag) end end function micro_ai_self_data.delete_mai_self_data(self_data, ai_id, vars_table) micro_ai_self_data.modify_mai_self_data(self_data, ai_id, "delete", vars_table) end function micro_ai_self_data.insert_mai_self_data(self_data, ai_id, vars_table) micro_ai_self_data.modify_mai_self_data(self_data, ai_id, "insert", vars_table) end function micro_ai_self_data.set_mai_self_data(self_data, ai_id, vars_table) micro_ai_self_data.modify_mai_self_data(self_data, ai_id, "set", vars_table) end function micro_ai_self_data.get_mai_self_data(self_data, ai_id, key) -- Get the content of the data [micro_ai] tag for the given @ai_id -- Return value: -- - If tag is found: value of key if @key parameter is given, otherwise -- table of key=value pairs (including the ai_id key) -- - If no such tag is found: nil (if @key is set), otherwise empty table for mai in wml.child_range(self_data, "micro_ai") do if (mai.ai_id == ai_id) then if key then return mai[key] else return mai end end end -- If we got here, no corresponding tag was found -- Return empty table; or nil if @key was set if (not key) then return {} end end return micro_ai_self_data
gpl-2.0
nyczducky/darkstar
scripts/zones/Abyssea-Uleguerand/npcs/qm6.lua
14
1348
----------------------------------- -- Zone: Abyssea-Uleguerand -- NPC: qm6 (???) -- Spawns Upas-Kamuy -- @pos ? ? ? 253 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(3252,1) and trade:getItemCount() == 1) then -- Player has all the required items. if (GetMobAction(17813935) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(17813935):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 3252); -- Inform player what items they need. 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
nyczducky/darkstar
scripts/zones/Port_Windurst/npcs/Khel_Pahlhama.lua
14
1243
----------------------------------- -- Area: Port Bastok -- NPC: Khel Pahlhama -- Linkshell merchant -- @pos 21 -2 -20 240 -- Confirmed shop stock, August 2013 ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:showText(npc,KHEL_PAHLHAMA_SHOP_DIALOG,513); stock = { 0x0200, 8000, --Linkshell 0x3f9d, 375 --Pendant Compass } showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Port_Bastok/npcs/Numa.lua
17
1786
----------------------------------- -- Area: Port Bastok -- NPC: Numa -- Standard Merchant NPC -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,NUMA_SHOP_DIALOG); stock = { 0x30A9, 5079,1, --Cotton Hachimaki 0x3129, 7654,1, --Cotton Dogi 0x31A9, 4212,1, --Cotton Tekko 0x3229, 6133,1, --Cotton Sitabaki 0x32A9, 3924,1, --Cotton Kyahan 0x3395, 3825,1, --Silver Obi 0x30A8, 759,2, --Hachimaki 0x3128, 1145,2, --Kenpogi 0x31A8, 630,2, --Tekko 0x3228, 915,2, --Sitabaki 0x32A8, 584,2, --Kyahan 0x02C0, 132,2, --Bamboo Stick 0x025D, 180,3, --Pickaxe 0x16EB, 13500,3, --Toolbag (Ino) 0x16EC, 18000,3, --Toolbag (Shika) 0x16ED, 18000,3 --Toolbag (Cho) } showNationShop(player, NATION_BASTOK, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nyczducky/darkstar
scripts/globals/items/anthos_xiphos.lua
41
1078
----------------------------------------- -- ID: 17750 -- Item: Anthos Xiphos -- Additional Effect: Water Damage ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 10; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(4,11); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_WATER, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_WATER,0); dmg = adjustForTarget(target,dmg,ELE_WATER); dmg = finalMagicNonSpellAdjustments(player,target,ELE_WATER,dmg); local message = MSGBASIC_ADD_EFFECT_DMG; if (dmg < 0) then message = MSGBASIC_ADD_EFFECT_HEAL; end return SUBEFFECT_WATER_DAMAGE,message,dmg; end end;
gpl-3.0
HalosGhost/irc_bot
src/plugins/mediawiki.lua
1
1692
local modules = modules local json = require 'json' local url = require 'socket.url' local https = require 'ssl.https' local plugin = {} plugin.help = 'Usage: mediawiki <APIURL> <search>' plugin.main = function(args) local _, _, apiurl, search = args.message:find('^(https?://%S+)%s+(.+)') if args.conf.debug then print(apiurl, query) end if not apiurl then modules.irc.privmsg(args.target, ('%s: Please give me a mediawiki API url, it should have api.php somewhere on the end.'):format(args.sender)) return end if not search then modules.irc.privmsg(args.target, ('%s: Please give me a search term.'):format(args.sender)) return end local act = '?action=opensearch&format=json&search=' local resp = https.request(apiurl .. act .. url.escape(search)) if not resp then modules.irc.privmsg(args.target, ('%s: Network request failed.'):format(args.sender)) return else if args.conf.debug then print(resp) end local res = json.decode(resp) if not res then modules.irc.privmsg(args.target, ('%s: Please give me a working API url.'):format(args.sender)) return elseif res["error"] then modules.irc.privmsg(args.target, ('%s: API error: %s'):format(args.sender, res["error"].code)) return else local lnk = (res[4][1] and res[4][1] ~= '') and res[4][1] or 'No results' local dsc = (res[3][1] and res[3][1] ~= '') and ' - ' .. res[3][1] or '' modules.irc.privmsg(args.target, ('%s: <%s>%s'):format(args.sender, lnk, dsc)) end end end return plugin
gpl-2.0
nyczducky/darkstar
scripts/zones/Den_of_Rancor/TextIDs.lua
7
1121
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6385; -- Obtained: <item> GIL_OBTAINED = 6386; -- Obtained <number> gil KEYITEM_OBTAINED = 6388; -- Obtained key item: <keyitem> FISHING_MESSAGE_OFFSET = 7233; -- You can't fish here HOMEPOINT_SET = 10533; -- Home point set! -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7340; -- You unlock the chest! CHEST_FAIL = 7341; -- Fails to open the chest. CHEST_TRAP = 7342; -- The chest was trapped! CHEST_WEAK = 7343; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7344; -- The chest was a mimic! CHEST_MOOGLE = 7345; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7346; -- The chest was but an illusion... CHEST_LOCKED = 7347; -- The chest appears to be locked. -- Other dialog LANTERN_OFFSET = 7205; -- The grating will not budge. -- conquest Base CONQUEST_BASE = 7046; -- Tallying conquest results...
gpl-3.0
AquariaOSE/Aquaria
files/scripts/entities/parrot.lua
6
3544
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end v.n = 0 v.dir = 0 local STATE_FLYING = 1000 local STATE_FALLING = 1001 v.inity = 0 v.drownTimer = 0 v.drownTime = 6 function init(me) setupEntity(me) entity_setEntityType(me, ET_ENEMY) entity_initSkeletal(me, "Parrot") --entity_setAllDamageTargets(me, true) --entity_setEntityLayer(me, 0) entity_setCollideRadius(me, 32) entity_setHealth(me, 5) entity_setState(me, STATE_FLYING) entity_setCanLeaveWater(me, true) entity_setMaxSpeed(me, 800) entity_scale(me, 0.8, 0.8) entity_setDeathParticleEffect(me, "ParrotHit") end function postInit(me) v.n = getNaija() entity_setTarget(me, v.n) v.inity = entity_y(me) end function update(me, dt) entity_handleShotCollisions(me) entity_touchAvatarDamage(me, entity_getCollideRadius(me), 0.5, 1000, 0) if entity_isState(me, STATE_FLYING) then if v.dir == 0 then entity_addVel(me, -800*dt, 0) else entity_addVel(me, 800*dt, 0) end entity_flipToVel(me) end if not entity_isState(me, STATE_IDLE) then entity_updateMovement(me, dt) --entity_setPosition(me, entity_x(me), v.inity, 0) end if entity_isUnderWater(me) then if not entity_isState(me, STATE_FALLING) then entity_setState(me, STATE_FALLING) end v.drownTimer = v.drownTimer + dt if v.drownTimer > v.drownTime then entity_damage(me, me, 999) end end end function enterState(me) if entity_isState(me, STATE_IDLE) then entity_animate(me, "idle", -1) elseif entity_isState(me, STATE_FLYING) then entity_animate(me, "fly", -1) entity_setWeight(me, 0) elseif entity_isState(me, STATE_FALLING) then entity_setWeight(me, 300) entity_addVel(me, -entity_velx(me)/2, 400) entity_setMaxSpeedLerp(me, 2, 0.1) entity_rotate(me, 160, 2, 0, 0, 1) entity_animate(me, "idle", -1) --spawnParticleEffect("ParrotHit", entity_x(me), entity_y(me)) end end function exitState(me) end function damage(me, attacker, bone, damageType, dmg) if attacker == me then return true end --debugLog(string.format("parrot health: %d", entity_getHealth(me))) spawnParticleEffect("ParrotHit", entity_x(me), entity_y(me)) if damageType == DT_AVATAR_BITE then entity_changeHealth(me, -50) return true elseif damageType == DT_AVATAR_ENERGYBLAST or damageType == DT_AVATAR_SHOCK or damageType == DT_CRUSH then entity_setState(me, STATE_FALLING) spawnParticleEffect("ParrotHit", entity_x(me), entity_y(me)) return true end return false end function animationKey(me, key) end function hitSurface(me) if v.dir == 0 then v.dir = 1 else v.dir = 0 end end function songNote(me, note) end function songNoteDone(me, note) end function song(me, song) end function activate(me) end
gpl-2.0
nyczducky/darkstar
scripts/zones/RuAun_Gardens/npcs/HomePoint#3.lua
27
1266
----------------------------------- -- Area: RuAun_Gardens -- NPC: HomePoint#3 -- @pos -312 -42 -422 130 ----------------------------------- package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/RuAun_Gardens/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fe, 61); 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 == 0x21fe) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
wenhulove333/ScutServer
Sample/Doudizhu/Client/lua/lib/ScutScene.lua
1
1385
ScutScene = {} g_scenes = {} function ScutScene:new(o) o = o or {} if o.root == nil then o.root = CCScene:create() print(o.root) end setmetatable(o, self) self.__index = self g_scenes[o.root] = o return o end function ScutScene:registerScriptTapHandler(func) end function ScutScene:registerCallback(func) func = func or function()end self.mCallbackFunc = func end function ScutScene:registerNetErrorFunc(func) func = func or function()end self.mNetErrorFunc = func end function ScutScene:registerNetCommonDataFunc(func) func = func or function()end self.mNetCommonDataFunc = func end function ScutScene:registerNetDecodeEnd() func = func or function()end self.NetDecodeEndFunc = func end function ScutScene:execCallback(nTag, nNetState, pData) if 2 == nNetState then local reader = ScutDataLogic.CDataRequest:Instance() local bValue = reader:LuaHandlePushDataWithInt(pData) if not bValue then return end if self.mCallbackFunc then self.mCallbackFunc(self.root) end if self.mNetCommonDataFunc then self.mNetCommonDataFunc() end netDecodeEnd(self.root, nTag) if self.mNetErrorFunc then -- self.mNetErrorFunc() end end end
mit
PierrotLC/CNN_classification
Optim.lua
1
4967
local pl = require('pl.import_into')() -- deepcopy routine assumes the presence of a 'clone' method in user. -- data should be used to deeply copy, which matches the behavior of Torch tensors. local function deepcopy(x) local typename = type(x) if typename == "userdata" then return x:clone() end if typename == "table" then local retval = { } for k,v in pairs(x) do retval[deepcopy(k)] = deepcopy(v) end return retval end return x end local Optim, parent = torch.class('nn.Optim') -- returns weight parameters, bias parameters and associated grad parameters for this module. -- annotates the return values with flag marking parameter set as bias parameters set. function Optim.weight_bias_parameters(module) local weight_params, bias_params if module.weight then weight_params = {module.weight, module.gradWeight} weight_params.is_bias = false end if module.bias then bias_params = {module.bias, module.gradBias} bias_params.is_bias = true end return {weight_params, bias_params} end -- The regular 'optim' package relies on 'getParameters', which is wrong before all. This 'optim' package uses separate optim state for each submodule of 'nn.Module'. function Optim:__init(model, optState, checkpoint_data) assert(model) assert(checkpoint_data or optState) assert(not (checkpoint_data and optState)) self.model = model self.modulesToOptState = {} -- Keep this around so we update it in setParameters self.originalOptState = optState -- Each module has some set of parameters and grad parameters. Since they may be allocated discontinuously, we need to separate optState for each parameter tensor. -- self.modulesToOptState maps each module to a lua table of optState clones. if not checkpoint_data then self.model:for_each(function(module) self.modulesToOptState[module] = { } local params = self.weight_bias_parameters(module) -- expects either an empty table or 2-element table, one for weights and one for biases : assert(pl.tablex.size(params) == 0 or pl.tablex.size(params) == 2) for i, _ in ipairs(params) do self.modulesToOptState[module][i] = deepcopy(optState) if params[i] and params[i].is_bias then -- never regularize biases self.modulesToOptState[module][i].weightDecay = 0.0 end end assert(module) assert(self.modulesToOptState[module]) end ) else local state = checkpoint_data.optim_state local modules = {} self.model:for_each(function(m) table.insert(modules, m) end ) assert(pl.tablex.compare_no_order(modules, pl.tablex.keys(state))) self.modulesToOptState = state end end function Optim:save() return { optim_state = self.modulesToOptState } end local function _type_all(obj, t) for k, v in pairs(obj) do if type(v) == 'table' then _type_all(v, t) else local tn = torch.typename(v) if tn and tn:find('torch%..+Tensor') then obj[k] = v:type(t) end end end end function Optim:type(t) self.model:for_each(function(module) local state= self.modulesToOptState[module] assert(state) _type_all(state, t) end ) end function Optim:optimize(optimMethod, inputs, targets, criterion) assert(optimMethod) assert(inputs) assert(targets) assert(criterion) assert(self.modulesToOptState) self.model:zeroGradParameters() local output = self.model:forward(inputs) local err = criterion:forward(output, targets) local df_do = criterion:backward(output, targets) self.model:backward(inputs, df_do) -- We'll set these in the loop that iterates over each module. Get them out here to be captured. local curGrad local curParam local function fEvalMod(x) return err, curGrad end for curMod, opt in pairs(self.modulesToOptState) do local curModParams = self.weight_bias_parameters(curMod) -- expects either an empty table or 2 element table, one for weights and one for biases : assert(pl.tablex.size(curModParams) == 0 or pl.tablex.size(curModParams) == 2) if curModParams then for i, tensor in ipairs(curModParams) do if curModParams[i] then -- expect param, gradParam pair curParam, curGrad = table.unpack(curModParams[i]) assert(curParam and curGrad) optimMethod(fEvalMod, curParam, opt[i]) end end end end return err, output end function Optim:setParameters(newParams) assert(newParams) assert(type(newParams) == 'table') local function splice(dest, src) for k,v in pairs(src) do dest[k] = v end end splice(self.originalOptState, newParams) for _,optStates in pairs(self.modulesToOptState) do for i,optState in pairs(optStates) do assert(type(optState) == 'table') splice(optState, newParams) end end end
apache-2.0
lgeek/koreader
spec/unit/luasettings_spec.lua
7
2854
describe("luasettings module", function() local Settings setup(function() require("commonrequire") Settings = require("frontend/luasettings"):open("this-is-not-a-valid-file") end) it("should handle undefined keys", function() Settings:delSetting("abc") assert.True(Settings:hasNot("abc")) assert.True(Settings:nilOrTrue("abc")) assert.False(Settings:isTrue("abc")) Settings:saveSetting("abc", true) assert.True(Settings:has("abc")) assert.True(Settings:nilOrTrue("abc")) assert.True(Settings:isTrue("abc")) end) it("should flip bool values", function() Settings:delSetting("abc") assert.True(Settings:hasNot("abc")) Settings:flipNilOrTrue("abc") assert.False(Settings:nilOrTrue("abc")) assert.True(Settings:has("abc")) assert.False(Settings:isTrue("abc")) Settings:flipNilOrTrue("abc") assert.True(Settings:nilOrTrue("abc")) assert.True(Settings:hasNot("abc")) assert.False(Settings:isTrue("abc")) Settings:flipTrue("abc") assert.True(Settings:has("abc")) assert.True(Settings:isTrue("abc")) assert.True(Settings:nilOrTrue("abc")) Settings:flipTrue("abc") assert.False(Settings:has("abc")) assert.False(Settings:isTrue("abc")) assert.True(Settings:nilOrTrue("abc")) end) it("should create child settings", function() Settings:delSetting("key") Settings:saveSetting("key", { a = "b", c = "true", d = false, }) local child = Settings:child("key") assert.is_not_nil(child) assert.True(child:has("a")) assert.are.equal(child:readSetting("a"), "b") assert.True(child:has("c")) assert.True(child:isTrue("c")) assert.True(child:has("d")) assert.True(child:isFalse("d")) assert.False(child:isTrue("e")) child:flipTrue("e") child:close() child = Settings:child("key") assert.True(child:isTrue("e")) end) describe("table wrapper", function() Settings:delSetting("key") it("should add item to table", function() Settings:addTableItem("key", 1) Settings:addTableItem("key", 2) Settings:addTableItem("key", 3) assert.are.equal(1, Settings:readSetting("key")[1]) assert.are.equal(2, Settings:readSetting("key")[2]) assert.are.equal(3, Settings:readSetting("key")[3]) end) it("should remove item from table", function() Settings:removeTableItem("key", 1) assert.are.equal(2, Settings:readSetting("key")[1]) assert.are.equal(3, Settings:readSetting("key")[2]) end) end) end)
agpl-3.0
nyczducky/darkstar
scripts/zones/Buburimu_Peninsula/npcs/Signpost.lua
13
1438
----------------------------------- -- Area: Buburimu Peninsula -- NPC: Signpost ----------------------------------- package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Buburimu_Peninsula/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (npc:getID() == 17261165) then player:messageSpecial(SIGN_5); elseif (npc:getID() == 17261166) then player:messageSpecial(SIGN_4); elseif (npc:getID() == 17261167) then player:messageSpecial(SIGN_3); elseif (npc:getID() == 17261168) then player:messageSpecial(SIGN_2); elseif (npc:getID() == 17261169) or (npc:getID() == 17261170) or (npc:getID() == 17261171) then player:messageSpecial(SIGN_1); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --print("CSID: %u",csid); --print("RESULT: %u",option); end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Jugner_Forest/mobs/Sappy_Sycamore.lua
14
1383
---------------------------------- -- Area: Jugner_Forest -- NM: Sappy Sycamore ----------------------------------- ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID()); mob:addMod(MOD_SLEEPRES,20); mob:addMod(MOD_BINDRES,20); end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(mob,target,damage) -- Guesstimating 1 in 4 chance to slow on melee. if ((math.random(1,100) >= 25) or (target:hasStatusEffect(EFFECT_SLOW) == true)) then return 0,0,0; else local duration = math.random(15,25); target:addStatusEffect(EFFECT_SLOW,15,0,duration); -- sproud smack like return SUBEFFECT_SLOW,MSGBASIC_ADD_EFFECT_STATUS,EFFECT_SLOW; end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) UpdateNMSpawnPoint(mob:getID()); mob:setRespawnTime(math.random(3600,4200)); -- repop 60-70min end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/Thierride.lua
14
3302
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Thierride -- @zone 80 -- @pos -124 -2 14 ----------------------------------- require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- Item 1019 = Lufet Salt -- Had to use setVar because you have to trade Salts one at a time according to the wiki. -- Lufet Salt can be obtained by killing Crabs in normal West Ronfaure. ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local lufetSalt = trade:hasItemQty(1019,1); local cnt = trade:getItemCount(); local beansAhoy = player:getQuestStatus(CRYSTAL_WAR,BEANS_AHOY); if (lufetSalt and cnt == 1 and beansAhoy == QUEST_ACCEPTED) then if (player:getVar("BeansAhoy") == 0 == true) then player:startEvent(0x0151); -- Traded the Correct Item Dialogue (NOTE: You have to trade the Salts one at according to wiki) elseif (player:needsToZone() == false) then player:startEvent(0x0154); -- Quest Complete Dialogue end else player:startEvent(0x0153); -- Wrong Item Traded end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local beansAhoy = player:getQuestStatus(CRYSTAL_WAR,BEANS_AHOY); if (beansAhoy == QUEST_AVAILABLE) then player:startEvent(0x014E); -- Quest Start elseif (beansAhoy == QUEST_ACCEPTED) then player:startEvent(0x014F); -- Quest Active, NPC Repeats what he says but as normal 'text' instead of cutscene. elseif (beansAhoy == QUEST_COMPLETED and getConquestTally() ~= player:getVar("BeansAhoy_ConquestWeek")) then player:startEvent(0x0156); elseif (beansAhoy == QUEST_COMPLETED) then player:startEvent(0x0155); else player:startEvent(0x014D); -- Default Dialogue 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 == 0x014E) then player:addQuest(CRYSTAL_WAR,BEANS_AHOY); elseif (csid == 0x0151) then player:tradeComplete(); player:setVar("BeansAhoy",1); player:needsToZone(true); elseif (csid == 0x0154 or csid == 0x0156) then if (player:hasItem(5704,1) or player:getFreeSlotsCount() < 1) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,5704) else player:addItem(5704,1); player:messageSpecial(ITEM_OBTAINED,5704); player:setVar("BeansAhoy_ConquestWeek",getConquestTally()); if (csid == 0x0154) then player:completeQuest(CRYSTAL_WAR,BEANS_AHOY); player:setVar("BeansAhoy",0); player:tradeComplete(); end end end end;
gpl-3.0
AinaSG/Crunchy
conf.lua
1
1388
function love.conf(t) t.title = "Crunchy - The Kawaii Roach" -- The title of the window the game is in (string) t.author = "Aina i Joan" -- The author of the game (string) t.identity = nil -- The name of the save directory (string) t.version = "0.9.1" -- The LÖVE version this game was made for (number) t.console = false -- Attach a console (boolean, Windows only) t.window.width = 1200 -- The window width (number) t.window.height = 600 -- The window height (number) t.window.fullscreen = false -- Enable fullscreen (boolean) t.window.vsync = true -- Enable vertical sync (boolean) t.modules.joystick = false -- Enable the joystick module (boolean) t.modules.audio = true -- Enable the audio module (boolean) t.modules.keyboard = true -- Enable the keyboard module (boolean) t.modules.event = true -- Enable the event module (boolean) t.modules.image = true -- Enable the image module (boolean) t.modules.graphics = true -- Enable the graphics module (boolean) t.modules.timer = true -- Enable the timer module (boolean) t.modules.mouse = true -- Enable the mouse module (boolean) t.modules.sound = true -- Enable the sound module (boolean) t.modules.physics = false -- Enable the physics module (boolean) end
gpl-2.0
nyczducky/darkstar
scripts/zones/La_Theine_Plateau/npcs/Chocobo_Tracks.lua
27
1348
----------------------------------- -- Area: La Theine Plateau -- NPC: Chocobo Tracks -- Involved in quest: Chocobo on the Loose! -- @pos -556 0 523 102 ----------------------------------- package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/La_Theine_Plateau/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(JEUNO,CHOCOBO_ON_THE_LOOSE) == QUEST_ACCEPTED and player:getVar("ChocoboOnTheLoose") < 2) then player:startEvent(0x00D1); else player:messageSpecial(CHOCOBO_TRACKS); 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 == 0x00D1) then player:setVar("ChocoboOnTheLoose",2); end end;
gpl-3.0
AquariaOSE/Aquaria
files/scripts/entities/merwoman.lua
6
2191
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end v.n = 0 function init(me) setupEntity(me) entity_setEntityType(me, ET_NEUTRAL) entity_initSkeletal(me, "merwoman") entity_scale(me, 0.6, 0.6) end function postInit(me) v.n = getNaija() entity_setTarget(me, v.n) local nd = entity_getNearestNode(me, "skin1") if nd~=0 and node_isEntityIn(nd, me) then entity_initSkeletal(me, "merwoman", "merwoman-skin1") end local nd = entity_getNearestNode(me, "skin2") if nd~=0 and node_isEntityIn(nd, me) then entity_initSkeletal(me, "merwoman", "merwoman-skin2") end entity_animate(me, "idle", -1) local nd = entity_getNearestNode(me, "flip") if nd~=0 and node_isEntityIn(nd, me) then entity_fh(me) end local nd = entity_getNearestNode(me, "sit") if nd~=0 and node_isEntityIn(nd, me) then debugLog("animating SIT") entity_animate(me, "sit", -1) end end function update(me, dt) entity_updateMovement(me, dt) end function enterState(me) if entity_isState(me, STATE_IDLE) then --entity_animate(me, "idle", -1) end end function exitState(me) end function damage(me, attacker, bone, damageType, dmg) return false end function animationKey(me, key) end function hitSurface(me) end function songNote(me, note) end function songNoteDone(me, note) end function song(me, song) end function activate(me) end
gpl-2.0
Klozz/LuaPlayer
src/auxiliary/boot.lua
1
1816
function dumpDirectory(filelist, directory) flist = System.listDirectory(directory) for idx, file in ipairs(flist) do if file.name ~= "." and file.name ~= ".." and file.name ~= "filelist.txt" then fullFile = directory .. "/" .. file.name if file.directory then dumpDirectory(filelist, fullFile) else fullFileHandle = io.open(fullFile, "r") if fullFileHandle then md5sum = System.md5sum(fullFileHandle:read("*a")) fullFileHandle:close() filelist:write(fullFile .. ", size: " .. file.size .. ", md5: " .. md5sum .. "\r\n") end end end end end flist = System.listDirectory() dofiles = { 0, 0, 0 } for idx, file in ipairs(flist) do if file.name ~= "." and file.name ~= ".." then if string.lower(file.name) == "script.lua" then -- luaplayer/script.lua dofiles[1] = file.name end if file.directory then fflist = System.listDirectory(file.name) for fidx, ffile in ipairs(fflist) do if string.lower(ffile.name) == "script.lua" then -- app bundle dofiles[2] = file.name.."/"..ffile.name System.currentDirectory(file.name) end if string.lower(ffile.name) == "index.lua" then -- app bundle dofiles[2] = file.name.."/"..ffile.name System.currentDirectory(file.name) end if string.lower(ffile.name) == "system.lua" then -- luaplayer/System dofiles[3] = file.name.."/"..ffile.name end end end end end done = false for idx, runfile in ipairs(dofiles) do if runfile ~= 0 then dofile(runfile) done = true break end end if not done then print("Boot error: No boot script found, creating filelist.txt...") filelist = io.open("filelist.txt", "w") dumpDirectory(filelist, System.currentDirectory()) print("Send the filelist.txt to the Lua Player maintainer for bugfixing.") filelist:close() end
bsd-3-clause
nyczducky/darkstar
scripts/globals/player.lua
24
8702
----------------------------------- -- -- -- ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/status"); require("scripts/globals/titles"); require("scripts/globals/gear_sets"); ----------------------------------- -- onGameIn ----------------------------------- function onGameIn(player, firstlogin, zoning) if (not zoning) then -- Things checked ONLY during logon go here. if (firstlogin) then CharCreate(player); end end if (zoning) then -- Things checked ONLY during zone in go here. -- Nothing here yet :P end -- Things checked BOTH during logon AND zone in below this line. checkForGearSet(player); if (player:getVar("GodMode") == 1) then -- Add bonus effects to the player.. player:addStatusEffect(EFFECT_MAX_HP_BOOST,1000,0,0); player:addStatusEffect(EFFECT_MAX_MP_BOOST,1000,0,0); player:addStatusEffect(EFFECT_SENTINEL,100,0,0); player:addStatusEffect(EFFECT_MIGHTY_STRIKES,1,0,0); player:addStatusEffect(EFFECT_HUNDRED_FISTS,1,0,0); player:addStatusEffect(EFFECT_CHAINSPELL,1,0,0); player:addStatusEffect(EFFECT_PERFECT_DODGE,1,0,0); player:addStatusEffect(EFFECT_INVINCIBLE,1,0,0); player:addStatusEffect(EFFECT_MANAFONT,1,0,0); player:addStatusEffect(EFFECT_REGAIN,150,1,0); player:addStatusEffect(EFFECT_REFRESH,99,0,0); player:addStatusEffect(EFFECT_REGEN,99,0,0); -- Add bonus mods to the player.. player:addMod(MOD_RACC,2500); player:addMod(MOD_RATT,2500); player:addMod(MOD_ACC,2500); player:addMod(MOD_ATT,2500); player:addMod(MOD_MATT,2500); player:addMod(MOD_MACC,2500); player:addMod(MOD_RDEF,2500); player:addMod(MOD_DEF,2500); player:addMod(MOD_MDEF,2500); -- Heal the player from the new buffs.. player:addHP( 50000 ); player:setMP( 50000 ); end if (player:getVar("GMHidden") == 1) then player:setGMHidden(true); end end; ----------------------------------- -- CharCreate ----------------------------------- function CharCreate(player) local race = player:getRace(); local body = nil; local leg = nil; local hand = nil; local feet = nil; -- ADD RACE SPECIFIC STARTGEAR switch(race) : caseof { -- HUME MALE [1] = function (x) body = 0x3157; hand = 0x31D2; leg = 0x3253; feet = 0x32CD; end, -- HUME FEMALE [2] = function (x) body = 0x3158; hand = 0x31D8; leg = 0x3254; feet = 0x32D2; end, -- ELVAAN MALE [3] = function (x) body = 0x3159; hand = 0x31D3; leg = 0x3255; feet = 0x32CE; end, -- ELVAAN FEMALE [4] = function (x) body = 0x315A; hand = 0x31D7; leg = 0x3259; feet = 0x32D3; end, -- TARU MALE [5] = function (x) body = 0x315B; hand = 0x31D4; leg = 0x3256; feet = 0x32CF; end, -- TARU FEMALE [6] = function (x) body = 0x315B; hand = 0x31D4; leg = 0x3256; feet = 0x32CF; end, -- MITHRA [7] = function (x) body = 0x315C; hand = 0x31D5; leg = 0x3257; feet = 0x32D0; end, -- GALKA [8] = function (x) body = 0x315D; hand = 0x31D6; leg = 0x3258; feet = 0x32D1; end, default = function (x) end, } -- Add starting gear if not(player:hasItem(body)) then player:addItem(body); player:equipItem(body); end if not(player:hasItem(hand)) then player:addItem(hand); player:equipItem(hand); end if not(player:hasItem(leg)) then player:addItem(leg); player:equipItem(leg); end if not(player:hasItem(feet)) then player:addItem(feet); player:equipItem(feet); end -- ADD JOB SPECIFIC STARTGEAR switch(player:getMainJob()) : caseof { -- WARRIOR JOB [0x01]= function (x) if not(player:hasItem(0x4096)) then player:addItem(0x4096); end end, -- MONK JOB [0x02]= function (x) if not(player:hasItem(0x3380)) then player:addItem(0x3380); end end, -- WHITE MAGE [0x03]= function(x) if not(player:hasItem(0x42AC)) then player:addItem(0x42AC); end if not(player:hasItem(0x1200)) then player:addItem(0x1200); end end, -- BLACK MAGE [0x04] = function(x) if not(player:hasItem(0x42D0)) then player:addItem(0x42D0); end if not(player:hasItem(0x11FF)) then player:addItem(0x11FF); end end, -- RED MAGE [0x05]= function (x) if not(player:hasItem(0x4062)) then player:addItem(0x4062); end if not(player:hasItem(0x11FE)) then player:addItem(0x11FE); end end, -- THIEF [0x06]= function (x) if not(player:hasItem(0x4063)) then player:addItem(0x4063); end end, default = function (x) end, } -- ADD NATION SPECIFIC STARTGEAR switch (player:getNation()) : caseof { -- SANDY CITIZEN [0] = function (x) if ((race == 3) or (race == 4)) then player:addItem(0x34B7); end; player:addKeyItem(MAP_OF_THE_SAN_DORIA_AREA); end, -- BASTOK CITIZEN [1] = function (x) if (((race == 1) or (race == 2) or (race == 8))) then player:addItem(0x34B9); end; player:addKeyItem(MAP_OF_THE_BASTOK_AREA); end, -- WINDY CITIZEN [2] = function(x) if (((race == 5) or (race == 6) or (race == 7))) then player:addItem(0x34B8); end; player:addKeyItem(MAP_OF_THE_WINDURST_AREA); end, default = function (x) end, } ----- settings.lua Perks ----- if (ADVANCED_JOB_LEVEL == 0) then for i = 6,22 do player:unlockJob(i); end end if (SUBJOB_QUEST_LEVEL == 0) then player:unlockJob(0); end if (ALL_MAPS == 1) then for i=385,447 do player:addKeyItem(i); end for i=1856,1917 do player:addKeyItem(i); end for i=2302,2305 do player:addKeyItem(i); end for i=2307,2309 do player:addKeyItem(i); end end if (INITIAL_LEVEL_CAP ~= 50) then player:levelCap(INITIAL_LEVEL_CAP) end if (START_INVENTORY > 30) then player:changeContainerSize(0,(START_INVENTORY - 30)) player:changeContainerSize(5,(START_INVENTORY - 30)) end if (UNLOCK_OUTPOST_WARPS >= 1) then player:addNationTeleport(0,2097120); player:addNationTeleport(1,2097120); player:addNationTeleport(2,2097120); if (UNLOCK_OUTPOST_WARPS == 2) then -- Tu'Lia and Tavnazia player:addNationTeleport(0,10485760); player:addNationTeleport(1,10485760); player:addNationTeleport(2,10485760); end end ----- End settings.lua Perks ----- -- SET START GIL --[[For some intermittent reason m_ZoneList ends up empty on characters, which is possibly also why they lose key items. When that happens, CharCreate will be run and they end up losing their gil to the code below. Added a conditional to hopefully prevent that until the bug is fixed. Used the if instead of addGil to prevent abuse on servers with very high values of START_GIL, I guess.]] if (player:getGil() < START_GIL) then player:setGil(START_GIL); end -- ADD ADVENTURER COUPON player:addItem(0x218); --SET TITLE player:addTitle(NEW_ADVENTURER); -- Needs Moghouse Intro player:setVar("MoghouseExplication",1); end; function onPlayerLevelUp(player) end function onPlayerLevelDown(player) end
gpl-3.0
nyczducky/darkstar
scripts/globals/mobskills/Crystal_Weapon.lua
37
1031
--------------------------------------------- -- Crystal Weapon -- -- Description: Invokes the power of a crystal to deal magical damage of a random element to a single target. -- Type: Magical -- Utsusemi/Blink absorb: Ignores shadows -- Range: Unknown -- Notes: Can be Fire, Earth, Wind, or Water element. Functions even at a distance (outside of melee range). --------------------------------------------- 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 element = math.random(6,9); local dmgmod = 1; local accmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg() * 5,accmod,dmgmod,TP_MAB_BONUS,1); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,element,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
nyczducky/darkstar
scripts/globals/mobskills/Glacial_Breath.lua
32
1239
--------------------------------------------- -- Glacial Breath -- -- Description: Deals Ice damage to enemies within a fan-shaped area. -- Type: Breath -- Utsusemi/Blink absorb: Ignores shadows -- Range: Unknown cone -- Notes: Used only by Jormungand and Isgebind --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/globals/utils"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:hasStatusEffect(EFFECT_BLOOD_WEAPON)) then return 1; elseif (target:isBehind(mob, 48) == true) then return 1; elseif (mob:AnimationSub() == 1) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) local dmgmod = MobBreathMove(mob, target, 0.2, 1.25, ELE_ICE, 1400); local angle = mob:getAngle(target); angle = mob:getRotPos() - angle; dmgmod = dmgmod * ((128-math.abs(angle))/128); dmgmod = utils.clamp(dmgmod, 50, 1600); local dmg = MobFinalAdjustments(dmgmod,mob,skill,target,MOBSKILL_BREATH,MOBPARAM_ICE,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Batallia_Downs/npcs/qm2.lua
17
1515
----------------------------------- -- Area: Batallia Downs -- NPC: qm2 (???) -- Pop for the quest "Chasing Quotas" ----------------------------------- package.loaded["scripts/zones/Batallia_Downs/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Batallia_Downs/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local Sturmtiger = player:getVar("SturmtigerKilled"); if (player:getVar("ChasingQuotas_Progress") == 5 and Sturmtiger == 0) then SpawnMob(17207696,300):updateClaim(player); elseif (Sturmtiger == 1) then player:addKeyItem(RANCHURIOMES_LEGACY); player:messageSpecial(KEYITEM_OBTAINED,RANCHURIOMES_LEGACY); player:setVar("ChasingQuotas_Progress",6); player:setVar("SturmtigerKilled",0); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end; ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) 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
ruleless/skynet
lualib/sharemap.lua
78
1496
local stm = require "stm" local sprotoloader = require "sprotoloader" local sproto = require "sproto" local setmetatable = setmetatable local sharemap = {} function sharemap.register(protofile) -- use global slot 0 for type define sprotoloader.register(protofile, 0) end local sprotoobj local function loadsp() if sprotoobj == nil then sprotoobj = sprotoloader.load(0) end return sprotoobj end function sharemap:commit() self.__obj(sprotoobj:encode(self.__typename, self.__data)) end function sharemap:copy() return stm.copy(self.__obj) end function sharemap.writer(typename, obj) local sp = loadsp() obj = obj or {} local stmobj = stm.new(sp:encode(typename,obj)) local ret = { __typename = typename, __obj = stmobj, __data = obj, commit = sharemap.commit, copy = sharemap.copy, } return setmetatable(ret, { __index = obj, __newindex = obj }) end local function decode(msg, sz, self) local data = self.__data for k in pairs(data) do data[k] = nil end return sprotoobj:decode(self.__typename, msg, sz, data) end function sharemap:update() return self.__obj(decode, self) end function sharemap.reader(typename, stmcpy) local sp = loadsp() local stmobj = stm.newcopy(stmcpy) local _, data = stmobj(function(msg, sz) return sp:decode(typename, msg, sz) end) local obj = { __typename = typename, __obj = stmobj, __data = data, update = sharemap.update, } return setmetatable(obj, { __index = data, __newindex = error }) end return sharemap
mit
LexLoki/Udemy-LOVE_game_development
Pong/Ball.lua
1
1701
local u = require 'utils' local Ball = {} Ball.radius = 20 Ball.color = {0,255,255} local decreaseAngle function Ball.new(x,y,speed) local self = { x=x, y=y, speed = speed, lastx = x, lasty = y } setmetatable(self, {__index=Ball}) return self end function Ball:update(dt) self.lastx = self.x self.lasty = self.y self.x = self.x + self.speed.x*dt self.y = self.y + self.speed.y*dt local w,h = love.graphics.getDimensions() if self.x>w-self.radius then self.speed.x = -self.speed.x self.x = 2*(w-self.radius)-self.x elseif self.x<self.radius then self.speed.x = -self.speed.x self.x = 2*self.radius-self.x end if self.y>h-self.radius then self.speed.y = -self.speed.y self.y = 2*(h-self.radius)-self.y elseif self.y<self.radius then self.speed.y = -self.speed.y self.y = 2*self.radius-self.y end --print(u.angle(self.speed)) end function Ball:angle() return u.angle(self.speed) end function Ball:reflectX(dir) self.speed.x = -self.speed.x if dir ~= 0 then --self.speed = u.rotate(self.speed,decreaseAngle(math.pi/2,u.angle(self.speed),dir)) end print('refx') end function Ball:reflectY(dir) self.speed.y = -self.speed.y if dir ~=0 then --self.speed = u.rotate(self.speed,decreaseAngle(math.pi,u.angle(self.speed),dir)) end print('refy') end function decreaseAngle(ref, angle, dir) local ang if dir>0 then return angle/2 else return (angle+ref)/2--(angle+u.sign(angle)*ref)/2 end end --[[ x y tx = x/2 ty tx*tx + ty*ty = x*x + y*y x*x/4 + ty*ty = x*x + y*y ty2 = 3/4*x2 + y2 ty = raiz ( 3/4*x2 + y2 ) ]] function Ball:draw() love.graphics.setColor(self.color) love.graphics.circle("fill",self.x,self.y,self.radius,100) end return Ball
mit
PierrotLC/CNN_classification
data.lua
1
1538
-- -- Data local ffi = require 'ffi' local Threads = require 'threads' -- This script contains the logic to create one thread for data-loading. -- For the data-loading details, look at donkey.lua ------------------------------------------------------------------------------- do -- start K datathreads (donkeys) if opt.nDonkeys > 0 then local options = opt -- make an upvalue to serialize over to donkey threads donkeys = Threads( opt.nDonkeys, function() require 'torch' end, function(idx) opt = options -- pass to all donkeys via upvalue tid = idx local seed = opt.manualSeed + idx torch.manualSeed(seed) print(string.format('Starting donkey with id: %d seed: %d', tid, seed)) paths.dofile('donkey.lua') end ); else -- single threaded data loading. useful for debugging paths.dofile('donkey.lua') donkeys = {} function donkeys:addjob(f1, f2) f2(f1()) end function donkeys:synchronize() end end end nClasses = nil classes = nil donkeys:addjob( function() return trainLoader.classes end, function(c) classes = c end ) donkeys:synchronize() nClasses = #classes assert(nClasses, "Failed to get nClasses") print('nClasses : ', nClasses) torch.save(paths.concat(opt.save, 'classes.t7'), classes) nTest = 0 donkeys:addjob( function() return testLoader:sizeTest() end, function(c) nTest = c end ) donkeys:synchronize() assert(nTest > 0, "Failed to get nTest") print('nTest : ', nTest)
apache-2.0
lgeek/koreader
frontend/ui/plugin/switch_plugin.lua
9
3125
--[[-- SwitchPlugin creates a plugin with a switch to enable or disable it. See spec/unit/switch_plugin_spec.lua for the usage. ]] local ConfirmBox = require("ui/widget/confirmbox") local DataStorage = require("datastorage") local LuaSettings = require("luasettings") local UIManager = require("ui/uimanager") local WidgetContainer = require("ui/widget/container/widgetcontainer") local logger = require("logger") local _ = require("gettext") local SwitchPlugin = WidgetContainer:new() function SwitchPlugin:extend(o) o = o or {} setmetatable(o, self) self.__index = self return o end function SwitchPlugin:new(o) o = self:extend(o) assert(type(o.name) == "string", "name is required"); o.settings = LuaSettings:open(DataStorage:getSettingsDir() .. "/" .. o.name .. ".lua") o.settings_id = 0 SwitchPlugin._init(o) return o end function SwitchPlugin:_init() if self.default_enable then self.enabled = self.settings:nilOrTrue("enable") else self.enabled = not self.settings:nilOrFalse("enable") end self.settings_id = self.settings_id + 1 logger.dbg("SwitchPlugin:_init() self.enabled: ", self.enabled, " with id ", self.settings_id) if self.enabled then self:_start() else self:_stop() end end function SwitchPlugin:flipSetting() if self.default_enable then self.settings:flipNilOrTrue("enable") else self.settings:flipNilOrFalse("enable") end self:_init() end function SwitchPlugin:onFlushSettings() self.settings:flush() end --- Show a ConfirmBox to ask for enabling or disabling this plugin. function SwitchPlugin:_showConfirmBox() UIManager:show(ConfirmBox:new{ text = self:_confirmMessage(), ok_text = self.enabled and _("Disable") or _("Enable"), ok_callback = function() self:flipSetting() end, }) end function SwitchPlugin:_confirmMessage() local result = "" if type(self.confirm_message) == "string" then result = self.confirm_message .. "\n" elseif type(self.confirm_message) == "function" then result = self.confirm_message() .. "\n" end if self.enabled then result = result .. _("Do you want to disable it?") else result = result .. _("Do you want to enable it?") end return result end function SwitchPlugin:init() if type(self.menu_item) == "string" and self.ui ~= nil and self.ui.menu ~= nil then self.ui.menu:registerToMainMenu(self) end end function SwitchPlugin:addToMainMenu(menu_items) assert(type(self.menu_item) == "string", "addToMainMenu should not be called without menu_item.") assert(type(self.menu_text) == "string", "Have you forgotten to set \"menu_text\"") menu_items[self.menu_item] = { text = self.menu_text, callback = function() self:_showConfirmBox() end, checked_func = function() return self.enabled end, } end -- Virtual function SwitchPlugin:_start() end -- Virtual function SwitchPlugin:_stop() end return SwitchPlugin
agpl-3.0
nyczducky/darkstar
scripts/globals/items/bunch_of_gysahl_greens.lua
12
1609
----------------------------------------- -- ID: 4545 -- Item: Bunch of Gysahl Greens -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility +3 -- Vitality -5 -- Additional Effect with Chocobo Shirt -- Agility +10 ----------------------------------------- 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,ChocoboShirt(target),0,300,4545); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) local power = effect:getPower(); if (power == 1) then chocoboShirt = 1; target:addMod(MOD_AGI, 13); target:addMod(MOD_VIT, -5); else target:addMod(MOD_AGI, 3); target:addMod(MOD_VIT, -5); end end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) local power = effect:getPower(); if (power == 1) then target:delMod(MOD_AGI, 13); target:delMod(MOD_VIT, -5); else target:delMod(MOD_AGI, 3); target:delMod(MOD_VIT, -5); end end;
gpl-3.0
AquariaOSE/Aquaria
files/scripts/entities/creatorform6.lua
6
12019
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end v.n = 0 local STATE_STEPFORE = 1000 local STATE_STEPBACK = 1001 local STATE_ATTACK1 = 1002 local STATE_ATTACK2 = 1003 local STATE_ATTACK3 = 1004 local STATE_BACKHANDATTACK = 1005 local STATE_MOUTHATTACK = 1006 local STATE_SPAWNNAIJA = 1007 local STATE_SCENEGHOST = 1010 v.maxLeft = 0 v.maxRight = 0 v.stepDelay = 0 v.attackDelay = 0 v.eye = 0 v.hand = 0 v.forearm = 0 v.socket = 0 v.neck = 0 v.backHand = 0 v.tongue = 0 v.li = 0 v.shieldHits = 3 --9 v.hits = 3 -- 3 v.camNode = 0 v.camBone = 0 v.chestMonster = 0 v.chestShield = 0 v.eyeCover = 0 v.eyeSocket = 0 v.eyeSpiral = 0 v.eyeCoverHits = 24 local PHASE_HASLI = 0 local PHASE_FINAL = 1 v.phase = PHASE_HASLI v.attackPhase = 0 local function enterFinalPhase(me) debugLog("setting phase to final") playSfx("naijali1") setFlag(FLAG_LI, 100) entity_setState(v.li, STATE_IDLE, -1, true) v.phase = PHASE_FINAL v.chestMonster = createEntity("chestmonster", "", entity_x(me), entity_y(me)) playSfx("licage-shatter") bone_alpha(v.chestShield, 0, 2) v.attackPhase = 0 end function init(me) setupEntity(me) entity_setEntityType(me, ET_ENEMY) entity_initSkeletal(me, "CreatorForm6") --entity_setAllDamageTargets(me, false) entity_setCull(me, false) entity_generateCollisionMask(me) entity_setState(me, STATE_IDLE) entity_scale(me, 2, 2) v.eye = entity_getBoneByName(me, "Eye") v.hand = entity_getBoneByName(me, "Hand") v.forearm = entity_getBoneByName(me, "Forearm") v.socket = entity_getBoneByName(me, "Socket") v.neck = entity_getBoneByName(me, "Neck") v.chestShield = entity_getBoneByName(me, "chestshield") v.eyeSocket = entity_getBoneByName(me, "eyesocket") v.eyeCover = entity_getBoneByName(me, "eyecover") entity_setTargetRange(me, 2000) bone_setVisible(v.eyeSocket, 0) v.backHand = entity_getBoneByName(me, "BackHand") v.tongue = entity_getBoneByName(me, "tongue") bone_setAnimated(v.eye, ANIM_POS) v.camBone = v.eye v.li = getLi() esetv(me, EV_SOULSCREAMRADIUS, -1) setFlag(FLAG_LI, 200) loadSound("licage-crack1") loadSound("licage-crack2") loadSound("licage-shatter") loadSound("creatorform6-die3") loadSound("hellbeast-shot-skull") entity_setDamageTarget(me, DT_AVATAR_PET, false) end function postInit(me) v.n = getNaija() entity_setTarget(me, v.n) local node = getNode("MAXLEFT") v.maxLeft = node_x(node) local node = getNode("MAXRIGHT") v.maxRight = node_x(node) v.camNode = getNode("CAM") if v.li == 0 then -- create li v.li = createEntity("Li") setLi(v.li) end entity_setState(v.li, STATE_TRAPPEDINCREATOR, -1, true) end v.pd = 0 function update(me, dt) if entity_isState(me, STATE_WAIT) then return end if entity_isState(me, STATE_TRANSITION) or entity_isState(me, STATE_SCENEGHOST) then local bx, by = bone_getWorldPosition(v.camBone) node_setPosition(v.camNode, bx, by) cam_toNode(v.camNode) v.pd = v.pd + dt if v.pd > 0.2 then spawnParticleEffect("TinyRedExplode", bx-500+math.random(1000), by-500 + math.random(1000)) v.pd = 0 end return end entity_updateMovement(me, dt) entity_handleShotCollisionsSkeletal(me) local bone = entity_collideSkeletalVsCircle(me, v.n) if bone ~= 0 then --[[ if avatar_isBursting() and bone ~= v.hand and bone ~= v.forearm and entity_setBoneLock(v.n, me, bone) then else ]]-- -- puuush --entity_addVel(v.n, -800, 0) local bx, by = bone_getWorldPosition(bone) local x, y = entity_getPosition(v.n) x = x - bx y = y - by x,y = vector_setLength(x, y, 2000) entity_clearVel(v.n) entity_addVel(v.n, x, y) x,y = vector_setLength(x, y, 8) entity_setPosition(v.n, entity_x(v.n) + x -20, entity_y(v.n) + y) --if bone == v.hand or bone == v.forearm then entity_damage(v.n, me, 1) avatar_fallOffWall() --end --entity_addVel(v.n, -400, 0) --end end overrideZoom(0.45) if entity_isState(me, STATE_IDLE) then v.stepDelay = v.stepDelay + dt if v.stepDelay > 2 then v.stepDelay = 0 if entity_x(me) > v.maxLeft and chance(50) then entity_setState(me, STATE_STEPFORE) elseif entity_x(me) < v.maxRight then entity_setState(me, STATE_STEPBACK) end end if v.phase == PHASE_HASLI then v.attackDelay = v.attackDelay + dt if v.attackDelay > 4 then v.attackDelay = 0 if v.attackPhase == 0 then entity_setState(me, STATE_BACKHANDATTACK) elseif v.attackPhase == 1 then entity_setState(me, STATE_SPAWNNAIJA) elseif v.attackPhase == 2 then entity_setState(me, STATE_MOUTHATTACK) end v.attackPhase = v.attackPhase + 1 if v.attackPhase > 2 then v.attackPhase = 0 end end end if v.phase == PHASE_FINAL then v.attackDelay = v.attackDelay + dt if v.attackDelay > 4 then v.attackDelay = 0 if v.attackPhase == 0 then entity_setState(v.chestMonster, STATE_OPEN) v.attackDelay = -3 elseif v.attackPhase == 1 then entity_setState(me, STATE_BACKHANDATTACK) elseif v.attackPhase == 2 then -- spawn aleph ??? elseif v.attackPhase == 3 then end v.attackPhase = v.attackPhase + 1 if v.attackPhase > 1 then v.attackPhase = 0 end end end end local dist = 270 local bx, by = bone_getWorldPosition(v.eye) if entity_y(v.n) > by + dist then bone_rotate(v.eye, -25, 0.5) elseif entity_y(v.n) < by - dist then bone_rotate(v.eye, 35, 0.5) else bone_rotate(v.eye, 0, 0.5) end if v.li ~= 0 and v.phase == PHASE_HASLI then entity_setPosition(v.li, bone_getWorldPosition(v.socket)) end if v.phase == PHASE_FINAL then if v.chestMonster ~= 0 then entity_setPosition(v.chestMonster, bone_getWorldPosition(v.socket)) end end if v.eyeSpiral ~= 0 then local bx,by = bone_getWorldPosition(v.eyeSocket) entity_setPosition(v.eyeSpiral, bx-64, by) end entity_clearTargetPoints(me) if v.phase == PHASE_HASLI then if bone_isVisible(v.eyeCover) then entity_addTargetPoint(me, bone_getWorldPosition(v.eyeCover)) end end end v.stepTime = 2 local function flash() end v.incut = false function enterState(me) if v.incut then return end if entity_isState(me, STATE_IDLE) then entity_animate(me, "idle", -1) elseif entity_isState(me, STATE_STEPFORE) then entity_setPosition(me, entity_x(me)-600, entity_y(me), v.stepTime, 0, 0, 0) entity_setStateTime(me, v.stepTime) elseif entity_isState(me, STATE_STEPBACK) then entity_setPosition(me, entity_x(me)+600, entity_y(me), v.stepTime, 0, 0, 0) entity_setStateTime(me, v.stepTime) elseif entity_isState(me, STATE_ATTACK1) then entity_setStateTime(me, entity_animate(me, "attack1")) elseif entity_isState(me, STATE_TRANSITION) then if v.chestMonster ~= 0 then entity_delete(v.chestMonster) v.chestMonster = 0 end bone_setAnimated(v.eye, ANIM_ALL) v.incut = true --entity_setStateTime(me, entity_animate(me, "die")) --entity_setStateTime(me, 22) -- 22 -- gets picked up by node FINALBOSSDEATH --[[ flash() entity_animate(me, "die1", -1) watch(7) flash() entity_animate(me, "die2", -1) watch(5) flash() entity_animate(me, "die3", -1) watch(9) entity_setStateTime(me, 0.01) ]]-- v.incut = false elseif entity_isState(me, STATE_SCENEGHOST) then debugLog("ghost") v.incut = true v.incut = false elseif entity_isState(me, STATE_WAIT) then debugLog("wait") elseif entity_isState(me, STATE_BACKHANDATTACK) then entity_setStateTime(me, entity_animate(me, "backHandAttack")) elseif entity_isState(me, STATE_MOUTHATTACK) then entity_setStateTime(me, entity_animate(me, "mouthattack")) elseif entity_isState(me, STATE_SPAWNNAIJA) then entity_setStateTime(me, entity_animate(me, "spawnthing")) end end function exitState(me) if entity_isState(me, STATE_STEPFORE) or entity_isState(me, STATE_STEPBACK) or entity_isState(me, STATE_ATTACK1) then entity_setState(me, STATE_IDLE) elseif entity_isState(me, STATE_TRANSITION) then --entity_setState(me, STATE_SCENEGHOST) elseif entity_isState(me, STATE_SCENEGHOST) then disableInput() fade(1, 2, 0, 0, 0) elseif entity_isState(me, STATE_BACKHANDATTACK) then entity_setState(me, STATE_IDLE) elseif entity_isState(me, STATE_MOUTHATTACK) then entity_setState(me, STATE_IDLE) elseif entity_isState(me, STATE_SPAWNNAIJA) then entity_setState(me, STATE_IDLE) end end function damage(me, attacker, bone, damageType, dmg) --[[ if v.phase == PHASE_HASLI then if damageType == DT_ENEMY_CREATOR then debugLog("damage type is dt_enemy_creator") if bone == v.socket then v.shieldHits = v.shieldHits - dmg bone_damageFlash(bone) if v.shieldHits <= 0 then enterFinalPhase(me) end end end end ]]-- if damageType == DT_ENEMY_BEAM then return false end if bone == v.eyeCover then bone_damageFlash(v.eyeCover) v.eyeCoverHits = v.eyeCoverHits - dmg playSfx("licage-crack1") if v.eyeCoverHits <= 0 then bone_setVisible(v.eyeCover, 0) bone_setVisible(v.eyeSocket, 1) playSfx("licage-shatter") v.eyeSpiral = createEntity("eyespiral", "", bone_getWorldPosition(v.eyeSocket)) end end if v.phase == PHASE_FINAL then if damageType == DT_AVATAR_DUALFORMNAIJA then v.hits = v.hits - 1 for i = 0,10 do bone_damageFlash(entity_getBoneByIdx(me, i)) end playSfx("creatorform6-die3") if v.hits <= 0 then entity_setState(me, STATE_TRANSITION) end end end return false end function animationKey(me, key) if entity_isState(me, STATE_BACKHANDATTACK) then if key == 4 or key == 5 or key == 6 or key == 7 or key == 8 then -- create entity debugLog("Creating entity") local bx, by = bone_getWorldPosition(v.backHand) local vx, vy = entity_getPosition(getNaija()) vx = vx - bx vy = vy - by --local e = createEntity("cf6-shot", "", bx, by) local s = createShot("creatorform6-hand", me, getNaija(), bx, by) shot_setAimVector(s, vx, vy) end elseif entity_isState(me, STATE_MOUTHATTACK) then if key == 4 or key == 5 or key == 6 or key == 7 or key == 8 or key == 9 or key == 10 then local bx, by = bone_getWorldPosition(v.tongue) local vx, vy = entity_getPosition(getNaija()) vx = vx - bx vy = vy - by local s = createShot("creatorform6-hand", me, getNaija(), bx, by) shot_setAimVector(s, vx, vy) end elseif entity_isState(me, STATE_SPAWNNAIJA) then if key == 5 then -- key == 3 or local bx, by = bone_getWorldPosition(v.hand) spawnParticleEffect("tinyredexplode", bx, by) createEntity("mutantnaija", "", bx, by) end end end function hitSurface(me) end function songNote(me, note) end function songNoteDone(me, note) end function song(me, song) end function activate(me) end function msg(me, msg) if msg == "eye" then v.camBone = v.eye elseif msg == "neck" then v.camBone = v.neck end if msg == "eyedied" then enterFinalPhase(me) end if msg == "eyepopped" then fade2(1, 0, 1, 1, 1) fade2(0, 1, 1, 1, 1) playSfx("creatorform6-die3") v.eyeSpiral = 0 setSceneColor(1, 0, 0, 0) setSceneColor(1, 1, 1, 4) entity_animate(me, "eyehurt", 0, 1) end end
gpl-2.0
abcdefg30/OpenRA
mods/d2k/maps/atreides-03a/atreides03a-AI.lua
7
1962
--[[ Copyright 2007-2022 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you 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. For more information, see COPYING. ]] AttackGroupSize = { easy = 6, normal = 8, hard = 10 } AttackDelays = { easy = { DateTime.Seconds(4), DateTime.Seconds(9) }, normal = { DateTime.Seconds(2), DateTime.Seconds(7) }, hard = { DateTime.Seconds(1), DateTime.Seconds(5) } } OrdosInfantryTypes = { "light_inf", "light_inf", "light_inf", "trooper", "trooper" } OrdosVehicleTypes = { "raider", "raider", "quad" } InitAIUnits = function() IdlingUnits[ordos] = Reinforcements.Reinforce(ordos, InitialOrdosReinforcements, OrdosPaths[2]) IdlingUnits[ordos][#IdlingUnits + 1] = OTrooper1 IdlingUnits[ordos][#IdlingUnits + 1] = OTrooper2 IdlingUnits[ordos][#IdlingUnits + 1] = ORaider DefendAndRepairBase(ordos, OrdosBase, 0.75, AttackGroupSize[Difficulty]) end ActivateAI = function() LastHarvesterEaten[ordos] = true Trigger.AfterDelay(0, InitAIUnits) OConyard.Produce(AtreidesUpgrades[1]) OConyard.Produce(AtreidesUpgrades[2]) local delay = function() return Utils.RandomInteger(AttackDelays[Difficulty][1], AttackDelays[Difficulty][2] + 1) end local infantryToBuild = function() return { Utils.Random(OrdosInfantryTypes) } end local vehiclesToBuild = function() return { Utils.Random(OrdosVehicleTypes) } end local attackThresholdSize = AttackGroupSize[Difficulty] * 2.5 -- Finish the upgrades first before trying to build something Trigger.AfterDelay(DateTime.Seconds(14), function() ProduceUnits(ordos, OBarracks, delay, infantryToBuild, AttackGroupSize[Difficulty], attackThresholdSize) ProduceUnits(ordos, OLightFactory, delay, vehiclesToBuild, AttackGroupSize[Difficulty], attackThresholdSize) end) end
gpl-3.0
dtrip/awesome
spec/wibox/widget/base_spec.lua
14
3351
--------------------------------------------------------------------------- -- @author Uli Schlachter -- @copyright 2016 Uli Schlachter --------------------------------------------------------------------------- local base = require("wibox.widget.base") local no_parent = base.no_parent_I_know_what_I_am_doing describe("wibox.widget.base", function() local widget1, widget2 before_each(function() widget1 = base.make_widget() widget2 = base.make_widget() widget1.layout = function() return { base.place_widget_at(widget2, 0, 0, 1, 1) } end end) describe("caches", function() it("garbage collectable", function() local alive = setmetatable({ widget1, widget2 }, { __mode = "kv" }) assert.is.equal(2, #alive) widget1, widget2 = nil, nil collectgarbage("collect") assert.is.equal(0, #alive) end) it("simple cache clear", function() local alive = setmetatable({ widget1, widget2 }, { __mode = "kv" }) base.layout_widget(no_parent, { "fake context" }, widget1, 20, 20) assert.is.equal(2, #alive) widget1, widget2 = nil, nil collectgarbage("collect") assert.is.equal(0, #alive) end) it("self-reference cache clear", function() widget2.widget = widget1 local alive = setmetatable({ widget1, widget2 }, { __mode = "kv" }) base.layout_widget(no_parent, { "fake context" }, widget1, 20, 20) assert.is.equal(2, #alive) widget1, widget2 = nil, nil collectgarbage("collect") assert.is.equal(0, #alive) end) end) describe("setup", function() it("Filters out 'false'", function() -- Regression test: There was a bug where "nil"s where correctly -- skipped, but "false" entries survived local layout1, layout2 = base.make_widget(), base.make_widget() local called = false function layout1:set_widget(w) called = true assert.equals(w, layout2) end function layout2:set_children(children) assert.is_same({nil, widget1, nil, widget2}, children) end layout2.allow_empty_widget = true layout1:setup{ layout = layout2, false, widget1, nil, widget2 } assert.is_true(called) end) it("Attribute 'false' works", function() -- Regression test: I introduced a bug with the above fix local layout1, layout2 = base.make_widget(), base.make_widget() local called1, called2 = false, false function layout1:set_widget(w) called1 = true assert.equals(w, layout2) end function layout2:set_children(children) assert.is_same({}, children) end function layout2:set_foo(foo) called2 = true assert.is_false(foo) end layout1:setup{ layout = layout2, foo = false } assert.is_true(called1) assert.is_true(called2) end) end) end) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
nyczducky/darkstar
scripts/zones/Selbina/npcs/Wenzel.lua
14
1051
---------------------------------- -- Area: Selbina -- NPC: Wenzel -- Type: Item Deliverer -- @pos 31.961 -14.661 57.997 248 ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, WENZEL_DELIVERY_DIALOG); player:openSendBox(); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nyczducky/darkstar
scripts/globals/weaponskills/resolution.lua
23
1835
----------------------------------- -- Resolution -- Great Sword weapon skill -- Skill Level: 357 -- Delivers a fivefold attack. Damage varies with TP. -- In order to obtain Resolution, the quest Martial Mastery must be completed. -- This Weapon Skill's first hit params.ftp is duplicated for all additional hits. -- Resolution has an attack penalty of -8%. -- Aligned with the Breeze Gorget, Thunder Gorget & Soil Gorget. -- Aligned with the Breeze Belt, Thunder Belt & Soil Belt. -- Element: None -- Modifiers: STR:73~85%, depending on merit points upgrades. -- 100%TP 200%TP 300%TP -- 0.71875 1.5 2.25 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 5; params.ftp100 = 0.71875; params.ftp200 = 0.84375 params.ftp300 = 0.96875 params.str_wsc = 0.85 + (player:getMerit(MERIT_RESOLUTION) / 100); params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 0.85; params.multiHitfTP = true if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 0.71875; params.ftp200 = 1.5 params.ftp300 = 2.25; params.str_wsc = 0.7 + (player:getMerit(MERIT_RESOLUTION) / 100); end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
rovemonteux/score_framework
src/io/midiio.lua
1
7449
------------------------------------------------------------------------------- ---- Score Framework - A Lua-based framework for creating multi-track MIDI files. ---- Copyright (c) 2017 Rove Monteux ---- ---- 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/>. --------------------------------------------------------------------------------- local MIDI = require 'MIDI' package.path = package.path .. ";../?.lua" require 'debug/dumper' -- duration of a 1/4 note in ms bpm_to_tempo = {[58]=1032,[59]=1016,[60]=1000,[61]=984,[62]=968,[63]=952,[64]=938,[65]=923,[66]=909,[67]=896,[68]=882,[69]=870,[70]=857,[71]=845,[72]=833,[73]=822,[74]=811,[75]=800,[76]=789,[77]=779,[78]=769,[79]=759,[80]=750,[81]=741,[82]=732,[83]=723,[84]=714,[85]=706,[86]=698,[87]=690,[88]=682,[89]=674,[90]=667,[91]=659,[92]=652,[93]=645,[94]=638,[95]=632,[96]=625,[97]=619,[98]=612,[99]=606,[100]=600,[101]=594,[102]=588,[103]=583,[104]=577,[105]=571,[106]=566,[107]=561,[108]=556,[109]=550,[110]=545,[111]=541,[112]=536,[113]=531,[114]=526,[115]=522,[116]=517,[117]=513,[118]=508,[119]=504} function write_midi () filename = score_name .. ".mid" drums_score = clone(my_score) -- position 2 drums_score[6] = nil drums_score[5] = nil drums_score[4] = nil drums_score[3] = nil bass_score = clone(my_score) -- position 3 table.remove(bass_score,6) table.remove(bass_score,5) table.remove(bass_score,4) table.remove(bass_score,2) synth_score = clone(my_score) -- position 4 table.remove(synth_score,6) table.remove(synth_score,5) table.remove(synth_score,3) table.remove(synth_score,2) guitar_score = clone(my_score) -- position 5 table.remove(guitar_score,6) table.remove(guitar_score,4) table.remove(guitar_score,3) table.remove(guitar_score,2) piano_score = clone(my_score) -- position 6 table.remove(piano_score,5) table.remove(piano_score,4) table.remove(piano_score,3) table.remove(piano_score,2) file = io.open("score_debug.txt", "w") file:write("Drums:\n") file:write(DataDumper(drums_score)) file:write("\n\nBass:\n") file:write(DataDumper(bass_score)) file:write("\n\nSynth:\n") file:write(DataDumper(synth_score)) file:write("\n\nGuitar:\n") file:write(DataDumper(guitar_score)) file:write("\n\nPiano:\n") file:write(DataDumper(guitar_score)) file:close() save('drums_',filename,drums_score) save('bass_',filename,bass_score) save('synth_',filename,synth_score) save('guitar_',filename,guitar_score) save('piano_',filename,piano_score) audio_process() end function audio_process() if (drum) then os.execute("timidity --output-24bit drums_"..score_name..".mid -OwS -k0 -a -o drums_"..score_name..".wav") end os.execute("timidity --output-24bit bass_"..score_name..".mid -OwS -k0 -a -o bass_"..score_name..".wav") os.execute("timidity --output-24bit synth_"..score_name..".mid -OwS -k0 -a -o synth_"..score_name..".wav") if (guitar) then os.execute("timidity --output-24bit guitar_"..score_name..".mid -OwS -k0 -a -o guitar_"..score_name..".wav") end os.execute("timidity --output-24bit piano_"..score_name..".mid -OwS -k0 -a -o piano_"..score_name..".wav") if (drum) then os.execute("sox -v 1.8 drums_"..score_name..".wav -b 24 drums_"..score_name.."-temp.wav equalizer 20 280 35 equalizer 4000 12000 35 equalizer 16000 2000 30 contrast 8 overdrive 2 50 reverb 3 rate 48000 dither -s -a") end os.execute("sox bass_"..score_name..".wav -b 24 bass_"..score_name.."-temp.wav equalizer 200 100 4 equalizer 14000 10000 -60 overdrive 4 80 rate 48000 dither -s -a") os.execute("sox bass_"..score_name.."-temp.wav -b 24 bass_"..score_name..".wav rate 48000 dither -s -a") os.execute("sox -v 0.5 bass_"..score_name..".wav -b 24 bass_"..score_name.."-temp.wav equalizer 10000 20000 -60 rate 48000 dither -s -a") os.execute("sox -v 0.6 synth_"..score_name..".wav -b 24 synth_"..score_name.."-temp.wav equalizer 2000 3000 5 contrast 2 overdrive 4 50 bass -3 echos 0.8 0.6 320 0.8 rate 48000 dither -s -a") os.execute("sox -v 1.6 piano_"..score_name..".wav -b 24 piano_"..score_name.."-temp.wav contrast 4 overdrive 2 50 echos 0.8 0.7 10 0.10 bass -4 rate 48000 dither -s -a") if (guitar) then os.execute("sox guitar_"..score_name..".wav -b 24 guitar_"..score_name.."-temp.wav treble 20 contrast 100 overdrive 68 100 rate 48000 dither -s -a") os.execute("sox guitar_"..score_name.."-temp.wav -b 24 guitar_"..score_name..".wav contrast 100 overdrive 68 100 bass 20 rate 48000 dither -s -a") os.execute("sox guitar_"..score_name..".wav -b 24 guitar_"..score_name.."-temp.wav contrast 100 overdrive 70 100 treble 20 reverb rate 48000 dither -s -a") os.execute("sox -v 0.01 guitar_"..score_name.."-temp.wav -b 24 guitar_"..score_name..".wav rate 48000 dither -s -a") end local mix = "sox -m " if (drum) then mix = mix .. "drums_" .. score_name .. "-temp.wav " end if (bass) then mix = mix .. "bass_" .. score_name .. "-temp.wav " end if (synthesizer) then mix = mix .. "synth_" .. score_name .. "-temp.wav " end if (piano) then mix = mix .. "piano_" .. score_name .. "-temp.wav " end mix = mix .. score_name .. "-temp.wav rate 48000 dither -s -a" print("Mix down: "..mix) os.execute(mix) local trim_factor = bpm_to_tempo[my_score[1]] / 300 print("tempo: "..my_score[1]..", trim factor: "..trim_factor) print("Trim factor: "..trim_factor) os.execute("sox "..score_name.."-temp.wav "..score_name.."-trim-temp.wav trim "..trim_factor.." rate 48000 dither -s -a") os.execute("sox "..score_name.."-trim-temp.wav "..score_name..".wav rate 48000 equalizer 4000 2000 4 lowpass -1 17801 compand .1,.3 9:-10,-0.3,-9 -6 -90 .1 dither -s -a") os.execute("sox -v 5.7 "..score_name..".wav "..score_name.."-temp.wav rate 48000 dither -s -a") os.execute("sox "..score_name.."-temp.wav "..score_name..".wav rate 48000 pad 1 dither -s -a") if (guitar) then os.execute("sox guitar_"..score_name..".wav guitar_"..score_name.."-trim-temp.wav trim "..trim_factor.." rate 48000 dither -s -a") os.execute("sox -m "..score_name..".wav guitar_"..score_name.."-trim-temp.wav "..score_name.."-plus-guitar-temp.wav rate 48000 dither -s -a") os.execute("mv "..score_name.."-plus-guitar-temp.wav "..score_name..".wav") end -- os.execute("sox "..score_name..".wav -n spectogram -o "..score_name..".png") os.execute("lame -q0 -b320 "..score_name..".wav rove_monteux-"..score_name..".mp3") end function save(prefix,filename,score) local midifile = assert(io.open(prefix..filename,'w')) midifile:write(MIDI.score2midi(score)) midifile:close() end function clone (t) if type(t) ~= "table" then return t end local meta = getmetatable(t) local target = {} for k, v in pairs(t) do if type(v) == "table" then target[k] = clone(v) else target[k] = v end end setmetatable(target, meta) return target end
gpl-3.0
bgshih/crnn
third_party/lmdb-lua-ffi/tests/test_reverse_keys.lua
1
1479
describe("LMDB revese keys", function() local os = require 'os' local lmdb = require 'lmdb' local utils = require 'utils' local dump = utils.dump local testdb = './db/test-rev' local env, msg = nil local revdb = nil local data = {19,28,37,46,55,64,73,82,91} setup(function() os.remove(testdb) os.remove(testdb .. '-lock') env, msg = lmdb.environment(testdb, {subdir = false, max_dbs=8}) revdb = env:db_open('rev_db', { reverse_keys = true }) env:transaction(function(txn) for i=1,9 do txn:put(data[i],10 - i) end end, lmdb.WRITE, revdb) end) teardown(function() env = nil msg = nil collectgarbage() os.remove(testdb) os.remove(testdb .. '-lock') end) it("checks cursor simple iteration", function() env:transaction(function(txn) local i, c = 9, txn:cursor() for k,v in c:iter() do assert.equals(k, tostring(i * 10 + 10 - i)) i = i - 1 end end, lmdb.READ_ONLY, revdb) end) it("checks cursor reverse iteration", function() env:transaction(function(txn) local i, c = 1, txn:cursor() for k,v in c:iter({reverse = true}) do assert.equals(k, tostring(i * 10 + 10 - i)) i = i + 1 end end, lmdb.READ_ONLY, revdb) end) end)
mit
nyczducky/darkstar
scripts/zones/Rabao/npcs/Edigey.lua
12
2587
----------------------------------- -- Area: Rabao -- NPC: Edigey -- Starts and Ends Quest: Don't Forget the Antidote ----------------------------------- package.loaded["scripts/zones/Rabao/TextIDs"] = nil; require("scripts/globals/titles"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Rabao/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) ForgetTheAntidote = player:getQuestStatus(OUTLANDS,DONT_FORGET_THE_ANTIDOTE); if ((ForgetTheAntidote == QUEST_ACCEPTED or ForgetTheAntidote == QUEST_COMPLETED) and trade:hasItemQty(1209,1) and trade:getItemCount() == 1) then player:startEvent(0x0004,0,1209); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) ForgetTheAntidote = player:getQuestStatus(OUTLANDS,DONT_FORGET_THE_ANTIDOTE); if (ForgetTheAntidote == QUEST_AVAILABLE and player:getFameLevel(RABAO) >= 4) then player:startEvent(0x0002,0,1209); elseif (ForgetTheAntidote == QUEST_ACCEPTED) then player:startEvent(0x0003,0,1209); elseif (ForgetTheAntidote == QUEST_COMPLETED) then player:startEvent(0x0005,0,1209); else player:startEvent(0x0032); 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 == 0x0002 and option == 1) then player:addQuest(OUTLANDS,DONT_FORGET_THE_ANTIDOTE); player:setVar("DontForgetAntidoteVar",1); elseif (csid == 0x0004 and player:getVar("DontForgetAntidoteVar") == 1) then --If completing for the first time player:setVar("DontForgetAntidoteVar",0); player:tradeComplete(); player:addTitle(262); player:addItem(16974); -- Dotanuki player:messageSpecial(ITEM_OBTAINED, 16974); player:completeQuest(OUTLANDS,DONT_FORGET_THE_ANTIDOTE); player:addFame(RABAO,60); elseif (csid == 0x0004) then --Subsequent completions player:tradeComplete(); player:addGil(GIL_RATE*1800); player:messageSpecial(GIL_OBTAINED, 1800); player:addFame(RABAO,30); end end;
gpl-3.0
nyczducky/darkstar
scripts/globals/items/bunny_ball.lua
12
1724
----------------------------------------- -- ID: 4349 -- Item: Bunny Ball -- Food Effect: 240Min, All Races ----------------------------------------- -- Health 10 -- Strength 2 -- Vitality 2 -- Intelligence -1 -- Attack % 30 (cap 30) -- Ranged ATT % 30 (cap 30) ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,4349); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 10); target:addMod(MOD_STR, 2); target:addMod(MOD_VIT, 2); target:addMod(MOD_INT, -1); target:addMod(MOD_FOOD_ATTP, 30); target:addMod(MOD_FOOD_ATT_CAP, 30); target:addMod(MOD_FOOD_RATTP, 30); target:addMod(MOD_FOOD_RATT_CAP, 30); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 10); target:delMod(MOD_STR, 2); target:delMod(MOD_VIT, 2); target:delMod(MOD_INT, -1); target:delMod(MOD_FOOD_ATTP, 30); target:delMod(MOD_FOOD_ATT_CAP, 30); target:delMod(MOD_FOOD_RATTP, 30); target:delMod(MOD_FOOD_RATT_CAP, 30); end;
gpl-3.0
nyczducky/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/_5f7.lua
12
1101
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Leviathan's Gate -- @pos 249 -34 100 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (npc:getAnimation() == 9) then player:messageSpecial(SOLID_STONE); end return 0; end; -- ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Periqia/IDs.lua
8
4247
Periqia = { text = { -- General Texts ITEM_CANNOT_BE_OBTAINED = 6378, -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6381, -- Obtained: <item> GIL_OBTAINED = 6384, -- Obtained <number> gil KEYITEM_OBTAINED = 6384, -- Obtained key item: <keyitem> -- Assault Texts ASSAULT_31_START = 7447, ASSAULT_32_START = 7448, ASSAULT_33_START = 7449, ASSAULT_34_START = 7450, ASSAULT_35_START = 7451, ASSAULT_36_START = 7452, ASSAULT_37_START = 7453, ASSAULT_38_START = 7454, ASSAULT_39_START = 7455, ASSAULT_40_START = 7456, TIME_TO_COMPLETE = 7477, MISSION_FAILED = 7478, RUNE_UNLOCKED_POS = 7479, RUNE_UNLOCKED = 7480, ASSAULT_POINTS_OBTAINED = 7481, TIME_REMAINING_MINUTES = 7482, TIME_REMAINING_SECONDS = 7483, PARTY_FALLEN = 7485, -- Seagull Grounded EXCALIACE_START = 7494, EXCALIACE_END1 = 7495, EXCALIACE_END2 = 7496, EXCALIACE_ESCAPE = 7497, EXCALIACE_PAIN1 = 7498, EXCALIACE_PAIN2 = 7499, EXCALIACE_PAIN3 = 7500, EXCALIACE_PAIN4 = 7501, EXCALIACE_PAIN5 = 7502, EXCALIACE_CRAB1 = 7503, EXCALIACE_CRAB2 = 7504, EXCALIACE_CRAB3 = 7505, EXCALIACE_DEBAUCHER1 = 7506, EXCALIACE_DEBAUCHER2 = 7507, EXCALIACE_RUN = 7508, EXCALIACE_TOO_CLOSE = 7509, EXCALIACE_TIRED = 7510, EXCALIACE_CAUGHT = 7511, }, mobs = { -- Seagull Grounded [31] = { CRAB1 = 17006594, CRAB2 = 17006595, CRAB3 = 17006596, CRAB4 = 17006597, CRAB5 = 17006598, CRAB6 = 17006599, CRAB7 = 17006600, CRAB8 = 17006601, CRAB9 = 17006602, DEBAUCHER1 = 17006603, PUGIL1 = 17006604, PUGIL2 = 17006605, PUGIL3 = 17006606, PUGIL4 = 17006607, PUGIL5 = 17006608, DEBAUCHER2 = 17006610, DEBAUCHER3 = 17006611, }, -- Shades of Vengeance [79] = { K23H1LAMIA1 = 17006754, K23H1LAMIA2 = 17006755, K23H1LAMIA3 = 17006756, K23H1LAMIA4 = 17006757, K23H1LAMIA5 = 17006758, K23H1LAMIA6 = 17006759, K23H1LAMIA7 = 17006760, K23H1LAMIA8 = 17006761, K23H1LAMIA9 = 17006762, K23H1LAMIA10 = 17006763, } }, npcs = { EXCALIACE = 17006593, ANCIENT_LOCKBOX = 17006809, RUNE_OF_RELEASE = 17006810, _1K1 = 17006840, _1K2 = 17006841, _1K3 = 17006842, _1K4 = 17006843, _1K5 = 17006844, _1K6 = 17006845, _1K7 = 17006846, _1K8 = 17006847, _1K9 = 17006848, _1KA = 17006849, _1KB = 17006850, _1KC = 17006851, _1KD = 17006852, _1KE = 17006853, _1KF = 17006854, _1KG = 17006855, _1KH = 17006856, _1KI = 17006857, _1KJ = 17006858, _1KK = 17006859, _1KL = 17006860, _1KM = 17006861, _1KN = 17006862, _1KO = 17006863, _1KP = 17006864, _1KQ = 17006865, _1KR = 17006866, _1KS = 17006867, _1KT = 17006868, _1KU = 17006869, _1KV = 17006870, _1KW = 17006871, _1KX = 17006872, _1KY = 17006873, _1KZ = 17006874, _JK0 = 17006875, _JK1 = 17006876, _JK2 = 17006877, _JK3 = 17006878, _JK4 = 17006879, _JK5 = 17006880, _JK6 = 17006881, _JK7 = 17006882, _JK8 = 17006883, _JK9 = 17006884, _JKA = 17006885, _JKB = 17006886, _JKC = 17006887, _JKD = 17006888, _JKE = 17006889, _JKF = 17006890, _JKG = 17006891, _JKH = 17006892, _JKI = 17006893, _JKJ = 17006894, _JKK = 17006895, _JKL = 17006896, _JKM = 17006897, _JKN = 17006898, _JKO = 17006899, } }
gpl-3.0
nyczducky/darkstar
scripts/globals/spells/bluemagic/sheep_song.lua
27
1358
----------------------------------------- -- Spell: Sheep Song -- Puts all enemies within range to sleep -- Spell cost: 22 MP -- Monster Type: Beasts -- Spell Type: Magical (Light) -- Blue Magic Points: 2 -- Stat Bonus: CHR+1, HP+5 -- Level: 16 -- Casting Time: Casting Time: 3 seconds -- Recast Time: Recast Time: 60 seconds -- Duration: 60 seconds -- Magic Bursts on: Transfixion, Fusion, and Light -- Combos: Auto Regen ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffect = EFFECT_SLEEP_I; local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT)); local resist = applyResistanceEffect(caster,spell,target,dINT,BLUE_SKILL,0,typeEffect); local duration = 60 * resist; if (resist > 0.5) then -- Do it! if (target:addStatusEffect(typeEffect,1,0,duration)) then spell:setMsg(236); else spell:setMsg(75); end else spell:setMsg(85); end; return typeEffect; end;
gpl-3.0
Tanmoytkd/vlc
share/lua/playlist/vimeo.lua
65
3213
--[[ $Id$ Copyright © 2009-2013 the VideoLAN team Authors: Konstantin Pavlov (thresh@videolan.org) François Revol (revol@free.fr) Pierre Ynard This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] function get_prefres() local prefres = -1 if vlc.var and vlc.var.inherit then prefres = vlc.var.inherit(nil, "preferred-resolution") if prefres == nil then prefres = -1 end end return prefres end -- Probe function. function probe() return ( vlc.access == "http" or vlc.access == "https" ) and ( string.match( vlc.path, "vimeo%.com/%d+$" ) or string.match( vlc.path, "player%.vimeo%.com" ) ) -- do not match other addresses, -- else we'll also try to decode the actual video url end -- Parse function. function parse() if not string.match( vlc.path, "player%.vimeo%.com" ) then -- Web page URL while true do local line = vlc.readline() if not line then break end path = string.match( line, "data%-config%-url=\"(.-)\"" ) if path then path = vlc.strings.resolve_xml_special_chars( path ) return { { path = path } } end end vlc.msg.err( "Couldn't extract vimeo video URL, please check for updates to this script" ) return { } else -- API URL local prefres = get_prefres() local line = vlc.readline() -- data is on one line only for stream in string.gmatch( line, "{([^}]*\"profile\":[^}]*)}" ) do local url = string.match( stream, "\"url\":\"(.-)\"" ) if url then path = url if prefres < 0 then break end local height = string.match( stream, "\"height\":(%d+)[,}]" ) if not height or tonumber(height) <= prefres then break end end end if not path then vlc.msg.err( "Couldn't extract vimeo video URL, please check for updates to this script" ) return { } end local name = string.match( line, "\"title\":\"(.-)\"" ) local artist = string.match( line, "\"owner\":{[^}]-\"name\":\"(.-)\"" ) local arturl = string.match( line, "\"thumbs\":{\"[^\"]+\":\"(.-)\"" ) local duration = string.match( line, "\"duration\":(%d+)[,}]" ) return { { path = path; name = name; artist = artist; arturl = arturl; duration = duration } } end end
gpl-2.0
omidtarh/elbot
plugins/face.lua
641
3073
local https = require("ssl.https") local ltn12 = require "ltn12" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function request(imageUrl) local api_key = mashape.api_key if api_key:isempty() then return nil, 'Configure your Mashape API Key' end local api = "https://faceplusplus-faceplusplus.p.mashape.com/detection/detect?" local parameters = "attribute=gender%2Cage%2Crace" parameters = parameters .. "&url="..(URL.escape(imageUrl) or "") local url = api..parameters local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "Accept: application/json" } print(url) local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return "", code end local body = table.concat(respbody) return body, code end local function parseData(data) local jsonBody = json:decode(data) local response = "" if jsonBody.error ~= nil then if jsonBody.error == "IMAGE_ERROR_FILE_TOO_LARGE" then response = response .. "The image is too big. Provide a smaller image." elseif jsonBody.error == "IMAGE_ERROR_FAILED_TO_DOWNLOAD" then response = response .. "Is that a valid url for an image?" else response = response .. jsonBody.error end elseif jsonBody.face == nil or #jsonBody.face == 0 then response = response .. "No faces found" else response = response .. #jsonBody.face .." face(s) found:\n\n" for k,face in pairs(jsonBody.face) do local raceP = "" if face.attribute.race.confidence > 85.0 then raceP = face.attribute.race.value:lower() elseif face.attribute.race.confidence > 50.0 then raceP = "(probably "..face.attribute.race.value:lower()..")" else raceP = "(posibly "..face.attribute.race.value:lower()..")" end if face.attribute.gender.confidence > 85.0 then response = response .. "There is a " else response = response .. "There may be a " end response = response .. raceP .. " " .. face.attribute.gender.value:lower() .. " " response = response .. ", " .. face.attribute.age.value .. "(±".. face.attribute.age.range ..") years old \n" end end return response end local function run(msg, matches) --return request('http://www.uni-regensburg.de/Fakultaeten/phil_Fak_II/Psychologie/Psy_II/beautycheck/english/durchschnittsgesichter/m(01-32)_gr.jpg') local data, code = request(matches[1]) if code ~= 200 then return "There was an error. "..code end return parseData(data) end return { description = "Who is in that photo?", usage = { "!face [url]", "!recognise [url]" }, patterns = { "^!face (.*)$", "^!recognise (.*)$" }, run = run }
gpl-2.0
mynameiscraziu/mycaty
plugins/face.lua
641
3073
local https = require("ssl.https") local ltn12 = require "ltn12" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function request(imageUrl) local api_key = mashape.api_key if api_key:isempty() then return nil, 'Configure your Mashape API Key' end local api = "https://faceplusplus-faceplusplus.p.mashape.com/detection/detect?" local parameters = "attribute=gender%2Cage%2Crace" parameters = parameters .. "&url="..(URL.escape(imageUrl) or "") local url = api..parameters local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "Accept: application/json" } print(url) local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return "", code end local body = table.concat(respbody) return body, code end local function parseData(data) local jsonBody = json:decode(data) local response = "" if jsonBody.error ~= nil then if jsonBody.error == "IMAGE_ERROR_FILE_TOO_LARGE" then response = response .. "The image is too big. Provide a smaller image." elseif jsonBody.error == "IMAGE_ERROR_FAILED_TO_DOWNLOAD" then response = response .. "Is that a valid url for an image?" else response = response .. jsonBody.error end elseif jsonBody.face == nil or #jsonBody.face == 0 then response = response .. "No faces found" else response = response .. #jsonBody.face .." face(s) found:\n\n" for k,face in pairs(jsonBody.face) do local raceP = "" if face.attribute.race.confidence > 85.0 then raceP = face.attribute.race.value:lower() elseif face.attribute.race.confidence > 50.0 then raceP = "(probably "..face.attribute.race.value:lower()..")" else raceP = "(posibly "..face.attribute.race.value:lower()..")" end if face.attribute.gender.confidence > 85.0 then response = response .. "There is a " else response = response .. "There may be a " end response = response .. raceP .. " " .. face.attribute.gender.value:lower() .. " " response = response .. ", " .. face.attribute.age.value .. "(±".. face.attribute.age.range ..") years old \n" end end return response end local function run(msg, matches) --return request('http://www.uni-regensburg.de/Fakultaeten/phil_Fak_II/Psychologie/Psy_II/beautycheck/english/durchschnittsgesichter/m(01-32)_gr.jpg') local data, code = request(matches[1]) if code ~= 200 then return "There was an error. "..code end return parseData(data) end return { description = "Who is in that photo?", usage = { "!face [url]", "!recognise [url]" }, patterns = { "^!face (.*)$", "^!recognise (.*)$" }, run = run }
gpl-2.0
Klozz/LuaPlayer
src/test/test.lua
1
9305
--[[ Regression and speed tests. Usage: write a function, which returns the time and some string, which are used for compare the functionality of this function againts a reference version of Lua Player and add the function name to the "tests" array. Results: PNGs are created for the tests and the reference.txt, which can be copied into this script, when started from a working Lua Player version. Errors are displayed in red at the end of the test. If it is mor than 10% slower than the reference, it is counted as an error. Looks like sometimes (very rare) the alpha blitting fails, but would be changed with the pspgl implementation anyway. ]] --System.usbDiskModeActivate() function profileStart() theTimer = Timer.new() theTimer:start() end function profile() return theTimer:time() end function createTestImage(destiantion, width, height) math.randomseed(0) for x = 0, width - 1 do for y = 0, height - 1 do destiantion:pixel(x, y, Color.new(math.random(0, 255), math.random(0, 255), math.random(0, 255))) end end end function md5ForFile(filename) local file = io.open(filename, "r") if file then local md5sum = System.md5sum(file:read("*a")) file:close() return md5sum end return -1 end function testSmallImage(pngName) width = 31 height = 43 profileStart() for i = 1, 100 do image = Image.createEmpty(width, height) createTestImage(image, width, height) end time = profile() image:save(pngName) return time, md5ForFile(pngName) end function testFullScreenPixelPlot(pngName) profileStart() createTestImage(screen, 480, 272) time = profile() screen.waitVblankStart() screen.flip() screen:save(pngName) return time, md5ForFile(pngName) end function testTransparencyImage(pngName) profileStart() width = 31 height = 43 image = Image.createEmpty(width, height) createTestImage(image, width, height) image:fillRect(10, 10, 10, 10) i2 = Image.createEmpty(100, 100) i2:clear(red) for i = 1, 2000 do i2:blit(5, 7, image) i2:blit(50, 9, image, 0, 0, image:width(), image:height(), false) end time = profile() i2:save(pngName) return time, md5ForFile(pngName) end function testTransparencyScreen(pngName) profileStart() width = 31 height = 43 image = Image.createEmpty(width, height) createTestImage(image, width, height) image:fillRect(10, 10, 10, 10) screen:clear(red) for i = 1, 1000 do screen:blit(5, 7, image) screen:blit(71, 9, image, 0, 0, image:width(), image:height(), false) end time = profile() screen.waitVblankStart() screen.flip() screen:save(pngName) return time, md5ForFile(pngName) end function testClippingImage(pngName) profileStart() width = 31 height = 43 image = Image.createEmpty(width, height) createTestImage(image, width, height) i2 = Image.createEmpty(100, 100) i2:clear(red) for i = 1, 1000 do i2:blit(5, 7, image) i2:blit(-5, 7, image) i2:blit(-5, -7, image) i2:blit(5, -7, image) i2:blit(80, -7, image) i2:blit(80, 7, image) i2:blit(50, 80, image) i2:blit(80, 80, image) i2:blit(30, 30, image, 2, 3, 10, 10) i2:blit(-5, 93, image, 2, 3, 10, 10) end time = profile() i2:save(pngName) return time, md5ForFile(pngName) end function testClippingScreen(pngName) profileStart() width = 31 height = 43 image = Image.createEmpty(width, height) createTestImage(image, width, height) screen:clear(red) for i = 1, 1000 do screen:blit(5, 7, image) screen:blit(-5, 7, image) screen:blit(-5, -7, image) screen:blit(5, -7, image) screen:blit(470, -7, image) screen:blit(470, 7, image) screen:blit(260, 470, image) screen:blit(260, 470, image) screen:blit(130, 30, image, 2, 3, 10, 10) screen:blit(-5, 265, image, 2, 3, 10, 10) end time = profile() screen.waitVblankStart() screen.flip() screen:save(pngName) return time, md5ForFile(pngName) end function testLine(target, pngName) target:clear() profileStart() for c = 0, 1000 do for i = 0, 20 do x0 = i/20*479 y1 = 271-i/20*271 target:drawLine(x0, 271, 479, y1, green) end end time = profile() screen.waitVblankStart() screen.flip() target:save(pngName) return time, md5ForFile(pngName) end function testLineImage(pngName) return testLine(Image.createEmpty(480, 272), pngName) end function testLineScreen(pngName) return testLine(screen, pngName) end function testText(target, pngName) target:clear() profileStart() for c = 0, 10000 do target:print(11, 13, "Hello", red) target:print(11, 130, "Hello", green) end time = profile() screen.waitVblankStart() screen.flip() target:save(pngName) return time, md5ForFile(pngName) end function testTextImage(pngName) return testText(Image.createEmpty(480, 272), pngName) end function testTextScreen(pngName) return testText(screen, pngName) end function testBlitSpeedAlpha(source, target, pngName) source:clear() target:clear() createTestImage(source, 480, 272) profileStart() for c = 0, 100 do target:blit(0, 0, source) end time = profile() screen.waitVblankStart() screen.flip() target:save(pngName) return time, md5ForFile(pngName) end function testBlitSpeedAlphaImage(pngName) return testBlitSpeedAlpha(Image.createEmpty(480, 272), Image.createEmpty(480, 272), pngName) end function testBlitSpeedAlphaScreen(pngName) return testBlitSpeedAlpha(Image.createEmpty(480, 272), screen, pngName) end function testBlitSpeedCopy(source, target, pngName) source:clear() target:clear() createTestImage(source, 480, 272) profileStart() for c = 0, 1000 do target:blit(0, 0, source, 0, 0, 480, 272, false) end time = profile() screen.waitVblankStart() screen.flip() target:save(pngName) return time, md5ForFile(pngName) end function testBlitSpeedCopyImage(pngName) return testBlitSpeedCopy(Image.createEmpty(480, 272), Image.createEmpty(480, 272), pngName) end function testBlitSpeedCopyScreen(pngName) return testBlitSpeedCopy(Image.createEmpty(480, 272), screen, pngName) end --[[ the old 5551 timings: { name="testSmallImage", time=8131, result="10d7fcf1f0a4c5c94984542e526dca9b" }, { name="testFullScreenPixelPlot", time=7178, result="5361a7ccb80fc2f861c878a55bd1bb1c" }, { name="testTransparencyImage", time=508, result="24814c6078ac85280d39fc9ae2ca1e95" }, { name="testTransparencyScreen", time=443, result="1b0d0d3a508e40565870cdf2d63182c1" }, { name="testClippingImage", time=734, result="f3b0612cf7f817144a8a367b3dc7777f" }, { name="testClippingScreen", time=1492, result="46849356d3a32a55ac461c62c96ab3e8" }, { name="testLineImage", time=2011, result="771f552f193347f3b2587833e5d72e97" }, { name="testLineScreen", time=660, result="90a154ffd897c6879087cf3e44f71994" }, { name="testTextImage", time=720, result="60da8160e4c9315529da05490c27b9f9" }, { name="testTextScreen", time=596, result="9098e15f373da5b19eaa8ef93dbea872" }, { name="testBlitSpeedAlphaImage", time=1020, result="858b57847ffc5d527203f98ea98ed8e2" }, { name="testBlitSpeedAlphaScreen", time=474, result="5361a7ccb80fc2f861c878a55bd1bb1c" }, { name="testBlitSpeedCopyImage", time=8382, result="858b57847ffc5d527203f98ea98ed8e2" }, { name="testBlitSpeedCopyScreen", time=1694, result="5361a7ccb80fc2f861c878a55bd1bb1c" }, testBlitSpeedAlphaScreen and testBlitSpeedCopyScreen needs to be faster for the 8888 mode ]] tests = { { name="testSmallImage", time=8757, result="01d42086a28ec1cf03c551ce75ddd30a" }, { name="testFullScreenPixelPlot", time=7760, result="b24f32a46df7088f08587d51e7071bd0" }, { name="testTransparencyImage", time=647, result="9b6cad02f04c0cb4942f5b602ba13357" }, { name="testTransparencyScreen", time=577, result="595c0b4d67c4f15142daf639d4ad4461" }, { name="testClippingImage", time=954, result="71fc06f295443cba12db8bdcd85ad078" }, { name="testClippingScreen", time=1787, result="d9a719f406a5f8f50e6a1c66758c081d" }, { name="testLineImage", time=2228, result="995675cd3da15e1918255a5aa6b53aae" }, { name="testLineScreen", time=737, result="213678f024aa302c7431a4c991fc355e" }, { name="testTextImage", time=807, result="7a0baad1a6a22afa622f05d749f7fffa" }, { name="testTextScreen", time=588, result="7716950c9b560863494f51b542dbd854" }, { name="testBlitSpeedAlphaImage", time=1332, result="5d917a000187d605ba4d07d4ff32bda3" }, { name="testBlitSpeedAlphaScreen", time=955, result="b24f32a46df7088f08587d51e7071bd0" }, { name="testBlitSpeedCopyImage", time=11198, result="5d917a000187d605ba4d07d4ff32bda3" }, { name="testBlitSpeedCopyScreen", time=3415, result="b24f32a46df7088f08587d51e7071bd0" }, } textY = 0 green = Color.new(0, 255, 0) red = Color.new(255, 0, 0) reference = io.open("reference.txt", "w") for _, test in tests do test.measuredTime, test.measuredResult = _G[test.name](test.name .. ".png") reference:write("\t{ name=\"" .. test.name .. "\", time=" .. test.measuredTime .. ", result=\"" .. test.measuredResult .. "\" },\n") end reference:close() screen:clear() for _, test in tests do if test.result ~= test.measuredResult then result = "not ok" color = red else result = "ok" color = green end delta = test.measuredTime - test.time if delta > test.time / 10 then color = red end screen:print(0, textY, test.name .. ": time delta: " .. delta .. ", result: " .. result, color) textY = textY + 8 end screen.flip() while true do screen.waitVblankStart() if Controls.read():start() then break end end
bsd-3-clause
dtrip/awesome
tests/test-awful-placement.lua
3
10098
local awful = require("awful") local test_client = require("_client") local runner = require("_runner") local cruled = require("ruled.client") -- This test makes some assumptions about the no_overlap behavior which may not -- be correct if the screen is in the portrait orientation. if mouse.screen.workarea.height >= mouse.screen.workarea.width then print("This test does not work with the portrait screen orientation.") runner.run_steps { function() return true end } return end local tests = {} -- Set it to something different than the default to make sure it doesn't change -- due to some request::border. local border_width = 3 local class = "test-awful-placement" local rule = { rule = { class = class }, properties = { floating = true, border_width = border_width, placement = awful.placement.no_overlap + awful.placement.no_offscreen } } cruled.append_rule(rule) local function check_geometry(c, x, y, width, height) local g = c:geometry() if g.x ~= x or g.y ~= y or g.width ~= width or g.height ~= height then assert(false, string.format("(%d, %d, %d, %d) ~= (%d, %d, %d, %d)", g.x, g.y, g.width, g.height, x, y, width, height)) end end local function default_test(c, geometry) check_geometry(c, geometry.expected_x, geometry.expected_y, geometry.expected_width or geometry.width, geometry.expected_height or (geometry.height)) return true end local client_data = {} local function add_client(args) local data = {} table.insert(client_data, data) local client_index = #client_data table.insert(tests, function(count) local name = string.format("client%010d", client_index) if count <= 1 then data.prev_client_count = #client.get() local geometry = args.geometry(mouse.screen.workarea) test_client(class, name, args.sn_rules, nil, nil, { size = { width = geometry.width, height = geometry.height } }) data.geometry = geometry return nil elseif #client.get() > data.prev_client_count then local c = data.c if not c then c = client.get()[1] assert(c.name == name) data.c = c end local test = args.test or default_test return test(c, data.geometry) end end) end -- Repeat testing 3 times, placing clients on different tags: -- -- - Iteration 1 places clients on the tag 1, which is selected. -- -- - Iteration 2 places clients on the tag 2, which is unselected; the -- selected tag 1 remains empty. -- -- - Iteration 3 places clients on the tag 3, which is unselected; the -- selected tag 1 contains some clients. -- for _, tag_num in ipairs{1, 2, 3} do local sn_rules if tag_num > 1 then sn_rules = { tag = root.tags()[tag_num] } end -- Put a 100x100 client on the tag 1 before iteration 3. if tag_num == 3 then add_client { geometry = function(wa) return { width = 100, height = 100, expected_x = wa.x, expected_y = wa.y } end } end -- The first 100x100 client should be placed at the top left corner. add_client { sn_rules = sn_rules, geometry = function(wa) return { width = 100, height = 100, expected_x = wa.x, expected_y = wa.y } end } -- Remember the first client data for the current iteration. local first_client_data = client_data[#client_data] -- The second 100x100 client should be placed to the right of the first -- client. Note that this assumption fails if the screen is in the portrait -- orientation (e.g., the test succeeds with a 600x703 screen and fails with -- 600x704). add_client { sn_rules = sn_rules, geometry = function(wa) return { width = 100, height = 100, expected_x = wa.x + 100 + 2*border_width, expected_y = wa.y } end } -- Hide last client. do local data = client_data[#client_data] table.insert(tests, function() data.c.hidden = true return true end) end -- Another 100x100 client should be placed to the right of the first client -- (the hidden client should be ignored during placement). add_client { sn_rules = sn_rules, geometry = function(wa) return { width = 100, height = 100, expected_x = wa.x + 100 + 2*border_width, expected_y = wa.y } end } -- Minimize last client. do local data = client_data[#client_data] table.insert(tests, function() data.c.minimized = true return true end) end -- Another 100x100 client should be placed to the right of the first client -- (the minimized client should be ignored during placement). add_client { sn_rules = sn_rules, geometry = function(wa) return { width = 100, height = 100, expected_x = wa.x + 100 + 2*border_width, expected_y = wa.y } end } -- Hide last client, and make the first client sticky. do local data = client_data[#client_data] table.insert(tests, function() data.c.hidden = true first_client_data.c.sticky = true return true end) end -- Another 100x100 client should be placed to the right of the first client -- (the sticky client should be taken into account during placement). add_client { sn_rules = sn_rules, geometry = function(wa) return { width = 100, height = 100, expected_x = wa.x + 100 + 2*border_width, expected_y = wa.y } end } -- Hide last client, and put the first client on the tag 9 (because the -- first client is sticky, it should remain visible). do local data = client_data[#client_data] table.insert(tests, function() data.c.hidden = true first_client_data.c:tags{ root.tags()[9] } return true end) end -- Another 100x100 client should be placed to the right of the first client -- (the sticky client should be taken into account during placement even if -- that client seems to be on an unselected tag). add_client { sn_rules = sn_rules, geometry = function(wa) return { width = 100, height = 100, expected_x = wa.x + 100 + 2*border_width, expected_y = wa.y } end } -- The wide client should be placed below the two 100x100 client. add_client { sn_rules = sn_rules, geometry = function(wa) return { width = wa.width - 50, height = 100, expected_x = wa.x, expected_y = wa.y + 2*border_width + 100 } end } -- The first large client which does not completely fit in any free area -- should be placed at the bottom left corner (no_overlap should place it -- below the wide client, and then no_offscreen should shift it up so that -- it would be completely inside the workarea). add_client { sn_rules = sn_rules, geometry = function(wa) return { width = wa.width - 10, height = wa.height - 50, expected_x = wa.x, expected_y = (wa.y + wa.height) - (wa.height - 50 + 2*border_width) } end } -- The second large client should be placed at the top right corner. add_client { sn_rules = sn_rules, geometry = function(wa) return { width = wa.width - 10, height = wa.height - 50, expected_x = (wa.x + wa.width) - (wa.width - 10 + 2*border_width), expected_y = wa.y } end } -- The third large client should be placed at the bottom right corner. add_client { sn_rules = sn_rules, geometry = function(wa) return { width = wa.width - 10, height = wa.height - 50, expected_x = (wa.x + wa.width ) - (wa.width - 10 + 2*border_width), expected_y = (wa.y + wa.height) - (wa.height - 50 + 2*border_width) } end } -- The fourth large client should be placed at the top left corner (the -- whole workarea is occupied now). add_client { sn_rules = sn_rules, geometry = function(wa) return { width = wa.width - 50, height = wa.height - 50, expected_x = wa.x, expected_y = wa.y } end } -- Kill test clients to prepare for the next iteration. table.insert(tests, function(count) if count <= 1 then for _, data in ipairs(client_data) do if data.c then data.c:kill() data.c = nil end end end if #client.get() == 0 then return true end end) end runner.run_steps(tests) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
nyczducky/darkstar
scripts/zones/Northern_San_dOria/npcs/Pulloie.lua
17
1041
----------------------------------- -- Area: Northern San d'Oria -- NPC: Pulloie -- Quest NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getNation() == 0) then player:startEvent(0x0253); else player:startEvent(0x0256); 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
nyczducky/darkstar
scripts/globals/items/bowl_of_adoulinian_soup.lua
12
1563
----------------------------------------- -- ID: 5998 -- Item: Bowl of Adoulin Soup -- Food Effect: 180 Min, All Races ----------------------------------------- -- HP % 3 Cap 40 -- Vitality 3 -- Defense % 15 Cap 70 -- HP Healing 6 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5998); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 3); target:addMod(MOD_FOOD_HP_CAP, 40); target:addMod(MOD_VIT, 3); target:addMod(MOD_FOOD_DEFP, 15); target:addMod(MOD_FOOD_DEF_CAP, 70); target:addMod(MOD_HPHEAL, 6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 3); target:delMod(MOD_FOOD_HP_CAP, 40); target:delMod(MOD_VIT, 3); target:delMod(MOD_FOOD_DEFP, 15); target:delMod(MOD_FOOD_DEF_CAP, 70); target:delMod(MOD_HPHEAL, 6); end;
gpl-3.0
timn/ros-fawkes_lua
src/fawkes/fsm.lua
1
11399
------------------------------------------------------------------------ -- fsm.lua - Lua Finite State Machines (FSM) -- -- Created: Fri Jun 13 11:25:36 2008 -- Copyright 2008-2010 Tim Niemueller [www.niemueller.de] -- 2010 Carnegie Mellon University -- 2010 Intel Labs Pittsburgh ------------------------------------------------------------------------ -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU Library General Public License for more details. -- -- Read the full text in the LICENSE.GPL file in the doc directory. require("fawkes.modinit") --- This module provides a generic finite state machine (FSM). -- @author Tim Niemueller module(..., fawkes.modinit.module_init) -- Re-export State and JumpState for convenience local statemod = require("fawkes.fsm.state") State = statemod.State local jumpstmod = require("fawkes.fsm.jumpstate") JumpState = jumpstmod.JumpState local fsmgrapher = require("fawkes.fsm.grapher") --- FSM Finite State Machine -- Representation with utility methods of a FSM. FSM = { current = nil, debug = false, export_states_to_parent = true } --- Constructor. -- Create a new FSM with the given table as the base. -- @param o table with initializations. The table may not have a metatable set and -- it must have the fields name (name of the FSM) and start (name of start state -- of the FSM). -- @return initialized FSM function FSM:new(o) assert(o, "FSM requires a table as argument") assert(o.name, "FSM requires a name") assert(o.start, "FSM requires start state") if o.debug then assert(type(o.debug) == "boolean", "FSM debug value must be a boolean") end assert(not getmetatable(o), "Meta table already set for object") setmetatable(o, self) self.__index = self o.recursion_limit = 10 o.current_recursion = 0 o.persistent_vars = {} o.vars = {} o.states = {} o.state_changed = false o.trace = {} o.tracing = true o.error = "" o.exit_state = o.exit_state o.fail_state = o.fail_state o.prepared = false o.max_num_traces = 40 return o end --- Check if state was reached in current trace. -- @param state state to check if a transition originated from or went to this one -- @return two values, first is true if state is included in -- current trace, false otherwise, second is a list of traces where the -- given state was involved. Note that the indexes of the traces in -- the list are not consecutive! function FSM:traced_state(state) if not self.tracing then return false end local traces = {} for i,t in ipairs(self.trace) do if t.from == state or t.to == state then traces[i] = t end end if next(traces) then return true, traces else return false, {} end end --- Check if the given transition was used in current trace. -- @param trans transition to check -- @return two values, first is true if transition is included in -- current trace, false otherwise, second is a list of traces where the -- given transition was involved. Note that the indexes of the traces in -- the list are not consecutive! function FSM:traced_trans(trans) if not self.tracing then return false end local traces = {} for i,t in ipairs(self.trace) do if t.transition == trans then traces[i] = t end end if next(traces) then return true, traces else return false, {} end end --- Check if the given state or transition was used in current trace. -- @param sot state or transition to check, if a string assumed to be a state name -- @return two values, first is true if state/transition is included in -- current trace, false otherwise, second is a list of traces where the -- given state/transition was involved. Note that the indexes of the traces in -- the list are not consecutive! function FSM:traced(sot) if not self.tracing then return false end local traces = {} if type(sot) == "string" then sot = self.states[sot] end for i,t in ipairs(self.trace) do if t.from == sot or t.transition == sot then traces[i] = t end end if next(traces) then return true, traces else return false, {} end end --- Get graph representation of FSM. -- This creates a graph representation of this FSM using the graphviz library. -- The graph is returned as a string in the dot graph language. -- @return graph representation as string in the dot graph language function FSM:graph() return fsmgrapher.dotgraph(self) end --- Check if the FSM changed since last call. -- The FSM has changed if there has been a transition to a new state since the -- last call to reset() or changed(). Note that changed() will only ever return -- true at most once per cycle as it resets the changed flag during execution. -- @return true if the FSM has changed, false otherwise function FSM:changed() local rv = self.state_changed self.state_changed = false return rv end --- Mark FSM as changed. -- This can be used to cause a redrawing of the FSM graph if a state changed its -- label for example. function FSM:mark_changed() self.state_changed = true end --- Set change state of FSM. -- @param changed true to mark FSM as changed, false otherwise function FSM:set_changed(changed) if changed ~= nil then self.state_changed = changed else self.state_changed = true end end --- Convenience method to create a new state. -- Creates a new instance of State and assigns it to the states table. Any variables -- that exist in the (optional) vars table are put into state as local variables. -- @param name name of the state and optionally the variable in the environment -- of the caller that holds this state -- @param vars all values from this table will be added to the newly created state. -- @param export_to if passed a table this method will assign the state to a field -- with the name of the state in that table. function FSM:new_state(name, vars, export_to) assert(self.states[name] == nil, "FSM:new_state: State with name " .. name .. " already exists") local o = {name = name, fsm = self} if vars then assert(type(vars) == "table", "FSM:new_state: vars parameter must be a table") for k,v in pairs(vars) do o[k] = v end end local s = State:new(o) self.states[name] = s if export_to then export_to[name] = s end return s end --- Enable or disable debugging. -- Value can be either set for an instance of SkillHSM, or globally for SkillHSM -- to set the new default value which applies to newly generated SkillHSMs. -- @param debug true to enable debugging, false to disable function FSM:set_debug(debug) self.debug = debug end --- Set error of FSM. -- Sets the error for the FSM and prints it as warning. -- @param error error message function FSM:set_error(error) self.error = error if self.debug and error ~= nil and error ~= "" then print_warn("FSM %s: %s", self.name, self.error) end end --- Remove all states. function FSM:clear_states() self.states = {} self.state_changed = true end --- Run the FSM. -- Runs the loop() function of the current state and executes possible state -- transitions that result from running the loop. function FSM:loop() self.current_recursion = 0 if not self.current then -- FSM was just reset, initialize start state self.current = self.states[self.start] assert(self.current, "Start state " .. tostring(self.start) .. " does not exist") self:trans(self.current:do_init()) self.state_changed = true end if self.current.name ~= self.fail_state then -- This is really noisy... -- if self.debug then -- print_debug(self.name .. ": Executing loop for state " .. self.current.name) -- end self:trans(self.current:do_loop()) elseif self.error == "" and self.previous then local t = self.previous:last_transition() if t and t.description then self:set_error(t.description) else self:set_error("reached fail state " .. self.fail_state .. " via unknown transition"); end end end --- Execute state transition. -- If next_state is not nil, it calls the exit() function of the current state, and -- then calls the init() function of the next state with any given additional -- parameters. After that, the current state becomes next. -- @param next_state next state, if nil no transition is executed -- @param ... any number of extra arguments, passed to next:init(). function FSM:trans(next_state, ...) if next_state then if self.tracing then local trans = self.current:last_transition() if #self.trace > self.max_num_traces then table.remove(self.trace) end table.insert(self.trace, {from = self.current, transition = trans, to = next_state}) end -- Some sanity check to avoid infinite loops self.current_recursion = self.current_recursion + 1 assert(self.current_recursion < self.recursion_limit, "Recursion limit (" .. tostring(self.recursion_limit) .. ") reached, infinite loop?") self.state_changed = true if self.debug then print_debug("%s: Transition %s -> %s", self.name, self.current.name, next_state.name) end self.current:do_exit() self.previous = self.current self.current = next_state return self:trans(next_state:do_init(...)) end end --- Resets the internal trace. -- Tracing information will be discarded. This can be used to restart the -- trace without causing a whole FSM reset. function FSM:reset_trace() self.trace = {} self.state_changed = true end --- Reset FSM. -- Unsets the current state, if there was one the exit() routine is called. All -- states of this FSM are reset, traces and variables are reset, FSM is marked as -- changed. The next call to loop() will initialize the start state and set it as -- current state. function FSM:reset() if self.current then self.current:do_exit() end for k,_ in pairs(self.vars) do self.vars[k] = nil end -- Do not do the following, it breaks jump conditions that are passed as -- Lua string --self.vars = {} if not self.prepared then for n,s in pairs(self.states) do s:prepare() end self.prepared = true end for n,s in pairs(self.states) do s:reset() end self.trace = {} self.current = nil self.state_changed = true self.error = "" if self.debug then print_debug("FSM '%s' reset done", self.name) end end --- Check if given object is an instance of FSM class. -- @return true if obj is an instance of FSM class function FSM.is_instance(obj) local mt = getmetatable(obj) while mt do if mt == FSM then return true end mt = getmetatable(mt) end return false end
gpl-2.0
sjznxd/lc-20121231
applications/luci-statistics/luasrc/model/cbi/luci_statistics/iwinfo.lua
78
1089
--[[ Luci configuration model for statistics - collectd interface plugin configuration (c) 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local m, s, o m = Map("luci_statistics", translate("Wireless iwinfo Plugin Configuration"), translate("The iwinfo plugin collects statistics about wireless signal strength, noise and quality.")) s = m:section(NamedSection, "collectd_iwinfo", "luci_statistics") o = s:option(Flag, "enable", translate("Enable this plugin")) o.default = 0 o = s:option(Value, "Interfaces", translate("Monitor interfaces"), translate("Leave unselected to automatically determine interfaces to monitor.")) o.template = "cbi/network_ifacelist" o.widget = "checkbox" o.nocreate = true o:depends("enable", 1) o = s:option(Flag, "IgnoreSelected", translate("Monitor all except specified")) o.default = 0 o:depends("enable", 1) return m
apache-2.0
hadess/libquvi-scripts-iplayer
share/lua/website/imdb.lua
4
3692
-- -- libquvi-scripts -- Copyright (C) 2011 quvi project -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library 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 -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- local IMDB = {} -- Utility functions unique to this script -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = 'imdb%.com' r.formats = 'default|best' local B = require 'quvi/bit' r.categories = B.bit_or(C.proto_http, C.proto_rtmp) local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/video/.+"}) return r end -- Query available formats. function query_formats(self) local page = quvi.fetch(self.page_url) local formats = IMDB.iter_formats(page) local t = {} for _,v in pairs(formats) do table.insert(t, IMDB.to_s(v)) end table.sort(t) self.formats = table.concat(t, "|") return self end -- Parse media URL. function parse(self) self.host_id = 'imdb' self.id = self.page_url:match('/video/%w+/(vi%d-)/') local page = quvi.fetch(self.page_url) self.title = page:match('<title>(.-) %- IMDb</title>') -- -- Format codes (for most videos): -- uff=1 - 480p RTMP -- uff=2 - 480p HTTP -- uff=3 - 720p HTTP -- local formats = IMDB.iter_formats(page) local U = require 'quvi/util' local format = U.choose_format(self, formats, IMDB.choose_best, IMDB.choose_default, IMDB.to_s) or error("unable to choose format") if not format.path then error("no match: media url") end local url = 'http://www.imdb.com' .. format.path local iframe = quvi.fetch(url, {fetch_type = 'config'}) local file = iframe:match('so%.addVariable%("file", "(.-)"%);') file = U.unescape(file) if file:match('^http.-') then self.url = {file} else local path = iframe:match('so%.addVariable%("id", "(.-)"%);') path = U.unescape(path) self.url = {file .. path} end -- Optional: we can live without these local thumb = iframe:match('so%.addVariable%("image", "(.-)"%);') self.thumbnail_url = thumb or '' return self end -- -- Utility functions -- function IMDB.iter_formats(page) local p = "case '(.-)' :.-url = '(.-)';" local t = {} for c,u in page:gmatch(p) do table.insert(t, {path=u, container=c}) --print(u,c) end -- First item is ad, so remove it table.remove(t, 1) return t end function IMDB.choose_best(t) -- Expect the last to be the 'best' return t[#t] end function IMDB.choose_default(t) -- Expect the second to be the 'default' return t[2] end function IMDB.to_s(t) return t.container end -- vim: set ts=4 sw=4 tw=72 expandtab:
lgpl-2.1
jbeich/Aquaria
files/scripts/maps/_unused/node_naija_minimap.lua
6
1097
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end function init(me) end function update(me, dt) if isFlag(FLAG_NAIJA_MINIMAP, 0) then if node_isEntityIn(me, getNaija()) then voice("naija_minimap") setFlag(FLAG_NAIJA_MINIMAP, 1) end end end
gpl-2.0
nyczducky/darkstar
scripts/globals/items/simit.lua
12
1253
----------------------------------------- -- ID: 5596 -- Item: simit -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 16 -- Dexterity -1 -- Vitality 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,1800,5596); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 16); target:addMod(MOD_DEX, -1); target:addMod(MOD_VIT, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 16); target:delMod(MOD_DEX, -1); target:delMod(MOD_VIT, 3); end;
gpl-3.0
nyczducky/darkstar
scripts/zones/Northern_San_dOria/npcs/Arienh.lua
14
1034
----------------------------------- -- Area: Northern San d'Oria -- NPC: Arienh -- Type: Standard Dialogue NPC -- @zone 231 -- @pos -37.292 -2.000 -6.817 -- ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,ARIENH_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
nyczducky/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Aligi-Kufongi.lua
27
3114
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Aligi-Kufongi -- Title Change NPC -- @pos -23 -21 15 26 ----------------------------------- require("scripts/globals/titles"); local title2 = { TAVNAZIAN_SQUIRE ,PUTRID_PURVEYOR_OF_PUNGENT_PETALS , MONARCH_LINN_PATROL_GUARD , SIN_HUNTER_HUNTER , DISCIPLE_OF_JUSTICE , DYNAMISTAVNAZIA_INTERLOPER , CONFRONTER_OF_NIGHTMARES , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title3 = { DEAD_BODY , FROZEN_DEAD_BODY , DREAMBREAKER , MIST_MELTER , DELTA_ENFORCER , OMEGA_OSTRACIZER , ULTIMA_UNDERTAKER , ULMIAS_SOULMATE , TENZENS_ALLY , COMPANION_OF_LOUVERANCE , TRUE_COMPANION_OF_LOUVERANCE , PRISHES_BUDDY , NAGMOLADAS_UNDERLING , ESHANTARLS_COMRADE_IN_ARMS , THE_CHEBUKKIS_WORST_NIGHTMARE , UNQUENCHABLE_LIGHT , WARRIOR_OF_THE_CRYSTAL , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title4 = { ANCIENT_FLAME_FOLLOWER , TAVNAZIAN_TRAVELER , TRANSIENT_DREAMER , THE_LOST_ONE , TREADER_OF_AN_ICY_PAST , BRANDED_BY_LIGHTNING , SEEKER_OF_THE_LIGHT , AVERTER_OF_THE_APOCALYPSE , BANISHER_OF_EMPTINESS , BREAKER_OF_THE_CHAINS , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title5 = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title6 = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title7 = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0156,npcUtil.genTmask(player,title2),npcUtil.genTmask(player,title3),npcUtil.genTmask(player,title4),npcUtil.genTmask(player,title5),npcUtil.genTmask(player,title6),npcUtil.genTmask(player,title7),1 ,player:getGil()); 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 == 0x0156) then if (option > 0 and option <29) then if (player:delGil(200)) then player:setTitle( title2[option] ) end elseif (option > 256 and option <285) then if (player:delGil(300)) then player:setTitle( title3[option - 256] ) end elseif (option > 512 and option < 541) then if (player:delGil(400)) then player:setTitle( title4[option - 512] ) end end end end;
gpl-3.0
sjznxd/lc-20121231
applications/luci-asterisk/luasrc/model/cbi/asterisk-mod-codec.lua
80
2172
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- cbimap = Map("asterisk", "asterisk", "") module = cbimap:section(TypedSection, "module", "Modules", "") module.anonymous = true codec_a_mu = module:option(ListValue, "codec_a_mu", "A-law and Mulaw direct Coder/Decoder", "") codec_a_mu:value("yes", "Load") codec_a_mu:value("no", "Do Not Load") codec_a_mu:value("auto", "Load as Required") codec_a_mu.rmempty = true codec_adpcm = module:option(ListValue, "codec_adpcm", "Adaptive Differential PCM Coder/Decoder", "") codec_adpcm:value("yes", "Load") codec_adpcm:value("no", "Do Not Load") codec_adpcm:value("auto", "Load as Required") codec_adpcm.rmempty = true codec_alaw = module:option(ListValue, "codec_alaw", "A-law Coder/Decoder", "") codec_alaw:value("yes", "Load") codec_alaw:value("no", "Do Not Load") codec_alaw:value("auto", "Load as Required") codec_alaw.rmempty = true codec_g726 = module:option(ListValue, "codec_g726", "ITU G.726-32kbps G726 Transcoder", "") codec_g726:value("yes", "Load") codec_g726:value("no", "Do Not Load") codec_g726:value("auto", "Load as Required") codec_g726.rmempty = true codec_gsm = module:option(ListValue, "codec_gsm", "GSM/PCM16 (signed linear) Codec Translation", "") codec_gsm:value("yes", "Load") codec_gsm:value("no", "Do Not Load") codec_gsm:value("auto", "Load as Required") codec_gsm.rmempty = true codec_speex = module:option(ListValue, "codec_speex", "Speex/PCM16 (signed linear) Codec Translator", "") codec_speex:value("yes", "Load") codec_speex:value("no", "Do Not Load") codec_speex:value("auto", "Load as Required") codec_speex.rmempty = true codec_ulaw = module:option(ListValue, "codec_ulaw", "Mu-law Coder/Decoder", "") codec_ulaw:value("yes", "Load") codec_ulaw:value("no", "Do Not Load") codec_ulaw:value("auto", "Load as Required") codec_ulaw.rmempty = true return cbimap
apache-2.0
nyczducky/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/CeraneIVirgaut1.lua
14
1059
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Cerane I Virgaut -- @zone 80 -- @pos -268 -4 100 ----------------------------------- 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
benloz10/FinalFrontier
gamemodes/finalfrontier/gamemode/sgui/accesspage.lua
3
1767
-- Copyright (c) 2014 James King [metapyziks@gmail.com] -- -- This file is part of Final Frontier. -- -- Final Frontier is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as -- published by the Free Software Foundation, either version 3 of -- the License, or (at your option) any later version. -- -- Final Frontier 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 Lesser General Public License -- along with Final Frontier. If not, see <http://www.gnu.org/licenses/>. local BASE = "page" GUI.BaseName = BASE GUI._roomView = nil GUI._doorViews = nil function GUI:Enter() self.Super[BASE].Enter(self) self._roomView = sgui.Create(self:GetScreen(), "roomview") self._roomView:SetCurrentRoom(self:GetRoom()) self._doorViews = {} if self:GetRoom() then for _, door in ipairs(self:GetRoom():GetDoors()) do local doorview = sgui.Create(self, "doorview") doorview:SetCurrentDoor(door) doorview.Enabled = true doorview.NeedsPermission = true self._doorViews[door] = doorview end end self:AddChild(self._roomView) local margin = 16 self._roomView:SetBounds(Bounds( margin, margin, self:GetWidth() - margin * 2, self:GetHeight() - margin * 2 )) if CLIENT then for door, doorview in pairs(self._doorViews) do doorview:ApplyTransform(self._roomView:GetAppliedTransform()) end end end
lgpl-3.0
benloz10/FinalFrontier
gamemodes/finalfrontier/gamemode/sgui/doorview.lua
3
5687
-- Copyright (c) 2014 James King [metapyziks@gmail.com] -- -- This file is part of Final Frontier. -- -- Final Frontier is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as -- published by the Free Software Foundation, either version 3 of -- the License, or (at your option) any later version. -- -- Final Frontier 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 Lesser General Public License -- along with Final Frontier. If not, see <http://www.gnu.org/licenses/>. local BASE = "base" if SERVER then resource.AddFile("materials/power.png") else GUI._powerImage = Material("power.png", "smooth") end GUI.BaseName = BASE GUI._door = nil GUI._bounds = nil GUI.CanClick = true GUI.Enabled = false GUI.NeedsPermission = true GUI.OpenLockedColor = Color(0, 64, 0, 255) GUI.OpenUnlockedColor = Color(0, 0, 0, 255) GUI.ClosedLockedColor = Color(127, 64, 64, 255) GUI.ClosedUnlockedColor = Color(64, 64, 64, 255) function GUI:SetCurrentDoor(door) self._door = door end function GUI:GetCurrentDoor() return self._door end if SERVER then function GUI:OnClick(x, y, button) local ply = self:GetUsingPlayer() local door = self:GetCurrentDoor() if not self.Enabled or (self.NeedsPermission and not ply:HasDoorPermission(door)) then return false end if button == MOUSE2 then if door:IsLocked() then door:Unlock() else door:Lock() end else if door:IsClosed() then door:LockOpen() else door:UnlockClose() end end return true end function GUI:UpdateLayout(layout) self.Super[BASE].UpdateLayout(self, layout) if self._door then layout.door = self._door:GetIndex() else layout.door = nil end end end if CLIENT then GUI._transform = nil GUI._poly = nil GUI.Color = Color(32, 32, 32, 255) function GUI:GetDoorColor() local door = self:GetCurrentDoor() if door:IsOpen() then if door:IsLocked() then return self.OpenLockedColor else return self.OpenUnlockedColor end else if door:IsLocked() then return self.ClosedLockedColor else return self.ClosedUnlockedColor end end end function GUI:ApplyTransform(transform) if self._transform == transform or not self._door then return end self._transform = transform self._poly = {} local bounds = Bounds() local ox = self:GetParent():GetGlobalLeft() local oy = self:GetParent():GetGlobalTop() for i, v in ipairs(self._door:GetCorners()) do local x, y = transform:Transform(v.x, v.y) self._poly[i] = { x = x, y = y } bounds:AddPoint(x - ox, y - oy) end self:SetBounds(bounds) end function GUI:GetAppliedTransform() return self._transform end function GUI:Draw() if self._transform then local last, lx, ly = nil, 0, 0 local ply = self:GetUsingPlayer() self.CanClick = self.Enabled and (not self.NeedsPermission or (ply and ply.HasDoorPermission and ply:HasDoorPermission(self._door))) surface.SetDrawColor(self:GetDoorColor()) surface.DrawPoly(self._poly) if self.CanClick and self:IsCursorInside() then surface.SetDrawColor(Color(255, 255, 255, 16)) surface.DrawPoly(self._poly) end surface.SetDrawColor(Color(255, 255, 255, 255)) last = self._poly[#self._poly] lx, ly = last.x, last.y for _, v in ipairs(self._poly) do surface.DrawLine(lx, ly, v.x, v.y) lx, ly = v.x, v.y end if self.Enabled and not self.CanClick then surface.SetDrawColor(Color(255, 255, 255, 32)) surface.DrawLine(self._poly[1].x, self._poly[1].y, self._poly[3].x, self._poly[3].y) surface.DrawLine(self._poly[2].x, self._poly[2].y, self._poly[4].x, self._poly[4].y) end if self:GetCurrentDoor():IsUnlocked() and not self:GetCurrentDoor():IsPowered() and Pulse(1) >= 0.5 then local size = math.min(self:GetWidth(), self:GetHeight()) local x, y = self:GetGlobalOrigin() x = x + (self:GetWidth() - size) * 0.5 y = y + (self:GetHeight() - size) * 0.5 surface.SetMaterial(self._powerImage) surface.SetDrawColor(Color(255, 219, 89, 255)) surface.DrawTexturedRect(x, y, size, size) draw.NoTexture() end end self.Super[BASE].Draw(self) end function GUI:UpdateLayout(layout) self.Super[BASE].UpdateLayout(self, layout) if layout.door then if not self._door or self._door:GetIndex() ~= layout.door then self:SetCurrentDoor(self:GetScreen():GetShip():GetDoorByIndex(layout.door)) end else self._door = nil end end end
lgpl-3.0
abcdefg30/OpenRA
mods/cnc/maps/nod09/nod09.lua
6
8708
--[[ Copyright 2007-2022 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you 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. For more information, see COPYING. ]] if Difficulty == "easy" then Rambo = "rmbo.easy" elseif Difficulty == "hard" then Rambo = "rmbo.hard" else Rambo = "rmbo" end WaypointGroup1 = { waypoint0, waypoint3, waypoint2, waypoint4, waypoint5, waypoint7 } WaypointGroup2 = { waypoint0, waypoint3, waypoint2, waypoint4, waypoint5, waypoint6 } WaypointGroup3 = { waypoint0, waypoint8, waypoint9, waypoint10, waypoint11, waypoint12, waypoint6, waypoint13 } Patrol1Waypoints = { waypoint0.Location, waypoint8.Location, waypoint9.Location, waypoint10.Location } Patrol2Waypoints = { waypoint0.Location, waypoint3.Location, waypoint2.Location, waypoint4.Location } GDI1 = { units = { ['e2'] = 3, ['e3'] = 2 }, waypoints = WaypointGroup1, delay = 40 } GDI2 = { units = { ['e1'] = 2, ['e2'] = 4 }, waypoints = WaypointGroup2, delay = 50 } GDI4 = { units = { ['jeep'] = 2 }, waypoints = WaypointGroup1, delay = 50 } GDI5 = { units = { ['mtnk'] = 1 }, waypoints = WaypointGroup1, delay = 40 } Auto1 = { units = { ['e1'] = 2, ['e3'] = 3 }, waypoints = WaypointGroup3, delay = 40 } Auto2 = { units = { ['e2'] = 2, ['e3'] = 2 }, waypoints = WaypointGroup3, delay = 50 } Auto3 = { units = { ['e1'] = 3, ['e2'] = 2 }, waypoints = WaypointGroup2, delay = 60 } Auto4 = { units = { ['mtnk'] = 1 }, waypoints = WaypointGroup1, delay = 50 } Auto5 = { units = { ['mtnk'] = 1 }, waypoints = WaypointGroup3, delay = 50 } Auto6 = { units = { ['e1'] = 2, ['e3'] = 2 }, waypoints = WaypointGroup3, delay = 50 } Auto7 = { units = { ['msam'] = 1 }, waypoints = WaypointGroup1, delay = 40 } Auto8 = { units = { ['msam'] = 1 }, waypoints = WaypointGroup3, delay = 50 } RmboReinforcements = { Rambo } EngineerReinforcements = { "e6", "e6" } RocketReinforcements = { "e3", "e3", "e3", "e3" } AutoAttackWaves = { GDI1, GDI2, GDI4, GDI5, Auto1, Auto2, Auto3, Auto4, Auto5, Auto6, Auto7, Auto8 } NodBaseTrigger = { CPos.New(9, 52), CPos.New(9, 51), CPos.New(9, 50), CPos.New(9, 49), CPos.New(9, 48), CPos.New(9, 47), CPos.New(9, 46), CPos.New(10, 46), CPos.New(11, 46), CPos.New(12, 46), CPos.New(13, 46), CPos.New(14, 46), CPos.New(15, 46), CPos.New(16, 46), CPos.New(17, 46), CPos.New(18, 46), CPos.New(19, 46), CPos.New(20, 46), CPos.New(21, 46), CPos.New(22, 46), CPos.New(23, 46), CPos.New(24, 46), CPos.New(25, 46), CPos.New(25, 47), CPos.New(25, 48), CPos.New(25, 49), CPos.New(25, 50), CPos.New(25, 51), CPos.New(25, 52) } EngineerTrigger = { CPos.New(5, 13), CPos.New(6, 13), CPos.New(7, 13), CPos.New(8, 13), CPos.New(9, 13), CPos.New(10, 13), CPos.New(16, 7), CPos.New(16, 6), CPos.New(16, 5), CPos.New(16, 4), CPos.New(16, 3)} RocketTrigger = { CPos.New(20, 15), CPos.New(21, 15), CPos.New(22, 15), CPos.New(23, 15), CPos.New(24, 15), CPos.New(25, 15), CPos.New(26, 15), CPos.New(32, 15), CPos.New(32, 14), CPos.New(32, 13), CPos.New(32, 12), CPos.New(32, 11)} AirstrikeDelay = DateTime.Minutes(2) + DateTime.Seconds(30) CheckForSams = function(Nod) local sams = Nod.GetActorsByType("sam") return #sams >= 3 end SendGDIAirstrike = function(hq, delay) if not hq.IsDead and hq.Owner == GDI then local target = GetAirstrikeTarget(Nod) if target then hq.TargetAirstrike(target, Angle.NorthEast + Angle.New(16)) Trigger.AfterDelay(delay, function() SendGDIAirstrike(hq, delay) end) else Trigger.AfterDelay(delay/4, function() SendGDIAirstrike(hq, delay) end) end end end SendWaves = function(counter, Waves) if counter <= #Waves then local team = Waves[counter] for type, amount in pairs(team.units) do MoveAndHunt(Utils.Take(amount, GDI.GetActorsByType(type)), team.waypoints) end Trigger.AfterDelay(DateTime.Seconds(team.delay), function() SendWaves(counter + 1, Waves) end) end end StartPatrols = function() local mtnks = GDI.GetActorsByType("mtnk") local msams = GDI.GetActorsByType("msam") if #mtnks >= 1 then mtnks[1].Patrol(Patrol1Waypoints, true, 20) end if #msams >= 1 then msams[1].Patrol(Patrol2Waypoints, true, 20) end end Trigger.OnEnteredFootprint(NodBaseTrigger, function(a, id) if not Nod.IsObjectiveCompleted(LocateNodBase) and a.Owner == Nod then Trigger.RemoveFootprintTrigger(id) Nod.MarkCompletedObjective(LocateNodBase) NodCYard.Owner = Nod local walls = NodBase.GetActorsByType("brik") Utils.Do(walls, function(actor) actor.Owner = Nod end) Trigger.AfterDelay(DateTime.Seconds(2), function() Media.PlaySpeechNotification(Nod, "NewOptions") end) end end) Trigger.OnEnteredFootprint(RocketTrigger, function(a, id) if not Nod.IsObjectiveCompleted(SecureFirstLanding) and a.Owner == Nod then Trigger.RemoveFootprintTrigger(id) Nod.MarkCompletedObjective(SecureFirstLanding) Trigger.AfterDelay(DateTime.Seconds(5), function() Media.PlaySpeechNotification(Nod, "Reinforce") Reinforcements.ReinforceWithTransport(Nod, "tran.in", RocketReinforcements, { HelicopterEntryRocket.Location, HelicopterGoalRocket.Location }, { HelicopterEntryRocket.Location }, nil, nil) end) Trigger.AfterDelay(DateTime.Seconds(10), function() EngineerFlareCamera1 = Actor.Create("camera", true, { Owner = Nod, Location = FlareEngineer.Location }) EngineerFlareCamera2 = Actor.Create("camera", true, { Owner = Nod, Location = CameraEngineerPath.Location }) EngineerFlare = Actor.Create("flare", true, { Owner = Nod, Location = FlareEngineer.Location }) end) Trigger.AfterDelay(DateTime.Minutes(1), function() RocketFlareCamera.Destroy() RocketFlare.Destroy() end) end end) Trigger.OnEnteredFootprint(EngineerTrigger, function(a, id) if not Nod.IsObjectiveCompleted(SecureSecondLanding) and a.Owner == Nod then Trigger.RemoveFootprintTrigger(id) Nod.MarkCompletedObjective(SecureSecondLanding) Trigger.AfterDelay(DateTime.Seconds(5), function() Media.PlaySpeechNotification(Nod, "Reinforce") Reinforcements.ReinforceWithTransport(Nod, "tran.in", EngineerReinforcements, { HelicopterEntryEngineer.Location, HelicopterGoalEngineer.Location }, { HelicopterEntryEngineer.Location }, nil, nil) end) Trigger.AfterDelay(DateTime.Minutes(1), function() if EngineerFlareCamera1 then EngineerFlareCamera1.Destroy() EngineerFlareCamera2.Destroy() EngineerFlare.Destroy() end end) end end) Trigger.OnKilledOrCaptured(OutpostProc, function() if not Nod.IsObjectiveCompleted(CaptureRefinery) then if OutpostProc.IsDead then Nod.MarkFailedObjective(CaptureRefinery) else Nod.MarkCompletedObjective(CaptureRefinery) Nod.Cash = 1000 end StartPatrols() Trigger.AfterDelay(DateTime.Minutes(1), function() SendWaves(1, AutoAttackWaves) end) Trigger.AfterDelay(AirstrikeDelay, function() SendGDIAirstrike(GDIHQ, AirstrikeDelay) end) Trigger.AfterDelay(DateTime.Minutes(3), function() ProduceInfantry(GDIPyle) end) Trigger.AfterDelay(DateTime.Minutes(3), function() ProduceVehicle(GDIWeap) end) end end) WorldLoaded = function() Nod = Player.GetPlayer("Nod") GDI = Player.GetPlayer("GDI") NodBase = Player.GetPlayer("NodBase") Camera.Position = CameraIntro.CenterPosition Media.PlaySpeechNotification(Nod, "Reinforce") Reinforcements.ReinforceWithTransport(Nod, "tran.in", RmboReinforcements, { HelicopterEntryRmbo.Location, HelicopterGoalRmbo.Location }, { HelicopterEntryRmbo.Location }) RocketFlareCamera = Actor.Create("camera", true, { Owner = Nod, Location = FlareRocket.Location }) RocketFlare = Actor.Create("flare", true, { Owner = Nod, Location = FlareRocket.Location }) StartAI() AutoGuard(GDI.GetGroundAttackers()) InitObjectives(Nod) SecureFirstLanding = Nod.AddObjective("Secure the first landing zone.") SecureSecondLanding = Nod.AddObjective("Secure the second landing zone.") LocateNodBase = Nod.AddObjective("Locate the Nod base.") CaptureRefinery = Nod.AddObjective("Capture the refinery.") EliminateGDI = Nod.AddObjective("Eliminate all GDI forces in the area.") BuildSAMs = Nod.AddObjective("Build 3 SAMs to fend off the GDI bombers.", "Secondary", false) GDIObjective = GDI.AddObjective("Eliminate all Nod forces in the area.") end Tick = function() if DateTime.GameTime > 2 and Nod.HasNoRequiredUnits() then GDI.MarkCompletedObjective(GDIObjective) end if DateTime.GameTime > 2 and GDI.HasNoRequiredUnits() then Nod.MarkCompletedObjective(EliminateGDI) end if not Nod.IsObjectiveCompleted(BuildSAMs) and CheckForSams(Nod) then Nod.MarkCompletedObjective(BuildSAMs) end end
gpl-3.0
SNiLD/TabletopSimulatorAgricola
src/Game Settings.lua
1
4871
--[[ Helpers ]] function table.contains(table, element) for _, value in pairs(table) do if value == element then return true end end return false end function table.removeByValue(table, value) found = false for tableKey, tableValue in pairs(table) do if tableValue == value then table[tableKey] = nil found = true end end return found end function table.getKey(table, value) for tableKey, tableValue in pairs(table) do if (tableValue == value) then return tableKey end end return nil end function table.toString(table, separator) result = "" for _, value in pairs(table) do if (string.len(result) == 0) then result = result .. value else result = result .. separator .. value end end return result end --[[ Globals for this script ]] objectGUIDsInTheZone = {} playerCount = 0 deckTypes = {} playerCountTokenGUIDs = { "f8d86b", "b51ba9", "feb2ff", "d5b306", "3eb5e5" } startGameTokenGUID = "201379" kDeckTokenGUID = "e1662e" eDeckTokenGUID = "9752bc" iDeckTokenGUID = "ae31c5" --[[ Private functions ]] function updateGameSettings() playerCount = 0 startGame = false deckTypes = {} for _, objectGUID in pairs(objectGUIDsInTheZone) do if (table.contains(playerCountTokenGUIDs, objectGUID)) then updatePlayerCount(objectGUID) elseif (objectGUID == kDeckTokenGUID) then table.insert(deckTypes, "K") elseif (objectGUID == eDeckTokenGUID) then table.insert(deckTypes, "E") elseif (objectGUID == iDeckTokenGUID) then table.insert(deckTypes, "I") elseif (objectGUID == startGameTokenGUID) then startGame = true end end print("Adjusting player count to " .. playerCount) setGlobalScriptVar("playerCount", playerCount) print("Adjusting deck types to '" .. table.toString(deckTypes, ",") .. "'") -- This is broken so we need to use other function at the moment -- setGlobalScriptTable(deckTypes, "deckTypes") callLuaFunctionInOtherScriptWithParams(nil, "setDeckTypes", deckTypes) if (startGame and not getGlobalScriptVar("gameStarted")) then print("Starting game") callLuaFunctionInOtherScript(nil, "initializeBoard") end end function updatePlayerCount(objectGUID) count = table.getKey(playerCountTokenGUIDs, objectGUID) if (count ~= nil and count > playerCount) then playerCount = count end end --[[ Event hooks ]] function onObjectEnterScriptingZone(zone, object) objectGUID = object.getGUID() if (zone.getGUID() ~= self.getGUID() or table.contains(objectGUIDsInTheZone, objectGUID)) then return end print("Object " .. object.getName() .. " type " .. object.name .. " GUID " .. objectGUID .. " entered Game Settings scripting zone") table.insert(objectGUIDsInTheZone, objectGUID) updateGameSettings() end function onObjectLeaveScriptingZone(zone, object) objectGUID = object.getGUID() if (zone.getGUID() ~= self.getGUID() or not table.contains(objectGUIDsInTheZone, objectGUID)) then return end print("Object " .. object.getName() .. " type " .. object.name .. " GUID " .. objectGUID .. " left Game Settings scripting zone") if (not table.removeByValue(objectGUIDsInTheZone, objectGUID)) then print("Object " .. object.getName() .. " GUID " .. objectGUID .. " was not in object GUIDs for this zone") return end updateGameSettings() end function onload() local playerCountButtonParameters = {} playerCountButtonParameters.click_function = "dummy" playerCountButtonParameters.label = "" playerCountButtonParameters.function_owner = nil playerCountButtonParameters.position = {0, -0.5, 0} playerCountButtonParameters.rotation = {180.0, 180.0, 0} playerCountButtonParameters.width = 0 playerCountButtonParameters.height = 0 playerCountButtonParameters.font_size = 180 for i=1, 5, 1 do playerCountButtonParameters.label = (i .. ' Players') getObjectFromGUID(playerCountTokenGUIDs[i]).createButton(playerCountButtonParameters) end playerCountButtonParameters.label = "Start\nGame" getObjectFromGUID(startGameTokenGUID).createButton(playerCountButtonParameters) playerCountButtonParameters.label = "K\nDeck" getObjectFromGUID(kDeckTokenGUID).createButton(playerCountButtonParameters) playerCountButtonParameters.label = "E\nDeck" getObjectFromGUID(eDeckTokenGUID).createButton(playerCountButtonParameters) playerCountButtonParameters.label = "I\nDeck" getObjectFromGUID(iDeckTokenGUID).createButton(playerCountButtonParameters) end
mit
AquariaOSE/Aquaria
files/scripts/entities/jellysmall.lua
6
5946
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end -- ================================================================================================ -- JELLY SMALL -- ================================================================================================ -- ================================================================================================ -- L O C A L V A R I A B L E S -- ================================================================================================ v.glow = 0 v.bulb = 0 v.revertTimer = 0 v.baseSpeed = 150 v.excitedSpeed = 300 v.runSpeed = 600 v.useMaxSpeed = 0 v.pushed = false v.shell = 0 v.soundDelay = 0 v.sx = 0 v.sy = 0 v.sz = 0.8 v.transition = false -- ================================================================================================ -- FUNCTIONS -- ================================================================================================ local function doIdleScale(me) entity_scale(me, 0.75*v.sz, 1*v.sz) entity_scale(me, 1*v.sz, 0.75*v.sz, 1.5, -1, 1, 1) end function init(me) setupBasicEntity( me, "", -- texture 3, -- health 2, -- manaballamount 2, -- exp 10, -- money 16, -- collideRadius (for hitting entities + spells) STATE_IDLE, -- initState 128, -- sprite width 128, -- sprite height 1, -- particle "explosion" type, 0 = none 0, -- 0/1 hit other entities off/on (uses collideRadius) 4000, -- updateCull -1: disabled, default: 4000 1 ) entity_setDeathParticleEffect(me, "TinyGreenExplode") v.useMaxSpeed = v.baseSpeed entity_setEntityType(me, ET_ENEMY) entity_initSkeletal(me, "JellySmall") --entity_scale(me, 0.6, 0.6) entity_setState(me, STATE_IDLE) --entity_setDropChance(me, 75) entity_initStrands(me, 5, 16, 8, 5, 0.8, 0.8, 1) v.glow = entity_getBoneByName(me, "Glow") v.bulb = entity_getBoneByName(me, "Bulb") v.shell = entity_getBoneByName(me, "Shell") doIdleScale(me) v.soundDelay = math.random(3) v.sx, v.sy = entity_getScale(me) entity_setDamageTarget(me, DT_AVATAR_LIZAP, false) entity_setDamageTarget(me, DT_AVATAR_PET, false) end function songNote(me, note) if getForm()~=FORM_NORMAL then return end --[[ v.sx, v.sy = entity_getScale(me) entity_scale(me, v.sx, v.sy) v.sx = v.sx*1.1 v.sy = v.sy*1.1 if v.sx > 1.0 then v.sx = 1.0 end if v.sy > 1.0 then v.sy = 1.0 end entity_scale(me, v.sx, v.sy, 0.2, 1, -1) ]]-- --[[ entity_setWidth(me, 128) entity_setHeight(me, 128) entity_setWidth(me, 512, 0.5, 1, -1) entity_setHeight(me, 512, 0.5, 1, -1) ]]-- bone_scale(v.shell, 1,1) bone_scale(v.shell, 1.1, 1.1, 0.1, 1, -1) entity_setMaxSpeed(me, v.excitedSpeed) v.revertTimer = 3 local transTime = 0.5 local r,g,b = getNoteColor(note) bone_setColor(v.bulb, r,g,b, transTime) r = (r+1.0)/2.0 g = (g+1.0)/2.0 b = (b+1.0)/2.0 bone_setColor(v.shell, r,g,b, transTime) end function update(me, dt) if entity_isState(me, STATE_IDLE) and not v.transition and not entity_isScaling(me) then entity_scale(me, 0.75*v.sz, 1*v.sz, 0.2) v.transition = true end if v.transition then if not entity_isScaling(me) then doIdleScale(me) v.transition = false end end entity_handleShotCollisions(me) entity_findTarget(me, 1024) if not entity_hasTarget(me) then --entity_doCollisionAvoidance(me, dt, 4, 0.1) end if v.revertTimer > 0 then v.soundDelay = v.soundDelay - dt if v.soundDelay < 0 then entity_sound(me, "JellyBlup", 1400+math.random(200)) v.soundDelay = 4 + math.random(2000)/1000.0 end v.revertTimer = v.revertTimer - dt if v.revertTimer < 0 then v.useMaxSpeed = v.baseSpeed entity_setMaxSpeed(me, v.baseSpeed) bone_setColor(v.shell, 1, 1, 1, 1) end end if entity_hasTarget(me) then if entity_isUnderWater(entity_getTarget(me)) then if getForm()==FORM_NORMAL then -- do something if entity_isTargetInRange(me, 1000) then if not entity_isTargetInRange(me, 64) then entity_moveTowardsTarget(me, dt, 250) end end else if entity_isTargetInRange(me, 512) then --entity_setMaxSpeed(me, 600) entity_setMaxSpeed(me, v.runSpeed) v.useMaxSpeed = v.runSpeed v.revertTimer = 0.1 entity_moveTowardsTarget(me, dt, -250) end end end --if not entity_isTargetInRange(me, 150) then --end end entity_doCollisionAvoidance(me, dt, 3, 1.0) entity_doEntityAvoidance(me, dt, 64, 0.2) entity_doSpellAvoidance(me, dt, 200, 0.8) entity_updateCurrents(me, dt*5) entity_rotateToVel(me, 0.1) entity_updateMovement(me, dt) end function hitSurface(me) end function enterState(me) if entity_isState(me, STATE_IDLE) then v.useMaxSpeed = v.baseSpeed entity_setMaxSpeed(me, v.baseSpeed) entity_animate(me, "idle", LOOP_INF) local x = math.random(2000)-1000 local y = math.random(2000)-1000 entity_addVel(me,x,y) end end function damage(me, attacker, bone, damageType, dmg) if damageType == DT_AVATAR_BITE then entity_setHealth(me, 0) end return true end function exitState(me) end
gpl-2.0
nyczducky/darkstar
scripts/globals/weaponskills/shockwave.lua
18
1486
----------------------------------- -- Shockwave -- Great Sword weapon skill -- Skill level: 150 -- Delivers an area of effect attack. Sleeps enemies. Duration of effect varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Aqua Gorget. -- Aligned with the Aqua Belt. -- Element: None -- Modifiers: STR:30% ; MND:30% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.3; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); if (damage > 0 and target:hasStatusEffect(EFFECT_SLEEP_I) == false) then local duration = (tp/1000 * 60); target:addStatusEffect(EFFECT_SLEEP_I, 1, 0, duration); end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
melfi19/OpenRA
mods/ra/maps/soviet-04b/AI.lua
19
2829
IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end IdlingUnits = function() local lazyUnits = Greece.GetGroundAttackers() Utils.Do(lazyUnits, function(unit) Trigger.OnDamaged(unit, function() Trigger.ClearAll(unit) Trigger.AfterDelay(0, function() IdleHunt(unit) end) end) end) end BaseBuildings = { { "powr", CVec.New(-4, -2), 300, true }, { "tent", CVec.New(-8, 1), 400, true }, { "proc", CVec.New(-5, 1), 1400, true }, { "weap", CVec.New(-12, -1), 2000, true } } BuildBase = function() if CYard.IsDead or CYard.Owner ~= Greece then return elseif Harvester.IsDead and Greece.Resources <= 299 then return end for i,v in ipairs(BaseBuildings) do if not v[4] then BuildBuilding(v) return end end Trigger.AfterDelay(DateTime.Seconds(10), BuildBase) end BuildBuilding = function(building) Trigger.AfterDelay(Actor.BuildTime(building[1]), function() local actor = Actor.Create(building[1], true, { Owner = Greece, Location = GreeceCYard.Location + building[2] }) Greece.Cash = Greece.Cash - building[3] building[4] = true Trigger.OnKilled(actor, function() building[4] = true end) Trigger.OnDamaged(actor, function(building) if building.Owner == Greece and building.Health < building.MaxHealth * 3/4 then building.StartBuildingRepairs() end end) Trigger.AfterDelay(DateTime.Seconds(10), BuildBase) end) end ProduceInfantry = function() if not BaseBuildings[2][4] then return elseif Harvester.IsDead and Greece.Resources <= 299 then return end local delay = Utils.RandomInteger(DateTime.Seconds(3), DateTime.Seconds(9)) local toBuild = { Utils.Random(AlliedInfantryTypes) } local Path = Utils.Random(AttackPaths) Greece.Build(toBuild, function(unit) InfAttack[#InfAttack + 1] = unit[1] if #InfAttack >= 10 then SendUnits(InfAttack, Path) InfAttack = { } Trigger.AfterDelay(DateTime.Minutes(2), ProduceInfantry) else Trigger.AfterDelay(delay, ProduceInfantry) end end) end ProduceArmor = function() if not BaseBuildings[4][4] then return elseif Harvester.IsDead and Greece.Resources <= 599 then return end local delay = Utils.RandomInteger(DateTime.Seconds(12), DateTime.Seconds(17)) local toBuild = { Utils.Random(AlliedArmorTypes) } local Path = Utils.Random(AttackPaths) Greece.Build(toBuild, function(unit) ArmorAttack[#ArmorAttack + 1] = unit[1] if #ArmorAttack >= 6 then SendUnits(ArmorAttack, Path) ArmorAttack = { } Trigger.AfterDelay(DateTime.Minutes(3), ProduceArmor) else Trigger.AfterDelay(delay, ProduceArmor) end end) end SendUnits = function(units, waypoints) Utils.Do(units, function(unit) if not unit.IsDead then Utils.Do(waypoints, function(waypoint) unit.AttackMove(waypoint.Location) end) unit.Hunt() end end) end
gpl-3.0
jbeich/Aquaria
files/scripts/maps/_unused/node_foundsecret03.lua
6
1100
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end v.done = false function init(me) end function update(me, dt) if v.done then return end if node_isEntityIn(me, getNaija()) then if foundLostMemory(FLAG_SECRET03) then v.done = true end end end
gpl-2.0
ruleless/skynet
lualib/http/internal.lua
95
2613
local table = table local type = type local M = {} local LIMIT = 8192 local function chunksize(readbytes, body) while true do local f,e = body:find("\r\n",1,true) if f then return tonumber(body:sub(1,f-1),16), body:sub(e+1) end if #body > 128 then -- pervent the attacker send very long stream without \r\n return end body = body .. readbytes() end end local function readcrln(readbytes, body) if #body >= 2 then if body:sub(1,2) ~= "\r\n" then return end return body:sub(3) else body = body .. readbytes(2-#body) if body ~= "\r\n" then return end return "" end end function M.recvheader(readbytes, lines, header) if #header >= 2 then if header:find "^\r\n" then return header:sub(3) end end local result local e = header:find("\r\n\r\n", 1, true) if e then result = header:sub(e+4) else while true do local bytes = readbytes() header = header .. bytes if #header > LIMIT then return end e = header:find("\r\n\r\n", -#bytes-3, true) if e then result = header:sub(e+4) break end if header:find "^\r\n" then return header:sub(3) end end end for v in header:gmatch("(.-)\r\n") do if v == "" then break end table.insert(lines, v) end return result end function M.parseheader(lines, from, header) local name, value for i=from,#lines do local line = lines[i] if line:byte(1) == 9 then -- tab, append last line if name == nil then return end header[name] = header[name] .. line:sub(2) else name, value = line:match "^(.-):%s*(.*)" if name == nil or value == nil then return end name = name:lower() if header[name] then local v = header[name] if type(v) == "table" then table.insert(v, value) else header[name] = { v , value } end else header[name] = value end end end return header end function M.recvchunkedbody(readbytes, bodylimit, header, body) local result = "" local size = 0 while true do local sz sz , body = chunksize(readbytes, body) if not sz then return end if sz == 0 then break end size = size + sz if bodylimit and size > bodylimit then return end if #body >= sz then result = result .. body:sub(1,sz) body = body:sub(sz+1) else result = result .. body .. readbytes(sz - #body) body = "" end body = readcrln(readbytes, body) if not body then return end end local tmpline = {} body = M.recvheader(readbytes, tmpline, body) if not body then return end header = M.parseheader(tmpline,1,header) return result, header end return M
mit