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
Mizugola/MeltingSaga
engine/Lib/Extlibs/pl/luabalanced.lua
8
7990
--- Extract delimited Lua sequences from strings. -- Inspired by Damian Conway's Text::Balanced in Perl. <br/> -- <ul> -- <li>[1] <a href="http://lua-users.org/wiki/LuaBalanced">Lua Wiki Page</a></li> -- <li>[2] http://search.cpan.org/dist/Text-Balanced/lib/Text/Balanced.pm</li> -- </ul> <br/> -- <pre class=example> -- local lb = require "pl.luabalanced" -- --Extract Lua expression starting at position 4. -- print(lb.match_expression("if x^2 + x > 5 then print(x) end", 4)) -- --> x^2 + x > 5 16 -- --Extract Lua string starting at (default) position 1. -- print(lb.match_string([["test\"123" .. "more"]])) -- --> "test\"123" 12 -- </pre> -- (c) 2008, David Manura, Licensed under the same terms as Lua (MIT license). -- @class module -- @name pl.luabalanced local M = {} local assert = assert -- map opening brace <-> closing brace. local ends = { ['('] = ')', ['{'] = '}', ['['] = ']' } local begins = {}; for k,v in pairs(ends) do begins[v] = k end -- Match Lua string in string <s> starting at position <pos>. -- Returns <string>, <posnew>, where <string> is the matched -- string (or nil on no match) and <posnew> is the character -- following the match (or <pos> on no match). -- Supports all Lua string syntax: "...", '...', [[...]], [=[...]=], etc. local function match_string(s, pos) pos = pos or 1 local posa = pos local c = s:sub(pos,pos) if c == '"' or c == "'" then pos = pos + 1 while 1 do pos = assert(s:find("[" .. c .. "\\]", pos), 'syntax error') if s:sub(pos,pos) == c then local part = s:sub(posa, pos) return part, pos + 1 else pos = pos + 2 end end else local sc = s:match("^%[(=*)%[", pos) if sc then local _; _, pos = s:find("%]" .. sc .. "%]", pos) assert(pos) local part = s:sub(posa, pos) return part, pos + 1 else return nil, pos end end end M.match_string = match_string -- Match bracketed Lua expression, e.g. "(...)", "{...}", "[...]", "[[...]]", -- [=[...]=], etc. -- Function interface is similar to match_string. local function match_bracketed(s, pos) pos = pos or 1 local posa = pos local ca = s:sub(pos,pos) if not ends[ca] then return nil, pos end local stack = {} while 1 do pos = s:find('[%(%{%[%)%}%]\"\']', pos) assert(pos, 'syntax error: unbalanced') local c = s:sub(pos,pos) if c == '"' or c == "'" then local part; part, pos = match_string(s, pos) assert(part) elseif ends[c] then -- open local mid, posb if c == '[' then mid, posb = s:match('^%[(=*)%[()', pos) end if mid then pos = s:match('%]' .. mid .. '%]()', posb) assert(pos, 'syntax error: long string not terminated') if #stack == 0 then local part = s:sub(posa, pos-1) return part, pos end else stack[#stack+1] = c pos = pos + 1 end else -- close assert(stack[#stack] == assert(begins[c]), 'syntax error: unbalanced') stack[#stack] = nil if #stack == 0 then local part = s:sub(posa, pos) return part, pos+1 end pos = pos + 1 end end end M.match_bracketed = match_bracketed -- Match Lua comment, e.g. "--...\n", "--[[...]]", "--[=[...]=]", etc. -- Function interface is similar to match_string. local function match_comment(s, pos) pos = pos or 1 if s:sub(pos, pos+1) ~= '--' then return nil, pos end pos = pos + 2 local partt, post = match_string(s, pos) if partt then return '--' .. partt, post end local part; part, pos = s:match('^([^\n]*\n?)()', pos) return '--' .. part, pos end -- Match Lua expression, e.g. "a + b * c[e]". -- Function interface is similar to match_string. local wordop = {['and']=true, ['or']=true, ['not']=true} local is_compare = {['>']=true, ['<']=true, ['~']=true} local function match_expression(s, pos) pos = pos or 1 local posa = pos local lastident local poscs, posce while pos do local c = s:sub(pos,pos) if c == '"' or c == "'" or c == '[' and s:find('^[=%[]', pos+1) then local part; part, pos = match_string(s, pos) assert(part, 'syntax error') elseif c == '-' and s:sub(pos+1,pos+1) == '-' then -- note: handle adjacent comments in loop to properly support -- backtracing (poscs/posce). poscs = pos while s:sub(pos,pos+1) == '--' do local part; part, pos = match_comment(s, pos) assert(part) pos = s:match('^%s*()', pos) posce = pos end elseif c == '(' or c == '{' or c == '[' then local part; part, pos = match_bracketed(s, pos) elseif c == '=' and s:sub(pos+1,pos+1) == '=' then pos = pos + 2 -- skip over two-char op containing '=' elseif c == '=' and is_compare[s:sub(pos-1,pos-1)] then pos = pos + 1 -- skip over two-char op containing '=' elseif c:match'^[%)%}%];,=]' then local part = s:sub(posa, pos-1) return part, pos elseif c:match'^[%w_]' then local newident,newpos = s:match('^([%w_]+)()', pos) if pos ~= posa and not wordop[newident] then -- non-first ident local pose = ((posce == pos) and poscs or pos) - 1 while s:match('^%s', pose) do pose = pose - 1 end local ce = s:sub(pose,pose) if ce:match'[%)%}\'\"%]]' or ce:match'[%w_]' and not wordop[lastident] then local part = s:sub(posa, pos-1) return part, pos end end lastident, pos = newident, newpos else pos = pos + 1 end pos = s:find('[%(%{%[%)%}%]\"\';,=%w_%-]', pos) end local part = s:sub(posa, #s) return part, #s+1 end M.match_expression = match_expression -- Match name list (zero or more names). E.g. "a,b,c" -- Function interface is similar to match_string, -- but returns array as match. local function match_namelist(s, pos) pos = pos or 1 local list = {} while 1 do local c = #list == 0 and '^' or '^%s*,%s*' local item, post = s:match(c .. '([%a_][%w_]*)%s*()', pos) if item then pos = post else break end list[#list+1] = item end return list, pos end M.match_namelist = match_namelist -- Match expression list (zero or more expressions). E.g. "a+b,b*c". -- Function interface is similar to match_string, -- but returns array as match. local function match_explist(s, pos) pos = pos or 1 local list = {} while 1 do if #list ~= 0 then local post = s:match('^%s*,%s*()', pos) if post then pos = post else break end end local item; item, pos = match_expression(s, pos) assert(item, 'syntax error') list[#list+1] = item end return list, pos end M.match_explist = match_explist -- Replace snippets of code in Lua code string <s> -- using replacement function f(u,sin) --> sout. -- <u> is the type of snippet ('c' = comment, 's' = string, -- 'e' = any other code). -- Snippet is replaced with <sout> (unless <sout> is nil or false, in -- which case the original snippet is kept) -- This is somewhat analogous to string.gsub . local function gsub(s, f) local pos = 1 local posa = 1 local sret = '' while 1 do pos = s:find('[%-\'\"%[]', pos) if not pos then break end if s:match('^%-%-', pos) then local exp = s:sub(posa, pos-1) if #exp > 0 then sret = sret .. (f('e', exp) or exp) end local comment; comment, pos = match_comment(s, pos) sret = sret .. (f('c', assert(comment)) or comment) posa = pos else local posb = s:find('^[\'\"%[]', pos) local str if posb then str, pos = match_string(s, posb) end if str then local exp = s:sub(posa, posb-1) if #exp > 0 then sret = sret .. (f('e', exp) or exp) end sret = sret .. (f('s', str) or str) posa = pos else pos = pos + 1 end end end local exp = s:sub(posa) if #exp > 0 then sret = sret .. (f('e', exp) or exp) end return sret end M.gsub = gsub return M
mit
jshackley/darkstar
scripts/globals/items/bowl_of_sutlac_+1.lua
36
1318
----------------------------------------- -- ID: 5578 -- Item: Bowl of Sutlac -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +10 -- MP +10 -- INT +2 -- MP Recovered while healing +2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5578); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 10); target:addMod(MOD_MP, 10); target:addMod(MOD_INT, 2); target:addMod(MOD_MPHEAL, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 10); target:delMod(MOD_MP, 10); target:delMod(MOD_INT, 2); target:delMod(MOD_MPHEAL, 2); end;
gpl-3.0
kidaa/turbo
turbo/platform.lua
11
1395
--- Turbo.lua C Platform / OS variables. -- -- Copyright 2014 John Abrahamsen -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local ffi = require "ffi" local uname = "" if not ffi.abi("win") then uname = (function() local f = io.popen("uname") local l = f:read("*a") f:close() return l end)() end return { __WINDOWS__ = ffi.abi("win"), __UNIX__ = uname:match("Unix") or uname:match("Linux") or uname:match("Darwin") and true or false, __LINUX__ = uname:match("Linux") and true or false, __DARWIN__ = uname:match("Darwin") and true or false, __ABI32__ = ffi.abi("32bit"), __ABI64__ = ffi.abi("64bit"), __X86__ = ffi.arch == "x86", __X64__ = ffi.arch == "x64", __PPC__ = ffi.arch == "ppc", __PPC64__ = ffi.arch == "ppc64le", __ARM__ = ffi.arch == "arm", __MIPSEL__ = ffi.arch == "mipsel", }
apache-2.0
josetaas/YokiRaidCursor
Tests/CursorTest.lua
1
1061
local Class = YokiRaidCursor.Class local Test = YokiRaidCursor.Testing.Test local CursorTest = Class('CursorTest', Test) function CursorTest:Initialize() Test:Register(CursorTest.Move_WithValidFrame_CentersOnFrame) Test:Register(CursorTest.Move_WithValidFrame_SetsTargetToFrame) end function CursorTest:Move_WithValidFrame_CentersOnFrame() local x, y, mockCursorFrame, mockFrame, cursor mockCursorFrame = Test:GetMock() mockFrame = Test:GetMock() cursor = YokiRaidCursor.Core.Cursor(mockCursorFrame) cursor:Move(mockFrame) Test:Verify(mockCursorFrame:ClearAllPoints()) Test:Verify(mockCursorFrame:SetPoint('TOPLEFT', mockFrame, 'CENTER', 0, 0)) end function CursorTest:Move_WithValidFrame_SetsTargetToFrame() local frame, mockCursorFrame, mockFrame, cursor mockCursorFrame = Test:GetMock() mockFrame = Test:GetMock() cursor = YokiRaidCursor.Core.Cursor(mockCursorFrame) cursor:Move(mockFrame) frame = cursor:GetTarget() Test:AssertEquals(mockFrame, frame) end local test = CursorTest()
mit
sugiartocokrowibowo/Algorithm-Implementations
Weighted_Random_Distribution/Lua/Yonaba/weighted_random.lua
27
1445
-- Weighted/Biased random distribution implementation -- See : http://codetheory.in/weighted-biased-random-number-generation-with-javascript-based-on-probability/ -- Note: The sum of weights should be 1. That is, all -- weights are decimal values lower than 1. -- Note: As all the implementations given below uses -- math.random, one can call math.randomseed with a -- custom seed before using them. -- items : an array-list of values -- weights : a map table holding the weight for each value in -- in the `items` list. -- returns : an iterator function local function expanding_random(items, weights) local list = {} for _, item in ipairs(items) do local n = weights[item] * 100 for i = 1, n do table.insert(list, item) end end return function() return list[math.random(1, #list)] end end -- items : an array-list of values -- weights : a map table holding the weight for each value in -- in the `items` list. -- returns : an iterator function local function in_place_random(items, weights) local partial_sums, partial_sum = {}, 0 for _, item in ipairs(items) do partial_sum = partial_sum + weights[item] table.insert(partial_sums, partial_sum) end return function() local n, s = math.random(), 0 for i, si in ipairs(partial_sums) do s = s + si if si > n then return items[i] end end end end return { expanding = expanding_random, in_place = in_place_random }
mit
jshackley/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/_1ee.lua
34
1045
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Door: Kokba Hostel -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --player:startEvent(0x0046); 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
KiloSierraCharlie/UsefulScripts
DarkRP/darkrpmodificationmaster/lua/darkrp_modules/propkillanouncer/sh_propkillanouncer.lua
2
1753
local killercolour = Color(255,0,0) // Prop killer's name color local victimcolour = Color(0,0,255) // Victim's name color local adminnoticeonly = true // Weather the notice should be admin only, or for everyone. local staffgroups = { "superadmin", "admin", "operator" } // ULX Group names, for those who should be notified if adminnoticeonly == false local possibleweapons = { "prop_physics", "prop_vehicle_jeep", "prop_vehicle_airboat" } // Allows for easier configuration, should another entity be considered a weapon, eg. Vehicles. function PlayerDeath( victim, inflictor, attacker ) if table.HasValue(possibleweapons, attacker:GetClass()) then // I'm a fan of table.HasValue - It is amazing. for k, ply in pairs( player.GetAll() ) do if( !adminnoticeonly )then // Since adminnoticeonly can only have 2 values, added a boolean, rather than integer value. ply:SendLua("chat.AddText("..victimcolour..", "..victim:Name()..", \" has been prop-killed by \", "..killercolour..", "..attacker:GetOwner():Name()..", \"(\", "..attacker:GetOwner():SteamID()..", \")\")")) // Added steam id, so players can be reported with screen shots easier. end if table.HasValue(staffgroups, ply:GetNWString("usergroup")) and adminnoticeonly then // Added a table.HasValue for easier configuration, and overall neater code. The "and adminnoticeonly" is to stop duplicate chat messages to admins. ply:SendLua("chat.AddText("..victimcolour..", "..victim:Name()..", \" has been prop-killed by \", "..killercolour..", "..attacker:GetOwner():Name()..", \"(\", "..attacker:GetOwner():SteamID()..", \")\")") // Added steam id, so console/admin can ban quicker, and more efficiently. end end end end hook.Add("PlayerDeath", "PropkillCheck", PlayerDeath)
unlicense
iofun/treehouse
luerl/0635ca2c31ba6fce9cb1008f846795a6.lua
1
2065
-- Our unit function table local this_unit = {} -- Where we are and fast we move local x, y, dx, dy -- Our name local name = "Protoss_Stargate" -- Our color local color = "yellow" -- Our BWAPI unit type local type = 167 -- Size of a clock tick msec local tick -- It's me, the unit structure local me = unit.self() -- The standard local variables local label = "large_structure" local armor = 1 local hitpoints,shield = 600,600 local ground_damage,air_damage = 0,0 local ground_cooldown,air_cooldown = 0,0 local ground_range,air_range = 0,0 local sight = 320 local supply = 0 local build_time = 1050 local build_score = 300 local destroy_score = 900 local mineral = 150 local gas = 150 local holdkey = "" -- The size of the region local xsize,ysize = region.size() -- The unit interface. function this_unit.start() end function this_unit.get_position() return x,y end function this_unit.set_position(a1, a2) x,y = a1,a2 end function this_unit.get_speed() return dx,dy end function this_unit.set_speed(a1, a2) dx,dy = a1,a2 end function this_unit.set_tick(a1) tick = a1 end local function move_xy_bounce(x, y, dx, dy, valid_x, valid_y) local nx = x + dx local ny = y + dy -- Bounce off the edge if (not valid_x(nx)) then nx = x - dx dx = -dx end -- Bounce off the edge if (not valid_y(ny)) then ny = y - dy dy = -dy end return nx, ny, dx, dy end local function move(x, y, dx, dy) local nx,ny,ndx,ndy = move_xy_bounce(x, y, dx, dy, region.valid_x, region.valid_y) -- Where we were and where we are now. local osx,osy = region.sector(x, y) local nsx,nsy = region.sector(nx, ny) if (osx ~= nsx or osy ~= nsy) then -- In new sector, move us to the right sector region.rem_sector(x, y) region.add_sector(nx, ny) end return nx,ny,ndx,ndy end function this_unit.tick() x,y,dx,dy = move(x, y, dx, dy) end function this_unit.attack() -- The unit has been zapped and will die region.rem_sector(x, y) end -- Return the unit table return this_unit
agpl-3.0
ByteFun/Starbound_mods
smount/tech/mech/mount91g.lua
1
38443
function checkCollision(position) local boundBox = mcontroller.boundBox() boundBox[1] = boundBox[1] - mcontroller.position()[1] + position[1] boundBox[2] = boundBox[2] - mcontroller.position()[2] + position[2] boundBox[3] = boundBox[3] - mcontroller.position()[1] + position[1] boundBox[4] = boundBox[4] - mcontroller.position()[2] + position[2] return not world.rectCollision(boundBox) end function randomProjectileLine(startPoint, endPoint, stepSize, projectile, chanceToSpawn) local dist = math.distance(startPoint, endPoint) local steps = math.floor(dist / stepSize) local normX = (endPoint[1] - startPoint[1]) / dist local normY = (endPoint[2] - startPoint[2]) / dist for i = 0, steps do local p1 = { normX * i * stepSize + startPoint[1], normY * i * stepSize + startPoint[2]} local p2 = { normX * (i + 1) * stepSize + startPoint[1] + math.random(-1, 1), normY * (i + 1) * stepSize + startPoint[2] + math.random(-1, 1)} if math.random() <= chanceToSpawn then world.spawnProjectile(projectile, math.midPoint(p1, p2), entity.id(), {normX, normY}, false) end end return endPoint end function blinkAdjust(position, doPathCheck, doCollisionCheck, doLiquidCheck, doStandCheck) local blinkCollisionCheckDiameter = tech.parameter("blinkCollisionCheckDiameter") local blinkVerticalGroundCheck = tech.parameter("blinkVerticalGroundCheck") local blinkFootOffset = tech.parameter("blinkFootOffset") local blinkHeadOffset = tech.parameter("blinkHeadOffset") if doPathCheck then local collisionBlocks = world.collisionBlocksAlongLine(mcontroller.position(), position, {"Null", "Block", "Dynamic"}, 1) if #collisionBlocks ~= 0 then local diff = world.distance(position, mcontroller.position()) diff[1] = diff[1] > 0 and 1 or -1 diff[2] = diff[2] > 0 and 1 or -1 position = {collisionBlocks[1][1] - math.min(diff[1], 0), collisionBlocks[1][2] - math.min(diff[2], 0)} end end if doCollisionCheck then local diff = world.distance(position, mcontroller.position()) local collisionPoly = mcontroller.collisionPoly() --Add foot offset if there is ground if diff[2] < 0 then local groundBlocks = world.collisionBlocksAlongLine(position, {position[1], position[2] + blinkFootOffset}, {"Null", "Block", "Dynamic"}, 1) if #groundBlocks > 0 then position[2] = groundBlocks[1][2] + 1 - blinkFootOffset end end --Add head offset if there is ceiling if diff[2] > 0 then local ceilingBlocks = world.collisionBlocksAlongLine(position, {position[1], position[2] + blinkHeadOffset}, {"Null", "Block", "Dynamic"}, 1) if #ceilingBlocks > 0 then position[2] = ceilingBlocks[1][2] - blinkHeadOffset end end --Resolve position position = world.resolvePolyCollision(collisionPoly, position, blinkCollisionCheckDiameter) if not position or world.lineTileCollision(mcontroller.position(), position, {"Null", "Block", "Dynamic"}) then return nil end end if doStandCheck then local groundFound = false for i = 1, blinkVerticalGroundCheck * 2 do local checkPosition = {position[1], position[2] - i / 2} if world.pointTileCollision(checkPosition, {"Null", "Block", "Dynamic", "Platform"}) then groundFound = true position = {checkPosition[1], checkPosition[2] + 0.5 - blinkFootOffset} break end end if not groundFound then return nil end end if doLiquidCheck and (world.liquidAt(position) or world.liquidAt({position[1], position[2] + blinkFootOffset})) then return nil end return position end function findRandomBlinkLocation(doCollisionCheck, doLiquidCheck, doStandCheck) local randomBlinkTries = tech.parameter("randomBlinkTries") local randomBlinkDiameter = tech.parameter("randomBlinkDiameter") for i=1,randomBlinkTries do local position = mcontroller.position() position[1] = position[1] + (math.random() * 2 - 1) * randomBlinkDiameter position[2] = position[2] + (math.random() * 2 - 1) * randomBlinkDiameter local position = blinkAdjust(position, false, doCollisionCheck, doLiquidCheck, doStandCheck) if position then return position end end return nil end function init() self.specialLast = false self.active = false self.fireTimer = 0 self.fireSecTimer = 0 tech.setVisible(false) tech.rotateGroup("guns", 0, true) self.multiJumps = 0 self.lastJump = false self.mode = "none" self.timer = 0 self.targetPosition = nil self.grabbed = false self.holdingJump = false self.ranOut = false self.airDashing = false self.dashTimer = 0 self.dashDirection = 0 self.dashLastInput = 0 self.dashTapLast = 0 self.dashTapTimer = 0 self.aoeLastInput = 0 self.aoeTapLast = 0 self.aoeTapTimer = 0 self.dashAttackfireTimer = 0 self.dashAttackTimer = 0 self.dashAttackDirection = 0 self.dashAttackLastInput = 0 self.dashAttackTapLast = 0 self.dashAttackTapTimer = 0 self.holdingUp = false self.holdingDown = false self.holdingLeft = false self.holdingRight = false self.speedMultiplier = 1.1 self.levitateActivated = false self.mechTimer = 0 self.chargePower = 0 self.chargeTimer = 0 self.chargeFireTimer = 0 self.chargeCharging = false self.chargeFiring = false self.chargeRecharging = false self.projectilesFired = 0 self.level = tech.parameter("mechLevel", 6) self.mechState = "off" self.mechStateTimer = 0 end function uninit() if self.active then local mechTransformPositionChange = tech.parameter("mechTransformPositionChange") mcontroller.translate({-mechTransformPositionChange[1], -mechTransformPositionChange[2]}) tech.setParentOffset({0, 0}) tech.setParentDirectives() self.active = false tech.setVisible(false) tech.setParentState() tech.setToolUsageSuppressed(false) mcontroller.controlFace(nil) end end function input(args) if self.dashTimer > 0 then return nil end local maximumDoubleTapTime = tech.parameter("maximumDoubleTapTime") if self.dashTapTimer > 0 then self.dashTapTimer = self.dashTapTimer - args.dt end if args.moves["right"] and self.active then if self.dashLastInput ~= 1 then if self.dashTapLast == 1 and self.dashTapTimer > 0 then self.dashTapLast = 0 self.dashTapTimer = 0 return "dashRight" else self.dashTapLast = 1 self.dashTapTimer = maximumDoubleTapTime end end self.dashLastInput = 1 elseif args.moves["left"] and self.active then if self.dashLastInput ~= -1 then if self.dashTapLast == -1 and self.dashTapTimer > 0 then self.dashTapLast = 0 self.dashTapTimer = 0 return "dashLeft" else self.dashTapLast = -1 self.dashTapTimer = maximumDoubleTapTime end end self.dashLastInput = -1 else self.dashLastInput = 0 end ------------------------ local maximumDoubleTapTime2 = tech.parameter("maximumDoubleTapTime2") if self.aoeTapTimer > 0 then self.aoeTapTimer = self.aoeTapTimer - args.dt end if args.moves[""] and self.active then if self.aoeLastInput ~= 1 then if self.aoeTapLast == 1 and self.aoeTapTimer > 0 then self.aoeTapLast = 0 self.aoeTapTimer = 0 return "mechSecFire" else self.aoeTapLast = 1 self.aoeTapTimer = maximumDoubleTapTime2 end end self.aoeLastInput = 1 else self.aoeLastInput = 0 end if args.moves[""] and tech.jumping() then self.holdingJump = true elseif not args.moves[""] then self.holdingJump = false end if args.moves["special"] == 1 and not self.specialLast then if self.active then return "mechDeactivate" else return "mechActivate" end elseif args.moves[""] == 2 and self.active then return "blink" elseif args.moves[""] and args.moves[""] and args.moves[""] and not self.levitateActivated and self.active then return "grab" elseif args.moves["down"] and args.moves["right"] and not self.levitateActivated and self.active then return "dashAttackRight" elseif args.moves["down"] and args.moves["left"] and not self.levitateActivated and self.active then return "dashAttackLeft" elseif args.moves["primaryFire"] and args.moves["altFire"] and self.active then return "mechMineFire" elseif args.moves["primaryFire"] and self.active then return "mechFire" elseif args.moves["altFire"] and self.active then return "mechAltFire" elseif args.moves[""] and args.moves[""] and self.active then return "mechSecFire" elseif args.moves[""] and not tech.canJump() and not self.holdingJump and self.active then return "jetpack" elseif args.moves["jump"] and not mcontroller.jumping() and not mcontroller.canJump() and not self.lastJump then self.lastJump = true return "multiJump" else self.lastJump = args.moves["jump"] end self.specialLast = args.moves["special"] == 1 -- RedOrb if args.moves["left"] then self.holdingLeft = true elseif not args.moves["left"] then self.holdingLeft = false end if args.moves["right"] then self.holdingRight = true elseif not args.moves["right"] then self.holdingRight = false end if args.moves["up"] then self.holdingUp = true elseif not args.moves["up"] then self.holdingUp = false end if args.moves["down"] then self.holdingDown = true elseif not args.moves["down"] then self.holdingDown = false end if not args.moves["jump"] and not args.moves["left"] and not args.moves["right"] and not args.moves["up"] and not args.moves["down"] and (not mcontroller.canJump() or mcontroller.liquidMovement()) and not self.holdingJump and self.levitateActivated then return "levitatehover" elseif args.moves[""] and args.moves[""] then return "levitate" elseif args.moves["left"] and args.moves["right"] and (not mcontroller.canJump() or mcontroller.liquidMovement()) and self.levitateActivated then return "levitatehover" elseif args.moves["up"] and args.moves["down"] and (not mcontroller.canJump() or mcontroller.liquidMovement()) and self.levitateActivated then return "levitatehover" elseif (args.moves["jump"] or args.moves["up"]) and args.moves["left"] and (not mcontroller.canJump() or mcontroller.liquidMovement()) and not self.holdingRight and self.levitateActivated then return "levitateleftup" elseif (args.moves["jump"] or args.moves["up"]) and args.moves["right"] and (not mcontroller.canJump() or mcontroller.liquidMovement()) and not self.holdingLeft and self.levitateActivated then return "levitaterightup" elseif args.moves["down"] and args.moves["left"] and (not mcontroller.canJump() or mcontroller.liquidMovement()) and not self.holdingRight and self.levitateActivated then return "levitateleftdown" elseif args.moves["down"] and args.moves["right"] and (not mcontroller.canJump() or mcontroller.liquidMovement()) and not self.holdingLeft and self.levitateActivated then return "levitaterightdown" elseif args.moves["left"] and (not mcontroller.canJump() or mcontroller.liquidMovement()) and not self.holdingRight and self.levitateActivated then return "levitateleft" elseif args.moves["right"] and (not mcontroller.canJump() or mcontroller.liquidMovement()) and not self.holdingLeft and self.levitateActivated then return "levitateright" elseif args.moves["up"] and (not mcontroller.canJump() or mcontroller.liquidMovement()) and not self.holdingDown and self.levitateActivated then return "levitateup" elseif args.moves["down"] and (not mcontroller.canJump() or mcontroller.liquidMovement()) and not self.holdingUp and self.levitateActivated then return "levitatedown" else return nil end -- RedOrb End end function update(args) tech.burstParticleEmitter("glowParticles") if self.mechTimer > 0 then self.mechTimer = self.mechTimer - args.dt end local dashControlForce = tech.parameter("dashControlForce") local dashSpeed = tech.parameter("dashSpeed") local dashDuration = tech.parameter("dashDuration") local energyUsageDash = tech.parameter("energyUsageDash") local usedEnergy = 0 if args.actions["dashRight"] and self.dashTimer <= 0 and status.resource("energy") > energyUsageDash then self.dashTimer = dashDuration self.dashDirection = 1 usedEnergy = energyUsageDash self.airDashing = not mcontroller.onGround() return tech.consumeTechEnergy(energyUsageDash) elseif args.actions["dashLeft"] and self.dashTimer <= 0 and status.resource("energy") > energyUsageDash then self.dashTimer = dashDuration self.dashDirection = -1 usedEnergy = energyUsageDash self.airDashing = not mcontroller.onGround() return tech.consumeTechEnergy(energyUsageDash) end if self.dashTimer > 0 then mcontroller.controlApproachXVelocity(dashSpeed * self.dashDirection, dashControlForce, true) if self.airDashing then mcontroller.controlParameters({gravityEnabled = false}) mcontroller.controlApproachYVelocity(0, dashControlForce, true) end if self.dashDirection == -1 then mcontroller.controlFace(-1) tech.setFlipped(true) else mcontroller.controlFace(1) tech.setFlipped(false) end tech.setAnimationState("dashing", "on") tech.setParticleEmitterActive("dashParticles", true) self.dashTimer = self.dashTimer - args.dt else tech.setAnimationState("dashing", "off") tech.setParticleEmitterActive("dashParticles", false) end local dashAttackControlForce = tech.parameter("dashAttackControlForce") local dashAttackSpeed = tech.parameter("dashAttackSpeed") local dashAttackDuration = tech.parameter("dashAttackDuration") local energyUsageDashAttack = tech.parameter("energyUsageDashAttack") local diffDash = world.distance(tech.aimPosition(), mcontroller.position()) local aimAngleDash = math.atan(diffDash[2], diffDash[1]) local mechDashFireCycle = tech.parameter("mechDashFireCycle") local mechDashProjectile = tech.parameter("mechDashProjectile") local mechDashProjectileConfig = tech.parameter("mechDashProjectileConfig") local flipDash = aimAngleDash > math.pi / 2 or aimAngleDash < -math.pi / 2 if flipDash then tech.setFlipped(false) mcontroller.controlFace(-1) self.dashAttackDirection = -1 else tech.setFlipped(true) mcontroller.controlFace(1) self.dashAttackDirection = 1 end if status.resource("energy") > energyUsageDashAttack and args.actions["dashAttackLeft"] or args.actions["dashAttackRight"] then if self.dashAttackTimer <= 0 then world.spawnProjectile(mechDashProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontDashGun", "firePoint")), entity.id(), {math.cos(aimAngleDash), math.sin(aimAngleDash)}, false, mechDashProjectileConfig) self.dashAttackTimer = self.dashAttackTimer + mechDashFireCycle else self.dashAttackTimer = self.dashAttackTimer - args.dt end mcontroller.controlApproachXVelocity(dashAttackSpeed * self.dashAttackDirection, dashAttackControlForce, true) tech.setAnimationState("dashingAttack", "on") tech.setParticleEmitterActive("dashAttackParticles", true) else tech.setAnimationState("dashingAttack", "off") tech.setParticleEmitterActive("dashAttackParticles", false) end local energyUsageBlink = tech.parameter("energyUsageBlink") local blinkMode = tech.parameter("blinkMode") local blinkOutTime = tech.parameter("blinkOutTime") local blinkInTime = tech.parameter("blinkInTime") if args.actions["blink"] and self.mode == "none" and status.resource("energy") > energyUsageBlink then local blinkPosition = nil if blinkMode == "random" then local randomBlinkAvoidCollision = tech.parameter("randomBlinkAvoidCollision") local randomBlinkAvoidMidair = tech.parameter("randomBlinkAvoidMidair") local randomBlinkAvoidLiquid = tech.parameter("randomBlinkAvoidLiquid") blinkPosition = findRandomBlinkLocation(randomBlinkAvoidCollision, randomBlinkAvoidMidair, randomBlinkAvoidLiquid) or findRandomBlinkLocation(randomBlinkAvoidCollision, randomBlinkAvoidMidair, false) or findRandomBlinkLocation(randomBlinkAvoidCollision, false, false) elseif blinkMode == "cursor" then blinkPosition = blinkAdjust(tech.aimPosition(), true, true, false, false) elseif blinkMode == "cursorPenetrate" then blinkPosition = blinkAdjust(tech.aimPosition(), false, true, false, false) end if blinkPosition then self.targetPosition = blinkPosition self.mode = "start" else -- Make some kind of error noise end end if self.mode == "start" then mcontroller.setVelocity({0, 0}) self.mode = "out" self.timer = 0 return tech.consumeTechEnergy(energyUsageBlink) elseif self.mode == "out" then tech.setParentDirectives("?multiply=00000000") tech.setAnimationState("blinking", "out") mcontroller.setVelocity({0, 0}) self.timer = self.timer + args.dt if self.timer > blinkOutTime then mcontroller.setPosition(self.targetPosition) self.mode = "in" self.timer = 0 end return 0 elseif self.mode == "in" then tech.setParentDirectives("?multiply=00000000") tech.setAnimationState("blinking", "in") mcontroller.setVelocity({0, 0}) self.timer = self.timer + args.dt if self.timer > blinkInTime then self.mode = "none" end return 0 end local energyUsageJump = tech.parameter("energyUsageJump") local multiJumpCount = tech.parameter("multiJumpCount") if args.actions["multiJump"] and self.multiJumps < multiJumpCount and status.resource("energy") > energyUsageJump then mcontroller.controlJump(true) self.multiJumps = self.multiJumps + 1 tech.burstParticleEmitter("multiJumpParticles") tech.playSound("sound") return tech.consumeTechEnergy(energyUsageJump) else if mcontroller.onGround() or mcontroller.liquidMovement() then self.multiJumps = 0 end end local energyCostPerSecond = tech.parameter("energyCostPerSecond") local energyCostPerSecondPrim = tech.parameter("energyCostPerSecondPrim") local energyCostPerSecondSec = tech.parameter("energyCostPerSecondSec") local energyCostPerSecondAlt = tech.parameter("energyCostPerSecondAlt") local mechCustomMovementParameters = tech.parameter("mechCustomMovementParameters") local mechTransformPositionChange = tech.parameter("mechTransformPositionChange") local parentOffset = tech.parameter("parentOffset") local mechCollisionTest = tech.parameter("mechCollisionTest") local mechAimLimit = tech.parameter("mechAimLimit") * math.pi / 180 local mechFrontRotationPoint = tech.parameter("mechFrontRotationPoint") local mechFrontFirePosition = tech.parameter("mechFrontFirePosition") local mechBackRotationPoint = tech.parameter("mechBackRotationPoint") local mechBackFirePosition = tech.parameter("mechBackFirePosition") local mechFireCycle = tech.parameter("mechFireCycle") local mechProjectile = tech.parameter("mechProjectile") local mechProjectileConfig = tech.parameter("mechProjectileConfig") local mechAltFireCycle = tech.parameter("mechAltFireCycle") local mechAltProjectile = tech.parameter("mechAltProjectile") local mechAltProjectile2 = tech.parameter("mechAltProjectile2") local mechAltProjectile3 = tech.parameter("mechAltProjectile3") local mechAltProjectile4 = tech.parameter("mechAltProjectile4") local mechAltProjectileConfig = tech.parameter("mechAltProjectileConfig") local mechSecFireCycle = tech.parameter("mechSecFireCycle") local mechSecProjectile = tech.parameter("mechSecProjectile") local mechSecProjectileConfig = tech.parameter("mechSecProjectileConfig") local mechGunBeamMaxRange = tech.parameter("mechGunBeamMaxRange") local mechGunBeamStep = tech.parameter("mechGunBeamStep") local mechGunBeamSmokeProkectile = tech.parameter("mechGunBeamSmokeProkectile") local mechGunBeamEndProjectile = tech.parameter("mechGunBeamEndProjectile") local mechGunBeamUpdateTime = tech.parameter("mechGunBeamUpdateTime") local mechTransform = tech.parameter("mechTransform") local mechMineFireCycle = tech.parameter("mechMineFireCycle") local mechMineDistance = tech.parameter("mechMineDistance") local mechMineEnergy = tech.parameter("mechMineEnergy") local chargingSound = tech.parameter("chargingSound") local chargeFireSound = tech.parameter("chargeFireSound") local primaryFireSound = tech.parameter("primaryFireSound") local aoeFireSound = tech.parameter("aoeFireSound") local mechActiveSide = nil if tech.setFlipped(true) then mechActiveSide = "left" elseif tech.setFlipped(false) then mechActiveSide = "right" end local mechStartupTime = tech.parameter("mechStartupTime") local mechShutdownTime = tech.parameter("mechShutdownTime") if not self.active and args.actions["mechActivate"] and self.mechState == "off" then mechCollisionTest[1] = mechCollisionTest[1] + mcontroller.position()[1] mechCollisionTest[2] = mechCollisionTest[2] + mcontroller.position()[2] mechCollisionTest[3] = mechCollisionTest[3] + mcontroller.position()[1] mechCollisionTest[4] = mechCollisionTest[4] + mcontroller.position()[2] if not world.rectCollision(mechCollisionTest) then tech.burstParticleEmitter("mechActivateParticles") mcontroller.translate(mechTransformPositionChange) tech.setVisible(true) tech.setAnimationState("transform", "in") -- status.modifyResource("health", status.stat("maxHealth") / 20) tech.setParentState("sit") tech.setToolUsageSuppressed(true) self.mechState = "turningOn" self.mechStateTimer = mechStartupTime self.active = true else -- Make some kind of error noise end elseif self.mechState == "turningOn" and self.mechStateTimer <= 0 then tech.setParentDirectives("?multiply=00000000") self.mechState = "on" self.mechStateTimer = 0 elseif (self.active and (args.actions["mechDeactivate"] and self.mechState == "on" or (energyCostPerSecond * args.dt > status.resource("energy")) and self.mechState == "on")) then self.mechState = "turningOff" tech.setAnimationState("transform", "out") self.mechStateTimer = mechShutdownTime elseif self.mechState == "turningOff" and self.mechStateTimer <= 0 then tech.burstParticleEmitter("mechDeactivateParticles") mcontroller.translate({-mechTransformPositionChange[1], -mechTransformPositionChange[2]}) tech.setVisible(false) tech.setParentState() tech.setToolUsageSuppressed(false) tech.setParentOffset({0, 0}) self.mechState = "off" tech.setParentDirectives() self.mechStateTimer = 0 self.active = false end mcontroller.controlFace(nil) if self.mechStateTimer > 0 then self.mechStateTimer = self.mechStateTimer - args.dt end if self.mechState == "on" then --effect.addStatModifierGroup({{stat = "invisible", amount = 1}}) end if self.active then local diff = world.distance(tech.aimPosition(), mcontroller.position()) local aimAngle = math.atan(diff[2], diff[1]) local flip = aimAngle > math.pi / 2 or aimAngle < -math.pi / 2 mcontroller.controlParameters(mechCustomMovementParameters) if flip then tech.setFlipped(false) local nudge = tech.transformedPosition({0, 0}) tech.setParentOffset({-parentOffset[1] - nudge[1], parentOffset[2] + nudge[2] - 0.125}) mcontroller.controlFace(-1) if aimAngle > 0 then aimAngle = math.max(aimAngle, math.pi - mechAimLimit) else aimAngle = math.min(aimAngle, -math.pi + mechAimLimit) end tech.rotateGroup("guns", math.pi + aimAngle) else tech.setFlipped(true) local nudge = tech.transformedPosition({0, 0}) tech.setParentOffset({parentOffset[1] + nudge[1], parentOffset[2] + nudge[2] - 0.125}) mcontroller.controlFace(1) if aimAngle > 0 then aimAngle = math.min(aimAngle, mechAimLimit) else aimAngle = math.max(aimAngle, -mechAimLimit) end tech.rotateGroup("guns", -aimAngle) end if not mcontroller.onGround() then if mcontroller.velocity()[2] > 0 then if args.actions["mechFire"] then tech.setAnimationState("movement", "jumpAttack") elseif args.actions["mechAltFire"] then tech.setAnimationState("movement", "jumpAttack") elseif args.actions["mechSecFire"] then tech.setAnimationState("movement", "jumpAttack") elseif args.actions["mechMineFire"] then tech.setAnimationState("movement", "mine") else tech.setAnimationState("movement", "jump") end else if args.actions["mechFire"] then tech.setAnimationState("movement", "fallAttack") elseif args.actions["mechAltFire"] then tech.setAnimationState("movement", "fallAttack") elseif args.actions["mechSecFire"] then tech.setAnimationState("movement", "fallAttack") elseif args.actions["mechMineFire"] then tech.setAnimationState("movement", "mine") else tech.setAnimationState("movement", "fall") end end elseif mcontroller.walking() or mcontroller.running() then if flip and mcontroller.movingDirection() == 1 or not flip and mcontroller.movingDirection() == -1 then if args.actions["mechFire"] then tech.setAnimationState("movement", "backWalkAttack") elseif args.actions["mechAltFire"] then tech.setAnimationState("movement", "backWalkAttack") elseif args.actions["mechSecFire"] then tech.setAnimationState("movement", "backWalkAttack") elseif args.actions["mechMineFire"] then tech.setAnimationState("movement", "mine") elseif args.actions["dashAttackRight"] then tech.setAnimationState("movement", "backWalkDash") elseif args.actions["dashAttackLeft"] then tech.setAnimationState("movement", "backWalkDash") else tech.setAnimationState("movement", "backWalk") end else if args.actions["mechFire"] then tech.setAnimationState("movement", "walkAttack") elseif args.actions["mechAltFire"] then tech.setAnimationState("movement", "walkAttack") elseif args.actions["mechSecFire"] then tech.setAnimationState("movement", "walkAttack") elseif args.actions["mechMineFire"] then tech.setAnimationState("movement", "mine") elseif args.actions["dashAttackRight"] then tech.setAnimationState("movement", "walkDash") elseif args.actions["dashAttackLeft"] then tech.setAnimationState("movement", "walkDash") else tech.setAnimationState("movement", "walk") end end else if args.actions["mechFire"] then tech.setAnimationState("movement", "idleAttack") elseif args.actions["mechAltFire"] then tech.setAnimationState("movement", "idleAttack") elseif args.actions["mechSecFire"] then tech.setAnimationState("movement", "idleAttack") elseif args.actions["mechMineFire"] then tech.setAnimationState("movement", "mine") else tech.setAnimationState("movement", "idle") end end if args.actions["mechFire"] and status.resource("energy") > energyCostPerSecondPrim then if self.fireTimer <= 0 then world.spawnProjectile(mechProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontGun", "firePoint")), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechProjectileConfig) tech.playSound("primaryFireSound") self.fireTimer = self.fireTimer + mechFireCycle tech.setAnimationState("frontFiring", "fire") else local oldFireTimer = self.fireTimer self.fireTimer = self.fireTimer - args.dt if oldFireTimer > mechFireCycle / 2 and self.fireTimer <= mechFireCycle / 2 then end end return tech.consumeTechEnergy(energyCostPerSecondPrim) end if not args.actions["mechFire"] then end --Charged Fire local mechChargeIncrement = tech.parameter("mechChargeIncrement") local energyCostPerCharge = tech.parameter("energyCostPerCharge") local mechChargeTime = tech.parameter("mechChargeTime") local mechChargeRatio = tech.parameter("mechChargeRatio") if args.actions["mechAltFire"] and not self.chargeFiring and not self.chargeRecharging then if not self.chargeCharging then if status.resource("energy") > energyCostPerCharge then self.chargeCharging = true self.chargePower = 1 tech.playSound("chargingSound") self.chargeTimer = mechChargeIncrement end elseif self.chargeTimer > 0 then self.chargeTimer = self.chargeTimer - args.dt elseif self.chargeTimer <= 0 and self.chargePower < 4 and status.resource("energy") > energyCostPerCharge then self.chargePower = self.chargePower + 1 tech.playSound("chargingSound") self.chargeTimer = mechChargeIncrement end if self.chargePower == 1 then tech.setAnimationState("frontAltFiring", "fireAlt") elseif self.chargePower == 2 then tech.setAnimationState("frontAltFiring", "fireAlt2") elseif self.chargePower == 3 then tech.setAnimationState("frontAltFiring", "fireAlt3") elseif self.chargePower == 4 then tech.setAnimationState("frontAltFiring", "fireAlt4") end elseif self.chargeCharging and not args.actions["mechAltFire"] and not self.chargeRecharging then self.chargeFireTimer = mechChargeTime * ( 1 + self.chargePower * mechChargeRatio ) self.chargeCharging = false self.chargeFiring = true elseif self.chargeFiring and self.chargeFireTimer > 0 and not self.chargeRecharging then self.chargeFireTimer = self.chargeFireTimer - args.dt if self.chargePower == 1 and status.resource("energy") > energyCostPerCharge * 1 then ---------------------------------------------- self.projectilesFired = 1 world.spawnProjectile(mechAltProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontAltGun", "firePoint")), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechAltProjectileConfig) tech.playSound("chargeFireSound") self.chargeRecharging = true ---------------------------------------------- elseif self.chargePower == 2 and status.resource("energy") > energyCostPerCharge * 2 then ---------------------------------------------- self.projectilesFired = 2 world.spawnProjectile(mechAltProjectile2, vec2.add(mcontroller.position(), tech.partPoint("frontAltGun", "firePoint")), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechAltProjectileConfig) tech.playSound("chargeFireSound") self.chargeRecharging = true ---------------------------------------------- elseif self.chargePower == 3 and status.resource("energy") > energyCostPerCharge * 3 then ---------------------------------------------- self.projectilesFired = 3 world.spawnProjectile(mechAltProjectile3, vec2.add(mcontroller.position(), tech.partPoint("frontAltGun", "firePoint")), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechAltProjectileConfig) tech.playSound("chargeFireSound") self.chargeRecharging = true ---------------------------------------------- elseif self.chargePower == 4 and status.resource("energy") > energyCostPerCharge * 4 then ---------------------------------------------- self.projectilesFired = 4 world.spawnProjectile(mechAltProjectile4, vec2.add(mcontroller.position(), tech.partPoint("frontAltGun", "firePoint")), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechAltProjectileConfig) tech.playSound("chargeFireSound") self.chargeRecharging = true ---------------------------------------------- end elseif self.chargeFiring and self.chargeFireTimer <= 0 and not self.chargeRecharging then self.chargeFiring = false self.chargeRecharging = true elseif self.chargeRecharging and self.chargeFireTimer > 0 then self.chargeFireTimer = self.chargeFireTimer - args.dt elseif self.chargeRecharging and self.chargeFireTimer <= 0 then self.chargePower = 0 self.chargeFireTimer = 0 self.chargeCharging = false self.chargeTimer = 0 self.chargeFiring = false self.chargeRecharging = false return tech.consumeTechEnergy(energyCostPerCharge * self.projectilesFired) end --Charged Fire End -- if args.actions["mechAltFire"] and args.availableEnergy > energyCostPerSecondAlt then -- if self.fireTimer <= 0 then -- world.spawnProjectile(mechAltProjectile, tech.partPoint("frontDashGun", "frontAltGunFirePoint"), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechAltProjectileConfig) -- self.fireTimer = self.fireTimer + mechAltFireCycle -- tech.setAnimationState("frontAltFiring", "fireAlt") -- else -- local oldFireTimer = self.fireTimer -- self.fireTimer = self.fireTimer - args.dt -- if oldFireTimer > mechAltFireCycle / 2 and self.fireTimer <= mechAltFireCycle / 2 then -- end -- end -- return tech.consumeTechEnergy(energyCostPerSecondAlt) -- end if args.actions["mechSecFire"] and status.resource("energy") > energyCostPerSecondSec then world.spawnProjectile(mechSecProjectile, vec2.add(mcontroller.position(), tech.partPoint("frontSecGun", "firePoint")), entity.id(), {math.cos(aimAngle), math.sin(aimAngle)}, false, mechAltProjectileConfig) tech.playSound("aoeFireSound") tech.setAnimationState("frontSecFiring", "fireSec") return tech.consumeTechEnergy(energyCostPerSecondSec) end if args.actions["mechMineFire"] then if self.fireTimer <= 0 and mechMineEnergy <= status.resource("energy") then if math.abs(world.distance(tech.aimPosition(),mcontroller.position())[1]) <= mechMineDistance then local x,y = tech.aimPosition()[1],tech.aimPosition()[2] local tilelist = {{x-1,y+2},{x,y+2},{x+1,y+2},{x-1,y-2},{x,y-2},{x+1,y-2}} for i = 1,5 do table.insert(tilelist,{x-3+i,y-1}) table.insert(tilelist,{x-3+i,y}) table.insert(tilelist,{x-3+i,y+1}) end world.damageTiles(tilelist, "foreground", mcontroller.position(), "blockish", 3.4) self.fireTimer = self.fireTimer + mechMineFireCycle end else self.fireTimer = self.fireTimer - args.dt end end local levitateSpeed = tech.parameter("levitateSpeed") local levitateControlForce = tech.parameter("levitateControlForce") local energyUsagePerSecondLevitate = tech.parameter("energyUsagePerSecondLevitate") local energyUsagelevitate = energyUsagePerSecondLevitate * args.dt if status.resource("energy") < energyUsagelevitate then self.ranOut = true elseif mcontroller.onGround() or mcontroller.liquidMovement() then self.ranOut = false end if args.actions["levitate"] and not self.ranOut then tech.setAnimationState("levitate", "on") mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true) self.levitateActivated = true return tech.consumeTechEnergy(energyUsagelevitate) elseif args.actions["levitatehover"] and not self.ranOut then tech.setAnimationState("levitate", "on") mcontroller.controlApproachYVelocity(0, levitateControlForce, true) mcontroller.controlApproachXVelocity(0, levitateControlForce, true) return tech.consumeTechEnergy(energyUsagelevitate) elseif args.actions["levitateleft"] and not self.ranOut then tech.setAnimationState("levitate", "on") mcontroller.controlApproachYVelocity(0, levitateControlForce, true) mcontroller.controlApproachXVelocity(-(levitateSpeed*self.speedMultiplier), levitateControlForce, true) return tech.consumeTechEnergy(energyUsagelevitate) elseif args.actions["levitateleftup"] and not self.ranOut then tech.setAnimationState("levitate", "on") mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true) mcontroller.controlApproachXVelocity(-(levitateSpeed*self.speedMultiplier), levitateControlForce, true) return tech.consumeTechEnergy(energyUsagelevitate) elseif args.actions["levitateleftdown"] and not self.ranOut then tech.setAnimationState("levitate", "on") mcontroller.controlApproachYVelocity(-(levitateSpeed)*0.5, levitateControlForce, true) mcontroller.controlApproachXVelocity(-(levitateSpeed*self.speedMultiplier), levitateControlForce, true) return tech.consumeTechEnergy(energyUsagelevitate) elseif args.actions["levitateright"] and not self.ranOut then tech.setAnimationState("levitate", "on") mcontroller.controlApproachYVelocity(0, levitateControlForce, true) mcontroller.controlApproachXVelocity(levitateSpeed*self.speedMultiplier, levitateControlForce, true) return tech.consumeTechEnergy(energyUsagelevitate) elseif args.actions["levitaterightup"] and not self.ranOut then tech.setAnimationState("levitate", "on") mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true) mcontroller.controlApproachXVelocity(levitateSpeed*self.speedMultiplier, levitateControlForce, true) return tech.consumeTechEnergy(energyUsagelevitate) elseif args.actions["levitaterightdown"] and not self.ranOut then tech.setAnimationState("levitate", "on") mcontroller.controlApproachYVelocity(-(levitateSpeed)*0.5, levitateControlForce, true) mcontroller.controlApproachXVelocity(levitateSpeed*self.speedMultiplier, levitateControlForce, true) return tech.consumeTechEnergy(energyUsagelevitate) elseif args.actions["levitateup"] and not self.ranOut then tech.setAnimationState("levitate", "on") mcontroller.controlApproachYVelocity(levitateSpeed, levitateControlForce, true) mcontroller.controlApproachXVelocity(0, levitateControlForce, true) return tech.consumeTechEnergy(energyUsagelevitate) elseif args.actions["levitatedown"] and not self.ranOut then tech.setAnimationState("levitate", "on") mcontroller.controlApproachYVelocity(-(levitateSpeed)*0.5, levitateControlForce, true) mcontroller.controlApproachXVelocity(0, levitateControlForce, true) return tech.consumeTechEnergy(energyUsagelevitate) else self.levitateActivated = false tech.setAnimationState("levitate", "off") return 0 end --return energyCostPerSecond * args.dt end return 0 end
gpl-2.0
VincentGong/chess
cocos2d-x/cocos/scripting/lua-bindings/auto/api/PhysicsJointRatchet.lua
6
1308
-------------------------------- -- @module PhysicsJointRatchet -- @extend PhysicsJoint -------------------------------- -- @function [parent=#PhysicsJointRatchet] getAngle -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#PhysicsJointRatchet] setAngle -- @param self -- @param #float float -------------------------------- -- @function [parent=#PhysicsJointRatchet] setPhase -- @param self -- @param #float float -------------------------------- -- @function [parent=#PhysicsJointRatchet] getPhase -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#PhysicsJointRatchet] setRatchet -- @param self -- @param #float float -------------------------------- -- @function [parent=#PhysicsJointRatchet] getRatchet -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#PhysicsJointRatchet] construct -- @param self -- @param #cc.PhysicsBody physicsbody -- @param #cc.PhysicsBody physicsbody -- @param #float float -- @param #float float -- @return PhysicsJointRatchet#PhysicsJointRatchet ret (return value: cc.PhysicsJointRatchet) return nil
mit
jshackley/darkstar
scripts/zones/Western_Altepa_Desert/TextIDs.lua
15
1562
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory. FULL_INVENTORY_AFTER_TRADE = 6383; -- You cannot obtain the <item>. Try trading again after sorting your inventory. ITEM_OBTAINED = 6384; -- Obtained: <item>. GIL_OBTAINED = 6385; -- Obtained <number> gil. KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>. ITEMS_OBTAINED = 6393; -- You obtain <param2 number> <param1 item>! NOTHING_OUT_OF_ORDINARY = 6398; -- There is nothing out of the ordinary here. FISHING_MESSAGE_OFFSET = 7204; -- You can't fish here. -- ZM4 dialog CANNOT_REMOVE_FRAG = 7336; -- It is an oddly shaped stone monument. A shining stone is embedded in it, but cannot be removed... ALREADY_OBTAINED_FRAG = 7337; -- You have already obtained this monument's ALREADY_HAVE_ALL_FRAGS = 7338; -- You have obtained all of the fragments. You must hurry to the ruins of the ancient shrine! FOUND_ALL_FRAGS = 7339; -- You now have all 8 fragments of light! ZILART_MONUMENT = 7340; -- It is an ancient Zilart monument. -- Other dialog THE_DOOR_IS_LOCKED = 7319; -- The door is locked. DOES_NOT_RESPOND = 7320; -- It does not respond. -- conquest Base CONQUEST_BASE = 7045; -- Tallying conquest results... --chocobo digging DIG_THROW_AWAY = 7217; -- You dig up$, but your inventory is full. You regretfully throw the # away. FIND_NOTHING = 7219; -- You dig and you dig, but find nothing.
gpl-3.0
jshackley/darkstar
scripts/zones/Lower_Jeuno/npcs/Naruru.lua
17
3726
----------------------------------- -- Area: Lower Jeuno -- NPC: Naruru -- Starts and Finishes Quests: Cook's Pride -- @pos -56 0.1 -138 245 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local TheWonderMagicSet = player:getQuestStatus(JEUNO,THE_WONDER_MAGIC_SET); local CooksPride = player:getQuestStatus(JEUNO,COOK_S_PRIDE); local TheKindCardian = player:getQuestStatus(JEUNO,THE_KIND_CARDIAN); local WildcatJeuno = player:getVar("WildcatJeuno"); if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,13) == false) then player:startEvent(10053); elseif (TheWonderMagicSet == QUEST_COMPLETED and CooksPride == QUEST_AVAILABLE) then if (player:getVar("CooksPrideVar") == 0) then player:startEvent(0x00BD); -- Start quest "Cook's pride" Long CS else player:startEvent(0x00BC); -- Start quest "Cook's pride" Short CS end elseif (CooksPride == QUEST_ACCEPTED and player:hasKeyItem(SUPER_SOUP_POT) == false) then player:startEvent(0x00BA); -- During quest "Cook's pride" elseif (player:hasKeyItem(SUPER_SOUP_POT) == true) then player:startEvent(0x00BB); -- Finish quest "Cook's pride" elseif (CooksPride == QUEST_COMPLETED and TheKindCardian == QUEST_AVAILABLE) then if (player:getVar("theLostCardianVar") == 0) then player:startEvent(0x001f); -- During quests "The lost cardian" else player:startEvent(0x0047); -- During quests "The lost cardian" end elseif (CooksPride == QUEST_COMPLETED and TheKindCardian ~= QUEST_COMPLETED) then player:startEvent(0x0047); -- During quests "The kind cardien" elseif (TheKindCardian == QUEST_COMPLETED) then player:startEvent(0x0048); -- New standard dialog after the quest "The kind cardien" else player:startEvent(0x0062); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if ((csid == 0x00BD or csid == 0x00BC) and option == 0) then player:addQuest(JEUNO,COOK_S_PRIDE); elseif (csid == 0x00BD and option == 1) then player:setVar("CooksPrideVar",1); elseif (csid == 0x00BB) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13446); else player:addTitle(MERCY_ERRAND_RUNNER); player:delKeyItem(SUPER_SOUP_POT); player:setVar("CooksPrideVar",0); player:addGil(GIL_RATE*3000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*3000); player:addItem(13446); player:messageSpecial(ITEM_OBTAINED,13446); -- Mythril Ring player:addFame(JEUNO, JEUNO_FAME*30); player:completeQuest(JEUNO,COOK_S_PRIDE); end elseif (csid == 10053) then player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",13,true); end end;
gpl-3.0
jshackley/darkstar
scripts/globals/weaponskills/skewer.lua
30
1368
----------------------------------- -- Skewer -- Polearm weapon skill -- Skill Level: 200 -- Delivers a three-hit attack. Chance of params.critical hit varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Light Gorget & Thunder Gorget. -- Aligned with the Light Belt & Thunder Belt. -- Element: None -- Modifiers: STR:50% -- 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) local params = {}; params.numHits = 3; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.35; 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.1; params.crit200 = 0.3; params.crit300 = 0.5; params.canCrit = true; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.5; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
kjmac123/metabuilder
metabuilder/metabase/msvctadp_common_android.lua
1
3052
import "metabase_common.lua" import "platform_android.lua" supportedplatforms { "TADP", } writer "writer_msvc.lua" option("msvc", "customwriter", "/writer_msvctadp_android.lua") option("msvc", "platform", "Tegra-Android") option("msvconfiguration", "AndroidArch", "armv7-a") option("msvccompile", "MultiProcessorCompilation", "true") option("msvccompile", "CppLanguageStandard", "gnu++11") config "Debug" --C/C++ --General option("msvclink", "GenerateDebugInformation", "true") --Optimization option("msvccompile", "OptimizationLevel", "O0") --Code generation option("msvccompile", "StackProtector", "false") --Ant Build option("antbuild", "AntBuildType", "Debug") option("antbuild", "Debuggable", "true") config_end() config "Release" --C/C++ --General option("msvclink", "GenerateDebugInformation", "true") --Optimization option("msvccompile", "OptimizationLevel", "O3") option("msvccompile", "OmitFramePointer", "true") --Code generation option("msvccompile", "StackProtector", "false") --Command Line option("msvccompile", "AdditionalOptions", "-funsafe-math-optimizations -ffast-math -ftree-vectorize %(AdditionalOptions)") --Ant Build option("antbuild", "AntBuildType", "Release") option("antbuild", "Debuggable", "true") config_end() config "Profile" --C/C++ --General option("msvclink", "GenerateDebugInformation", "true") --Optimization option("msvccompile", "OptimizationLevel", "O3") option("msvccompile", "OmitFramePointer", "false") --Code generation option("msvccompile", "StackProtector", "false") --Command Line option("msvccompile", "AdditionalOptions", "-funsafe-math-optimizations -ffast-math -ftree-vectorize %(AdditionalOptions)") --Ant Build option("antbuild", "AntBuildType", "Release") option("antbuild", "Debuggable", "true") config_end() config "Master" --C/C++ --General --option("msvclink", "GenerateDebugInformation", "false") option("msvclink", "GenerateDebugInformation", "true") --Optimization option("msvccompile", "OptimizationLevel", "O3") --option("msvccompile", "OmitFramePointer", "true") --Code generation option("msvccompile", "StackProtector", "false") --Command Line option("msvccompile", "AdditionalOptions", "-funsafe-math-optimizations -ffast-math -ftree-vectorize %(AdditionalOptions)") --Ant Build option("antbuild", "AntBuildType", "Release") option("antbuild", "Debuggable", "false") config_end() tadp = {} function tadp.setminapi(minapi) option("msvconfiguration", "AndroidMinAPI", minapi) end function tadp.settargetapi(targetapi) option("msvconfiguration", "AndroidTargetAPI", targetapi) end function tadp.setproguardenabled(value) local tmp = nil if value then tmp = "true" else tmp = "false" end option("_android", "ProguardEnabled", tmp) end function tadp.setdebuggable(value) local tmp = nil if value then tmp = "true" else tmp = "false" end option("_android", "Debuggable", tmp) end
mit
SpRoXx/GTW-RPG
[resources]/GTWtraindriver/train_s.lua
1
8533
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: http://forum.404rq.com/bug-reports/ Suggestions: http://forum.404rq.com/mta-servers-development/ Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- -- Globally accessible tables local train_payment_timers = { } --[[ Find and return the ID of nearest station ]]-- function find_nearest_station(plr, route) if not plr or not isElement(plr) or getElementType(plr) ~= "player" then return 1 end local x,y,z = getElementPosition(plr) local ID,total_dist = 1,9999 for k=1, #train_routes[route] do local dist = getDistanceBetweenPoints3D(train_routes[route][k][1],train_routes[route][k][2],train_routes[route][k][3], x,y,z) if dist < total_dist then total_dist = dist ID = k end end return ID end --[[ Calculate the ID for next trainstation and inform the passengers ]]-- function create_new_train_station(plr, ID) -- There must be a route at this point if not plr or not getElementData(plr, "GTWtraindriver.currentRoute") then return end -- Did we reach the end of the line yet? if so then restart the same route if #train_routes[getElementData(plr, "GTWtraindriver.currentRoute")] < ID then ID = 1; setElementData(plr, "GTWtraindriver.currentstation", 1) end -- Get the coordinates of the next station from our table local x,y,z = train_routes[getElementData(plr, "GTWtraindriver.currentRoute")][ID][1], train_routes[getElementData(plr, "GTWtraindriver.currentRoute")][ID][2], train_routes[getElementData(plr, "GTWtraindriver.currentRoute")][ID][3] -- Tell the client to make a marker and a blip for the traindriver triggerClientEvent(plr, "GTWtraindriver.createtrainstation", plr, x,y,z) -- Get the train object and check for passengers in it local veh = getPedOccupiedVehicle(plr) if not veh then return end local passengers = getVehicleOccupants(veh) if not passengers then return end -- Alright, we got some passengers, let's tell them where we're going for k,pa in pairs(passengers) do setTimer(delayed_message, 10000, 1, "Next station: "..getZoneName(x,y,z).. " in "..getZoneName(x,y,z, true), pa, 55,200, 0) end -- Save the station ID setElementData(plr, "GTWtraindriver.currentstation", ID) end --[[ Drivers get's a route asigned while passengers has to pay when entering the train ]]-- function on_train_enter(plr, seat, jacked) -- Make sure the vehicle is a train if not train_vehicles[getElementModel(source)] then return end if getElementType(plr) ~= "player" then return end -- Start the payment timer for passengers entering the train if seat > 0 then driver = getVehicleOccupant(source, 0) if driver and getElementType(driver) == "player" and getPlayerTeam(driver) and getPlayerTeam(driver) == getTeamFromName( "Civilians" ) and getElementData(driver, "Occupation") == "Train Driver" then -- Initial payment pay_for_the_ride(driver, plr) -- Kill the timer if it exist and make a new one if isTimer( train_payment_timers[plr] ) then killTimer( train_payment_timers[plr] ) end train_payment_timers[plr] = setTimer(pay_for_the_ride, 30000, 0, driver, plr) end end -- Whoever entered the train is a traindriver if getPlayerTeam(plr) and getPlayerTeam(plr) == getTeamFromName("Civilians") and getElementData(plr, "Occupation") == "Train Driver" and seat == 0 and train_vehicles[getElementModel(source )] then -- Let him choose a route to drive triggerClientEvent(plr, "GTWtraindriver.selectRoute", plr) end end addEventHandler("onVehicleEnter", root, on_train_enter) --[[ A new route has been selected, load it's data ]]-- function start_new_route(route) setElementData(client, "GTWtraindriver.currentRoute", route) if not getElementData(client, "GTWtraindriver.currentstation") then local first_station = find_nearest_station(client, route) create_new_train_station(client, first_station) else create_new_train_station(client, getElementData(client, "GTWtraindriver.currentstation")) end exports.GTWtopbar:dm("Drive your train to the first station to start your route", client, 0, 255, 0) end addEvent("GTWtraindriver.selectRouteReceive", true) addEventHandler("GTWtraindriver.selectRouteReceive", root, start_new_route) --[[ Handles payments in trains ]]-- function pay_for_the_ride(driver, passenger, first) -- Make sure that both the driver and passenger are players if not driver or not isElement(driver) or getElementType(driver) ~= "player" then return end if not passenger or not isElement(passenger) or getElementType(passenger) ~= "player" then return end -- Make sure the passenger is still inside the train local veh = getPedOccupiedVehicle(driver) if getVehicleOccupant(veh, 0) == driver and getElementData(driver, "Occupation") == "Train Driver" then -- First payment are more expensive if first then takePlayerMoney( passenger, 25 ) givePlayerMoney( driver, 25 ) else takePlayerMoney( passenger, 5 ) givePlayerMoney( driver, 5 ) end else -- Throw the passenger out if he can't pay for the ride any more removePedFromVehicle ( passenger ) if isElement(train_payment_timers[passenger]) then killTimer(train_payment_timers[passenger]) end exports.GTWtopbar:dm( "You can't afford this train ride anymore!", passenger, 255, 0, 0 ) end end --[[ station the payment timer when a passenger exit the train ]]-- function vehicle_exit(plr, seat, jacked) if isTimer(train_payment_timers[plr]) then killTimer(train_payment_timers[plr]) end end addEventHandler("onVehicleExit", root, vehicle_exit) --[[ Calculate the next station ]]-- function calculate_next_station(td_payment) -- Make sure the player is driving a train if not isPedInVehicle(client) then return end if not train_vehicles[getElementModel(getPedOccupiedVehicle(client))] then return end -- Calculate the payment minus charges for damage local fine = math.floor(td_payment - (td_payment*(1-(getElementHealth(getPedOccupiedVehicle(client))/1000)))) -- Increase stats by 1 local playeraccount = getPlayerAccount(client) local train_stations = (getAccountData(playeraccount, "acorp_stats_train_stations") or 0) + 1 setAccountData(playeraccount, "acorp_stats_train_stations", train_stations) -- Pay the driver givePlayerMoney(client, fine + math.floor(train_stations/4)) -- Notify about the payment reduce if the train is damaged if math.floor(td_payment - fine) > 1 then takePlayerMoney(client, math.floor(td_payment - fine)) exports.GTWtopbar:dm("Removed $"..tostring(math.floor(td_payment - fine)).." due to damage on your train!", client, 255, 0, 0) end -- Get the next station on the list if #train_routes[getElementData(client, "GTWtraindriver.currentRoute")] == tonumber(getElementData(client, "GTWtraindriver.currentstation")) then setElementData( client, "GTWtraindriver.currentstation", 1) else setElementData(client, "GTWtraindriver.currentstation", tonumber( getElementData(client, "GTWtraindriver.currentstation" ))+1) end -- Force the client to create markers and blips for the next station create_new_train_station(client, tonumber(getElementData(client, "GTWtraindriver.currentstation"))) end addEvent("GTWtraindriver.paytrainDriver", true) addEventHandler("GTWtraindriver.paytrainDriver", resourceRoot, calculate_next_station) --[[ A little hack for developers to manually change the route ID ]]-- function set_manual_station(plr, cmd, ID) local is_staff = exports.GTWstaff:isStaff(plr) if not is_staff then return end setElementData(plr, "GTWtraindriver.currentstation", tonumber(ID) or 1) create_new_train_station(plr, tonumber(ID) or 1) end addCommandHandler("settrainstation", set_manual_station) --[[ Display a delayed message securely ]]-- function delayed_message(text, plr, r,g,b, color_coded) if not plr or not isElement(plr) or getElementType(plr) ~= "player" then return end if not getPlayerTeam(plr) or getPlayerTeam(plr) ~= getTeamFromName("Civilians") or getElementData(plr, "Occupation") ~= "Train Driver" then return end if not getPedOccupiedVehicle(plr) or not train_vehicles[getElementModel(getPedOccupiedVehicle(plr))] then return end exports.GTWtopbar:dm(text, plr, r,g,b, color_coded) end
bsd-2-clause
jshackley/darkstar
scripts/zones/Cloister_of_Frost/mobs/Shiva_Prime.lua
1
1736
----------------------------------- -- Area: Cloister of Frost -- MOB: Shiva Prime -- Involved in Quest: Trial by Ice -- Involved in Mission: ASA-4 Sugar Coated Directive ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/status"); ----------------------------------- -- OnMobFight Action ----------------------------------- function onMobFight(mob, target) local mobId = mob:getID(); -- ASA-4: Astral Flow Behavior - Guaranteed to Use At Least 5 times before killable, at specified intervals. if (mob:getBattlefield():getBcnmID() == 484 and GetMobAction(mobId) == ACTION_ATTACK) then local astralFlows = mob:getLocalVar("astralflows"); if ((astralFlows == 0 and mob:getHPP() <= 80) or (astralFlows == 1 and mob:getHPP() <= 60) or (astralFlows == 2 and mob:getHPP() <= 40) or (astralFlows == 3 and mob:getHPP() <= 20) or (astralFlows == 4 and mob:getHPP() <= 1)) then mob:setLocalVar("astralflows",astralFlows + 1); mob:useMobAbility(628); if (astralFlows >= 5) then mob:setUnkillable(false); end end end end; ----------------------------------- -- OnMobSpawn Action ----------------------------------- function onMobSpawn(mob) -- ASA-4: Avatar is Unkillable Until Its Used Astral Flow At Least 5 times At Specified Intervals if (mob:getBattlefield():getBcnmID() == 484) then mob:setLocalVar("astralflows",0); mob:setUnkillable(true); end end; ----------------------------------- -- OnMobDeath Action ----------------------------------- function onMobDeath(mob,killer,ally) end;
gpl-3.0
jshackley/darkstar
scripts/globals/abilities/box_step.lua
28
7984
----------------------------------- -- Ability: Box Step -- Lowers target's defense. If successful, you will earn two Finishing Moves. -- Obtained: Dancer Level 30 -- TP Required: 10% -- Recast Time: 00:05 -- Duration: First Step lasts 1 minute, each following Step extends its current duration by 30 seconds. ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/weaponskills"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (player:getAnimation() ~= 1) then return MSGBASIC_REQUIRES_COMBAT,0; else if (player:hasStatusEffect(EFFECT_TRANCE)) then return 0,0; elseif (player:getTP() < 10) then return MSGBASIC_NOT_ENOUGH_TP,0; else return 0,0; end end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) -- Only remove TP if the player doesn't have Trance. if not player:hasStatusEffect(EFFECT_TRANCE) then player:delTP(10); end; local hit = 2; local effect = 1; if math.random() <= getHitRate(player,target,true,player:getMod(MOD_STEP_ACCURACY)) then hit = 6; local mjob = player:getMainJob(); local daze = 1; if (mjob == 19) then if (target:hasStatusEffect(EFFECT_SLUGGISH_DAZE_1)) then local duration = target:getStatusEffect(EFFECT_SLUGGISH_DAZE_1):getDuration(); target:delStatusEffectSilent(EFFECT_SLUGGISH_DAZE_1); if (player:hasStatusEffect(EFFECT_PRESTO)) then target:addStatusEffect(EFFECT_SLUGGISH_DAZE_3,1,0,duration+30); daze = 3; effect = 3; else target:addStatusEffect(EFFECT_SLUGGISH_DAZE_2,1,0,duration+30); daze = 2; effect = 2; end elseif (target:hasStatusEffect(EFFECT_SLUGGISH_DAZE_2)) then local duration = target:getStatusEffect(EFFECT_SLUGGISH_DAZE_2):getDuration(); target:delStatusEffectSilent(EFFECT_SLUGGISH_DAZE_2); if (player:hasStatusEffect(EFFECT_PRESTO)) then target:addStatusEffect(EFFECT_SLUGGISH_DAZE_4,1,0,duration+30); daze = 3; effect = 4; else target:addStatusEffect(EFFECT_SLUGGISH_DAZE_3,1,0,duration+30); daze = 2; effect = 3; end elseif (target:hasStatusEffect(EFFECT_SLUGGISH_DAZE_3)) then local duration = target:getStatusEffect(EFFECT_SLUGGISH_DAZE_3):getDuration(); target:delStatusEffectSilent(EFFECT_SLUGGISH_DAZE_3); if (player:hasStatusEffect(EFFECT_PRESTO)) then target:addStatusEffect(EFFECT_SLUGGISH_DAZE_5,1,0,duration+30); daze = 3; effect = 5; else target:addStatusEffect(EFFECT_SLUGGISH_DAZE_4,1,0,duration+30); daze = 2; effect = 4; end elseif (target:hasStatusEffect(EFFECT_SLUGGISH_DAZE_4)) then local duration = target:getStatusEffect(EFFECT_SLUGGISH_DAZE_4):getDuration(); target:delStatusEffectSilent(EFFECT_SLUGGISH_DAZE_4); if (player:hasStatusEffect(EFFECT_PRESTO)) then daze = 3; else daze = 2; end target:addStatusEffect(EFFECT_SLUGGISH_DAZE_2,1,0,duration+30); effect = 5; elseif (target:hasStatusEffect(EFFECT_SLUGGISH_DAZE_5)) then local duration = target:getStatusEffect(EFFECT_SLUGGISH_DAZE_5):getDuration(); target:delStatusEffectSilent(EFFECT_SLUGGISH_DAZE_5); target:addStatusEffect(EFFECT_SLUGGISH_DAZE_3,1,0,duration+30); daze = 1; effect = 5; else if (player:hasStatusEffect(EFFECT_PRESTO)) then target:addStatusEffect(EFFECT_SLUGGISH_DAZE_2,1,0,60); daze = 3; effect = 2; else target:addStatusEffect(EFFECT_SLUGGISH_DAZE_1,1,0,60); daze = 2; effect = 1; end end; else if (target:hasStatusEffect(EFFECT_SLUGGISH_DAZE_1)) then local duration = target:getStatusEffect(EFFECT_SLUGGISH_DAZE_1):getDuration(); target:delStatusEffectSilent(EFFECT_SLUGGISH_DAZE_1); target:addStatusEffect(EFFECT_SLUGGISH_DAZE_2,1,0,duration+30); effect = 2; elseif (target:hasStatusEffect(EFFECT_SLUGGISH_DAZE_2)) then local duration = target:getStatusEffect(EFFECT_SLUGGISH_DAZE_2):getDuration(); target:delStatusEffectSilent(EFFECT_SLUGGISH_DAZE_2); target:addStatusEffect(EFFECT_SLUGGISH_DAZE_3,1,0,duration+30); effect = 3; elseif (target:hasStatusEffect(EFFECT_SLUGGISH_DAZE_3)) then local duration = target:getStatusEffect(EFFECT_SLUGGISH_DAZE_3):getDuration(); target:delStatusEffectSilent(EFFECT_SLUGGISH_DAZE_3); target:addStatusEffect(EFFECT_SLUGGISH_DAZE_4,1,0,duration+30); effect = 4; elseif (target:hasStatusEffect(EFFECT_SLUGGISH_DAZE_4)) then local duration = target:getStatusEffect(EFFECT_SLUGGISH_DAZE_4):getDuration(); target:delStatusEffectSilent(EFFECT_SLUGGISH_DAZE_4); target:addStatusEffect(EFFECT_SLUGGISH_DAZE_5,1,0,duration+30); effect = 5; elseif (target:hasStatusEffect(EFFECT_SLUGGISH_DAZE_5)) then local duration = target:getStatusEffect(EFFECT_SLUGGISH_DAZE_5):getDuration(); target:delStatusEffectSilent(EFFECT_SLUGGISH_DAZE_5); target:addStatusEffect(EFFECT_SLUGGISH_DAZE_5,1,0,duration+30); effect = 5; else target:addStatusEffect(EFFECT_SLUGGISH_DAZE_1,1,0,60); effect = 1; end; end if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_1)) then player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_1); player:addStatusEffect(EFFECT_FINISHING_MOVE_1+daze,1,0,7200); elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_2)) then player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_2); player:addStatusEffect(EFFECT_FINISHING_MOVE_2+daze,1,0,7200); elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_3)) then player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_3); if (daze > 2) then daze = 2; end; player:addStatusEffect(EFFECT_FINISHING_MOVE_3+daze,1,0,7200); elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_4)) then player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_4); player:addStatusEffect(EFFECT_FINISHING_MOVE_5,1,0,7200); elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_5)) then else player:addStatusEffect(EFFECT_FINISHING_MOVE_1 - 1 + daze,1,0,7200); end; else ability:setMsg(158); end return effect, getStepAnimation(player:getWeaponSkillType(SLOT_MAIN)), hit; end;
gpl-3.0
sp3ctum/lean
tests/lua/tc_bug1.lua
4
2343
local env = environment() local N = Const("N") local p = Const("p") local q = Const("q") local a = Const("a") local b = Const("b") local f = Const("f") local H1 = Const("H1") local H2 = Const("H2") local And = Const("and") local and_intro = Const("and_intro") local A = Local("A", Prop) local B = Local("B", Prop) local C = Local("C", Prop) env = add_decl(env, mk_constant_assumption("N", Type)) env = add_decl(env, mk_constant_assumption("p", mk_arrow(N, N, Prop))) env = add_decl(env, mk_constant_assumption("q", mk_arrow(N, Prop))) env = add_decl(env, mk_constant_assumption("f", mk_arrow(N, N))) env = add_decl(env, mk_constant_assumption("a", N)) env = add_decl(env, mk_constant_assumption("b", N)) env = add_decl(env, mk_constant_assumption("and", mk_arrow(Prop, Prop, Prop))) env = add_decl(env, mk_constant_assumption("and_intro", Pi(A, B, mk_arrow(A, B, And(A, B))))) env = add_decl(env, mk_constant_assumption("foo_intro", Pi(A, B, C, mk_arrow(B, B)))) env = add_decl(env, mk_constant_assumption("foo_intro2", Pi(A, B, C, mk_arrow(B, B)))) env = add_decl(env, mk_axiom("Ax1", q(a))) env = add_decl(env, mk_axiom("Ax2", q(a))) env = add_decl(env, mk_axiom("Ax3", q(b))) local Ax1 = Const("Ax1") local Ax2 = Const("Ax2") local Ax3 = Const("Ax3") local foo_intro = Const("foo_intro") local foo_intro2 = Const("foo_intro2") local ng = name_generator("foo") local tc = type_checker(env, ng) local m1 = mk_metavar("m1", Prop) print("before is_def_eq") local tc = type_checker(env, ng) r, cs = tc:is_def_eq(foo_intro(m1, q(a), q(a), Ax1), foo_intro(q(a), q(a), q(a), Ax2)) assert(r) cs = cs:linearize() assert(#cs == 1) assert(cs[1]:lhs() == m1) assert(cs[1]:rhs() == q(a)) local tc = type_checker(env, ng) print(tostring(foo_intro) .. " : " .. tostring(tc:check(foo_intro))) print(tostring(foo_intro2) .. " : " .. tostring(tc:check(foo_intro2))) assert(tc:is_def_eq(foo_intro, foo_intro2)) print("before is_def_eq2") local r, cs = tc:is_def_eq(foo_intro(m1, q(a), q(b), Ax1), foo_intro2(q(a), q(a), q(a), Ax2)) assert(r) cs = cs:linearize() assert(#cs == 0) local tc = type_checker(env, ng) print("before failure") assert(not pcall(function() print(tc:check(and_intro(m1, q(a), Ax1, Ax3))) end)) print("before success") local t, cs = tc:check(and_intro(m1, q(a), Ax1, Ax2)) cs = cs:linearize() assert(#cs == 1)
apache-2.0
jshackley/darkstar
scripts/globals/spells/katon_san.lua
17
1616
----------------------------------------- -- Spell: Katon: San -- Deals fire damage to an enemy and lowers its resistance against water. ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) --doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus) local duration = 15 + caster:getMerit(MERIT_KATON_EFFECT) -- T1 bonus debuff duration local bonusAcc = 0; local bonusMab = caster:getMerit(MERIT_KATON_EFFECT) + caster:getMod(MOD_NIN_NUKE_BONUS); -- T1 mag atk + "enhances Ninjustu damage" mod if(caster:getMerit(MERIT_KATON_SAN) ~= 0) then -- T2 mag atk/mag acc, don't want to give a penalty to entities that can cast this without merits bonusMab = bonusMab + caster:getMerit(MERIT_KATON_SAN) - 5; -- merit gives 5 power but no bonus with one invest, thus subtract 5 bonusAcc = bonusAcc + caster:getMerit(MERIT_KATON_SAN) - 5; end; if (caster:isBehind(target,15) and caster:hasStatusEffect(EFFECT_INNIN)) then -- Innin mag atk bonus from behind, guesstimating angle at 15 degrees bonusMab = bonusMab + caster:getStatusEffect(EFFECT_INNIN):getPower(); end local dmg = doNinjutsuNuke(134,1,caster,spell,target,false,bonusAcc,bonusMab); handleNinjutsuDebuff(caster,target,spell,30,duration,MOD_WATERRES); return dmg; end;
gpl-3.0
jshackley/darkstar
scripts/globals/items/crab_stewpot.lua
36
1675
----------------------------------------- -- ID: 5544 -- Item: Crab Stewpot -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +10% Cap 50 -- MP +10 -- HP Recoverd while healing 5 -- MP Recovered while healing 1 -- Defense +15% Cap 50 -- Evasion +5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5544); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 10); target:addMod(MOD_FOOD_HP_CAP, 50); target:addMod(MOD_MP, 10); target:addMod(MOD_HPHEAL, 5); target:addMod(MOD_MPHEAL, 1); target:addMod(MOD_FOOD_DEFP, 15); target:addMod(MOD_FOOD_DEF_CAP, 50); target:addMod(MOD_EVA, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 10); target:delMod(MOD_FOOD_HP_CAP, 50); target:delMod(MOD_MP, 10); target:delMod(MOD_HPHEAL, 5); target:delMod(MOD_MPHEAL, 1); target:delMod(MOD_FOOD_DEFP, 15); target:delMod(MOD_FOOD_DEF_CAP, 50); target:delMod(MOD_EVA, 5); end;
gpl-3.0
Victek/wrt1900ac-aa
veriksystems/luci-0.11/applications/luci-asterisk/luasrc/model/cbi/asterisk-sip-connections.lua
11
3982
--[[ 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: asterisk-sip-connections.lua 3620 2008-10-23 15:42:12Z jow $ ]]-- cbimap = Map("asterisk", "asterisk", "") sip = cbimap:section(TypedSection, "sip", "SIP Connection", "") sip.addremove = true alwaysinternational = sip:option(Flag, "alwaysinternational", "Always Dial International", "") alwaysinternational.optional = true canreinvite = sip:option(ListValue, "canreinvite", "Reinvite/redirect media connections", "") canreinvite:value("yes", "Yes") canreinvite:value("nonat", "Yes when not behind NAT") canreinvite:value("update", "Use UPDATE rather than INVITE for path redirection") canreinvite:value("no", "No") canreinvite.optional = true context = sip:option(ListValue, "context", "Context to use", "") context.titleref = luci.dispatcher.build_url( "admin", "services", "asterisk", "dialplans" ) cbimap.uci:foreach( "asterisk", "dialplan", function(s) context:value(s['.name']) end ) cbimap.uci:foreach( "asterisk", "dialzone", function(s) context:value(s['.name']) end ) countrycode = sip:option(Value, "countrycode", "Country Code for connection", "") countrycode.optional = true dtmfmode = sip:option(ListValue, "dtmfmode", "DTMF mode", "") dtmfmode:value("info", "Use RFC2833 or INFO for the BudgeTone") dtmfmode:value("rfc2833", "Use RFC2833 for the BudgeTone") dtmfmode:value("inband", "Use Inband (only with ulaw/alaw)") dtmfmode.optional = true extension = sip:option(Value, "extension", "Add as Extension", "") extension.optional = true fromdomain = sip:option(Value, "fromdomain", "Primary domain identity for From: headers", "") fromdomain.optional = true fromuser = sip:option(Value, "fromuser", "From user (required by many SIP providers)", "") fromuser.optional = true host = sip:option(Value, "host", "Host name (or blank)", "") host.optional = true incoming = sip:option(DynamicList, "incoming", "Ring on incoming dialplan contexts", "") incoming.optional = true insecure = sip:option(ListValue, "insecure", "Allow Insecure for", "") insecure:value("port", "Allow mismatched port number") insecure:value("invite", "Do not require auth of incoming INVITE") insecure:value("port,invite", "Allow mismatched port and Do not require auth of incoming INVITE") insecure.optional = true internationalprefix = sip:option(Value, "internationalprefix", "International Dial Prefix", "") internationalprefix.optional = true mailbox = sip:option(Value, "mailbox", "Mailbox for MWI", "") mailbox.optional = true nat = sip:option(Flag, "nat", "NAT between phone and Asterisk", "") nat.optional = true pedantic = sip:option(Flag, "pedantic", "Check tags in headers", "") pedantic.optional = true port = sip:option(Value, "port", "SIP Port", "") port.optional = true prefix = sip:option(Value, "prefix", "Dial Prefix (for external line)", "") prefix.optional = true qualify = sip:option(Value, "qualify", "Reply Timeout (ms) for down connection", "") qualify.optional = true register = sip:option(Flag, "register", "Register connection", "") register.optional = true secret = sip:option(Value, "secret", "Secret", "") secret.optional = true selfmailbox = sip:option(Flag, "selfmailbox", "Dial own extension for mailbox", "") selfmailbox.optional = true timeout = sip:option(Value, "timeout", "Dial Timeout (sec)", "") timeout.optional = true type = sip:option(ListValue, "type", "Client Type", "") type:value("friend", "Friend (outbound/inbound)") type:value("user", "User (inbound - authenticate by \"from\")") type:value("peer", "Peer (outbound - match by host)") type.optional = true username = sip:option(Value, "username", "Username", "") username.optional = true return cbimap
gpl-2.0
jshackley/darkstar
scripts/globals/effects/accuracy_boost.lua
18
1090
----------------------------------- -- -- EFFECT_ACCURACY_BOOST -- ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) if (effect:getPower()>100) then effect:setPower(50); end target:addMod(MOD_ACCP,effect:getPower()); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) -- the effect loses accuracy of 1 every 3 ticks depending on the source of the acc boost local boostACC_effect_size = effect:getPower(); if (boostACC_effect_size > 0) then effect:setPower(boostACC_effect_size - 1) target:delMod(MOD_ACC,1); end end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) local boostACC_effect_size = effect:getPower(); if (boostACC_effect_size > 0) then target:delMod(MOD_ACCP,effect:getPower()); end end;
gpl-3.0
jshackley/darkstar
scripts/globals/items/dish_of_spaghetti_melanzane.lua
35
1401
----------------------------------------- -- ID: 5213 -- Item: dish_of_spaghetti_melanzane -- Food Effect: 30Min, All Races ----------------------------------------- -- Health % 25 -- Health Cap 100 -- Vitality 2 -- Store TP 4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5213); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 25); target:addMod(MOD_FOOD_HP_CAP, 100); target:addMod(MOD_VIT, 2); target:addMod(MOD_STORETP, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 25); target:delMod(MOD_FOOD_HP_CAP, 100); target:delMod(MOD_VIT, 2); target:delMod(MOD_STORETP, 4); end;
gpl-3.0
jshackley/darkstar
scripts/zones/West_Ronfaure/npcs/qm2.lua
34
1498
----------------------------------- -- Area: West Ronfaure -- NPC: qm2 (???) -- Involved in Quest: The Dismayed Customer -- @pos -550 -0 -542 100 ----------------------------------- package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/West_Ronfaure/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(SANDORIA, THE_DISMAYED_CUSTOMER) == QUEST_ACCEPTED and player:getVar("theDismayedCustomer") == 2) then player:addKeyItem(GULEMONTS_DOCUMENT); player:messageSpecial(KEYITEM_OBTAINED, GULEMONTS_DOCUMENT); player:setVar("theDismayedCustomer", 0); else player:messageSpecial(DISMAYED_CUSTOMER); 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
LiberatorUSA/GUCEF
tools/ArchiveDiff/premake5.lua
1
3723
-------------------------------------------------------------------- -- This file was automatically generated by ProjectGenerator -- which is tooling part the build system designed for GUCEF -- (Galaxy Unlimited Framework) -- For the latest info, see http://www.VanvelzenSoftware.com/ -- -- The contents of this file are placed in the public domain. Feel -- free to make use of it in any way you like. -------------------------------------------------------------------- -- -- Configuration for module: ArchiveDiff configuration( { "LINUX32" } ) project( "ArchiveDiff" ) configuration( { "LINUX64" } ) project( "ArchiveDiff" ) configuration( { "WIN32" } ) project( "ArchiveDiff" ) configuration( { "WIN64" } ) project( "ArchiveDiff" ) configuration( {} ) location( os.getenv( "PM5OUTPUTDIR" ) ) configuration( {} ) targetdir( os.getenv( "PM5TARGETDIR" ) ) configuration( {} ) language( "C" ) configuration( { "LINUX32" } ) language( "C++" ) configuration( { "LINUX64" } ) language( "C++" ) configuration( { "WIN32" } ) language( "C++" ) configuration( { "WIN64" } ) language( "C++" ) configuration( { "LINUX32" } ) configuration( { LINUX32 } ) kind( "ConsoleApp" ) configuration( { "LINUX64" } ) configuration( { LINUX64 } ) kind( "ConsoleApp" ) configuration( { "WIN32" } ) configuration( { WIN32 } ) kind( "WindowedApp" ) configuration( { "WIN64" } ) configuration( { WIN64 } ) kind( "WindowedApp" ) configuration( { LINUX32 } ) links( { "ArchiveDiffLib", "gucefCORE", "gucefMT", "gucefPATCHER" } ) links( { "ArchiveDiffLib", "gucefCORE", "gucefMT", "gucefPATCHER" } ) configuration( { LINUX32 } ) defines( { "ARCHIVEDIFF_BUILD_MODULE" } ) configuration( { LINUX64 } ) links( { "ArchiveDiffLib", "gucefCORE", "gucefMT", "gucefPATCHER" } ) links( { "ArchiveDiffLib", "gucefCORE", "gucefMT", "gucefPATCHER" } ) configuration( { LINUX64 } ) defines( { "ARCHIVEDIFF_BUILD_MODULE" } ) configuration( { WIN32 } ) links( { "ArchiveDiffLib", "gucefCORE", "gucefMT", "gucefPATCHER" } ) links( { "ArchiveDiffLib", "gucefCORE", "gucefMT", "gucefPATCHER" } ) configuration( { WIN32 } ) defines( { "ARCHIVEDIFF_BUILD_MODULE" } ) configuration( { WIN64 } ) links( { "ArchiveDiffLib", "gucefCORE", "gucefMT", "gucefPATCHER" } ) links( { "ArchiveDiffLib", "gucefCORE", "gucefMT", "gucefPATCHER" } ) configuration( { WIN64 } ) defines( { "ARCHIVEDIFF_BUILD_MODULE" } ) configuration( { "LINUX32" } ) vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } } files( { "src/ArchiveDiff_main.cpp" } ) configuration( { "LINUX64" } ) vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } } files( { "src/ArchiveDiff_main.cpp" } ) configuration( { "WIN32" } ) vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } } files( { "src/ArchiveDiff_main.cpp" } ) configuration( { "WIN64" } ) vpaths { ["Platform Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } } files( { "src/ArchiveDiff_main.cpp" } ) configuration( {} ) includedirs( { "../../common/include", "../../platform/gucefCOM/include", "../../platform/gucefCOMCORE/include", "../../platform/gucefCORE/include", "../../platform/gucefMT/include", "../../platform/gucefPATCHER/include", "../ArchiveDiffLib/include" } ) configuration( { "LINUX32" } ) includedirs( { "../../platform/gucefCORE/include/linux" } ) configuration( { "LINUX64" } ) includedirs( { "../../platform/gucefCORE/include/linux" } ) configuration( { "WIN32" } ) includedirs( { "../../platform/gucefCORE/include/mswin" } ) configuration( { "WIN64" } ) includedirs( { "../../platform/gucefCORE/include/mswin" } )
apache-2.0
jshackley/darkstar
scripts/zones/Yhoator_Jungle/npcs/Harvesting_Point.lua
29
1116
----------------------------------- -- Area: Yhoator Jungle -- NPC: Harvesting Point ----------------------------------- package.loaded["scripts/zones/Yhoator_Jungle/TextIDs"] = nil; ------------------------------------- require("scripts/globals/harvesting"); require("scripts/zones/Yhoator_Jungle/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) startHarvesting(player,player:getZoneID(),npc,trade,0x000B); end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(HARVESTING_IS_POSSIBLE_HERE,1020); 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
a1ive/grub2-filemanager
boot/grubfm/g4d_path.lua
1
1376
#!lua -- Grub2-FileManager -- Copyright (C) 2018, 2019, 2020 A1ive. -- -- Grub2-FileManager 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. -- -- Grub2-FileManager 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 Grub2-FileManager. If not, see <http://www.gnu.org/licenses/>. file = grub.getenv ("g4d_path") if (file == nil) then file = "" end device = string.match (file, "^%(([%w,]+)%)/.*$") if string.match (device, "^hd[%d]+,[%w]+") ~= nil then -- (hdx,y) devnum = string.match (device, "^hd%d+,%a*(%d+)$") devnum = devnum - 1 g4d_file = "(" .. string.match (device, "^(hd%d+,)%a*%d+$") .. devnum .. ")" .. string.match (file, "^%([%w,]+%)(.*)$") elseif string.match (device, "^[hcf]d[%d]*") ~= nil then -- (hdx) (cdx) (fdx) (cd) g4d_file = file else -- (loop) (memdisk) (proc) etc. g4d_file = "" end g4d_file = string.gsub (g4d_file, " ", "\\ ") grub.exportenv ("g4d_path", g4d_file)
gpl-3.0
Ombridride/minetest-minetestforfun-server
mods/mobs/npc.lua
7
3971
-- Npc by TenPlus1 mobs.npc_drops = { "farming:meat", "farming:donut", "farming:bread", "default:apple", "default:sapling", "default:junglesapling", "shields:shield_enhanced_wood", "3d_armor:chestplate_cactus", "3d_armor:boots_bronze", "default:sword_steel", "default:pick_steel", "default:shovel_steel", "default:bronze_ingot", "bucket:bucket_water", "default:stick", "cavestuff:pebble_1", "building_blocks:stick", "default:cobble", "default:gravel", "default:clay_lump", "default:sand", "default:dirt_with_grass", "default:dirt", "default:chest", "default:torch"} mobs:register_mob("mobs:npc", { -- animal, monster, npc type = "npc", -- aggressive, deals 6 damage to player/monster when hit passive = false, group_attack = true, damage = 4, -- 3 damages if tamed attack_type = "dogfight", attacks_monsters = true, pathfinding = false, -- health & armor hp_min = 20, hp_max = 20, armor = 200, -- textures and model collisionbox = {-0.35,-1.0,-0.35, 0.35,0.8,0.35}, visual = "mesh", mesh = "character.b3d", drawtype = "front", textures = { {"mobs_npc.png"}, }, child_texture = { {"mobs_npc_baby.png"}, -- derpy baby by AmirDerAssassine }, -- sounds makes_footstep_sound = true, sounds = { random = "mobs_npc", damage = "mobs_npc_hit", attack = "mobs_npc_attack", death = "mobs_npc_death", }, -- speed and jump walk_velocity = 3, run_velocity = 3, jump = true, -- drops wood and chance of apples when dead drops = { {name = "default:wood", chance = 1, min = 1, max = 3}, {name = "default:apple", chance = 2, min = 1, max = 2}, {name = "default:axe_stone", chance = 3, min = 1, max = 1}, {name = "maptools:silver_coin", chance = 10, min = 1, max = 1,}, }, -- damaged by water_damage = 0, lava_damage = 6, light_damage = 0, -- follow diamond follow = {"farming:bread", "mobs:meat", "default:diamond"}, view_range = 16, -- set owner and order owner = "", order = "follow", fear_height = 3, -- model animation animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, -- right clicking with "cooked meat" or "bread" will give npc more health on_rightclick = function(self, clicker) local item = clicker:get_wielded_item() local name = clicker:get_player_name() if item:get_name() == "default:diamond" then --/MFF (Crabman|07/14/2015) tamed with diamond if (self.diamond_count or 0) < 4 then self.diamond_count = (self.diamond_count or 0) + 1 if not minetest.setting_getbool("creative_mode") then item:take_item() clicker:set_wielded_item(item) end if self.diamond_count >= 4 then self.damages = 3 self.tamed = true self.owner = clicker:get_player_name() end end return -- feed to heal npc elseif not mobs:feed_tame(self, clicker, 8, true, true) then -- right clicking with gold lump drops random item from mobs.npc_drops if item:get_name() == "default:gold_lump" then if not minetest.setting_getbool("creative_mode") then item:take_item() clicker:set_wielded_item(item) end local pos = self.object:getpos() pos.y = pos.y + 0.5 minetest.add_item(pos, { name = mobs.npc_drops[math.random(1, #mobs.npc_drops)] }) return -- if owner switch between follow and stand elseif self.owner and self.owner == clicker:get_player_name() then if self.order == "follow" then self.order = "stand" else self.order = "follow" end end mobs:capture_mob(self, clicker, 0, 5, 80, false, nil) end end, }) -- spawning enable for now mobs:spawn_specific("mobs:npc", {"default:dirt_with_grass", "default:dirt", "default:junglegrass", "default:sand"}, {"air"}, -1, 20, 30, 500000, 1, -31000, 31000, true, true) -- register spawn egg mobs:register_egg("mobs:npc", "Npc", "mobs_npc_male_inv.png", 1)
unlicense
jshackley/darkstar
scripts/zones/Qufim_Island/npcs/Singing_Blade_IM.lua
30
3053
----------------------------------- -- Area: Qufim Island -- NPC: Singing Blade, I.M. -- Type: Border Conquest Guards -- @pos 179.093 -21.575 -15.282 126 ----------------------------------- package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Qufim_Island/TextIDs"); local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = QUFIMISLAND; local csid = 0x7ff8; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
jshackley/darkstar
scripts/zones/Labyrinth_of_Onzozo/mobs/Goblin_Alchemist.lua
2
1028
----------------------------------- -- Area: Labyrinth of Onzozo -- MOB: Goblin Alchemist -- Note: Place holder Soulstealer Skullnix ----------------------------------- require("scripts/zones/Labyrinth_of_Onzozo/MobIDs"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) checkGoVregime(ally,mob,771,2); checkGoVregime(ally,mob,772,2); checkGoVregime(ally,mob,774,2); local mob = mob:getID(); if (Soulstealer_Skullnix_PH[mob] ~= nil) then local ToD = GetServerVariable("[POP]Soulstealer_Skullnix"); if (ToD <= os.time(t) and GetMobAction(Soulstealer_Skullnix) == 0) then if (math.random((1),(20)) == 5) then UpdateNMSpawnPoint(Soulstealer_Skullnix); GetMobByID(Soulstealer_Skullnix):setRespawnTime(GetMobRespawnTime(mob)); SetServerVariable("[PH]Soulstealer_Skullnix", mob); DeterMob(mob, true); end end end end;
gpl-3.0
LiberatorUSA/GUCEF
dependencies/agar/ada-gui/GENERATION/bindings_c.lua
4
3564
#!/usr/bin/env lua local ts = tostring io.write ([[ void agar_gui_widget_bind_pointer (AG_Widget *w, const char *binding, void **p) { AG_BindPointer (w, binding, p); } void agar_gui_widget_bind_boolean (AG_Widget *w, const char *binding, int *var) { AG_BindBool (w, binding, var); } void agar_gui_widget_bind_integer (AG_Widget *w, const char *binding, int *var) { AG_BindInt (w, binding, var); } void agar_gui_widget_bind_unsigned (AG_Widget *w, const char *binding, unsigned *var) { AG_BindUint (w, binding, var); } void agar_gui_widget_bind_float (AG_Widget *w, const char *binding, float *var) { AG_BindFloat (w, binding, var); } void agar_gui_widget_bind_double (AG_Widget *w, const char *binding, double *var) { AG_BindDouble (w, binding, var); } ]]) for _, value in pairs ({8, 16, 32}) do io.write ([[ void agar_gui_widget_bind_uint]]..ts(value)..[[ (AG_Widget *w, const char *binding, Uint]]..ts(value)..[[ *val) { AG_BindUint]]..ts(value)..[[ (w, binding, val); } void agar_gui_widget_bind_int]]..ts(value)..[[ (AG_Widget *w, const char *binding, Sint]]..ts(value)..[[ *val) { AG_BindSint]]..ts(value)..[[ (w, binding, val); } void agar_gui_widget_bind_flag]]..ts(value)..[[ (AG_Widget *w, const char *binding, Uint]]..ts(value)..[[ *val, Uint]]..ts(value)..[[ bitmask) { AG_BindFlag]]..ts(value)..[[ (w, binding, val, bitmask); } ]]) end io.write ([[ void * agar_gui_widget_get_pointer (AG_Widget *w, const char *binding) { return AG_WidgetPointer (w, binding); } int agar_gui_widget_get_boolean (AG_Widget *w, const char *binding) { return AG_GetInt (w, binding); } int agar_gui_widget_get_integer (AG_Widget *w, const char *binding) { return AG_GetInt (w, binding); } unsigned int agar_gui_widget_get_unsigned (AG_Widget *w, const char *binding) { return AG_GetUint (w, binding); } float agar_gui_widget_get_float (AG_Widget *w, const char *binding) { return AG_GetFloat (w, binding); } double agar_gui_widget_get_double (AG_Widget *w, const char *binding) { return AG_GetDouble (w, binding); } ]]) for _, value in pairs ({8, 16, 32}) do io.write ([[ Uint]]..ts(value)..[[ agar_gui_widget_get_uint]]..ts(value)..[[ (AG_Widget *w, const char *binding) { return AG_GetUint]]..ts(value)..[[ (w, binding); } Sint]]..ts(value)..[[ agar_gui_widget_get_int]]..ts(value)..[[ (AG_Widget *w, const char *binding) { return AG_GetSint]]..ts(value)..[[ (w, binding); } ]]) end io.write ([[ void agar_gui_widget_set_pointer (AG_Widget *w, const char *binding, void *val) { AG_SetPointer (w, binding, val); } void agar_gui_widget_set_boolean (AG_Widget *w, const char *binding, int val) { AG_SetInt (w, binding, val); } void agar_gui_widget_set_integer (AG_Widget *w, const char *binding, int val) { AG_SetInt (w, binding, val); } void agar_gui_widget_set_unsigned (AG_Widget *w, const char *binding, unsigned int val) { AG_SetUint (w, binding, val); } void agar_gui_widget_set_float (AG_Widget *w, const char *binding, float val) { AG_SetFloat (w, binding, val); } void agar_gui_widget_set_double (AG_Widget *w, const char *binding, double val) { AG_SetDouble (w, binding, val); } ]]) for _, value in pairs ({8, 16, 32}) do io.write ([[ void agar_gui_widget_set_uint]]..ts(value)..[[ (AG_Widget *w, const char *binding, Uint]]..ts(value)..[[ val) { AG_SetUint]]..ts(value)..[[ (w, binding, val); } void agar_gui_widget_set_int]]..ts(value)..[[ (AG_Widget *w, const char *binding, Sint]]..ts(value)..[[ val) { AG_SetSint]]..ts(value)..[[ (w, binding, val); } ]]) end
apache-2.0
jshackley/darkstar
scripts/zones/Korroloka_Tunnel/npcs/Excavation_Point.lua
29
1117
----------------------------------- -- Area: Korroloka Tunnel -- NPC: Excavation Point ----------------------------------- package.loaded["scripts/zones/Korroloka_Tunnel/TextIDs"] = nil; ------------------------------------- require("scripts/globals/excavation"); require("scripts/zones/Korroloka_Tunnel/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) startExcavation(player,player:getZoneID(),npc,trade,0x0000); end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(MINING_IS_POSSIBLE_HERE,605); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
jshackley/darkstar
scripts/globals/spells/bluemagic/flying_hip_press.lua
27
1410
----------------------------------------- -- Spell: Flying Hip Press -- Deals wind damage to enemies within range -- Spell cost: 125 MP -- Monster Type: Beastmen -- Spell Type: Magical (Wind) -- Blue Magic Points: 3 -- Stat Bonus: AGI+1 -- Level: 58 -- Casting Time: 5.75 seconds -- Recast Time: 34.5 seconds -- Magic Bursts On: Detonation, Fragmentation, and Light -- Combos: Max HP 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 params = {}; params.multiplier = 2.775; params.tMultiplier = 2.912; params.duppercap = 58; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.2; params.mnd_wsc = 0.5; params.chr_wsc = 0.2; damage = BlueMagicalSpell(caster, target, spell, params, MND_BASED); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
jshackley/darkstar
scripts/zones/Western_Adoulin/Zone.lua
33
1246
----------------------------------- -- -- Zone: Western Adoulin -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Western_Adoulin/TextIDs"] = nil; require("scripts/zones/Western_Adoulin/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-142,4,-18,4); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
jshackley/darkstar
scripts/zones/Upper_Jeuno/npcs/Mejuone.lua
37
1157
----------------------------------- -- Area: Upper Jeuno -- NPC: Mejuone -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,MEJUONE_SHOP_DIALOG); stock = {0x11C1,62, -- Gysahl Greens 0x0348,7, -- Chocobo Feather 0x439B,9} -- Dart 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
Ombridride/minetest-minetestforfun-server
mods/watershed/init.lua
3
24366
-- Parameters local YMIN = -33000 -- Approximate base of realm stone local YMAX = 33000 -- Approximate top of atmosphere / mountains / floatlands local TERCEN = -128 -- Terrain zero level, average seabed local YWAT = 1 -- Sea surface y local YSAV = 5 -- Average sandline y, dune grasses above this local SAMP = 3 -- Sandline amplitude local YCLOMIN = 207 -- Minimum height of mod clouds local CLOUDS = true -- Mod clouds? local TERSCA = 512 -- Vertical terrain scale local XLSAMP = 0.1 -- Extra large scale height variation amplitude local BASAMP = 0.3 -- Base terrain amplitude local MIDAMP = 0.1 -- Mid terrain amplitude local CANAMP = 0.4 -- Canyon terrain maximum amplitude local ATANAMP = 1.1 -- Arctan function amplitude, -- smaller = more and larger floatlands above ridges local BLENEXP = 2 -- Terrain blend exponent local TSTONE = 0.02 -- Density threshold for stone, depth of soil at TERCEN local TRIVER = -0.028 -- Densitybase threshold for river surface local TRSAND = -0.035 -- Densitybase threshold for river sand local TSTREAM = -0.004 -- Densitymid threshold for stream surface local TSSAND = -0.005 -- Densitymid threshold for stream sand local TLAVA = 2 -- Maximum densitybase threshold for lava, -- small because grad is non-linear local TFIS = 0.01 -- Fissure threshold, controls width local TSEAM = 0.2 -- Seam threshold, width of seams local ORESCA = 512 -- Seam system vertical scale local ORETHI = 0.002 -- Ore seam thickness tuner local BERGDEP = 32 -- Maximum iceberg depth local TFOG = -0.04 -- Fog top densitymid threshold local biomeparams = { HITET = 0.35, -- High temperature threshold LOTET = -0.35, -- Low .. ICETET = -0.7, -- Ice .. HIHUT = 0.35, -- High humidity threshold LOHUT = -0.35, -- Low .. BLEND = 0.02, -- Biome blend randomness } local flora = { PINCHA = 36, -- Pine tree 1/x chance per node APTCHA = 36, -- Appletree FLOCHA = 289, -- Flower GRACHA = 36, -- Grassland grasses JUTCHA = 16, -- Jungletree JUGCHA = 16, -- Junglegrass CACCHA = 800, -- Cactus CACCHA_DRYGRASS = 1600, DRYCHA = 150, -- Dry shrub ACACHA = 1369, -- Acacia tree GOGCHA = 9, -- Golden grass PAPCHA = 4, -- Papyrus DUGCHA = 16, -- Dune grass } local np = { -- pack it in a single table to avoid "function has more than 60 upvalues" -- 3D noises -- 3D noise for terrain terrain = { offset = 0, scale = 1, spread = {x = 384, y = 192, z = 384}, seed = 593, octaves = 5, persist = 0.67 }, -- 3D noise for fissures fissure = { offset = 0, scale = 1, spread = {x = 256, y = 512, z = 256}, seed = 20099, octaves = 5, persist = 0.5 }, -- 3D noise for ore seam networks seam = { offset = 0, scale = 1, spread = {x = 512, y = 512, z = 512}, seed = -992221, octaves = 2, persist = 0.5 }, -- 3D noise for rock strata inclination strata = { offset = 0, scale = 1, spread = {x = 512, y = 512, z = 512}, seed = 92219, octaves = 3, persist = 0.5 }, -- 3D noises for caves, from Valleys Mapgen mod by Gael-de-Sailly cave1 = { offset = 0, scale = 1, spread = {x = 32, y = 32, z = 32}, seed = -4640, octaves = 4, persist = 0.5 }, cave2 = { offset = 0, scale = 1, seed = 8804, spread = {x = 32, y = 32, z = 32}, octaves = 4, persist = 0.5 }, cave3 = { offset = 0, scale = 1, seed = -4780, spread = {x = 32, y = 32, z = 32}, octaves = 4, persist = 0.5 }, cave4 = { offset = 0, scale = 1, seed = -9969, spread = {x = 32, y = 32, z = 32}, octaves = 4, persist = 0.5 }, -- 2D noises -- 2D noise for mid terrain / streambed height mid = { offset = 0, scale = 1, spread = {x = 768, y = 768, z = 768}, seed = 85546, octaves = 5, persist = 0.5 }, -- 2D noise for base terrain / riverbed height base = { offset = 0, scale = 1, spread = {x = 1024, y = 1024, z = 1024}, seed = 8890, octaves = 3, persist = 0.33 }, -- 2D noise for extra large scale height variation xlscale = { offset = 0, scale = 1, spread = {x = 4096, y = 4096, z = 4096}, seed = -72, octaves = 3, persist = 0.33 }, -- 2D noise for magma surface magma = { offset = 0, scale = 1, spread = {x = 128, y = 128, z = 128}, seed = -13, octaves = 2, persist = 0.5 }, -- 2D noise for temperature, the same than in Plantlife and Snowdrift temp = { offset = 0, scale = 1, spread = {x = 256, y = 256, z = 256}, seed = 112, octaves = 3, persist = 0.5 }, -- 2D noise for humidity humid = { offset = 0, scale = 1, spread = {x = 256, y = 256, z = 256}, seed = 72384, octaves = 4, persist = 0.66 }, } -- Do files dofile(minetest.get_modpath("watershed") .. "/nodes.lua") dofile(minetest.get_modpath("watershed") .. "/functions.lua") -- Initialize 3D and 2D noise objects to nil local nobj_terrain = nil local nobj_fissure = nil local nobj_temp = nil local nobj_humid = nil local nobj_seam = nil local nobj_strata = nil local nobj_cave1 = nil local nobj_cave2 = nil local nobj_cave3 = nil local nobj_cave4 = nil local nobj_mid = nil local nobj_base = nil local nobj_xlscale = nil local nobj_magma = nil -- Localise noise buffers local nbuf_terrain = {} local nbuf_fissure = {} local nbuf_temp = {} local nbuf_humid = {} local nbuf_seam = {} local nbuf_strata = {} local nbuf_cave1 local nbuf_cave2 local nbuf_cave3 local nbuf_cave4 local nbuf_mid = {} local nbuf_base = {} local nbuf_xlscale = {} local nbuf_magma = {} -- Mapchunk generation function local global_seed function watershed_chunkgen(x0, y0, z0, x1, y1, z1, area, data) local c_air = minetest.get_content_id("air") local c_ignore = minetest.get_content_id("ignore") local c_water = minetest.get_content_id("default:water_source") local c_sand = minetest.get_content_id("default:sand") local c_desand = minetest.get_content_id("default:desert_sand") local c_snowblock = minetest.get_content_id("default:snowblock") local c_ice = minetest.get_content_id("default:ice") local c_dirtsnow = minetest.get_content_id("default:dirt_with_snow") local c_jungrass = minetest.get_content_id("default:junglegrass") local c_dryshrub = minetest.get_content_id("default:dry_shrub") local c_danwhi = minetest.get_content_id("flowers:dandelion_white") local c_danyel = minetest.get_content_id("flowers:dandelion_yellow") local c_rose = minetest.get_content_id("flowers:rose") local c_tulip = minetest.get_content_id("flowers:tulip") local c_geranium = minetest.get_content_id("flowers:geranium") local c_viola = minetest.get_content_id("flowers:viola") local c_stodiam = minetest.get_content_id("default:stone_with_diamond") local c_mese = minetest.get_content_id("default:mese") local c_stogold = minetest.get_content_id("default:stone_with_gold") local c_stocopp = minetest.get_content_id("default:stone_with_copper") local c_stoiron = minetest.get_content_id("default:stone_with_iron") local c_stocoal = minetest.get_content_id("default:stone_with_coal") local c_sandstone = minetest.get_content_id("default:sandstone") local c_gravel = minetest.get_content_id("default:gravel") local c_clay = minetest.get_content_id("default:clay") local c_grass5 = minetest.get_content_id("default:grass_5") local c_obsidian = minetest.get_content_id("default:obsidian") local c_wsfreshwater = minetest.get_content_id("watershed:freshwater") local c_wsstone = minetest.get_content_id("watershed:stone") local c_wsredstone = minetest.get_content_id("watershed:redstone") local c_wsgrass = minetest.get_content_id("watershed:grass") local c_wsdrygrass = minetest.get_content_id("watershed:drygrass") local c_wsgoldengrass = minetest.get_content_id("watershed:goldengrass") local c_wsdirt = minetest.get_content_id("watershed:dirt") local c_wspermafrost = minetest.get_content_id("watershed:permafrost") local c_wslava = minetest.get_content_id("watershed:lava") local c_wsfreshice = minetest.get_content_id("watershed:freshice") local c_wscloud = minetest.get_content_id("air") -- disable clouds local c_wsicydirt = minetest.get_content_id("watershed:icydirt") -- perlinmap stuff local sidelen = x1 - x0 + 1 local sqr_sidelen = sidelen ^ 2 local chulensxyz = {x = sidelen, y = sidelen + 2, z = sidelen} local chulensxz = {x = sidelen, y = sidelen, z = 1} local minposxyz = {x = x0, y = y0 - 1, z = z0} local minposxz = {x = x0, y = z0} -- 3D and 2D noise objects created once on first mapchunk generation only nobj_terrain = nobj_terrain or minetest.get_perlin_map(np.terrain, chulensxyz) nobj_fissure = nobj_fissure or minetest.get_perlin_map(np.fissure, chulensxyz) nobj_temp = nobj_temp or minetest.get_perlin_map(np.temp, chulensxyz) nobj_humid = nobj_humid or minetest.get_perlin_map(np.humid, chulensxyz) nobj_seam = nobj_seam or minetest.get_perlin_map(np.seam, chulensxyz) nobj_strata = nobj_strata or minetest.get_perlin_map(np.strata, chulensxyz) nobj_cave1 = nobj_cave1 or minetest.get_perlin_map(np.cave1, chulensxyz) nobj_cave2 = nobj_cave2 or minetest.get_perlin_map(np.cave2, chulensxyz) nobj_cave3 = nobj_cave3 or minetest.get_perlin_map(np.cave3, chulensxyz) nobj_cave4 = nobj_cave4 or minetest.get_perlin_map(np.cave4, chulensxyz) nobj_mid = nobj_mid or minetest.get_perlin_map(np.mid, chulensxz) nobj_base = nobj_base or minetest.get_perlin_map(np.base, chulensxz) nobj_xlscale = nobj_xlscale or minetest.get_perlin_map(np.xlscale, chulensxz) nobj_magma = nobj_magma or minetest.get_perlin_map(np.magma, chulensxz) -- 3D and 2D perlinmaps created per mapchunk local nvals_terrain = nobj_terrain:get3dMap_flat(minposxyz) local nvals_fissure = nobj_fissure:get3dMap_flat(minposxyz) local nvals_temp = nobj_temp :get2dMap_flat(minposxz) local nvals_humid = nobj_humid :get2dMap_flat(minposxz) local nvals_seam = nobj_seam :get3dMap_flat(minposxyz) local nvals_strata = nobj_strata :get3dMap_flat(minposxyz) local nvals_cave1 = nobj_cave1 :get3dMap_flat(minposxyz) local nvals_cave2 = nobj_cave2 :get3dMap_flat(minposxyz) local nvals_cave3 = nobj_cave3 :get3dMap_flat(minposxyz) local nvals_cave4 = nobj_cave4 :get3dMap_flat(minposxyz) local nvals_mid = nobj_mid :get2dMap_flat(minposxz) local nvals_base = nobj_base :get2dMap_flat(minposxz) local nvals_xlscale = nobj_xlscale:get2dMap_flat(minposxz) local nvals_magma = nobj_magma :get2dMap_flat(minposxz) -- ungenerated chunk below? local viu = area:index(x0, y0 - 1, z0) local ungen = data[viu] == c_ignore -- mapgen loop local nixyz = 1 -- 3D and 2D perlinmap indexes local nixz = 1 local stable = {} -- stability table of true/false. -- is node supported from below by 2 stone or nodes on 2 stone? local under = {} -- biome table. -- biome number of previous fine material placed in column for z = z0, z1 do for y = y0 - 1, y1 + 1 do local vi = area:index(x0, y, z) local viu = area:index(x0, y - 1, z) for x = x0, x1 do local si = x - x0 + 1 -- stable, under tables index -- noise values for node local n_absterrain = math.abs(nvals_terrain[nixyz]) local n_fissure = nvals_fissure[nixyz] local n_seam = nvals_seam[nixyz] local n_strata = nvals_strata[nixyz] local n_cave1 = nvals_cave1[nixyz] local n_cave2 = nvals_cave2[nixyz] local n_cave3 = nvals_cave3[nixyz] local n_cave4 = nvals_cave4[nixyz] local n_absmid = math.abs(nvals_mid[nixz]) local n_absbase = math.abs(nvals_base[nixz]) local n_xlscale = nvals_xlscale[nixz] local n_magma = nvals_magma[nixz] local n_temp = nvals_temp[nixz] local n_humid = nvals_humid[nixz] -- get densities local n_invbase = (1 - n_absbase) local terblen = (math.max(n_invbase, 0)) ^ BLENEXP local grad = math.atan((TERCEN - y) / TERSCA) * ATANAMP local densitybase = n_invbase * BASAMP + n_xlscale * XLSAMP + grad local densitymid = n_absmid * MIDAMP + densitybase local canexp = 0.5 + terblen * 0.5 local canamp = terblen * CANAMP local density = n_absterrain ^ canexp * canamp * n_absmid + densitymid -- other values local triver = TRIVER * n_absbase -- river threshold local trsand = TRSAND * n_absbase -- river sand local tstream = TSTREAM * (1 - n_absmid) -- stream threshold local tssand = TSSAND * (1 - n_absmid) -- stream sand local tstone = TSTONE * (1 + grad) -- stone threshold local tlava = TLAVA * (1 - n_magma ^ 4 * terblen ^ 16 * 0.6) -- lava threshold local ysand = YSAV + n_fissure * SAMP + math.random() * 2 -- sandline local bergdep = math.abs(n_seam) * BERGDEP -- iceberg depth local nofis = false -- set fissure bool if math.abs(n_fissure) >= TFIS and n_cave1 ^ 2 + n_cave2 ^ 2 + n_cave3 ^ 2 + n_cave4 ^ 2 >= 0.07 then -- from Valleys Mapgen nofis = true end local biome = false -- select biome for node if n_temp < biomeparams.LOTET + (math.random() - 0.5) * biomeparams.BLEND then if n_humid < biomeparams.LOHUT + (math.random() - 0.5) * biomeparams.BLEND then biome = 1 -- tundra elseif n_humid > biomeparams.HIHUT + (math.random() - 0.5) * biomeparams.BLEND then biome = 3 -- taiga else biome = 2 -- snowy plains end elseif n_temp > biomeparams.HITET + (math.random() - 0.5) * biomeparams.BLEND then if n_humid < biomeparams.LOHUT + (math.random() - 0.5) * biomeparams.BLEND then biome = 7 -- desert elseif n_humid > biomeparams.HIHUT + (math.random() - 0.5) * biomeparams.BLEND then biome = 9 -- rainforest else biome = 8 -- savanna end else if n_humid < biomeparams.LOHUT then biome = 4 -- dry grassland elseif n_humid > biomeparams.HIHUT then biome = 6 -- deciduous forest else biome = 5 -- grassland end end -- overgeneration and in-chunk generation if y == y0 - 1 then -- node layer below chunk, initialise tables under[si] = 0 if ungen then if nofis and density >= 0 then -- if node solid stable[si] = 2 else stable[si] = 0 end else -- scan top layer of chunk below local nodid = data[vi] if nodid == c_wsstone or nodid == c_wsredstone or nodid == c_wsdirt or nodid == c_wspermafrost or nodid == c_sand or nodid == c_desand or nodid == c_mese or nodid == c_stodiam or nodid == c_stogold or nodid == c_stocopp or nodid == c_stoiron or nodid == c_stocoal or nodid == c_sandstone or nodid == c_gravel or nodid == c_clay or nodid == c_obsidian then stable[si] = 2 else stable[si] = 0 end end elseif y >= y0 and y <= y1 then -- chunk -- add nodes and flora if densitybase >= tlava then -- lava if densitybase >= 0 then data[vi] = c_wslava end stable[si] = 0 under[si] = 0 elseif densitybase >= tlava - math.min(0.6 + density * 6, 0.6) and density < tstone then -- obsidian data[vi] = c_obsidian stable[si] = 1 under[si] = 0 elseif density >= tstone and nofis -- stone cut by fissures or (density >= tstone and density < TSTONE * 1.2 and y <= YWAT) -- stone around water or (density >= tstone and density < TSTONE * 1.2 and densitybase >= triver ) -- stone around river or (density >= tstone and density < TSTONE * 1.2 and densitymid >= tstream ) then -- stone around stream local densitystr = n_strata * 0.25 + (TERCEN - y) / ORESCA -- periodic strata 'density' local densityper = densitystr - math.floor(densitystr) if (densityper >= 0.05 and densityper <= 0.09) -- sandstone strata or (densityper >= 0.25 and densityper <= 0.28) or (densityper >= 0.45 and densityper <= 0.47) or (densityper >= 0.74 and densityper <= 0.76) or (densityper >= 0.77 and densityper <= 0.79) or (densityper >= 0.84 and densityper <= 0.87) or (densityper >= 0.95 and densityper <= 0.98) then if y > -84 and (y >= -80 or math.random() > 0.5) then data[vi] = c_sandstone else data[vi] = c_wsstone end elseif biome == 7 and density < TSTONE * 3 then -- desert stone as surface layer data[vi] = c_wsredstone elseif math.abs(n_seam) < TSEAM then -- ore seams if densityper >= 0.55 and densityper <= 0.55 + ORETHI * 2 then data[vi] = c_gravel else data[vi] = c_wsstone end else data[vi] = c_wsstone end stable[si] = stable[si] + 1 under[si] = 0 -- fine materials elseif density >= 0 and density < tstone and stable[si] >= 2 then -- fine materials if y == YWAT - 2 and math.abs(n_temp) < 0.05 then -- clay data[vi] = c_clay elseif y <= ysand then -- seabed/beach/dune sand not cut by fissures data[vi] = c_sand under[si] = 10 -- beach/dunes elseif densitybase >= trsand + math.random() * 0.001 then -- river sand data[vi] = c_sand under[si] = 11 -- riverbank papyrus elseif densitymid >= tssand + math.random() * 0.001 then -- stream sand data[vi] = c_sand under[si] = 0 elseif nofis then -- fine materials cut by fissures if biome == 1 then data[vi] = c_wspermafrost under[si] = 1 -- tundra elseif biome == 2 then data[vi] = c_wsdirt under[si] = 2 -- snowy plains elseif biome == 3 then data[vi] = c_wsdirt under[si] = 3 -- taiga elseif biome == 4 then data[vi] = c_wsdirt under[si] = 4 -- dry grassland elseif biome == 5 then data[vi] = c_wsdirt under[si] = 5 -- grassland elseif biome == 6 then data[vi] = c_wsdirt under[si] = 6 -- forest elseif biome == 7 then data[vi] = c_desand under[si] = 7 -- desert elseif biome == 8 then data[vi] = c_wsdirt under[si] = 8 -- savanna elseif biome == 9 then data[vi] = c_wsdirt under[si] = 9 -- rainforest end else -- fissure stable[si] = 0 under[si] = 0 end elseif y >= YWAT - bergdep and y <= YWAT + bergdep / 8 -- icesheet and n_temp < biomeparams.ICETET and density < tstone and nofis then data[vi] = c_ice under[si] = 12 stable[si] = 0 elseif y <= YWAT and density < tstone then -- sea water data[vi] = c_water under[si] = 0 stable[si] = 0 -- river water not in fissures elseif densitybase >= triver and density < tstone then if n_temp < biomeparams.ICETET then data[vi] = c_wsfreshice else data[vi] = c_wsfreshwater end stable[si] = 0 under[si] = 0 -- stream water not in fissures elseif densitymid >= tstream and density < tstone then if n_temp < biomeparams.ICETET then data[vi] = c_wsfreshice else data[vi] = c_wsfreshwater end stable[si] = 0 under[si] = 0 -- air above surface node elseif density < 0 and y >= YWAT and under[si] ~= 0 then local fnoise = n_fissure -- noise for flower colours if under[si] == 1 then data[viu] = c_wsicydirt if math.random(flora.DRYCHA) == 2 then data[vi] = c_dryshrub end elseif under[si] == 2 then data[viu] = c_dirtsnow data[vi] = c_snowblock elseif under[si] == 3 then if math.random(flora.PINCHA) == 2 then watershed_pinetree(x, y, z, area, data) else data[viu] = c_dirtsnow data[vi] = c_snowblock end elseif under[si] == 4 then data[viu] = c_wsdrygrass if math.random(flora.CACCHA_DRYGRASS) == 2 then watershed_cactus(x, y, z, area, data) elseif math.random(flora.DRYCHA) == 2 then data[vi] = c_dryshrub end elseif under[si] == 5 then data[viu] = c_wsgrass if math.random(flora.FLOCHA) == 2 then watershed_flower(data, vi, fnoise) elseif math.random(flora.GRACHA) == 2 then data[vi] = c_grass5 end elseif under[si] == 6 then if math.random(flora.APTCHA) == 2 then watershed_appletree(x, y, z, area, data) else data[viu] = c_wsgrass if math.random(flora.FLOCHA) == 2 then watershed_flower(data, vi, fnoise) elseif math.random(flora.GRACHA) == 2 then data[vi] = c_grass5 end end elseif under[si] == 7 and n_temp < biomeparams.HITET + 0.1 then if math.random(flora.CACCHA) == 2 then watershed_cactus(x, y, z, area, data) elseif math.random(flora.DRYCHA) == 2 then data[vi] = c_dryshrub end elseif under[si] == 8 then if math.random(flora.ACACHA) == 2 then watershed_acaciatree(x, y, z, area, data) else data[viu] = c_wsdrygrass if math.random(flora.GOGCHA) == 2 then data[vi] = c_wsgoldengrass end end elseif under[si] == 9 then if math.random(flora.JUTCHA) == 2 then watershed_jungletree(x, y, z, area, data) else data[viu] = c_wsgrass if math.random(flora.JUGCHA) == 2 then data[vi] = c_jungrass end end elseif under[si] == 10 then -- dunes if math.random(flora.DUGCHA) == 2 and y > YSAV and biome >= 4 then data[vi] = c_wsgoldengrass end elseif under[si] == 11 and n_temp > biomeparams.HITET then -- hot biome riverbank if math.random(flora.PAPCHA) == 2 then watershed_papyrus(x, y, z, area, data) end -- snowy iceberg elseif under[si] == 12 and n_humid > biomeparams.LOHUT + (math.random() - 0.5) * biomeparams.BLEND then data[vi] = c_snowblock end stable[si] = 0 under[si] = 0 else -- air stable[si] = 0 under[si] = 0 end elseif y == y1 + 1 then -- plane of nodes above chunk if density < 0 and y >= YWAT and under[si] ~= 0 then -- if air above fine materials if under[si] == 1 then -- add surface nodes to chunk top layer data[viu] = c_wsicydirt elseif under[si] == 2 then data[viu] = c_dirtsnow data[vi] = c_snowblock -- snowblocks in chunk above elseif under[si] == 3 then data[viu] = c_dirtsnow data[vi] = c_snowblock elseif under[si] == 4 then data[viu] = c_wsdrygrass elseif under[si] == 5 then data[viu] = c_wsgrass elseif under[si] == 6 then data[viu] = c_wsgrass elseif under[si] == 8 then data[viu] = c_wsdrygrass elseif under[si] == 9 then data[viu] = c_wsgrass end end end nixyz = nixyz + 1 nixz = nixz + 1 vi = vi + 1 viu = viu + 1 end nixz = nixz - sidelen end nixz = nixz + sidelen end darkage_mapgen(data, area, {x=x0, y=y0, z=z0}, {x=x1, y=y1, z=z1}, global_seed) -- Generate darkage ores end -- On generated function minetest.register_on_generated(function(minp, maxp, seed) global_seed = seed if minp.y < YMIN or maxp.y > YMAX then return end local t1 = os.clock() local x1 = maxp.x local y1 = maxp.y local z1 = maxp.z local x0 = minp.x local y0 = minp.y local z0 = minp.z minetest.log("action", "[watershed] generate mapchunk minp (" .. x0 .. " " .. y0 .. " " .. z0 .. ")") local vm, emin, emax = minetest.get_mapgen_object("voxelmanip") local area = VoxelArea:new{MinEdge = emin, MaxEdge = emax} local data = vm:get_data() watershed_chunkgen(x0, y0, z0, x1, y1, z1, area, data) vm:set_data(data) minetest.generate_ores(vm, minp, maxp) minetest.generate_decorations(vm, minp, maxp) vm:set_lighting({day = 0, night = 0}) vm:calc_lighting() vm:write_to_map(data) vm:update_liquids() local chugent = math.ceil((os.clock() - t1) * 1000) minetest.log("action", "[watershed] " .. chugent .. " ms") end) default.register_ores() farming.register_mgv6_decorations() -- cherry tree minetest.register_decoration({ deco_type = "simple", place_on = "default:dirt_with_grass", sidelen = 16, noise_params = { offset = 0, scale = 0.005, spread = {x=100, y=100, z=100}, seed = 278, octaves = 2, persist = 0.7 }, decoration = "default:mg_cherry_sapling", height = 1, })
unlicense
jshackley/darkstar
scripts/globals/items/boneworkers_belt.lua
30
1207
----------------------------------------- -- ID: 15449 -- Item: Boneworker's belt -- Enchantment: Synthesis image support -- 2Min, All Races ----------------------------------------- -- Enchantment: Synthesis image support -- Duration: 2Min -- Bonecraft Skill +3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_BONECRAFT_IMAGERY) == true) then result = 241; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_BONECRAFT_IMAGERY,3,0,120); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_SKILL_BON, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_SKILL_BON, 1); end;
gpl-3.0
jshackley/darkstar
scripts/zones/Castle_Oztroja_[S]/Zone.lua
28
1334
----------------------------------- -- -- Zone: Castle_Oztroja_[S] (99) -- ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Castle_Oztroja_[S]/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(-239.447,-1.813,-19.98,250); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
drhelius/Gearboy
platforms/ios/dependencies/SDL-2.0.4-9174/premake/util/sdl_gen_config.lua
7
2700
-- Copyright (C) 1997-2014 Sam Lantinga <slouken@libsdl.org> -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely. -- -- Meta-build system using premake created and maintained by -- Benjamin Henning <b.henning@digipen.edu> --[[ sdl_gen_config.lua Given a series of set configuration values from the project definitions, this file contains a series of functions that generate valid preprocessor definitions to enable or disable various features of the SDL2 library. These definitions are pasted into a template SDL config header file, which is then saved in the local directory and referenced to in generated project files. This file depends on sdl_file.lua. ]] -- The line that must exist in the template file in order to properly paste -- the generated definitions. local searchKey = "/%* Paste generated code here %*/\n" local configFile, templateFileContents local insertLocation -- This function begins config header generation given the name of the generated -- file and the name of the template file to use. function startGeneration(file, template) configFile = fileopen(file, "wt") templateFileContents = readfile(template, "rt") insertLocation = templateFileContents:find(searchKey) if insertLocation then configFile:write(templateFileContents:sub(1, insertLocation - 1)) end end -- Adds a table of configuration values to the generated file. Each -- configuration line is wrapped around a preprocessor definition check, so they -- can be manually overwritten by the developer if necessary. The definition -- pastes string versions of both the key and the value on the line, where -- either is allowed to be empty. That means the table stores key-value pairs. function addConfig(tbl) -- if no insert location, don't paste anything if not insertLocation then return end for k,v in pairs(tbl) do configFile:print(0, "#ifndef " .. k) configFile:print(0, "#define " .. tostring(k) .. " " .. tostring(v)) configFile:print(0, "#endif") end end -- Finishes the generation and writes the remains of the template file into the -- generated config file. function endGeneration() if insertLocation then configFile:write(templateFileContents:sub(insertLocation + #searchKey - 2)) else -- write entire file since nothing is being pasted configFile:write(templateFileContents) end configFile:close() end
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/weaponskills/freezebite.lua
6
1231
----------------------------------- -- Freezebite -- Great Sword weapon skill -- Skill Level: 100 -- Delivers an ice elemental attack. Damage varies with TP. -- Aligned with the Snow Gorget & Breeze Gorget. -- Aligned with the Snow Belt & Breeze Belt. -- Element: Ice -- Modifiers: STR:30% ; INT:20% -- 100%TP 200%TP 300%TP -- 1.00 1.50 3.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function OnUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 3; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.2; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
teahouse/FWServer
skynet/lualib/skynet/manager.lua
72
1923
local skynet = require "skynet" local c = require "skynet.core" function skynet.launch(...) local addr = c.command("LAUNCH", table.concat({...}," ")) if addr then return tonumber("0x" .. string.sub(addr , 2)) end end function skynet.kill(name) if type(name) == "number" then skynet.send(".launcher","lua","REMOVE",name, true) name = skynet.address(name) end c.command("KILL",name) end function skynet.abort() c.command("ABORT") end local function globalname(name, handle) local c = string.sub(name,1,1) assert(c ~= ':') if c == '.' then return false end assert(#name <= 16) -- GLOBALNAME_LENGTH is 16, defined in skynet_harbor.h assert(tonumber(name) == nil) -- global name can't be number local harbor = require "skynet.harbor" harbor.globalname(name, handle) return true end function skynet.register(name) if not globalname(name) then c.command("REG", name) end end function skynet.name(name, handle) if not globalname(name, handle) then c.command("NAME", name .. " " .. skynet.address(handle)) end end local dispatch_message = skynet.dispatch_message function skynet.forward_type(map, start_func) c.callback(function(ptype, msg, sz, ...) local prototype = map[ptype] if prototype then dispatch_message(prototype, msg, sz, ...) else dispatch_message(ptype, msg, sz, ...) c.trash(msg, sz) end end, true) skynet.timeout(0, function() skynet.init_service(start_func) end) end function skynet.filter(f ,start_func) c.callback(function(...) dispatch_message(f(...)) end) skynet.timeout(0, function() skynet.init_service(start_func) end) end function skynet.monitor(service, query) local monitor if query then monitor = skynet.queryservice(true, service) else monitor = skynet.uniqueservice(true, service) end assert(monitor, "Monitor launch failed") c.command("MONITOR", string.format(":%08x", monitor)) return monitor end return skynet
mit
FFXIOrgins/FFXIOrgins
scripts/zones/Beaucedine_Glacier/npcs/Luck_Rune.lua
34
1089
----------------------------------- -- Area: Beaucedine Glacier -- NPC: Luck Rune -- Involved in Quest: Mhaura Fortune -- @pos 70.736 -37.778 149.624 111 ----------------------------------- package.loaded["scripts/zones/Beaucedine_Glacier/TextIDs"] = nil; ------------------------------------- require("scripts/zones/Beaucedine_Glacier/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_THE_ORDINARY); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
sjznxd/luci-0.11-aa
applications/luci-pbx/luasrc/model/cbi/pbx-advanced.lua
29
14365
--[[ 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 appname = "PBX" modulename = "pbx-advanced" defaultbindport = 5060 defaultrtpstart = 19850 defaultrtpend = 19900 -- Returns all the network related settings, including a constructed RTP range function get_network_info() externhost = m.uci:get(modulename, "advanced", "externhost") ipaddr = m.uci:get("network", "lan", "ipaddr") bindport = m.uci:get(modulename, "advanced", "bindport") rtpstart = m.uci:get(modulename, "advanced", "rtpstart") rtpend = m.uci:get(modulename, "advanced", "rtpend") if bindport == nil then bindport = defaultbindport end if rtpstart == nil then rtpstart = defaultrtpstart end if rtpend == nil then rtpend = defaultrtpend end if rtpstart == nil or rtpend == nil then rtprange = nil else rtprange = rtpstart .. "-" .. rtpend end return bindport, rtprange, ipaddr, externhost end -- If not present, insert empty rules in the given config & section named PBX-SIP and PBX-RTP function insert_empty_sip_rtp_rules(config, section) -- Add rules named PBX-SIP and PBX-RTP if not existing found_sip_rule = false found_rtp_rule = false m.uci:foreach(config, section, function(s1) if s1._name == 'PBX-SIP' then found_sip_rule = true elseif s1._name == 'PBX-RTP' then found_rtp_rule = true end end) if found_sip_rule ~= true then newrule=m.uci:add(config, section) m.uci:set(config, newrule, '_name', 'PBX-SIP') end if found_rtp_rule ~= true then newrule=m.uci:add(config, section) m.uci:set(config, newrule, '_name', 'PBX-RTP') end end -- Delete rules in the given config & section named PBX-SIP and PBX-RTP function delete_sip_rtp_rules(config, section) -- Remove rules named PBX-SIP and PBX-RTP commit = false m.uci:foreach(config, section, function(s1) if s1._name == 'PBX-SIP' or s1._name == 'PBX-RTP' then m.uci:delete(config, s1['.name']) commit = true end end) -- If something changed, then we commit the config. if commit == true then m.uci:commit(config) end end -- Deletes QoS rules associated with this PBX. function delete_qos_rules() delete_sip_rtp_rules ("qos", "classify") end function insert_qos_rules() -- Insert empty PBX-SIP and PBX-RTP rules if not present. insert_empty_sip_rtp_rules ("qos", "classify") -- Get the network information bindport, rtprange, ipaddr, externhost = get_network_info() -- Iterate through the QoS rules, and if there is no other rule with the same port -- range at the priority service level, insert this rule. commit = false m.uci:foreach("qos", "classify", function(s1) if s1._name == 'PBX-SIP' then if s1.ports ~= bindport or s1.target ~= "Priority" or s1.proto ~= "udp" then m.uci:set("qos", s1['.name'], "ports", bindport) m.uci:set("qos", s1['.name'], "proto", "udp") m.uci:set("qos", s1['.name'], "target", "Priority") commit = true end elseif s1._name == 'PBX-RTP' then if s1.ports ~= rtprange or s1.target ~= "Priority" or s1.proto ~= "udp" then m.uci:set("qos", s1['.name'], "ports", rtprange) m.uci:set("qos", s1['.name'], "proto", "udp") m.uci:set("qos", s1['.name'], "target", "Priority") commit = true end end end) -- If something changed, then we commit the qos config. if commit == true then m.uci:commit("qos") end end -- This function is a (so far) unsuccessful attempt to manipulate the firewall rules from here -- Need to do more testing and eventually move to this mode. function maintain_firewall_rules() -- Get the network information bindport, rtprange, ipaddr, externhost = get_network_info() commit = false -- Only if externhost is set, do we control firewall rules. if externhost ~= nil and bindport ~= nil and rtprange ~= nil then -- Insert empty PBX-SIP and PBX-RTP rules if not present. insert_empty_sip_rtp_rules ("firewall", "rule") -- Iterate through the firewall rules, and if the dest_port and dest_ip setting of the\ -- SIP and RTP rule do not match what we want configured, set all the entries in the rule\ -- appropriately. m.uci:foreach("firewall", "rule", function(s1) if s1._name == 'PBX-SIP' then if s1.dest_port ~= bindport then m.uci:set("firewall", s1['.name'], "dest_port", bindport) m.uci:set("firewall", s1['.name'], "src", "wan") m.uci:set("firewall", s1['.name'], "proto", "udp") m.uci:set("firewall", s1['.name'], "target", "ACCEPT") commit = true end elseif s1._name == 'PBX-RTP' then if s1.dest_port ~= rtprange then m.uci:set("firewall", s1['.name'], "dest_port", rtprange) m.uci:set("firewall", s1['.name'], "src", "wan") m.uci:set("firewall", s1['.name'], "proto", "udp") m.uci:set("firewall", s1['.name'], "target", "ACCEPT") commit = true end end end) else -- We delete the firewall rules if one or more of the necessary parameters are not set. sip_rule_name=nil rtp_rule_name=nil -- First discover the configuration names of the rules. m.uci:foreach("firewall", "rule", function(s1) if s1._name == 'PBX-SIP' then sip_rule_name = s1['.name'] elseif s1._name == 'PBX-RTP' then rtp_rule_name = s1['.name'] end end) -- Then, using the names, actually delete the rules. if sip_rule_name ~= nil then m.uci:delete("firewall", sip_rule_name) commit = true end if rtp_rule_name ~= nil then m.uci:delete("firewall", rtp_rule_name) commit = true end end -- If something changed, then we commit the firewall config. if commit == true then m.uci:commit("firewall") end end m = Map (modulename, translate("Advanced Settings"), translate("This section contains settings that do not need to be changed under \ normal circumstances. In addition, here you can configure your system \ for use with remote SIP devices, and resolve call quality issues by enabling \ the insertion of QoS rules.")) -- Recreate the voip server config, and restart necessary services after changes are commited -- to the advanced configuration. The firewall must restart because of "Remote Usage". function m.on_after_commit(self) -- Make sure firewall rules are in place maintain_firewall_rules() -- If insertion of QoS rules is enabled if m.uci:get(modulename, "advanced", "qos_enabled") == "yes" then insert_qos_rules() else delete_qos_rules() 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") luci.sys.call("/etc/init.d/firewall restart 1\>/dev/null 2\>/dev/null") end ----------------------------------------------------------------------------- s = m:section(NamedSection, "advanced", "settings", translate("Advanced Settings")) s.anonymous = true s:tab("general", translate("General Settings")) s:tab("remote_usage", translate("Remote Usage"), translatef("You can use your SIP devices/softphones with this system from a remote location \ as well, as long as your Internet Service Provider gives you a public IP. \ You will be able to call other local users for free (e.g. other Analog Telephone Adapters (ATAs)) \ and use your VoIP providers to make calls as if you were local to the PBX. \ After configuring this tab, go back to where users are configured and see the new \ Server and Port setting you need to configure the remote SIP devices with. Please note that if this \ PBX is not running on your router/gateway, you will need to configure port forwarding (NAT) on your \ router/gateway. Please forward the ports below (SIP port and RTP range) to the IP address of the \ device running this PBX.")) s:tab("qos", translate("QoS Settings"), translate("If you experience jittery or high latency audio during heavy downloads, you may want \ to enable QoS. QoS prioritizes traffic to and from your network for specified ports and IP \ addresses, resulting in better latency and throughput for sound in our case. If enabled below, \ a QoS rule for this service will be configured by the PBX automatically, but you must visit the \ QoS configuration page (Network->QoS) to configure other critical QoS settings like Download \ and Upload speed.")) ringtime = s:taboption("general", Value, "ringtime", translate("Number of Seconds to Ring"), translate("Set the number of seconds to ring users upon incoming calls before hanging up \ or going to voicemail, if the voicemail is installed and enabled.")) ringtime.default = 30 ua = s:taboption("general", Value, "useragent", translate("User Agent String"), translate("This is the name that the VoIP server will use to identify itself when \ registering to VoIP (SIP) providers. Some providers require this to a specific \ string matching a hardware SIP device.")) ua.default = appname h = s:taboption("remote_usage", Value, "externhost", translate("Domain/IP Address/Dynamic Domain"), translate("You can enter your domain name, external IP address, or dynamic domain name here \ Please keep in mind that if your IP address is dynamic and it changes your configuration \ will become invalid. Hence, it's recommended to set up Dynamic DNS in this case.")) h.datatype = "hostname" p = s:taboption("remote_usage", Value, "bindport", translate("External SIP Port"), translate("Pick a random port number between 6500 and 9500 for the service to listen on. \ Do not pick the standard 5060, because it is often subject to brute-force attacks. \ When finished, (1) click \"Save and Apply\", and (2) click the \"Restart VoIP Service\" \ button above. Finally, (3) look in the \"SIP Device/Softphone Accounts\" section for \ updated Server and Port settings for your SIP Devices/Softphones.")) p.datatype = "port" p = s:taboption("remote_usage", Value, "rtpstart", translate("RTP Port Range Start"), translate("RTP traffic carries actual voice packets. This is the start of the port range \ that will be used for setting up RTP communication. It's usually OK to leave this \ at the default value.")) p.datatype = "port" p.default = defaultrtpstart p = s:taboption("remote_usage", Value, "rtpend", translate("RTP Port Range End")) p.datatype = "port" p.default = defaultrtpend p = s:taboption("qos", ListValue, "qos_enabled", translate("Insert QoS Rules")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" return m
apache-2.0
Distroformo/SSO-English-patch
script/i18n/skill.lua
1
22229
--[[ @i18n skill ]] local _t = require("i18n").context("skill") module("STRING_TABLE") ---------------------- --生产相关 PRODUCE_SKILL_NEED_LEARN = _t"^ff0000您还没有学会生产技能," PRODUCE_SKILL_LEVEL = _t"%dLv." PRODUCE_SKILL_LEVEL_AND_EXP = _t"%dLv. (%d / %d)" PRODUCE_SKILL_NAME_LEVEL_AND_EXP = _t"%s:%dLv. (%d / %d)" PRODUCE_SKILL_LEARN_NAME_AND_LEVEL = _t"%s %d级可学习" PRODUCE_SKILL_NAME_AND_LEVEL = _t"%s %dLv." PRODUCE_SKILL_PROGRESS_EXP_AND_MAX = "%d/%d" PRODUCE_SKILL_PROGRESS_EXP_AND_MAX_FULL = _t"Full Lv." PRODUCE_CONSUME_ENERGY_SUFFICIENT = "^ffffff%d/^ffffff%d" PRODUCE_CONSUME_ENERGY_INSUFFICIENT = "^ffffff%d/^ff0000%d" PRODUCT_CONSUME_ENERGY_NAME = _t"消耗精力: %d" PRODUCE_CONSUME_ENERGY_HINT = _t"消耗精力值 %d 点,当前共有 %d 点精力\r精力上限为 %d 点\r每日上线的前两个小时自动回复精力" PRODUCE_SKILL_LEARNED = _t"Learned" PRODUCE_SKILL_UNLEARNED = _t"Unlearned" PRODUCE_SKILL_NOT_LEARN = _t"%s:^ff0000Not Learned" PRODUCE_EXP_ADD = "熟练度增加:%.1f" PRODUCE_RECIPE_NEED_SKILL_LEVEL = _t"Skill Lv. Needed:%d" PRODUCE_RECIPE_NAME_AND_PRODUCT_COUNT = "%s (%d)" PRODUCT_RECIPE_NAME_LOW = "^ff8000%s" PRODUCT_RECIPE_NAME_MEDIUM = "^ffffff%s" PRODUCT_RECIPE_NAME_HIGH = "^80ff00%s" PRODUCT_RECIPE_NAME_VERY_HIGH = "^c0c0c0%s" PRODUCE_VITALITY = _t"活力:%d" PRODUCE_VITALITY_COST = _t"消耗活力:%d" LEARN_PRODUCE_NOT_ENOUGH_MONEY = _t"你所携带的金钱不够支付该生产技能的学习费用" LEARN_PRODUCE_SKILL = _t"你学会了生产技能 %s" LEARN_PRODUCE_SKILL_LEVEL = _t"生产技能 %s 升到%dLv." LEARN_PRODUCE_FILTER_ALL = _t"全部" LEARN_PRODUCE_FILTER_AVAILABLE = _t"可学技能" LEARN_PRODUCE_FILTER_UNAVAILABLE = _t"不可学技能" PRODUCE_MATERIAL_NONE = _t"None" PRODUCT_PROBABILTY = _t"Probability:%s" PRODUCT_PROBABILTY_VERY_LOW = _t"^ff0000VeryLow" PRODUCT_PROBABILTY_LOW = _t"^ffff00Low" PRODUCT_PROBABILTY_MEDIUM = _t"^ffffffMedium" PRODUCT_PROBABILTY_HIGH = _t"^00ff00High" PRODUCT_PROBABILTY_VERY_HIGH = _t"^00ff00VeryHigh" PRODUCT_PROBABILTY_ULTRA_HIGH = "" PRODUCE_SKILL_LEARN_TIPS_1 = _t"主要产出补充药剂,以及短时提升自身实力或降低敌人实力的药剂" PRODUCE_SKILL_LEARN_TIPS_2 = _t"主要产出装备聚能,圣衣星铸,宝物升阶用的各类道具" PRODUCE_SKILL_LEARN_TIPS_3 = _t"主要产出各类符文,用于装备和宝物的符文镶嵌" PRODUCE_SKILL_LEARN_TIPS_4 = _t"用于制作精制的食物,其效果远大于普通食物" PRODUCE_SKILL_LEARN_TIPS_5 = _t"用于制作精制的食物,其效果远大于普通食物" PRODUCE_ERROR = _t"无法使用该配方进行生产" PRODUCE_ERROR_PACK_FULL = _t"没有足够的包裹空间" PRODUCE_ERROR_NOT_ENOUGH_MONEY = _t"Not enough money" PRODUCE_ERROR_NEED_PLAYER_LEVEL = _t"Need player%dLv." PRODUCE_ERROR_NEED_SKILL_LEVEL = _t"Need skill%dLv." PRODUCE_ERROR_NEED_NPC = _t"NeedNPC“%s”Nearby" PRODUCE_ERROR_NEED_VITALITY = _t"没有足够的活力" PRODUCE_ERROR_NEED_ENERGY = _t"没有足够的精力" PRODUCE_ERROR_RECIPE_LEARNED = _t"已经学会此配方,无需再次学习" PRODUCE_ERROR_RECIPE_LOW_LEV = _t"生产技能等级不足" PRODUCE_ERROR_RECIPE_UNLEARNED = _t"没有学会对应的生产技能" LIVING_NAME0 = _t"通用" LIVING_NAME1 = _t"铁匠" LIVING_NAME2 = _t"裁缝" LIVING_NAME3 = _t"工匠" LIVING_NAME4 = _t"厨师" LIVING_NAME5 = _t"药师" NEEDTOOL = _t"你需要工具 %s" LEVELTOOLOW = _t"你的等级不足,不能这样做" NEEDLIVINGSKILL = _t"需要%s达到%dLv." ---------------------- --技能相关 SKILL_ZERO = _t"待学习" SKILL_UPGRADE_BINDMONEY = _t"Need Cuopon:" SKILL_UPGRADE_MONEY = _t"Need Gold:" SKILL_LEV_MAX = _t"技能等级达到最大,无法升Lv." SKILL_LEARN_INVALID_CONDITION1 = _t"无效技能ID" SKILL_LEARN_INVALID_CONDITION2 = _t"技能学习的等级无效" SKILL_LEARN_INVALID_CONDITION3 = _t"天赋学习需求等级不满足" SKILL_LEARN_INVALID_CONDITION4 = _t"前提天赋加点不满足" SKILL_LEARN_INVALID_CONDITION5 = _t"天赋点数不足" SKILL_LEARN_INVALID_CONDITION6 = _t"不可学习的技能类别" SKILL_LEARN_VALID_CONDITION1 = _t"技能等级错误" SKILL_LEARN_VALID_CONDITION2 = _t"技能要求守护星座不符" SKILL_LEARN_VALID_CONDITION3 = _t"玩家等级不符" SKILL_LEARN_VALID_CONDITION4 = _t"前提技能不符" SKILL_LEARN_VALID_CONDITION5 = _t"前提声望不符" SKILL_LEARN_VALID_CONDITION6 = _t"缺少金币" SKILL_LEARN_VALID_CONDITION7 = _t"缺少金券" SKILL_LEARN_VALID_CONDITION8 = _t"缺少指定声望" SKILL_LEARN_VALID_CONDITION9 = _t"缺少指定物品" SKILL_LEARN_VALID_CONDITION10 = _t"缺少经验" SKILL_LEARN_VALID_CONDITION11 = _t"未加入军团" SKILL_LEARN_VALID_CONDITION12 = _t"前提职业觉悟不够" SKILL_LEVEL = _t"%dLv." SKILL_LEVEL_MAX = _t"%dLv.,Full Lv." SKILL_INITIATIVE = _t"Active" SKILL_PASSIVE = _t"Passive" LEARN_SKILL_FILTER_ALL = _t"All" LEARN_SKILL_FILTER_AVAILABLE = _t"Available" LEARN_SKILL_FILTER_UNAVAILABLE = _t"Unavailable" SKILL_DISABLE_OUT_OF_RANGE = _t"Out Of Range" SKILL_DISABLE_LESS_MIN_RANGE = _t"小于最小施法范围" SKILL_DISABLE_WHEN_MOUNT = _t"Can't Use While Riding" SKILL_ITEM_DISABLE_WHEN_MOUNT = _t"Disable While Riding" CHANNEL_SKILL_CANCEL = _t"通道技能被取消" CHARGE_POWER_LEV = "X%d" PRE_SKILL_LEV_LOW = _t"前提技能等级不足。" SKILLINTERRUPT = _t"技能被中断" SKILL_MATTER_USE_ERROR = _t"目标不存在或者不正确,无法使用这个物品" COOLING = _t"Skill Not Ready" SKILL_ITEM_USE_NEED_IN_AREA = _t"请找到可以使用这个物品的地点" MOVE_CANNOT_CAST_NOTINST_SKILL = _t"移动过程中无法使用非瞬发技能" SKILL_MOVE_POS_INVALID = _t"技能无法移动到指定位置" SKILLS_PANEL_WISDOM = _t"Awareness Value: %d" SKILLS_PANEL_LEVEL_WISDOM = "Upgrade%dNeeded Awareness Class Value: %.0f" SKILLS_PANEL_ARMY_IN = _t"To upgrade this skills join a Legion" PROF_ENERGY_HEAL = _t"神恩领域" PROF_ENERGY_DAMAGE = _t"神威领域" SKILL_LEVEL_UP_MUCH_EXP_COST_HINT = _t"The exp to learn the skill is huge, sure you want to learn it?" SKILL_ROLE_INFO_PANEL_LABEL_NEED_LEVEL = _t"Need Lv:%s" SKILL_ROLE_INFO_PANEL_LABEL_NEED_EXP = _t"Need Exp:%s" SKILL_ROLE_INFO_PANEL_LABEL_CUR_EXP = _t"Current Exp:%s" SKILL_ROLE_INFO_PANEL_LABEL_NEED_GOLD = _t"Need Gold:%s" SKILL_ROLE_INFO_PANEL_LABEL_CUR_GOLD = _t"Current Gold:%s" SKILL_ROLE_INFO_PANEL_LABEL_NEED_REPU = _t"Need Repu:%s" SKILL_ROLE_INFO_PANEL_LABEL_CUR_REPU = _t"Current Repu:%s" SKILL_ROLE_INFO_PANEL_LABEL_NEED_PROF_EXPENDITURE = _t"Need%sGuard Sign Awareness:%s" SKILL_ROLE_INFO_PANEL_LABEL_CUR_PROF_EXPENDITURE = _t"Current%sGuard Sign Awareness:%s" MONSTER_AGGROPOLICY_0 = _t"Normal" MONSTER_AGGROPOLICY_1 = _t"Active" COSMOS_PERCENT = _t"^O110Cosmos:%d%%\rBy fighting accumulate cosmos" COSMOS_FULL_HINT = _t"Cosmos is full, click the outbreak cosmos" --小宇宙爆发通用描述 COSMOS_BURST_COMMON_DESC = _t"^ff0000^O013小宇宙爆发\r^00ff00^O001短时间内极大的提升战力。能量达到^e5872f50%^00ff00,^e5872f75%^00ff00,^e5872f100%^00ff00时可以爆发不同强度的小宇宙,能量越多,追加能力越强。" COSMOS_BURST_ADDON_COMMON_DESC = _t"^ffffff★星魂爆发属性" COSMOS_BURST_NOADDON_COMMON_DESC = _t"^00ff00☆在小宇宙中注入星魂可追加爆发属性" COSMOS_BURST_LEVEL_COMMON_DESC = { "^f2f3f2Attack+1000\rDefense+2000\rSpeed+2.5", _t"^f2f3f2Attack+500\rDefense+1000", _t"^f2f3f2Attack+500\rDefense+1000", } --默认技能释放条件表 SKILL_CAST_CONDITION_DEFAULT = { CHECK_SKILL_CAST_CONDITION1 = _t"体力值不足,此技能无法使用", CHECK_SKILL_CAST_CONDITION2 = _t"小宇宙能量不足,无法爆发", CHECK_SKILL_CAST_CONDITION3 = _t"斗气值VP不足,此技能无法使用", CHECK_SKILL_CAST_CONDITION4 = _t"没有足够的技能所需物品,此技能无法使用", CHECK_SKILL_CAST_CONDITION5 = _t"身上有异常状态,此技能无法使用", CHECK_SKILL_CAST_CONDITION6 = _t"当前变身状态下,此技能无法使用", CHECK_SKILL_CAST_CONDITION7 = _t"生命值低于限制值,此技能无法使用", CHECK_SKILL_CAST_CONDITION8 = _t"生命值高于限制值,此技能无法使用", CHECK_SKILL_CAST_CONDITION9 = _t"能量值低于限制值,此技能无法使用", CHECK_SKILL_CAST_CONDITION10 = _t"能量值高于限制值,此技能无法使用", CHECK_SKILL_CAST_CONDITION11 = _t"没有装备技能所需武器,此技能无法使用", CHECK_SKILL_CAST_CONDITION12 = _t"目标不符合,此技能无法使用", CHECK_SKILL_CAST_CONDITION13 = _t"缺少前提状态,此技能无法使用", CHECK_SKILL_CAST_CONDITION14 = _t"身上有异常状态,此技能无法使用", CHECK_SKILL_CAST_CONDITION15 = _t"精力值不足,此技能无法使用", CHECK_SKILL_CAST_CONDITION16 = _t"变身状态禁用守护星座技能", CHECK_SKILL_CAST_CONDITION17 = _t"神恩领域值不足", CHECK_SKILL_CAST_CONDITION18 = _t"神威领域值不足", CHECK_SKILL_CAST_CONDITION19 = _t"当前场景不能使用该技能", CHECK_SKILL_CAST_CONDITION20 = _t"挂件状态下此技能无法使用", CHECK_SKILL_CAST_CONDITION21 = _t"战斗状态下不可用", CHECK_SKILL_CAST_CONDITION22 = _t"职业不符", CHECK_SKILL_CAST_CONDITION23 = _t"斗魂技能未激活", CHECK_SKILL_CAST_CONDITION24 = _t"小宇宙未爆发无法使用", CHECK_SKILL_CAST_CONDITION25 = _t"战场状态下不可用", } --特定技能释放条件表 SKILL_CAST_CONTDITION = {} --技能释放条件职业相关表 SKILL_CAST_CONTDITION_PROF = {} --技能释放条件之白鸟 SKILL_CAST_CONTDITION_PROF[3] = { CHECK_SKILL_CAST_CONDITION17 = _t"冻气不足", } CMDDESC_WALKRUN = _t"^O009Walk/Run" CMDDESC_FINDTARGET = _t"^O009Search" CMDDESC_ASSISTATTACK = _t"^O009Assist" CMDDESC_INVITETOTEAM = _t"^O009Team Invite" CMDDESC_LEAVETEAM = _t"^O009Leave Team" CMDDESC_KICKTEAMMEM = _t"^O009Remove from Team" CMDDESC_FINDTEAM = _t"^O009Search Team" CMDDESC_STARTTRADE = _t"^O009Trade" CMDDESC_SELLBOOTH = _t"^O009摆摊" CMDDESC_BUYBOOTH = _t"^O009摆摊" CMDDESC_INVITETOFACTION = _t"^O009Legion Invite" CMDDESC_FLY = _t"^O009Fly" CMDDESC_PICKUP = _t"^O009Pick" CMDDESC_GATHER = _t"^O009挖掘采集" CMDDESC_RUSHFLY = _t"^O009加速飞行" CMDDESC_BINDBUDDY = _t"^O009相依相偎" CMDDESC_SKILLGROUP = _t"^O009连续技(%d)" CMDDESC_NULL3 = " " CMDDESC_PET_NORMAL_ATTACK = _t"^O009魔宠普通攻击" CMDDESC_MOUNT = _t"^O009Ride" CMDDESC_TALK_TO_NPC = _t"^O009Talk" CMDDESC_TELEPORT_TO_LEAGUEBASE = _t"^O009TP to Legion Base" CMDDESC_REST = _t"^O009Rest" CMDDESC_REST_HINT = _t"^O009使用后进入祈祷状态\r将每10秒钟获得一次经验\r每秒恢复60点生命,20点体力值\r移动将会打断" CMDDESC_AFK = _t"^O009Bathing Glory" CMDDESC_AFK_HINT = _t"^O009使用条件:满20级\r进入沐浴荣光状态后\r每5分钟获得一次存储经验\r战斗力越高储存经验获得越多\r每天最多可以进行8小时沐浴荣光" CMDDESC_AIRCRAFT = _t"^O009骑乘飞行" CMDDESC_AIRCRAFT_HINT = _t"^O009使用条件:需要装备飞行器" CMDDESE_HIDE_PLAYER = _t"^O009Hide other players" CMDDESE_HIDE_PET = _t"^O009Hide other players pets" CMDDESE_HIDE_PLAYER_HINT = _t"^O009使用后隐藏其他玩家,再次使用后解除隐藏" CMDDESE_HIDE_PET_HINT = _t"^O009使用后隐藏其他玩家宠物,再次使用后解除隐藏" DESC_LEARN_LACK_COLOR = "^FF0000" SKILL_ITEM_ERROR_DEFAULT = { CHANNEL_SKILL_CANCEL = _t"物品使用被取消", --- 通道技能取消提示 SKILL_DISABLE_LESS_MIN_RANGE = _t"物品小于最小使用范围", --- 小于最小施放范围提示 CHECK_SKILL_CAST_CONDITION1 = _t"体力值不足,此物品无法使用", ---蓝不足提示 CHECK_SKILL_CAST_CONDITION2 = _t"小宇宙能量不足,无法爆发", ---小宇宙能量(怒气)不足提示 CHECK_SKILL_CAST_CONDITION3 = _t"斗气值不足,此物品无法使用", ---斗气值不足提示 CHECK_SKILL_CAST_CONDITION4 = _t"缺少所需物品,此物品无法使用", ---技能需求物品提示 CHECK_SKILL_CAST_CONDITION5 = _t"身上有异常状态,此物品无法使用", ---被眩晕/沉默等无法使用技能 CHECK_SKILL_CAST_CONDITION6 = _t"当前变身状态下,此物品无法使用", ---变身限制技能使用提示 CHECK_SKILL_CAST_CONDITION7 = _t"生命值低于限制值,此物品无法使用", ---生命值过低提示 CHECK_SKILL_CAST_CONDITION8 = _t"生命值高于限制值,此物品无法使用", ---生命值过高提示 CHECK_SKILL_CAST_CONDITION9 = _t"能量值低于限制值,此物品无法使用", ---蓝过低提升 CHECK_SKILL_CAST_CONDITION10 = _t"能量值高于限制值,此物品无法使用", ---蓝过高提示 CHECK_SKILL_CAST_CONDITION11 = _t"没有装备所需武器,此物品无法使用", ---没有武器提示 CHECK_SKILL_CAST_CONDITION12 = _t"当前目标不符合物品作用目标,此物品无法使用",--- 目标不正确提示 CHECK_SKILL_CAST_CONDITION13 = _t"缺少前提状态,此物品无法使用", ---缺少前提buff提示 CHECK_SKILL_CAST_CONDITION14 = _t"身上有异常状态,此物品无法使用", ---用状态位限制技能施放提示 CHECK_SKILL_CAST_CONDITION15 = _t"精力值不足,此物品无法使用", ---ep 不足提示 CHECK_SKILL_CAST_CONDITION16 = _t"变身状态此物品无法使用", ---变身禁用守护星座技能提示 CHECK_SKILL_CAST_CONDITION17 = _t"神恩领域值不足", CHECK_SKILL_CAST_CONDITION18 = _t"神威领域值不足", CHECK_SKILL_CAST_CONDITION19 = _t"当前场景不能使用该技能" , CHECK_SKILL_CAST_CONDITION20 = _t"挂件限制", CHECK_SKILL_CAST_CONDITION21 = _t"战斗状态下不可用" , CHECK_SKILL_CAST_CONDITION22 = _t"职业不符", } SKILL_ITEM_ERROR = {} SKILL_ITEM_ERROR[9838] = { CHANNEL_SKILL_CANCEL = _t"物品使用被取消", SKILL_DISABLE_LESS_MIN_RANGE = _t"物品小于最小使用范围", CHECK_SKILL_CAST_CONDITION1 = _t"体力值不足,此物品无法使用", CHECK_SKILL_CAST_CONDITION2 = _t"小宇宙能量不足,无法爆发", CHECK_SKILL_CAST_CONDITION3 = _t"斗气值VP不足,此物品无法使用", CHECK_SKILL_CAST_CONDITION4 = _t"缺少所需物品,此物品无法使用", CHECK_SKILL_CAST_CONDITION5 = _t"身上有异常状态,此物品无法使用", CHECK_SKILL_CAST_CONDITION6 = _t"当前变身状态下,此物品无法使用", CHECK_SKILL_CAST_CONDITION7 = _t"生命值HP低于限制值,此物品无法使用", CHECK_SKILL_CAST_CONDITION8 = _t"生命值HP高于限制值,此物品无法使用", CHECK_SKILL_CAST_CONDITION9 = _t"能量值MP低于限制值,此物品无法使用", CHECK_SKILL_CAST_CONDITION10 = _t"能量值MP高于限制值,此物品无法使用", CHECK_SKILL_CAST_CONDITION11 = _t"没有装备所需武器,此物品无法使用", CHECK_SKILL_CAST_CONDITION12 = _t"当前目标不符合物品作用目标,此物品无法使用", CHECK_SKILL_CAST_CONDITION13 = _t"缺少前提状态,此物品无法使用", CHECK_SKILL_CAST_CONDITION14 = _t"身上有异常状态,此物品无法使用", CHECK_SKILL_CAST_CONDITION15 = _t"精力值不足,此物品无法使用", CHECK_SKILL_CAST_CONDITION16 = _t"变身状态此物品无法使用", CHECK_SKILL_CAST_CONDITION17 = _t"神恩领域值不足", CHECK_SKILL_CAST_CONDITION18 = _t"神威领域值不足", CHECK_SKILL_CAST_CONDITION19 = _t"当前场景不能使用该技能", CHECK_SKILL_CAST_CONDITION20 = _t"挂件限制", CHECK_SKILL_CAST_CONDITION21 = _t"战斗状态下不可用" , CHECK_SKILL_CAST_CONDITION22 = _t"职业不符", } ---------------------- --小宇宙 COSMOS_ACTIVE_STAR_SOUL_WITH_ITEM = _t"激活需要%d点小宇宙潜能和%s,确定激活?" COSMOS_ACTIVE_STAR_SOUL = _t"激活需要%d点小宇宙潜能,确定激活?" COSMOS_ACTIVE_ITEM_NOT_OBTAIN = _t"缺少激活物品%s" COSMOS_ACTIVE_PLAYER_LEVEL = _t"激活需要玩家%d级以上" COSMOS_ATCTVE_PLAYER_REPU = _t"激活需要小宇宙潜能%d以上" COSMOS_ACTIVE_SUCC_MSG = _t"您的小宇宙激活了新的星命点" COSMOS_STAR_ATTRIBUTE_FORMAT = _t"<尚未注入星魂>\r^00ff00\r右键点击星魂,可将其注入星命点。" COSMOS_STAR_ATTRIBUTE_FULL_FORMAT = _t"<注入星魂>\r^ffff00★战力 %s \r%s\r^00ff00\r右键点击已注入星魂,可将其析出。" COSMOS_STAR_EMBED_SUCC = _t"注入成功" COSMOS_STAR_UNEMBED_SUCC = _t"析出成功" COSMOS_STAR_OPER_ERROR1 = _t"星命点信息错误" COSMOS_STAR_OPER_ERROR2 = _t"类型不符" COSMOS_STAR_OPER_ERROR3 = _t"小宇宙空间已满,无法析出星魂" COSMOS_STAR_OPER_ERROR4 = _t"小宇宙尚未激活" COSMOS_STAR_OPER_ERROR5 = _t"无法进行当前等级占星" COSMOS_STAR_OPER_ERROR6 = _t" 小宇宙潜能不足\r^O114^00ff00参加各类多人活动均可获得相关道具,补充潜能" COSMOS_STAR_OPER_ERROR7 = _t"小宇宙空间已满,无法进行占星操作" COSMOS_STAR_OPER_ERROR8 = _t"物品信息错误" COSMOS_STAR_OPER_ERROR9 = _t"已注入同类爆发属性主序星魂,注入失败" COSMOS_STAR_ACTIVE_ERROR = _t"小宇宙尚未激活" COSMOS_STAR_MERGE_LEV_ERROR = _t"低品质星魂无法融合高品质星魂" COSMOS_STAR_MERGE_CONFIGM = _t"^f2f3f2%s^00ff00将融合^f2f3f2%s, ^00ff00获得^f2f3f2%d^00ff00点经验" COSMOS_STAR_MERGE_DST_DISABLE = _t"%s不允许融合" COSMOS_STAR_MERGE_SRC_DISABLE = _t"%s不允许被融合" COSMOS_STAR_MERGE_SUCC = _t"星魂融合成功" COSMOS_STAR_MERGE_DST_LEVEL_MAX = _t"星魂已满级,无法融合其他星魂" COSMOS_STAR_MERGE_LOCK = _t"星魂已被锁,请解锁后再融合" COSMOS_STAR_BOX_USE_ERROR = _t"小宇宙空间已满" COSMOS_MERGE_ALL_HINT = _t"确定要融合所有非锁定星魂么?" COSMOS_ASTROLOGY_RESULT = "" COSMOS_ASTROLOGY_OBTAIN = _t"获得%s" COSMOS_ASTROLOGY_OBTAIN_FAIL = _t"占星失败" COSMOS_ASTROLOGY_LEV_UP = "" COSMOS_ASTROLOGY_LEV_DOWN = "" COSMOS_ASTROLOGY_LEV_EQUAL = "" COSMOS_ASTROLOGY_HINT1 = _t"^O057^ffc000黑暗神喻^O001\r^f2f3f2消耗300小宇宙潜能\r^00ff00聆听^ffc000黑暗神喻^00ff00获得低级星魂,一定概率领悟^ffc000青铜神喻" COSMOS_ASTROLOGY_HINT2 = _t"^O057^ffc000青铜神喻^O001\r^f2f3f2消耗250小宇宙潜能\r^00ff00聆听^ffc000青铜神喻^00ff00获得次级星魂,一定概率领悟^ffc000白银神喻" COSMOS_ASTROLOGY_HINT3 = _t"^O057^ffc000白银神喻^O001\r^f2f3f2消耗200小宇宙潜能\r^00ff00聆听^ffc000白银神喻^00ff00获得中级星魂,一定概率领悟^ffc000黄金神喻" COSMOS_ASTROLOGY_HINT4 = _t"^O057^ffc000黄金神喻^O001\r^f2f3f2消耗150小宇宙潜能\r^00ff00聆听^ffc000黄金神喻^00ff00获得高级星魂,一定概率领悟^ffc000雅典娜神喻" COSMOS_ASTROLOGY_HINT5 = _t"^O057^ffc000雅典娜神喻^O001\r^f2f3f2消耗100小宇宙潜能\r^00ff00聆听^ffc000雅典娜神喻^00ff00获得高级星魂" COSMOS_VALUE_HINT = _t"^O057小宇宙潜能^ffc000\r用于增强自身的小宇宙强度" COSMOS_STAR_FORCE_HINT = _t"^O057星力^ffc000\r小宇宙中的星魂战力总和。星力越高,占星成功率越高" --小宇宙星魂链未全部激活提示 COSMOS_STAR_CHAIN_NOT_FULL_HINT = _t"^ff0000%s\r激活%d个星命点开启" KOSUMO_LEVEL = _t"小宇宙等级:%d Lv." KOSUMO_REQUIREMENT_HINT = _t"需要:\r人物等级:%s%d级^ffffff / %d级\r消耗经验:%s%ld^ffffff / %d\r已加小宇宙技能点数:%s%d^ffffff / %d\r" KOSUMO_CHAIN_REQUIREMENT_HINT = _t"需要:\r人物等级:%d级 / %d级\r小宇宙等级:%d级 / %d级\r" STAR_CHAIN_LEVEL = _t"星魂链等级:%d" STAR_CHAIN_HINT_ADDON = _t"^eeee00激活属性:\r%s" STAR_CHAIN_DISABLED = _t"^ff0000星魂链尚未开启" STAR_CHAIN_ERROR_UNKNOW = _t"星魂石镶嵌时发生未知错误" STAR_CHAIN_ERROR_CHAIN_NOT_AVAILABLE = _t"该星魂链目前不能镶嵌" STAR_CHAIN_ERROR_CHAIN_LEVEL = _t"星魂链尚未开启" STAR_CHAIN_ERROR_WRONG_SLOT = _t"星魂石镶嵌位置不符" --斗魂阶位 GIFT_SKILL_ENHANCE = _t"%s%d阶" GIFT_NOT_GET_FONT_COLOR = "^ff0000" GIFT_GET_FONT_COLOR = "^ffffff" GIFT_PROF_BG_IMG = "special\\Gift\\BG%d.dds" GIFT_CLOTH_NOT_GOT_HINT = _t"%s圣衣未获得" GIFT_ENHANCE_LEVEL_LESS_HINT = _t"%s圣衣的星铸等级不够" GIFT_NOT_ACTIVE = _t"可以单击激活此斗魂" GIFT_ACTIVE = _t"斗魂已激活,可以单击取消" --连续技 SEQUENCE_SKILL_DEFAULT_NAME = _t"连续技(%d)" --buff层数,用于在buff图标上显示 TARGET_BUFF_LEVEL_DESC = "^O030^ffffff%2d" SELF_BUFF_LEVEL_DESC = "^O030^ffffff%4d"
gpl-3.0
msburgess3200/PERP
gamemodes/perp/gamemode/vehicles/speedo.lua
1
2152
VEHICLE = {}; VEHICLE.ID = 'f'; VEHICLE.FID = '6'; VEHICLE.Name = "Speedo"; VEHICLE.Make = "Vapid ST"; VEHICLE.Model = "Speedo"; VEHICLE.Script = "speedo"; VEHICLE.Cost = 65000; VEHICLE.PaintJobCost = 4500; VEHICLE.DF = true; VEHICLE.CustomBodyGroup = nil; VEHICLE.PaintJobs = { {model = 'models/sickness/speedodr.mdl', skin = '0', name = 'Black', color = Color(0, 0, 0, 255)}, {model = 'models/sickness/speedodr.mdl', skin = '1', name = 'White', color = Color(255, 250, 250, 255)}, {model = 'models/sickness/speedodr.mdl', skin = '2', name = 'Red', color = Color(205, 51, 51, 255)}, {model = 'models/sickness/speedodr.mdl', skin = '3', name = 'Pale Green', color = Color(152, 251, 152, 255)}, {model = 'models/sickness/speedodr.mdl', skin = '4', name = 'Dodger Blue', color = Color(24, 116, 205, 255)}, }; VEHICLE.PassengerSeats = { {Vector(20, -30, 30), Angle(0, 0, 0)}, {Vector(25, 60, 30), Angle(0, 95, 0)}, {Vector(-25, 65, 30), Angle(0, -95, 0)}, }; VEHICLE.ExitPoints = { Vector(-93.6075, 48.9518, 4.2876), Vector(93.6075, 48.9518, 4.2876), }; VEHICLE.DefaultIceFriction = .2; VEHICLE.PlayerReposition_Pos = nil; VEHICLE.PlayerReposition_Ang = nil; VEHICLE.ViewAdjustments_FirstPerson = nil; VEHICLE.ViewAdjustments_ThirdPerson = nil; VEHICLE.RequiredClass = nil; VEHICLE.PaintText = "A ped- Speedo, don't go out taking my kids now!"; VEHICLE.HornNoise = NORMAL_HORNS; VEHICLE.HeadlightPositions = { {Vector(38.7723, 102.7135, 49.6355), Angle(20, 0, 0)}; {Vector(-38.7723, 102.7135, 49.6355), Angle(20, 0, 0)}; }; VEHICLE.TaillightPositions = { {Vector(-21.2796, -76.8145, 30.8403), Angle(20, -180, 0)}; {Vector(21.2796, -76.8145, 30.8403), Angle(20, -180, 0)}; }; VEHICLE.UnderglowPositions = { {Vector(0, 35, 5)}; {Vector(0, -35, 5)}; }; VEHICLE.RevvingSound = "vehicles/enzo/turbo.mp3"; VEHICLE.SpinoutSound = "vehicles/golf/skid_highfriction.wav"; GM:RegisterVehicle(VEHICLE);
mit
FFXIOrgins/FFXIOrgins
scripts/zones/Windurst_Woods/npcs/Apururu.lua
11
5650
----------------------------------- -- Area: Windurst Woods -- NPC: Apururu -- Involved in Quests: The Kind Cardian, Can Cardians Cry? -- @zone 241 -- @pos -11 -2 13 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; package.loaded["scripts/globals/missions"] = nil; package.loaded["scripts/globals/quests"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local TKC = player:getQuestStatus(JEUNO,THE_KIND_CARDIAN); local C3 = player:getQuestStatus(WINDURST,CAN_CARDIANS_CRY); -- The Kind Cardian if(TKC == QUEST_ACCEPTED) then if(trade:hasItemQty(969,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then player:startEvent(0x018d); end -- Can Cardians Cry? elseif(C3 == QUEST_ACCEPTED) then count = trade:getItemCount(); if(trade:hasItemQty(551,1) and count == 1) then player:startEvent(0x0145,0,6000,5000); -- finish C3 end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local ANC3K = player:getQuestStatus(WINDURST,THE_ALL_NEW_C_3000); -- previous quest in line local C3 = player:getQuestStatus(WINDURST,CAN_CARDIANS_CRY); local TKC = player:getQuestStatus(JEUNO,THE_KIND_CARDIAN); -- Check if we are on Windurst Mission 1-2 if(player:getCurrentMission(WINDURST) == THE_HEART_OF_THE_MATTER) then MissionStatus = player:getVar("MissionStatus"); if(MissionStatus == 0) then player:startEvent(0x0089); elseif(MissionStatus < 4) then player:startEvent(0x008a); elseif(MissionStatus == 6) then -- Cardinals encountered, no orbs -- Mission's over - Bad end (ish anyway, you lost the orbs) player:startEvent(0x008f); elseif(MissionStatus == 5) then -- Cardinals not encountered -- Mission's over - Good end (you came back with the orbs) player:startEvent(0x0091); end -- The Kind Cardian elseif (TKC == QUEST_ACCEPTED) then if(player:getVar("theKindCardianVar") == 0) then player:startEvent(0x0188); elseif(player:getVar("theKindCardianVar") == 1) then player:startEvent(0x0189); elseif(player:getVar("theKindCardianVar") == 2) then player:startEvent(0x018e); end -- Can Cardians Cry? elseif (ANC3K == QUEST_COMPLETED and C3 == QUEST_AVAILABLE and player:getFameLevel (WINDURST) >= 5) then player:startEvent(0x013F,0,6000); -- start C3 elseif (C3 == QUEST_ACCEPTED) then player:startEvent(0x0140,0,6000); -- C3 reminder elseif (C3 == QUEST_COMPLETED) then player:startEvent(0x014A); -- new dialog after C3 -- standard dialog else player:startEvent(0x0112); 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); -- Windurst mission 1-2 start if(csid == 0x0089) then player:setVar("MissionStatus",1); player:addKeyItem(FIRST_DARK_MANA_ORB); -- Give the player the key items player:addKeyItem(SECOND_DARK_MANA_ORB); player:addKeyItem(THIRD_DARK_MANA_ORB); player:addKeyItem(FOURTH_DARK_MANA_ORB); player:addKeyItem(FIFTH_DARK_MANA_ORB); player:addKeyItem(SIXTH_DARK_MANA_ORB); player:messageSpecial(KEYITEM_OBTAINED,FIRST_DARK_MANA_ORB); -- Display the key item messages player:messageSpecial(KEYITEM_OBTAINED,SECOND_DARK_MANA_ORB); player:messageSpecial(KEYITEM_OBTAINED,THIRD_DARK_MANA_ORB); player:messageSpecial(KEYITEM_OBTAINED,FOURTH_DARK_MANA_ORB); player:messageSpecial(KEYITEM_OBTAINED,FIFTH_DARK_MANA_ORB); player:messageSpecial(KEYITEM_OBTAINED,SIXTH_DARK_MANA_ORB); player:setVar("MissionStatus_orb1",1); -- Set the orb variables; 1 = not handled; 2 = handled; player:setVar("MissionStatus_orb2",1); player:setVar("MissionStatus_orb3",1); player:setVar("MissionStatus_orb4",1); player:setVar("MissionStatus_orb5",1); player:setVar("MissionStatus_orb6",1); elseif(csid == 0x008f or csid == 0x0091) then finishMissionTimeline(player,1,csid,option); player:setVar("MissionStatus_orb1",0); player:setVar("MissionStatus_orb2",0); player:setVar("MissionStatus_orb3",0); player:setVar("MissionStatus_orb4",0); player:setVar("MissionStatus_orb5",0); player:setVar("MissionStatus_orb6",0); player:delKeyItem(FIRST_GLOWING_MANA_ORB); -- Remove the glowing orb key items player:delKeyItem(SECOND_GLOWING_MANA_ORB); player:delKeyItem(THIRD_GLOWING_MANA_ORB); player:delKeyItem(FOURTH_GLOWING_MANA_ORB); player:delKeyItem(FIFTH_GLOWING_MANA_ORB); player:delKeyItem(SIXTH_GLOWING_MANA_ORB); -- The Kind Cardian elseif(csid == 0x0188 and option == 1) then player:setVar("theKindCardianVar",1); elseif(csid == 0x018d) then player:delKeyItem(TWO_OF_SWORDS); player:setVar("theKindCardianVar",2); player:addFame(WINDURST,WIN_FAME*30); player:tradeComplete(); end end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/zones/Windurst_Waters_[S]/npcs/Ezura-Romazura.lua
34
1541
----------------------------------- -- Area: Windurst Waters [S] -- NPC: Ezura-Romazura -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/Windurst_Waters_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,EZURAROMAZURA_SHOP_DIALOG); stock = {0x12a3,123750, -- Scroll of Stone V 0x12ad,133110, -- Scroll of Water V 0x129e,144875, -- Scroll of Aero V 0x1294,162500, -- Scroll of Fire V 0x1299,186375, -- Scroll of Blizzard V 0x131d,168150, -- Scroll of Stoneja 0x131f,176700, -- Scroll of Waterja 0x131a,193800, -- Scroll of Firaja 0x131c,185240, -- Scroll of Aeroja 0x12ff,126000} -- Scroll of Break 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
FFXIOrgins/FFXIOrgins
scripts/zones/Port_Jeuno/npcs/Challoux.lua
37
1148
----------------------------------- -- Area: Port Jeuno -- NPC: Challoux -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil; require("scripts/zones/Port_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,CHALLOUX_SHOP_DIALOG); stock = {0x11C1,62, --Gysahl Greens 0x0348,4, --Chocobo Feather 0x439B,9} --Dart 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
PioneerMakeTeam/Cretaceous
wicker/lib/searchspace.lua
6
1536
--[[ Copyright (C) 2013 simplex 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, see <http://www.gnu.org/licenses/>. ]]-- local TheSim = TheSim local FindValidPositionByFan = FindValidPositionByFan local Lambda = wickerrequire 'paradigms.functional' local Pred = wickerrequire 'lib.predicates' local myutils = wickerrequire 'utils' FindAllEntities = myutils.game.FindAllEntities FindSomeEntity = myutils.game.FindSomeEntity Annulus = Class(function(self, center, r, R, rng, tries) self.center = center self.r = r self.R = R self.rng = rng or math.random self.tries = tries or 16 end) function Annulus:Search(f) local function test_at_offset(dv) return f(self.center + dv) end for _=1, self.tries do local offset = FindValidPositionByFan( 2*math.pi*math.random(), -- No, math.random shouldn't be self.rng. An annulus is radially symmetric. self.r + (self.R - self.r)*self.rng(), 8, test_at_offset ) if offset then return self.center + offset end end end return _M
mit
sadegh1996/sword_antispam
plugins/plugins.lua
10
8430
do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled) local tmp = '\n\n@telemanager_ch' local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'.'..status..' '..v..' \n' end end local text = text..'\n\n'..nsum..' plugins installed\n\n'..nact..' plugins enabled\n\n'..nsum-nact..' plugins disabled'..tmp return text end local function list_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") -- text = text..v..' '..status..'\n' end end local text = text..'\nPlugins Reloaded !\n\n'..nact..' plugins enabled\n'..nsum..' plugins installed\n\n@telemanager_ch' return text end local function reload_plugins( ) plugins = {} load_plugins() return list_plugins(true) end local function enable_plugin( plugin_name ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then return ''..plugin_name..' is enabled' end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins( ) else return ''..plugin_name..' does not exists' end end local function disable_plugin( name, chat ) -- Check if plugins exists if not plugin_exists(name) then return ' '..name..' does not exists' end local k = plugin_enabled(name) -- Check if plugin is enabled if not k then return ' '..name..' not enabled' end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true) end local function disable_plugin_on_chat(receiver, plugin) if not plugin_exists(plugin) then return "Plugin doesn't exists" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() return ' '..plugin..' disabled on this chat' end local function reenable_plugin_on_chat(receiver, plugin) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return 'This plugin is not disabled' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() return ' '..plugin..' is enabled again' end local function run(msg, matches) -- Show the available plugins if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo return list_all_plugins() end -- Re-enable a plugin for this chat if matches[1] == '+' and matches[3] == 'chat' then if is_momod(msg) then local receiver = get_receiver(msg) local plugin = matches[2] print("enable "..plugin..' on this chat') return reenable_plugin_on_chat(receiver, plugin) end end -- Enable a plugin if matches[1] == '+' and is_sudo(msg) then --after changed to moderator mode, set only sudo if is_momod(msg) then local plugin_name = matches[2] print("enable: "..matches[2]) return enable_plugin(plugin_name) end end -- Disable a plugin on a chat if matches[1] == '-' and matches[3] == 'chat' then if is_momod(msg) then local plugin = matches[2] local receiver = get_receiver(msg) print("disable "..plugin..' on this chat') return disable_plugin_on_chat(receiver, plugin) end end -- Disable a plugin if matches[1] == '-' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[2] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[2]) return disable_plugin(matches[2]) end -- Reload all the plugins! if matches[1] == '*' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { moderator = { "!plugins disable [plugin] chat : disable plugin only this chat.", "!plugins enable [plugin] chat : enable plugin only this chat.", }, sudo = { "!plugins : list all plugins.", "!plugins + [plugin] : enable plugin.", "!plugins - [plugin] : disable plugin.", "!plugins * : reloads all plugins." }, }, patterns = { "^!plugins$", "^!plugins? (+) ([%w_%.%-]+)$", "^!plugins? (-) ([%w_%.%-]+)$", "^!plugins? (+) ([%w_%.%-]+) (chat)", "^!plugins? (-) ([%w_%.%-]+) (chat)", "^!plugins? (*)$", "^[!/](reload)$" }, run = run, moderated = true, -- set to moderator mode --privileged = true } end -- -_-_-_-_-_-_-_-_-_- ||-_-_-_-_-_ || ||-_-_-_-_-_ -- || || || || -- || || || || -- || || || || -- || ||-_-_-_-_-_ || ||-_-_-_-_-_ -- || || || || -- || || || || -- || || || || -- || ||-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_ -- -- -- /\ /\ /-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_ -- ||\\ //|| //\\ || //|| //\\ // || || // -- || \\ // || // \\ || // || // \\ // || || // -- || \\ // || // \\ || // || // \\ || || || // -- || \\ // || //______\\ || // || //______\\ || -_-_-_- ||-_-_-_-_-_ || // -- || \\ // || // \\ || // || // \\ || || || || \\ -- || \\ // || // \\ || // || // \\ \\ || || || \\ -- || \\// || // \\ ||// || // \\ \\-_-_-_-_-|| ||-_-_-_-_-_ || \\ -- -- -- ||-_-_-_- || || || //-_-_-_-_-_- -- || || || || || // -- ||_-_-_|| || || || // -- || || || || \\ -- || || \\ // \\ -- || || \\ // // -- || ||-_-_-_-_ \\-_-_-_-// -_-_-_-_-_-// -- --By @ali_ghoghnoos --@telemanager_ch
gpl-2.0
FFXIOrgins/FFXIOrgins
scripts/zones/South_Gustaberg/Zone.lua
2
2783
----------------------------------- -- -- Zone: South_Gustaberg (107) -- ----------------------------------- package.loaded["scripts/zones/South_Gustaberg/TextIDs"] = nil; require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/South_Gustaberg/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; wc = player:getWeather(); if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-601.433,35.204,-520.031,1); end if(player:getCurrentMission(COP) == THE_CALL_OF_THE_WYRMKING and player:getVar("VowsDone") == 1)then cs= 0x038A; elseif (player:getQuestStatus(WINDURST, I_CAN_HEAR_A_RAINBOW) == QUEST_ACCEPTED and player:hasItem(1125,0)) then colors = player:getVar("ICanHearARainbow"); o = (tonumber(colors) % 4 >= 2); cs = 0x0385; if (o == false and wc < 4) then player:setVar("ICanHearARainbow_Weather",1); player:setVar("ICanHearARainbow",colors+2); else cs = -1; end end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0385) then weather = player:getVar("ICanHearARainbow_Weather"); if (weather == 1) then weather = 0; end if (player:getVar("ICanHearARainbow") < 127) then player:updateEvent(0,0,weather); else player:updateEvent(0,0,weather,6); end end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x038A) then if (player:getCurrentMission(COP) == A_TRANSIENT_DREAM)then player:completeMission(COP,A_TRANSIENT_DREAM); player:addMission(COP,THE_CALL_OF_THE_WYRMKING); end player:setVar("VowsDone",0); elseif (csid == 0x0385) then player:setVar("ICanHearARainbow_Weather",0); end end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/zones/Bhaflau_Remnants/Zone.lua
36
1125
----------------------------------- -- -- Zone: Bhaflau_Remnants -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Bhaflau_Remnants/TextIDs"] = nil; require("scripts/zones/Bhaflau_Remnants/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
JulianVolodia/awesome
lib/awful/completion.lua
11
7193
--------------------------------------------------------------------------- --- Completion module. -- -- This module store a set of function using shell to complete commands name. -- -- @author Julien Danjou &lt;julien@danjou.info&gt; -- @author Sébastien Gross &lt;seb-awesome@chezwam.org&gt; -- @copyright 2008 Julien Danjou, Sébastien Gross -- @release @AWESOME_VERSION@ -- @module awful.completion --------------------------------------------------------------------------- -- Grab environment we need local io = io local os = os local table = table local math = math local print = print local pairs = pairs local string = string local util = require("awful.util") local completion = {} -- mapping of command/completion function local bashcomp_funcs = {} local bashcomp_src = "@SYSCONFDIR@/bash_completion" --- Enable programmable bash completion in awful.completion.bash at the price of -- a slight overhead. -- @param src The bash completion source file, /etc/bash_completion by default. function completion.bashcomp_load(src) if src then bashcomp_src = src end local c, err = io.popen("/usr/bin/env bash -c 'source " .. bashcomp_src .. "; complete -p'") if c then while true do local line = c:read("*line") if not line then break end -- if a bash function is used for completion, register it if line:match(".* -F .*") then bashcomp_funcs[line:gsub(".* (%S+)$","%1")] = line:gsub(".*-F +(%S+) .*$", "%1") end end c:close() else print(err) end end local function bash_escape(str) str = str:gsub(" ", "\\ ") str = str:gsub("%[", "\\[") str = str:gsub("%]", "\\]") str = str:gsub("%(", "\\(") str = str:gsub("%)", "\\)") return str end --- Use shell completion system to complete command and filename. -- @param command The command line. -- @param cur_pos The cursor position. -- @param ncomp The element number to complete. -- @param shell The shell to use for completion (bash (default) or zsh). -- @return The new command, the new cursor position, the table of all matches. function completion.shell(command, cur_pos, ncomp, shell) local wstart = 1 local wend = 1 local words = {} local cword_index = 0 local cword_start = 0 local cword_end = 0 local i = 1 local comptype = "file" -- do nothing if we are on a letter, i.e. not at len + 1 or on a space if cur_pos ~= #command + 1 and command:sub(cur_pos, cur_pos) ~= " " then return command, cur_pos elseif #command == 0 then return command, cur_pos end while wend <= #command do wend = command:find(" ", wstart) if not wend then wend = #command + 1 end table.insert(words, command:sub(wstart, wend - 1)) if cur_pos >= wstart and cur_pos <= wend + 1 then cword_start = wstart cword_end = wend cword_index = i end wstart = wend + 1 i = i + 1 end if cword_index == 1 and not string.find(words[cword_index], "/") then comptype = "command" end local shell_cmd if shell == "zsh" or (not shell and os.getenv("SHELL"):match("zsh$")) then if comptype == "file" then -- NOTE: ${~:-"..."} turns on GLOB_SUBST, useful for expansion of -- "~/" ($HOME). ${:-"foo"} is the string "foo" as var. shell_cmd = "/usr/bin/env zsh -c 'local -a res; res=( ${~:-" .. string.format('%q', words[cword_index]) .. "}* ); " .. "print -ln -- ${res[@]}'" else -- check commands, aliases, builtins, functions and reswords shell_cmd = "/usr/bin/env zsh -c 'local -a res; ".. "res=( ".. "\"${(k)commands[@]}\" \"${(k)aliases[@]}\" \"${(k)builtins[@]}\" \"${(k)functions[@]}\" \"${(k)reswords[@]}\" ".. "${PWD}/*(:t)".. "); ".. "print -ln -- ${(M)res[@]:#" .. string.format('%q', words[cword_index]) .. "*}'" end else if bashcomp_funcs[words[1]] then -- fairly complex command with inline bash script to get the possible completions shell_cmd = "/usr/bin/env bash -c 'source " .. bashcomp_src .. "; " .. "__print_completions() { for ((i=0;i<${#COMPREPLY[*]};i++)); do echo ${COMPREPLY[i]}; done }; " .. "COMP_WORDS=(" .. command .."); COMP_LINE=\"" .. command .. "\"; " .. "COMP_COUNT=" .. cur_pos .. "; COMP_CWORD=" .. cword_index-1 .. "; " .. bashcomp_funcs[words[1]] .. "; __print_completions'" else shell_cmd = "/usr/bin/env bash -c 'compgen -A " .. comptype .. " " .. string.format('%q', words[cword_index]) .. "'" end end local c, err = io.popen(shell_cmd .. " | sort -u") local output = {} i = 0 if c then while true do local line = c:read("*line") if not line then break end if os.execute("test -d " .. string.format('%q', line)) == 0 then line = line .. "/" end table.insert(output, bash_escape(line)) end c:close() else print(err) end -- no completion, return if #output == 0 then return command, cur_pos end -- cycle while ncomp > #output do ncomp = ncomp - #output end local str = command:sub(1, cword_start - 1) .. output[ncomp] .. command:sub(cword_end) cur_pos = cword_end + #output[ncomp] + 1 return str, cur_pos, output end --- Run a generic completion. -- For this function to run properly the awful.completion.keyword table should -- be fed up with all keywords. The completion is run against these keywords. -- @param text The current text the user had typed yet. -- @param cur_pos The current cursor position. -- @param ncomp The number of yet requested completion using current text. -- @param keywords The keywords table uised for completion. -- @return The new match, the new cursor position, the table of all matches. function completion.generic(text, cur_pos, ncomp, keywords) -- The keywords table may be empty if #keywords == 0 then return text, #text + 1 end -- if no text had been typed yet, then we could start cycling around all -- keywords with out filtering and move the cursor at the end of keyword if text == nil or #text == 0 then ncomp = math.fmod(ncomp - 1, #keywords) + 1 return keywords[ncomp], #keywords[ncomp] + 2 end -- Filter out only keywords starting with text local matches = {} for _, x in pairs(keywords) do if x:sub(1, #text) == text then table.insert(matches, x) end end -- if there are no matches just leave out with the current text and position if #matches == 0 then return text, #text + 1, matches end -- cycle around all matches ncomp = math.fmod(ncomp - 1, #matches) + 1 return matches[ncomp], #matches[ncomp] + 1, matches end return completion -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
hb9cwp/snabbswitch
src/dynasm.lua
2
37530
------------------------------------------------------------------------------ -- DynASM. A dynamic assembler for code generation engines. -- Originally designed and implemented for LuaJIT. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- See below for full copyright notice. ------------------------------------------------------------------------------ -- Application information. local _info = { name = "DynASM", description = "A dynamic assembler for code generation engines", version = "1.4.0_luamode", vernum = 10400, release = "2015-10-18", author = "Mike Pall", url = "http://luajit.org/dynasm.html", license = "MIT", copyright = [[ Copyright (C) 2005-2015 Mike Pall. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [ MIT license: http://www.opensource.org/licenses/mit-license.php ] ]], } -- Cache library functions. local type, pairs, ipairs = type, pairs, ipairs local pcall, error, assert = pcall, error, assert local select, tostring = select, tostring local _s = string local sub, match, gmatch, gsub = _s.sub, _s.match, _s.gmatch, _s.gsub local format, rep, upper = _s.format, _s.rep, _s.upper local _t = table local insert, remove, concat, sort = _t.insert, _t.remove, _t.concat, _t.sort local exit = os.exit local io = io local stdin, stdout, stderr = io.stdin, io.stdout, io.stderr -- Helper to update a table with the elements another table. local function update(dst, src) if src then for k,v in pairs(src) do dst[k] = v end end return dst end ------------------------------------------------------------------------------ -- Program options. local g_opt -- Global state for current file. local g_fname, g_curline, g_indent, g_lineno, g_synclineno, g_arch local g_errcount -- Write buffer for output file. local g_wbuffer, g_capbuffer -- Map for defines (initially empty, chains to arch-specific map). local map_def -- Sections names. local map_sections -- The opcode map. Begins as an empty map set to inherit from map_initop, -- It's later changed to inherit from the arch-specific map, which itself is set -- to inherit from map_coreop. local map_op -- The initial opcode map to initialize map_op with on each global reset. local map_initop = {} -- Dummy action flush function. Replaced with arch-specific function later. local function dummy_wflush(term) end local wflush -- Init/reset the global state for processing a new file. local function reset() g_opt = {} g_opt.dumpdef = 0 g_opt.include = { "" } g_opt.lang = nil g_opt.comment = "//|" g_opt.endcomment = "" g_opt.cpp = true -- Write `#line` directives g_fname = nil g_curline = nil g_indent = "" g_lineno = 0 g_synclineno = -1 g_errcount = 0 g_arch = nil g_wbuffer = {} g_capbuffer = nil map_def = {} map_sections = {} map_op = setmetatable({}, { __index = map_initop }) wflush = dummy_wflush end ------------------------------------------------------------------------------ -- Write an output line (or callback function) to the buffer. local function wline(line, needindent) local buf = g_capbuffer or g_wbuffer buf[#buf+1] = needindent and g_indent..line or line g_synclineno = g_synclineno + 1 end -- Write assembler line as a comment, if requestd. local function wcomment(aline) if g_opt.comment then wline(g_opt.comment..aline..g_opt.endcomment, true) end end -- Resync CPP line numbers. local function wsync() if g_synclineno ~= g_lineno and g_opt.cpp then if not g_opt.lang == "lua" then wline("#line "..g_lineno..' "'..g_fname..'"') end g_synclineno = g_lineno end end -- Dump all buffered output lines. local function wdumplines(out, buf) for _,line in ipairs(buf) do if type(line) == "string" then assert(out:write(line, "\n")) else -- Special callback to dynamically insert lines after end of processing. line(out) end end end ------------------------------------------------------------------------------ -- Emit an error. Processing continues with next statement. local function werror(msg) error(format("%s:%s: error: %s:\n%s", g_fname, g_lineno, msg, g_curline), 0) end -- Emit a fatal error. Processing stops. local function wfatal(msg) g_errcount = "fatal" werror(msg) end -- Print a warning. Processing continues. local function wwarn(msg) stderr:write(format("%s:%s: warning: %s:\n%s\n", g_fname, g_lineno, msg, g_curline)) end -- Print caught error message. But suppress excessive errors. local function wprinterr(...) if type(g_errcount) == "number" then -- Regular error. g_errcount = g_errcount + 1 if g_errcount < 21 then -- Seems to be a reasonable limit. stderr:write(...) elseif g_errcount == 21 then stderr:write(g_fname, ":*: warning: too many errors (suppressed further messages).\n") end else -- Fatal error. stderr:write(...) return true -- Stop processing. end end ------------------------------------------------------------------------------ -- Map holding all option handlers. local opt_map = {} local opt_current -- Print error and exit with error status. local function opterror(...) stderr:write("dynasm.lua: ERROR: ", ...) stderr:write("\n") exit(1) end -- Get option parameter. local function optparam(args) local argn = args.argn local p = args[argn] if not p then opterror("missing parameter for option `", opt_current, "'.") end args.argn = argn + 1 return p end ------------------------------------------------------------------------------ -- Core pseudo-opcodes. local map_coreop = {} -- Forward declarations. local dostmt local readfile ------------------------------------------------------------------------------ -- Pseudo-opcode to define a substitution. map_coreop[".define_2"] = function(params, nparams) if not params then return nparams == 1 and "name" or "name, subst" end local name, def = params[1], params[2] or "1" if not match(name, "^[%a_][%w_]*$") then werror("bad or duplicate define") end map_def[name] = def end map_coreop[".define_1"] = map_coreop[".define_2"] -- Define a substitution on the command line. function opt_map.D(args) local namesubst = optparam(args) local name, subst = match(namesubst, "^([%a_][%w_]*)=(.*)$") if name then map_def[name] = subst elseif match(namesubst, "^[%a_][%w_]*$") then map_def[namesubst] = "1" else opterror("bad define") end end -- Undefine a substitution on the command line. function opt_map.U(args) local name = optparam(args) if match(name, "^[%a_][%w_]*$") then map_def[name] = nil else opterror("bad define") end end -- Helper for definesubst. local gotsubst local function definesubst_one(word) local subst = map_def[word] if subst then gotsubst = word; return subst else return word end end -- Iteratively substitute defines. local function definesubst(stmt) -- Limit number of iterations. for i=1,100 do gotsubst = false stmt = gsub(stmt, "#?[%w_]+", definesubst_one) if not gotsubst then break end end if gotsubst then wfatal("recursive define involving `"..gotsubst.."'") end return stmt end -- Dump all defines. local function dumpdefines(out, lvl) local t = {} for name in pairs(map_def) do t[#t+1] = name end sort(t) out:write("Defines:\n") for _,name in ipairs(t) do local subst = map_def[name] if g_arch then subst = g_arch.revdef(subst) end out:write(format(" %-20s %s\n", name, subst)) end out:write("\n") end ------------------------------------------------------------------------------ -- Support variables for conditional assembly. local condlevel = 0 local condstack = {} -- Evaluate condition with a Lua expression. Substitutions already performed. local function cond_eval(cond) local func, err if setfenv then func, err = loadstring("return "..cond, "=expr") else -- No globals. All unknown identifiers evaluate to nil. func, err = load("return "..cond, "=expr", "t", {}) end if func then if setfenv then setfenv(func, {}) -- No globals. All unknown identifiers evaluate to nil. end local ok, res = pcall(func) if ok then if res == 0 then return false end -- Oh well. return not not res end err = res end wfatal("bad condition: "..err) end -- Skip statements until next conditional pseudo-opcode at the same level. local function stmtskip() local dostmt_save = dostmt local lvl = 0 dostmt = function(stmt) local op = match(stmt, "^%s*(%S+)") if op == ".if" then lvl = lvl + 1 elseif lvl ~= 0 then if op == ".endif" then lvl = lvl - 1 end elseif op == ".elif" or op == ".else" or op == ".endif" then dostmt = dostmt_save dostmt(stmt) end end end -- Pseudo-opcodes for conditional assembly. map_coreop[".if_1"] = function(params) if not params then return "condition" end local lvl = condlevel + 1 local res = cond_eval(params[1]) condlevel = lvl condstack[lvl] = res if not res then stmtskip() end end map_coreop[".elif_1"] = function(params) if not params then return "condition" end if condlevel == 0 then wfatal(".elif without .if") end local lvl = condlevel local res = condstack[lvl] if res then if res == "else" then wfatal(".elif after .else") end else res = cond_eval(params[1]) if res then condstack[lvl] = res return end end stmtskip() end map_coreop[".else_0"] = function(params) if condlevel == 0 then wfatal(".else without .if") end local lvl = condlevel local res = condstack[lvl] condstack[lvl] = "else" if res then if res == "else" then wfatal(".else after .else") end stmtskip() end end map_coreop[".endif_0"] = function(params) local lvl = condlevel if lvl == 0 then wfatal(".endif without .if") end condlevel = lvl - 1 end -- Check for unfinished conditionals. local function checkconds() if g_errcount ~= "fatal" and condlevel ~= 0 then wprinterr(g_fname, ":*: error: unbalanced conditional\n") end end ------------------------------------------------------------------------------ -- Search for a file in the given path and open it for reading. local function pathopen(path, name) local dirsep = package and match(package.path, "\\") and "\\" or "/" for _,p in ipairs(path) do local fullname = p == "" and name or p..dirsep..name local fin = io.open(fullname, "r") if fin then g_fname = fullname return fin end end end -- Include a file. map_coreop[".include_1"] = function(params) if not params then return "filename" end local name = params[1] -- Save state. Ugly, I know. but upvalues are fast. local gf, gl, gcl, gi = g_fname, g_lineno, g_curline, g_indent -- Read the included file. local fatal = readfile(pathopen(g_opt.include, name) or wfatal("include file `"..name.."' not found")) -- Restore state. g_synclineno = -1 g_fname, g_lineno, g_curline, g_indent = gf, gl, gcl, gi if fatal then wfatal("in include file") end end -- Make .include and conditionals initially available, too. map_initop[".include_1"] = map_coreop[".include_1"] map_initop[".if_1"] = map_coreop[".if_1"] map_initop[".elif_1"] = map_coreop[".elif_1"] map_initop[".else_0"] = map_coreop[".else_0"] map_initop[".endif_0"] = map_coreop[".endif_0"] ------------------------------------------------------------------------------ -- Support variables for macros. local mac_capture, mac_lineno, mac_name local mac_active = {} local mac_list = {} -- Pseudo-opcode to define a macro. map_coreop[".macro_*"] = function(mparams) if not mparams then return "name [, params...]" end -- Split off and validate macro name. local name = remove(mparams, 1) if not name then werror("missing macro name") end if not (match(name, "^[%a_][%w_%.]*$") or match(name, "^%.[%w_%.]*$")) then wfatal("bad macro name `"..name.."'") end -- Validate macro parameter names. local mdup = {} for _,mp in ipairs(mparams) do if not match(mp, "^[%a_][%w_]*$") then wfatal("bad macro parameter name `"..mp.."'") end if mdup[mp] then wfatal("duplicate macro parameter name `"..mp.."'") end mdup[mp] = true end -- Check for duplicate or recursive macro definitions. local opname = name.."_"..#mparams if map_op[opname] or map_op[name.."_*"] then wfatal("duplicate macro `"..name.."' ("..#mparams.." parameters)") end if mac_capture then wfatal("recursive macro definition") end -- Enable statement capture. local lines = {} mac_lineno = g_lineno mac_name = name mac_capture = function(stmt) -- Statement capture function. -- Stop macro definition with .endmacro pseudo-opcode. if not match(stmt, "^%s*.endmacro%s*$") then lines[#lines+1] = stmt return end mac_capture = nil mac_lineno = nil mac_name = nil mac_list[#mac_list+1] = opname -- Add macro-op definition. map_op[opname] = function(params) if not params then return mparams, lines end -- Protect against recursive macro invocation. if mac_active[opname] then wfatal("recursive macro invocation") end mac_active[opname] = true -- Setup substitution map. local subst = {} for i,mp in ipairs(mparams) do subst[mp] = params[i] end local mcom if g_opt.maccomment and g_opt.comment then mcom = " MACRO "..name.." ("..#mparams..")" wcomment("{"..mcom) end -- Loop through all captured statements for _,stmt in ipairs(lines) do -- Substitute macro parameters. local st = gsub(stmt, "[%w_]+", subst) st = definesubst(st) st = gsub(st, "%s*%.%.%s*", "") -- Token paste a..b. if mcom and sub(st, 1, 1) ~= "|" then wcomment(st) end -- Emit statement. Use a protected call for better diagnostics. local ok, err = pcall(dostmt, st) if not ok then -- Add the captured statement to the error. wprinterr(err, "\n", g_indent, "| ", stmt, "\t[MACRO ", name, " (", #mparams, ")]\n") end end if mcom then wcomment("}"..mcom) end mac_active[opname] = nil end end end -- An .endmacro pseudo-opcode outside of a macro definition is an error. map_coreop[".endmacro_0"] = function(params) wfatal(".endmacro without .macro") end -- Dump all macros and their contents (with -PP only). local function dumpmacros(out, lvl) sort(mac_list) out:write("Macros:\n") for _,opname in ipairs(mac_list) do local name = sub(opname, 1, -3) local params, lines = map_op[opname]() out:write(format(" %-20s %s\n", name, concat(params, ", "))) if lvl > 1 then for _,line in ipairs(lines) do out:write(" |", line, "\n") end out:write("\n") end end out:write("\n") end -- Check for unfinished macro definitions. local function checkmacros() if mac_capture then wprinterr(g_fname, ":", mac_lineno, ": error: unfinished .macro `", mac_name ,"'\n") end end ------------------------------------------------------------------------------ -- Support variables for captures. local cap_lineno, cap_name local cap_buffers = {} local cap_used = {} -- Start a capture. map_coreop[".capture_1"] = function(params) if not params then return "name" end wflush() local name = params[1] if not match(name, "^[%a_][%w_]*$") then wfatal("bad capture name `"..name.."'") end if cap_name then wfatal("already capturing to `"..cap_name.."' since line "..cap_lineno) end cap_name = name cap_lineno = g_lineno -- Create or continue a capture buffer and start the output line capture. local buf = cap_buffers[name] if not buf then buf = {}; cap_buffers[name] = buf end g_capbuffer = buf g_synclineno = 0 end -- Stop a capture. map_coreop[".endcapture_0"] = function(params) wflush() if not cap_name then wfatal(".endcapture without a valid .capture") end cap_name = nil cap_lineno = nil g_capbuffer = nil g_synclineno = 0 end -- Dump a capture buffer. map_coreop[".dumpcapture_1"] = function(params) if not params then return "name" end wflush() local name = params[1] if not match(name, "^[%a_][%w_]*$") then wfatal("bad capture name `"..name.."'") end cap_used[name] = true wline(function(out) local buf = cap_buffers[name] if buf then wdumplines(out, buf) end end) g_synclineno = 0 end -- Dump all captures and their buffers (with -PP only). local function dumpcaptures(out, lvl) out:write("Captures:\n") for name,buf in pairs(cap_buffers) do out:write(format(" %-20s %4s)\n", name, "("..#buf)) if lvl > 1 then local bar = rep("=", 76) out:write(" ", bar, "\n") for _,line in ipairs(buf) do out:write(" ", line, "\n") end out:write(" ", bar, "\n\n") end end out:write("\n") end -- Check for unfinished or unused captures. local function checkcaptures() if cap_name then wprinterr(g_fname, ":", cap_lineno, ": error: unfinished .capture `", cap_name,"'\n") return end for name in pairs(cap_buffers) do if not cap_used[name] then wprinterr(g_fname, ":*: error: missing .dumpcapture ", name ,"\n") end end end ------------------------------------------------------------------------------ -- Pseudo-opcode to define code sections. -- TODO: Data sections, BSS sections. Needs extra C code and API. map_coreop[".section_*"] = function(params) if not params then return "name..." end if #map_sections > 0 then werror("duplicate section definition") end wflush() for sn,name in ipairs(params) do local opname = "."..name.."_0" if not match(name, "^[%a][%w_]*$") or map_op[opname] or map_op["."..name.."_*"] then werror("bad section name `"..name.."'") end map_sections[#map_sections+1] = name if g_opt.lang == "lua" then wline(format("local DASM_SECTION_%s\t= %d", upper(name), sn-1)) else wline(format("#define DASM_SECTION_%s\t%d", upper(name), sn-1)) end map_op[opname] = function(params) g_arch.section(sn-1) end end if g_opt.lang == "lua" then wline(format("local DASM_MAXSECTION\t= %d", #map_sections)) else wline(format("#define DASM_MAXSECTION\t\t%d", #map_sections)) end end -- Dump all sections. local function dumpsections(out, lvl) out:write("Sections:\n") for _,name in ipairs(map_sections) do out:write(format(" %s\n", name)) end out:write("\n") end ------------------------------------------------------------------------------ -- Replacement for customized Lua, which lacks the package library. local prefix = "" if not require then function require(name) local fp = assert(io.open(prefix..name..".lua")) local s = fp:read("*a") assert(fp:close()) return assert(loadstring(s, "@"..name..".lua"))() end end -- Load architecture-specific module. local function loadarch(arch) if not match(arch, "^[%w_]+$") then return "bad arch name" end local ok, m_arch = pcall(require, "dasm_"..arch) if not ok then return "cannot load module: "..m_arch end g_arch = m_arch wflush = m_arch.passcb(wline, werror, wfatal, wwarn) m_arch.setup(arch, g_opt) local arch_map_op arch_map_op, map_def = m_arch.mergemaps(map_coreop, map_def) map_op = setmetatable(map_op, { __index = arch_map_op }) end -- Dump architecture description. function opt_map.dumparch(args) local name = optparam(args) if not g_arch then local err = loadarch(name) if err then opterror(err) end end local t = {} for name in pairs(map_coreop) do t[#t+1] = name end for name in pairs(map_op) do t[#t+1] = name end sort(t) local out = stdout local _arch = g_arch._info out:write(format("%s version %s, released %s, %s\n", _info.name, _info.version, _info.release, _info.url)) g_arch.dumparch(out) local pseudo = true out:write("Pseudo-Opcodes:\n") for _,sname in ipairs(t) do local name, nparam = match(sname, "^(.+)_([0-9%*])$") if name then if pseudo and sub(name, 1, 1) ~= "." then out:write("\nOpcodes:\n") pseudo = false end local f = map_op[sname] local s if nparam ~= "*" then nparam = nparam + 0 end if nparam == 0 then s = "" elseif type(f) == "string" then s = map_op[".template__"](nil, f, nparam) else s = f(nil, nparam) end if type(s) == "table" then for _,s2 in ipairs(s) do out:write(format(" %-12s %s\n", name, s2)) end else out:write(format(" %-12s %s\n", name, s)) end end end out:write("\n") exit(0) end -- Pseudo-opcode to set the architecture. -- Only initially available (map_op is replaced when called). map_initop[".arch_1"] = function(params) if not params then return "name" end local err = loadarch(params[1]) if err then wfatal(err) end if g_opt.lang == "lua" then wline(format("if dasm._VERSION ~= %d then", _info.vernum)) wline(' error("Version mismatch between DynASM and included encoding engine")') wline("end") else wline(format("#if DASM_VERSION != %d", _info.vernum)) wline('#error "Version mismatch between DynASM and included encoding engine"') wline("#endif") end end -- Dummy .arch pseudo-opcode to improve the error report. map_coreop[".arch_1"] = function(params) if not params then return "name" end if g_arch._info.arch ~= params[1] then wfatal("invalid .arch statement. arch already loaded: `", g_arch._info.arch, "`.") end end ------------------------------------------------------------------------------ -- Dummy pseudo-opcode. Don't confuse '.nop' with 'nop'. map_coreop[".nop_*"] = function(params) if not params then return "[ignored...]" end end -- Pseudo-opcodes to raise errors. map_coreop[".error_1"] = function(params) if not params then return "message" end werror(params[1]) end map_coreop[".fatal_1"] = function(params) if not params then return "message" end wfatal(params[1]) end -- Dump all user defined elements. local function dumpdef(out) local lvl = g_opt.dumpdef if lvl == 0 then return end dumpsections(out, lvl) dumpdefines(out, lvl) if g_arch then g_arch.dumpdef(out, lvl) end dumpmacros(out, lvl) dumpcaptures(out, lvl) end ------------------------------------------------------------------------------ -- Helper for splitstmt. local splitlvl local function splitstmt_one(c) if c == "(" then splitlvl = ")"..splitlvl elseif c == "[" then splitlvl = "]"..splitlvl elseif c == "{" then splitlvl = "}"..splitlvl elseif c == ")" or c == "]" or c == "}" then if sub(splitlvl, 1, 1) ~= c then werror("unbalanced (), [] or {}") end splitlvl = sub(splitlvl, 2) elseif splitlvl == "" then return " \0 " end return c end -- Split statement into (pseudo-)opcode and params. local function splitstmt(stmt) -- Convert label with trailing-colon into .label statement. local label = match(stmt, "^%s*(.+):%s*$") if label then return ".label", {label} end -- Split at commas and equal signs, but obey parentheses and brackets. splitlvl = "" stmt = gsub(stmt, "[,%(%)%[%]{}]", splitstmt_one) if splitlvl ~= "" then werror("unbalanced () or []") end -- Split off opcode. local op, other = match(stmt, "^%s*([^%s%z]+)%s*(.*)$") if not op then werror("bad statement syntax") end -- Split parameters. local params = {} for p in gmatch(other, "%s*(%Z+)%z?") do params[#params+1] = gsub(p, "%s+$", "") end if #params > 16 then werror("too many parameters") end params.op = op return op, params end -- Process a single statement. dostmt = function(stmt) -- Ignore empty statements. if match(stmt, "^%s*$") then return end -- Capture macro defs before substitution. if mac_capture then return mac_capture(stmt) end stmt = definesubst(stmt) -- Emit C code without parsing the line. if sub(stmt, 1, 1) == "|" then local tail = sub(stmt, 2) wflush() if sub(tail, 1, 2) == "//" then wcomment(tail) else wline(tail, true) end return end -- Split into (pseudo-)opcode and params. local op, params = splitstmt(stmt) -- Get opcode handler (matching # of parameters or generic handler). local f = map_op[op.."_"..#params] or map_op[op.."_*"] if not f then if not g_arch then wfatal("first statement must be .arch") end -- Improve error report. for i=0,9 do if map_op[op.."_"..i] then werror("wrong number of parameters for `"..op.."'") end end werror("unknown statement `"..op.."'") end -- Call opcode handler or special handler for template strings. if type(f) == "string" then map_op[".template__"](params, f) else f(params) end end -- Process a single line. local function doline(line) if g_opt.flushline then wflush() end -- Assembler line? local indent, aline = match(line, "^(%s*)%|(.*)$") if not aline then -- No, plain C code line, need to flush first. wflush() wsync() wline(line, false) return end g_indent = indent -- Remember current line indentation. -- Emit C code (even from macros). Avoids echo and line parsing. if sub(aline, 1, 1) == "|" then if not mac_capture then wsync() elseif g_opt.comment then wsync() wcomment(aline) end dostmt(aline) return end -- Echo assembler line as a comment. if g_opt.comment then wsync() wcomment(aline) end -- Strip assembler comments. aline = gsub(aline, "//.*$", "") if g_opt.lang == "lua" then aline = gsub(aline, "%-%-.*$", "") end -- Split line into statements at semicolons. if match(aline, ";") then for stmt in gmatch(aline, "[^;]+") do dostmt(stmt) end else dostmt(aline) end end ------------------------------------------------------------------------------ -- Write DynASM header. local function dasmhead(out) if not g_opt.comment then return end if g_opt.lang == "lua" then out:write(format([[ -- -- This file has been pre-processed with DynASM. -- %s -- DynASM version %s, DynASM %s version %s -- DO NOT EDIT! The original file is in "%s". -- ]], _info.url, _info.version, g_arch._info.arch, g_arch._info.version, g_fname)) else out:write(format([[ /* ** This file has been pre-processed with DynASM. ** %s ** DynASM version %s, DynASM %s version %s ** DO NOT EDIT! The original file is in "%s". */ ]], _info.url, _info.version, g_arch._info.arch, g_arch._info.version, g_fname)) end end -- Read input file. readfile = function(fin) -- Process all lines. for line in fin:lines() do g_lineno = g_lineno + 1 g_curline = line local ok, err = pcall(doline, line) if not ok and wprinterr(err, "\n") then return true end end wflush() -- Close input file. assert(fin == stdin or fin:close()) end -- Write output file. local function writefile(outfile) local fout -- Open output file. if outfile == nil or outfile == "-" then fout = stdout elseif type(outfile) == "string" then fout = assert(io.open(outfile, "w")) else fout = outfile end -- Write all buffered lines wdumplines(fout, g_wbuffer) -- Close output file. assert(fout == stdout or fout:close()) -- Optionally dump definitions. dumpdef(fout == stdout and stderr or stdout) end -- Translate an input file to an output file. local function translate(infile, outfile) -- Put header. wline(dasmhead) -- Read input file. local fin if infile == "-" then g_fname = "(stdin)" fin = stdin elseif type(infile) == "string" then g_fname = infile fin = assert(io.open(infile, "r")) else g_fname = "=(translate)" fin = infile end readfile(fin) -- Check for errors. if not g_arch then wprinterr(g_fname, ":*: error: missing .arch directive\n") end checkconds() checkmacros() checkcaptures() if g_errcount ~= 0 then stderr:write(g_fname, ":*: info: ", g_errcount, " error", (type(g_errcount) == "number" and g_errcount > 1) and "s" or "", " in input file -- no output file generated.\n") dumpdef(stderr) exit(1) end -- Write output file. writefile(outfile) end ------------------------------------------------------------------------------ -- Print help text. function opt_map.help() stdout:write("DynASM -- ", _info.description, ".\n") stdout:write("DynASM ", _info.version, " ", _info.release, " ", _info.url, "\n") stdout:write[[ Usage: dynasm [OPTION]... INFILE.dasc|INFILE.dasl|- -h, --help Display this help text. -V, --version Display version and copyright information. -o, --outfile FILE Output file name (default is stdout). -I, --include DIR Add directory to the include search path. -l, --lang C|Lua Generate C or Lua code (default C for dasc, Lua for dasl). -c, --ccomment Use /* */ comments for assembler lines. -C, --cppcomment Use // comments for assembler lines (default). -N, --nocomment Suppress assembler lines in output. -M, --maccomment Show macro expansions as comments (default off). -L, --nolineno Suppress CPP line number information in output. -F, --flushline Flush action list for every line. -D NAME[=SUBST] Define a substitution. -U NAME Undefine a substitution. -P, --dumpdef Dump defines, macros, etc. Repeat for more output. -A, --dumparch ARCH Load architecture ARCH and dump description. ]] exit(0) end -- Print version information. function opt_map.version() stdout:write(format("%s version %s, released %s\n%s\n\n%s", _info.name, _info.version, _info.release, _info.url, _info.copyright)) exit(0) end -- Misc. options. function opt_map.lang(args) g_opt.lang = optparam(args):lower() end function opt_map.outfile(args) g_opt.outfile = optparam(args) end function opt_map.include(args) insert(g_opt.include, 1, optparam(args)) end function opt_map.ccomment() g_opt.comment = "/*|"; g_opt.endcomment = " */" end function opt_map.cppcomment() g_opt.comment = "//|"; g_opt.endcomment = "" end function opt_map.nocomment() g_opt.comment = false end function opt_map.maccomment() g_opt.maccomment = true end function opt_map.nolineno() g_opt.cpp = false end function opt_map.flushline() g_opt.flushline = true end function opt_map.dumpdef() g_opt.dumpdef = g_opt.dumpdef + 1 end ------------------------------------------------------------------------------ -- Short aliases for long options. local opt_alias = { h = "help", ["?"] = "help", V = "version", o = "outfile", I = "include", l = "lang", c = "ccomment", C = "cppcomment", N = "nocomment", M = "maccomment", L = "nolineno", F = "flushline", P = "dumpdef", A = "dumparch", } -- Parse single option. local function parseopt(opt, args) opt_current = #opt == 1 and "-"..opt or "--"..opt local f = opt_map[opt] or opt_map[opt_alias[opt]] if not f then opterror("unrecognized option `", opt_current, "'. Try `--help'.\n") end f(args) end local languages = {c = true, lua = true} local langext = {dasc = "c", dasl = "lua"} --Set language options (Lua or C code gen) based on file extension. local function setlang(infile) -- Infer language from file extension, if `lang` not set. if not g_opt.lang and type(infile) == "string" then g_opt.lang = langext[match(infile, "%.([^%.]+)$")] or "c" end -- Check that the `lang` option is valid. if not languages[g_opt.lang] then opterror("invalid language `", tostring(g_opt.lang), "`.") end -- Adjust comment options for Lua mode. if g_opt.lang == "lua" then if g_opt.comment then g_opt.cpp = false g_opt.comment = "--|" g_opt.endcomment = "" end end -- Set initial defines only available in Lua mode. local ffi = require'ffi' map_def.ARCH = ffi.arch --for `.arch ARCH` map_def[upper(ffi.arch)] = 1 --for `.if X86 ...` map_def.OS = ffi.os --for `.if OS == 'Windows'` map_def[upper(ffi.os)] = 1 --for `.if WINDOWS ...` end -- Parse arguments. local function parseargs(args) --Reset globals. reset() -- Process all option arguments. args.argn = 1 repeat local a = args[args.argn] if not a then break end local lopt, opt = match(a, "^%-(%-?)(.+)") if not opt then break end args.argn = args.argn + 1 if lopt == "" then -- Loop through short options. for o in gmatch(opt, ".") do parseopt(o, args) end else -- Long option. parseopt(opt, args) end until false -- Check for proper number of arguments. local nargs = #args - args.argn + 1 if nargs ~= 1 then if nargs == 0 then if g_opt.dumpdef > 0 then return dumpdef(stdout) end end opt_map.help() end local infile = args[args.argn] -- Set language options. setlang(infile) -- Translate a single input file to a single output file -- TODO: Handle multiple files? translate(infile, g_opt.outfile) end ------------------------------------------------------------------------------ if ... == "dynasm" then -- use as module -- Make a reusable translate() function with support for setting options. local translate = function(infile, outfile, opt) reset() update(g_opt, opt) setlang(infile) if g_opt.subst then for name, subst in pairs(g_opt.subst) do map_def[name] = tostring(subst) end end translate(infile, outfile) end -- Dummy file:close() method. local function dummyclose() return true end -- Create a pseudo-file object that implements the file:lines() method -- which reads data from a string. local function string_infile(s) local lines = function() local term = match(s, "\r\n") and "\r\n" or match(s, "\r") and "\r" or match(s, "\n") and "\n" or "" return gmatch(s, "([^\n\r]*)"..term) end return {lines = lines, close = dummyclose} end -- Create a pseudo-file object that implements the file:write() method -- which forwards each non-empty value to a function. local function func_outfile(func) local function write(_, ...) for i = 1, select('#', ...) do local v = select(i, ...) assert(type(v) == "string" or type(v) == "number", "invalid value") local s = tostring(v) if #s > 0 then func(s) end end return true end return {write = write, close = dummyclose} end -- Create a pseudo-file object that accumulates writes to a table. local function table_outfile(t) return func_outfile(function(s) t[#t+1] = s end) end -- Translate an input file to a string. local function translate_tostring(infile, opt) local t = {} translate(infile, table_outfile(t), opt) return table.concat(t) end -- Create an iterator that translates an input file -- and returns the translated file in chunks. local function translate_toiter(infile, opt) return coroutine.wrap(function() translate(infile, func_outfile(coroutine.yield), opt) end) end -- Load a dasl file and return it as a Lua chunk. local function dasl_loadfile(infile, opt) local opt = update({lang = "lua"}, opt) local read = translate_toiter(infile, opt) local filename = type(infile) == "string" and infile or "=(load)" return load(read, filename) end -- Load a dasl string and return it as a Lua chunk. local function dasl_loadstring(s, opt) return dasl_loadfile(string_infile(s), opt) end -- Register a module loader for *.dasl files. insert(package.loaders, function(modname) local daslpath = gsub(gsub(package.path, "%.lua;", ".dasl;"), "%.lua$", ".dasl") local path, reason = package.searchpath(modname, daslpath) if not path then return reason end return function() local chunk = assert(dasl_loadfile(path, {comment = false})) return chunk(modname) end end) -- Make and return the DynASM API. return { --low-level intf. translate = translate, string_infile = string_infile, func_outfile = func_outfile, table_outfile = table_outfile, translate_tostring = translate_tostring, translate_toiter = translate_toiter, --hi-level intf. loadfile = dasl_loadfile, loadstring = dasl_loadstring, } else -- use as standalone script -- Add the directory dynasm.lua resides in to the Lua module search path. local arg = arg if arg and arg[0] then prefix = match(arg[0], "^(.*[/\\])") if package and prefix then package.path = prefix.."?.lua;"..package.path end end -- Start DynASM. parseargs{...} end ------------------------------------------------------------------------------
apache-2.0
FFXIOrgins/FFXIOrgins
scripts/zones/Temenos/mobs/Airi.lua
17
1277
----------------------------------- -- Area: Temenos Central 1floor -- NPC: Airi ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) if(IsMobDead(16929047)==true)then mob:addStatusEffect(EFFECT_REGAIN,7,3,0); mob:addStatusEffect(EFFECT_REGEN,50,3,0); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); if(IsMobDead(16929046)==true and IsMobDead(16929047)==true and IsMobDead(16929048)==true and IsMobDead(16929049)==true and IsMobDead(16929050)==true and IsMobDead(16929051)==true)then GetNPCByID(16928768+71):setPos(mobX,mobY,mobZ); GetNPCByID(16928768+71):setStatus(STATUS_NORMAL); GetNPCByID(16928770+471):setStatus(STATUS_NORMAL); end end;
gpl-3.0
subzrk/BadRotations
Libs/DiesalGUI-1.0/Objects/Window.lua
1
12116
-- $Id: Window.lua 60 2016-11-04 01:34:23Z diesal2010 $ local DiesalGUI = LibStub("DiesalGUI-1.0") -- | Libraries |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local DiesalTools = LibStub("DiesalTools-1.0") local DiesalStyle = LibStub("DiesalStyle-1.0") local Colors = DiesalStyle.Colors -- | Lua Upvalues |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local type, select, pairs, tonumber = type, select, pairs, tonumber local floor, ceil = math.floor, math.ceil -- | WoW Upvalues |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- | Window |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local Type = "Window" local Version = 14 -- ~~| Stylesheets |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local Stylesheet = { ['frame-outline'] = { type = 'outline', layer = 'BACKGROUND', color = '000000', }, ['frame-shadow'] = { type = 'shadow', }, ['titleBar-color'] = { type = 'texture', layer = 'BACKGROUND', color = '000000', alpha = .95, }, ['titletext-Font'] = { type = 'font', color = 'd8d8d8', }, ['closeButton-icon'] = { type = 'texture', layer = 'ARTWORK', image = {'DiesalGUIcons', {9,5,16,256,128}}, alpha = .3, position = {-2,nil,-1,nil}, width = 16, height = 16, }, ['closeButton-iconHover'] = { type = 'texture', layer = 'HIGHLIGHT', image = {'DiesalGUIcons', {9,5,16,256,128}, 'b30000'}, alpha = 1, position = {-2,nil,-1,nil}, width = 16, height = 16, }, ['header-background'] = { type = 'texture', layer = 'BACKGROUND', gradient = {'VERTICAL',Colors.UI_400_GR[1],Colors.UI_400_GR[2]}, alpha = .95, position = {0,0,0,-1}, }, ['header-inline'] = { type = 'outline', layer = 'BORDER', gradient = {'VERTICAL','ffffff','ffffff'}, alpha = {.05,.02}, position = {0,0,0,-1}, }, ['header-divider'] = { type = 'texture', layer = 'BORDER', color = '000000', alpha = 1, position = {0,0,nil,0}, height = 1, }, ['content-background'] = { type = 'texture', layer = 'BACKGROUND', color = Colors.UI_100, alpha = .95, }, ['content-outline'] = { type = 'outline', layer = 'BORDER', color = 'FFFFFF', alpha = .01 }, ['footer-background'] = { type = 'texture', layer = 'BACKGROUND', gradient = {'VERTICAL',Colors.UI_400_GR[1],Colors.UI_400_GR[2]}, alpha = .95, position = {0,0,-1,0}, }, ['footer-divider'] = { type = 'texture', layer = 'BACKGROUND', color = '000000', position = {0,0,0,nil}, height = 1, }, ['footer-inline'] = { type = 'outline', layer = 'BORDER', gradient = {'VERTICAL','ffffff','ffffff'}, alpha = {.05,.02}, position = {0,0,-1,0}, debug = true, }, } local wireFrame = { ['frame-white'] = { type = 'outline', layer = 'OVERLAY', color = 'ffffff', }, ['titleBar-yellow'] = { type = 'outline', layer = 'OVERLAY', color = 'fffc00', }, ['closeButton-orange'] = { type = 'outline', layer = 'OVERLAY', color = 'ffd400', }, ['header-blue'] = { type = 'outline', layer = 'OVERLAY', color = '00aaff', }, ['footer-green'] = { type = 'outline', layer = 'OVERLAY', color = '55ff00', }, } local sizerWireFrame = { ['sizerR-yellow'] = { type = 'outline', layer = 'OVERLAY', color = 'fffc00', }, ['sizerB-green'] = { type = 'outline', layer = 'OVERLAY', color = '55ff00', }, ['sizerBR-blue'] = { type = 'outline', layer = 'OVERLAY', color = '00aaff', }, } -- | Window Locals |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local function round(num) if num >= 0 then return floor(num+.5) else return ceil(num-.5) end end -- | Methods |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local methods = { ['OnAcquire'] = function(self) self:ApplySettings() self:SetStylesheet(Stylesheet) -- self:SetStylesheet(sizerWireFrame) self:Show() end, ['OnRelease'] = function(self) end, ['SetTopLevel'] = function(self) DiesalGUI:SetTopLevel(self.frame) end, ['SetContentHeight'] = function(self, height) local contentHeight = round(self.content:GetHeight()) self.frame:SetHeight( (self.settings.height - contentHeight) + height ) end, ['ApplySettings'] = function(self) local settings = self.settings local frame = self.frame local titleBar = self.titleBar local closeButton = self.closeButton local header = self.header local content = self.content local footer = self.footer local headerHeight = settings.header and settings.headerHeight or 0 local footerHeight = settings.footer and settings.footerHeight or 0 frame:SetMinResize(settings.minWidth,settings.minHeight) frame:SetMaxResize(settings.maxWidth,settings.maxHeight) self:UpdatePosition() self:UpdateSizers() titleBar:SetHeight(settings.titleBarHeight) closeButton:SetHeight(settings.titleBarHeight) closeButton:SetWidth(settings.titleBarHeight) content:SetPoint("TOPLEFT",settings.padding[1],-(settings.titleBarHeight + headerHeight)) content:SetPoint("BOTTOMRIGHT",-settings.padding[2],footerHeight + settings.padding[4]) header:SetHeight(headerHeight) footer:SetHeight(footerHeight) header[settings.header and "Show" or "Hide"](header) footer[settings.footer and "Show" or "Hide"](footer) header:SetPoint("TOPLEFT",self.titleBar,"BOTTOMLEFT",settings.padding[1],0) header:SetPoint("TOPRIGHT",self.titleBar,"BOTTOMRIGHT",-settings.padding[2],0) footer:SetPoint("BOTTOMLEFT",settings.padding[1],settings.padding[4]) footer:SetPoint("BOTTOMRIGHT",-settings.padding[2],settings.padding[4]) end, ['UpdatePosition'] = function(self) self.frame:ClearAllPoints() if self.settings.top and self.settings.left then self.frame:SetPoint("TOP",UIParent,"BOTTOM",0,self.settings.top) self.frame:SetPoint("LEFT",UIParent,"LEFT",self.settings.left,0) else self.frame:SetPoint("CENTER",UIParent,"CENTER") end self.frame:SetWidth(self.settings.width) self.frame:SetHeight(self.settings.height) end, ['UpdateSizers'] = function(self) local settings = self.settings local frame = self.frame local sizerB = self.sizerB local sizerR = self.sizerR local sizerBR = self.sizerBR sizerBR[settings.sizerBR and "Show" or "Hide"](sizerBR) sizerBR:SetSize(settings.sizerBRWidth,settings.sizerBRHeight) sizerB[settings.sizerB and "Show" or "Hide"](sizerB) sizerB:SetHeight(settings.sizerHeight) sizerB:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-settings.sizerBRWidth,0) sizerR[settings.sizerR and "Show" or "Hide"](sizerR) sizerR:SetWidth(settings.sizerWidth) sizerR:SetPoint("TOPRIGHT",frame,"TOPRIGHT",0,-settings.titleBarHeight) sizerR:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",0,settings.sizerBRHeight) end, ['SetTitle'] = function(self,title,subtitle) local settings = self.settings settings.title = title or settings.title settings.subTitle = subtitle or settings.subTitle self.titletext:SetText(('%s |cff7f7f7f%s'):format(settings.title,settings.subTitle)) end, } -- | Constructor |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local function Constructor() local self = DiesalGUI:CreateObjectBase(Type) local frame = CreateFrame('Frame',nil,UIParent) self.frame = frame self.defaults = { height = 300, width = 500, minHeight = 200, minWidth = 200, maxHeight = 9999, maxWidth = 9999, left = nil, top = nil, titleBarHeight= 18, title = '', subTitle = '', padding = {1,1,0,1}, header = false, headerHeight = 21, footer = false, footerHeight = 21, sizerR = true, sizerB = true, sizerBR = true, sizerWidth = 6, sizerHeight = 6, sizerBRHeight = 6, sizerBRWidth = 6, } -- ~~ Events ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- OnAcquire, OnRelease, OnHeightSet, OnWidthSet -- OnSizeChanged, OnDragStop, OnHide, OnShow, OnClose -- ~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ frame:EnableMouse() frame:SetMovable(true) frame:SetResizable(true) frame:SetScript("OnMouseDown", function(this,button) DiesalGUI:OnMouse(this,button) end) frame:SetScript("OnSizeChanged", function(this,width,height) self.settings.width = DiesalTools.Round(width) self.settings.height = DiesalTools.Round(height) self:FireEvent( "OnSizeChanged", self.settings.width, self.settings.height ) end) frame:SetScript("OnHide",function(this) self:FireEvent("OnHide") end) frame:SetScript("OnShow",function(this) self:FireEvent("OnShow") end) frame:SetToplevel(true) frame.obj = self local titleBar = self:CreateRegion("Button", 'titleBar', frame) titleBar:SetPoint("TOPLEFT") titleBar:SetPoint("TOPRIGHT") titleBar:EnableMouse() titleBar:SetScript("OnMouseDown",function(this,button) DiesalGUI:OnMouse(this,button) frame:StartMoving() end) titleBar:SetScript("OnMouseUp", function(this) frame:StopMovingOrSizing() self.settings.top = DiesalTools.Round(frame:GetTop()) self.settings.left = DiesalTools.Round(frame:GetLeft()) self:UpdatePosition() self:FireEvent( "OnDragStop", self.settings.left, self.settings.top ) end) local closeButton = self:CreateRegion("Button", 'closeButton', titleBar) closeButton:SetPoint("TOPRIGHT", -1, 1) closeButton:SetScript("OnClick", function(this,button) DiesalGUI:OnMouse(this,button) PlaySound("gsTitleOptionExit") self:FireEvent("OnClose") self:Hide() end) local titletext = self:CreateRegion("FontString", 'titletext', titleBar) titletext:SetWordWrap(false) titletext:SetPoint("TOPLEFT", 4, -5) titletext:SetPoint("TOPRIGHT", -20, -5) titletext:SetJustifyH("TOP") titletext:SetJustifyH("LEFT") self:CreateRegion("Frame", 'header', frame) self:CreateRegion("Frame", 'content', frame) self:CreateRegion("Frame", 'footer', frame) local sizerBR = self:CreateRegion("Frame", 'sizerBR', frame) sizerBR:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",0,0) sizerBR:EnableMouse() sizerBR:SetScript("OnMouseDown",function(this,button) DiesalGUI:OnMouse(this,button) frame:StartSizing("BOTTOMRIGHT") end) sizerBR:SetScript("OnMouseUp", function(this) frame:StopMovingOrSizing() self:UpdatePosition() self:FireEvent( "OnSizeStop", self.settings.width, self.settings.height ) end) local sizerB = self:CreateRegion("Frame", 'sizerB', frame) sizerB:SetPoint("BOTTOMLEFT",frame,"BOTTOMLEFT",0,0) sizerB:EnableMouse() sizerB:SetScript("OnMouseDown",function(this,button) DiesalGUI:OnMouse(this,button) frame:StartSizing("BOTTOM") end) sizerB:SetScript("OnMouseUp", function(this) frame:StopMovingOrSizing() self:UpdatePosition() self:FireEvent( "OnSizeStop", self.settings.width, self.settings.height ) end) local sizerR = self:CreateRegion("Frame", 'sizerR', frame) sizerR:EnableMouse() sizerR:SetScript("OnMouseDown",function(this,button) DiesalGUI:OnMouse(this,button) frame:StartSizing("RIGHT") end) sizerR:SetScript("OnMouseUp", function(this) frame:StopMovingOrSizing() self:UpdatePosition() self:FireEvent( "OnSizeStop", self.settings.width, self.settings.height ) end) -- ~~ Methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ for method, func in pairs(methods) do self[method] = func end -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ return self end DiesalGUI:RegisterObjectConstructor(Type,Constructor,Version)
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/items/galette_des_rois.lua
39
1322
----------------------------------------- -- ID: 5875 -- Item: Galette Des Rois -- Food Effect: 180 Min, All Races ----------------------------------------- -- MP % 1 -- Intelligence +2 -- Random Jewel ----------------------------------------- require("scripts/globals/status"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD)) then result = 246; end if (target:getFreeSlotsCount() == 0) then result = 308; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5875); local rand = math.random(784,815); target:addItem(rand); -- Random Jewel end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPP, 1); target:addMod(MOD_INT, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPP, 1); target:delMod(MOD_INT, 2); end;
gpl-3.0
sjznxd/luci-0.11-aa
protocols/ipv6/luasrc/model/cbi/admin_network/proto_6to4.lua
12
1276
--[[ LuCI - Lua Configuration Interface Copyright 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 ]]-- local map, section, net = ... local ipaddr, defaultroute, metric, ttl, mtu ipaddr = section:taboption("general", Value, "ipaddr", translate("Local IPv4 address"), translate("Leave empty to use the current WAN address")) ipaddr.datatype = "ip4addr" defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface")) ttl.placeholder = "64" ttl.datatype = "range(1,255)" mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface")) mtu.placeholder = "1280" mtu.datatype = "max(1500)"
apache-2.0
FFXIOrgins/FFXIOrgins
scripts/zones/Dynamis-Xarcabard/mobs/Marquis_Gamygyn.lua
19
1256
----------------------------------- -- Area: Dynamis Xarcabard -- NPC: Marquis Gamygyn ----------------------------------- require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local Animate_Trigger = GetServerVariable("[DynaXarcabard]Boss_Trigger"); if(mob:isInBattlefieldList() == false) then mob:addInBattlefieldList(); Animate_Trigger = Animate_Trigger + 8192; SetServerVariable("[DynaXarcabard]Boss_Trigger",Animate_Trigger); if(Animate_Trigger == 32767) then SpawnMob(17330911); -- 142 SpawnMob(17330912); -- 143 SpawnMob(17330183); -- 177 SpawnMob(17330184); -- 178 activateAnimatedWeapon(); -- Change subanim of all animated weapon end end if(Animate_Trigger == 32767) then killer:messageSpecial(PRISON_OF_SOULS_HAS_SET_FREE); end end;
gpl-3.0
togolwb/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
teahouse/FWServer
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
gitfancode/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
joshimoo/Algorithm-Implementations
Derivative/Lua/Yonaba/derivative_test.lua
26
1356
-- Tests for derivative.lua local drv = require 'derivative' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end local function fuzzyEqual(a, b, eps) local eps = eps or 1e-4 return (math.abs(a - b) < eps) end run('Testing left derivative', function() local f = function(x) return x * x end assert(fuzzyEqual(drv.left(f, 5), 2 * 5)) local f = function(x) return x * x * x end assert(fuzzyEqual(drv.left(f, 5), 3 * 5 * 5)) end) run('Testing right derivative', function() local f = function(x) return x * x end assert(fuzzyEqual(drv.right(f, 5), 2 * 5)) local f = function(x) return x * x * x end assert(fuzzyEqual(drv.right(f, 5), 3 * 5 * 5)) end) run('Testing mid derivative', function() local f = function(x) return x * x end assert(fuzzyEqual(drv.mid(f, 5), 2 * 5)) local f = function(x) return x * x * x end assert(fuzzyEqual(drv.mid(f, 5), 3 * 5 * 5)) end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
msburgess3200/PERP
gamemodes/perp/gamemode/sv_modules/sv_mixing.lua
1
7289
MixRange = 150 local combineSound = Sound("buttons/button19.wav") local function MixItems(objPl, _, tblArgs) local iID = tonumber(tblArgs[1]) local tblMixture for k, v in pairs(MIXTURE_DATABASE) do if(v.ID == iID) then tblMixture = v end end if(not tblMixture) then objPl:Notify("Invalid mixture!") return end if(tblMixture.MixInWorld) then objPl:Notify("You can't create this mixture from the menu. Mix the ingredients together in the game world.") return end local tblRequired = {} for k, v in pairs(tblMixture.Ingredients) do tblRequired[v] = tblRequired[v] or 0 tblRequired[v] = tblRequired[v] + 1 end for i, a in pairs(tblRequired) do if(objPl:GetItemCount(i) < a) then objPl:Notify("You don't have the resources to create this mixture.") return end end for _, req in pairs(tblMixture.Requires) do if(objPl:GetPERPLevel(req[1]) < req[2]) then objPl:Notify("You don't have the required skills to do this.") return end end if(tblMixture.RequiresWaterSource and !GAMEMODE.FindWaterSource(objPl:GetPos(), MixRange)) then objPl:Notify("This mixture requires a water source.") return end if (tblMixture.RequiresHeatSource and !GAMEMODE.FindHeatSource(objPl:GetPos(), MixRange)) then objPl:Notify("This mixture requires a heat source.") return end if (tblMixture.RequiresSawHorse) then if(!GAMEMODE.FindSawHorse(objPl:GetPos(), MixRange)) then objPl:Notify("This mixture requires a saw horse.") return else objPl:GiveExperience(SKILL_WOODWORKING, GAMEMODE.ExperienceForWoordWorking) end end local iResults = tblMixture.Results if(not iResults) then objPl:Notify("Error creating item - invalid mixture result!") return end if(type(iResults) == "string") then objPl:Notify("Error creating item - mixture result is string!!") return end local trd = {} trd.start = objPl:EyePos() trd.endpos = trd.start + objPl:GetAimVector() * 200 trd.filter = objPl local tr = util.TraceLine(trd) local item = ITEM_DATABASE[iResults] if(not item) then objPl:Notify("Error creating item - invalid result from table!") return end if (item.ID == 13) then //weed if !tblMixture.CanMix(objPl) then return; end local newItem = ents.Create("ent_pot"); newItem:SetPos(tr.HitPos + Vector(0, 0, 5)); newItem:Spawn(); newItem:EmitSound(combineSound); newItem.ItemSpawner = objPl; elseif (item.ID == 160) then //cocain if !tblMixture.CanMix(objPl) then return; end local newItem = ents.Create("ent_coca"); newItem:SetPos(tr.HitPos + Vector(0, 0, 5)); newItem:Spawn(); newItem:EmitSound(combineSound); newItem.ItemSpawner = objPl; else if !tblMixture.CanMix(objPl) then return; end local newItem = ents.Create("ent_item") newItem:SetPos(tr.HitPos + Vector(0, 0, 10)) newItem:SetModel(item.WorldModel) newItem:SetContents(item.ID, objPl) newItem:Spawn() newItem:EmitSound(combineSound); newItem.ItemOwner = objPl end for k, v in pairs(tblRequired) do objPl:TakeItemByID(k, v, true) end objPl:GiveExperience(SKILL_CRAFTING, GAMEMODE.ExperienceForCraft) end concommand.Add("perp_mix", MixItems) --[[ local toMake for k, v in pairs(MIXTURE_DATABASE) do if (self:GetTable().Owner:HasMixture(k)) then self:GetTable().Owner.LastAttemptedTable = self:GetTable().Owner.LastAttemptedTable or {} if (!self:GetTable().Owner.LastAttemptedTable[k] || self:GetTable().Owner.LastAttemptedTable[k] <= CurTime()) then self:GetTable().Owner.LastAttemptedTable[k] = CurTime() + 1 local hasFirstItem = false local hasSecondItem = false local checkList = {} // See if our two main ingredients are even involved. for _, req in pairs(v.Ingredients) do checkList[tonumber(req)] = checkList[tonumber(req)] or 0 checkList[tonumber(req)] = checkList[tonumber(req)] + 1 if (!hasFirstItem && req == self:GetTable().ItemID) then hasFirstItem = true elseif (!hasSecondItem && req == Ent:GetTable().ItemID) then hasSecondItem = true end end // Okay, we have the first two ingredients for sure. See if we have the skills. if (hasFirstItem && hasSecondItem) then local hasAllReqs = true for _, req in pairs(v.Requires) do if (self:GetTable().Owner:GetLevel(req[1]) < req[2]) then hasAllReqs = false break end end if (hasAllReqs) then // Wonderful, we have all the reqs. Now make sure we have the rest of the ingredients! for k, v in pairs(ents.FindInSphere(self:GetPos(), MixRange)) do if (v:GetClass() == "ent_item" && v:GetTable().ItemID && (!v:GetTable().Tapped || v:GetTable().Tapped < CurTime()) && checkList[v:GetTable().ItemID]) then checkList[v:GetTable().ItemID] = checkList[v:GetTable().ItemID] - 1 end end local usedAllIngredients = true for k, v in pairs(checkList) do if (v > 0) then usedAllIngredients = false end end if (usedAllIngredients) then // Okay, so we have all ingridients what about water / heat sources? if (!v.RequiresHeatSource || GAMEMODE.FindHeatSource(self:GetPos(), MixRange)) then if (!v.RequiresWaterSource || GAMEMODE.FindWaterSource(self:GetPos(), MixRange)) then // Wonderful, now lets make sure the mixture wants us to do this. if (!v.CanMix || v.CanMix(self:GetTable().Owner, self:GetPos())) then toMake = v break end else self:GetTable().Owner:Notify("This mixture requires a water source.") end else self:GetTable().Owner:Notify("This mixture requires a heat source.") end end end end end end end if (!toMake) then return end local checkList = {} for _, req in pairs(toMake.Ingredients) do checkList[tonumber(req)] = checkList[tonumber(req)] or 0 checkList[tonumber(req)] = checkList[tonumber(req)] + 1 end local oldOwner = self:GetTable().Owner local oldPos = self:GetPos() for k, v in pairs(ents.FindInSphere(self:GetPos(), MixRange)) do if (v:GetClass() == "ent_item" && v:GetTable().ItemID && (!v:GetTable().Tapped || v:GetTable().Tapped < CurTime()) && checkList[v:GetTable().ItemID] && checkList[v:GetTable().ItemID] > 0) then checkList[v:GetTable().ItemID] = checkList[v:GetTable().ItemID] - 1 v:GetTable().Tapped = CurTime() + 5 v:Remove() end end if (toMake.Results == 13) then local newItem = ents.Create("ent_pot") newItem:SetPos(oldPos + Vector(0, 0, 10)) newItem:Spawn() newItem.ItemSpawner = oldOwner elseif (toMake.Results == 69) then local newItem = ents.Create("ent_coca") newItem:SetPos(oldPos + Vector(0, 0, 10)) newItem:Spawn() newItem.ItemSpawner = oldOwner else local results = ITEM_DATABASE[toMake.Results] local newItem = ents.Create("ent_item") newItem:SetPos(oldPos + Vector(0, 0, 10)) newItem:SetModel(results.WorldModel) newItem:SetContents(results.ID, oldOwner) newItem:Spawn() newItem.ItemOwner = self.ItemOwner or NULL end oldOwner:GiveExperience(SKILL_CRAFTING, GAMEMODE.ExperienceForCraft) self:EmitSound(combineSound)]]
mit
FFXIOrgins/FFXIOrgins
scripts/zones/Southern_San_dOria/npcs/Raimbroy.lua
17
3316
----------------------------------- -- Area: Southern San d'Oria -- NPC: Raimbroy -- Starts and Finishes Quest: The Sweetest Things -- @zone 230 -- @pos ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); -- "The Sweetest Things" quest status var theSweetestThings = player:getQuestStatus(SANDORIA,THE_SWEETEST_THINGS); if(theSweetestThings ~= QUEST_AVAILABLE) then if(trade:hasItemQty(4370,5) and trade:getItemCount() == 5) then player:startEvent(0x0217,GIL_RATE*400); else player:startEvent(0x020a); end end if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) theSweetestThings = player:getQuestStatus(SANDORIA, THE_SWEETEST_THINGS); -- "The Sweetest Things" Quest Dialogs if(player:getFameLevel(SANDORIA) >= 2 and theSweetestThings == QUEST_AVAILABLE) then theSweetestThingsVar = player:getVar("theSweetestThings"); if(theSweetestThingsVar == 1) then player:startEvent(0x0215); elseif(theSweetestThingsVar == 2) then player:startEvent(0x0216); else player:startEvent(0x0214); end elseif(theSweetestThings == QUEST_ACCEPTED) then player:startEvent(0x0218); elseif(theSweetestThings == QUEST_COMPLETED) then player:startEvent(0x0219); 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); -- "The Sweetest Things" ACCEPTED if(csid == 0x0214) then player:setVar("theSweetestThings", 1); elseif(csid == 0x0215) then if(option == 0) then player:addQuest(SANDORIA,THE_SWEETEST_THINGS); player:setVar("theSweetestThings", 0); else player:setVar("theSweetestThings", 2); end elseif(csid == 0x0216 and option == 0) then player:addQuest(SANDORIA, THE_SWEETEST_THINGS); player:setVar("theSweetestThings", 0); elseif(csid == 0x0217) then player:tradeComplete(); player:addTitle(APIARIST); player:addGil(GIL_RATE*400); if(player:getQuestStatus(SANDORIA, THE_SWEETEST_THINGS) == QUEST_ACCEPTED) then player:addFame(SANDORIA,SAN_FAME*30); player:completeQuest(SANDORIA, THE_SWEETEST_THINGS); else player:addFame(SANDORIA, SAN_FAME*5); end end end;
gpl-3.0
Arashbrsh/copyuz
plugins/stats.lua
458
4098
-- Saves the number of messages from a user -- Can check the number of messages with !stats do local NUM_MSG_MAX = 5 local TIME_CHECK = 4 -- seconds local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ('..user_id..')' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = '' for k,user in pairs(users_info) do text = text..user.name..' => '..user.msgs..'\n' end return text end -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then print('Service message') return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then print('User '..msg.from.id..'is flooding '..msgs) msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nChats: '..r return text end local function run(msg, matches) if matches[1]:lower() == "stats" then if not matches[2] then if msg.to.type == 'chat' then local chat_id = msg.to.id return chat_stats(chat_id) else return 'Stats works only on chats' end end if matches[2] == "bot" then if not is_sudo(msg) then return "Bot stats requires privileged user" else return bot_stats() end end if matches[2] == "chat" then if not is_sudo(msg) then return "This command requires privileged user" else return chat_stats(matches[3]) end end end end return { description = "Plugin to update user stats.", usage = { "!stats: Returns a list of Username [telegram_id]: msg_num", "!stats chat <chat_id>: Show stats for chat_id", "!stats bot: Shows bot stats (sudo users)" }, patterns = { "^!([Ss]tats)$", "^!([Ss]tats) (chat) (%d+)", "^!([Ss]tats) (bot)" }, run = run, pre_process = pre_process } end
gpl-2.0
msburgess3200/PERP
gamemodes/perp/gamemode/items/furniture_fence.lua
1
1216
local ITEM = {}; ITEM.ID = 55; ITEM.Reference = "furniture_fence"; ITEM.Name = "Wooden Fence"; ITEM.Description = "Designed for both privacy and protection.\n\nLeft click to spawn as prop."; ITEM.Weight = 10; ITEM.Cost = 400; ITEM.MaxStack = 100; ITEM.InventoryModel = "models/props_wasteland/wood_fence01a.mdl"; ITEM.ModelCamPos = Vector(0, 132, 0); ITEM.ModelLookAt = Vector(0, 0, 0); ITEM.ModelFOV = 70; ITEM.WorldModel = "models/props_wasteland/wood_fence01a.mdl"; ITEM.RestrictedSelling = false; // Used for drugs and the like. So we can't sell it. ITEM.EquipZone = nil; ITEM.PredictUseDrop = false; // If this isn't true, the server will tell the client when something happens to us. if SERVER then function ITEM.OnUse ( Player ) local prop = Player:SpawnProp(ITEM); if (!prop || !IsValid(prop)) then return false; end return true; end function ITEM.OnDrop ( Player ) return true; end function ITEM.Equip ( Player ) end function ITEM.Holster ( Player ) end else function ITEM.OnUse ( slotID ) return true; end function ITEM.OnDrop ( ) return true; end end GM:RegisterItem(ITEM);
mit
FFXIOrgins/FFXIOrgins
scripts/zones/Temenos/mobs/Light_Elemental.lua
17
1674
----------------------------------- -- Area: Temenos E T -- NPC: Light_Elemental ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) local mobID = mob:getID(); if(mobID==16929031)then GetMobByID(16929032):updateEnmity(target); GetMobByID(16929030):updateEnmity(target); elseif(mobID==16929032)then GetMobByID(16929031):updateEnmity(target); GetMobByID(16929030):updateEnmity(target); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); switch (mobID): caseof { [16929031] = function (x) if(IsMobDead(16929030)==true and IsMobDead(16929032)==true )then GetNPCByID(16928768+77):setPos(0.5,-6,-459); GetNPCByID(16928768+77):setStatus(STATUS_NORMAL); GetNPCByID(16928768+472):setStatus(STATUS_NORMAL); end end , [16929032] = function (x) if(IsMobDead(16929030)==true and IsMobDead(16929031)==true )then GetNPCByID(16928768+77):setPos(0.5,-6,-459); GetNPCByID(16928768+77):setStatus(STATUS_NORMAL); GetNPCByID(16928768+472):setStatus(STATUS_NORMAL); end end , } end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/zones/Ghelsba_Outpost/bcnms/toadal_recall.lua
10
1477
----------------------------------- -- Area: Ghelsba Outpost -- Name: toadal_recall BCNM30 -- @pos -162 -11 78 140 ----------------------------------- package.loaded["scripts/zones/Ghelsba_Outpost/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Ghelsba_Outpost/TextIDs"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function OnBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function OnBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function OnBcnmLeave(player,instance,leavecode) -- print(leave code ..leavecode); if(leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),2,2,2); elseif(leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print(bc update csid ..csid.. and option ..option); end; function onEventFinish(player,csid,option) -- print(bc finish csid ..csid.. and option ..option); end;
gpl-3.0
gitfancode/skynet
examples/login/msgagent.lua
58
1165
local skynet = require "skynet" skynet.register_protocol { name = "client", id = skynet.PTYPE_CLIENT, unpack = skynet.tostring, } local gate local userid, subid local CMD = {} function CMD.login(source, uid, sid, secret) -- you may use secret to make a encrypted data stream skynet.error(string.format("%s is login", uid)) gate = source userid = uid subid = sid -- you may load user data from database end local function logout() if gate then skynet.call(gate, "lua", "logout", userid, subid) end skynet.exit() end function CMD.logout(source) -- NOTICE: The logout MAY be reentry skynet.error(string.format("%s is logout", userid)) logout() end function CMD.afk(source) -- the connection is broken, but the user may back skynet.error(string.format("AFK")) end skynet.start(function() -- If you want to fork a work thread , you MUST do it in CMD.login skynet.dispatch("lua", function(session, source, command, ...) local f = assert(CMD[command]) skynet.ret(skynet.pack(f(source, ...))) end) skynet.dispatch("client", function(_,_, msg) -- the simple echo service skynet.sleep(10) -- sleep a while skynet.ret(msg) end) end)
mit
MAXtgBOT/Telemax-TG
plugins/setrank-global rank.lua
1
8848
do local ramin = 205903314 --put your id here(BOT OWNER ID) local function setrank(msg, name, value) -- setrank function local hash = nil if msg.to.type == 'chat' then hash = 'rank:variables' end if hash then redis:hset(hash, name, value) return send_msg('chat#id'..msg.to.id, 'مقام کاربر ('..name..') به '..value..' تغییر داده شد ', ok_cb, true) end end local function res_user_callback(extra, success, result) -- /info <username> function if success == 1 then if result.username then Username = '@'..result.username else Username = 'ندارد' end local text = 'نام کامل : '..(result.first_name or '')..' '..(result.last_name or '')..'\n' ..'یوزر: '..Username..'\n' ..'ایدی کاربری : '..result.id..'\n\n' local hash = 'rank:variables' local value = redis:hget(hash, result.id) if not value then if result.id == tonumber(reza) then text = text..'مقام : مدیر کل ربات (Executive Admin) \n\n' elseif is_admin2(result.id) then text = text..'مقام : ادمین ربات (Admin) \n\n' elseif is_owner2(result.id, extra.chat2) then text = text..'مقام : مدیر کل گروه (Owner) \n\n' elseif is_momod2(result.id, extra.chat2) then text = text..'مقام : مدیر گروه (Moderator) \n\n' else text = text..'مقام : کاربر (Member) \n\n' end else text = text..'مقام : '..value..'\n\n' end local uhash = 'user:'..result.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..result.id..':'..extra.chat2 user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n' text = text..'@Hextor Team' send_msg(extra.receiver, text, ok_cb, true) else send_msg(extra.receiver, extra.user..' نام کاربری مورد نظر یافت نشد.', ok_cb, false) end end local function action_by_id(extra, success, result) -- /info <ID> function if success == 1 then if result.username then Username = '@'..result.username else Username = 'ندارد' end local text = 'نام کامل : '..(result.first_name or '')..' '..(result.last_name or '')..'\n' ..'یوزر: '..Username..'\n' ..'ایدی کاربری : '..result.id..'\n\n' local hash = 'rank:variables' local value = redis:hget(hash, result.id) if not value then if result.id == tonumber(reza) then text = text..'مقام : مدیر کل ربات (Executive Admin) \n\n' elseif is_admin2(result.id) then text = text..'مقام : ادمین ربات (Admin) \n\n' elseif is_owner2(result.id, extra.chat2) then text = text..'مقام : مدیر کل گروه (Owner) \n\n' elseif is_momod2(result.id, extra.chat2) then text = text..'مقام : مدیر گروه (Moderator) \n\n' else text = text..'مقام : کاربر (Member) \n\n' end else text = text..'مقام : '..value..'\n\n' end local uhash = 'user:'..result.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..result.id..':'..extra.chat2 user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n' text = text..'@Hextor Team' send_msg(extra.receiver, text, ok_cb, true) else send_msg(extra.receiver, 'ایدی شخص مورد نظر در سیستم ثبت نشده است.\nاز دستور زیر استفاده کنید\n/info @username', ok_cb, false) end end local function action_by_reply(extra, success, result)-- (reply) /info function if result.from.username then Username = '@'..result.from.username else Username = 'ندارد' end local text = 'نام کامل : '..(result.from.first_name or '')..' '..(result.from.last_name or '')..'\n' ..'یوزر: '..Username..'\n' ..'ایدی کاربری : '..result.from.id..'\n\n' local hash = 'rank:variables' local value = redis:hget(hash, result.from.id) if not value then if result.from.id == tonumber(reza) then text = text..'مقام : مدیر کل ربات (Executive Admin) \n\n' elseif is_admin2(result.from.id) then text = text..'مقام : ادمین ربات (Admin) \n\n' elseif is_owner2(result.from.id, result.to.id) then text = text..'مقام : مدیر کل گروه (Owner) \n\n' elseif is_momod2(result.from.id, result.to.id) then text = text..'مقام : مدیر گروه (Moderator) \n\n' else text = text..'مقام : کاربر (Member) \n\n' end else text = text..'مقام : '..value..'\n\n' end local user_info = {} local uhash = 'user:'..result.from.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..result.from.id..':'..result.to.id user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n' text = text..'@Hextor Team' send_msg(extra.receiver, text, ok_cb, true) end local function action_by_reply2(extra, success, result) local value = extra.value setrank(result, result.from.id, value) end local function run(msg, matches) if matches[1]:lower() == 'setrank' then local hash = 'usecommands:'..msg.from.id..':'..msg.to.id redis:incr(hash) if not is_sudo(msg) then return "Only for Sudo" end local receiver = get_receiver(msg) local Reply = msg.reply_id if msg.reply_id then local value = string.sub(matches[2], 1, 1000) msgr = get_message(msg.reply_id, action_by_reply2, {receiver=receiver, Reply=Reply, value=value}) else local name = string.sub(matches[2], 1, 50) local value = string.sub(matches[3], 1, 1000) local text = setrank(msg, name, value) return text end end if matches[1]:lower() == 'info' and not matches[2] then local receiver = get_receiver(msg) local Reply = msg.reply_id if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {receiver=receiver, Reply=Reply}) else if msg.from.username then Username = '@'..msg.from.username else Username = 'ندارد' end local text = 'نام : '..(msg.from.first_name or 'ندارد')..'\n' local text = text..'فامیل : '..(msg.from.last_name or 'ندارد')..'\n' local text = text..'یوزر : '..Username..'\n' local text = text..'ایدی کاربری : '..msg.from.id..'\n\n' local hash = 'rank:variables' if hash then local value = redis:hget(hash, msg.from.id) if not value then if msg.from.id == tonumber(reza) then text = text..'مقام : مدیر کل ربات (Executive Admin) \n\n' elseif is_sudo(msg) then text = text..'مقام : ادمین ربات (Admin) \n\n' elseif is_owner(msg) then text = text..'مقام : مدیر کل گروه (Owner) \n\n' elseif is_momod(msg) then text = text..'مقام : مدیر گروه (Moderator) \n\n' else text = text..'مقام : کاربر (Member) \n\n' end else text = text..'مقام : '..value..'\n' end end local uhash = 'user:'..msg.from.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..msg.from.id..':'..msg.to.id user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n' if msg.to.type == 'chat' then text = text..'نام گروه : '..msg.to.title..'\n' text = text..'ایدی گروه : '..msg.to.id end text = text..'\n\n@Hextor Team' return send_msg(receiver, text, ok_cb, true) end end if matches[1]:lower() == 'info' and matches[2] then local user = matches[2] local chat2 = msg.to.id local receiver = get_receiver(msg) if string.match(user, '^%d+$') then user_info('user#id'..user, action_by_id, {receiver=receiver, user=user, text=text, chat2=chat2}) elseif string.match(user, '^@.+$') then username = string.gsub(user, '@', '') msgr = res_user(username, res_user_callback, {receiver=receiver, user=user, text=text, chat2=chat2}) end end end return { description = 'Know your information or the info of a chat members.', usage = { '!info: Return your info and the chat info if you are in one.', '(Reply)!info: Return info of replied user if used by reply.', '!info <id>: Return the info\'s of the <id>.', '!info @<user_name>: Return the member @<user_name> information from the current chat.', '!setrank <userid> <rank>: change members rank.', '(Reply)!setrank <rank>: change members rank.', }, patterns = { "^[/!]([Ii][Nn][Ff][Oo])$", "^[/!]([Ii][Nn][Ff][Oo]) (.*)$", "^[/!]([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (%d+) (.*)$", "^[/!]([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (.*)$", }, run = run } end
gpl-2.0
joshimoo/Algorithm-Implementations
Best_First_Search/Lua/Yonaba/bfs_test.lua
26
2639
-- Tests for bfs.lua local BFS = require 'bfs' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function same(t, p, comp) for k,v in ipairs(t) do if not comp(v, p[k]) then return false end end return true end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end run('Testing BFS search on linear graph', function() local comp = function(a, b) return a.value == b end local ln_handler = require 'handlers.linear_handler' ln_handler.init(-2,5) local bfs = BFS(ln_handler) local start, goal = ln_handler.getNode(0), ln_handler.getNode(5) assert(same(bfs:findPath(start, goal), {0,1,2,3,4,5}, comp)) start, goal = ln_handler.getNode(-2), ln_handler.getNode(2) assert(same(bfs:findPath(start, goal), {-2,-1,0,1,2}, comp)) end) run('Testing BFS search on grid graph', function() local comp = function(a, b) return a.x == b[1] and a.y == b[2] end local gm_handler = require 'handlers.gridmap_handler' local bfs = BFS(gm_handler) local map = {{0,0,0,0,0},{0,1,1,1,1},{0,0,0,0,0}} gm_handler.init(map) gm_handler.diagonal = false local start, goal = gm_handler.getNode(1,1), gm_handler.getNode(5,3) assert(same(bfs:findPath(start, goal), {{1,1},{1,2},{1,3},{2,3},{3,3},{4,3},{5,3}}, comp)) gm_handler.diagonal = true assert(same(bfs:findPath(start, goal), {{1,1},{1,2},{2,3},{3,3},{4,3},{5,3}}, comp)) end) run('Testing BFS search on point graph', function() local comp = function(a, b) return a.x == b[1] and a.y == b[2] end local pg_handler = require 'handlers.point_graph_handler' local bfs = BFS(pg_handler) pg_handler.addNode('a') pg_handler.addNode('b') pg_handler.addNode('c') pg_handler.addNode('d') pg_handler.addNode('e') pg_handler.addEdge('a', 'b', 10) pg_handler.addEdge('b', 'e', 10) pg_handler.addEdge('a', 'c', 5) pg_handler.addEdge('c', 'd', 5) pg_handler.addEdge('d', 'e', 5) local comp = function(a, b) return a.name == b end local start, goal = pg_handler.getNode('a'), pg_handler.getNode('e') assert(same(bfs:findPath(start, goal), {'a','c','d','e'}, comp)) pg_handler.setEdgeWeight('a', 'b', 1) pg_handler.setEdgeWeight('b', 'e', 1) assert(same(bfs:findPath(start, goal), {'a','b','e'}, comp)) end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
FFXIOrgins/FFXIOrgins
scripts/zones/Phomiuna_Aqueducts/npcs/qm3.lua
34
1033
----------------------------------- -- Area: Phomiuna Aqueducts -- NPC: qm3 (???) -- Notes: Opens north door @ J-9 -- @pos 116.743 -24.636 27.518 27 ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DoorOffset = npc:getID() - 2; if (GetNPCByID(DoorOffset):getAnimation() == 9) then GetNPCByID(DoorOffset):openDoor(7) -- _0ri 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
Gael-de-Sailly/minetest-minetestforfun-server
mods/moreblocks/stairsplus/conversion.lua
9
4118
--[[ More Blocks: conversion Copyright (c) 2011-2015 Calinou and contributors. Licensed under the zlib license. See LICENSE.md for more information. --]] -- Function to convert all stairs/slabs/etc nodes from -- inverted, wall, etc to regular + 6d facedir local dirs1 = {21, 20, 23, 22, 21} local dirs2 = {15, 8, 17, 6, 15} local dirs3 = {14, 11, 16, 5, 14} function stairsplus:register_6dfacedir_conversion(modname, material) --print("Register stairsplus 6d facedir conversion") --print('ABM for '..modname..' "'..material..'"') local objects_list1 = { modname.. ":slab_" ..material.. "_inverted", modname.. ":slab_" ..material.. "_quarter_inverted", modname.. ":slab_" ..material.. "_three_quarter_inverted", modname.. ":stair_" ..material.. "_inverted", modname.. ":stair_" ..material.. "_wall", modname.. ":stair_" ..material.. "_wall_half", modname.. ":stair_" ..material.. "_wall_half_inverted", modname.. ":stair_" ..material.. "_half_inverted", modname.. ":stair_" ..material.. "_right_half_inverted", modname.. ":panel_" ..material.. "_vertical", modname.. ":panel_" ..material.. "_top", } local objects_list2 = { modname.. ":slab_" ..material.. "_wall", modname.. ":slab_" ..material.. "_quarter_wall", modname.. ":slab_" ..material.. "_three_quarter_wall", modname.. ":stair_" ..material.. "_inner_inverted", modname.. ":stair_" ..material.. "_outer_inverted", modname.. ":micro_" ..material.. "_top" } for _, object in pairs(objects_list1) do local flip_upside_down = false local flip_to_wall = false local dest_object = object if string.find(dest_object, "_inverted") then flip_upside_down = true dest_object = string.gsub(dest_object, "_inverted", "") end if string.find(object, "_top") then flip_upside_down = true dest_object = string.gsub(dest_object, "_top", "") end if string.find(dest_object, "_wall") then flip_to_wall = true dest_object = string.gsub(dest_object, "_wall", "") end if string.find(dest_object, "_vertical") then flip_to_wall = true dest_object = string.gsub(dest_object, "_vertical", "") end if string.find(dest_object, "_half") and not string.find(dest_object, "_right_half") then dest_object = string.gsub(dest_object, "_half", "_right_half") elseif string.find(dest_object, "_right_half") then dest_object = string.gsub(dest_object, "_right_half", "_half") end --print(" +---> convert " ..object) --print(" | to " ..dest_object) minetest.register_abm({ nodenames = {object}, interval = 1, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) local fdir = node.param2 or 0 if flip_upside_down and not flip_to_wall then nfdir = dirs1[fdir + 2] elseif flip_to_wall and not flip_upside_down then nfdir = dirs2[fdir + 1] elseif flip_to_wall and flip_upside_down then nfdir = dirs3[fdir + 2] end minetest.set_node(pos, {name = dest_object, param2 = nfdir}) end }) end for _, object in pairs(objects_list2) do local flip_upside_down = false local flip_to_wall = false local dest_object = object if string.find(dest_object, "_inverted") then flip_upside_down = true dest_object = string.gsub(dest_object, "_inverted", "") end if string.find(dest_object, "_top") then flip_upside_down = true dest_object = string.gsub(dest_object, "_top", "") end if string.find(dest_object, "_wall") then flip_to_wall = true dest_object = string.gsub(dest_object, "_wall", "") end --print(" +---> convert " ..object) --print(" | to " ..dest_object) minetest.register_abm({ nodenames = {object}, interval = 1, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) local fdir = node.param2 local nfdir = 20 if flip_upside_down and not flip_to_wall then nfdir = dirs1[fdir + 1] elseif flip_to_wall and not flip_upside_down then nfdir = dirs2[fdir + 2] end minetest.set_node(pos, {name = dest_object, param2 = nfdir}) end }) end end
unlicense
Ali-2h/lwl
plugins/ingroup.lua
37
31653
do local function check_member(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as the owner.') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg}) end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted.') end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name if success == -1 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' then print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'rem' then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local receiver = 'user#id'..msg.action.user.id local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return false end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Welcome to "' .. string.gsub(msg.to.print_name, '_', ' ') ..'" this group has rules that you should follow:\n'..rules savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..msg.action.user.id) send_large_msg(receiver, rules) end if matches[1] == 'chat_del_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and matches[2] then if not is_owner(msg) then return "Only owner can promote" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'demote' and matches[2] then if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username then return "You can't demote yourself" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end if matches[1] == 'newlink' then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'link' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end if matches[1] == 'setowner' then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group owner is ["..group_owner..']' end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'help' then if not is_momod(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end end return { patterns = { "^[!/$&#@]([Aa]dd)$", "^[!/$&#@]([Rr]em)$", "^[!/$&#@]([Rr]ules)$", "^[!/$&#@]({Aa]bout)$", "^[!/$&#@]([Ss]etname) (.*)$", "^[!/$&#@]([Ss]etphoto)$", "^[!/$&#@]([Pp]romote) (.*)$", "^[!/$&#@]([Hh]elp)$", "^[!/$&#@]([Cc]lean) (.*)$", "^[!/$&#@]([Dd]emote) (.*)$", "^[!/$&#@]([Ss]et) ([^%s]+) (.*)$", "^[!/$&#@]([Ll]ock) (.*)$", "^[!/$&#@]([Ss]etowner) (%d+)$", "^[!/$&#@]([Oo]wner)$", "^[!/$&#@]([Rr]es) (.*)$", "^[!/$&#@]([Ss]etgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^[!/$&#@]([Uu]nlock) (.*)$", "^[!/$&#@]([Ss]etflood) (%d+)$", "^[!/$&#@]([Ss]ettings)$", "^[!/$&#@]([Mm]odlist)$", "^[!/$&#@]([Nn]ewlink)$", "^[!/$&#@]([Ll]ink)$", "%[(photo)%]" }, run = run } end
gpl-2.0
daofeng2015/luci
applications/luci-app-pbx/luasrc/model/cbi/pbx-advanced.lua
18
14476
--[[ 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 appname = "PBX" modulename = "pbx-advanced" defaultbindport = 5060 defaultrtpstart = 19850 defaultrtpend = 19900 -- Returns all the network related settings, including a constructed RTP range function get_network_info() externhost = m.uci:get(modulename, "advanced", "externhost") ipaddr = m.uci:get("network", "lan", "ipaddr") bindport = m.uci:get(modulename, "advanced", "bindport") rtpstart = m.uci:get(modulename, "advanced", "rtpstart") rtpend = m.uci:get(modulename, "advanced", "rtpend") if bindport == nil then bindport = defaultbindport end if rtpstart == nil then rtpstart = defaultrtpstart end if rtpend == nil then rtpend = defaultrtpend end if rtpstart == nil or rtpend == nil then rtprange = nil else rtprange = rtpstart .. "-" .. rtpend end return bindport, rtprange, ipaddr, externhost end -- If not present, insert empty rules in the given config & section named PBX-SIP and PBX-RTP function insert_empty_sip_rtp_rules(config, section) -- Add rules named PBX-SIP and PBX-RTP if not existing found_sip_rule = false found_rtp_rule = false m.uci:foreach(config, section, function(s1) if s1._name == 'PBX-SIP' then found_sip_rule = true elseif s1._name == 'PBX-RTP' then found_rtp_rule = true end end) if found_sip_rule ~= true then newrule=m.uci:add(config, section) m.uci:set(config, newrule, '_name', 'PBX-SIP') end if found_rtp_rule ~= true then newrule=m.uci:add(config, section) m.uci:set(config, newrule, '_name', 'PBX-RTP') end end -- Delete rules in the given config & section named PBX-SIP and PBX-RTP function delete_sip_rtp_rules(config, section) -- Remove rules named PBX-SIP and PBX-RTP commit = false m.uci:foreach(config, section, function(s1) if s1._name == 'PBX-SIP' or s1._name == 'PBX-RTP' then m.uci:delete(config, s1['.name']) commit = true end end) -- If something changed, then we commit the config. if commit == true then m.uci:commit(config) end end -- Deletes QoS rules associated with this PBX. function delete_qos_rules() delete_sip_rtp_rules ("qos", "classify") end function insert_qos_rules() -- Insert empty PBX-SIP and PBX-RTP rules if not present. insert_empty_sip_rtp_rules ("qos", "classify") -- Get the network information bindport, rtprange, ipaddr, externhost = get_network_info() -- Iterate through the QoS rules, and if there is no other rule with the same port -- range at the priority service level, insert this rule. commit = false m.uci:foreach("qos", "classify", function(s1) if s1._name == 'PBX-SIP' then if s1.ports ~= bindport or s1.target ~= "Priority" or s1.proto ~= "udp" then m.uci:set("qos", s1['.name'], "ports", bindport) m.uci:set("qos", s1['.name'], "proto", "udp") m.uci:set("qos", s1['.name'], "target", "Priority") commit = true end elseif s1._name == 'PBX-RTP' then if s1.ports ~= rtprange or s1.target ~= "Priority" or s1.proto ~= "udp" then m.uci:set("qos", s1['.name'], "ports", rtprange) m.uci:set("qos", s1['.name'], "proto", "udp") m.uci:set("qos", s1['.name'], "target", "Priority") commit = true end end end) -- If something changed, then we commit the qos config. if commit == true then m.uci:commit("qos") end end -- This function is a (so far) unsuccessful attempt to manipulate the firewall rules from here -- Need to do more testing and eventually move to this mode. function maintain_firewall_rules() -- Get the network information bindport, rtprange, ipaddr, externhost = get_network_info() commit = false -- Only if externhost is set, do we control firewall rules. if externhost ~= nil and bindport ~= nil and rtprange ~= nil then -- Insert empty PBX-SIP and PBX-RTP rules if not present. insert_empty_sip_rtp_rules ("firewall", "rule") -- Iterate through the firewall rules, and if the dest_port and dest_ip setting of the\ -- SIP and RTP rule do not match what we want configured, set all the entries in the rule\ -- appropriately. m.uci:foreach("firewall", "rule", function(s1) if s1._name == 'PBX-SIP' then if s1.dest_port ~= bindport then m.uci:set("firewall", s1['.name'], "dest_port", bindport) m.uci:set("firewall", s1['.name'], "src", "wan") m.uci:set("firewall", s1['.name'], "proto", "udp") m.uci:set("firewall", s1['.name'], "target", "ACCEPT") commit = true end elseif s1._name == 'PBX-RTP' then if s1.dest_port ~= rtprange then m.uci:set("firewall", s1['.name'], "dest_port", rtprange) m.uci:set("firewall", s1['.name'], "src", "wan") m.uci:set("firewall", s1['.name'], "proto", "udp") m.uci:set("firewall", s1['.name'], "target", "ACCEPT") commit = true end end end) else -- We delete the firewall rules if one or more of the necessary parameters are not set. sip_rule_name=nil rtp_rule_name=nil -- First discover the configuration names of the rules. m.uci:foreach("firewall", "rule", function(s1) if s1._name == 'PBX-SIP' then sip_rule_name = s1['.name'] elseif s1._name == 'PBX-RTP' then rtp_rule_name = s1['.name'] end end) -- Then, using the names, actually delete the rules. if sip_rule_name ~= nil then m.uci:delete("firewall", sip_rule_name) commit = true end if rtp_rule_name ~= nil then m.uci:delete("firewall", rtp_rule_name) commit = true end end -- If something changed, then we commit the firewall config. if commit == true then m.uci:commit("firewall") end end m = Map (modulename, translate("Advanced Settings"), translate("This section contains settings that do not need to be changed under \ normal circumstances. In addition, here you can configure your system \ for use with remote SIP devices, and resolve call quality issues by enabling \ the insertion of QoS rules.")) -- Recreate the voip server config, and restart necessary services after changes are commited -- to the advanced configuration. The firewall must restart because of "Remote Usage". function m.on_after_commit(self) -- Make sure firewall rules are in place maintain_firewall_rules() -- If insertion of QoS rules is enabled if m.uci:get(modulename, "advanced", "qos_enabled") == "yes" then insert_qos_rules() else delete_qos_rules() 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") luci.sys.call("/etc/init.d/firewall restart 1\>/dev/null 2\>/dev/null") end ----------------------------------------------------------------------------- s = m:section(NamedSection, "advanced", "settings", translate("Advanced Settings")) s.anonymous = true s:tab("general", translate("General Settings")) s:tab("remote_usage", translate("Remote Usage"), translatef("You can use your SIP devices/softphones with this system from a remote location \ as well, as long as your Internet Service Provider gives you a public IP. \ You will be able to call other local users for free (e.g. other Analog Telephone Adapters (ATAs)) \ and use your VoIP providers to make calls as if you were local to the PBX. \ After configuring this tab, go back to where users are configured and see the new \ Server and Port setting you need to configure the remote SIP devices with. Please note that if this \ PBX is not running on your router/gateway, you will need to configure port forwarding (NAT) on your \ router/gateway. Please forward the ports below (SIP port and RTP range) to the IP address of the \ device running this PBX.")) s:tab("qos", translate("QoS Settings"), translate("If you experience jittery or high latency audio during heavy downloads, you may want \ to enable QoS. QoS prioritizes traffic to and from your network for specified ports and IP \ addresses, resulting in better latency and throughput for sound in our case. If enabled below, \ a QoS rule for this service will be configured by the PBX automatically, but you must visit the \ QoS configuration page (Network->QoS) to configure other critical QoS settings like Download \ and Upload speed.")) ringtime = s:taboption("general", Value, "ringtime", translate("Number of Seconds to Ring"), translate("Set the number of seconds to ring users upon incoming calls before hanging up \ or going to voicemail, if the voicemail is installed and enabled.")) ringtime.datatype = "port" ringtime.default = 30 ua = s:taboption("general", Value, "useragent", translate("User Agent String"), translate("This is the name that the VoIP server will use to identify itself when \ registering to VoIP (SIP) providers. Some providers require this to a specific \ string matching a hardware SIP device.")) ua.default = appname h = s:taboption("remote_usage", Value, "externhost", translate("Domain/IP Address/Dynamic Domain"), translate("You can enter your domain name, external IP address, or dynamic domain name here. \ The best thing to input is a static IP address. If your IP address is dynamic and it changes, \ your configuration will become invalid. Hence, it's recommended to set up Dynamic DNS in this case. \ and enter your Dynamic DNS hostname here. You can configure Dynamic DNS with the luci-app-ddns package.")) h.datatype = "host(0)" p = s:taboption("remote_usage", Value, "bindport", translate("External SIP Port"), translate("Pick a random port number between 6500 and 9500 for the service to listen on. \ Do not pick the standard 5060, because it is often subject to brute-force attacks. \ When finished, (1) click \"Save and Apply\", and (2) look in the \ \"SIP Device/Softphone Accounts\" section for updated Server and Port settings \ for your SIP Devices/Softphones.")) p.datatype = "port" p = s:taboption("remote_usage", Value, "rtpstart", translate("RTP Port Range Start"), translate("RTP traffic carries actual voice packets. This is the start of the port range \ that will be used for setting up RTP communication. It's usually OK to leave this \ at the default value.")) p.datatype = "port" p.default = defaultrtpstart p = s:taboption("remote_usage", Value, "rtpend", translate("RTP Port Range End")) p.datatype = "port" p.default = defaultrtpend p = s:taboption("qos", ListValue, "qos_enabled", translate("Insert QoS Rules")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" return m
apache-2.0
subzrk/BadRotations
Libs/DiesalGUI-1.0/Objects/CheckBox.lua
1
5756
-- $Id: CheckBox.lua 60 2016-11-04 01:34:23Z diesal2010 $ local DiesalGUI = LibStub("DiesalGUI-1.0") -- ~~| Libraries |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local DiesalTools = LibStub("DiesalTools-1.0") local DiesalStyle = LibStub("DiesalStyle-1.0") -- ~~| Diesal Upvalues |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local Colors = DiesalStyle.Colors local HSL, ShadeColor, TintColor = DiesalTools.HSL, DiesalTools.ShadeColor, DiesalTools.TintColor -- ~~| Lua Upvalues |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local type, tonumber, select = type, tonumber, select local pairs, ipairs, next = pairs, ipairs, next local min, max = math.min, math.max -- ~~| WoW Upvalues |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local CreateFrame, UIParent, GetCursorPosition = CreateFrame, UIParent, GetCursorPosition local GetScreenWidth, GetScreenHeight = GetScreenWidth, GetScreenHeight local GetSpellInfo, GetBonusBarOffset, GetDodgeChance = GetSpellInfo, GetBonusBarOffset, GetDodgeChance local GetPrimaryTalentTree, GetCombatRatingBonus = GetPrimaryTalentTree, GetCombatRatingBonus -- ~~| Button |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local TYPE = "CheckBox" local VERSION = 1 -- ~~| Button Stylesheets |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local Stylesheet = { ['frame-background'] = { type = 'texture', layer = 'BACKGROUND', color = '000000', alpha = .60, position = -2 }, ['frame-inline'] = { type = 'outline', layer = 'BORDER', color = '000000', alpha = .6, position = -2 }, ['frame-outline'] = { type = 'outline', layer = 'BORDER', color = 'FFFFFF', alpha = .02, position = -1, }, } local checkBoxStyle = { base = { type = 'texture', layer = 'ARTWORK', color = Colors.UI_A400, position = -3, }, disabled = { type = 'texture', color = HSL(Colors.UI_Hue,Colors.UI_Saturation,.35), }, enabled = { type = 'texture', color = Colors.UI_A400, }, } local wireFrame = { ['frame-white'] = { type = 'outline', layer = 'OVERLAY', color = 'ffffff', }, } -- ~~| Button Methods |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local methods = { ['OnAcquire'] = function(self) self:ApplySettings() self:SetStylesheet(Stylesheet) self:Enable() -- self:SetStylesheet(wireFrameSheet) self:Show() end, ['OnRelease'] = function(self) end, ['ApplySettings'] = function(self) local settings = self.settings local frame = self.frame self:SetWidth(settings.width) self:SetHeight(settings.height) end, ["SetChecked"] = function(self,value) self.settings.checked = value self.frame:SetChecked(value) self[self.settings.disabled and "Disable" or "Enable"](self) end, ["GetChecked"] = function(self) return self.settings.checked end, ["Disable"] = function(self) self.settings.disabled = true DiesalStyle:StyleTexture(self.check,checkBoxStyle.disabled) self.frame:Disable() end, ["Enable"] = function(self) self.settings.disabled = false DiesalStyle:StyleTexture(self.check,checkBoxStyle.enabled) self.frame:Enable() end, ["RegisterForClicks"] = function(self,...) self.frame:RegisterForClicks(...) end, } -- ~~| Button Constructor |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local function Constructor() local self = DiesalGUI:CreateObjectBase(TYPE) local frame = CreateFrame('CheckButton', nil, UIParent) self.frame = frame -- ~~ Default Settings ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ self.defaults = { height = 11, width = 11, } -- ~~ Events ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- OnAcquire, OnRelease, OnHeightSet, OnWidthSet -- OnValueChanged, OnEnter, OnLeave, OnDisable, OnEnable -- ~~ Construct ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local check = self:CreateRegion("Texture", 'check', frame) DiesalStyle:StyleTexture(check,checkBoxStyle.base) frame:SetCheckedTexture(check) frame:SetScript('OnClick', function(this,button,...) DiesalGUI:OnMouse(this,button) if not self.settings.disabled then self:SetChecked(not self.settings.checked) if self.settings.checked then PlaySound("igMainMenuOptionCheckBoxOn") else PlaySound("igMainMenuOptionCheckBoxOff") end self:FireEvent("OnValueChanged", self.settings.checked) end end) frame:SetScript('OnEnter', function(this) self:FireEvent("OnEnter") end) frame:SetScript('OnLeave', function(this) self:FireEvent("OnLeave") end) frame:SetScript("OnDisable", function(this) self:FireEvent("OnDisable") end) frame:SetScript("OnEnable", function(this) self:FireEvent("OnEnable") end) -- ~~ Methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ for method, func in pairs(methods) do self[method] = func end -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ return self end DiesalGUI:RegisterObjectConstructor(TYPE,Constructor,VERSION)
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/zones/Aht_Urhgan_Whitegate/npcs/Zarfhid.lua
34
1034
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Zarfhid -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00DC); 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
FFXIOrgins/FFXIOrgins
scripts/zones/Monarch_Linn/bcnms/ancient_vows.lua
4
2608
----------------------------------- -- Area: Monarch Linn -- Name: Ancient Vows ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/missions"); -- After registering the BCNM via bcnmRegister(bcnmid) function OnBcnmRegister(player,instance) -- initialize timers if they don't already exist -- a random seed of 30 to 100 seconds is added to mix up the changes -- Changes should be ~60 seconds apart, although I've seen one ~50 if(AncientVowsFormTimer == nil) then AncientVowsFormTimer = {}; -- Instance 1 AncientVowsFormTimer[16904193] = {}; AncientVowsFormTimer[16904194] = {}; AncientVowsFormTimer[16904195] = {}; -- Instance 2 AncientVowsFormTimer[16904196] = {}; AncientVowsFormTimer[16904197] = {}; AncientVowsFormTimer[16904198] = {}; -- Instance 3 AncientVowsFormTimer[16904199] = {}; AncientVowsFormTimer[16904200] = {}; AncientVowsFormTimer[16904201] = {}; end end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function OnBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function OnBcnmLeave(player,instance,leavecode) --printf("leavecode: %u",leavecode); if(leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:getCurrentMission(COP) == ANCIENT_VOWS and player:getVar("PromathiaStatus") == 2) then player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,0); else player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,1); end elseif(leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) if(csid == 0x7d01)then player:addExp(1000); player:addTitle(TAVNAZIAN_TRAVELER); if (player:getCurrentMission(COP) == ANCIENT_VOWS and player:getVar("PromathiaStatus") == 2) then player:setVar("VowsDone",1); player:setVar("PromathiaStatus",0); player:completeMission(COP,ANCIENT_VOWS); player:addMission(COP,THE_CALL_OF_THE_WYRMKING); player:setPos(694,-5.5,-619,74,107); -- To South Gustaberg end end end;
gpl-3.0
hagish/lua-debugger
remdebug/src/controller.lua
1
7901
-- -- RemDebug 1.0 Beta -- Copyright Kepler Project 2005 (http://www.keplerproject.org/remdebug) -- local socket = require"socket" print("Lua Remote Debugger") print("Run the program you wish to debug") local server = socket.bind("*", 8171) local client = server:accept() local breakpoints = {} local watches = {} client:send("STEP\n") client:receive() local breakpoint = client:receive() local _, _, file, line = string.find(breakpoint, "^202 Paused%s+([%w%p]+)%s+(%d+)$") if file and line then print("Paused at file " .. file ) print("Type 'help' for commands") else local _, _, size = string.find(breakpoint, "^401 Error in Execution (%d+)$") if size then print("Error in remote application: ") print(client:receive(size)) end end local basedir = "" while true do io.write("> ") local line = io.read("*line") local _, _, command = string.find(line, "^([a-z]+)") if command == "run" or command == "step" or command == "over" then client:send(string.upper(command) .. "\n") client:receive() local breakpoint = client:receive() if not breakpoint then print("Program finished") os.exit() end local _, _, status = string.find(breakpoint, "^(%d+)") if status == "202" then local _, _, file, line = string.find(breakpoint, "^202 Paused%s+([%w%p]+)%s+(%d+)$") if file and line then print("Paused at file " .. file .. " line " .. line) end elseif status == "203" then local _, _, file, line, watch_idx = string.find(breakpoint, "^203 Paused%s+([%w%p]+)%s+(%d+)%s+(%d+)$") if file and line and watch_idx then print("Paused at file " .. file .. " line " .. line .. " (watch expression " .. watch_idx .. ": [" .. watches[watch_idx] .. "])") end elseif status == "401" then local _, _, size = string.find(breakpoint, "^401 Error in Execution (%d+)$") if size then print("Error in remote application: ") print(client:receive(tonumber(size))) os.exit() end else print("Unknown error") os.exit() end elseif command == "exit" then client:close() os.exit() elseif command == "setb" then local _, _, _, filename, line = string.find(line, "^([a-z]+)%s+([%w%p]+)%s+(%d+)$") if filename and line then filename = basedir .. filename if not breakpoints[filename] then breakpoints[filename] = {} end client:send("SETB " .. filename .. " " .. line .. "\n") if client:receive() == "200 OK" then breakpoints[filename][line] = true else print("Error: breakpoint not inserted") end else print("Invalid command") end elseif command == "setw" then local _, _, exp = string.find(line, "^[a-z]+%s+(.+)$") if exp then client:send("SETW " .. exp .. "\n") local answer = client:receive() local _, _, watch_idx = string.find(answer, "^200 OK (%d+)$") if watch_idx then watches[watch_idx] = exp print("Inserted watch exp no. " .. watch_idx) else print("Error: Watch expression not inserted") end else print("Invalid command") end elseif command == "delb" then local _, _, _, filename, line = string.find(line, "^([a-z]+)%s+([%w%p]+)%s+(%d+)$") if filename and line then filename = basedir .. filename if not breakpoints[filename] then breakpoints[filename] = {} end client:send("DELB " .. filename .. " " .. line .. "\n") if client:receive() == "200 OK" then breakpoints[filename][line] = nil else print("Error: breakpoint not removed") end else print("Invalid command") end elseif command == "delallb" then for filename, breaks in pairs(breakpoints) do for line, _ in pairs(breaks) do client:send("DELB " .. filename .. " " .. line .. "\n") if client:receive() == "200 OK" then breakpoints[filename][line] = nil else print("Error: breakpoint at file " .. filename .. " line " .. line .. " not removed") end end end elseif command == "delw" then local _, _, index = string.find(line, "^[a-z]+%s+(%d+)$") if index then client:send("DELW " .. index .. "\n") if client:receive() == "200 OK" then watches[index] = nil else print("Error: watch expression not removed") end else print("Invalid command") end elseif command == "delallw" then for index, exp in pairs(watches) do client:send("DELW " .. index .. "\n") if client:receive() == "200 OK" then watches[index] = nil else print("Error: watch expression at index " .. index .. " [" .. exp .. "] not removed") end end elseif command == "eval" then local _, _, exp = string.find(line, "^[a-z]+%s+(.+)$") if exp then client:send("EXEC return (" .. exp .. ")\n") local line = client:receive() local _, _, status, len = string.find(line, "^(%d+)[a-zA-Z ]+(%d+)$") if status == "200" then len = tonumber(len) local res = client:receive(len) print(res) elseif status == "401" then len = tonumber(len) local res = client:receive(len) print("Error in expression:") print(res) else print("Unknown error") end else print("Invalid command") end elseif command == "exec" then local _, _, exp = string.find(line, "^[a-z]+%s+(.+)$") if exp then client:send("EXEC " .. exp .. "\n") local line = client:receive() local _, _, status, len = string.find(line, "^(%d+)[%s%w]+(%d+)$") if status == "200" then len = tonumber(len) local res = client:receive(len) print(res) elseif status == "401" then len = tonumber(len) local res = client:receive(len) print("Error in expression:") print(res) else print("Unknown error") end else print("Invalid command") end elseif command == "listb" then for k, v in pairs(breakpoints) do io.write(k .. ": ") for k, v in pairs(v) do io.write(k .. " ") end io.write("\n") end elseif command == "listw" then for i, v in pairs(watches) do print("Watch exp. " .. i .. ": " .. v) end elseif command == "basedir" then local _, _, dir = string.find(line, "^[a-z]+%s+(.+)$") if dir then if not string.find(dir, "/$") then dir = dir .. "/" end basedir = dir print("New base directory is " .. basedir) else print(basedir) end elseif command == "help" then print("setb <file> <line> -- sets a breakpoint") print("delb <file> <line> -- removes a breakpoint") print("delallb -- removes all breakpoints") print("setw <exp> -- adds a new watch expression") print("delw <index> -- removes the watch expression at index") print("delallw -- removes all watch expressions") print("run -- run until next breakpoint") print("step -- run until next line, stepping into function calls") print("over -- run until next line, stepping over function calls") print("listb -- lists breakpoints") print("listw -- lists watch expressions") print("eval <exp> -- evaluates expression on the current context and returns its value") print("exec <stmt> -- executes statement on the current context") print("basedir [<path>] -- sets the base path of the remote application, or shows the current one") print("exit -- exits debugger") else local _, _, spaces = string.find(line, "^(%s*)$") if not spaces then print("Invalid command") end end end
mit
Gael-de-Sailly/minetest-minetestforfun-server
mods/vector_extras/vector_meta.lua
8
4424
vector.meta = vector.meta or {} vector.meta.nodes = {} vector.meta.nodes_file = { load = function() local nodesfile = io.open(minetest.get_worldpath()..'/vector_nodes.txt', "r") if nodesfile then local contents = nodesfile:read('*all') io.close(nodesfile) if contents ~= nil then local lines = string.split(contents, "\n") for _,entry in ipairs(lines) do local name, px, py, pz, meta = unpack(string.split(entry, "°")) vector.meta.set_node({x=px, y=py, z=pz}, name, meta) end end end end, save = function() --WRITE CHANGES TO FILE local output = '' for x,ys in pairs(vector.meta.nodes) do for y,zs in pairs(ys) do for z,names in pairs(zs) do for name,meta in pairs(names) do output = name.."°"..x.."°"..y.."°"..z.."°"..dump(meta).."\n" end end end end local f = io.open(minetest.get_worldpath()..'/vector_nodes.txt', "w") f:write(output) io.close(f) end } local function table_empty(tab) --looks if it's an empty table if next(tab) == nil then return true end return false end function vector.meta.nodes_info() --returns an info string of the node table local tmp = "[vector] "..dump(vector.meta.nodes).."\n[vector]:\n" for x,a in pairs(vector.meta.nodes) do for y,b in pairs(a) do for z,c in pairs(b) do for name,meta in pairs(c) do tmp = tmp..">\t"..name.." "..x.." "..y.." "..z.." "..dump(meta).."\n" end end end end return tmp end function vector.meta.clean_node_table() --replaces {} with nil local again = true while again do again = false for x,ys in pairs(vector.meta.nodes) do if table_empty(ys) then vector.meta.nodes[x] = nil again = true else for y,zs in pairs(ys) do if table_empty(zs) then vector.meta.nodes[x][y] = nil again = true else for z,names in pairs(zs) do if table_empty(names) then vector.meta.nodes[x][y][z] = nil again = true else for name,meta in pairs(names) do if table_empty(meta) or meta == "" then vector.meta.nodes[x][y][z][name] = nil again = true end end end end end end end end end end function vector.meta.complete_node_table(pos, name) --neccesary because tab[1] wouldn't work if tab is not a table local tmp = vector.meta.nodes[pos.x] if not tmp then vector.meta.nodes[pos.x] = {} end local tmp = vector.meta.nodes[pos.x][pos.y] if not tmp then vector.meta.nodes[pos.x][pos.y] = {} end local tmp = vector.meta.nodes[pos.x][pos.y][pos.z] if not tmp then vector.meta.nodes[pos.x][pos.y][pos.z] = {} end local tmp = vector.meta.nodes[pos.x][pos.y][pos.z][name] if not tmp then vector.meta.nodes[pos.x][pos.y][pos.z][name] = {} end end function vector.meta.get_node(pos, name) if not pos then return false end local tmp = vector.meta.nodes[pos.x] if not tmp or table_empty(tmp) then return false end local tmp = vector.meta.nodes[pos.x][pos.y] if not tmp or table_empty(tmp) then return false end local tmp = vector.meta.nodes[pos.x][pos.y][pos.z] if not tmp or table_empty(tmp) then return false end -- if name isn't mentioned, just look if there's a node if not name then return true end local tmp = vector.meta.nodes[pos.x][pos.y][pos.z][name] if not tmp or table_empty(tmp) then return false end return tmp end function vector.meta.remove_node(pos) if not pos then return false end if vector.meta.get_node(pos) then vector.meta.nodes[pos.x][pos.y][pos.z] = nil local xarr = vector.meta.nodes[pos.x] if table_empty(xarr[pos.y]) then vector.meta.nodes[pos.x][pos.y] = nil end if table_empty(xarr) then vector.meta.nodes[pos.x] = nil end else print("[vector_extras] Warning: The node at "..vector.pos_to_string(pos).." wasn't stored in vector.meta.nodes.") end end function vector.meta.set_node(pos, name, meta) if not (name or pos) then return false end vector.meta.complete_node_table(pos, name) meta = meta or true vector.meta.nodes[pos.x][pos.y][pos.z][name] = meta end minetest.register_chatcommand('cleanvectormetatable',{ description = 'Tidy up it.', params = "", privs = {}, func = function(name) vector.meta.clean_node_table() local tmp = vector.meta.nodes_info() minetest.chat_send_player(name, tmp) print("[vector_extras] "..tmp) end }) vector.meta.nodes_file.load()
unlicense
FFXIOrgins/FFXIOrgins
scripts/zones/Windurst_Waters/npcs/Piketo-Puketo.lua
12
1991
----------------------------------- -- Area: Windurst Waters -- NPC: Piketo-Puketo -- Type: Cooking Guild Master -- @pos -124.012 -2.999 59.998 238 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/globals/crafting"); require("scripts/zones/Windurst_Waters/TextIDs"); local SKILLID = 56; -- Cooking ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local newRank = tradeTestItem(player,npc,trade,SKILLID); if(newRank ~= 0) then player:setSkillRank(SKILLID,newRank); player:startEvent(0x271e,0,0,0,0,newRank); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local getNewRank = 0; local craftSkill = player:getSkillLevel(SKILLID); local testItem = getTestItem(player,npc,SKILLID); local guildMember = isGuildMember(player,4); if(guildMember == 1) then guildMember = 150995375; end if(canGetNewRank(player,craftSkill,SKILLID) == 1) then getNewRank = 100; end player:startEvent(0x271d,testItem,getNewRank,30,guildMember,44,0,0,0); end; -- 0x03d2 0x03d7 0x03d4 0x03d5 0x271d 0x271e ----------------------------------- -- 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 == 0x271d and option == 1) then local crystal = math.random(4096,4101); if(player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,crystal); else player:addItem(crystal); player:messageSpecial(ITEM_OBTAINED,crystal); signupGuild(player,16); end end end;
gpl-3.0
MOSAVI17/Gbot
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
FFXIOrgins/FFXIOrgins
scripts/zones/Al_Zahbi/npcs/Banjanu.lua
38
1025
----------------------------------- -- Area: Al Zahbi -- NPC: Banjanu -- Type: Standard NPC -- @zone: 48 -- @pos -75.954 0.999 105.367 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0106); 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
FFXIOrgins/FFXIOrgins
scripts/zones/Phomiuna_Aqueducts/npcs/_0rw.lua
17
1303
----------------------------------- -- Area: Phomiuna_Aqueducts -- NPC: _0rw (Oil Lamp) -- Notes: Opens south door at J-9 from inside. -- @pos 103.703 -26.180 83.000 27 ----------------------------------- package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Phomiuna_Aqueducts/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DoorOffset = npc:getID() - 1; if (GetNPCByID(DoorOffset):getAnimation() == 9) then if(player:getZPos() < 85) then npc:openDoor(7); -- torch animation GetNPCByID(DoorOffset):openDoor(7); -- _0rh end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/zones/Southern_San_dOria/npcs/Katharina.lua
37
1095
----------------------------------- -- Area: Southern San d'Oria -- NPC: Katharina -- General Info NPC ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- require("scripts/globals/settings"); function onTrigger(player,npc) player:startEvent(0x377); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --print("CSID:",csid); --print("RESULT:",option); end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/zones/Caedarva_Mire/npcs/Kwadaaf.lua
23
1347
----------------------------------- -- Area: Caedarva Mire -- NPC: Kwadaaf -- Type: Entry to Alzadaal Undersea Ruins -- @pos -639.000 12.323 -260.000 79 ----------------------------------- package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Caedarva_Mire/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:getItemCount() == 1 and trade:hasItemQty(2185,1)) then -- Silver player:tradeComplete(); player:startEvent(0x00df); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getXPos() < -639) then player:startEvent(0x00de); else player:startEvent(0x00e0); 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 == 0x00df) then player:setPos(-235,-4,220,0,72); end end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/zones/La_Theine_Plateau/npcs/Deaufrain.lua
17
2302
----------------------------------- -- Area: La Theine Plateau -- NPC: Deaufrain -- Involved in Mission: The Rescue Drill -- @pos -304 28 339 102 ----------------------------------- package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/La_Theine_Plateau/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getCurrentMission(SANDORIA) == THE_RESCUE_DRILL) then local MissionStatus = player:getVar("MissionStatus"); if(MissionStatus == 3) then player:startEvent(0x0066); elseif(MissionStatus == 4) then player:showText(npc, RESCUE_DRILL + 4); elseif(MissionStatus == 8) then if(player:getVar("theRescueDrillRandomNPC") == 3) then player:startEvent(0x0071); else player:showText(npc, RESCUE_DRILL + 21); end elseif(MissionStatus == 9) then if(player:getVar("theRescueDrillRandomNPC") == 3) then player:showText(npc, RESCUE_DRILL + 25); else player:showText(npc, RESCUE_DRILL + 26); end elseif(MissionStatus >= 10) then player:showText(npc, RESCUE_DRILL + 30); else player:showText(npc, RESCUE_DRILL); end else player:showText(npc, RESCUE_DRILL); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x0066) then player:setVar("MissionStatus",4); elseif(csid == 0x0071) then if(player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,16535); -- Bronze Sword else player:addItem(16535); player:messageSpecial(ITEM_OBTAINED, 16535); -- Bronze Sword player:setVar("MissionStatus",9); end end end;
gpl-3.0
kastnerkyle/MemNN
MemN2N-lang-model/data.lua
18
1101
-- Copyright (c) 2015-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. require('paths') local stringx = require('pl.stringx') local file = require('pl.file') function g_read_words(fname, vocab, ivocab) local data = file.read(fname) local lines = stringx.splitlines(data) local c = 0 for n = 1,#lines do local w = stringx.split(lines[n]) c = c + #w + 1 end local words = torch.Tensor(c, 1) c = 0 for n = 1,#lines do local w = stringx.split(lines[n]) for i = 1,#w do c = c + 1 if not vocab[w[i]] then ivocab[#vocab+1] = w[i] vocab[w[i]] = #vocab+1 end words[c][1] = vocab[w[i]] end c = c + 1 words[c][1] = vocab['<eos>'] end print('Read ' .. c .. ' words from ' .. fname) return words end
bsd-3-clause
bitemyapp/MemNN
MemN2N-lang-model/data.lua
18
1101
-- Copyright (c) 2015-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. require('paths') local stringx = require('pl.stringx') local file = require('pl.file') function g_read_words(fname, vocab, ivocab) local data = file.read(fname) local lines = stringx.splitlines(data) local c = 0 for n = 1,#lines do local w = stringx.split(lines[n]) c = c + #w + 1 end local words = torch.Tensor(c, 1) c = 0 for n = 1,#lines do local w = stringx.split(lines[n]) for i = 1,#w do c = c + 1 if not vocab[w[i]] then ivocab[#vocab+1] = w[i] vocab[w[i]] = #vocab+1 end words[c][1] = vocab[w[i]] end c = c + 1 words[c][1] = vocab['<eos>'] end print('Read ' .. c .. ' words from ' .. fname) return words end
bsd-3-clause
FFXIOrgins/FFXIOrgins
scripts/zones/The_Celestial_Nexus/mobs/Orbital.lua
19
2130
----------------------------------- -- Area: The Celestial Nexus -- NPC: Orbital -- Zilart Mission 16 BCNM Fight ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/status"); require("scripts/globals/magic"); function onMobInitialize(mob) mob:addMod(MOD_REGAIN, 50); end ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; function onMobFight(mob, target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("updateCSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,target) --printf("finishCSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x7d04) then if (GetMobByID(target:getID()-1):getName() == "Orbital") then DespawnMob(target:getID()); DespawnMob(target:getID()-1); DespawnMob(target:getID()-3); DespawnMob(target:getID()-4); mob = SpawnMob(target:getID()-2); mob:updateEnmity(player); --the "30 seconds of rest" you get before he attacks you, and making sure he teleports first in range mob:addStatusEffectEx(EFFECT_BIND, 0, 1, 0, 30); mob:addStatusEffectEx(EFFECT_SILENCE, 0, 1, 0, 40); else DespawnMob(target:getID()); DespawnMob(target:getID()+1); DespawnMob(target:getID()-2); DespawnMob(target:getID()-3); mob = SpawnMob(target:getID()-1); mob:updateEnmity(player); --the "30 seconds of rest" you get before he attacks you, and making sure he teleports first in range mob:addStatusEffectEx(EFFECT_BIND, 0, 1, 0, 30); mob:addStatusEffectEx(EFFECT_SILENCE, 0, 1, 0, 40); end end end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/weaponskills/shell_crusher.lua
6
1519
----------------------------------- -- Shell Crusher -- Staff weapon skill -- Skill Level: 175 -- Lowers target's defense. Duration of effect varies with TP. -- If unresisted, lowers target defense by 25%. -- Will stack with Sneak Attack. -- Aligned with the Breeze Gorget. -- Aligned with the Breeze Belt. -- Element: None -- Modifiers: STR:35% -- 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) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.35; 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 = 1; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); if damage > 0 then local tp = player:getTP(); local duration = (tp/100 * 60) + 120; if(target:hasStatusEffect(EFFECT_DEFENSE_DOWN) == false) then target:addStatusEffect(EFFECT_DEFENSE_DOWN, 25, 0, duration); end end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/zones/Windurst_Walls/Zone.lua
4
2810
----------------------------------- -- -- Zone: Windurst_Walls (239) -- ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/zones/Windurst_Walls/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) zone:registerRegion(1, -2,-17,140, 2,-16,142); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; -- MOG HOUSE EXIT if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then position = math.random(1,5) - 123; player:setPos(-257.5,-5.05,position,0); if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then cs = 0x7534; end player:setVar("PlayerMainJob",0); elseif(ENABLE_ASA == 1 and player:getCurrentMission(ASA) == A_SHANTOTTO_ASCENSION and (prevZone == 238 or prevZone == 241) and player:getMainLvl()>=10) then cs = 0x01fe; end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) switch (region:GetRegionID()): caseof { [1] = function (x) -- Heaven's Tower enter portal player:startEvent(0x56); end, } end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x56) then player:setPos(0,0,-22.40,192,242); elseif (csid == 0x7534 and option == 0) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); elseif(csid == 0x01fe) then player:startEvent(0x0202); elseif (csid == 0x0202) then player:completeMission(ASA,A_SHANTOTTO_ASCENSION); player:addMission(ASA,BURGEONING_DREAD); player:setVar("ASA_Status",0); end end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/items/crepe_caprice.lua
36
1318
----------------------------------------- -- ID: 5776 -- Item: Crepe Caprice -- Food Effect: 60 Min, All Races ----------------------------------------- -- HP +20 -- MP Healing 3 -- Magic Accuracy +5 -- Magic Defense +2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5776); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_MPHEAL, 3); target:addMod(MOD_MACC, 5); target:addMod(MOD_MDEF, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_MPHEAL, 3); target:delMod(MOD_MACC, 5); target:delMod(MOD_MDEF, 2); end;
gpl-3.0
mehrpouya81/gamer1
plugins/stats.lua
236
3989
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'teleseed' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "teleseed" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tatslist)$", "^[!/]([Ss]tats) (group) (%d+)", "^[!/]([Ss]tats) (teleseed)",-- Put everything you like :) "^[!/]([Tt]eleseed)"-- Put everything you like :) }, run = run } end
gpl-2.0
FFXIOrgins/FFXIOrgins
scripts/zones/FeiYin/TextIDs.lua
3
2300
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6557; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6560; -- Obtained: <item> GIL_OBTAINED = 6561; -- Obtained <number> gil KEYITEM_OBTAINED = 6563; -- Obtained key item: <keyitem> FISHING_MESSAGE_OFFSET = 7203; -- You can't fish here -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7328; -- You unlock the chest! CHEST_FAIL = 7329; -- Fails to open the chest. CHEST_TRAP = 7330; -- The chest was trapped! CHEST_WEAK = 7331; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7332; -- The chest was a mimic! CHEST_MOOGLE = 7333; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7334; -- The chest was but an illusion... CHEST_LOCKED = 7335; -- The chest appears to be locked. -- Other Dialog SENSE_OF_FOREBODING = 6575; -- You are suddenly overcome with a sense of foreboding... NOTHING_OUT_OF_ORDINARY = 6574; -- There is nothing out of the ordinary here. -- ACP mission MARK_OF_SEED_HAS_VANISHED = 7471; -- The Mark of Seed has vanished without a trace... MARK_OF_SEED_IS_ABOUT_TO_DISSIPATE = 7470; -- The Mark of Seed is about to dissipate entirely! Only a faint outline remains... MARK_OF_SEED_GROWS_FAINTER = 7469; -- The Mark of Seed grows fainter still. Before long, it will fade away entirely... MARK_OF_SEED_FLICKERS = 7468; -- The glow of the Mark of Seed flickers and dims ever so slightly... SCINTILLATING_BURST_OF_LIGHT = 7459; -- As you extend your hand, there is a scintillating burst of light! YOU_REACH_FOR_THE_LIGHT = 7458; -- You reach for the light, but there is no discernable effect... EVEN_GREATER_INTENSITY = 7457; -- The emblem on your hand glows with even greater intensity! THE_LIGHT_DWINDLES = 7456; -- However, the light dwindles and grows dim almost at once... YOU_REACH_OUT_TO_THE_LIGHT = 7455; -- You reach out to the light, and one facet of a curious seed-shaped emblem materializes on the back of your hand. SOFTLY_SHIMMERING_LIGHT = 7454; -- You see a softly shimmering light... -- conquest Base CONQUEST_BASE = 3;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/zones/Bastok_Markets/npcs/Gwill.lua
17
2876
----------------------------------- -- Area: Bastok Markets -- NPC: Gwill -- Starts & Ends Quest: The Return of the Adventurer -- Involved in Quests: The Cold Light of Day, Riding on the Clouds -- @zone 235 -- @pos 0 0 0 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) returnOfAdven = player:getQuestStatus(BASTOK,THE_RETURN_OF_THE_ADVENTURER); if(returnOfAdven == QUEST_ACCEPTED and trade:hasItemQty(628,1) and trade:getItemCount() == 1) then player:startEvent(0x00f3); end if(player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_2") == 2) then if(trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_2",0); player:tradeComplete(); player:addKeyItem(SMILING_STONE); player:messageSpecial(KEYITEM_OBTAINED,SMILING_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) pFame = player:getFameLevel(BASTOK); FatherFigure = player:getQuestStatus(BASTOK,FATHER_FIGURE); TheReturn = player:getQuestStatus(BASTOK,THE_RETURN_OF_THE_ADVENTURER); if(FatherFigure == QUEST_COMPLETED and TheReturn == QUEST_AVAILABLE and pFame >= 3) then player:startEvent(0x00f2); elseif(player:getQuestStatus(BASTOK,THE_COLD_LIGHT_OF_DAY) == QUEST_ACCEPTED) then player:startEvent(0x0067); else player:startEvent(0x0071); 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 == 0x00f2) then player:addQuest(BASTOK,THE_RETURN_OF_THE_ADVENTURER); elseif(csid == 0x00f3) then if(player:getFreeSlotsCount() >= 1) then player:tradeComplete(); player:addTitle(KULATZ_BRIDGE_COMPANION); player:addItem(12498); player:messageSpecial(ITEM_OBTAINED,12498); player:addFame(BASTOK,BAS_FAME*80); player:completeQuest(BASTOK,THE_RETURN_OF_THE_ADVENTURER); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12498); end end end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/items/dish_of_spaghetti_boscaiola.lua
35
1721
----------------------------------------- -- ID: 5192 -- Item: dish_of_spaghetti_boscaiola -- Food Effect: 30Min, All Races ----------------------------------------- -- Health % 18 -- Health Cap 120 -- Magic 35 -- Strength -5 -- Dexterity -2 -- Vitality 2 -- Mind 4 -- Magic Regen While Healing 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,1800,5192); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 18); target:addMod(MOD_FOOD_HP_CAP, 120); target:addMod(MOD_MP, 35); target:addMod(MOD_STR, -5); target:addMod(MOD_DEX, -2); target:addMod(MOD_VIT, 2); target:addMod(MOD_MND, 4); target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 18); target:delMod(MOD_FOOD_HP_CAP, 120); target:delMod(MOD_MP, 35); target:delMod(MOD_STR, -5); target:delMod(MOD_DEX, -2); target:delMod(MOD_VIT, 2); target:delMod(MOD_MND, 4); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
velukh/MplusLedger
DataBroker.lua
1
4003
local ldb = LibStub:GetLibrary("LibDataBroker-1.1", true) local MplusLedger = MplusLedger local UiUtils = MplusLedgerUiUtils local AceConfigDialog = LibStub("AceConfigDialog-3.0") local ldbPlugin = ldb:NewDataObject("MplusLedger", { type = "data source", text = "0", icon = "Interface\\ICONS\\INV_Relics_Hourglass" }) function ldbPlugin.OnClick(self, button) if button == "RightButton" then AceConfigDialog:Open("M+ Ledger") else MplusLedger:ToggleFrame() end end local function GenerateKeystoneString(keystone) local mythicName = keystone.name local mythicLevel = keystone.mythicLevel local affixes = keystone.affixes local affixString for _, affixName in pairs(affixes) do if not affixString then affixString = affixName else affixString = affixString .. ", " .. affixName end end local labelText = "+" .. mythicLevel .. " " .. mythicName if affixString then labelText = labelText .. " (" .. affixString .. ")" end return UiUtils:Indent(labelText) end function ldbPlugin.OnTooltipShow(tooltip) tooltip:AddLine("M+ Ledger") tooltip:AddLine(" ") local keystones = MplusLedger:GetCurrentKeystones() local yourKeystone = MplusLedger:GetSpecificCharacterKeystone() local characterName = UnitName("player") local showNoKeyCharacters = MplusLedger:GetConfig("display_no_key_characters") tooltip:AddLine(UiUtils:ClassColoredName(characterName, yourKeystone.classToken)) if yourKeystone.keystone then tooltip:AddLine(GenerateKeystoneString(yourKeystone.keystone)) else tooltip:AddLine(UiUtils:Indent("No keystone")) end local numOtherKeystones = 0 for character, stoneInfo in pairs(keystones) do if characterName ~= character then if stoneInfo.keystone ~= nil then numOtherKeystones = numOtherKeystones + 1 end end end if numOtherKeystones > 0 then tooltip:AddLine(" ") tooltip:AddLine("Other Characters:") tooltip:AddLine(" ") for character, stoneInfo in pairs(keystones) do if characterName ~= character then local shouldShowNoKeys = stoneInfo.keystone == nil and showNoKeyCharacters if stoneInfo.keystone or shouldShowNoKeys then tooltip:AddLine(UiUtils:ClassColoredName(character, stoneInfo.classToken)) if not stoneInfo.keystone then tooltip:AddLine(UiUtils:Indent("No keystone")) else tooltip:AddLine(GenerateKeystoneString(stoneInfo.keystone)) end end end end end local showPartyInMinimap = MplusLedger:GetConfig("display_party_in_minimap") local numGroupMembers = GetNumGroupMembers() if showPartyInMinimap and numGroupMembers > 1 then local partyKeystones = MplusLedger:GetPartyMemberKeystones() tooltip:AddLine(" ") tooltip:AddLine("Party members:") tooltip:AddLine(" ") for _, partyStoneInfo in pairs(partyKeystones) do if characterName ~= partyStoneInfo.name then local shouldShowNoKeys = partyStoneInfo.mythicLevel == "0" and showNoKeyCharacters if tonumber(partyStoneInfo.mythicLevel) > 0 or shouldShowNoKeys then tooltip:AddLine(UiUtils:ClassColoredName(partyStoneInfo.name, partyStoneInfo.classToken)) if partyStoneInfo.mythicLevel == "0" then tooltip:AddLine(UiUtils:Indent("No keystone")) else tooltip:AddLine(UiUtils:Indent("+" .. partyStoneInfo.mythicLevel .. " " .. partyStoneInfo.dungeon)) end end end end end tooltip:AddLine(" ") tooltip:AddLine("Left-click to toggle your M+ Ledger") tooltip:AddLine("Right-click to open M+ Ledger config options") end local f = CreateFrame("Frame") f:SetScript("OnEvent", function() local icon = LibStub("LibDBIcon-1.0", true) if not MplusLedgerIconDB then MplusLedgerIconDB = {} end if MplusLedger:GetConfig("enable_minimap") then icon:Register("MplusLedger", ldbPlugin, MplusLedgerIconDB) end end) f:RegisterEvent("PLAYER_LOGIN")
mit
FFXIOrgins/FFXIOrgins
scripts/zones/Kazham/npcs/Mumupp.lua
19
1873
----------------------------------- -- Area: Kazham -- NPC: Mumupp -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); local path = { 94.732452, -15.000000, -114.034622, 94.210846, -15.000000, -114.989388, 93.508865, -15.000000, -116.274101, 94.584877, -15.000000, -116.522118, 95.646988, -15.000000, -116.468452, 94.613518, -15.000000, -116.616562, 93.791100, -15.000000, -115.858505, 94.841835, -15.000000, -116.108437, 93.823380, -15.000000, -116.712860, 94.986847, -15.000000, -116.571831, 94.165512, -15.000000, -115.965698, 95.005806, -15.000000, -116.519707, 93.935555, -15.000000, -116.706291, 94.943497, -15.000000, -116.578346, 93.996826, -15.000000, -115.932816, 95.060165, -15.000000, -116.180840, 94.081062, -15.000000, -115.923836, 95.246490, -15.000000, -116.215691, 94.234077, -15.000000, -115.960793 }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(pathfind.first(path)); onPath(npc); end; function onPath(npc) pathfind.patrol(npc, path); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00C7); npc:wait(-1); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,npc) --printf("CSID: %u",csid); --printf("RESULT: %u",option); npc:wait(0); end;
gpl-3.0