repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
pleonex/telegram-bot | 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 |
TeleDALAD/harchi | 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 |
everhopingandwaiting/telegram-bot | 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 |
naclander/tome | game/engines/default/engine/DirectPath.lua | 3 | 1779 | -- TE4 - T-Engine 4
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
require "engine.class"
local Map = require "engine.Map"
--- Computes a direct line path from start to end
module(..., package.seeall, class.make)
--- Initializes DirectPath for a map and an actor
function _M:init(map, actor)
self.map = map
self.actor = actor
end
--- Compute path from sx/sy to tx/ty
-- @param sx the start coord
-- @param sy the start coord
-- @param tx the end coord
-- @param ty the end coord
-- @param use_has_seen if true the astar wont consider non-has_seen grids
-- @return either nil if no path or a list of nodes in the form { {x=...,y=...}, {x=...,y=...}, ..., {x=tx,y=ty}}
function _M:calc(sx, sy, tx, ty, use_has_seen)
local path = {}
local l = line.new(sx, sy, tx, ty)
local nx, ny = l()
while nx and ny do
if (not use_has_seen or self.map.has_seens(nx, ny)) and self.map:isBound(nx, ny) and not self.map:checkEntity(nx, ny, Map.TERRAIN, "block_move", self.actor, nil, true) then
path[#path+1] = {x=nx, y=ny}
else
break
end
nx, ny = l()
end
return path
end
| gpl-3.0 |
greasydeal/darkstar | scripts/zones/Dynamis-Windurst/mobs/Tzee_Xicu_Idol.lua | 11 | 1290 | -----------------------------------
-- Area: Dynamis Windurst
-- NPC: Tzee Xicu Idol
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/dynamis");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
SpawnMob(17543597):updateEnmity(target); -- 122
SpawnMob(17543598):updateEnmity(target); -- 123
SpawnMob(17543599):updateEnmity(target); -- 124
SpawnMob(17543600):updateEnmity(target); -- 125
SpawnMob(17543170):updateEnmity(target); -- Maa Febi the Steadfast
SpawnMob(17543171):updateEnmity(target); -- Muu Febi the Steadfast
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
if(alreadyReceived(killer,8) == false) then
addDynamisList(killer,128);
killer:addTitle(DYNAMISWINDURST_INTERLOPER); -- Add title
local npc = GetNPCByID(17543480); -- Spawn ???
npc:setPos(mob:getXPos(),mob:getYPos(),mob:getZPos());
npc:setStatus(0);
killer:launchDynamisSecondPart(); -- Spawn dynamis second part
end
end; | gpl-3.0 |
kellyjf/wireshark | test/lua/gregex.lua | 29 | 8743 |
-- Tests for GLib Regex functions
-- written by Hadriel Kaplan, based on Lrexlib's test suite
-- This is a test script for tshark/wireshark.
-- This script runs inside tshark/wireshark, so to run it do:
-- tshark -r empty.cap -X lua_script:<path_to_testdir>/lua/gregex.lua -X lua_script1:glib
--
-- if you have to give addtional paths to find the dependent lua files,
-- use the '-X lua_script1:' syntax to add more arguments
--
-- available arguments:
-- -d<dir> provides path directory for lua include files
-- -v verbose mode
-- -V very verbose mode
-- save args before we do anything else
local args = {...}
for i,v in ipairs(args) do
print(i.." = "..v)
end
-- save current locale and replace it with C-locale
local old_locale = os.setlocale()
print("Previous locale was '" .. old_locale .. "', setting it to C-locale now")
os.setlocale("C")
local function testing(...)
print("---- Testing "..tostring(...).." ----")
end
local count = 0
local function test(name, ...)
count = count + 1
io.write("test "..name.."-"..count.."...")
if (...) == true then
io.write("passed\n")
io.flush()
else
io.write("failed!\n")
io.flush()
error(name.." test failed!")
end
end
------------- First test some basic stuff to make sure we're sane -----------
print("Lua version: ".._VERSION)
testing("Lrexlib GLib Regex library")
local lib = GRegex
test("global",_G.GRegex == lib)
for name, val in pairs(lib) do
print("\t"..name.." = "..type(val))
end
test("class",type(lib) == 'table')
test("class",type(lib._VERSION) == 'string')
test("class",type(lib.find) == 'function')
test("class",type(lib.compile_flags) == 'function')
test("class",type(lib.match_flags) == 'function')
test("class",type(lib.flags) == 'function')
test("class",type(lib.gsub) == 'function')
test("class",type(lib.gmatch) == 'function')
test("class",type(lib.new) == 'function')
test("class",type(lib.match) == 'function')
test("class",type(lib.split) == 'function')
test("class",type(lib.version) == 'function')
testing("info and flags")
test("typeof",typeof(lib) == 'GRegex')
print(lib._VERSION)
print("Glib version = "..lib.version())
local function getTSize(t)
local c = 0
for k,v in pairs(t) do
-- print(k.." = "..v)
c = c + 1
end
return c
end
local flags = lib.flags()
-- print("size = "..c)
-- it's 84 for newer GLib, 61 for older
test("flags", getTSize(flags) > 60)
test("cflags", getTSize(lib.compile_flags()) > 15)
test("eflags", getTSize(lib.match_flags()) > 8)
testing("new")
local results
local function checkFunc(objname,funcname,...)
results = { pcall(objname[funcname],...) }
if results[1] then
return true
end
-- print("Got this error: '"..tostring(results[2]).."'")
return false
end
test("new", checkFunc(lib,"new",".*"))
test("new", checkFunc(lib,"new",""))
test("new", checkFunc(lib,"new","(hello|world)"))
test("new_err", not checkFunc(lib,"new","*"))
test("new_err", not checkFunc(lib,"new"))
test("new_err", not checkFunc(lib,"new","(hello|world"))
test("new_err", not checkFunc(lib,"new","[0-9"))
-- invalid compile flag
test("new_err", not checkFunc(lib,"new","[0-9]",flags.PARTIAL))
local val1 = "hello world foo bar"
local val2 = "hello wORld FOO bar"
local patt = "hello (world) (.*) bar"
local rgx = lib.new(patt)
local rgx2 = lib.new(patt,flags.CASELESS)
testing("typeof")
test("typeof",typeof(rgx) == 'GRegex')
test("typeof",typeof(rgx2) == 'GRegex')
testing("match")
test("match", checkFunc(lib,"match", val1,patt, 1, flags.CASELESS) and results[2] == "world" and results[3] == "foo")
test("match", checkFunc(lib,"match", val2,patt, 1, flags.CASELESS) and results[2] == "wORld" and results[3] == "FOO")
test("match", checkFunc(lib,"match", val1,rgx) and results[2] == "world" and results[3] == "foo")
test("match", checkFunc(rgx,"match", rgx,val1) and results[2] == "world" and results[3] == "foo")
test("match", checkFunc(rgx2,"match", rgx2,val2, 1) and results[2] == "wORld" and results[3] == "FOO")
-- different offset won't match this pattern
test("match_err", checkFunc(rgx2,"match", rgx2,val2, 4) and results[2] == nil)
-- invalid compile flag
test("match_err", not checkFunc(lib,"match", val1,patt, 1, flags.PARTIAL))
-- invalid match flag
test("match_err", not checkFunc(rgx,"match", rgx,val1, 1, flags.CASELESS))
testing("find")
test("find", checkFunc(lib,"find", val1,patt) and results[2] == 1 and results[3] == val1:len()
and results[4] == "world" and results[5] == "foo")
test("find", checkFunc(lib,"find", val1,rgx) and results[2] == 1 and results[3] == val1:len()
and results[4] == "world" and results[5] == "foo")
test("find", checkFunc(rgx,"find", rgx,val1) and results[2] == 1 and results[3] == val1:len()
and results[4] == "world" and results[5] == "foo")
testing("match")
--checkFunc(rgx,"exec", rgx,val1)
--print(results[4][3],results[4][4])
test("exec", checkFunc(rgx,"exec", rgx,val1) and results[2] == 1 and results[3] == val1:len()
and results[4][1] == 7 and results[4][2] == 11 and results[4][3] == 13 and results[4][4] == 15)
print("\n----------------------------------------------------------\n")
------- OK, we're sane, so run all the library's real tests ---------
testing("Lrexlib-provided tests")
-- we're not using the "real" lib name
local GLIBNAME = "GRegex"
local isglobal = true
do
local dir
for i = 1, select ("#", ...) do
local arg = select (i, ...)
--print(arg)
if arg:sub(1,2) == "-d" then
dir = arg:sub(3)
end
end
dir = dir:gsub("[/\\]+$", "")
local path = dir .. "/?.lua;"
if package.path:sub(1, #path) ~= path then
package.path = path .. package.path
end
end
local luatest = require "luatest"
-- returns: number of failures
local function test_library (libname, setfile, verbose, really_verbose)
if verbose then
print (("[lib: %s; file: %s]"):format (libname, setfile))
end
local lib = isglobal and _G[libname] or require (libname)
local f = require (setfile)
local sets = f (libname, isglobal)
local n = 0 -- number of failures
for _, set in ipairs (sets) do
if verbose then
print (set.Name or "Unnamed set")
end
local err = luatest.test_set (set, lib, really_verbose)
if verbose then
for _,v in ipairs (err) do
print ("\nTest " .. v.i)
print (" Expected result:\n "..tostring(v))
luatest.print_results (v[1], " ")
table.remove(v,1)
print ("\n Got:")
luatest.print_results (v, " ")
end
end
n = n + #err
end
if verbose then
print ""
end
return n
end
local avail_tests = {
posix = { lib = "rex_posix", "common_sets", "posix_sets" },
gnu = { lib = "rex_gnu", "common_sets", "emacs_sets", "gnu_sets" },
oniguruma = { lib = "rex_onig", "common_sets", "oniguruma_sets", },
pcre = { lib = "rex_pcre", "common_sets", "pcre_sets", "pcre_sets2", },
glib = { lib = GLIBNAME, "common_sets", "pcre_sets", "pcre_sets2", "glib_sets" },
spencer = { lib = "rex_spencer", "common_sets", "posix_sets", "spencer_sets" },
tre = { lib = "rex_tre", "common_sets", "posix_sets", "spencer_sets", --[["tre_sets"]] },
}
do
local verbose, really_verbose, tests, nerr = false, false, {}, 0
local dir
-- check arguments
for i = 1, select ("#", ...) do
local arg = select (i, ...)
--print(arg)
if arg:sub(1,1) == "-" then
if arg == "-v" then
verbose = true
elseif arg == "-V" then
verbose = true
really_verbose = true
elseif arg:sub(1,2) == "-d" then
dir = arg:sub(3)
end
else
if avail_tests[arg] then
tests[#tests+1] = avail_tests[arg]
else
error ("invalid argument: [" .. arg .. "]")
end
end
end
assert (#tests > 0, "no library specified")
-- give priority to libraries located in the specified directory
if dir and not isglobal then
dir = dir:gsub("[/\\]+$", "")
for _, ext in ipairs {"dll", "so", "dylib"} do
if package.cpath:match ("%?%." .. ext) then
local cpath = dir .. "/?." .. ext .. ";"
if package.cpath:sub(1, #cpath) ~= cpath then
package.cpath = cpath .. package.cpath
end
break
end
end
end
-- do tests
for _, test in ipairs (tests) do
package.loaded[test.lib] = nil -- to force-reload the tested library
for _, setfile in ipairs (test) do
nerr = nerr + test_library (test.lib, setfile, verbose, really_verbose)
end
end
print ("Total number of failures: " .. nerr)
assert(nerr == 0, "Test failed!")
end
print("Resetting locale to: " .. old_locale)
os.setlocale(old_locale)
print("\n-----------------------------\n")
print("All tests passed!\n\n")
| gpl-2.0 |
SIfoxDevTeam/wireshark | test/lua/gregex.lua | 29 | 8743 |
-- Tests for GLib Regex functions
-- written by Hadriel Kaplan, based on Lrexlib's test suite
-- This is a test script for tshark/wireshark.
-- This script runs inside tshark/wireshark, so to run it do:
-- tshark -r empty.cap -X lua_script:<path_to_testdir>/lua/gregex.lua -X lua_script1:glib
--
-- if you have to give addtional paths to find the dependent lua files,
-- use the '-X lua_script1:' syntax to add more arguments
--
-- available arguments:
-- -d<dir> provides path directory for lua include files
-- -v verbose mode
-- -V very verbose mode
-- save args before we do anything else
local args = {...}
for i,v in ipairs(args) do
print(i.." = "..v)
end
-- save current locale and replace it with C-locale
local old_locale = os.setlocale()
print("Previous locale was '" .. old_locale .. "', setting it to C-locale now")
os.setlocale("C")
local function testing(...)
print("---- Testing "..tostring(...).." ----")
end
local count = 0
local function test(name, ...)
count = count + 1
io.write("test "..name.."-"..count.."...")
if (...) == true then
io.write("passed\n")
io.flush()
else
io.write("failed!\n")
io.flush()
error(name.." test failed!")
end
end
------------- First test some basic stuff to make sure we're sane -----------
print("Lua version: ".._VERSION)
testing("Lrexlib GLib Regex library")
local lib = GRegex
test("global",_G.GRegex == lib)
for name, val in pairs(lib) do
print("\t"..name.." = "..type(val))
end
test("class",type(lib) == 'table')
test("class",type(lib._VERSION) == 'string')
test("class",type(lib.find) == 'function')
test("class",type(lib.compile_flags) == 'function')
test("class",type(lib.match_flags) == 'function')
test("class",type(lib.flags) == 'function')
test("class",type(lib.gsub) == 'function')
test("class",type(lib.gmatch) == 'function')
test("class",type(lib.new) == 'function')
test("class",type(lib.match) == 'function')
test("class",type(lib.split) == 'function')
test("class",type(lib.version) == 'function')
testing("info and flags")
test("typeof",typeof(lib) == 'GRegex')
print(lib._VERSION)
print("Glib version = "..lib.version())
local function getTSize(t)
local c = 0
for k,v in pairs(t) do
-- print(k.." = "..v)
c = c + 1
end
return c
end
local flags = lib.flags()
-- print("size = "..c)
-- it's 84 for newer GLib, 61 for older
test("flags", getTSize(flags) > 60)
test("cflags", getTSize(lib.compile_flags()) > 15)
test("eflags", getTSize(lib.match_flags()) > 8)
testing("new")
local results
local function checkFunc(objname,funcname,...)
results = { pcall(objname[funcname],...) }
if results[1] then
return true
end
-- print("Got this error: '"..tostring(results[2]).."'")
return false
end
test("new", checkFunc(lib,"new",".*"))
test("new", checkFunc(lib,"new",""))
test("new", checkFunc(lib,"new","(hello|world)"))
test("new_err", not checkFunc(lib,"new","*"))
test("new_err", not checkFunc(lib,"new"))
test("new_err", not checkFunc(lib,"new","(hello|world"))
test("new_err", not checkFunc(lib,"new","[0-9"))
-- invalid compile flag
test("new_err", not checkFunc(lib,"new","[0-9]",flags.PARTIAL))
local val1 = "hello world foo bar"
local val2 = "hello wORld FOO bar"
local patt = "hello (world) (.*) bar"
local rgx = lib.new(patt)
local rgx2 = lib.new(patt,flags.CASELESS)
testing("typeof")
test("typeof",typeof(rgx) == 'GRegex')
test("typeof",typeof(rgx2) == 'GRegex')
testing("match")
test("match", checkFunc(lib,"match", val1,patt, 1, flags.CASELESS) and results[2] == "world" and results[3] == "foo")
test("match", checkFunc(lib,"match", val2,patt, 1, flags.CASELESS) and results[2] == "wORld" and results[3] == "FOO")
test("match", checkFunc(lib,"match", val1,rgx) and results[2] == "world" and results[3] == "foo")
test("match", checkFunc(rgx,"match", rgx,val1) and results[2] == "world" and results[3] == "foo")
test("match", checkFunc(rgx2,"match", rgx2,val2, 1) and results[2] == "wORld" and results[3] == "FOO")
-- different offset won't match this pattern
test("match_err", checkFunc(rgx2,"match", rgx2,val2, 4) and results[2] == nil)
-- invalid compile flag
test("match_err", not checkFunc(lib,"match", val1,patt, 1, flags.PARTIAL))
-- invalid match flag
test("match_err", not checkFunc(rgx,"match", rgx,val1, 1, flags.CASELESS))
testing("find")
test("find", checkFunc(lib,"find", val1,patt) and results[2] == 1 and results[3] == val1:len()
and results[4] == "world" and results[5] == "foo")
test("find", checkFunc(lib,"find", val1,rgx) and results[2] == 1 and results[3] == val1:len()
and results[4] == "world" and results[5] == "foo")
test("find", checkFunc(rgx,"find", rgx,val1) and results[2] == 1 and results[3] == val1:len()
and results[4] == "world" and results[5] == "foo")
testing("match")
--checkFunc(rgx,"exec", rgx,val1)
--print(results[4][3],results[4][4])
test("exec", checkFunc(rgx,"exec", rgx,val1) and results[2] == 1 and results[3] == val1:len()
and results[4][1] == 7 and results[4][2] == 11 and results[4][3] == 13 and results[4][4] == 15)
print("\n----------------------------------------------------------\n")
------- OK, we're sane, so run all the library's real tests ---------
testing("Lrexlib-provided tests")
-- we're not using the "real" lib name
local GLIBNAME = "GRegex"
local isglobal = true
do
local dir
for i = 1, select ("#", ...) do
local arg = select (i, ...)
--print(arg)
if arg:sub(1,2) == "-d" then
dir = arg:sub(3)
end
end
dir = dir:gsub("[/\\]+$", "")
local path = dir .. "/?.lua;"
if package.path:sub(1, #path) ~= path then
package.path = path .. package.path
end
end
local luatest = require "luatest"
-- returns: number of failures
local function test_library (libname, setfile, verbose, really_verbose)
if verbose then
print (("[lib: %s; file: %s]"):format (libname, setfile))
end
local lib = isglobal and _G[libname] or require (libname)
local f = require (setfile)
local sets = f (libname, isglobal)
local n = 0 -- number of failures
for _, set in ipairs (sets) do
if verbose then
print (set.Name or "Unnamed set")
end
local err = luatest.test_set (set, lib, really_verbose)
if verbose then
for _,v in ipairs (err) do
print ("\nTest " .. v.i)
print (" Expected result:\n "..tostring(v))
luatest.print_results (v[1], " ")
table.remove(v,1)
print ("\n Got:")
luatest.print_results (v, " ")
end
end
n = n + #err
end
if verbose then
print ""
end
return n
end
local avail_tests = {
posix = { lib = "rex_posix", "common_sets", "posix_sets" },
gnu = { lib = "rex_gnu", "common_sets", "emacs_sets", "gnu_sets" },
oniguruma = { lib = "rex_onig", "common_sets", "oniguruma_sets", },
pcre = { lib = "rex_pcre", "common_sets", "pcre_sets", "pcre_sets2", },
glib = { lib = GLIBNAME, "common_sets", "pcre_sets", "pcre_sets2", "glib_sets" },
spencer = { lib = "rex_spencer", "common_sets", "posix_sets", "spencer_sets" },
tre = { lib = "rex_tre", "common_sets", "posix_sets", "spencer_sets", --[["tre_sets"]] },
}
do
local verbose, really_verbose, tests, nerr = false, false, {}, 0
local dir
-- check arguments
for i = 1, select ("#", ...) do
local arg = select (i, ...)
--print(arg)
if arg:sub(1,1) == "-" then
if arg == "-v" then
verbose = true
elseif arg == "-V" then
verbose = true
really_verbose = true
elseif arg:sub(1,2) == "-d" then
dir = arg:sub(3)
end
else
if avail_tests[arg] then
tests[#tests+1] = avail_tests[arg]
else
error ("invalid argument: [" .. arg .. "]")
end
end
end
assert (#tests > 0, "no library specified")
-- give priority to libraries located in the specified directory
if dir and not isglobal then
dir = dir:gsub("[/\\]+$", "")
for _, ext in ipairs {"dll", "so", "dylib"} do
if package.cpath:match ("%?%." .. ext) then
local cpath = dir .. "/?." .. ext .. ";"
if package.cpath:sub(1, #cpath) ~= cpath then
package.cpath = cpath .. package.cpath
end
break
end
end
end
-- do tests
for _, test in ipairs (tests) do
package.loaded[test.lib] = nil -- to force-reload the tested library
for _, setfile in ipairs (test) do
nerr = nerr + test_library (test.lib, setfile, verbose, really_verbose)
end
end
print ("Total number of failures: " .. nerr)
assert(nerr == 0, "Test failed!")
end
print("Resetting locale to: " .. old_locale)
os.setlocale(old_locale)
print("\n-----------------------------\n")
print("All tests passed!\n\n")
| gpl-2.0 |
greasydeal/darkstar | scripts/zones/Lower_Jeuno/npcs/Ruslan.lua | 37 | 2004 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Ruslan
-- Involved In Quest: Wondering Minstrel
-- Working 100%
-- @zone = 245
-- @pos = -19 -1 -58
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
wonderingstatus = player:getQuestStatus(WINDURST,WONDERING_MINSTREL);
if (wonderingstatus == QUEST_ACCEPTED) then
prog = player:getVar("QuestWonderingMin_var")
if (prog == 0) then -- WONDERING_MINSTREL + Rosewood Lumber: During Quest / Progression
player:startEvent(0x2719,0,718);
player:setVar("QuestWonderingMin_var",1);
elseif (prog == 1) then -- WONDERING_MINSTREL + Rosewood Lumber: Quest Objective Reminder
player:startEvent(0x271a,0,718);
end
elseif (wonderingstatus == QUEST_COMPLETED) then
rand = math.random(3);
if (rand == 1) then
player:startEvent(0x271b); -- WONDERING_MINSTREL: After Quest
else
player:startEvent(0x2718); -- Standard Conversation
end
else
player:startEvent(0x2718); -- Standard Conversation
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
LegionXI/darkstar | scripts/globals/items/walnut_cookie.lua | 12 | 1410 | -----------------------------------------
-- ID: 5922
-- Item: Walnut Cookie
-- Food Effect: 3 Min, All Races
-----------------------------------------
-- HP Healing 3
-- MP Healing 6
-- Bird Killer 10
-- Resist Paralyze 10
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,180,5922);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HPHEAL, 3);
target:addMod(MOD_MPHEAL, 6);
target:addMod(MOD_BIRD_KILLER, 10);
target:addMod(MOD_PARALYZERES, 10);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HPHEAL, 3);
target:delMod(MOD_MPHEAL, 6);
target:delMod(MOD_BIRD_KILLER, 10);
target:delMod(MOD_PARALYZERES, 10);
end;
| gpl-3.0 |
ibm2431/darkstar | scripts/zones/Port_Windurst/Zone.lua | 9 | 1803 | -----------------------------------
--
-- Zone: Port_Windurst (240)
--
-----------------------------------
local ID = require("scripts/zones/Port_Windurst/IDs");
require("scripts/globals/conquest");
require("scripts/globals/settings");
require("scripts/globals/zone");
-----------------------------------
function onInitialize(zone)
SetExplorerMoogles(ID.npc.EXPLORER_MOOGLE);
end;
function onZoneIn(player,prevZone)
local cs = -1;
-- FIRST LOGIN (START CS)
if (player:getPlaytime(false) == 0) then
if (OPENING_CUTSCENE_ENABLE == 1) then
cs = 305;
end
player:setPos(-120,-5.5,175,48);
player:setHomePoint();
end
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
if (prevZone == dsp.zone.WINDURST_JEUNO_AIRSHIP) then
cs = 10004;
player:setPos(228.000, -3.000, 76.000, 160);
else
position = math.random(1,5) + 195;
player:setPos(position,-15.56,258,65);
if (player:getMainJob() ~= player:getCharVar("PlayerMainJob")) then
cs = 30004;
end
player:setCharVar("PlayerMainJob",0);
end
end
return cs;
end;
function onConquestUpdate(zone, updatetype)
dsp.conq.onConquestUpdate(zone, updatetype)
end;
function onTransportEvent(player,transport)
player:startEvent(10002);
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 305) then
player:messageSpecial(ID.text.ITEM_OBTAINED,536);
elseif (csid == 10002) then
player:setPos(0,0,0,0,225);
elseif (csid == 30004 and option == 0) then
player:setHomePoint();
player:messageSpecial(ID.text.HOMEPOINT_SET);
end
end;
| gpl-3.0 |
greasydeal/darkstar | scripts/globals/items/serving_of_cherry_bavarois_+1.lua | 35 | 1388 | -----------------------------------------
-- ID: 5746
-- Item: serving_of_cherry_bavarois_+1
-- Food Effect: 4Hrs, All Races
-----------------------------------------
-- HP 30
-- Intelligence 4
-- MP 15
-- HP Recovered While Healing 4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5746);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 30);
target:addMod(MOD_INT, 4);
target:addMod(MOD_MP, 15);
target:addMod(MOD_HPHEAL, 4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 30);
target:delMod(MOD_INT, 4);
target:delMod(MOD_MP, 15);
target:delMod(MOD_HPHEAL, 4);
end;
| gpl-3.0 |
gwlim/luci | applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/smap_devinfo_mini.lua | 141 | 1031 | --[[
smap_devinfo - SIP Device Information
(c) 2009 Daniel Dickinson
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$
]]--
require("luci.i18n")
require("luci.util")
require("luci.sys")
require("luci.model.uci")
require("luci.controller.luci_diag.smap_common")
require("luci.controller.luci_diag.devinfo_common")
local debug = false
m = SimpleForm("luci-smap-to-devinfo", translate("Phone Information"), translate("Scan for supported SIP devices on specified networks."))
m.reset = false
m.submit = false
local outnets = luci.controller.luci_diag.smap_common.get_params()
luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.smap_common.command_function)
luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, true, "smap", true, debug)
luci.controller.luci_diag.smap_common.action_links(m, true)
return m
| apache-2.0 |
greasydeal/darkstar | scripts/zones/Tavnazian_Safehold/npcs/qm2.lua | 19 | 1697 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: ???
-- Involved in Quest: Unforgiven
-- @zone 26
-- @pos 110.714 -40.856 -53.154
-----------------------------------
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
require("scripts/zones/Tavnazian_Safehold/TextIDs")
require("scripts/globals/quests");
require("scripts/globals/keyitems");
-----------------------------------
-- For those who don't know
-- at the end of if(player:getQuestStatus(REGION,QUEST_NAME)
-- == 0 means QUEST_AVAILABLE
-- == 1 means QUEST_ACCEPTED
-- == 2 means QUEST_COMPLETED
-- e.g. if(player:getQuestStatus(OTHER_AREAS,UNFORGIVEN) == 0
-- means if(player:getQuestStatus(OTHER_AREAS,UNFORGIVEN) == QUEST AVAILABLE
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local Unforgiven = player:getQuestStatus(OTHER_AREAS,UNFORGIVEN);
if (Unforgiven == 1 and player:hasKeyItem(609) == false) then
player:addKeyItem(609);
player:messageSpecial(KEYITEM_OBTAINED,609) -- ALABASTER HAIRPIN for Unforgiven Quest
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 |
SIfoxDevTeam/wireshark | test/lua/pcap_file.lua | 30 | 27491 | -- pcap_file_reader.lua
--------------------------------------------------------------------------------
--[[
This is a Wireshark Lua-based pcap capture file reader.
Author: Hadriel Kaplan
This "capture file" reader reads pcap files - the old style ones. Don't expect this to
be as good as the real thing; this is a simplistic implementation to show how to
create such file readers, and for testing purposes.
This script requires Wireshark v1.12 or newer.
--]]
--------------------------------------------------------------------------------
-- do not modify this table
local debug = {
DISABLED = 0,
LEVEL_1 = 1,
LEVEL_2 = 2
}
-- set this DEBUG to debug.LEVEL_1 to enable printing debug info
-- set it to debug.LEVEL_2 to enable really verbose printing
local DEBUG = debug.LEVEL_1
local wireshark_name = "Wireshark"
if not GUI_ENABLED then
wireshark_name = "Tshark"
end
-- verify Wireshark is new enough
local major, minor, micro = get_version():match("(%d+)%.(%d+)%.(%d+)")
if major and tonumber(major) <= 1 and ((tonumber(minor) <= 10) or (tonumber(minor) == 11 and tonumber(micro) < 3)) then
error( "Sorry, but your " .. wireshark_name .. " version (" .. get_version() .. ") is too old for this script!\n" ..
"This script needs " .. wireshark_name .. "version 1.12 or higher.\n" )
end
-- verify we have the Struct library in wireshark
-- technically we should be able to do this with 'require', but Struct is a built-in
assert(Struct.unpack, wireshark_name .. " does not have the Struct library!")
--------------------------------------------------------------------------------
-- early definitions
-- throughout most of this file I try to pre-declare things to help ease
-- reading it and following the logic flow, but some things just have to be done
-- before others, so this sections has such things that cannot be avoided
--------------------------------------------------------------------------------
-- first some variable declarations for functions we'll define later
local parse_file_header, parse_rec_header, read_common
-- these will be set inside of parse_file_header(), but we're declaring them up here
local default_settings =
{
debug = DEBUG,
corrected_magic = 0xa1b2c3d4,
version_major = 2,
version_minor = 4,
timezone = 0,
sigfigs = 0,
read_snaplen = 0, -- the snaplen we read from file
snaplen = 0, -- the snaplen we use (limited by WTAP_MAX_PACKET_SIZE)
linktype = -1, -- the raw linktype number in the file header
wtap_type = wtap_encaps.UNKNOWN, -- the mapped internal wtap number based on linktype
endianess = ENC_BIG_ENDIAN,
time_precision = wtap_tsprecs.USEC,
rec_hdr_len = 16, -- default size of record header
rec_hdr_patt = "I4 I4 I4 I4", -- pattern for Struct to use
num_rec_fields = 4, -- number of vars in pattern
}
local dprint = function() end
local dprint2 = function() end
local function reset_debug()
if default_settings.debug > debug.DISABLED then
dprint = function(...)
print(table.concat({"Lua:", ...}," "))
end
if default_settings.debug > debug.LEVEL_1 then
dprint2 = dprint
end
end
end
-- call it now
reset_debug()
--------------------------------------------------------------------------------
-- file reader handling functions for Wireshark to use
--------------------------------------------------------------------------------
----------------------------------------
-- The read_open() is called by Wireshark once per file, to see if the file is this reader's type.
-- Wireshark passes in (1) a File object and (2) CaptureInfo object to this function
-- It expects in return either nil or false to mean it's not our file type, or true if it is
-- In our case what this means is we figure out if the file has the magic header, and get the
-- endianess of the file, and the encapsulation type of its frames/records
local function read_open(file, capture)
dprint2("read_open() called")
local file_settings = parse_file_header(file)
if file_settings then
dprint2("read_open: success, file is for us")
-- save our state
capture.private_table = file_settings
-- if the file is for us, we MUST set the file position cursor to
-- where we want the first call to read() function to get it the next time
-- for example if we checked a few records to be sure it's or type
-- but in this simple example we only verify the file header (24 bytes)
-- and we want the file position to remain after that header for our read()
-- call, so we don't change it back
--file:seek("set",position)
-- these we can also set per record later during read operations
capture.time_precision = file_settings.time_precision
capture.encap = file_settings.wtap_type
capture.snapshot_length = file_settings.snaplen
return true
end
dprint2("read_open: file not for us")
-- if it's not for us, wireshark will reset the file position itself
return false
end
----------------------------------------
-- Wireshark/tshark calls read() for each frame/record in the file
-- It passes in (1) a File, (2) CaptureInfo, and (3) FrameInfo object to this function
-- It expects in return the file offset position the record starts at,
-- or nil/false if there's an error or end-of-file is reached.
-- The offset position is used later: wireshark remembers it and gives
-- it to seek_read() at various random times
local function read(file, capture, frame)
dprint2("read() called")
-- call our common reader function
local position = file:seek()
if not read_common("read", file, capture, frame) then
-- this isnt' actually an error, because it might just mean we reached end-of-file
-- so let's test for that (read(0) is a special case in Lua, see Lua docs)
if file:read(0) ~= nil then
dprint("read: failed to call read_common")
else
dprint2("read: reached end of file")
end
return false
end
dprint2("read: succeess")
-- return the position we got to (or nil if we hit EOF/error)
return position
end
----------------------------------------
-- Wireshark/tshark calls seek_read() for each frame/record in the file, at random times
-- It passes in (1) a File, (2) CaptureInfo, (3) FrameInfo object, and the offset position number
-- It expects in return true for successful parsing, or nil/false if there's an error.
local function seek_read(file, capture, frame, offset)
dprint2("seek_read() called")
-- first move to the right position in the file
file:seek("set",offset)
if not read_common("seek_read", file, capture, frame) then
dprint("seek_read: failed to call read_common")
return false
end
return true
end
----------------------------------------
-- Wireshark/tshark calls read_close() when it's closing the file completely
-- It passes in (1) a File and (2) CaptureInfo object to this function
-- this is a good opportunity to clean up any state you may have created during
-- file reading. (in our case there's no real state)
local function read_close(file, capture)
dprint2("read_close() called")
-- we don't really have to reset anything, because we used the
-- capture.private_table and wireshark clears it for us after this function
return true
end
----------------------------------------
-- An often unused function, Wireshark calls this when the sequential walk-through is over
-- (i.e., no more calls to read(), only to seek_read()).
-- It passes in (1) a File and (2) CaptureInfo object to this function
-- This gives you a chance to clean up any state you used during read() calls, but remember
-- that there will be calls to seek_read() after this (in Wireshark, though not Tshark)
local function seq_read_close(file, capture)
dprint2("First pass of read() calls are over, but there may be seek_read() calls after this")
return true
end
----------------------------------------
-- ok, so let's create a FileHandler object
local fh = FileHandler.new("Lua-based PCAP reader", "lua_pcap", "A Lua-based file reader for PCAP-type files","rms")
-- set above functions to the FileHandler
fh.read_open = read_open
fh.read = read
fh.seek_read = seek_read
fh.read_close = read_close
fh.seq_read_close = seq_read_close
fh.extensions = "pcap;cap" -- this is just a hint
-- and finally, register the FileHandler!
register_filehandler(fh)
dprint2("FileHandler registered")
--------------------------------------------------------------------------------
-- ok now for the boring stuff that actually does the work
--------------------------------------------------------------------------------
----------------------------------------
-- in Lua, we have access to encapsulation types in the 'wtap_encaps' table, but
-- those numbers don't actually necessarily match the numbers in pcap files
-- for the encapsulation type, because the namespace got screwed up at some
-- point in the past (blame LBL NRG, not wireshark for that)
-- but I'm not going to create the full mapping of these two namespaces
-- instead we'll just use this smaller table to map them
-- these are taken from wiretap/pcap-common.c
local pcap2wtap = {
[0] = wtap_encaps.NULL,
[1] = wtap_encaps.ETHERNET,
[6] = wtap_encaps.TOKEN_RING,
[8] = wtap_encaps.SLIP,
[9] = wtap_encaps.PPP,
[101] = wtap_encaps.RAW_IP,
[105] = wtap_encaps.IEEE_802_11,
[127] = wtap_encaps.IEEE_802_11_RADIOTAP,
[140] = wtap_encaps.MTP2,
[141] = wtap_encaps.MTP3,
[143] = wtap_encaps.DOCSIS,
[147] = wtap_encaps.USER0,
[148] = wtap_encaps.USER1,
[149] = wtap_encaps.USER2,
[150] = wtap_encaps.USER3,
[151] = wtap_encaps.USER4,
[152] = wtap_encaps.USER5,
[153] = wtap_encaps.USER6,
[154] = wtap_encaps.USER7,
[155] = wtap_encaps.USER8,
[156] = wtap_encaps.USER9,
[157] = wtap_encaps.USER10,
[158] = wtap_encaps.USER11,
[159] = wtap_encaps.USER12,
[160] = wtap_encaps.USER13,
[161] = wtap_encaps.USER14,
[162] = wtap_encaps.USER15,
[186] = wtap_encaps.USB,
[187] = wtap_encaps.BLUETOOTH_H4,
[189] = wtap_encaps.USB_LINUX,
[195] = wtap_encaps.IEEE802_15_4,
}
-- we can use the above to directly map very quickly
-- but to map it backwards we'll use this, because I'm lazy:
local function wtap2pcap(encap)
for k,v in pairs(pcap2wtap) do
if v == encap then
return k
end
end
return 0
end
----------------------------------------
-- here are the "structs" we're going to parse, of the various records in a pcap file
-- these pattern string gets used in calls to Struct.unpack()
--
-- we will prepend a '<' or '>' later, once we figure out what endian-ess the files are in
--
-- this is a constant for minimum we need to read before we figure out the filetype
local FILE_HDR_LEN = 24
-- a pcap file header struct
-- this is: magic, version_major, version_minor, timezone, sigfigs, snaplen, encap type
local FILE_HEADER_PATT = "I4 I2 I2 i4 I4 I4 I4"
-- it's too bad Struct doesn't have a way to get the number of vars the pattern holds
-- another thing to add to my to-do list?
local NUM_HDR_FIELDS = 7
-- these will hold the '<'/'>' prepended version of above
--local file_header, rec_header
-- snaplen/caplen can't be bigger than this
local WTAP_MAX_PACKET_SIZE = 65535
----------------------------------------
-- different pcap file types have different magic values
-- we need to know various things about them for various functions
-- in this script, so this table holds all the info
--
-- See default_settings table above for the defaults used if this table
-- doesn't override them.
--
-- Arguably, these magic types represent different "Protocols" to dissect later,
-- but this script treats them all as "pcapfile" protocol.
--
-- From this table, we'll auto-create a value-string table for file header magic field
local magic_spells =
{
normal =
{
magic = 0xa1b2c3d4,
name = "Normal (Big-endian)",
},
swapped =
{
magic = 0xd4c3b2a1,
name = "Swapped Normal (Little-endian)",
endianess = ENC_LITTLE_ENDIAN,
},
modified =
{
-- this is for a ss991029 patched format only
magic = 0xa1b2cd34,
name = "Modified",
rec_hdr_len = 24,
rec_hdr_patt = "I4I4I4I4 I4 I2 I1 I1",
num_rec_fields = 8,
},
swapped_modified =
{
-- this is for a ss991029 patched format only
magic = 0x34cdb2a1,
name = "Swapped Modified",
rec_hdr_len = 24,
rec_hdr_patt = "I4I4I4I4 I4 I2 I1 I1",
num_rec_fields = 8,
endianess = ENC_LITTLE_ENDIAN,
},
nsecs =
{
magic = 0xa1b23c4d,
name = "Nanosecond",
time_precision = wtap_filetypes.TSPREC_NSEC,
},
swapped_nsecs =
{
magic = 0x4d3cb2a1,
name = "Swapped Nanosecond",
endianess = ENC_LITTLE_ENDIAN,
time_precision = wtap_filetypes.TSPREC_NSEC,
},
}
-- create a magic-to-spell entry table from above magic_spells table
-- so we can find them faster during file read operations
-- we could just add them right back into spells table, but this is cleaner
local magic_values = {}
for k,t in pairs(magic_spells) do
magic_values[t.magic] = t
end
-- the function which makes a copy of the default settings per file
local function new_settings()
dprint2("creating new file_settings")
local file_settings = {}
for k,v in pairs(default_settings) do
file_settings[k] = v
end
return file_settings
end
-- set the file_settings that the magic value defines in magic_values
local function set_magic_file_settings(magic)
local t = magic_values[magic]
if not t then
dprint("set_magic_file_settings: did not find magic settings for:",magic)
return false
end
local file_settings = new_settings()
-- the magic_values/spells table uses the same key names, so this is easy
for k,v in pairs(t) do
file_settings[k] = v
end
-- based on endianess, set the file_header and rec_header
-- and determine corrected_magic
if file_settings.endianess == ENC_BIG_ENDIAN then
file_settings.file_hdr_patt = '>' .. FILE_HEADER_PATT
file_settings.rec_hdr_patt = '>' .. file_settings.rec_hdr_patt
file_settings.corrected_magic = magic
else
file_settings.file_hdr_patt = '<' .. FILE_HEADER_PATT
file_settings.rec_hdr_patt = '<' .. file_settings.rec_hdr_patt
local m = Struct.pack(">I4", magic)
file_settings.corrected_magic = Struct.unpack("<I4", m)
end
file_settings.rec_hdr_len = Struct.size(file_settings.rec_hdr_patt)
return file_settings
end
----------------------------------------
-- internal functions declared previously
----------------------------------------
----------------------------------------
-- used by read_open(), this parses the file header
parse_file_header = function(file)
dprint2("parse_file_header() called")
-- by default, file:read() gets the next "string", meaning ending with a newline \n
-- but we want raw byte reads, so tell it how many bytes to read
local line = file:read(FILE_HDR_LEN)
-- it's ok for us to not be able to read it, but we need to tell wireshark the
-- file's not for us, so return false
if not line then return false end
dprint2("parse_file_header: got this line:\n'", Struct.tohex(line,false,":"), "'")
-- let's peek at the magic int32, assuming it's big-endian
local magic = Struct.unpack(">I4", line)
local file_settings = set_magic_file_settings(magic)
if not file_settings then
dprint("magic was: '", magic, "', so not a known pcap file?")
return false
end
-- this is: magic, version_major, version_minor, timezone, sigfigs, snaplen, encap type
local fields = { Struct.unpack(file_settings.file_hdr_patt, line) }
-- sanity check; also note that Struct.unpack() returns the fields plus
-- a number of where in the line it stopped reading (i.e., the end in this case)
-- so we got back number of fields + 1
if #fields ~= NUM_HDR_FIELDS + 1 then
-- this should never happen, since we already told file:read() to grab enough bytes
dprint("parse_file_header: failed to read the file header")
return nil
end
-- fields[1] is the magic, which we already parsed and saved before, but just to be sure
-- our endianess is set right, we validate what we got is what we expect now that
-- endianess has been corrected
if fields[1] ~= file_settings.corrected_magic then
dprint ("parse_file_header: endianess screwed up? Got:'", fields[1],
"', but wanted:", file_settings.corrected_magic)
return nil
end
file_settings.version_major = fields[2]
file_settings.version_minor = fields[3]
file_settings.timezone = fields[4]
file_settings.sigfigs = fields[5]
file_settings.read_snaplen = fields[6]
file_settings.linktype = fields[7]
-- wireshark only supports version 2.0 and later
if fields[2] < 2 then
dprint("got version =",VERSION_MAJOR,"but only version 2 or greater supported")
return false
end
-- convert pcap file interface type to wtap number type
file_settings.wtap_type = pcap2wtap[file_settings.linktype]
if not file_settings.wtap_type then
dprint("file nettype", file_settings.linktype,
"couldn't be mapped to wireshark wtap type")
return false
end
file_settings.snaplen = file_settings.read_snaplen
if file_settings.snaplen > WTAP_MAX_PACKET_SIZE then
file_settings.snaplen = WTAP_MAX_PACKET_SIZE
end
dprint2("read_file_header: got magic='", magic,
"', major version='", file_settings.version_major,
"', minor='", file_settings.version_minor,
"', timezone='", file_settings.timezone,
"', sigfigs='", file_settings.sigfigs,
"', read_snaplen='", file_settings.read_snaplen,
"', snaplen='", file_settings.snaplen,
"', nettype ='", file_settings.linktype,
"', wtap ='", file_settings.wtap_type)
--ok, it's a pcap file
dprint2("parse_file_header: success")
return file_settings
end
----------------------------------------
-- this is used by both read() and seek_read()
-- the calling function to this should have already set the file position correctly
read_common = function(funcname, file, capture, frame)
dprint2(funcname,": read_common() called")
-- get the state info
local file_settings = capture.private_table
-- first parse the record header, which will set the FrameInfo fields
if not parse_rec_header(funcname, file, file_settings, frame) then
dprint2(funcname, ": read_common: hit end of file or error")
return false
end
frame.encap = file_settings.wtap_type
-- now we need to get the packet bytes from the file record into the frame...
-- we *could* read them into a string using file:read(numbytes), and then
-- set them to frame.data so that wireshark gets it...
-- but that would mean the packet's string would be copied into Lua
-- and then sent right back into wireshark, which is gonna slow things
-- down; instead FrameInfo has a read_data() method, which makes
-- wireshark read directly from the file into the frame buffer, so we use that
if not frame:read_data(file, frame.captured_length) then
dprint(funcname, ": read_common: failed to read data from file into buffer")
return false
end
return true
end
----------------------------------------
-- the function to parse individual records
parse_rec_header = function(funcname, file, file_settings, frame)
dprint2(funcname,": parse_rec_header() called")
local line = file:read(file_settings.rec_hdr_len)
-- it's ok for us to not be able to read it, if it's end of file
if not line then return false end
-- this is: time_sec, time_usec, capture_len, original_len
local fields = { Struct.unpack(file_settings.rec_hdr_patt, line) }
-- sanity check; also note that Struct.unpack() returns the fields plus
-- a number of where in the line it stopped reading (i.e., the end in this case)
-- so we got back number of fields + 1
if #fields ~= file_settings.num_rec_fields + 1 then
dprint(funcname, ": parse_rec_header: failed to read the record header, got:",
#fields, ", expected:", file_settings.num_rec_fields)
return nil
end
local nsecs = fields[2]
if file_settings.time_precision == wtap_filetypes.TSPREC_USEC then
nsecs = nsecs * 1000
elseif file_settings.time_precision == wtap_filetypes.TSPREC_MSEC then
nsecs = nsecs * 1000000
end
frame.time = NSTime(fields[1], nsecs)
local caplen, origlen = fields[3], fields[4]
-- sanity check, verify captured length isn't more than original length
if caplen > origlen then
dprint("captured length of", caplen, "is bigger than original length of", origlen)
-- swap them, a cool Lua ability
caplen, origlen = origlen, caplen
end
if caplen > WTAP_MAX_PACKET_SIZE then
dprint("Got a captured_length of", caplen, "which is too big")
caplen = WTAP_MAX_PACKET_SIZE
end
frame.rec_type = wtap_rec_types.PACKET
frame.captured_length = caplen
frame.original_length = origlen
frame.flags = wtap_presence_flags.TS + wtap_presence_flags.CAP_LEN -- for timestamp|cap_len
dprint2(funcname,": parse_rec_header() returning")
return true
end
--------------------------------------------------------------------------------
-- file writer handling functions for Wireshark to use
--------------------------------------------------------------------------------
-- file encaps we can handle writing
local canwrite = {
[ wtap_encaps.NULL ] = true,
[ wtap_encaps.ETHERNET ] = true,
[ wtap_encaps.PPP ] = true,
[ wtap_encaps.RAW_IP ] = true,
[ wtap_encaps.IEEE_802_11 ] = true,
[ wtap_encaps.MTP2 ] = true,
[ wtap_encaps.MTP3 ] = true,
-- etc., etc.
}
-- we can't reuse the variables we used in the reader, because this script might be used to both
-- open a file for reading and write it out, at the same time, so we cerate another file_settings
-- instance.
-- set the file_settings for the little-endian version in magic_spells
local function create_writer_file_settings()
dprint2("create_writer_file_settings called")
local t = magic_spells.swapped
local file_settings = new_settings()
-- the magic_values/spells table uses the same key names, so this is easy
for k,v in pairs(t) do
file_settings[k] = v
end
-- based on endianess, set the file_header and rec_header
-- and determine corrected_magic
if file_settings.endianess == ENC_BIG_ENDIAN then
file_settings.file_hdr_patt = '>' .. FILE_HEADER_PATT
file_settings.rec_hdr_patt = '>' .. file_settings.rec_hdr_patt
file_settings.corrected_magic = file_settings.magic
else
file_settings.file_hdr_patt = '<' .. FILE_HEADER_PATT
file_settings.rec_hdr_patt = '<' .. file_settings.rec_hdr_patt
local m = Struct.pack(">I4", file_settings.magic)
file_settings.corrected_magic = Struct.unpack("<I4", m)
end
file_settings.rec_hdr_len = Struct.size(file_settings.rec_hdr_patt)
return file_settings
end
----------------------------------------
-- The can_write_encap() function is called by Wireshark when it wants to write out a file,
-- and needs to see if this file writer can handle the packet types in the window.
-- We need to return true if we can handle it, else false
local function can_write_encap(encap)
dprint2("can_write_encap() called with encap=",encap)
return canwrite[encap] or false
end
local function write_open(file, capture)
dprint2("write_open() called")
local file_settings = create_writer_file_settings()
-- write out file header
local hdr = Struct.pack(file_settings.file_hdr_patt,
file_settings.corrected_magic,
file_settings.version_major,
file_settings.version_minor,
file_settings.timezone,
file_settings.sigfigs,
capture.snapshot_length,
wtap2pcap(capture.encap))
if not hdr then
dprint("write_open: error generating file header")
return false
end
dprint2("write_open generating:", Struct.tohex(hdr))
if not file:write(hdr) then
dprint("write_open: error writing file header to file")
return false
end
-- save settings
capture.private_table = file_settings
return true
end
local function write(file, capture, frame)
dprint2("write() called")
-- get file settings
local file_settings = capture.private_table
if not file_settings then
dprint("write() failed to get private table file settings")
return false
end
-- write out record header: time_sec, time_usec, capture_len, original_len
-- first get times
local nstime = frame.time
-- pcap format is in usecs, but wireshark's internal is nsecs
local nsecs = nstime.nsecs
if file_settings.time_precision == wtap_filetypes.TSPREC_USEC then
nsecs = nsecs / 1000
elseif file_settings.time_precision == wtap_filetypes.TSPREC_MSEC then
nsecs = nsecs / 1000000
end
local hdr = Struct.pack(file_settings.rec_hdr_patt,
nstime.secs,
nsecs,
frame.captured_length,
frame.original_length)
if not hdr then
dprint("write: error generating record header")
return false
end
if not file:write(hdr) then
dprint("write: error writing record header to file")
return false
end
-- we could write the packet data the same way, by getting frame.data and writing it out
-- but we can avoid copying those bytes into Lua by using the write_data() function
if not frame:write_data(file) then
dprint("write: error writing record data to file")
return false
end
return true
end
local function write_close(file, capture)
dprint2("write_close() called")
dprint2("Good night, and good luck")
return true
end
-- ok, so let's create another FileHandler object
local fh2 = FileHandler.new("Lua-based PCAP writer", "lua_pcap2", "A Lua-based file writer for PCAP-type files","wms")
-- set above functions to the FileHandler
fh2.can_write_encap = can_write_encap
fh2.write_open = write_open
fh2.write = write
fh2.write_close = write_close
fh2.extensions = "pcap;cap" -- this is just a hint
-- and finally, register the FileHandler!
register_filehandler(fh2)
dprint2("Second FileHandler registered")
| gpl-2.0 |
LegionXI/darkstar | scripts/zones/Port_San_dOria/npcs/Meta.lua | 17 | 1397 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Meta
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_San_dOria/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x208);
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 |
Codex-NG/otxserver | data/spells/scripts/party/enchant.lua | 11 | 1779 | local combat = createCombatObject()
local area = createCombatArea(AREA_CROSS5X5)
setCombatArea(combat, area)
setCombatParam(combat, COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_RED)
setCombatParam(combat, COMBAT_PARAM_AGGRESSIVE, 0)
local condition = createConditionObject(CONDITION_ATTRIBUTES)
setConditionParam(condition, CONDITION_PARAM_SUBID, 3)
setConditionParam(condition, CONDITION_PARAM_BUFF_SPELL, 1)
setConditionParam(condition, CONDITION_PARAM_TICKS, 2 * 60 * 1000)
setConditionParam(condition, CONDITION_PARAM_STAT_MAGICPOINTS, 1)
local baseMana = 120
function onCastSpell(cid, var)
local pos = getCreaturePosition(cid)
local membersList = getPartyMembers(cid)
if(membersList == nil or type(membersList) ~= 'table' or #membersList <= 1) then
doPlayerSendCancel(cid, "No party members in range.")
doSendMagicEffect(pos, CONST_ME_POFF)
return false
end
local affectedList = {}
for _, pid in ipairs(membersList) do
if(getDistanceBetween(getCreaturePosition(pid), pos) <= 36) then
table.insert(affectedList, pid)
end
end
local tmp = #affectedList
if(tmp <= 1) then
doPlayerSendCancel(cid, "No party members in range.")
doSendMagicEffect(pos, CONST_ME_POFF)
return false
end
local mana = math.ceil((0.9 ^ (tmp - 1) * baseMana) * tmp)
if(getPlayerMana(cid) < mana) then
doPlayerSendDefaultCancel(cid, RETURNVALUE_NOTENOUGHMANA)
doSendMagicEffect(pos, CONST_ME_POFF)
return false
end
if(doCombat(cid, combat, var) ~= true) then
doPlayerSendDefaultCancel(cid, RETURNVALUE_NOTPOSSIBLE)
doSendMagicEffect(pos, CONST_ME_POFF)
return false
end
doPlayerAddMana(cid, -(mana - baseMana), FALSE)
doPlayerAddManaSpent(cid, (mana - baseMana))
for _, pid in ipairs(affectedList) do
doAddCondition(pid, condition)
end
return true
end
| gpl-2.0 |
LegionXI/darkstar | scripts/globals/abilities/chaos_roll.lua | 15 | 4467 | -----------------------------------
-- Ability: Chaos Roll
-- Enhances attack for party members within area of effect
-- Optimal Job: Dark Knight
-- Lucky Number: 4
-- Unlucky Number: 8
-- Level: 14
--
-- Die Roll |No DRK |With DRK
-- -------- -------- -----------
-- 1 |6% |16%
-- 2 |8% |18%
-- 3 |9% |19%
-- 4 |25% |35%
-- 5 |11% |21%
-- 6 |13% |23%
-- 7 |16% |26%
-- 8 |3% |13%
-- 9 |17% |27%
-- 10 |19% |29%
-- 11 |31% |41%
-- Bust |-10% |-10%
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/ability");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
local effectID = EFFECT_CHAOS_ROLL
ability:setRange(ability:getRange() + player:getMod(MOD_ROLL_RANGE));
if (player:hasStatusEffect(effectID)) then
return MSGBASIC_ROLL_ALREADY_ACTIVE,0;
elseif atMaxCorsairBusts(player) then
return MSGBASIC_CANNOT_PERFORM,0;
else
return 0,0;
end
end;
-----------------------------------
-- onUseAbilityRoll
-----------------------------------
function onUseAbility(caster,target,ability,action)
if (caster:getID() == target:getID()) then
corsairSetup(caster, ability, action, EFFECT_CHAOS_ROLL, JOBS.DRK);
end
local total = caster:getLocalVar("corsairRollTotal")
return applyRoll(caster,target,ability,action,total)
end;
function onUseAbilityRoll(caster,target,ability,total)
local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK)
local effectpowers = {6, 8, 9, 25, 11, 13, 16, 3, 17, 19, 31, 10}
local effectpower = effectpowers[total];
local jobBonus = caster:getLocalVar("DRK_roll_bonus");
if (total < 12) then
if (jobBonus == 0) then -- this happens on the first roll only, and only for the roller
if (caster:hasPartyJob(JOBS.DRK) or math.random(0, 99) < caster:getMod(MOD_JOB_BONUS_CHANCE)) then
jobBonus = 1; -- enables job boost
-- print("first roll w/ bonus")
else
jobBonus = 2; -- setting this to 2 so it doesn't allow for another attempt to apply the job bonus with the modifier upon double-up.
-- print("first roll")
end
end
if (jobBonus == 1) then
effectpower = effectpower + 10;
-- print("activate job bonus");
end
if (target:getID() == caster:getID()) then -- only need to set the variable for the caster, and just once.
caster:setLocalVar("DRK_roll_bonus", jobBonus);
end
-- print(caster:getLocalVar("DRK_roll_bonus"));
end
if (caster:getMainJob() == JOBS.COR and caster:getMainLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl());
elseif (caster:getSubJob() == JOBS.COR and caster:getSubLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl());
end
if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_CHAOS_ROLL, effectpower, 0, duration, caster:getID(), total, MOD_ATTP) == false) then
ability:setMsg(423);
end
end;
function applyRoll(caster,target,ability,action,total)
local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK)
local effectpowers = {6, 8, 9, 25, 11, 13, 16, 3, 17, 19, 31, 10}
local effectpower = effectpowers[total];
if (caster:getLocalVar("corsairRollBonus") == 1 and total < 12) then
effectpower = effectpower + 10
end
if (caster:getMainJob() == JOBS.COR and caster:getMainLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl());
elseif (caster:getSubJob() == JOBS.COR and caster:getSubLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl());
end
if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_CHAOS_ROLL, effectpower, 0, duration, caster:getID(), total, MOD_ATTP) == false) then
ability:setMsg(422);
elseif total > 11 then
ability:setMsg(426);
end
return total;
end
| gpl-3.0 |
evrooije/beerarchy | mods/00_bt_nodes/farming/soil.lua | 5 | 2010 |
local S = farming.intllib
-- normal soil
minetest.register_node("farming:soil", {
description = S("Soil"),
tiles = {"default_dirt.png^farming_soil.png", "default_dirt.png"},
drop = "default:dirt",
groups = {crumbly = 3, not_in_creative_inventory = 1, soil = 2},
sounds = default.node_sound_dirt_defaults(),
})
-- wet soil
minetest.register_node("farming:soil_wet", {
description = S("Wet Soil"),
tiles = {"default_dirt.png^farming_soil_wet.png", "default_dirt.png^farming_soil_wet_side.png"},
drop = "default:dirt",
groups = {crumbly = 3, not_in_creative_inventory = 1, soil = 3},
sounds = default.node_sound_dirt_defaults(),
})
-- sand is not soil, change existing sand-soil to use normal soil
minetest.register_alias("farming:desert_sand_soil", "farming:soil")
minetest.register_alias("farming:desert_sand_soil_wet", "farming:soil_wet")
-- if water near soil then change to wet soil
minetest.register_abm({
nodenames = {"farming:soil", "farming:soil_wet"},
interval = 15,
chance = 4,
catch_up = false,
action = function(pos, node)
pos.y = pos.y + 1
local nn = minetest.get_node_or_nil(pos)
pos.y = pos.y - 1
if nn then nn = nn.name else return end
-- what's on top of soil, if solid/not plant change soil to dirt
if minetest.registered_nodes[nn]
and minetest.registered_nodes[nn].walkable
and minetest.get_item_group(nn, "plant") == 0 then
minetest.set_node(pos, {name = "default:dirt"})
return
end
-- if map around soil not loaded then skip until loaded
if minetest.find_node_near(pos, 3, {"ignore"}) then
return
end
-- check if there is water nearby and change soil accordingly
if minetest.find_node_near(pos, 3, {"group:water"}) then
if node.name == "farming:soil" then
minetest.set_node(pos, {name = "farming:soil_wet"})
end
elseif node.name == "farming:soil_wet" then
minetest.set_node(pos, {name = "farming:soil"})
elseif node.name == "farming:soil" then
minetest.set_node(pos, {name = "default:dirt"})
end
end,
}) | lgpl-2.1 |
LegionXI/darkstar | scripts/globals/spells/blind.lua | 20 | 1377 | -----------------------------------------
-- Spell: Blind
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
-- Pull base stats.
local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_MND)); --blind uses caster INT vs target MND
-- Base power. May need more research.
local power = math.floor((dINT + 60) / 4);
if (power < 5) then
power = 5;
end
if (power > 20) then
power = 20;
end
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
power = power * 2;
end
-- Duration, including resistance. Unconfirmed.
local duration = 120 * applyResistanceEffect(caster,spell,target,dINT,35,0,EFFECT_BLINDNESS);
if (duration >= 60) then --Do it!
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
duration = duration * 2;
end
caster:delStatusEffect(EFFECT_SABOTEUR);
if (target:addStatusEffect(EFFECT_BLINDNESS,power,0,duration)) then
spell:setMsg(236);
else
spell:setMsg(75);
end
else
spell:setMsg(85);
end
return EFFECT_BLINDNESS;
end;
| gpl-3.0 |
PerimeterX/perimeterx-nginx-plugin | vendor/lua-cjson/lua/cjson/util.lua | 170 | 6837 | local json = require "cjson"
-- Various common routines used by the Lua CJSON package
--
-- Mark Pulford <mark@kyne.com.au>
-- Determine with a Lua table can be treated as an array.
-- Explicitly returns "not an array" for very sparse arrays.
-- Returns:
-- -1 Not an array
-- 0 Empty table
-- >0 Highest index in the array
local function is_array(table)
local max = 0
local count = 0
for k, v in pairs(table) do
if type(k) == "number" then
if k > max then max = k end
count = count + 1
else
return -1
end
end
if max > count * 2 then
return -1
end
return max
end
local serialise_value
local function serialise_table(value, indent, depth)
local spacing, spacing2, indent2
if indent then
spacing = "\n" .. indent
spacing2 = spacing .. " "
indent2 = indent .. " "
else
spacing, spacing2, indent2 = " ", " ", false
end
depth = depth + 1
if depth > 50 then
return "Cannot serialise any further: too many nested tables"
end
local max = is_array(value)
local comma = false
local fragment = { "{" .. spacing2 }
if max > 0 then
-- Serialise array
for i = 1, max do
if comma then
table.insert(fragment, "," .. spacing2)
end
table.insert(fragment, serialise_value(value[i], indent2, depth))
comma = true
end
elseif max < 0 then
-- Serialise table
for k, v in pairs(value) do
if comma then
table.insert(fragment, "," .. spacing2)
end
table.insert(fragment,
("[%s] = %s"):format(serialise_value(k, indent2, depth),
serialise_value(v, indent2, depth)))
comma = true
end
end
table.insert(fragment, spacing .. "}")
return table.concat(fragment)
end
function serialise_value(value, indent, depth)
if indent == nil then indent = "" end
if depth == nil then depth = 0 end
if value == json.null then
return "json.null"
elseif type(value) == "string" then
return ("%q"):format(value)
elseif type(value) == "nil" or type(value) == "number" or
type(value) == "boolean" then
return tostring(value)
elseif type(value) == "table" then
return serialise_table(value, indent, depth)
else
return "\"<" .. type(value) .. ">\""
end
end
local function file_load(filename)
local file
if filename == nil then
file = io.stdin
else
local err
file, err = io.open(filename, "rb")
if file == nil then
error(("Unable to read '%s': %s"):format(filename, err))
end
end
local data = file:read("*a")
if filename ~= nil then
file:close()
end
if data == nil then
error("Failed to read " .. filename)
end
return data
end
local function file_save(filename, data)
local file
if filename == nil then
file = io.stdout
else
local err
file, err = io.open(filename, "wb")
if file == nil then
error(("Unable to write '%s': %s"):format(filename, err))
end
end
file:write(data)
if filename ~= nil then
file:close()
end
end
local function compare_values(val1, val2)
local type1 = type(val1)
local type2 = type(val2)
if type1 ~= type2 then
return false
end
-- Check for NaN
if type1 == "number" and val1 ~= val1 and val2 ~= val2 then
return true
end
if type1 ~= "table" then
return val1 == val2
end
-- check_keys stores all the keys that must be checked in val2
local check_keys = {}
for k, _ in pairs(val1) do
check_keys[k] = true
end
for k, v in pairs(val2) do
if not check_keys[k] then
return false
end
if not compare_values(val1[k], val2[k]) then
return false
end
check_keys[k] = nil
end
for k, _ in pairs(check_keys) do
-- Not the same if any keys from val1 were not found in val2
return false
end
return true
end
local test_count_pass = 0
local test_count_total = 0
local function run_test_summary()
return test_count_pass, test_count_total
end
local function run_test(testname, func, input, should_work, output)
local function status_line(name, status, value)
local statusmap = { [true] = ":success", [false] = ":error" }
if status ~= nil then
name = name .. statusmap[status]
end
print(("[%s] %s"):format(name, serialise_value(value, false)))
end
local result = { pcall(func, unpack(input)) }
local success = table.remove(result, 1)
local correct = false
if success == should_work and compare_values(result, output) then
correct = true
test_count_pass = test_count_pass + 1
end
test_count_total = test_count_total + 1
local teststatus = { [true] = "PASS", [false] = "FAIL" }
print(("==> Test [%d] %s: %s"):format(test_count_total, testname,
teststatus[correct]))
status_line("Input", nil, input)
if not correct then
status_line("Expected", should_work, output)
end
status_line("Received", success, result)
print()
return correct, result
end
local function run_test_group(tests)
local function run_helper(name, func, input)
if type(name) == "string" and #name > 0 then
print("==> " .. name)
end
-- Not a protected call, these functions should never generate errors.
func(unpack(input or {}))
print()
end
for _, v in ipairs(tests) do
-- Run the helper if "should_work" is missing
if v[4] == nil then
run_helper(unpack(v))
else
run_test(unpack(v))
end
end
end
-- Run a Lua script in a separate environment
local function run_script(script, env)
local env = env or {}
local func
-- Use setfenv() if it exists, otherwise assume Lua 5.2 load() exists
if _G.setfenv then
func = loadstring(script)
if func then
setfenv(func, env)
end
else
func = load(script, nil, nil, env)
end
if func == nil then
error("Invalid syntax.")
end
func()
return env
end
-- Export functions
return {
serialise_value = serialise_value,
file_load = file_load,
file_save = file_save,
compare_values = compare_values,
run_test_summary = run_test_summary,
run_test = run_test,
run_test_group = run_test_group,
run_script = run_script
}
-- vi:ai et sw=4 ts=4:
| mit |
creationix/nodemcu-firmware | app/cjson/lua/cjson/util.lua | 170 | 6837 | local json = require "cjson"
-- Various common routines used by the Lua CJSON package
--
-- Mark Pulford <mark@kyne.com.au>
-- Determine with a Lua table can be treated as an array.
-- Explicitly returns "not an array" for very sparse arrays.
-- Returns:
-- -1 Not an array
-- 0 Empty table
-- >0 Highest index in the array
local function is_array(table)
local max = 0
local count = 0
for k, v in pairs(table) do
if type(k) == "number" then
if k > max then max = k end
count = count + 1
else
return -1
end
end
if max > count * 2 then
return -1
end
return max
end
local serialise_value
local function serialise_table(value, indent, depth)
local spacing, spacing2, indent2
if indent then
spacing = "\n" .. indent
spacing2 = spacing .. " "
indent2 = indent .. " "
else
spacing, spacing2, indent2 = " ", " ", false
end
depth = depth + 1
if depth > 50 then
return "Cannot serialise any further: too many nested tables"
end
local max = is_array(value)
local comma = false
local fragment = { "{" .. spacing2 }
if max > 0 then
-- Serialise array
for i = 1, max do
if comma then
table.insert(fragment, "," .. spacing2)
end
table.insert(fragment, serialise_value(value[i], indent2, depth))
comma = true
end
elseif max < 0 then
-- Serialise table
for k, v in pairs(value) do
if comma then
table.insert(fragment, "," .. spacing2)
end
table.insert(fragment,
("[%s] = %s"):format(serialise_value(k, indent2, depth),
serialise_value(v, indent2, depth)))
comma = true
end
end
table.insert(fragment, spacing .. "}")
return table.concat(fragment)
end
function serialise_value(value, indent, depth)
if indent == nil then indent = "" end
if depth == nil then depth = 0 end
if value == json.null then
return "json.null"
elseif type(value) == "string" then
return ("%q"):format(value)
elseif type(value) == "nil" or type(value) == "number" or
type(value) == "boolean" then
return tostring(value)
elseif type(value) == "table" then
return serialise_table(value, indent, depth)
else
return "\"<" .. type(value) .. ">\""
end
end
local function file_load(filename)
local file
if filename == nil then
file = io.stdin
else
local err
file, err = io.open(filename, "rb")
if file == nil then
error(("Unable to read '%s': %s"):format(filename, err))
end
end
local data = file:read("*a")
if filename ~= nil then
file:close()
end
if data == nil then
error("Failed to read " .. filename)
end
return data
end
local function file_save(filename, data)
local file
if filename == nil then
file = io.stdout
else
local err
file, err = io.open(filename, "wb")
if file == nil then
error(("Unable to write '%s': %s"):format(filename, err))
end
end
file:write(data)
if filename ~= nil then
file:close()
end
end
local function compare_values(val1, val2)
local type1 = type(val1)
local type2 = type(val2)
if type1 ~= type2 then
return false
end
-- Check for NaN
if type1 == "number" and val1 ~= val1 and val2 ~= val2 then
return true
end
if type1 ~= "table" then
return val1 == val2
end
-- check_keys stores all the keys that must be checked in val2
local check_keys = {}
for k, _ in pairs(val1) do
check_keys[k] = true
end
for k, v in pairs(val2) do
if not check_keys[k] then
return false
end
if not compare_values(val1[k], val2[k]) then
return false
end
check_keys[k] = nil
end
for k, _ in pairs(check_keys) do
-- Not the same if any keys from val1 were not found in val2
return false
end
return true
end
local test_count_pass = 0
local test_count_total = 0
local function run_test_summary()
return test_count_pass, test_count_total
end
local function run_test(testname, func, input, should_work, output)
local function status_line(name, status, value)
local statusmap = { [true] = ":success", [false] = ":error" }
if status ~= nil then
name = name .. statusmap[status]
end
print(("[%s] %s"):format(name, serialise_value(value, false)))
end
local result = { pcall(func, unpack(input)) }
local success = table.remove(result, 1)
local correct = false
if success == should_work and compare_values(result, output) then
correct = true
test_count_pass = test_count_pass + 1
end
test_count_total = test_count_total + 1
local teststatus = { [true] = "PASS", [false] = "FAIL" }
print(("==> Test [%d] %s: %s"):format(test_count_total, testname,
teststatus[correct]))
status_line("Input", nil, input)
if not correct then
status_line("Expected", should_work, output)
end
status_line("Received", success, result)
print()
return correct, result
end
local function run_test_group(tests)
local function run_helper(name, func, input)
if type(name) == "string" and #name > 0 then
print("==> " .. name)
end
-- Not a protected call, these functions should never generate errors.
func(unpack(input or {}))
print()
end
for _, v in ipairs(tests) do
-- Run the helper if "should_work" is missing
if v[4] == nil then
run_helper(unpack(v))
else
run_test(unpack(v))
end
end
end
-- Run a Lua script in a separate environment
local function run_script(script, env)
local env = env or {}
local func
-- Use setfenv() if it exists, otherwise assume Lua 5.2 load() exists
if _G.setfenv then
func = loadstring(script)
if func then
setfenv(func, env)
end
else
func = load(script, nil, nil, env)
end
if func == nil then
error("Invalid syntax.")
end
func()
return env
end
-- Export functions
return {
serialise_value = serialise_value,
file_load = file_load,
file_save = file_save,
compare_values = compare_values,
run_test_summary = run_test_summary,
run_test = run_test,
run_test_group = run_test_group,
run_script = run_script
}
-- vi:ai et sw=4 ts=4:
| mit |
LegionXI/darkstar | scripts/globals/items/nopales_salad.lua | 12 | 1358 | -----------------------------------------
-- ID: 5701
-- Item: nopales_salad
-- Food Effect: 3Hrs, All Races
-----------------------------------------
-- Strength 1
-- Agility 6
-- Ranged Accuracy +20
-- Ranged Attack +10
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5701);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 1);
target:addMod(MOD_AGI, 6);
target:addMod(MOD_RACC, 20);
target:addMod(MOD_RATT, 10);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 1);
target:delMod(MOD_AGI, 6);
target:delMod(MOD_RACC, 20);
target:delMod(MOD_RATT, 10);
end;
| gpl-3.0 |
naclander/tome | game/modules/tome/data/general/objects/totems.lua | 3 | 2553 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
newEntity{
define_as = "BASE_TOTEM",
slot = "TOOL",
type = "charm", subtype="totem",
unided_name = "totem", id_by_type = true,
display = "-", color=colors.WHITE, image = resolvers.image_material("totem", "wood"),
encumber = 2,
rarity = 12,
add_name = "#CHARM# #CHARGES#",
use_sound = "talents/spell_generic",
desc = [[Natural totems are made by powerful wilders to store nature power.]],
egos = "/data/general/objects/egos/totems.lua", egos_chance = { prefix=resolvers.mbonus(20, 5), suffix=resolvers.mbonus(20, 5) },
addons = "/data/general/objects/egos/totems-powers.lua",
power_source = {nature=true},
randart_able = "/data/general/objects/random-artifacts/generic.lua",
talent_cooldown = "T_GLOBAL_CD",
}
newEntity{ base = "BASE_TOTEM",
name = "elm totem", short_name = "elm",
color = colors.UMBER,
level_range = {1, 10},
cost = 1,
material_level = 1,
charm_power = resolvers.mbonus_material(15, 10),
}
newEntity{ base = "BASE_TOTEM",
name = "ash totem", short_name = "ash",
color = colors.UMBER,
level_range = {10, 20},
cost = 2,
material_level = 2,
charm_power = resolvers.mbonus_material(20, 20),
}
newEntity{ base = "BASE_TOTEM",
name = "yew totem", short_name = "yew",
color = colors.UMBER,
level_range = {20, 30},
cost = 3,
material_level = 3,
charm_power = resolvers.mbonus_material(25, 30),
}
newEntity{ base = "BASE_TOTEM",
name = "elven-wood totem", short_name = "e.wood",
color = colors.UMBER,
level_range = {30, 40},
cost = 4,
material_level = 4,
charm_power = resolvers.mbonus_material(30, 40),
}
newEntity{ base = "BASE_TOTEM",
name = "dragonbone totem", short_name = "dragonbone",
color = colors.UMBER,
level_range = {40, 50},
cost = 5,
material_level = 5,
charm_power = resolvers.mbonus_material(35, 50),
}
| gpl-3.0 |
ibm2431/darkstar | scripts/zones/Mine_Shaft_2716/bcnms/century_of_hardship.lua | 9 | 1420 | -----------------------------------
-- A Century of Hardship
-- Mine Shaft #2716 mission battlefield
-----------------------------------
require("scripts/globals/battlefield")
require("scripts/globals/missions")
-----------------------------------
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
local arg8 = (player:getCurrentMission(COP) ~= dsp.mission.id.cop.THREE_PATHS or player:getCharVar("COP_Louverance_s_Path") ~= 5) and 1 or 0
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), arg8)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 32001 then
if player:getCurrentMission(COP) == dsp.mission.id.cop.THREE_PATHS and player:getCharVar("COP_Louverance_s_Path") == 5 then
player:setCharVar("COP_Louverance_s_Path", 6)
end
player:addExp(1000)
end
end
| gpl-3.0 |
LegionXI/darkstar | scripts/zones/Rabao/npcs/Edigey.lua | 12 | 2587 | -----------------------------------
-- Area: Rabao
-- NPC: Edigey
-- Starts and Ends Quest: Don't Forget the Antidote
-----------------------------------
package.loaded["scripts/zones/Rabao/TextIDs"] = nil;
require("scripts/globals/titles");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Rabao/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
ForgetTheAntidote = player:getQuestStatus(OUTLANDS,DONT_FORGET_THE_ANTIDOTE);
if ((ForgetTheAntidote == QUEST_ACCEPTED or ForgetTheAntidote == QUEST_COMPLETED) and trade:hasItemQty(1209,1) and trade:getItemCount() == 1) then
player:startEvent(0x0004,0,1209);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
ForgetTheAntidote = player:getQuestStatus(OUTLANDS,DONT_FORGET_THE_ANTIDOTE);
if (ForgetTheAntidote == QUEST_AVAILABLE and player:getFameLevel(RABAO) >= 4) then
player:startEvent(0x0002,0,1209);
elseif (ForgetTheAntidote == QUEST_ACCEPTED) then
player:startEvent(0x0003,0,1209);
elseif (ForgetTheAntidote == QUEST_COMPLETED) then
player:startEvent(0x0005,0,1209);
else
player:startEvent(0x0032);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0002 and option == 1) then
player:addQuest(OUTLANDS,DONT_FORGET_THE_ANTIDOTE);
player:setVar("DontForgetAntidoteVar",1);
elseif (csid == 0x0004 and player:getVar("DontForgetAntidoteVar") == 1) then --If completing for the first time
player:setVar("DontForgetAntidoteVar",0);
player:tradeComplete();
player:addTitle(262);
player:addItem(16974); -- Dotanuki
player:messageSpecial(ITEM_OBTAINED, 16974);
player:completeQuest(OUTLANDS,DONT_FORGET_THE_ANTIDOTE);
player:addFame(RABAO,60);
elseif (csid == 0x0004) then --Subsequent completions
player:tradeComplete();
player:addGil(GIL_RATE*1800);
player:messageSpecial(GIL_OBTAINED, 1800);
player:addFame(RABAO,30);
end
end;
| gpl-3.0 |
ibm2431/darkstar | scripts/globals/items/sea_bass_croute.lua | 11 | 1485 | -----------------------------------------
-- ID: 4353
-- Item: sea_bass_croute
-- Food Effect: 30Min, All Races
-----------------------------------------
-- MP +5% (cap 150)
-- Dexterity 4
-- Mind 5
-- Accuracy 3
-- Ranged Accuracy % 6 (cap 20)
-- HP recovered while healing 9
-- MP recovered while healing 2
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,1800,4353)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.FOOD_MPP, 5)
target:addMod(dsp.mod.FOOD_MP_CAP, 150)
target:addMod(dsp.mod.DEX, 4)
target:addMod(dsp.mod.ACC, 3)
target:addMod(dsp.mod.FOOD_RACCP, 6)
target:addMod(dsp.mod.FOOD_RACC_CAP, 20)
target:addMod(dsp.mod.HPHEAL, 9)
target:addMod(dsp.mod.MPHEAL, 2)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.FOOD_MPP, 5)
target:delMod(dsp.mod.FOOD_MP_CAP, 150)
target:delMod(dsp.mod.DEX, 4)
target:delMod(dsp.mod.ACC, 3)
target:delMod(dsp.mod.FOOD_RACCP, 6)
target:delMod(dsp.mod.FOOD_RACC_CAP, 20)
target:delMod(dsp.mod.HPHEAL, 9)
target:delMod(dsp.mod.MPHEAL, 2)
end
| gpl-3.0 |
ibm2431/darkstar | scripts/globals/spells/bluemagic/corrosive_ooze.lua | 12 | 1952 | -----------------------------------------
-- Spell: Corrosive Ooze
-- Deals water damage to an enemy. Additional Effect: Attack Down and Defense Down
-- Spell cost: 55 MP
-- Monster Type: Amorphs
-- Spell Type: Magical (Water)
-- Blue Magic Points: 4
-- Stat Bonus: HP-10 MP+10
-- Level: 66
-- Casting Time: 5 seconds
-- Recast Time: 30 seconds
--
-- Combos: Clear Mind
-----------------------------------------
require("scripts/globals/bluemagic")
require("scripts/globals/status")
require("scripts/globals/magic")
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
local params = {}
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
local multi = 2.125
if (caster:hasStatusEffect(dsp.effect.AZURE_LORE)) then
multi = multi + 0.50
end
params.multiplier = multi
params.tMultiplier = 2.0
params.duppercap = 69
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.0
params.chr_wsc = 0.0
damage = BlueMagicalSpell(caster, target, spell, params, INT_BASED)
damage = BlueFinalAdjustments(caster, target, spell, damage, params)
local params = {}
params.diff = caster:getStat(dsp.mod.INT) - target:getStat(dsp.mod.INT)
params.attribute = dsp.mod.INT
params.skillType = dsp.skill.BLUE_MAGIC
params.bonus = 1.0
local resist = applyResistance(caster, target, spell, params)
local typeEffectOne = dsp.effect.DEFENSE_DOWN
local typeEffectTwo = dsp.effect.ATTACK_DOWN
local duration = 60
if (damage > 0 and resist > 0.3) then
target:addStatusEffect(typeEffectOne,5,0,duration)
target:addStatusEffect(typeEffectTwo,5,0,duration)
end
return damage
end | gpl-3.0 |
ibm2431/darkstar | scripts/zones/Wajaom_Woodlands/IDs.lua | 9 | 3174 | -----------------------------------
-- Area: Wajaom_Woodlands
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.WAJAOM_WOODLANDS] =
{
text =
{
NOTHING_HAPPENS = 119, -- Nothing happens...
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
FISHING_MESSAGE_OFFSET = 7049, -- You can't fish here.
DIG_THROW_AWAY = 7062, -- You dig up <item>, but your inventory is full. You regretfully throw the <item> away.
FIND_NOTHING = 7064, -- You dig and you dig, but find nothing.
PLACE_HYDROGAUGE = 7342, -- You set the <item> in the glowing trench.
ENIGMATIC_LIGHT = 7343, -- The <item> is giving off an enigmatic light.
LEYPOINT = 7398, -- An eerie red glow emanates from this stone platform. The surrounding air feels alive with energy...
HARVESTING_IS_POSSIBLE_HERE = 7406, -- Harvesting is possible here if you have <item>.
HEAVY_FRAGRANCE = 8485, -- The heady fragrance of wine pervades the air...
INSECT_WINGS = 8487, -- Broken shards of insect wing are scattered all over...
PAMAMA_PEELS = 8489, -- Piles of pamama peels litter the ground...
BROKEN_SHARDS = 8492, -- Broken shards of insect wing are scattered all over...
DRAWS_NEAR = 8515, -- Something draws near!
COMMON_SENSE_SURVIVAL = 9633, -- It appears that you have arrived at a new survival guide provided by the Adventurers' Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world.
},
mob =
{
JADED_JODY_PH =
{
[16986376] = 16986378, -- -560 -8 -360
[16986390] = 16986378, -- -565 -7 -324
},
ZORAAL_JA_S_PKUUCHA_PH =
{
[16986191] = 16986197, -- 181.000 -18.000 -63.000
[16986192] = 16986197, -- 181.000 -19.000 -77.000
[16986193] = 16986197, -- 195.000 -18.000 -95.000
[16986194] = 16986197, -- 220.000 -19.000 -80.000
[16986195] = 16986197, -- 219.000 -18.000 -59.000
[16986196] = 16986197, -- 203.000 -16.000 -74.000
},
ZORAAL_JA_S_PKUUCHA = 16986197,
PERCIPIENT_ZORAAL_JA = 16986198,
VULPANGUE = 16986428,
IRIZ_IMA = 16986429,
GOTOH_ZHA_THE_REDOLENT = 16986430,
TINNIN = 16986431,
},
npc =
{
HARVESTING =
{
16986725,
16986726,
16986727,
16986728,
16986729,
16986730,
},
},
}
return zones[dsp.zone.WAJAOM_WOODLANDS] | gpl-3.0 |
greasydeal/darkstar | scripts/zones/Qulun_Dome/TextIDs.lua | 4 | 1409 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6383; -- Obtained: <item>
GIL_OBTAINED = 6384; -- Obtained <number> gil
KEYITEM_OBTAINED = 6386; -- Obtained key item: <keyitem>
-- Other Dialog
NOTHING_OUT_OF_ORDINARY = 6397; -- There is nothing out of the ordinary here.
YOU_FIND_NOTHING = 7241; -- You find nothing.
IT_SEEMS_TO_BE_LOCKED_BY_POWERFUL_MAGIC = 7197; -- A door... It seems to be locked by powerful magic.
THE_3_ITEMS_GLOW_FAINTLY = 7198; -- glow faintly
THE_MAGICITE_GLOWS_OMINOUSLY = 7240; -- The magicite glows ominously.
CANNOT_BE_OPENED_FROM_THIS_SIDE = 7202; -- It cannot be opened from this side!
DIAMOND_QUADAV_ENGAGE = 7242; -- Gwa-ha-ha, puny peoples! Ou-ur king never forge-ets a gru-udge. He'll gri-ind you into pa-aste!
DIAMOND_QUADAV_DEATH = 7243; -- Glo-ory to the Adamantking!
QUADAV_KING_ENGAGE = 7244; -- Childre-en of Altana? I will ba-athe in your blood as I did at the Ba-attle of Jeuno!
QUADAV_KING_DEATH = 7245; -- I a-am fini-ished. Hear me, wa-arriors of the Quadav! The throne of the Adamantking and the line of Za'Dha pa-asses to my bro-other...
-- conquest Base
CONQUEST_BASE = 7038; -- Tallying conquest results...
| gpl-3.0 |
naclander/tome | game/modules/tome/data/timed_effects/mental.lua | 1 | 122471 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
local Stats = require "engine.interface.ActorStats"
local Particles = require "engine.Particles"
local Entity = require "engine.Entity"
local Chat = require "engine.Chat"
local Map = require "engine.Map"
local Level = require "engine.Level"
local Astar = require "engine.Astar"
newEffect{
name = "SILENCED", image = "effects/silenced.png",
desc = "Silenced",
long_desc = function(self, eff) return "The target is silenced, preventing it from casting spells and using some vocal talents." end,
type = "mental",
subtype = { silence=true },
status = "detrimental",
parameters = {},
on_gain = function(self, err) return "#Target# is silenced!", "+Silenced" end,
on_lose = function(self, err) return "#Target# is not silenced anymore.", "-Silenced" end,
activate = function(self, eff)
eff.tmpid = self:addTemporaryValue("silence", 1)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("silence", eff.tmpid)
end,
}
newEffect{
name = "SUMMON_CONTROL", image = "talents/summon_control.png",
desc = "Summon Control",
long_desc = function(self, eff) return ("Reduces damage received by %d%% and increases summon time by %d."):format(eff.res, eff.incdur) end,
type = "mental",
subtype = { focus=true },
status = "beneficial",
parameters = { res=10, incdur=10 },
activate = function(self, eff)
eff.resid = self:addTemporaryValue("resists", {all=eff.res})
eff.durid = self:addTemporaryValue("summon_time", eff.incdur)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("resists", eff.resid)
self:removeTemporaryValue("summon_time", eff.durid)
end,
on_timeout = function(self, eff)
eff.dur = self.summon_time
end,
}
newEffect{
name = "CONFUSED", image = "effects/confused.png",
desc = "Confused",
long_desc = function(self, eff) return ("The target is confused, acting randomly (chance %d%%) and unable to perform complex actions."):format(eff.power) end,
type = "mental",
subtype = { confusion=true },
status = "detrimental",
parameters = { power=50 },
on_gain = function(self, err) return "#Target# wanders around!.", "+Confused" end,
on_lose = function(self, err) return "#Target# seems more focused.", "-Confused" end,
activate = function(self, eff)
eff.power = math.floor(math.max(eff.power - (self:attr("confusion_immune") or 0) * 100, 10))
eff.power = util.bound(eff.power, 0, 50)
eff.tmpid = self:addTemporaryValue("confused", eff.power)
if eff.power <= 0 then eff.dur = 0 end
end,
deactivate = function(self, eff)
self:removeTemporaryValue("confused", eff.tmpid)
if self == game.player and self.updateMainShader then self:updateMainShader() end
end,
}
newEffect{
name = "DOMINANT_WILL", image = "talents/yeek_will.png",
desc = "Mental Domination",
long_desc = function(self, eff) return ("The target's mind has been shattered. Its body remains as a thrall to %s."):format(eff.src.name:capitalize()) end,
type = "mental",
subtype = { dominate=true },
status = "detrimental",
parameters = { },
on_gain = function(self, err) return "#Target#'s mind is shattered." end,
activate = function(self, eff)
eff.pid = self:addTemporaryValue("inc_damage", {all=-15})
self.ai_state = self.ai_state or {}
eff.oldstate = {
faction = self.faction,
ai_state = table.clone(self.ai_state, true),
remove_from_party_on_death = self.remove_from_party_on_death,
no_inventory_access = self.no_inventory_access,
move_others = self.move_others,
summoner = self.summoner,
summoner_gain_exp = self.summoner_gain_exp,
ai = self.ai,
}
self.faction = eff.src.faction
self.ai_state.tactic_leash = 100
self.remove_from_party_on_death = true
self.no_inventory_access = true
self.move_others = true
self.summoner = eff.src
self.summoner_gain_exp = true
if self.dead then return end
game.party:addMember(self, {
control="full",
type="thrall",
title="Thrall",
orders = {leash=true, follow=true},
on_control = function(self)
self:hotkeyAutoTalents()
end,
leave_level = function(self, party_def) -- Cancel control and restore previous actor status.
local eff = self:hasEffect(self.EFF_DOMINANT_WILL)
local uid = self.uid
eff.survive_domination = true
self:removeTemporaryValue("inc_damage", eff.pid)
game.party:removeMember(self)
self:replaceWith(require("mod.class.NPC").new(self))
self.uid = uid
__uids[uid] = self
self.faction = eff.oldstate.faction
self.ai_state = eff.oldstate.ai_state
self.ai = eff.oldstate.ai
self.remove_from_party_on_death = eff.oldstate.remove_from_party_on_death
self.no_inventory_access = eff.oldstate.no_inventory_access
self.move_others = eff.oldstate.move_others
self.summoner = eff.oldstate.summoner
self.summoner_gain_exp = eff.oldstate.summoner_gain_exp
self:removeEffect(self.EFF_DOMINANT_WILL)
end,
})
end,
deactivate = function(self, eff)
if eff.survive_domination then
game.logSeen(self, "%s's mind recovers from the domination.",self.name:capitalize())
else
game.logSeen(self, "%s collapses.",self.name:capitalize())
self:die(eff.src)
end
end,
}
newEffect{
name = "BATTLE_SHOUT", image = "talents/battle_shout.png",
desc = "Battle Shout",
long_desc = function(self, eff) return ("Increases maximum life and stamina by %d%%. When the effect ends, the extra life and stamina will be lost."):format(eff.power) end,
type = "mental",
subtype = { morale=true },
status = "beneficial",
parameters = { power=10 },
activate = function(self, eff)
local lifeb = self.max_life * eff.power/100
local stamb = self.max_stamina * eff.power/100
eff.max_lifeID = self:addTemporaryValue("max_life", lifeb) --Avoid healing effects
eff.lifeID = self:addTemporaryValue("life",lifeb)
eff.max_stamina = self:addTemporaryValue("max_stamina", stamb)
self:incStamina(stamb)
eff.stamina = stamb
end,
deactivate = function(self, eff)
self:removeTemporaryValue("life", eff.lifeID)
self:removeTemporaryValue("max_life", eff.max_lifeID)
self:removeTemporaryValue("max_stamina", eff.max_stamina)
self:incStamina(-eff.stamina)
end,
}
newEffect{
name = "BATTLE_CRY", image = "talents/battle_cry.png",
desc = "Battle Cry",
long_desc = function(self, eff) return ("The target's will to defend itself is shattered by the powerful battle cry, reducing defense by %d."):format(eff.power) end,
type = "mental",
subtype = { morale=true },
status = "detrimental",
parameters = { power=10 },
on_gain = function(self, err) return "#Target#'s will is shattered.", "+Battle Cry" end,
on_lose = function(self, err) return "#Target# regains some of its will.", "-Battle Cry" end,
activate = function(self, eff)
eff.tmpid = self:addTemporaryValue("combat_def", -eff.power)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("combat_def", eff.tmpid)
end,
}
newEffect{
name = "WILLFUL_COMBAT", image = "talents/willful_combat.png",
desc = "Willful Combat",
long_desc = function(self, eff) return ("The target puts all its willpower into its blows, improving physical power by %d."):format(eff.power) end,
type = "mental",
subtype = { focus=true },
status = "beneficial",
parameters = { power=10 },
on_gain = function(self, err) return "#Target# lashes out with pure willpower." end,
on_lose = function(self, err) return "#Target#'s willpower rush ends." end,
activate = function(self, eff)
eff.tmpid = self:addTemporaryValue("combat_dam", eff.power)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("combat_dam", eff.tmpid)
end,
}
newEffect{
name = "GLOOM_WEAKNESS", image = "effects/gloom_weakness.png",
desc = "Gloom Weakness",
long_desc = function(self, eff) return ("The gloom reduces damage the target inflicts by %d%%."):format(-eff.incDamageChange) end,
type = "mental",
subtype = { gloom=true },
status = "detrimental",
parameters = { atk=10, dam=10 },
on_gain = function(self, err) return "#F53CBE##Target# is weakened by the gloom." end,
on_lose = function(self, err) return "#F53CBE##Target# is no longer weakened." end,
activate = function(self, eff)
eff.particle = self:addParticles(Particles.new("gloom_weakness", 1))
eff.incDamageId = self:addTemporaryValue("inc_damage", {all = eff.incDamageChange})
end,
deactivate = function(self, eff)
self:removeParticles(eff.particle)
self:removeTemporaryValue("inc_damage", eff.incDamageId)
end,
}
newEffect{
name = "GLOOM_SLOW", image = "effects/gloom_slow.png",
desc = "Slowed by the gloom",
long_desc = function(self, eff) return ("The gloom reduces the target's global speed by %d%%."):format(eff.power * 100) end,
type = "mental",
subtype = { gloom=true, slow=true },
status = "detrimental",
parameters = { power=0.1 },
on_gain = function(self, err) return "#F53CBE##Target# moves reluctantly!", "+Slow" end,
on_lose = function(self, err) return "#Target# overcomes the gloom.", "-Slow" end,
activate = function(self, eff)
eff.particle = self:addParticles(Particles.new("gloom_slow", 1))
eff.tmpid = self:addTemporaryValue("global_speed_add", -eff.power)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("global_speed_add", eff.tmpid)
self:removeParticles(eff.particle)
end,
}
newEffect{
name = "GLOOM_STUNNED", image = "effects/gloom_stunned.png",
desc = "Stunned by the gloom",
long_desc = function(self, eff) return ("The gloom has stunned the target, reducing damage by 70%%, putting random talents on cooldown and reducing movement speed by 50%%. While stunned talents do not cooldown."):format() end,
type = "mental",
subtype = { gloom=true, stun=true },
status = "detrimental",
parameters = {},
on_gain = function(self, err) return "#F53CBE##Target# is stunned with fear!", "+Stunned" end,
on_lose = function(self, err) return "#Target# overcomes the gloom", "-Stunned" end,
activate = function(self, eff)
eff.particle = self:addParticles(Particles.new("gloom_stunned", 1))
eff.tmpid = self:addTemporaryValue("stunned", 1)
eff.tcdid = self:addTemporaryValue("no_talents_cooldown", 1)
eff.speedid = self:addTemporaryValue("movement_speed", -0.5)
local tids = {}
for tid, lev in pairs(self.talents) do
local t = self:getTalentFromId(tid)
if t and not self.talents_cd[tid] and t.mode == "activated" and not t.innate and util.getval(t.no_energy, self, t) ~= true then tids[#tids+1] = t end
end
for i = 1, 4 do
local t = rng.tableRemove(tids)
if not t then break end
self.talents_cd[t.id] = 1 -- Just set cooldown to 1 since cooldown does not decrease while stunned
end
end,
deactivate = function(self, eff)
self:removeParticles(eff.particle)
self:removeTemporaryValue("stunned", eff.tmpid)
self:removeTemporaryValue("no_talents_cooldown", eff.tcdid)
self:removeTemporaryValue("movement_speed", eff.speedid)
end,
}
newEffect{
name = "GLOOM_CONFUSED", image = "effects/gloom_confused.png",
desc = "Confused by the gloom",
long_desc = function(self, eff) return ("The gloom has confused the target, making it act randomly (%d%% chance) and unable to perform complex actions."):format(eff.power) end,
type = "mental",
subtype = { gloom=true, confusion=true },
status = "detrimental",
parameters = { power = 10 },
on_gain = function(self, err) return "#F53CBE##Target# is lost in despair!", "+Confused" end,
on_lose = function(self, err) return "#Target# overcomes the gloom", "-Confused" end,
activate = function(self, eff)
eff.particle = self:addParticles(Particles.new("gloom_confused", 1))
eff.power = math.floor(math.max(eff.power - (self:attr("confusion_immune") or 0) * 100, 10))
eff.power = util.bound(eff.power, 0, 50)
eff.tmpid = self:addTemporaryValue("confused", eff.power)
if eff.power <= 0 then eff.dur = 0 end
end,
deactivate = function(self, eff)
self:removeParticles(eff.particle)
self:removeTemporaryValue("confused", eff.tmpid)
if self == game.player then self:updateMainShader() end
end,
}
newEffect{
name = "DISMAYED", image = "talents/dismay.png",
desc = "Dismayed",
long_desc = function(self, eff) return ("The target is dismayed. The next melee attack against the target will be a guaranteed critical hit.") end,
type = "mental",
subtype = { gloom=true, confusion=true },
status = "detrimental",
parameters = {},
on_gain = function(self, err) return "#F53CBE##Target# is dismayed!", "+Dismayed" end,
on_lose = function(self, err) return "#Target# overcomes the dismay", "-Dismayed" end,
activate = function(self, eff)
eff.particle = self:addParticles(Particles.new("dismayed", 1))
end,
deactivate = function(self, eff)
self:removeParticles(eff.particle)
end,
}
newEffect{
name = "STALKER", image = "talents/stalk.png",
desc = "Stalking",
display_desc = function(self, eff)
return ([[Stalking %d/%d +%d ]]):format(eff.target.life, eff.target.max_life, eff.bonus)
end,
long_desc = function(self, eff)
local t = self:getTalentFromId(self.T_STALK)
local effStalked = eff.target:hasEffect(eff.target.EFF_STALKED)
local desc = ([[Stalking %s. Bonus level %d: +%d attack, +%d%% melee damage, +%0.2f hate/turn prey was hit.]]):format(
eff.target.name, eff.bonus, t.getAttackChange(self, t, eff.bonus), t.getStalkedDamageMultiplier(self, t, eff.bonus) * 100 - 100, t.getHitHateChange(self, t, eff.bonus))
if effStalked and effStalked.damageChange and effStalked.damageChange > 0 then
desc = desc..("Prey damage modifier: %d%%."):format(effStalked.damageChange)
end
return desc
end,
type = "mental",
subtype = { veil=true },
status = "beneficial",
parameters = {},
activate = function(self, eff)
self:logCombat(eff.target, "#F53CBE##Target# is being stalked by #Source#!")
end,
deactivate = function(self, eff)
self:logCombat(eff.target, "#F53CBE##Target# is no longer being stalked by #Source#.")
end,
on_timeout = function(self, eff)
if not eff.target or eff.target.dead or not eff.target:hasEffect(eff.target.EFF_STALKED) then
self:removeEffect(self.EFF_STALKER)
end
end,
}
newEffect{
name = "STALKED", image = "effects/stalked.png",
desc = "Stalked",
long_desc = function(self, eff)
local effStalker = eff.src:hasEffect(eff.src.EFF_STALKER)
if not effStalker then return "Being stalked." end
local t = self:getTalentFromId(eff.src.T_STALK)
local desc = ([[Being stalked by %s. Stalker bonus level %d: +%d attack, +%d%% melee damage, +%0.2f hate/turn prey was hit.]]):format(
eff.src.name, effStalker.bonus, t.getAttackChange(eff.src, t, effStalker.bonus), t.getStalkedDamageMultiplier(eff.src, t, effStalker.bonus) * 100 - 100, t.getHitHateChange(eff.src, t, effStalker.bonus))
if eff.damageChange and eff.damageChange > 0 then
desc = desc..(" Prey damage modifier: %d%%."):format(eff.damageChange)
end
return desc
end,
type = "mental",
subtype = { veil=true },
status = "detrimental",
parameters = {},
activate = function(self, eff)
local effStalker = eff.src:hasEffect(eff.src.EFF_STALKER)
eff.particleBonus = effStalker.bonus
eff.particle = self:addParticles(Particles.new("stalked", 1, { bonus = eff.particleBonus }))
end,
deactivate = function(self, eff)
if eff.particle then self:removeParticles(eff.particle) end
if eff.damageChangeId then self:removeTemporaryValue("inc_damage", eff.damageChangeId) end
end,
on_timeout = function(self, eff)
if not eff.src or eff.src.dead or not eff.src:hasEffect(eff.src.EFF_STALKER) then
self:removeEffect(self.EFF_STALKED)
else
local effStalker = eff.src:hasEffect(eff.src.EFF_STALKER)
if eff.particleBonus ~= effStalker.bonus then
eff.particleBonus = effStalker.bonus
self:removeParticles(eff.particle)
eff.particle = self:addParticles(Particles.new("stalked", 1, { bonus = eff.particleBonus }))
end
end
end,
updateDamageChange = function(self, eff)
if eff.damageChangeId then
self:removeTemporaryValue("inc_damage", eff.damageChangeId)
eff.damageChangeId = nil
end
if eff.damageChange and eff.damageChange > 0 then
eff.damageChangeId = eff.target:addTemporaryValue("inc_damage", {all=eff.damageChange})
end
end,
}
newEffect{
name = "BECKONED", image = "talents/beckon.png",
desc = "Beckoned",
long_desc = function(self, eff)
local message = ("The target has been beckoned by %s and is heeding the call. There is a %d%% chance of moving towards the beckoner each turn."):format(eff.src.name, eff.chance)
if eff.spellpowerChangeId and eff.mindpowerChangeId then
message = message..(" (spellpower: %d, mindpower: %d"):format(eff.spellpowerChange, eff.mindpowerChange)
end
return message
end,
type = "mental",
subtype = { dominate=true },
status = "detrimental",
parameters = { speedChange=0.5 },
on_gain = function(self, err) return "#Target# has been beckoned.", "+Beckoned" end,
on_lose = function(self, err) return "#Target# is no longer beckoned.", "-Beckoned" end,
activate = function(self, eff)
eff.particle = self:addParticles(Particles.new("beckoned", 1))
eff.spellpowerChangeId = self:addTemporaryValue("combat_spellpower", eff.spellpowerChange)
eff.mindpowerChangeId = self:addTemporaryValue("combat_mindpower", eff.mindpowerChange)
end,
deactivate = function(self, eff)
if eff.particle then self:removeParticles(eff.particle) end
if eff.spellpowerChangeId then
self:removeTemporaryValue("combat_spellpower", eff.spellpowerChangeId)
eff.spellpowerChangeId = nil
end
if eff.mindpowerChangeId then
self:removeTemporaryValue("combat_mindpower", eff.mindpowerChangeId)
eff.mindpowerChangeId = nil
end
end,
on_timeout = function(self, eff)
end,
do_act = function(self, eff)
if eff.src.dead then
self:removeEffect(self.EFF_BECKONED)
return
end
if not self:enoughEnergy() then return nil end
-- apply periodic timer instead of random chance
if not eff.timer then
eff.timer = rng.float(0, 100)
end
if not self:checkHit(eff.src:combatMindpower(), self:combatMentalResist(), 0, 95, 5) then
eff.timer = eff.timer + eff.chance * 0.5
game.logSeen(self, "#F53CBE#%s struggles against the beckoning.", self.name:capitalize())
else
eff.timer = eff.timer + eff.chance
end
if eff.timer > 100 then
eff.timer = eff.timer - 100
local distance = self.x and eff.src.x and core.fov.distance(self.x, self.y, eff.src.x, eff.src.y) or 1000
if math.floor(distance) > 1 and distance <= eff.range then
-- in range but not adjacent
-- add debuffs
if not eff.spellpowerChangeId then eff.spellpowerChangeId = self:addTemporaryValue("combat_spellpower", eff.spellpowerChange) end
if not eff.mindpowerChangeId then eff.mindpowerChangeId = self:addTemporaryValue("combat_mindpower", eff.mindpowerChange) end
-- custom pull logic (adapted from move_dmap; forces movement, pushes others aside, custom particles)
if not self:attr("never_move") then
local source = eff.src
local moveX, moveY = source.x, source.y -- move in general direction by default
if not self:hasLOS(source.x, source.y) then
local a = Astar.new(game.level.map, self)
local path = a:calc(self.x, self.y, source.x, source.y)
if path then
moveX, moveY = path[1].x, path[1].y
end
end
if moveX and moveY then
local old_move_others, old_x, old_y = self.move_others, self.x, self.y
self.move_others = true
local old = rawget(self, "aiCanPass")
self.aiCanPass = mod.class.NPC.aiCanPass
mod.class.NPC.moveDirection(self, moveX, moveY, false)
self.aiCanPass = old
self.move_others = old_move_others
if old_x ~= self.x or old_y ~= self.y then
game.level.map:particleEmitter(self.x, self.y, 1, "beckoned_move", {power=power, dx=self.x - source.x, dy=self.y - source.y})
end
end
end
else
-- adjacent or out of range..remove debuffs
if eff.spellpowerChangeId then
self:removeTemporaryValue("combat_spellpower", eff.spellpowerChangeId)
eff.spellpowerChangeId = nil
end
if eff.mindpowerChangeId then
self:removeTemporaryValue("combat_mindpower", eff.mindpowerChangeId)
eff.mindpowerChangeId = nil
end
end
end
end,
do_onTakeHit = function(self, eff, dam)
eff.resistChance = (eff.resistChance or 0) + math.min(100, math.max(0, dam / self.max_life * 100))
if rng.percent(eff.resistChance) then
game.logSeen(self, "#F53CBE#%s is jolted to attention by the damage and is no longer being beckoned.", self.name:capitalize())
self:removeEffect(self.EFF_BECKONED)
end
return dam
end,
}
newEffect{
name = "OVERWHELMED", image = "talents/frenzy.png",
desc = "Overwhelmed",
long_desc = function(self, eff) return ("The target has been overwhemed by a furious assault, reducing attack by %d."):format( -eff.attackChange) end,
type = "mental",
subtype = { fear=true },
status = "detrimental",
parameters = { damageChange=0.1 },
on_gain = function(self, err) return "#Target# has been overwhelmed.", "+Overwhelmed" end,
on_lose = function(self, err) return "#Target# is no longer overwhelmed.", "-Overwhelmed" end,
activate = function(self, eff)
eff.attackChangeId = self:addTemporaryValue("combat_atk", eff.attackChange)
eff.particle = self:addParticles(Particles.new("overwhelmed", 1))
end,
deactivate = function(self, eff)
self:removeTemporaryValue("combat_atk", eff.attackChangeId)
self:removeParticles(eff.particle)
end,
}
newEffect{
name = "HARASSED", image = "talents/harass_prey.png",
desc = "Harassed",
long_desc = function(self, eff) return ("The target has been harassed by its stalker, reducing damage by %d%%."):format( -eff.damageChange * 100) end,
type = "mental",
subtype = { fear=true },
status = "detrimental",
parameters = { damageChange=0.1 },
on_gain = function(self, err) return "#Target# has been harassed.", "+Harassed" end,
on_lose = function(self, err) return "#Target# is no longer harassed.", "-Harassed" end,
activate = function(self, eff)
eff.damageChangeId = self:addTemporaryValue("inc_damage", {all=eff.damageChange})
eff.particle = self:addParticles(Particles.new("harassed", 1))
end,
deactivate = function(self, eff)
self:removeTemporaryValue("inc_damage", eff.damageChangeId)
self:removeParticles(eff.particle)
end,
}
newEffect{
name = "DOMINATED", image = "talents/dominate.png",
desc = "Dominated",
long_desc = function(self, eff) return ("The target has been dominated. It is unable to move and has lost %d armor and %d defense. Attacks from %s gain %d%% damage penetration."):format(-eff.armorChange, -eff.defenseChange, eff.src.name:capitalize(), eff.resistPenetration) end,
type = "mental",
subtype = { dominate=true },
status = "detrimental",
on_gain = function(self, err) return "#F53CBE##Target# has been dominated!", "+Dominated" end,
on_lose = function(self, err) return "#F53CBE##Target# is no longer dominated.", "-Dominated" end,
parameters = { armorChange = -3, defenseChange = -3, physicalResistChange = -0.1 },
activate = function(self, eff)
eff.neverMoveId = self:addTemporaryValue("never_move", 1)
eff.armorId = self:addTemporaryValue("combat_armor", eff.armorChange)
eff.defenseId = self:addTemporaryValue("combat_def", eff.armorChange)
eff.particle = self:addParticles(Particles.new("dominated", 1))
end,
deactivate = function(self, eff)
self:removeTemporaryValue("never_move", eff.neverMoveId)
self:removeTemporaryValue("combat_armor", eff.armorId)
self:removeTemporaryValue("combat_def", eff.defenseId)
self:removeParticles(eff.particle)
end,
}
newEffect{
name = "FEED", image = "talents/feed.png",
desc = "Feeding",
long_desc = function(self, eff) return ("%s is feeding from %s."):format(self.name:capitalize(), eff.target.name) end,
type = "mental",
subtype = { psychic_drain=true },
status = "beneficial",
parameters = { },
activate = function(self, eff)
eff.src = self
-- hate
if eff.hateGain and eff.hateGain > 0 then
eff.hateGainId = self:addTemporaryValue("hate_regen", eff.hateGain)
end
-- health
if eff.constitutionGain and eff.constitutionGain > 0 then
eff.constitutionGainId = self:addTemporaryValue("inc_stats", { [Stats.STAT_CON] = eff.constitutionGain })
end
if eff.lifeRegenGain and eff.lifeRegenGain > 0 then
eff.lifeRegenGainId = self:addTemporaryValue("life_regen", eff.lifeRegenGain)
end
-- power
if eff.damageGain and eff.damageGain > 0 then
eff.damageGainId = self:addTemporaryValue("inc_damage", {all=eff.damageGain})
end
-- strengths
if eff.resistGain and eff.resistGain > 0 then
local gainList = {}
for id, resist in pairs(eff.target.resists) do
if resist > 0 and id ~= "all" then
gainList[id] = eff.resistGain * 0.01 * resist
end
end
eff.resistGainId = self:addTemporaryValue("resists", gainList)
end
eff.target:setEffect(eff.target.EFF_FED_UPON, eff.dur, { src = eff.src, target = eff.target, constitutionLoss = -eff.constitutionGain, lifeRegenLoss = -eff.lifeRegenGain, damageLoss = -eff.damageGain, resistLoss = -eff.resistGain })
end,
deactivate = function(self, eff)
-- hate
if eff.hateGainId then self:removeTemporaryValue("hate_regen", eff.hateGainId) end
-- health
if eff.constitutionGainId then self:removeTemporaryValue("inc_stats", eff.constitutionGainId) end
if eff.lifeRegenGainId then self:removeTemporaryValue("life_regen", eff.lifeRegenGainId) end
-- power
if eff.damageGainId then self:removeTemporaryValue("inc_damage", eff.damageGainId) end
-- strengths
if eff.resistGainId then self:removeTemporaryValue("resists", eff.resistGainId) end
if eff.particles then
-- remove old particle emitter
game.level.map:removeParticleEmitter(eff.particles)
eff.particles = nil
end
eff.target:removeEffect(eff.target.EFF_FED_UPON, false, true)
end,
updateFeed = function(self, eff)
local source = eff.src
local target = eff.target
if source.dead or target.dead or not game.level:hasEntity(source) or not game.level:hasEntity(target) or not source:hasLOS(target.x, target.y) or core.fov.distance(self.x, self.y, target.x, target.y) > (eff.range or 10) then
source:removeEffect(source.EFF_FEED)
if eff.particles then
game.level.map:removeParticleEmitter(eff.particles)
eff.particles = nil
end
return
end
-- update particles position
if not eff.particles or eff.particles.x ~= source.x or eff.particles.y ~= source.y or eff.particles.tx ~= target.x or eff.particles.ty ~= target.y then
if eff.particles then
game.level.map:removeParticleEmitter(eff.particles)
end
-- add updated particle emitter
local dx, dy = target.x - source.x, target.y - source.y
eff.particles = Particles.new("feed_hate", math.max(math.abs(dx), math.abs(dy)), { tx=dx, ty=dy })
eff.particles.x = source.x
eff.particles.y = source.y
eff.particles.tx = target.x
eff.particles.ty = target.y
game.level.map:addParticleEmitter(eff.particles)
end
end
}
newEffect{
name = "FED_UPON", image = "effects/fed_upon.png",
desc = "Fed Upon",
long_desc = function(self, eff) return ("%s is fed upon by %s."):format(self.name:capitalize(), eff.src.name) end,
type = "mental",
subtype = { psychic_drain=true },
status = "detrimental",
remove_on_clone = true,
no_remove = true,
parameters = { },
activate = function(self, eff)
-- health
if eff.constitutionLoss and eff.constitutionLoss < 0 then
eff.constitutionLossId = self:addTemporaryValue("inc_stats", { [Stats.STAT_CON] = eff.constitutionLoss })
end
if eff.lifeRegenLoss and eff.lifeRegenLoss < 0 then
eff.lifeRegenLossId = self:addTemporaryValue("life_regen", eff.lifeRegenLoss)
end
-- power
if eff.damageLoss and eff.damageLoss < 0 then
eff.damageLossId = self:addTemporaryValue("inc_damage", {all=eff.damageLoss})
end
-- strengths
if eff.resistLoss and eff.resistLoss < 0 then
local lossList = {}
for id, resist in pairs(self.resists) do
if resist > 0 and id ~= "all" then
lossList[id] = eff.resistLoss * 0.01 * resist
end
end
eff.resistLossId = self:addTemporaryValue("resists", lossList)
end
end,
deactivate = function(self, eff)
-- health
if eff.constitutionLossId then self:removeTemporaryValue("inc_stats", eff.constitutionLossId) end
if eff.lifeRegenLossId then self:removeTemporaryValue("life_regen", eff.lifeRegenLossId) end
-- power
if eff.damageLossId then self:removeTemporaryValue("inc_damage", eff.damageLossId) end
-- strengths
if eff.resistLossId then self:removeTemporaryValue("resists", eff.resistLossId) end
if eff.target == self and eff.src:hasEffect(eff.src.EFF_FEED) then
eff.src:removeEffect(eff.src.EFF_FEED)
end
end,
on_timeout = function(self, eff)
-- no_remove prevents targets from dispelling feeding, make sure this gets removed if something goes wrong
if eff.dur <= 0 or eff.src.dead then
self:removeEffect(eff.src.EFF_FED_UPON, false, true)
end
end,
}
newEffect{
name = "AGONY", image = "talents/agony.png",
desc = "Agony",
long_desc = function(self, eff) return ("%s is writhing in agony, suffering from %d to %d damage over %d turns."):format(self.name:capitalize(), eff.damage / eff.duration, eff.damage, eff.duration) end,
type = "mental",
subtype = { pain=true, psionic=true },
status = "detrimental",
parameters = { damage=10, mindpower=10, range=10, minPercent=10 },
on_gain = function(self, err) return "#Target# is writhing in agony!", "+Agony" end,
on_lose = function(self, err) return "#Target# is no longer writhing in agony.", "-Agony" end,
activate = function(self, eff)
eff.power = 0
end,
deactivate = function(self, eff)
if eff.particle then self:removeParticles(eff.particle) end
end,
on_timeout = function(self, eff)
eff.turn = (eff.turn or 0) + 1
local damage = math.floor(eff.damage * (eff.turn / eff.duration))
if damage > 0 then
DamageType:get(DamageType.MIND).projector(eff.src, self.x, self.y, DamageType.MIND, { dam=damage, crossTierChance=25 })
game:playSoundNear(self, "talents/fire")
end
if self.dead then
if eff.particle then self:removeParticles(eff.particle) end
return
end
if eff.particle then self:removeParticles(eff.particle) end
eff.particle = nil
eff.particle = self:addParticles(Particles.new("agony", 1, { power = 10 * eff.turn / eff.duration }))
end,
}
newEffect{
name = "HATEFUL_WHISPER", image = "talents/hateful_whisper.png",
desc = "Hateful Whisper",
long_desc = function(self, eff) return ("%s has heard the hateful whisper."):format(self.name:capitalize()) end,
type = "mental",
subtype = { madness=true, psionic=true },
status = "detrimental",
parameters = { },
on_gain = function(self, err) return "#Target# has heard the hateful whisper!", "+Hateful Whisper" end,
on_lose = function(self, err) return "#Target# no longer hears the hateful whisper.", "-Hateful Whisper" end,
activate = function(self, eff)
if not eff.src.dead and eff.src:knowTalent(eff.src.T_HATE_POOL) then
eff.src:incHate(eff.hateGain)
end
DamageType:get(DamageType.MIND).projector(eff.src, self.x, self.y, DamageType.MIND, { dam=eff.damage, crossTierChance=25 })
if self.dead then
-- only spread on activate if the target is dead
if eff.jumpCount > 0 then
eff.jumpCount = eff.jumpCount - 1
self.tempeffect_def[self.EFF_HATEFUL_WHISPER].doSpread(self, eff)
end
else
eff.particle = self:addParticles(Particles.new("hateful_whisper", 1, { }))
end
game:playSoundNear(self, "talents/fire")
eff.firstTurn = true
end,
deactivate = function(self, eff)
if eff.particle then self:removeParticles(eff.particle) end
end,
on_timeout = function(self, eff)
if self.dead then return false end
if eff.firstTurn then
-- pause a turn before infecting others
eff.firstTurn = false
elseif eff.jumpDuration > 0 then
-- limit the total duration of all spawned effects
eff.jumpDuration = eff.jumpDuration - 1
if eff.jumpCount > 0 then
-- guaranteed jump
eff.jumpCount = eff.jumpCount - 1
self.tempeffect_def[self.EFF_HATEFUL_WHISPER].doSpread(self, eff)
elseif rng.percent(eff.jumpChance) then
-- per turn chance of a jump
self.tempeffect_def[self.EFF_HATEFUL_WHISPER].doSpread(self, eff)
end
end
end,
doSpread = function(self, eff)
local targets = {}
local grids = core.fov.circle_grids(self.x, self.y, eff.jumpRange, true)
for x, yy in pairs(grids) do
for y, _ in pairs(grids[x]) do
local a = game.level.map(x, y, game.level.map.ACTOR)
if a and eff.src:reactionToward(a) < 0 and self:hasLOS(a.x, a.y) then
if not a:hasEffect(a.EFF_HATEFUL_WHISPER) then
targets[#targets+1] = a
end
end
end
end
if #targets > 0 then
local target = rng.table(targets)
target:setEffect(target.EFF_HATEFUL_WHISPER, eff.duration, {
src = eff.src,
duration = eff.duration,
damage = eff.damage,
mindpower = eff.mindpower,
jumpRange = eff.jumpRange,
jumpCount = 0, -- secondary effects do not get automatic spreads
jumpChance = eff.jumpChance,
jumpDuration = eff.jumpDuration,
hateGain = eff.hateGain
})
game.level.map:particleEmitter(target.x, target.y, 1, "reproach", { dx = self.x - target.x, dy = self.y - target.y })
end
end,
}
newEffect{
name = "MADNESS_SLOW", image = "effects/madness_slowed.png",
desc = "Slowed by madness",
long_desc = function(self, eff) return ("Madness reduces the target's global speed by %d%% and lowers mind resistance by %d%%."):format(eff.power * 100, -eff.mindResistChange) end,
type = "mental",
subtype = { madness=true, slow=true },
status = "detrimental",
parameters = { power=0.1 },
on_gain = function(self, err) return "#F53CBE##Target# slows in the grip of madness!", "+Slow" end,
on_lose = function(self, err) return "#Target# overcomes the madness.", "-Slow" end,
activate = function(self, eff)
eff.particle = self:addParticles(Particles.new("gloom_slow", 1))
eff.mindResistChangeId = self:addTemporaryValue("resists", { [DamageType.MIND]=eff.mindResistChange })
eff.tmpid = self:addTemporaryValue("global_speed_add", -eff.power)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("resists", eff.mindResistChangeId)
self:removeTemporaryValue("global_speed_add", eff.tmpid)
self:removeParticles(eff.particle)
end,
}
newEffect{
name = "MADNESS_STUNNED", image = "effects/madness_stunned.png",
desc = "Stunned by madness",
long_desc = function(self, eff) return ("Madness has stunned the target, reducing damage by 70%%, lowering mind resistance by %d%%, putting random talents on cooldown and reducing movement speed by 50%%. While stunned talents do not cooldown."):format(eff.mindResistChange) end,
type = "mental",
subtype = { madness=true, stun=true },
status = "detrimental",
parameters = {mindResistChange = -10},
on_gain = function(self, err) return "#F53CBE##Target# is stunned by madness!", "+Stunned" end,
on_lose = function(self, err) return "#Target# overcomes the madness", "-Stunned" end,
activate = function(self, eff)
eff.particle = self:addParticles(Particles.new("gloom_stunned", 1))
eff.mindResistChangeId = self:addTemporaryValue("resists", { [DamageType.MIND]=eff.mindResistChange })
eff.tmpid = self:addTemporaryValue("stunned", 1)
eff.tcdid = self:addTemporaryValue("no_talents_cooldown", 1)
eff.speedid = self:addTemporaryValue("movement_speed", -0.5)
local tids = {}
for tid, lev in pairs(self.talents) do
local t = self:getTalentFromId(tid)
if t and not self.talents_cd[tid] and t.mode == "activated" and not t.innate then tids[#tids+1] = t end
end
for i = 1, 4 do
local t = rng.tableRemove(tids)
if not t then break end
self.talents_cd[t.id] = 1 -- Just set cooldown to 1 since cooldown does not decrease while stunned
end
end,
deactivate = function(self, eff)
self:removeParticles(eff.particle)
self:removeTemporaryValue("resists", eff.mindResistChangeId)
self:removeTemporaryValue("stunned", eff.tmpid)
self:removeTemporaryValue("no_talents_cooldown", eff.tcdid)
self:removeTemporaryValue("movement_speed", eff.speedid)
end,
}
newEffect{
name = "MADNESS_CONFUSED", image = "effects/madness_confused.png",
desc = "Confused by madness",
long_desc = function(self, eff) return ("Madness has confused the target, lowering mind resistance by %d%% and making it act randomly (%d%% chance) and unable to perform complex actions."):format(eff.mindResistChange, eff.power) end,
type = "mental",
subtype = { madness=true, confusion=true },
status = "detrimental",
parameters = { power=10 },
on_gain = function(self, err) return "#F53CBE##Target# is lost in madness!", "+Confused" end,
on_lose = function(self, err) return "#Target# overcomes the madness", "-Confused" end,
activate = function(self, eff)
eff.particle = self:addParticles(Particles.new("gloom_confused", 1))
eff.mindResistChangeId = self:addTemporaryValue("resists", { [DamageType.MIND]=eff.mindResistChange })
eff.power = math.floor(math.max(eff.power - (self:attr("confusion_immune") or 0) * 100, 10))
eff.power = util.bound(eff.power, 0, 50)
eff.tmpid = self:addTemporaryValue("confused", eff.power)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("resists", eff.mindResistChangeId)
self:removeParticles(eff.particle)
self:removeTemporaryValue("confused", eff.tmpid)
if self == game.player and self.updateMainShader then self:updateMainShader() end
end,
}
newEffect{
name = "MALIGNED", image = "talents/getsture_of_malice.png",
desc = "Maligned",
long_desc = function(self, eff) return ("The target is under a malign influence. All resists have been lowered by %d%%."):format(-eff.resistAllChange) end,
type = "mental",
subtype = { curse=true },
status = "detrimental",
parameters = {},
on_gain = function(self, err) return "#F53CBE##Target# has been maligned!", "+Maligned" end,
on_lose = function(self, err) return "#Target# is no longer maligned", "-Maligned" end,
activate = function(self, eff)
eff.particle = self:addParticles(Particles.new("maligned", 1))
eff.resistAllChangeId = self:addTemporaryValue("resists", { all=eff.resistAllChange })
end,
deactivate = function(self, eff)
self:removeTemporaryValue("resists", eff.resistAllChangeId)
self:removeParticles(eff.particle)
end,
on_merge = function(self, old_eff, new_eff)
old_eff.dur = new_eff.dur
return old_eff
end,
}
local function updateFearParticles(self)
local hasParticles = false
if self:hasEffect(self.EFF_PARANOID) then hasParticles = true end
if self:hasEffect(self.EFF_DISPAIR) then hasParticles = true end
if self:hasEffect(self.EFF_TERRIFIED) then hasParticles = true end
if self:hasEffect(self.EFF_DISTRESSED) then hasParticles = true end
if self:hasEffect(self.EFF_HAUNTED) then hasParticles = true end
if self:hasEffect(self.EFF_TORMENTED) then hasParticles = true end
if not self.fearParticlesId and hasParticles then
self.fearParticlesId = self:addParticles(Particles.new("fear_blue", 1))
elseif self.fearParticlesId and not hasParticles then
self:removeParticles(self.fearParticlesId)
self.fearParticlesId = nil
end
end
newEffect{
name = "PARANOID", image = "effects/paranoid.png",
desc = "Paranoid",
long_desc = function(self, eff) return ("Paranoia has gripped the target, causing a %d%% chance they will physically attack anyone nearby, friend or foe. Targets of the attack may become paranoid themselves."):format(eff.attackChance) end,
type = "mental",
subtype = { fear=true },
status = "detrimental",
parameters = {},
on_gain = function(self, err) return "#F53CBE##Target# becomes paranoid!", "+Paranoid" end,
on_lose = function(self, err) return "#Target# is no longer paranoid", "-Paranoid" end,
activate = function(self, eff)
updateFearParticles(self)
end,
deactivate = function(self, eff)
updateFearParticles(self)
local tInstillFear = self:getTalentFromId(self.T_INSTILL_FEAR)
tInstillFear.endEffect(self, tInstillFear)
end,
do_act = function(self, eff)
if not self:enoughEnergy() then return nil end
-- apply periodic timer instead of random chance
if not eff.timer then
eff.timer = rng.float(0, 100)
end
if not self:checkHit(eff.src:combatMindpower(), self:combatMentalResist(), 0, 95, 5) then
eff.timer = eff.timer + eff.attackChance * 0.5
game.logSeen(self, "#F53CBE#%s struggles against the paranoia.", self.name:capitalize())
else
eff.timer = eff.timer + eff.attackChance
end
if eff.timer > 100 then
eff.timer = eff.timer - 100
local start = rng.range(0, 8)
for i = start, start + 8 do
local x = self.x + (i % 3) - 1
local y = self.y + math.floor((i % 9) / 3) - 1
if (self.x ~= x or self.y ~= y) then
local target = game.level.map(x, y, Map.ACTOR)
if target then
self:logCombat(target, "#F53CBE##Source# attacks #Target# in a fit of paranoia.")
if self:attackTarget(target, nil, 1, false) and target ~= eff.src then
if not target:canBe("fear") then
game.logSeen(target, "#F53CBE#%s ignores the fear!", target.name:capitalize())
elseif not target:checkHit(eff.mindpower, target:combatMentalResist()) then
game.logSeen(target, "%s resists the fear!", target.name:capitalize())
else
target:setEffect(target.EFF_PARANOID, eff.duration, {src=eff.src, attackChance=eff.attackChance, mindpower=eff.mindpower, duration=eff.duration })
end
end
return
end
end
end
end
end,
}
newEffect{
name = "DISPAIR", image = "effects/despair.png",
desc = "Despair",
long_desc = function(self, eff) return ("The target is in despair, reducing all damage reduction by %d%%."):format(-eff.resistAllChange) end,
type = "mental",
subtype = { fear=true },
status = "detrimental",
parameters = {},
on_gain = function(self, err) return "#F53CBE##Target# is in despair!", "+Despair" end,
on_lose = function(self, err) return "#Target# is no longer in despair", "-Despair" end,
activate = function(self, eff)
eff.damageId = self:addTemporaryValue("resists", { all=eff.resistAllChange })
updateFearParticles(self)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("resists", eff.damageId)
updateFearParticles(self)
local tInstillFear = self:getTalentFromId(self.T_INSTILL_FEAR)
tInstillFear.endEffect(self, tInstillFear)
end,
}
newEffect{
name = "TERRIFIED", image = "effects/terrified.png",
desc = "Terrified",
long_desc = function(self, eff) return ("The target is terrified, causing talents and attacks to fail %d%% of the time."):format(eff.actionFailureChance) end,
type = "mental",
subtype = { fear=true },
status = "detrimental",
parameters = {},
on_gain = function(self, err) return "#F53CBE##Target# becomes terrified!", "+Terrified" end,
on_lose = function(self, err) return "#Target# is no longer terrified", "-Terrified" end,
activate = function(self, eff)
eff.terrifiedId = self:addTemporaryValue("terrified", eff.actionFailureChance)
updateFearParticles(self)
end,
deactivate = function(self, eff)
eff.terrifiedId = self:removeTemporaryValue("terrified", eff.terrifiedId)
updateFearParticles(self)
local tInstillFear = self:getTalentFromId(self.T_INSTILL_FEAR)
tInstillFear.endEffect(self, tInstillFear)
end,
}
newEffect{
name = "DISTRESSED", image = "effects/distressed.png",
desc = "Distressed",
long_desc = function(self, eff) return ("The target is distressed, reducing all saves by %d."):format(-eff.saveChange) end,
type = "mental",
subtype = { fear=true },
status = "detrimental",
parameters = {},
on_gain = function(self, err) return "#F53CBE##Target# becomes distressed!", "+Distressed" end,
on_lose = function(self, err) return "#Target# is no longer distressed", "-Distressed" end,
activate = function(self, eff)
eff.physicalId = self:addTemporaryValue("combat_physresist", eff.saveChange)
eff.mentalId = self:addTemporaryValue("combat_mentalresist", eff.saveChange)
eff.spellId = self:addTemporaryValue("combat_spellresist", eff.saveChange)
updateFearParticles(self)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("combat_physresist", eff.physicalId)
self:removeTemporaryValue("combat_mentalresist", eff.mentalId)
self:removeTemporaryValue("combat_spellresist", eff.spellId)
updateFearParticles(self)
local tInstillFear = self:getTalentFromId(self.T_INSTILL_FEAR)
tInstillFear.endEffect(self, tInstillFear)
end,
}
newEffect{
name = "HAUNTED", image = "effects/haunted.png",
desc = "Haunted",
long_desc = function(self, eff) return ("The target is haunted by a feeling of dread, causing each existing or new fear effect to inflict %d mind damage."):format(eff.damage) end,
type = "mental",
subtype = { fear=true },
status = "detrimental",
parameters = {damage=10},
on_gain = function(self, err) return "#F53CBE##Target# becomes haunted!", "+Haunted" end,
on_lose = function(self, err) return "#Target# is no longer haunted", "-Haunted" end,
activate = function(self, eff)
for e, p in pairs(self.tmp) do
def = self.tempeffect_def[e]
if def.subtype and def.subtype.fear then
if not self.dead then
game.logSeen(self, "#F53CBE#%s is struck by fear of the %s effect.", self.name:capitalize(), def.desc)
eff.src:project({type="hit", x=self.x,y=self.y}, self.x, self.y, DamageType.MIND, { dam=eff.damage,alwaysHit=true,criticals=false,crossTierChance=0 })
end
end
end
updateFearParticles(self)
end,
deactivate = function(self, eff)
updateFearParticles(self)
local tInstillFear = self:getTalentFromId(self.T_INSTILL_FEAR)
tInstillFear.endEffect(self, tInstillFear)
end,
on_setFearEffect = function(self, e)
local eff = self:hasEffect(self.EFF_HAUNTED)
game.logSeen(self, "#F53CBE#%s is struck by fear of the %s effect.", self.name:capitalize(), util.getval(e.desc, self, e))
eff.src:project({type="hit", x=self.x,y=self.y}, self.x, self.y, DamageType.MIND, { dam=eff.damage,alwaysHit=true,criticals=false,crossTierChance=0 })
end,
}
newEffect{
name = "TORMENTED", image = "effects/tormented.png",
desc = "Tormented",
long_desc = function(self, eff) return ("The target's mind is being tormented, causing %d apparitions to manifest and attack the target, inflicting %d mind damage each before disappearing."):format(eff.count, eff.damage) end,
type = "mental",
subtype = { fear=true },
status = "detrimental",
parameters = {count=1, damage=10},
on_gain = function(self, err) return "#F53CBE##Target# becomes tormented!", "+Tormented" end,
on_lose = function(self, err) return "#Target# is no longer tormented", "-Tormented" end,
activate = function(self, eff)
updateFearParticles(self)
end,
deactivate = function(self, eff)
updateFearParticles(self)
local tInstillFear = self:getTalentFromId(self.T_INSTILL_FEAR)
tInstillFear.endEffect(self, tInstillFear)
end,
npcTormentor = {
name = "tormentor",
display = "h", color=colors.DARK_GREY, image="npc/horror_eldritch_nightmare_horror.png",
blood_color = colors.BLACK,
desc = "A vision of terror that wracks the mind.",
type = "horror", subtype = "eldritch",
rank = 2,
size_category = 2,
body = { INVEN = 10 },
no_drops = true,
autolevel = "summoner",
level_range = {1, nil}, exp_worth = 0,
ai = "summoned", ai_real = "dumb_talented_simple", ai_state = { talent_in=2, ai_move="move_ghoul", },
stats = { str=10, dex=20, wil=20, con=10, cun=30 },
infravision = 10,
can_pass = {pass_wall=20},
resists = { all = 100, [DamageType.MIND]=-100 },
no_breath = 1,
fear_immune = 1,
blind_immune = 1,
infravision = 10,
see_invisible = 80,
max_life = resolvers.rngavg(50, 80),
combat_armor = 1, combat_def = 50,
combat = { dam=1 },
resolvers.talents{
},
on_act = function(self)
local target = self.ai_target.actor
if not target or target.dead then
self:die()
else
game.logSeen(self, "%s is tormented by a vision!", target.name:capitalize())
self:project({type="hit", x=target.x,y=target.y}, target.x, target.y, engine.DamageType.MIND, { dam=self.tormentedDamage,alwaysHit=true,crossTierChance=75 })
self:die()
end
end,
},
on_timeout = function(self, eff)
if eff.src.dead then return true end
-- tormentors per turn are pre-calculated in a table, but ordered, so take a random one
local count = rng.tableRemove(eff.counts)
for c = 1, count do
local start = rng.range(0, 8)
for i = start, start + 8 do
local x = self.x + (i % 3) - 1
local y = self.y + math.floor((i % 9) / 3) - 1
if game.level.map:isBound(x, y) and not game.level.map(x, y, Map.ACTOR) then
local def = self.tempeffect_def[self.EFF_TORMENTED]
local m = require("mod.class.NPC").new(def.npcTormentor)
m.faction = eff.src.faction
m.summoner = eff.src
m.summoner_gain_exp = true
m.summon_time = 3
m.tormentedDamage = eff.damage
m:resolve() m:resolve(nil, true)
m:forceLevelup(self.level)
m:setTarget(self)
game.zone:addEntity(game.level, m, "actor", x, y)
break
end
end
end
end,
}
newEffect{
name = "PANICKED", image = "talents/panic.png",
desc = "Panicked",
long_desc = function(self, eff) return ("The target has been panicked by %s, causing them to have a %d%% chance of fleeing in terror instead of acting."):format(eff.src.name, eff.chance) end,
type = "mental",
subtype = { fear=true },
status = "detrimental",
parameters = {},
on_gain = function(self, err) return "#F53CBE##Target# becomes panicked!", "+Panicked" end,
on_lose = function(self, err) return "#Target# is no longer panicked", "-Panicked" end,
activate = function(self, eff)
eff.particlesId = self:addParticles(Particles.new("fear_violet", 1))
end,
deactivate = function(self, eff)
self:removeParticles(eff.particlesId)
local tInstillFear = self:getTalentFromId(self.T_INSTILL_FEAR)
tInstillFear.endEffect(self, tInstillFear)
end,
do_act = function(self, eff)
if not self:enoughEnergy() then return nil end
if eff.src.dead then return true end
-- apply periodic timer instead of random chance
if not eff.timer then
eff.timer = rng.float(0, 100)
end
if not self:checkHit(eff.src:combatMindpower(), self:combatMentalResist(), 0, 95, 5) then
eff.timer = eff.timer + eff.chance * 0.5
game.logSeen(self, "#F53CBE#%s struggles against the panic.", self.name:capitalize())
else
eff.timer = eff.timer + eff.chance
end
if eff.timer > 100 then
eff.timer = eff.timer - 100
local distance = core.fov.distance(self.x, self.y, eff.src.x, eff.src.y)
if distance <= eff.range then
-- in range
if not self:attr("never_move") then
local sourceX, sourceY = eff.src.x, eff.src.y
local bestX, bestY
local bestDistance = 0
local start = rng.range(0, 8)
for i = start, start + 8 do
local x = self.x + (i % 3) - 1
local y = self.y + math.floor((i % 9) / 3) - 1
if x ~= self.x or y ~= self.y then
local distance = core.fov.distance(x, y, sourceX, sourceY)
if distance > bestDistance
and game.level.map:isBound(x, y)
and not game.level.map:checkAllEntities(x, y, "block_move", self)
and not game.level.map(x, y, Map.ACTOR) then
bestDistance = distance
bestX = x
bestY = y
end
end
end
if bestX then
self:move(bestX, bestY, false)
game.logPlayer(self, "#F53CBE#You panic and flee from %s.", eff.src.name)
else
self:logCombat(eff.src, "#F53CBE##Source# panics but fails to flee from #Target#.")
self:useEnergy(game.energy_to_act * self:combatMovementSpeed(bestX, bestY))
end
end
end
end
end,
}
newEffect{
name = "QUICKNESS", image = "effects/quickness.png",
desc = "Quick",
long_desc = function(self, eff) return ("Increases run speed by %d%%."):format(eff.power * 100) end,
type = "mental",
subtype = { telekinesis=true, speed=true },
status = "beneficial",
parameters = { power=0.1 },
on_gain = function(self, err) return "#Target# speeds up.", "+Quick" end,
on_lose = function(self, err) return "#Target# slows down.", "-Quick" end,
activate = function(self, eff)
eff.tmpid = self:addTemporaryValue("movement_speed", eff.power)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("movement_speed", eff.tmpid)
end,
}
newEffect{
name = "PSIFRENZY", image = "talents/frenzied_psifighting.png",
desc = "Frenzied Psi-fighting",
long_desc = function(self, eff) return ("Causes telekinetically-wielded weapons to hit up to %d targets each turn."):format(eff.power) end,
type = "mental",
subtype = { telekinesis=true, frenzy=true },
status = "beneficial",
parameters = {dam=10},
on_gain = function(self, err) return "#Target# enters a frenzy!", "+Frenzy" end,
on_lose = function(self, err) return "#Target# is no longer frenzied.", "-Frenzy" end,
}
newEffect{
name = "KINSPIKE_SHIELD", image = "talents/kinetic_shield.png",
desc = "Spiked Kinetic Shield",
long_desc = function(self, eff)
local tl = self:getTalentLevel(self.T_ABSORPTION_MASTERY)
local xs = (tl>=3 and ", nature" or "")..(tl>=6 and ", temporal" or "")
return ("The target erects a powerful kinetic shield capable of absorbing %d/%d physical%s or acid damage before it crumbles."):format(self.kinspike_shield_absorb, eff.power, xs)
end,
type = "mental",
subtype = { telekinesis=true, shield=true },
status = "beneficial",
parameters = { power=100 },
on_gain = function(self, err) return "A powerful kinetic shield forms around #target#.", "+Shield" end,
on_lose = function(self, err) return "The powerful kinetic shield around #target# crumbles.", "-Shield" end,
activate = function(self, eff)
eff.tmpid = self:addTemporaryValue("kinspike_shield", eff.power)
self.kinspike_shield_absorb = eff.power
if core.shader.active(4) then
eff.particle = self:addParticles(Particles.new("shader_shield", 1, {size_factor=1.4, img="shield5"}, {type="runicshield", ellipsoidalFactor=1, time_factor=-10000, llpow=1, aadjust=7, bubbleColor={1, 0, 0.3, 0.6}, auraColor={1, 0, 0.3, 1}}))
else
eff.particle = self:addParticles(Particles.new("generic_shield", 1, {r=1, g=0, b=0.3, a=1}))
end
end,
deactivate = function(self, eff)
self:removeParticles(eff.particle)
self:removeTemporaryValue("kinspike_shield", eff.tmpid)
self.kinspike_shield_absorb = nil
end,
}
newEffect{
name = "THERMSPIKE_SHIELD", image = "talents/thermal_shield.png",
desc = "Spiked Thermal Shield",
long_desc = function(self, eff)
local tl = self:getTalentLevel(self.T_ABSORPTION_MASTERY)
local xs = (tl>=3 and ", light" or "")..(tl>=6 and ", arcane" or "")
return ("The target erects a powerful thermal shield capable of absorbing %d/%d fire%s or cold damage before it crumbles."):format(self.thermspike_shield_absorb, eff.power, xs)
end,
type = "mental",
subtype = { telekinesis=true, shield=true },
status = "beneficial",
parameters = { power=100 },
on_gain = function(self, err) return "A powerful thermal shield forms around #target#.", "+Shield" end,
on_lose = function(self, err) return "The powerful thermal shield around #target# crumbles.", "-Shield" end,
activate = function(self, eff)
eff.tmpid = self:addTemporaryValue("thermspike_shield", eff.power)
self.thermspike_shield_absorb = eff.power
if core.shader.active(4) then
eff.particle = self:addParticles(Particles.new("shader_shield", 1, {size_factor=1.4, img="shield5"}, {type="runicshield", ellipsoidalFactor=1, time_factor=-10000, llpow=1, aadjust=7, bubbleColor={0.3, 1, 1, 0.6}, auraColor={0.3, 1, 1, 1}}))
else
eff.particle = self:addParticles(Particles.new("generic_shield", 1, {r=0.3, g=1, b=1, a=1}))
end
end,
deactivate = function(self, eff)
self:removeParticles(eff.particle)
self:removeTemporaryValue("thermspike_shield", eff.tmpid)
self.thermspike_shield_absorb = nil
end,
}
newEffect{
name = "CHARGESPIKE_SHIELD", image = "talents/charged_shield.png",
desc = "Spiked Charged Shield",
long_desc = function(self, eff)
local tl = self:getTalentLevel(self.T_ABSORPTION_MASTERY)
local xs = (tl>=3 and ", darkness" or "")..(tl>=6 and ", mind" or "")
return ("The target erects a powerful charged shield capable of absorbing %d/%d lightning%s or blight damage before it crumbles."):format(self.chargespike_shield_absorb, eff.power, xs)
end,
type = "mental",
subtype = { telekinesis=true, shield=true },
status = "beneficial",
parameters = { power=100 },
on_gain = function(self, err) return "A powerful charged shield forms around #target#.", "+Shield" end,
on_lose = function(self, err) return "The powerful charged shield around #target# crumbles.", "-Shield" end,
activate = function(self, eff)
eff.tmpid = self:addTemporaryValue("chargespike_shield", eff.power)
self.chargespike_shield_absorb = eff.power
if core.shader.active(4) then
eff.particle = self:addParticles(Particles.new("shader_shield", 1, {size_factor=1.4, img="shield5"}, {type="runicshield", ellipsoidalFactor=1, time_factor=-10000, llpow=1, aadjust=7, bubbleColor={0.8, 1, 0.2, 0.6}, auraColor={0.8, 1, 0.2, 1}}))
else
eff.particle = self:addParticles(Particles.new("generic_shield", 1, {r=0.8, g=1, b=0.2, a=1}))
end
end,
deactivate = function(self, eff)
self:removeParticles(eff.particle)
self:removeTemporaryValue("chargespike_shield", eff.tmpid)
self.chargespike_shield_absorb = nil
end,
}
newEffect{
name = "CONTROL", image = "talents/perfect_control.png",
desc = "Perfect control",
long_desc = function(self, eff) return ("The target's combat attack and crit chance are improved by %d and %d%%, respectively."):format(eff.power, 0.5*eff.power) end,
type = "mental",
subtype = { telekinesis=true, focus=true },
status = "beneficial",
parameters = { power=10 },
activate = function(self, eff)
eff.attack = self:addTemporaryValue("combat_atk", eff.power)
eff.crit = self:addTemporaryValue("combat_physcrit", 0.5*eff.power)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("combat_atk", eff.attack)
self:removeTemporaryValue("combat_physcrit", eff.crit)
end,
}
newEffect{
name = "PSI_REGEN", image = "talents/matter_is_energy.png",
desc = "Matter is energy",
long_desc = function(self, eff) return ("The gem's matter gradually transforms, granting %0.2f energy per turn."):format(eff.power) end,
type = "mental",
subtype = { psychic_drain=true },
status = "beneficial",
parameters = { power=10 },
on_gain = function(self, err) return "Energy starts pouring from the gem into #Target#.", "+Energy" end,
on_lose = function(self, err) return "The flow of energy from #Target#'s gem ceases.", "-Energy" end,
activate = function(self, eff)
eff.tmpid = self:addTemporaryValue("psi_regen", eff.power)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("psi_regen", eff.tmpid)
end,
}
newEffect{
name = "MASTERFUL_TELEKINETIC_ARCHERY", image = "talents/masterful_telekinetic_archery.png",
desc = "Telekinetic Archery",
long_desc = function(self, eff) return ("Your telekinetically-wielded bow automatically attacks the nearest target each turn.") end,
type = "mental",
subtype = { telekinesis=true },
status = "beneficial",
parameters = {dam=10},
on_gain = function(self, err) return "#Target# enters a telekinetic archer's trance!", "+Telekinetic archery" end,
on_lose = function(self, err) return "#Target# is no longer in a telekinetic archer's trance.", "-Telekinetic archery" end,
}
newEffect{
name = "WEAKENED_MIND", image = "talents/taint__telepathy.png",
desc = "Receptive Mind",
long_desc = function(self, eff) return ("Decreases mind save by %d and increases mindpower by %d."):format(eff.save, eff.power) end,
type = "mental",
subtype = { morale=true },
status = "detrimental",
parameters = { power=10, save=10 },
activate = function(self, eff)
eff.mindid = self:addTemporaryValue("combat_mentalresist", -eff.save)
eff.powdid = self:addTemporaryValue("combat_mindpower", eff.power)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("combat_mentalresist", eff.mindid)
self:removeTemporaryValue("combat_mindpower", eff.powdid)
end,
}
newEffect{
name = "VOID_ECHOES", image = "talents/echoes_from_the_void.png",
desc = "Void Echoes",
long_desc = function(self, eff) return ("The target is seeing echoes from the void and will take %0.2f mind damage as well as some resource damage each turn it fails a mental save."):format(eff.power) end,
type = "mental",
subtype = { madness=true, psionic=true },
status = "detrimental",
parameters = { power=10 },
on_gain = function(self, err) return "#Target# is being driven mad by the void.", "+Void Echoes" end,
on_lose = function(self, err) return "#Target# has survived the void madness.", "-Void Echoes" end,
on_timeout = function(self, eff)
local drain = DamageType:get(DamageType.MIND).projector(eff.src or self, self.x, self.y, DamageType.MIND, eff.power) / 2
self:incMana(-drain)
self:incVim(-drain * 0.5)
self:incPositive(-drain * 0.25)
self:incNegative(-drain * 0.25)
self:incStamina(-drain * 0.65)
self:incHate(-drain * 0.2)
self:incPsi(-drain * 0.2)
end,
}
newEffect{
name = "WAKING_NIGHTMARE", image = "talents/waking_nightmare.png",
desc = "Waking Nightmare",
long_desc = function(self, eff) return ("The target is lost in a nightmare that deals %0.2f mind damage each turn and has a %d%% chance to cause a random detrimental effect."):format(eff.dam, eff.chance) end,
type = "mental",
subtype = { nightmare=true, darkness=true },
status = "detrimental",
parameters = { chance=10, dam = 10 },
on_gain = function(self, err) return "#F53CBE##Target# is lost in a nightmare.", "+Night Terrors" end,
on_lose = function(self, err) return "#Target# is free from the nightmare.", "-Night Terrors" end,
on_timeout = function(self, eff)
DamageType:get(DamageType.DARKNESS).projector(eff.src or self, self.x, self.y, DamageType.DARKNESS, eff.dam)
local chance = eff.chance
if self:attr("sleep") then chance = 100-(100-chance)/2 end -- Half normal chance to avoid effect
if rng.percent(chance) then
-- Pull random effect
chance = rng.range(1, 3)
if chance == 1 then
if self:canBe("blind") then
self:setEffect(self.EFF_BLINDED, 3, {})
end
elseif chance == 2 then
if self:canBe("stun") then
self:setEffect(self.EFF_STUNNED, 3, {})
end
elseif chance == 3 then
if self:canBe("confusion") then
self:setEffect(self.EFF_CONFUSED, 3, {power=50})
end
end
game.logSeen(self, "#F53CBE#%s succumbs to the nightmare!", self.name:capitalize())
end
end,
}
newEffect{
name = "INNER_DEMONS", image = "talents/inner_demons.png",
desc = "Inner Demons",
long_desc = function(self, eff) return ("The target is plagued by inner demons and each turn there's a %d%% chance that one will appear. If the caster is killed or the target resists setting his demons loose the effect will end early."):format(eff.chance) end,
type = "mental",
subtype = { nightmare=true },
status = "detrimental",
remove_on_clone = true,
parameters = {chance=0},
on_gain = function(self, err) return "#F53CBE##Target# is plagued by inner demons!", "+Inner Demons" end,
on_lose = function(self, err) return "#Target# is freed from the demons.", "-Inner Demons" end,
on_timeout = function(self, eff)
if eff.src.dead or not game.level:hasEntity(eff.src) then eff.dur = 0 return true end
local t = eff.src:getTalentFromId(eff.src.T_INNER_DEMONS)
local chance = eff.chance
if self:attr("sleep") then chance = 100-(100-chance)/2 end -- Half normal chance not to manifest
if rng.percent(chance) then
if self:attr("sleep") or self:checkHit(eff.src:combatMindpower(), self:combatMentalResist(), 0, 95, 5) then
t.summon_inner_demons(eff.src, self, t)
else
eff.dur = 0
end
end
end,
}
newEffect{
name = "PACIFICATION_HEX", image = "talents/pacification_hex.png",
desc = "Pacification Hex",
long_desc = function(self, eff) return ("The target is hexed, granting it %d%% chance each turn to be dazed for 3 turns."):format(eff.chance) end,
type = "mental",
subtype = { hex=true, dominate=true },
status = "detrimental",
parameters = {chance=10, power=10},
on_gain = function(self, err) return "#Target# is hexed!", "+Pacification Hex" end,
on_lose = function(self, err) return "#Target# is free from the hex.", "-Pacification Hex" end,
-- Damage each turn
on_timeout = function(self, eff)
if not self:hasEffect(self.EFF_DAZED) and rng.percent(eff.chance) and self:canBe("stun") then
self:setEffect(self.EFF_DAZED, 3, {})
if not self:checkHit(eff.power, self:combatSpellResist(), 0, 95, 15) then eff.dur = 0 end
end
end,
activate = function(self, eff)
if self:canBe("stun") then
self:setEffect(self.EFF_DAZED, 3, {})
end
end,
}
newEffect{
name = "BURNING_HEX", image = "talents/burning_hex.png",
desc = "Burning Hex",
long_desc = function(self, eff) return ("The target is hexed. Each time it uses an ability it takes %0.2f fire damage, and talent cooldowns are increased by %s plus 1 turn."):
format(eff.dam, eff.power and ("%d%%"):format((eff.power-1)*100) or "")
end,
type = "mental",
subtype = { hex=true, fire=true },
status = "detrimental",
-- _M:getTalentCooldown(t) in mod.class.Actor.lua references this table to compute cooldowns
parameters = {dam=10, power = 1},
on_gain = function(self, err) return "#Target# is hexed!", "+Burning Hex" end,
on_lose = function(self, err) return "#Target# is free from the hex.", "-Burning Hex" end,
}
newEffect{
name = "EMPATHIC_HEX", image = "talents/empathic_hex.png",
desc = "Empathic Hex",
long_desc = function(self, eff) return ("The target is hexed, creating an empathic bond with its victims. It takes %d%% feedback damage from all damage done."):format(eff.power) end,
type = "mental",
subtype = { hex=true, dominate=true },
status = "detrimental",
parameters = { power=10 },
on_gain = function(self, err) return "#Target# is hexed.", "+Empathic Hex" end,
on_lose = function(self, err) return "#Target# is free from the hex.", "-Empathic hex" end,
activate = function(self, eff)
eff.tmpid = self:addTemporaryValue("martyrdom", eff.power)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("martyrdom", eff.tmpid)
end,
}
newEffect{
name = "DOMINATION_HEX", image = "talents/domination_hex.png",
desc = "Domination Hex",
long_desc = function(self, eff) return ("The target is hexed, temporarily changing its faction to %s."):format(engine.Faction.factions[eff.faction].name) end,
type = "mental",
subtype = { hex=true, dominate=true },
status = "detrimental",
parameters = {},
on_gain = function(self, err) return "#Target# is hexed.", "+Domination Hex" end,
on_lose = function(self, err) return "#Target# is free from the hex.", "-Domination hex" end,
activate = function(self, eff)
self:setTarget() -- clear ai target
eff.olf_faction = self.faction
self.faction = eff.src.faction
end,
deactivate = function(self, eff)
self.faction = eff.olf_faction
end,
}
newEffect{
name = "DOMINATE_ENTHRALL", image = "talents/yeek_will.png",
desc = "Enthralled",
long_desc = function(self, eff) return ("The target is enthralled, temporarily changing its faction.") end,-- to %s.")--:format(engine.Faction.factions[eff.faction].name) end,
type = "mental",
subtype = { dominate=true },
status = "detrimental",
parameters = {},
on_gain = function(self, err) return "#Target# is entralled.", "+Enthralled" end,
on_lose = function(self, err) return "#Target# is free from the domination.", "-Enthralled" end,
activate = function(self, eff)
eff.olf_faction = self.faction
self.faction = eff.src.faction
end,
deactivate = function(self, eff)
self.faction = eff.olf_faction
end,
}
newEffect{
name = "HALFLING_LUCK", image = "talents/halfling_luck.png",
desc = "Halflings's Luck",
long_desc = function(self, eff) return ("The target's luck and cunning combine to grant it %d%% higher combat critical chance, %d%% higher mental critical chance, and %d%% higher spell critical chance."):format(eff.physical, eff.mind, eff.spell) end,
type = "mental",
subtype = { focus=true },
status = "beneficial",
parameters = { spell=10, physical=10 },
on_gain = function(self, err) return "#Target# seems more aware." end,
on_lose = function(self, err) return "#Target#'s awareness returns to normal." end,
activate = function(self, eff)
self:effectTemporaryValue(eff, "combat_physcrit", eff.physical)
self:effectTemporaryValue(eff, "combat_spellcrit", eff.spell)
self:effectTemporaryValue(eff, "combat_mindcrit", eff.mind)
self:effectTemporaryValue(eff, "combat_physresist", eff.physical)
self:effectTemporaryValue(eff, "combat_spellresist", eff.spell)
self:effectTemporaryValue(eff, "combat_mentalresist", eff.mind)
end,
}
newEffect{
name = "ATTACK", image = "talents/perfect_strike.png",
desc = "Attack",
long_desc = function(self, eff) return ("The target's combat attack is improved by %d."):format(eff.power) end,
type = "mental",
subtype = { focus=true },
status = "beneficial",
parameters = { power=10 },
on_gain = function(self, err) return "#Target# aims carefully." end,
on_lose = function(self, err) return "#Target# aims less carefully." end,
activate = function(self, eff)
eff.tmpid = self:addTemporaryValue("combat_atk", eff.power)
eff.bid = self:addTemporaryValue("blind_fight", 1)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("combat_atk", eff.tmpid)
self:removeTemporaryValue("blind_fight", eff.bid)
end,
}
newEffect{
name = "DEADLY_STRIKES", image = "talents/deadly_strikes.png",
desc = "Deadly Strikes",
long_desc = function(self, eff) return ("The target's armour penetration is increased by %d."):format(eff.power) end,
type = "mental",
subtype = { focus=true },
status = "beneficial",
parameters = { power=10 },
on_gain = function(self, err) return "#Target# aims carefully." end,
on_lose = function(self, err) return "#Target# aims less carefully." end,
activate = function(self, eff)
eff.tmpid = self:addTemporaryValue("combat_apr", eff.power)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("combat_apr", eff.tmpid)
end,
}
newEffect{
name = "FRENZY", image = "effects/frenzy.png",
desc = "Frenzy",
long_desc = function(self, eff) return ("Increases global action speed by %d%% and physical crit by %d%%.\nAdditionally the target will continue to fight until its Life reaches -%d%%."):format(eff.power * 100, eff.crit, eff.dieat * 100) end,
type = "mental",
subtype = { frenzy=true, speed=true },
status = "beneficial",
parameters = { power=0.1 },
on_gain = function(self, err) return "#Target# goes into a killing frenzy.", "+Frenzy" end,
on_lose = function(self, err) return "#Target# calms down.", "-Frenzy" end,
on_merge = function(self, old_eff, new_eff)
-- use on merge so reapplied frenzy doesn't kill off creatures with negative life
old_eff.dur = new_eff.dur
old_eff.power = new_eff.power
old_eff.crit = new_eff.crit
return old_eff
end,
activate = function(self, eff)
eff.tmpid = self:addTemporaryValue("global_speed_add", eff.power)
eff.critid = self:addTemporaryValue("combat_physcrit", eff.crit)
eff.dieatid = self:addTemporaryValue("die_at", -self.max_life * eff.dieat)
end,
deactivate = function(self, eff)
-- check negative life first incase the creature has healing
if self.life <= 0 then
local sx, sy = game.level.map:getTileToScreen(self.x, self.y)
game.flyers:add(sx, sy, 30, (rng.range(0,2)-1) * 0.5, rng.float(-2.5, -1.5), "Falls dead!", {255,0,255})
game.logSeen(self, "%s dies when its frenzy ends!", self.name:capitalize())
self:die(self)
end
self:removeTemporaryValue("global_speed_add", eff.tmpid)
self:removeTemporaryValue("combat_physcrit", eff.critid)
self:removeTemporaryValue("die_at", eff.dieatid)
end,
}
newEffect{
name = "BLOODBATH", image = "talents/bloodbath.png",
desc = "Bloodbath",
long_desc = function(self, eff) return ("The thrill of combat improves the target's maximum life by %d%%, life regeneration by %0.2f, and stamina regeneration by %0.2f."):format(eff.hp, eff.cur_regen or eff.regen, eff.cur_regen/5 or eff.regen/5) end,
type = "mental",
subtype = { frenzy=true, heal=true },
status = "beneficial",
parameters = { hp=10, regen=10, max=50 },
on_gain = function(self, err) return nil, "+Bloodbath" end,
on_lose = function(self, err) return nil, "-Bloodbath" end,
on_merge = function(self, old_eff, new_eff)
if old_eff.cur_regen + new_eff.regen < new_eff.max then game.logSeen(self, "%s's blood frenzy intensifies!", self.name:capitalize()) end
new_eff.templife_id = old_eff.templife_id
self:removeTemporaryValue("max_life", old_eff.life_id)
self:removeTemporaryValue("life_regen", old_eff.life_regen_id)
self:removeTemporaryValue("stamina_regen", old_eff.stamina_regen_id)
new_eff.particle1 = old_eff.particle1
new_eff.particle2 = old_eff.particle2
-- Take the new values, dont heal, otherwise you get a free heal each crit .. which is totaly broken
local v = new_eff.hp * self.max_life / 100
new_eff.life_id = self:addTemporaryValue("max_life", v)
new_eff.cur_regen = math.min(old_eff.cur_regen + new_eff.regen, new_eff.max)
new_eff.life_regen_id = self:addTemporaryValue("life_regen", new_eff.cur_regen)
new_eff.stamina_regen_id = self:addTemporaryValue("stamina_regen", new_eff.cur_regen/5)
return new_eff
end,
activate = function(self, eff)
local v = eff.hp * self.max_life / 100
eff.life_id = self:addTemporaryValue("max_life", v)
eff.templife_id = self:addTemporaryValue("life",v) -- Prevent healing_factor affecting activation
eff.cur_regen = eff.regen
eff.life_regen_id = self:addTemporaryValue("life_regen", eff.regen)
eff.stamina_regen_id = self:addTemporaryValue("stamina_regen", eff.regen /5)
game.logSeen(self, "%s revels in the spilt blood and grows stronger!",self.name:capitalize())
if core.shader.active(4) then
eff.particle1 = self:addParticles(Particles.new("shader_shield", 1, {toback=true, size_factor=1.5, y=-0.3, img="healarcane"}, {type="healing", time_factor=4000, noup=2.0, beamColor1={0xff/255, 0x22/255, 0x22/255, 1}, beamColor2={0xff/255, 0x60/255, 0x60/255, 1}, circleColor={0,0,0,0}, beamsCount=8}))
eff.particle2 = self:addParticles(Particles.new("shader_shield", 1, {toback=false, size_factor=1.5, y=-0.3, img="healarcane"}, {type="healing", time_factor=4000, noup=1.0, beamColor1={0xff/255, 0x22/255, 0x22/255, 1}, beamColor2={0xff/255, 0x60/255, 0x60/255, 1}, circleColor={0,0,0,0}, beamsCount=8}))
end
end,
deactivate = function(self, eff)
self:removeParticles(eff.particle1)
self:removeParticles(eff.particle2)
self:removeTemporaryValue("max_life", eff.life_id)
self:removeTemporaryValue("life_regen", eff.life_regen_id)
self:removeTemporaryValue("stamina_regen", eff.stamina_regen_id)
self:removeTemporaryValue("life",eff.templife_id) -- remove extra hps to prevent excessive heals at high level
game.logSeen(self, "%s no longer revels in blood quite so much.",self.name:capitalize())
end,
}
newEffect{
name = "BLOODRAGE", image = "talents/bloodrage.png",
desc = "Bloodrage",
long_desc = function(self, eff) return ("The target's strength is increased by %d by the thrill of combat."):format(eff.cur_inc) end,
type = "mental",
subtype = { frenzy=true },
status = "beneficial",
parameters = { inc=1, max=10 },
on_merge = function(self, old_eff, new_eff)
self:removeTemporaryValue("inc_stats", old_eff.tmpid)
old_eff.cur_inc = math.min(old_eff.cur_inc + new_eff.inc, new_eff.max)
old_eff.tmpid = self:addTemporaryValue("inc_stats", {[Stats.STAT_STR] = old_eff.cur_inc})
old_eff.dur = new_eff.dur
return old_eff
end,
activate = function(self, eff)
eff.cur_inc = eff.inc
eff.tmpid = self:addTemporaryValue("inc_stats", {[Stats.STAT_STR] = eff.inc})
end,
deactivate = function(self, eff)
self:removeTemporaryValue("inc_stats", eff.tmpid)
end,
}
newEffect{
name = "UNSTOPPABLE", image = "talents/unstoppable.png",
desc = "Unstoppable",
long_desc = function(self, eff) return ("The target is unstoppable! It refuses to die, and at the end it will heal %d Life."):format(eff.kills * eff.hp_per_kill * self.max_life / 100) end,
type = "mental",
subtype = { frenzy=true },
status = "beneficial",
parameters = { hp_per_kill=2 },
activate = function(self, eff)
eff.kills = 0
eff.tmpid = self:addTemporaryValue("unstoppable", 1)
eff.healid = self:addTemporaryValue("no_life_regen", 1)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("unstoppable", eff.tmpid)
self:removeTemporaryValue("no_life_regen", eff.healid)
self:heal(eff.kills * eff.hp_per_kill * self.max_life / 100, eff)
end,
}
newEffect{
name = "INCREASED_LIFE", image = "effects/increased_life.png",
desc = "Increased Life",
long_desc = function(self, eff) return ("The target's maximum life is increased by %d."):format(eff.life) end,
type = "mental",
subtype = { frenzy=true, heal=true },
status = "beneficial",
on_gain = function(self, err) return "#Target# gains extra life.", "+Life" end,
on_lose = function(self, err) return "#Target# loses extra life.", "-Life" end,
parameters = { life = 50 },
activate = function(self, eff)
self.max_life = self.max_life + eff.life
self.life = self.life + eff.life
self.changed = true
end,
deactivate = function(self, eff)
self.max_life = self.max_life - eff.life
self.life = self.life - eff.life
self.changed = true
if self.life <= 0 then
self.life = 1
self:setEffect(self.EFF_STUNNED, 3, {})
game.logSeen(self, "%s's increased life fades, leaving it stunned by the loss.", self.name:capitalize())
end
end,
}
newEffect{
name = "GESTURE_OF_GUARDING", image = "talents/gesture_of_guarding.png",
desc = "Guarded",
long_desc = function(self, eff)
local xs = ""
local dam, deflects = eff.dam, eff.deflects
if deflects < 1 then -- Partial deflect has reduced effectiveness
dam = dam*math.max(0,deflects)
deflects = 1
end
if self:isTalentActive(self.T_GESTURE_OF_PAIN) then xs = (" with a %d%% chance to counterattack"):format(self:callTalent(self.T_GESTURE_OF_GUARDING,"getCounterAttackChance")) end
return ("Guarding against melee damage: Will dismiss up to %d damage from the next %0.1f attack(s)%s."):format(dam, deflects, xs)
end,
charges = function(self, eff) return "#LIGHT_GREEN#"..math.ceil(eff.deflects) end,
type = "mental",
subtype = { curse=true },
status = "beneficial",
decrease = 0,
no_stop_enter_worlmap = true, no_stop_resting = true,
parameters = {dam = 1, deflects = 1},
activate = function(self, eff)
eff.dam = self:callTalent(self.T_GESTURE_OF_GUARDING,"getDamageChange")
eff.deflects = self:callTalent(self.T_GESTURE_OF_GUARDING,"getDeflects")
if eff.dam <= 0 or eff.deflects <= 0 then eff.dur = 0 end
end,
deactivate = function(self, eff)
end,
}
newEffect{
name = "RAMPAGE", image = "talents/rampage.png",
desc = "Rampaging",
long_desc = function(self, eff)
local desc = ("The target is rampaging! (+%d%% movement speed, +%d%% attack speed"):format(eff.movementSpeedChange * 100, eff.combatPhysSpeedChange * 100)
if eff.physicalDamageChange > 0 then
desc = desc..(", +%d%% physical damage, +%d physical save, +%d mental save"):format(eff.physicalDamageChange, eff.combatPhysResistChange, eff.combatMentalResistChange)
end
if eff.damageShieldMax > 0 then
desc = desc..(", %d/%d damage shrugged off this turn"):format(math.max(0, eff.damageShieldMax - eff.damageShield), eff.damageShieldMax)
end
desc = desc..")"
return desc
end,
type = "mental",
subtype = { frenzy=true, speed=true, evade=true },
status = "beneficial",
parameters = { },
on_gain = function(self, err) return "#F53CBE##Target# begins rampaging!", "+Rampage" end,
on_lose = function(self, err) return "#F53CBE##Target# is no longer rampaging.", "-Rampage" end,
activate = function(self, eff)
if eff.movementSpeedChange or 0 > 0 then eff.movementSpeedId = self:addTemporaryValue("movement_speed", eff.movementSpeedChange) end
if eff.combatPhysSpeedChange or 0 > 0 then eff.combatPhysSpeedId = self:addTemporaryValue("combat_physspeed", eff.combatPhysSpeedChange) end
if eff.physicalDamageChange or 0 > 0 then eff.physicalDamageId = self:addTemporaryValue("inc_damage", { [DamageType.PHYSICAL] = eff.physicalDamageChange }) end
if eff.combatPhysResistChange or 0 > 0 then eff.combatPhysResistId = self:addTemporaryValue("combat_physresist", eff.combatPhysResistChange) end
if eff.combatMentalResistChange or 0 > 0 then eff.combatMentalResistId = self:addTemporaryValue("combat_mentalresist", eff.combatMentalResistChange) end
if not self:addShaderAura("rampage", "awesomeaura", {time_factor=5000, alpha=0.7}, "particles_images/bloodwings.png") then
eff.particle = self:addParticles(Particles.new("rampage", 1))
end
end,
deactivate = function(self, eff)
if eff.movementSpeedId then self:removeTemporaryValue("movement_speed", eff.movementSpeedId) end
if eff.combatPhysSpeedId then self:removeTemporaryValue("combat_physspeed", eff.combatPhysSpeedId) end
if eff.physicalDamageId then self:removeTemporaryValue("inc_damage", eff.physicalDamageId) end
if eff.combatPhysResistId then self:removeTemporaryValue("combat_physresist", eff.combatPhysResistId) end
if eff.combatMentalResistId then self:removeTemporaryValue("combat_mentalresist", eff.combatMentalResistId) end
self:removeShaderAura("rampage")
self:removeParticles(eff.particle)
end,
on_timeout = function(self, eff)
-- restore damage shield
if eff.damageShieldMax and eff.damageShield ~= eff.damageShieldMax and not self.dead then
eff.damageShieldUsed = (eff.damageShieldUsed or 0) + eff.damageShieldMax - eff.damageShield
game.logSeen(self, "%s has shrugged off %d damage and is ready for more.", self.name:capitalize(), eff.damageShieldMax - eff.damageShield)
eff.damageShield = eff.damageShieldMax
if eff.damageShieldBonus and eff.damageShieldUsed >= eff.damageShieldBonus and eff.actualDuration < eff.maxDuration then
eff.actualDuration = eff.actualDuration + 1
eff.dur = eff.dur + 1
eff.damageShieldBonus = nil
game.logPlayer(self, "#F53CBE#Your rampage is invigorated by the intense onslaught! (+1 duration)")
end
end
end,
do_onTakeHit = function(self, eff, dam)
if not eff.damageShieldMax or eff.damageShield <= 0 then return dam end
local absorb = math.min(eff.damageShield, dam)
eff.damageShield = eff.damageShield - absorb
--game.logSeen(self, "%s shrugs off %d damage.", self.name:capitalize(), absorb)
return dam - absorb
end,
do_postUseTalent = function(self, eff)
if eff.dur > 0 then
eff.dur = eff.dur - 1
game.logPlayer(self, "#F53CBE#You feel your rampage slowing down. (-1 duration)")
end
end,
}
newEffect{
name = "PREDATOR", image = "effects/predator.png",
desc = "Predator",
no_stop_enter_worlmap = true,
decrease = 0,
no_remove = true,
cancel_on_level_change = true,
long_desc = function(self, eff)
local desc = ([[The target is hunting creatures of type / sub-type: %s / %s with %d%% effectiveness. Kills: %d / %d kills, Damage: %+d%% / %+d%%]]):format(eff.type, eff.subtype, (eff.effectiveness * 100) or 0, eff.typeKills, eff.subtypeKills, (eff.typeDamageChange * 100) or 0, (eff.subtypeDamageChange * 100) or 0)
if eff.subtypeAttackChange or 0 > 0 then
desc = desc..([[, Attack: %+d / %+d, Stun: -- / %0.1f%%, Outmaneuver: %0.1f%% / %0.1f%%]]):format(eff.typeAttackChange or 0, eff.subtypeAttackChange or 0, eff.subtypeStunChance or 0, eff.typeOutmaneuverChance or 0, eff.subtypeOutmaneuverChance or 0)
end
return desc
end,
type = "mental",
subtype = { predator=true },
status = "beneficial",
parameters = { power=10 },
on_gain = function(self, eff) return ("#Target# begins hunting %s / %s."):format(eff.type, eff.subtype) end,
on_lose = function(self, eff) return ("#Target# is no longer hunting %s / %s."):format(eff.type, eff.subtype) end,
activate = function(self, eff)
local e = self.tempeffect_def[self.EFF_PREDATOR]
e.updateEffect(self, eff)
end,
deactivate = function(self, eff)
end,
addKill = function(self, target, e, eff)
if target.type == eff.type then
local isSubtype = (target.subtype == eff.subtype)
if isSubtype then
eff.subtypeKills = eff.subtypeKills + 1
eff.killExperience = eff.killExperience + 1
else
eff.typeKills = eff.typeKills + 1
eff.killExperience = eff.killExperience + 0.25
end
e.updateEffect(self, eff)
-- apply hate bonus
if isSubtype and self:knowTalent(self.T_HATE_POOL) then
self:incHate(eff.hateBonus)
game.logPlayer(self, "#F53CBE#The death of your prey feeds your hate. (+%d hate)", eff.hateBonus)
end
-- apply mimic effect
if isSubtype and self:knowTalent(self.T_MIMIC) then
local tMimic = self:getTalentFromId(self.T_MIMIC)
self:setEffect(self.EFF_MIMIC, 1, { target = target, maxIncrease = math.ceil(tMimic.getMaxIncrease(self, tMimic) * eff.effectiveness) })
end
end
end,
updateEffect = function(self, eff)
local tMarkPrey = self:getTalentFromId(self.T_MARK_PREY)
eff.maxKillExperience = tMarkPrey.getMaxKillExperience(self, tMarkPrey)
eff.effectiveness = math.min(1, eff.killExperience / eff.maxKillExperience)
eff.subtypeDamageChange = tMarkPrey.getSubtypeDamageChange(self, tMarkPrey) * eff.effectiveness
eff.typeDamageChange = tMarkPrey.getTypeDamageChange(self, tMarkPrey) * eff.effectiveness
local tAnatomy = self:getTalentFromId(self.T_ANATOMY)
if tAnatomy and self:getTalentLevelRaw(tAnatomy) > 0 then
eff.subtypeAttackChange = tAnatomy.getSubtypeAttackChange(self, tAnatomy) * eff.effectiveness
eff.typeAttackChange = tAnatomy.getTypeAttackChange(self, tAnatomy) * eff.effectiveness
eff.subtypeStunChance = tAnatomy.getSubtypeStunChance(self, tAnatomy) * eff.effectiveness
else
eff.subtypeAttackChange = 0
eff.typeAttackChange = 0
eff.subtypeStunChance = 0
end
local tOutmaneuver = self:getTalentFromId(self.T_OUTMANEUVER)
if tOutmaneuver and self:getTalentLevelRaw(tOutmaneuver) > 0 then
eff.typeOutmaneuverChance = tOutmaneuver.getTypeChance(self, tOutmaneuver) * eff.effectiveness
eff.subtypeOutmaneuverChance = tOutmaneuver.getSubtypeChance(self, tOutmaneuver) * eff.effectiveness
else
eff.typeOutmaneuverChance = 0
eff.subtypeOutmaneuverChance = 0
end
eff.hateBonus = tMarkPrey.getHateBonus(self, tMarkPrey)
end,
}
newEffect{
name = "OUTMANEUVERED", image = "talents/outmaneuver.png",
desc = "Outmaneuvered",
long_desc = function(self, eff)
local desc = ("The target has been outmaneuvered. (%d%% physical resistance, "):format(eff.physicalResistChange)
local first = true
for id, value in pairs(eff.incStats) do
if not first then desc = desc..", " end
first = false
desc = desc..("%+d %s"):format(value, Stats.stats_def[id].name:capitalize())
end
desc = desc..")"
return desc
end,
type = "mental",
subtype = { predator=true },
status = "detrimental",
on_gain = function(self, eff) return "#Target# is outmaneuvered." end,
on_lose = function(self, eff) return "#Target# is no longer outmaneuvered." end,
addEffect = function(self, eff)
if eff.physicalResistId then self:removeTemporaryValue("resists", eff.physicalResistId) end
eff.physicalResistId = self:addTemporaryValue("resists", { [DamageType.PHYSICAL]=eff.physicalResistChange })
local maxId
local maxValue = 0
for id, def in ipairs(self.stats_def) do
if def.id ~= self.STAT_LCK then
local value = self:getStat(id, nil, nil, false)
if value > maxValue then
maxId = id
maxValue = value
end
end
end
if eff.incStatsId then self:removeTemporaryValue("inc_stats", eff.incStatsId) end
eff.incStats = eff.incStats or {}
eff.incStats[maxId] = (eff.incStats[maxId] or 0) - eff.statReduction
eff.incStatsId = self:addTemporaryValue("inc_stats", eff.incStats)
game.logSeen(self, ("%s has lost %d %s."):format(self.name:capitalize(), eff.statReduction, Stats.stats_def[maxId].name:capitalize()))
end,
activate = function(self, eff)
self.tempeffect_def[self.EFF_OUTMANEUVERED].addEffect(self, eff)
end,
deactivate = function(self, eff)
if eff.physicalResistId then self:removeTemporaryValue("resists", eff.physicalResistId) end
if eff.incStatsId then self:removeTemporaryValue("inc_stats", eff.incStatsId) end
end,
on_merge = function(self, old_eff, new_eff)
-- spread old effects over new duration
old_eff.physicalResistChange = math.min(50, new_eff.physicalResistChange + (old_eff.physicalResistChange * old_eff.dur / new_eff.dur))
for id, value in pairs(old_eff.incStats) do
old_eff.incStats[id] = math.ceil(value * old_eff.dur / new_eff.dur)
end
old_eff.dur = new_eff.dur
-- add new effect
self.tempeffect_def[self.EFF_OUTMANEUVERED].addEffect(self, old_eff)
return old_eff
end,
}
newEffect{
name = "MIMIC", image = "talents/mimic.png",
desc = "Mimic",
long_desc = function(self, eff)
if not eff.incStatsId then return "The target is mimicking a previous victim. (no gains)." end
local desc = "The target is mimicking a previous victim. ("
local first = true
for id, value in pairs(eff.incStats) do
if not first then desc = desc..", " end
first = false
desc = desc..("%+d %s"):format(value, Stats.stats_def[id].name:capitalize())
end
desc = desc..")"
return desc
end,
type = "mental",
subtype = { predator=true },
status = "beneficial",
no_stop_enter_worlmap = true,
decrease = 0,
no_remove = true,
cancel_on_level_change = true,
parameters = { },
on_lose = function(self, eff) return "#Target# is no longer mimicking a previous victim." end,
activate = function(self, eff)
-- old version used difference from target stats and self stats; new version just uses target stats
local sum = 0
local values = {}
for id, def in ipairs(self.stats_def) do
if def.id and def.id ~= self.STAT_LCK then
--local diff = eff.target:getStat(def.id, nil, nil, true) - self:getStat(def.id, nil, nil, true)
local diff = eff.target:getStat(def.id, nil, nil, false)
if diff > 0 then
table.insert(values, { def.id, diff })
sum = sum + diff
end
end
end
if sum > 0 then
eff.incStats = {}
if sum <= eff.maxIncrease then
-- less than maximum; apply all stat differences
for i, value in ipairs(values) do
eff.incStats[value[1]] = value[2]
end
else
-- distribute stats based on fractions and calculate what the remainder will be
local sumIncrease = 0
for i, value in ipairs(values) do
value[2] = eff.maxIncrease * value[2] / sum
sumIncrease = sumIncrease + math.floor(value[2])
end
local remainder = eff.maxIncrease - sumIncrease
-- sort on fractional amount for distributing the remainder points
table.sort(values, function(a,b) return a[2] % 1 > b[2] % 1 end)
-- convert fractions to stat increases and apply remainder
for i, value in ipairs(values) do
eff.incStats[value[1]] = math.floor(value[2]) + (i <= remainder and 1 or 0)
end
end
eff.incStatsId = self:addTemporaryValue("inc_stats", eff.incStats)
end
if not eff.incStatsId then
self:logCombat(eff.target, "#Source# is mimicking #Target#. (no gains).")
else
local desc = "#Source# is mimicking #Target#. ("
local first = true
for id, value in pairs(eff.incStats) do
if not first then desc = desc..", " end
first = false
desc = desc..("%+d %s"):format(value, Stats.stats_def[id].name:capitalize())
end
desc = desc..")"
self:logCombat(eff.target, desc)
end
end,
deactivate = function(self, eff)
if eff.incStatsId then self:removeTemporaryValue("inc_stats", eff.incStatsId) end
eff.incStats = nil
end,
on_merge = function(self, old_eff, new_eff)
if old_eff.incStatsId then self:removeTemporaryValue("inc_stats", old_eff.incStatsId) end
old_eff.incStats = nil
old_eff.incStatsId = nil
self.tempeffect_def[self.EFF_MIMIC].activate(self, new_eff)
return new_eff
end
}
newEffect{
name = "ORC_FURY", image = "talents/orc_fury.png",
desc = "Orcish Fury",
long_desc = function(self, eff) return ("The target enters a destructive fury, increasing all damage done by %d%%."):format(eff.power) end,
type = "mental",
subtype = { frenzy=true },
status = "beneficial",
parameters = { power=10 },
on_gain = function(self, err) return "#Target# enters a state of bloodlust." end,
on_lose = function(self, err) return "#Target# calms down." end,
activate = function(self, eff)
eff.pid = self:addTemporaryValue("inc_damage", {all=eff.power})
end,
deactivate = function(self, eff)
self:removeTemporaryValue("inc_damage", eff.pid)
end,
}
newEffect{
name = "INTIMIDATED",
desc = "Intimidated",
long_desc = function(self, eff) return ("The target's morale is weakened, reducing its attack power, mind power, and spellpower by %d."):format(eff.power) end,
type = "mental",
subtype = { fear=true },
status = "detrimental",
on_gain = function(self, err) return "#Target#'s morale has been lowered.", "+Intimidated" end,
on_lose = function(self, err) return "#Target# has regained its confidence.", "-Intimidated" end,
parameters = { power=1 },
activate = function(self, eff)
eff.damid = self:addTemporaryValue("combat_dam", -eff.power)
eff.spellid = self:addTemporaryValue("combat_spellpower", -eff.power)
eff.mindid = self:addTemporaryValue("combat_mindpower", -eff.power)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("combat_dam", eff.damid)
self:removeTemporaryValue("combat_spellpower", eff.spellid)
self:removeTemporaryValue("combat_mindpower", eff.mindid)
end,
}
newEffect{
name = "BRAINLOCKED",
desc = "Brainlocked",
long_desc = function(self, eff) return ("Renders a random talent unavailable. No talents will cool down until the effect has worn off."):format() end,
type = "mental",
subtype = { ["cross tier"]=true },
status = "detrimental",
parameters = {},
on_gain = function(self, err) return nil, "+Brainlocked" end,
on_lose = function(self, err) return nil, "-Brainlocked" end,
activate = function(self, eff)
eff.tcdid = self:addTemporaryValue("no_talents_cooldown", 1)
local tids = {}
for tid, lev in pairs(self.talents) do
local t = self:getTalentFromId(tid)
if t and not self.talents_cd[tid] and t.mode == "activated" and not t.innate then tids[#tids+1] = t end
end
for i = 1, 1 do
local t = rng.tableRemove(tids)
if not t then break end
self.talents_cd[t.id] = 1
end
end,
deactivate = function(self, eff)
self:removeTemporaryValue("no_talents_cooldown", eff.tcdid)
end,
}
newEffect{
name = "FRANTIC_SUMMONING", image = "talents/frantic_summoning.png",
desc = "Frantic Summoning",
long_desc = function(self, eff) return ("Reduces the time taken for summoning by %d%%."):format(eff.power) end,
type = "mental",
subtype = { summon=true },
status = "beneficial",
on_gain = function(self, err) return "#Target# starts summoning at high speed.", "+Frantic Summoning" end,
on_lose = function(self, err) return "#Target#'s frantic summoning ends.", "-Frantic Summoning" end,
parameters = { power=20 },
activate = function(self, eff)
eff.failid = self:addTemporaryValue("no_equilibrium_summon_fail", 1)
eff.speedid = self:addTemporaryValue("fast_summons", eff.power)
-- Find a cooling down summon talent and enable it
local list = {}
for tid, dur in pairs(self.talents_cd) do
local t = self:getTalentFromId(tid)
if t.is_summon then
list[#list+1] = t
end
end
if #list > 0 then
local t = rng.table(list)
self.talents_cd[t.id] = nil
if self.onTalentCooledDown then self:onTalentCooledDown(t.id) end
end
end,
deactivate = function(self, eff)
self:removeTemporaryValue("no_equilibrium_summon_fail", eff.failid)
self:removeTemporaryValue("fast_summons", eff.speedid)
end,
}
newEffect{
name = "WILD_SUMMON", image = "talents/wild_summon.png",
desc = "Wild Summon",
long_desc = function(self, eff) return ("%d%% chance to get a more powerful summon."):format(eff.chance) end,
type = "mental",
subtype = { summon=true },
status = "beneficial",
parameters = { chance=100 },
activate = function(self, eff)
eff.tid = self:addTemporaryValue("wild_summon", eff.chance)
end,
on_timeout = function(self, eff)
eff.chance = eff.chance or 100
eff.chance = math.floor(eff.chance * 0.66)
self:removeTemporaryValue("wild_summon", eff.tid)
eff.tid = self:addTemporaryValue("wild_summon", eff.chance)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("wild_summon", eff.tid)
end,
}
newEffect{
name = "LOBOTOMIZED", image = "talents/psychic_lobotomy.png",
desc = "Lobotomized (confused)",
long_desc = function(self, eff) return ("The target's mental faculties have been severely impaired, making it act randomly each turn (%d%% chance) and reducing its cunning by %d."):format(eff.confuse, eff.power/2) end,
type = "mental",
subtype = { confusion=true },
status = "detrimental",
on_gain = function(self, err) return "#Target# higher mental functions have been imparied.", "+Lobotomized" end,
on_lose = function(self, err) return "#Target#'s regains its senses.", "-Lobotomized" end,
parameters = { power=1, confuse=10, dam=1 },
activate = function(self, eff)
DamageType:get(DamageType.MIND).projector(eff.src or self, self.x, self.y, DamageType.MIND, {dam=eff.dam, alwaysHit=true})
eff.confuse = math.floor(math.max(eff.confuse - (self:attr("confusion_immune") or 0) * 100, 10))
eff.confuse = util.bound(eff.confuse, 0, 50) -- Confusion cap of 50%
eff.tmpid = self:addTemporaryValue("confused", eff.confuse)
eff.cid = self:addTemporaryValue("inc_stats", {[Stats.STAT_CUN]=-eff.power/2})
if eff.power <= 0 then eff.dur = 0 end
eff.particles = self:addParticles(engine.Particles.new("generic_power", 1, {rm=100, rM=125, gm=100, gM=125, bm=100, bM=125, am=200, aM=255}))
end,
deactivate = function(self, eff)
self:removeTemporaryValue("confused", eff.tmpid)
self:removeTemporaryValue("inc_stats", eff.cid)
if eff.particles then self:removeParticles(eff.particles) end
if self == game.player and self.updateMainShader then self:updateMainShader() end
end,
}
newEffect{
name = "PSIONIC_SHIELD", image = "talents/kinetic_shield.png",
desc = "Psionic Shield",
display_desc = function(self, eff) return eff.kind:capitalize().." Psionic Shield" end,
long_desc = function(self, eff) return ("Reduces all incoming %s damage by %d."):format(eff.what, eff.power) end,
type = "mental",
subtype = { psionic=true, shield=true },
status = "beneficial",
parameters = { power=10, kind="kinetic" },
activate = function(self, eff)
if eff.kind == "kinetic" then
eff.sid = self:addTemporaryValue("flat_damage_armor", {[DamageType.PHYSICAL] = eff.power, [DamageType.ACID] = eff.power})
eff.what = "physical and acid"
elseif eff.kind == "thermal" then
eff.sid = self:addTemporaryValue("flat_damage_armor", {[DamageType.FIRE] = eff.power, [DamageType.COLD] = eff.power})
eff.what = "fire and cold"
elseif eff.kind == "charged" then
eff.sid = self:addTemporaryValue("flat_damage_armor", {[DamageType.LIGHTNING] = eff.power, [DamageType.BLIGHT] = eff.power})
eff.what = "lightning and blight"
end
end,
deactivate = function(self, eff)
if eff.sid then
self:removeTemporaryValue("flat_damage_armor", eff.sid)
end
end,
}
newEffect{
name = "CLEAR_MIND", image = "talents/mental_shielding.png",
desc = "Clear Mind",
long_desc = function(self, eff) return ("Nullifies the next %d detrimental mental effects."):format(self.mental_negative_status_effect_immune) end,
type = "mental",
subtype = { psionic=true, },
status = "beneficial",
parameters = { power=2 },
activate = function(self, eff)
self.mental_negative_status_effect_immune = eff.power
eff.particles = self:addParticles(engine.Particles.new("generic_power", 1, {rm=0, rM=0, gm=100, gM=180, bm=180, bM=255, am=200, aM=255}))
end,
deactivate = function(self, eff)
self.mental_negative_status_effect_immune = nil
self:removeParticles(eff.particles)
end,
}
newEffect{
name = "RESONANCE_FIELD", image = "talents/resonance_field.png",
desc = "Resonance Field",
long_desc = function(self, eff) return ("The target is surrounded by a psychic field, absorbing 50%% of all damage (up to %d/%d)."):format(self.resonance_field_absorb, eff.power) end,
type = "mental",
subtype = { psionic=true, shield=true },
status = "beneficial",
parameters = { power=100 },
on_gain = function(self, err) return "A psychic field forms around #target#.", "+Resonance Shield" end,
on_lose = function(self, err) return "The psychic field around #target# crumbles.", "-Resonance Shield" end,
damage_feedback = function(self, eff, src, value)
if eff.particle and eff.particle._shader and eff.particle._shader.shad and src and src.x and src.y then
local r = -rng.float(0.2, 0.4)
local a = math.atan2(src.y - self.y, src.x - self.x)
eff.particle._shader:setUniform("impact", {math.cos(a) * r, math.sin(a) * r})
eff.particle._shader:setUniform("impact_tick", core.game.getTime())
end
end,
activate = function(self, eff)
self.resonance_field_absorb = eff.power
eff.sid = self:addTemporaryValue("resonance_field", eff.power)
if core.shader.active(4) then
eff.particle = self:addParticles(Particles.new("shader_shield", 1, {size_factor=1.1}, {type="shield", time_factor=-8000, llpow=1, aadjust=7, color={1, 1, 0}}))
-- eff.particle = self:addParticles(Particles.new("shader_shield", 1, {img="shield2", size_factor=1.25}, {type="shield", time_factor=6000, color={1, 1, 0}}))
else
eff.particle = self:addParticles(Particles.new("generic_shield", 1, {r=1, g=1, b=0, a=1}))
end
end,
deactivate = function(self, eff)
self.resonance_field_absorb = nil
self:removeParticles(eff.particle)
self:removeTemporaryValue("resonance_field", eff.sid)
end,
}
newEffect{
name = "MIND_LINK_TARGET", image = "talents/mind_link.png",
desc = "Mind Link",
long_desc = function(self, eff) return ("The target's mind has been invaded, increasing all mind damage it receives from %s by %d%%."):format(eff.src.name:capitalize(), eff.power) end,
type = "mental",
subtype = { psionic=true },
status = "detrimental",
parameters = {power = 1, range = 5},
remove_on_clone = true, decrease = 0,
on_gain = function(self, err) return "#Target#'s mind has been invaded!", "+Mind Link" end,
on_lose = function(self, err) return "#Target# is free from the mental invasion.", "-Mind Link" end,
on_timeout = function(self, eff)
-- Remove the mind link when appropriate
local p = eff.src:isTalentActive(eff.src.T_MIND_LINK)
if not p or p.target ~= self or eff.src.dead or not game.level:hasEntity(eff.src) or core.fov.distance(self.x, self.y, eff.src.x, eff.src.y) > eff.range then
self:removeEffect(self.EFF_MIND_LINK_TARGET)
end
end,
}
newEffect{
name = "FEEDBACK_LOOP", image = "talents/feedback_loop.png",
desc = "Feedback Loop",
long_desc = function(self, eff) return "The target is gaining feedback." end,
type = "mental",
subtype = { psionic=true },
status = "beneficial",
parameters = { power = 1 },
on_gain = function(self, err) return "#Target# is gaining feedback.", "+Feedback Loop" end,
on_lose = function(self, err) return "#Target# is no longer gaining feedback.", "-Feedback Loop" end,
activate = function(self, eff)
eff.particle = self:addParticles(Particles.new("ultrashield", 1, {rm=255, rM=255, gm=180, gM=255, bm=0, bM=0, am=35, aM=90, radius=0.2, density=15, life=28, instop=40}))
end,
deactivate = function(self, eff)
self:removeParticles(eff.particle)
end,
}
newEffect{
name = "FOCUSED_WRATH", image = "talents/focused_wrath.png",
desc = "Focused Wrath",
long_desc = function(self, eff) return ("The target's subconscious has focused its attention on %s."):format(eff.target.name:capitalize()) end,
type = "mental",
subtype = { psionic=true },
status = "beneficial",
parameters = { power = 1 },
on_gain = function(self, err) return "#Target#'s subconscious has been focused.", "+Focused Wrath" end,
on_lose = function(self, err) return "#Target#'s subconscious has returned to normal.", "-Focused Wrath" end,
on_timeout = function(self, eff)
if not eff.target or eff.target.dead or not game.level:hasEntity(eff.target) then
self:removeEffect(self.EFF_FOCUSED_WRATH)
end
end,
}
newEffect{
name = "SLEEP", image = "talents/sleep.png",
desc = "Sleep",
long_desc = function(self, eff) return ("The target is asleep and unable to act. Every %d damage it takes will reduce the duration of the effect by one turn."):format(eff.power) end,
type = "mental",
subtype = { sleep=true },
status = "detrimental",
parameters = { power=1, insomnia=1, waking=0, contagious=0 },
on_gain = function(self, err) return "#Target# has been put to sleep.", "+Sleep" end,
on_lose = function(self, err) return "#Target# is no longer sleeping.", "-Sleep" end,
on_timeout = function(self, eff)
local dream_prison = false
if eff.src and eff.src.isTalentActive and eff.src:isTalentActive(eff.src.T_DREAM_PRISON) then
local t = eff.src:getTalentFromId(eff.src.T_DREAM_PRISON)
if core.fov.distance(self.x, self.y, eff.src.x, eff.src.y) <= eff.src:getTalentRange(t) then
dream_prison = true
end
end
if dream_prison then
eff.dur = eff.dur + 1
if not eff.particle then
if core.shader.active(4) then
eff.particle = self:addParticles(Particles.new("shader_shield", 1, {img="shield2", size_factor=1.25}, {type="shield", time_factor=6000, aadjust=5, color={0, 1, 1}}))
else
eff.particle = self:addParticles(Particles.new("generic_shield", 1, {r=0, g=1, b=1, a=1}))
end
end
elseif eff.contagious > 0 and eff.dur > 1 then
local t = eff.src:getTalentFromId(eff.src.T_SLEEP)
t.doContagiousSleep(eff.src, self, eff, t)
end
if eff.particle and not dream_prison then
self:removeParticles(eff.particle)
end
-- Incriment Insomnia Duration
if not self:attr("lucid_dreamer") then
self:setEffect(self.EFF_INSOMNIA, 1, {power=eff.insomnia})
end
end,
activate = function(self, eff)
eff.sid = self:addTemporaryValue("sleep", 1)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("sleep", eff.sid)
if not self:attr("sleep") and not self.dead and game.level:hasEntity(self) and eff.waking > 0 then
local t = eff.src:getTalentFromId(self.T_RESTLESS_NIGHT)
t.doRestlessNight(eff.src, self, eff.waking)
end
if eff.particle then
self:removeParticles(eff.particle)
end
end,
}
newEffect{
name = "SLUMBER", image = "talents/slumber.png",
desc = "Slumber",
long_desc = function(self, eff) return ("The target is in a deep sleep and unable to act. Every %d damage it takes will reduce the duration of the effect by one turn."):format(eff.power) end,
type = "mental",
subtype = { sleep=true },
status = "detrimental",
parameters = { power=1, insomnia=1, waking=0 },
on_gain = function(self, err) return "#Target# is in a deep sleep.", "+Slumber" end,
on_lose = function(self, err) return "#Target# is no longer sleeping.", "-Slumber" end,
on_timeout = function(self, eff)
local dream_prison = false
if eff.src and eff.src.isTalentActive and eff.src:isTalentActive(eff.src.T_DREAM_PRISON) then
local t = eff.src:getTalentFromId(eff.src.T_DREAM_PRISON)
if core.fov.distance(self.x, self.y, eff.src.x, eff.src.y) <= eff.src:getTalentRange(t) then
dream_prison = true
end
end
if dream_prison then
eff.dur = eff.dur + 1
if not eff.particle then
if core.shader.active(4) then
eff.particle = self:addParticles(Particles.new("shader_shield", 1, {img="shield2", size_factor=1.25}, {type="shield", time_factor=6000, aadjust=5, color={0, 1, 1}}))
else
eff.particle = self:addParticles(Particles.new("generic_shield", 1, {r=0, g=1, b=1, a=1}))
end
end
elseif eff.particle and not dream_prison then
self:removeParticles(eff.particle)
end
-- Incriment Insomnia Duration
if not self:attr("lucid_dreamer") then
self:setEffect(self.EFF_INSOMNIA, 1, {power=eff.insomnia})
end
end,
activate = function(self, eff)
eff.sid = self:addTemporaryValue("sleep", 1)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("sleep", eff.sid)
if not self:attr("sleep") and not self.dead and game.level:hasEntity(self) and eff.waking > 0 then
local t = eff.src:getTalentFromId(self.T_RESTLESS_NIGHT)
t.doRestlessNight(eff.src, self, eff.waking)
end
if eff.particle then
self:removeParticles(eff.particle)
end
end,
}
newEffect{
name = "NIGHTMARE", image = "talents/nightmare.png",
desc = "Nightmare",
long_desc = function(self, eff) return ("The target is in a nightmarish sleep, suffering %0.2f mind damage each turn and unable to act. Every %d damage it takes will reduce the duration of the effect by one turn."):format(eff.dam, eff.power) end,
type = "mental",
subtype = { nightmare=true, sleep=true },
status = "detrimental",
parameters = { power=1, dam=0, insomnia=1, waking=0},
on_gain = function(self, err) return "#F53CBE##Target# is lost in a nightmare.", "+Nightmare" end,
on_lose = function(self, err) return "#Target# is free from the nightmare.", "-Nightmare" end,
on_timeout = function(self, eff)
local dream_prison = false
if eff.src and eff.src.isTalentActive and eff.src:isTalentActive(eff.src.T_DREAM_PRISON) then
local t = eff.src:getTalentFromId(eff.src.T_DREAM_PRISON)
if core.fov.distance(self.x, self.y, eff.src.x, eff.src.y) <= eff.src:getTalentRange(t) then
dream_prison = true
end
end
if dream_prison then
eff.dur = eff.dur + 1
if not eff.particle then
if core.shader.active(4) then
eff.particle = self:addParticles(Particles.new("shader_shield", 1, {img="shield2", size_factor=1.25}, {type="shield", aadjust=5, color={0, 1, 1}}))
else
eff.particle = self:addParticles(Particles.new("generic_shield", 1, {r=0, g=1, b=1, a=1}))
end
end
else
-- Store the power for later
local real_power = eff.temp_power or eff.power
-- Temporarily spike the temp_power so the nightmare doesn't break it
eff.temp_power = 10000
DamageType:get(DamageType.DARKNESS).projector(eff.src or self, self.x, self.y, DamageType.DARKNESS, eff.dam)
-- Set the power back to its baseline
eff.temp_power = real_power
end
if eff.particle and not dream_prison then
self:removeParticles(eff.particle)
end
-- Incriment Insomnia Duration
if not self:attr("lucid_dreamer") then
self:setEffect(self.EFF_INSOMNIA, 1, {power=eff.insomnia})
end
end,
activate = function(self, eff)
eff.sid = self:addTemporaryValue("sleep", 1)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("sleep", eff.sid)
if not self:attr("sleep") and not self.dead and game.level:hasEntity(self) and eff.waking > 0 then
local t = eff.src:getTalentFromId(self.T_RESTLESS_NIGHT)
t.doRestlessNight(eff.src, self, eff.waking)
end
if eff.particle then
self:removeParticles(eff.particle)
end
end,
}
newEffect{
name = "RESTLESS_NIGHT", image = "talents/restless_night.png",
desc = "Restless Night",
long_desc = function(self, eff) return ("Fatigue from poor sleep, dealing %0.2f mind damage per turn."):format(eff.power) end,
type = "mental",
subtype = { psionic=true},
status = "detrimental",
parameters = { power=1 },
on_gain = function(self, err) return "#Target# had a restless night.", "+Restless Night" end,
on_lose = function(self, err) return "#Target# has recovered from poor sleep.", "-Restless Night" end,
on_merge = function(self, old_eff, new_eff)
-- Merge the flames!
local olddam = old_eff.power * old_eff.dur
local newdam = new_eff.power * new_eff.dur
local dur = math.ceil((old_eff.dur + new_eff.dur) / 2)
old_eff.dur = dur
old_eff.power = (olddam + newdam) / dur
return old_eff
end,
on_timeout = function(self, eff)
DamageType:get(DamageType.MIND).projector(eff.src or self, self.x, self.y, DamageType.MIND, eff.power)
end,
}
newEffect{
name = "INSOMNIA", image = "effects/insomnia.png",
desc = "Insomnia",
long_desc = function(self, eff) return ("The target is wide awake and has %d%% resistance to sleep effects."):format(eff.cur_power) end,
type = "mental",
subtype = { psionic=true },
status = "beneficial",
parameters = { power=0 },
on_gain = function(self, err) return "#Target# is suffering from insomnia.", "+Insomnia" end,
on_lose = function(self, err) return "#Target# is no longer suffering from insomnia.", "-Insomnia" end,
on_merge = function(self, old_eff, new_eff)
-- Add the durations on merge
local dur = old_eff.dur + new_eff.dur
old_eff.dur = math.min(10, dur)
old_eff.cur_power = old_eff.power * old_eff.dur
-- Need to remove and re-add the effect
self:removeTemporaryValue("sleep_immune", old_eff.sid)
old_eff.sid = self:addTemporaryValue("sleep_immune", old_eff.cur_power/100)
return old_eff
end,
on_timeout = function(self, eff)
-- Insomnia only ticks when we're awake
if self:attr("sleep") and self:attr("sleep") > 0 then
eff.dur = eff.dur + 1
else
-- Deincrement the power
eff.cur_power = eff.power * eff.dur
self:removeTemporaryValue("sleep_immune", eff.sid)
eff.sid = self:addTemporaryValue("sleep_immune", eff.cur_power/100)
end
end,
activate = function(self, eff)
eff.cur_power = eff.power * eff.dur
eff.sid = self:addTemporaryValue("sleep_immune", eff.cur_power/100)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("sleep_immune", eff.sid)
end,
}
newEffect{
name = "SUNDER_MIND", image = "talents/sunder_mind.png",
desc = "Sundered Mind",
long_desc = function(self, eff) return ("The target's mental faculties have been impaired, reducing its mental save by %d."):format(eff.cur_power or eff.power) end,
type = "mental",
subtype = { psionic=true },
status = "detrimental",
on_gain = function(self, err) return "#Target#'s mental functions have been impaired.", "+Sundered Mind" end,
on_lose = function(self, err) return "#Target# regains its senses.", "-Sundered Mind" end,
parameters = { power=10 },
on_merge = function(self, old_eff, new_eff)
self:removeTemporaryValue("combat_mentalresist", old_eff.sunder)
old_eff.cur_power = old_eff.cur_power + new_eff.power
old_eff.sunder = self:addTemporaryValue("combat_mentalresist", -old_eff.cur_power)
old_eff.dur = new_eff.dur
return old_eff
end,
activate = function(self, eff)
eff.cur_power = eff.power
eff.sunder = self:addTemporaryValue("combat_mentalresist", -eff.power)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("combat_mentalresist", eff.sunder)
end,
}
newEffect{
name = "BROKEN_DREAM", image = "effects/broken_dream.png",
desc = "Broken Dream",
long_desc = function(self, eff) return ("The target's dreams have been broken by the dreamforge, reducing its mental save by %d and reducing its chance of successfully casting a spell by %d%%."):format(eff.power, eff.fail) end,
type = "mental",
subtype = { psionic=true, morale=true },
status = "detrimental",
on_gain = function(self, err) return "#Target#'s dreams have been broken.", "+Broken Dream" end,
on_lose = function(self, err) return "#Target# regains hope.", "-Broken Dream" end,
parameters = { power=10, fail=10 },
activate = function(self, eff)
eff.silence = self:addTemporaryValue("spell_failure", eff.fail)
eff.sunder = self:addTemporaryValue("combat_mentalresist", -eff.power)
end,
deactivate = function(self, eff)
self:removeTemporaryValue("spell_failure", eff.silence)
self:removeTemporaryValue("combat_mentalresist", eff.sunder)
end,
}
newEffect{
name = "FORGE_SHIELD", image = "talents/block.png",
desc = "Forge Shield",
long_desc = function(self, eff)
local e_string = ""
if eff.number == 1 then
e_string = DamageType.dam_def[next(eff.d_types)].name
else
local list = table.keys(eff.d_types)
for i = 1, #list do
list[i] = DamageType.dam_def[list[i]].name
end
e_string = table.concat(list, ", ")
end
local function tchelper(first, rest)
return first:upper()..rest:lower()
end
return ("Absorbs %d damage from the next blockable attack. Currently Blocking: %s."):format(eff.power, e_string:gsub("(%a)([%w_']*)", tchelper))
end,
type = "mental",
subtype = { psionic=true },
status = "beneficial",
parameters = { power=1 },
on_gain = function(self, eff) return nil, nil end,
on_lose = function(self, eff) return nil, nil end,
damage_feedback = function(self, eff, src, value)
if eff.particle and eff.particle._shader and eff.particle._shader.shad and src and src.x and src.y then
local r = -rng.float(0.2, 0.4)
local a = math.atan2(src.y - self.y, src.x - self.x)
eff.particle._shader:setUniform("impact", {math.cos(a) * r, math.sin(a) * r})
eff.particle._shader:setUniform("impact_tick", core.game.getTime())
end
end,
activate = function(self, eff)
if core.shader.active(4) then
eff.particle = self:addParticles(Particles.new("shader_shield", 1, {size_factor=1.1}, {type="shield", time_factor=-8000, llpow=1, aadjust=7, color={1, 0.5, 0}}))
else
eff.particle = self:addParticles(Particles.new("generic_shield", 1, {r=1, g=0.5, b=0.0, a=1}))
end
end,
deactivate = function(self, eff)
self:removeParticles(eff.particle)
end,
}
newEffect{
name = "DRACONIC_WILL", image = "talents/draconic_will.png",
desc = "Draconic Will",
long_desc = function(self, eff) return "The target is immune to all detrimental effects." end,
type = "mental",
subtype = { nature=true },
status = "beneficial",
on_gain = function(self, err) return "#Target#'s skin hardens.", "+Draconic Will" end,
on_lose = function(self, err) return "#Target#'s skin is back to normal.", "-Draconic Will" end,
parameters = { },
activate = function(self, eff)
self:effectTemporaryValue(eff, "negative_status_effect_immune", 1)
end,
}
newEffect{
name = "HIDDEN_RESOURCES", image = "talents/hidden_resources.png",
desc = "Hidden Resources",
long_desc = function(self, eff) return "The target does not consume any resources." end,
type = "mental",
subtype = { willpower=true },
status = "beneficial",
on_gain = function(self, err) return "#Target#'s focuses.", "+Hidden Ressources" end,
on_lose = function(self, err) return "#Target#'s loses some focus.", "-Hidden Ressources" end,
parameters = { },
activate = function(self, eff)
self:effectTemporaryValue(eff, "force_talent_ignore_ressources", 1)
end,
}
newEffect{
name = "SPELL_FEEDBACK", image = "talents/spell_feedback.png",
desc = "Spell Feedback",
long_desc = function(self, eff) return ("The target suffers %d%% spell failue."):format(eff.power) end,
type = "mental",
subtype = { nature=true },
status = "detrimental",
on_gain = function(self, err) return "#Target# is surrounded by antimagic forces.", "+Spell Feedback" end,
on_lose = function(self, err) return "#Target#'s antimagic forces vanishes.", "-Spell Feedback" end,
parameters = { power=40 },
activate = function(self, eff)
self:effectTemporaryValue(eff, "spell_failure", eff.power)
end,
}
newEffect{
name = "MIND_PARASITE", image = "talents/mind_parasite.png",
desc = "Mind Parasite",
long_desc = function(self, eff) return ("The target is infected with a mind parasite. Each time it uses a talent it has a %d%% chance to have %d random talent(s) put on cooldown for %d turns."):format(eff.chance, eff.nb, eff.turns) end,
type = "mental",
subtype = { nature=true, mind=true },
status = "detrimental",
on_gain = function(self, err) return "#Target# is infected with a mind parasite.", "+Mind Parasite" end,
on_lose = function(self, err) return "#Target# is free from the mind parasite.", "-Mind Parasite" end,
parameters = { chance=40, nb=1, turns=2 },
activate = function(self, eff)
self:effectTemporaryValue(eff, "random_talent_cooldown_on_use", eff.chance)
self:effectTemporaryValue(eff, "random_talent_cooldown_on_use_nb", eff.nb)
self:effectTemporaryValue(eff, "random_talent_cooldown_on_use_turns", eff.turns)
end,
}
newEffect{
name = "MINDLASH", image = "talents/mindlash.png",
desc = "Mindlash",
long_desc = function(self, eff) return ("Repeated mindlash usage is very taxing increasing the psi cost each time (currently %d%%)"):format(eff.power * 100) end,
type = "mental",
subtype = { mind=true },
status = "detrimental",
parameters = { },
on_merge = function(self, old_eff, new_eff)
new_eff.power = old_eff.power + 1
return new_eff
end,
activate = function(self, eff)
eff.power = 2
end,
}
newEffect{
name = "SHADOW_EMPATHY", image = "talents/shadow_empathy.png",
desc = "Shadow Empathy",
long_desc = function(self, eff) return ("%d%% of all damage is redirected to a random shadow."):format(eff.power) end,
type = "mental",
subtype = { mind=true, shield=true },
status = "beneficial",
parameters = { power=10 },
activate = function(self, eff)
self:effectTemporaryValue(eff, "shadow_empathy", eff.power)
eff.particle = self:addParticles(Particles.new("darkness_power", 1))
end,
deactivate = function(self, eff)
self:removeParticles(eff.particle)
end,
}
newEffect{
name = "SHADOW_DECOY", image = "talents/shadow_decoy.png",
desc = "Shadow Decoy",
long_desc = function(self, eff) return ("A random shadow absorbed a fatal blow for you, granting you a negative shield of %d."):format(eff.power) end,
type = "mental",
subtype = { mind=true, shield=true },
status = "beneficial",
parameters = { power=10 },
activate = function(self, eff)
self:effectTemporaryValue(eff, "die_at", -eff.power)
eff.particle = self:addParticles(Particles.new("darkness_power", 1))
end,
deactivate = function(self, eff)
self:removeParticles(eff.particle)
end,
}
| gpl-3.0 |
ibm2431/darkstar | scripts/zones/Balgas_Dais/bcnms/treasure_and_tribulations.lua | 9 | 1073 | -----------------------------------
-- Treasure and Tribulations
-- Balga's Dais BCNM50, Comet Orb
-- !additem 1177
-----------------------------------
require("scripts/globals/battlefield")
-----------------------------------
function onBattlefieldInitialise(battlefield)
battlefield:setLocalVar("loot", 1)
end
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), 0)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
| gpl-3.0 |
greasydeal/darkstar | scripts/zones/Al_Zahbi/npcs/Zafif.lua | 36 | 1695 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Zafif
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
require("scripts/zones/Al_Zahbi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,ZAFIF_SHOP_DIALOG);
stock = {0x1204,23400, -- Scroll of Cure IV
0x1208,11200, -- Scroll of Curaga II
0x1209,19932, -- Scroll of Curaga III
0x122D,32000, -- Scroll of Protect III
0x122E,91116, -- Scroll of Protect IV
0x1280,85500, -- Scroll of Protectra IV
0x1215,35000, -- Scroll of Holy
0x1227,20000, -- Scroll of Banishga II
0x1211,2330, -- Scroll of Silena
0x1212,19200, -- Scroll of Stona
0x1213,13300, -- Scroll of Viruna
0x1214,8586, -- Scroll of Cursna
0x1304,77600, -- Scroll of Dispell
0x1270,27000, -- Scroll of Flash
0x128E,99375, -- Scroll of Reraise III
0x126B,28500} -- Scroll of Reprisal
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 |
Codex-NG/otxserver | data/npc/scripts/bless.lua | 28 | 2641 | local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
local node1 = keywordHandler:addKeyword({'first bless'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you want to buy the first blessing for 10000 gold?'})
node1:addChildKeyword({'yes'}, StdModule.bless, {npcHandler = npcHandler, bless = 1, premium = true, cost = 10000})
node1:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Too expensive, eh?'})
local node2 = keywordHandler:addKeyword({'second bless'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you want to buy the second blessing for 10000 gold?'})
node2:addChildKeyword({'yes'}, StdModule.bless, {npcHandler = npcHandler, bless = 2, premium = true, cost = 10000})
node2:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Too expensive, eh?'})
local node3 = keywordHandler:addKeyword({'third bless'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you want to buy the third blessing for 10000 gold?'})
node3:addChildKeyword({'yes'}, StdModule.bless, {npcHandler = npcHandler, bless = 3, premium = true, cost = 10000})
node3:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Too expensive, eh?'})
local node4 = keywordHandler:addKeyword({'fourth bless'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you want to buy the fourth blessing for 10000 gold?'})
node4:addChildKeyword({'yes'}, StdModule.bless, {npcHandler = npcHandler, bless = 4, premium = true, cost = 10000})
node4:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Too expensive, eh?'})
local node5 = keywordHandler:addKeyword({'fifth bless'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you want to buy the fifth blessing for 10000 gold?'})
node5:addChildKeyword({'yes'}, StdModule.bless, {npcHandler = npcHandler, bless = 5, premium = true, cost = 10000})
node5:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Too expensive, eh?'})
npcHandler:addModule(FocusModule:new()) | gpl-2.0 |
ibm2431/darkstar | scripts/globals/mobskills/tourbillion.lua | 11 | 1465 | ---------------------------------------------
-- Tourbillion
--
-- Description: Delivers an area attack. Additional effect duration varies with TP. Additional effect: Weakens defense.
-- Type: Physical
-- Shadow per hit
-- Range: Unknown range
---------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if(mob:getFamily() == 316) then
local mobSkin = mob:getModelId()
if (mobSkin == 1805) then
return 0
else
return 1
end
end
--[[TODO: Khimaira should only use this when its wings are up, which is animationsub() == 0.
There's no system to put them "down" yet, so it's not really fair to leave it active.
Tyger's fair game, though. :)]]
return 0
end
function onMobWeaponSkill(target, mob, skill)
local numhits = 3
local accmod = 1
local dmgmod = 1.5
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.SLASHING,info.hitslanded)
local duration = 20 * (skill:getTP() / 1000)
MobPhysicalStatusEffectMove(mob, target, skill, dsp.effect.DEFENSE_DOWN, 20, 0, duration)
target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.SLASHING)
return dmg
end
| gpl-3.0 |
chanko08/KillerLibrarian2 | systems/player.lua | 2 | 4418 | local player = {}
player.assets = {
walk = {
path="assets/gfx/player_walk.png",
frame_width=36,
frames='1-6'
},
default = {
path="assets/gfx/player_stand.png",
frame_width=32,
frames=1
},
shoot = {
path="assets/gfx/player_fire.png",
frame_width=38,
frames=1
},
}
player.sound = {
hurt = love.audio.newSource("assets/sfx/Hit_Hurt.wav", "static"),
shoot = love.audio.newSource("assets/sfx/Laser_Shoot.wav", "static"),
jump = love.audio.newSource("assets/sfx/Jump.wav", "static")
}
player.controller = tiny.processingSystem()
player.controller.filter = tiny.requireAll('Player')
player.controller.keyboard = true
local function handle_keyboard_down(entity, key)
if key =='left' then
entity.vel.x = -entity.lateral_speed
entity.facing = key
animation.switch(entity, 'walk', true)
end
if key =='right' then
entity.vel.x = entity.lateral_speed
entity.facing = key
animation.switch(entity, 'walk')
end
if key=='up' then
entity.looking_up = true
end
if key == ' ' and not entity.jumping then
player.sound.jump:rewind()
player.sound.jump:play()
entity.vel.y = entity.jump_speed
entity.jumping = true
entity.ignore_next_ground_hit = true
animation.switch(entity, 'jump')
end
if key == 'lctrl' then
--default to shooting
player.sound.shoot:rewind()
player.sound.shoot:play()
local librarycard = librarycard.new(entity)
tiny.addEntity(ecs, librarycard)
if entity.vel.x == 0 then
local mir = true
if entity.facing == 'right' then
mir = false
end
animation.switch(entity, 'shoot', mir)
end
end
end
local function handle_keyboard_up(entity, key)
if key =='left' then
if entity.vel.x < 0 then
entity.vel.x = 0
animation.switch(entity, 'default', true)
end
end
if key =='right' then
if entity.vel.x > 0 then
entity.vel.x = 0
animation.switch(entity, 'default')
end
end
if key=='up' then
entity.looking_up = false
end
if key == 'lctrl' then
if entity.vel.x == 0 then
local mir = true
if entity.facing == 'right' then
mir = false
end
animation.switch(entity, 'default', mir)
end
end
end
function player.controller:process(entity, control)
if control.key and control.isDown then
handle_keyboard_down(entity, control.key)
elseif control.key then
handle_keyboard_up(entity, control.key)
end
end
player.system = tiny.processingSystem()
player.system.filter = tiny.requireAll('Player')
function player.system:process(entity, dt)
if entity.collision.num_cols > 0 then
-- check if we hit the ground
for i,col in ipairs(entity.collision.cols) do
if col.normal.y < 0 and not entity.ignore_next_ground_hit then
entity.jumping = false
else
entity.ignore_next_ground_hit = false
end
if col.other.enemy and entity.can_be_hurt then
player.sound.hurt:play()
entity.health = entity.health - 4
entity.can_be_hurt = false
Timer.add(0.5, function() entity.can_be_hurt=true end)
end
end
end
if entity.book_count == 0 then
if entity.next_level_id == 0 then
switch_state(game_win_state)
return
else
switch_state(level_state, entity.next_level_id)
end
end
if entity.health <= 0 then
switch_state(game_over_state, entity.next_level_id - 1)
end
end
function player.new(map, obj)
--set up position of player correctly
local x = math.floor(obj.x / map.tilewidth) * map.tilewidth
local y = (math.floor(obj.y / map.tileheight) - 1) * map.tileheight
collision.new(
animation.new(
player.assets,
obj
),
x,
y,
32,
64,
function(player, other)
if other.enemy or other.Book then
return 'cross'
end
return 'slide'
end
)
obj.jump_speed = -400
obj.lateral_speed = 200
obj.keyboard = true
obj.max_fall_speed = 500
obj.jumping = true
obj.facing = 'right'
obj.looking_up = false
obj.health = 100
print('TOTAL BOOKS!', map.properties.book_count)
obj.total_books = map.properties.book_count
obj.book_count = map.properties.book_count
obj.next_level_id = map.properties.next_level or 0
obj.score = 0
obj.can_be_hurt = true
camera = Camera(map, obj)
return obj
end
return player
| mit |
ibm2431/darkstar | scripts/globals/spells/freeze_ii.lua | 6 | 1267 | -----------------------------------------
-- Spell: Freeze II
-- Deals ice damage to an enemy and lowers its resistance against fire.
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/magic")
-----------------------------------------
function onMagicCastingCheck(caster, target, spell)
return 0
end
function onSpellCast(caster, target, spell)
local spellParams = {}
spellParams.hasMultipleTargetReduction = false
spellParams.resistBonus = 1.0
spellParams.V = 710
spellParams.V0 = 800
spellParams.V50 = 900
spellParams.V100 = 1000
spellParams.V200 = 1200
spellParams.M = 2
spellParams.M0 = 2
spellParams.M50 = 2
spellParams.M100 = 2
spellParams.M200 = 2
spellParams.I = 780
if (caster:getMerit(dsp.merit.FREEZE_II) ~= 0) then
spellParams.AMIIburstBonus = (caster:getMerit(dsp.merit.FREEZE_II) - 1) * 0.03
spellParams.AMIIaccBonus = (caster:getMerit(dsp.merit.FREEZE_II) - 1) * 5
end
-- no point in making a separate function for this if the only thing they won't have in common is the name
handleNinjutsuDebuff(caster,target,spell,30,10,dsp.mod.FIRERES)
return doElementalNuke(caster, spell, target, spellParams)
end
| gpl-3.0 |
LegionXI/darkstar | scripts/zones/Periqia/IDs.lua | 8 | 4247 | Periqia = {
text = {
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6378, -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6381, -- Obtained: <item>
GIL_OBTAINED = 6384, -- Obtained <number> gil
KEYITEM_OBTAINED = 6384, -- Obtained key item: <keyitem>
-- Assault Texts
ASSAULT_31_START = 7447,
ASSAULT_32_START = 7448,
ASSAULT_33_START = 7449,
ASSAULT_34_START = 7450,
ASSAULT_35_START = 7451,
ASSAULT_36_START = 7452,
ASSAULT_37_START = 7453,
ASSAULT_38_START = 7454,
ASSAULT_39_START = 7455,
ASSAULT_40_START = 7456,
TIME_TO_COMPLETE = 7477,
MISSION_FAILED = 7478,
RUNE_UNLOCKED_POS = 7479,
RUNE_UNLOCKED = 7480,
ASSAULT_POINTS_OBTAINED = 7481,
TIME_REMAINING_MINUTES = 7482,
TIME_REMAINING_SECONDS = 7483,
PARTY_FALLEN = 7485,
-- Seagull Grounded
EXCALIACE_START = 7494,
EXCALIACE_END1 = 7495,
EXCALIACE_END2 = 7496,
EXCALIACE_ESCAPE = 7497,
EXCALIACE_PAIN1 = 7498,
EXCALIACE_PAIN2 = 7499,
EXCALIACE_PAIN3 = 7500,
EXCALIACE_PAIN4 = 7501,
EXCALIACE_PAIN5 = 7502,
EXCALIACE_CRAB1 = 7503,
EXCALIACE_CRAB2 = 7504,
EXCALIACE_CRAB3 = 7505,
EXCALIACE_DEBAUCHER1 = 7506,
EXCALIACE_DEBAUCHER2 = 7507,
EXCALIACE_RUN = 7508,
EXCALIACE_TOO_CLOSE = 7509,
EXCALIACE_TIRED = 7510,
EXCALIACE_CAUGHT = 7511,
},
mobs = {
-- Seagull Grounded
[31] = {
CRAB1 = 17006594,
CRAB2 = 17006595,
CRAB3 = 17006596,
CRAB4 = 17006597,
CRAB5 = 17006598,
CRAB6 = 17006599,
CRAB7 = 17006600,
CRAB8 = 17006601,
CRAB9 = 17006602,
DEBAUCHER1 = 17006603,
PUGIL1 = 17006604,
PUGIL2 = 17006605,
PUGIL3 = 17006606,
PUGIL4 = 17006607,
PUGIL5 = 17006608,
DEBAUCHER2 = 17006610,
DEBAUCHER3 = 17006611,
},
-- Shades of Vengeance
[79] = {
K23H1LAMIA1 = 17006754,
K23H1LAMIA2 = 17006755,
K23H1LAMIA3 = 17006756,
K23H1LAMIA4 = 17006757,
K23H1LAMIA5 = 17006758,
K23H1LAMIA6 = 17006759,
K23H1LAMIA7 = 17006760,
K23H1LAMIA8 = 17006761,
K23H1LAMIA9 = 17006762,
K23H1LAMIA10 = 17006763,
}
},
npcs = {
EXCALIACE = 17006593,
ANCIENT_LOCKBOX = 17006809,
RUNE_OF_RELEASE = 17006810,
_1K1 = 17006840,
_1K2 = 17006841,
_1K3 = 17006842,
_1K4 = 17006843,
_1K5 = 17006844,
_1K6 = 17006845,
_1K7 = 17006846,
_1K8 = 17006847,
_1K9 = 17006848,
_1KA = 17006849,
_1KB = 17006850,
_1KC = 17006851,
_1KD = 17006852,
_1KE = 17006853,
_1KF = 17006854,
_1KG = 17006855,
_1KH = 17006856,
_1KI = 17006857,
_1KJ = 17006858,
_1KK = 17006859,
_1KL = 17006860,
_1KM = 17006861,
_1KN = 17006862,
_1KO = 17006863,
_1KP = 17006864,
_1KQ = 17006865,
_1KR = 17006866,
_1KS = 17006867,
_1KT = 17006868,
_1KU = 17006869,
_1KV = 17006870,
_1KW = 17006871,
_1KX = 17006872,
_1KY = 17006873,
_1KZ = 17006874,
_JK0 = 17006875,
_JK1 = 17006876,
_JK2 = 17006877,
_JK3 = 17006878,
_JK4 = 17006879,
_JK5 = 17006880,
_JK6 = 17006881,
_JK7 = 17006882,
_JK8 = 17006883,
_JK9 = 17006884,
_JKA = 17006885,
_JKB = 17006886,
_JKC = 17006887,
_JKD = 17006888,
_JKE = 17006889,
_JKF = 17006890,
_JKG = 17006891,
_JKH = 17006892,
_JKI = 17006893,
_JKJ = 17006894,
_JKK = 17006895,
_JKL = 17006896,
_JKM = 17006897,
_JKN = 17006898,
_JKO = 17006899,
}
}
| gpl-3.0 |
LegionXI/darkstar | scripts/zones/Southern_San_dOria_[S]/npcs/Achtelle.lua | 28 | 1049 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Achtelle
-- @zone 80
-- @pos 108 2 -11
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--player:startEvent(0x01FE); Event doesnt work but this is her default dialogue, threw in something below til it gets fixed
player:showText(npc, 13454); -- (Couldn't find default dialogue) How very good to see you again!
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
LegionXI/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/HomePoint#1.lua | 27 | 1295 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: HomePoint#1
-- @pos -21.129 0.001 -20.944 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 65);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
naclander/tome | game/modules/tome/data/general/objects/scrolls.lua | 1 | 14097 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
newEntity{
define_as = "BASE_SCROLL",
type = "scroll", subtype="scroll",
unided_name = "scroll", id_by_type = true,
display = "?", color=colors.WHITE, image="object/scroll.png",
encumber = 0.1,
stacking = true,
use_sound = "actions/read",
use_no_blind = true,
use_no_silence = true,
fire_destroy = {{10,1}, {20,2}, {40,5}, {60,10}, {120,20}},
desc = [[Magical scrolls can have wildly different effects! Most of them function better with a high Magic score.]],
egos = "/data/general/objects/egos/scrolls.lua", egos_chance = resolvers.mbonus(10, 5),
}
newEntity{
define_as = "BASE_INFUSION",
type = "scroll", subtype="infusion", add_name = " (#INSCRIPTION#)",
unided_name = "infusion", id_by_type = true,
display = "?", color=colors.LIGHT_GREEN, image="object/rune_green.png",
encumber = 0.1,
use_sound = "actions/read",
use_no_blind = true,
use_no_silence = true,
fire_destroy = {{100,1}, {200,2}, {400,5}, {600,10}, {1200,20}},
desc = [[Natural infusions may be grafted onto your body, granting you an on-demand ability.]],
egos = "/data/general/objects/egos/infusions.lua", egos_chance = resolvers.mbonus(30, 5),
material_level_min_only = true,
power_source = {nature=true},
use_simple = { name="inscribe your skin with the infusion.", use = function(self, who, inven, item)
if who:setInscription(nil, self.inscription_talent, self.inscription_data, true, true, {obj=self, inven=inven, item=item}) then
return {used=true, id=true, destroy=true}
end
end}
}
newEntity{
define_as = "BASE_RUNE",
type = "scroll", subtype="rune", add_name = " (#INSCRIPTION#)",
unided_name = "rune", id_by_type = true,
display = "?", color=colors.LIGHT_BLUE, image="object/rune_red.png",
encumber = 0.1,
use_sound = "actions/read",
use_no_blind = true,
use_no_silence = true,
fire_destroy = {{10,1}, {20,2}, {40,5}, {60,10}, {120,20}},
desc = [[Magical runes may be inscribed onto your body, granting you an on-demand ability.]],
egos = "/data/general/objects/egos/infusions.lua", egos_chance = resolvers.mbonus(30, 5),
material_level_min_only = true,
power_source = {arcane=true},
use_simple = { name="inscribe your skin with the rune.", use = function(self, who, inven, item)
if who:setInscription(nil, self.inscription_talent, self.inscription_data, true, true, {obj=self, inven=inven, item=item}) then
return {used=true, id=true, destroy=true}
end
end}
}
newEntity{
define_as = "BASE_TAINT",
type = "scroll", subtype="taint", add_name = " (#INSCRIPTION#)",
unided_name = "taint", id_by_type = true,
display = "?", color=colors.LIGHT_BLUE, image="object/rune_yellow.png",
encumber = 0.1,
use_sound = "actions/read",
use_no_blind = true,
use_no_silence = true,
fire_destroy = {{10,1}, {20,2}, {40,5}, {60,10}, {120,20}},
desc = [[Corrupted taints may be inscribed onto your body, granting you an on-demand ability.]],
egos = "/data/general/objects/egos/infusions.lua", egos_chance = resolvers.mbonus(30, 5),
power_source = {arcane=true},
use_simple = { name="inscribe your skin with the taint.", use = function(self, who, inven, item)
if who:setInscription(nil, self.inscription_talent, self.inscription_data, true, true, {obj=self, inven=inven, item=item}) then
return {used=true, id=true, destroy=true}
end
end}
}
newEntity{
define_as = "BASE_LORE",
type = "lore", subtype="lore", not_in_stores=true, no_unique_lore=true,
unided_name = "scroll", identified=true,
display = "?", color=colors.ANTIQUE_WHITE, image="object/scroll-lore.png",
encumber = 0,
checkFilter = function(self) if self.lore and game.party.lore_known and game.party.lore_known[self.lore] then print('[LORE] refusing', self.lore) return false else return true end end,
desc = [[This parchment contains some lore.]],
}
newEntity{
define_as = "BASE_LORE_RANDOM",
type = "lore", subtype="lore", not_in_stores=true, no_unique_lore=true,
unided_name = "scroll", identified=true,
display = "?", color=colors.ANTIQUE_WHITE, image="object/scroll.png",
encumber = 0,
checkFilter = function(self) if self.lore and game.party.lore_known and game.party.lore_known[self.lore] then print('[LORE] refusing', self.lore) return false else return true end end,
desc = [[This parchment contains some lore.]],
}
-----------------------------------------------------------
-- Infusions
-----------------------------------------------------------
newEntity{ base = "BASE_INFUSION",
name = "healing infusion",
level_range = {7, 50},
rarity = 16,
cost = 10,
material_level = 1,
inscription_kind = "heal",
inscription_data = {
cooldown = resolvers.rngrange(12, 17),
heal = resolvers.mbonus_level(400, 40, function(e, v) return v * 0.06 end),
use_stat_mod = 2.7,
},
inscription_talent = "INFUSION:_HEALING",
}
newEntity{ base = "BASE_INFUSION",
name = "regeneration infusion",
level_range = {1, 50},
rarity = 15,
cost = 10,
material_level = 1,
inscription_kind = "heal",
inscription_data = {
cooldown = resolvers.rngrange(12, 17),
dur = 5,
heal = resolvers.mbonus_level(550, 60, function(e, v) return v * 0.06 end),
use_stat_mod = 3.4,
},
inscription_talent = "INFUSION:_REGENERATION",
}
newEntity{ base = "BASE_INFUSION",
name = "wild infusion",
level_range = {1, 50},
rarity = 13,
cost = 20,
material_level = 1,
inscription_kind = "protect",
inscription_data = resolvers.generic(function(e)
local what = {}
local effects = {physical=true, mental=true, magical=true}
local eff1 = rng.tableIndex(effects)
what[eff1] = true
local two = rng.percent(20) and true or false
if two then
local eff2 = rng.tableIndex(effects, {eff1})
what[eff2] = true
end
return {
cooldown = rng.range(12, 17),
dur = rng.mbonus(4, resolvers.current_level, resolvers.mbonus_max_level) + 4,
power = rng.mbonus(20, resolvers.current_level, resolvers.mbonus_max_level) + 10,
use_stat_mod = 0.1,
what=what,
}
end),
inscription_talent = "INFUSION:_WILD",
}
newEntity{ base = "BASE_INFUSION",
name = "movement infusion",
level_range = {10, 50},
rarity = 15,
cost = 30,
material_level = 3,
inscription_kind = "movement",
inscription_data = {
cooldown = resolvers.rngrange(13, 20),
dur = resolvers.mbonus_level(5, 4, function(e, v) return v * 1 end),
speed = resolvers.mbonus_level(700, 500, function(e, v) return v * 0.001 end),
use_stat_mod = 3,
},
inscription_talent = "INFUSION:_MOVEMENT",
}
newEntity{ base = "BASE_INFUSION",
name = "sun infusion",
level_range = {1, 50},
rarity = 13,
cost = 10,
material_level = 1,
inscription_kind = "attack",
inscription_data = {
cooldown = resolvers.rngrange(9, 15),
range = resolvers.mbonus_level(5, 5, function(e, v) return v * 0.1 end),
turns = resolvers.rngrange(3, 5),
power = resolvers.mbonus_level(5, 20, function(e, v) return v * 0.1 end),
use_stat_mod = 1.2,
},
inscription_talent = "INFUSION:_SUN",
}
newEntity{ base = "BASE_INFUSION",
name = "heroism infusion",
level_range = {25, 50},
rarity = 16,
cost = 40,
material_level = 3,
inscription_kind = "utility",
inscription_data = {
cooldown = resolvers.rngrange(20, 30),
dur = resolvers.mbonus_level(7, 7),
power = resolvers.mbonus_level(4, 4, function(e, v) return v * 3 end),
die_at = resolvers.mbonus_level(700, 100, function(e, v) return v * 0.2 end),
use_stat_mod = 0.14,
},
inscription_talent = "INFUSION:_HEROISM",
}
newEntity{ base = "BASE_INFUSION",
name = "insidious poison infusion",
level_range = {10, 50},
rarity = 16,
cost = 20,
material_level = 2,
inscription_kind = "attack",
inscription_data = {
cooldown = resolvers.rngrange(15, 25),
range = resolvers.mbonus_level(3, 3),
heal_factor = resolvers.mbonus_level(50, 20, function(e, v) return v * 0.1 end),
power = resolvers.mbonus_level(300, 70, function(e, v) return v * 0.1 end),
use_stat_mod = 2,
},
inscription_talent = "INFUSION:_INSIDIOUS_POISON",
}
-----------------------------------------------------------
-- Runes
-----------------------------------------------------------
newEntity{ base = "BASE_RUNE",
name = "phase door rune",
level_range = {1, 50},
rarity = 15,
cost = 10,
material_level = 1,
inscription_kind = "teleport",
inscription_data = {
cooldown = resolvers.rngrange(8, 10),
dur = resolvers.mbonus_level(5, 3),
power = resolvers.mbonus_level(30, 15, function(e, v) return v * 1 end),
range = resolvers.mbonus_level(10, 5, function(e, v) return v * 1 end),
use_stat_mod = 0.07,
},
inscription_talent = "RUNE:_PHASE_DOOR",
}
newEntity{ base = "BASE_RUNE",
name = "controlled phase door rune",
level_range = {35, 50},
rarity = 17,
cost = 50,
material_level = 4,
inscription_kind = "movement",
inscription_data = {
cooldown = resolvers.rngrange(10, 12),
range = resolvers.mbonus_level(6, 5, function(e, v) return v * 3 end),
use_stat_mod = 0.05,
},
inscription_talent = "RUNE:_CONTROLLED_PHASE_DOOR",
}
newEntity{ base = "BASE_RUNE",
name = "teleportation rune",
level_range = {10, 50},
rarity = 15,
cost = 10,
material_level = 2,
inscription_kind = "teleport",
inscription_data = {
cooldown = resolvers.rngrange(14, 19),
range = resolvers.mbonus_level(100, 20, function(e, v) return v * 0.03 end),
use_stat_mod = 1,
},
inscription_talent = "RUNE:_TELEPORTATION",
}
newEntity{ base = "BASE_RUNE",
name = "shielding rune",
level_range = {5, 50},
rarity = 15,
cost = 20,
material_level = 3,
inscription_kind = "protect",
inscription_data = {
cooldown = resolvers.rngrange(14, 24),
dur = resolvers.mbonus_level(5, 3),
power = resolvers.mbonus_level(500, 50, function(e, v) return v * 0.06 end),
use_stat_mod = 3,
},
inscription_talent = "RUNE:_SHIELDING",
}
newEntity{ base = "BASE_RUNE",
name = "invisibility rune",
level_range = {18, 50},
rarity = 19,
cost = 40,
material_level = 3,
inscription_kind = "utility",
inscription_data = {
cooldown = resolvers.rngrange(14, 24),
dur = resolvers.mbonus_level(9, 4, function(e, v) return v * 1 end),
power = resolvers.mbonus_level(8, 7, function(e, v) return v * 1 end),
use_stat_mod = 0.08,
},
inscription_talent = "RUNE:_INVISIBILITY",
}
newEntity{ base = "BASE_RUNE",
name = "vision rune",
level_range = {15, 50},
rarity = 16,
cost = 30,
material_level = 2,
inscription_kind = "detection",
inscription_data = {
cooldown = resolvers.rngrange(20, 30),
range = resolvers.mbonus_level(10, 8),
dur = resolvers.mbonus_level(20, 12),
power = resolvers.mbonus_level(20, 10, function(e, v) return v * 0.3 end),
esp = resolvers.rngtable{"humanoid","demon","dragon","horror","undead","animal"},
use_stat_mod = 0.14,
},
inscription_talent = "RUNE:_VISION",
}
newEntity{ base = "BASE_RUNE",
name = "heat beam rune",
level_range = {25, 50},
rarity = 16,
cost = 20,
material_level = 3,
inscription_kind = "attack",
inscription_data = {
cooldown = resolvers.rngrange(15, 25),
range = resolvers.mbonus_level(5, 4),
power = resolvers.mbonus_level(300, 60, function(e, v) return v * 0.1 end),
use_stat_mod = 1.8,
},
inscription_talent = "RUNE:_HEAT_BEAM",
}
newEntity{ base = "BASE_RUNE",
name = "frozen spear rune",
level_range = {25, 50},
rarity = 16,
cost = 20,
material_level = 3,
inscription_kind = "attack",
inscription_data = {
cooldown = resolvers.rngrange(15, 25),
range = resolvers.mbonus_level(5, 4),
power = resolvers.mbonus_level(300, 60, function(e, v) return v * 0.1 end),
use_stat_mod = 1.8,
},
inscription_talent = "RUNE:_FROZEN_SPEAR",
}
newEntity{ base = "BASE_RUNE",
name = "acid wave rune",
level_range = {25, 50},
rarity = 16,
cost = 20,
material_level = 3,
inscription_kind = "attack",
inscription_data = {
cooldown = resolvers.rngrange(15, 25),
range = resolvers.mbonus_level(3, 2),
power = resolvers.mbonus_level(250, 40, function(e, v) return v * 0.1 end),
reduce = resolvers.mbonus_level(25, 10),
use_stat_mod = 1.8,
},
inscription_talent = "RUNE:_ACID_WAVE",
}
newEntity{ base = "BASE_RUNE",
name = "lightning rune",
level_range = {25, 50},
rarity = 16,
cost = 20,
material_level = 3,
inscription_kind = "attack",
inscription_data = {
cooldown = resolvers.rngrange(15, 25),
range = resolvers.mbonus_level(5, 4),
power = resolvers.mbonus_level(400, 50, function(e, v) return v * 0.1 end),
use_stat_mod = 1.8,
},
inscription_talent = "RUNE:_LIGHTNING",
}
newEntity{ base = "BASE_RUNE",
name = "manasurge rune",
level_range = {1, 50},
rarity = 22,
cost = 10,
material_level = 1,
inscription_kind = "utility",
inscription_data = {
cooldown = resolvers.rngrange(20, 30),
dur = 10,
mana = resolvers.mbonus_level(1200, 600, function(e, v) return v * 0.003 end),
use_stat_mod = 4,
},
inscription_talent = "RUNE:_MANASURGE",
}
-----------------------------------------------------------
-- Taints
-----------------------------------------------------------
--[[
newEntity{ base = "BASE_TAINT",
name = "taint of the devourer",
level_range = {1, 50},
rarity = 15,
cost = 10,
material_level = 1,
inscription_kind = "heal",
inscription_data = {
cooldown = resolvers.rngrange(12, 17),
effects = resolvers.mbonus_level(3, 2, function(e, v) return v * 0.06 end),
heal = resolvers.mbonus_level(70, 40, function(e, v) return v * 0.06 end),
use_stat_mod = 0.6,
},
inscription_talent = "TAINT:_DEVOURER",
}
]]
| gpl-3.0 |
greasydeal/darkstar | scripts/zones/Metalworks/npcs/Topuru-Kuperu.lua | 38 | 1044 | -----------------------------------
-- Area: Metalworks
-- NPC: Topuru-Kuperu
-- Type: Standard NPC
-- @zone: 237
-- @pos 28.284 -17.39 42.269
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00fb);
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 |
greasydeal/darkstar | scripts/globals/mobskills/red_lotus_blade.lua | 7 | 1311 | ---------------------------------------------
-- red lotus blade
--
-- Description: Delivers a four-hit attack. Chance of critical varies with TP.
-- Type: Physical
-- Shadow per hit
-- Range: Melee
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
require("scripts/zones/Qubia_Arena/TextIDs");
require("scripts/zones/Throne_Room/TextIDs");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if(mob:getFamily() == 482)then
target:showText(mob,NO_HIDE_AWAY);
return 0;
elseif(mob:getFamily() == 483)then
target:showText(mob,RLB_PREPARE);
return 0;
else
return 0;
end
end;
function onMobWeaponSkill(target, mob, skill)
if(mob:getFamily() == 482)then
target:showText(mob,FEEL_MY_PAIN);
elseif(mob:getFamily() == 483)then
target:showText(mob,RLB_LAND);
else
mob:messageBasic(43, 0, 687+256);
end
skill:setSkillchain(40);
local numhits = 4;
local accmod = 1;
local dmgmod = 1.25;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_CRIT_VARIES,1.1,1.2,1.3);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
LegionXI/darkstar | scripts/zones/Labyrinth_of_Onzozo/MobIDs.lua | 31 | 2026 | -----------------------------------
-- Area: Labyrinth of Onzozo (213)
-- Comments: -- posX, posY, posZ
--(Taken from 'mob_spawn_points' table)
-----------------------------------
-- Mysticmaker Profblix
Mysticmaker_Profblix=17649693;
-- Lord of Onzozo
Lord_of_Onzozo=17649731;
Lord_of_Onzozo_PH={
[17649730] = '1', -- -39.356, 14.265, -60.406
};
-- Ose
Ose=17649822;
Ose_PH={
[17649813] = '1', -- -1.758, 4.982, 153.412
[17649814] = '1', -- 8.113, 5.055, 159.197
[17649824] = '1', -- 9.000, 4.000, 176.000
[17649819] = '1', -- -7.000, 4.467, 184.000
[17649820] = '1', -- -7.233, 4.976, 204.202
[17649823] = '1', -- 26.971, 4.440, 216.229
[17649816] = '1', -- 48.440, 5.070, 174.352
[17649815] = '1', -- 39.858, 4.364, 164.961
};
-- Soulstealer Skullnix
Soulstealer_Skullnix=17649818;
Soulstealer_Skullnix_PH={
[17649838] = '1', -- 38.347, 5.500, 178.050
[17649834] = '1', -- 43.103, 5.677, 181.977
[17649843] = '1', -- 41.150, 5.026, 204.483
[17649825] = '1', -- 24.384, 5.471, 197.938
[17649829] = '1', -- 13.729, 4.814, 166.295
[17649831] = '1', -- 5.096, 3.930, 166.865
};
-- Narasimha
Narasimha=17649784;
Narasimha_PH={
[17649783] = '1', -- -119.897, 0.275, 127.060
[17649787] = '1', -- -126.841, -0.554, 129.681
[17649790] = '1', -- -140.000, -0.955, 144.000
};
-- Hellion
Hellion=17649795;
Hellion_PH={
[17649797] = '1', -- 136.566, 14.708, 70.077
[17649810] = '1', -- 127.523, 14.327, 210.258
};
-- Peg Powler
Peg_Powler=17649761;
Peg_Powler_PH={
[17649755] = '1', -- -100.912, 4.263, -21.983
[17649759] = '1', -- -128.471, 4.952, 0.489
[17649760] = '1', -- -104.000, 4.000, 28.000
[17649758] = '1', -- -111.183, 5.357, 44.411
[17649762] = '1', -- -81.567, 5.013, 37.186
[17649763] = '1', -- -72.956, 4.943, 39.293
[17649770] = '1', -- -33.112, 4.735, 34.742
[17649769] = '1', -- -51.745, 4.288, 46.295
[17649774] = '1', -- -54.100, 5.462, 81.680
[17649773] = '1', -- -65.089, 5.386, 81.363
[17649766] = '1', -- -64.269, 5.441, 72.382
}; | gpl-3.0 |
ibm2431/darkstar | scripts/zones/Kuftal_Tunnel/IDs.lua | 9 | 5694 | -----------------------------------
-- Area: Kuftal_Tunnel
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.KUFTAL_TUNNEL] =
{
text =
{
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
NOTHING_OUT_OF_ORDINARY = 6402, -- There is nothing out of the ordinary here.
CONQUEST_BASE = 7049, -- Tallying conquest results...
FISHING_MESSAGE_OFFSET = 7208, -- You can't fish here.
CHEST_UNLOCKED = 7316, -- You unlock the chest!
FELL = 7334, -- The piece of wood fell off the cliff!
EVIL = 7335, -- You sense an evil presence...
FISHBONES = 7349, -- Fish bones lie scattered about the area...
SENSE_OMINOUS_PRESENCE = 7351, -- You sense an ominous presence...
REGIME_REGISTERED = 10335, -- New training regime registered!
COMMON_SENSE_SURVIVAL = 11419, -- It appears that you have arrived at a new survival guide provided by the Adventurers' Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world.
PLAYER_OBTAINS_ITEM = 11387, -- <name> obtains <item>!
UNABLE_TO_OBTAIN_ITEM = 11388, -- You were unable to obtain the item.
PLAYER_OBTAINS_TEMP_ITEM = 11389, -- <name> obtains the temporary item: <item>!
ALREADY_POSSESS_TEMP = 11390, -- You already possess that temporary item.
NO_COMBINATION = 11395, -- You were unable to enter a combination.
COMMON_SENSE_SURVIVAL = 11419, -- It appears that you have arrived at a new survival guide provided by the Adventurers' Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world.
},
mob =
{
AMEMET_PH =
{
[17490000] = 17490016, -- 123.046 0.250 18.642
[17489994] = 17490016, -- 112.135 -0.278 38.281
[17490001] = 17490016, -- 112.008 -0.530 50.994
[17490003] = 17490016, -- 122.654 -0.491 0.840
[17490008] = 17490016, -- 123.186 0.213 -24.716
[17490005] = 17490016, -- 118.633 -0.470 -43.282
[17490010] = 17490016, -- 109.000 -0.010 -48.000
[17490004] = 17490016, -- 96.365 -0.269 -7.619
[17490002] = 17490016, -- 89.590 -0.321 -9.390
[17489933] = 17490016, -- 68.454 -0.417 -0.413
[17489932] = 17490016, -- 74.662 -0.513 3.685
[17490009] = 17490016, -- 67.998 -0.500 12.000
[17489934] = 17490016, -- 92.000 -0.396 14.000
},
ARACHNE_PH =
{
[17490222] = 17490217, -- 19.000 20.000 37.000
[17490221] = 17490217, -- -10.000 20.000 14.000
[17490219] = 17490217, -- -20.000 20.000 38.000
[17490220] = 17490217, -- -20.000 21.000 1.000
},
BLOODTHIRSTER_MADKIX_PH =
{
[17490173] = 17490159, -- 265.000 9.000 30.000
[17490182] = 17490159, -- 256.000 10.000 34.000
},
PELICAN_PH =
{
[17490097] = 17490101, -- 178.857 20.256 -44.151
[17490094] = 17490101, -- 180.000 21.000 -39.000
[17490098] = 17490101, -- 179.394 20.061 -34.062
},
SABOTENDER_MARIACHI_PH =
{
[17489987] = 17489980, -- -23.543 -0.396 59.578
[17489983] = 17489980, -- -45.000 -0.115 39.000
[17489985] = 17489980, -- -34.263 -0.512 30.437
[17489984] = 17489980, -- -38.791 0.230 26.579
[17489977] = 17489980, -- -41.000 0.088 -3.000
[17489978] = 17489980, -- -54.912 0.347 -1.681
[17489979] = 17489980, -- -58.807 -0.327 -8.531
[17489981] = 17489980, -- -82.074 -0.450 -0.738
[17489982] = 17489980, -- -84.721 -0.325 -2.861
[17489974] = 17489980, -- -41.000 -0.488 -31.000
[17489975] = 17489980, -- -33.717 -0.448 -43.478
[17489971] = 17489980, -- -17.217 -0.956 -57.647
},
YOWIE_PH =
{
[17490175] = 17490204, -- 27.000 19.000 132.000
[17490174] = 17490204, -- 20.000 20.000 118.000
[17490168] = 17490204, -- 19.000 18.000 100.000
[17490167] = 17490204, -- 18.000 21.000 82.000
[17490161] = 17490204, -- 23.000 20.000 75.000
[17490176] = 17490204, -- 19.000 19.000 55.000
[17490160] = 17490204, -- 34.000 21.000 59.000
[17490146] = 17490204, -- 59.000 21.000 65.000
[17490148] = 17490204, -- 58.000 21.000 57.000
[17490144] = 17490204, -- 72.000 21.000 63.000
[17490141] = 17490204, -- 87.000 21.000 59.000
},
TALEKEEPER_OFFSET = 17489926,
MIMIC = 17490230,
CANCER = 17490231,
PHANTOM_WORM = 17490233,
GUIVRE = 17490234,
KETTENKAEFER = 17490235,
},
npc =
{
PHANTOM_WORM_QM = 17490253,
CASKET_BASE = 17490257,
DOOR_ROCK = 17490280,
TREASURE_COFFER = 17490304,
},
}
return zones[dsp.zone.KUFTAL_TUNNEL] | gpl-3.0 |
SOHUDBA/SOHU-DBProxy | tests/suite/base/t/constants-mock.lua | 4 | 1633 | --[[ $%BEGINLICENSE%$
Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; version 2 of the
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
local proto = assert(require("mysql.proto"))
---
-- if the assert()ions in -test.lua fail, the default behaviour of the proxy
-- will jump in and we will forward the query to the backend. That's us.
--
-- We will answer the query. Our answer is "failed"
function connect_server()
-- emulate a server
proxy.response = {
type = proxy.MYSQLD_PACKET_RAW,
packets = {
proto.to_challenge_packet({
server_version = 50114
})
}
}
return proxy.PROXY_SEND_RESULT
end
function read_query(packet)
if packet:byte() ~= proxy.COM_QUERY then
proxy.response = {
type = proxy.MYSQLD_PACKET_OK
}
return proxy.PROXY_SEND_RESULT
end
proxy.response = {
type = proxy.MYSQLD_PACKET_OK,
resultset = {
fields = {
{ name = "Result", type = proxy.MYSQL_TYPE_STRING },
},
rows = { { "failed" } }
}
}
return proxy.PROXY_SEND_RESULT
end
| gpl-2.0 |
greasydeal/darkstar | scripts/zones/Port_Jeuno/npcs/_6ue.lua | 20 | 1386 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Door: Departures Exit (for Windurst)
-- @zone 246
-- @pos 3 7 -54
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Port_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:hasKeyItem(AIRSHIP_PASS) == true and player:getGil() >= 200) then
player:startEvent(0x0027);
else
player:startEvent(0x002f);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x0027) then
Z = player:getZPos();
if(Z >= -61 and Z <= -58) then
player:delGil(200);
end
end
end; | gpl-3.0 |
LegionXI/darkstar | scripts/zones/Upper_Delkfutts_Tower/npcs/_4e1.lua | 14 | 1209 | -----------------------------------
-- Area: Upper Delkfutt's Tower
-- NPC: Door
-- @pos 315 16 20 158
-----------------------------------
package.loaded["scripts/zones/Upper_Delkfutts_Tower/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Upper_Delkfutts_Tower/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0002);
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0002 and option == 1) then
player:setPos(524, 16, 20, 0, 0xB8); -- to Lower Delkfutt's Tower
end
end; | gpl-3.0 |
rigeirani/btg | 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 |
ibm2431/darkstar | scripts/globals/items/pumpkin_pie_+1.lua | 11 | 1064 | -----------------------------------------
-- ID: 4525
-- Item: pumpkin_pie_+1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Magic 45
-- Intelligence 4
-- Charisma -1
-- MP Recovered While Healing 1
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,3600,4525)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.MP, 45)
target:addMod(dsp.mod.INT, 4)
target:addMod(dsp.mod.CHR, -1)
target:addMod(dsp.mod.MPHEAL, 1)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.MP, 45)
target:delMod(dsp.mod.INT, 4)
target:delMod(dsp.mod.CHR, -1)
target:delMod(dsp.mod.MPHEAL, 1)
end
| gpl-3.0 |
greasydeal/darkstar | scripts/zones/Castle_Oztroja/npcs/Kaa_Toru_the_Just.lua | 19 | 1579 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: Kaa Toru the Just
-- Type: Mission NPC [ Windurst Mission 6-2 NPC ]~
-- @pos -100.188 -62.125 145.422 151
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Castle_Oztroja/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getCurrentMission(WINDURST) == SAINTLY_INVITATION and player:getVar("MissionStatus") == 2) then
player:startEvent(0x002d,0,200);
else
player:startEvent(0x002e);
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 == 0x002d) then
player:delKeyItem(HOLY_ONES_INVITATION);
player:addKeyItem(HOLY_ONES_OATH);
player:messageSpecial(KEYITEM_OBTAINED,HOLY_ONES_OATH);
player:addItem(13134); -- Ashura Necklace
player:messageSpecial(ITEM_OBTAINED,13134);
player:setVar("MissionStatus",3);
end
end;
| gpl-3.0 |
LegionXI/darkstar | scripts/globals/weaponskills/apex_arrow.lua | 13 | 1509 | -----------------------------------
-- Apex Arrow
-- Archery weapon skill
-- Skill level: 357
-- Merit
-- RNG or SAM
-- Aligned with the Thunder & Light Gorget.
-- Aligned with the Thunder Belt & Light Belt.
-- Element: None
-- Modifiers: AGI:73~85%
-- 100%TP 200%TP 300%TP
-- 3.00 3.00 3.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 1;
params.ftp100 = 3; params.ftp200 = 3; params.ftp300 = 3;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0;
params.agi_wsc = 0.85 + (player:getMerit(MERIT_APEX_ARROW) / 100); 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;
params.ignoresDef = true;
params.ignored100 = 0.15;
params.ignored200 = 0.35;
params.ignored300 = 0.5;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.agi_wsc = 0.7 + (player:getMerit(MERIT_APEX_ARROW) / 100);
end
local damage, criticalHit, tpHits, extraHits = doRangedWeaponskill(player, target, wsID, params, tp, primary);
return tpHits, extraHits, criticalHit, damage;
end;
| gpl-3.0 |
ibm2431/darkstar | scripts/zones/Windurst_Woods/npcs/Nokkhi_Jinjahl.lua | 12 | 5098 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Nokkhi Jinjahl
-- Type: Travelling Merchant NPC / NPC Quiver Maker / Windurst 1st Place
-- !pos 4 1 -43 241
-----------------------------------
local ID = require("scripts/zones/Windurst_Woods/IDs")
-----------------------------------
function onTrade(player,npc,trade)
local ammoList =
{
{21307, 6199}, -- arrow, achiyalabopa
{21306, 6200}, -- arrow, adlivun
{19195, 5819}, -- arrow, antlion
{18154, 4221}, -- arrow, beetle
{21309, 6137}, -- arrow, chapuli
{18159, 4224}, -- arrow, demon
{21302, 6269}, -- arrow, eminent
{19800, 5912}, -- arrow, gargouille
{18156, 4222}, -- arrow, horn
{17320, 4225}, -- arrow, iron
{17325, 5332}, -- arrow, kabura
{21308, 6138}, -- arrow, mantid
{21303, 6280}, -- arrow, ra'kaznar
{21304, 6202}, -- arrow, raaz
{19182, 5871}, -- arrow, ruszor
{18155, 4223}, -- arrow, scorpion
{17321, 4226}, -- arrow, silver
{18158, 5333}, -- arrow, sleep
{17330, 4219}, -- arrow, stone
{21305, 6201}, -- arrow, tulfaire
{21314, 6278}, -- bolt, abrasion
{21321, 6203}, -- bolt, achiyalabopa
{18148, 5335}, -- bolt, acid
{19801, 5913}, -- bolt, adaman
{21320, 6204}, -- bolt, adlivun
{21318, 6206}, -- bolt, bismuth
{18150, 5334}, -- bolt, blind
{18151, 5339}, -- bolt, bloody
{21322, 6140}, -- bolt, damascus
{19183, 5872}, -- bolt, dark adaman
{19196, 5820}, -- bolt, darkling
{17338, 4229}, -- bolt, darksteel
{21316, 6270}, -- bolt, eminent
{19197, 5821}, -- bolt, fusion
{21313, 6310}, -- bolt, gashing
{18153, 5336}, -- bolt, holy
{21324, 6139}, -- bolt, midrium
{17337, 4228}, -- bolt, mythril
{21323, 6141}, -- bolt, oxidant
{21317, 6281}, -- bolt, ra'kaznar
{21315, 6279}, -- bolt, righteous
{18149, 5337}, -- bolt, sleep
{21319, 6205}, -- bolt, titanium
{18152, 5338}, -- bolt, venom
{19803, 5915}, -- bullet, adaman
{21336, 6208}, -- bullet, adlivun
{21337, 6207}, -- bullet, achiyalabopa
{17340, 5363}, -- bullet
{21333, 6210}, -- bullet, bismuth
{17343, 5359}, -- bullet, bronze
{21338, 6143}, -- bullet, damascus
{19184, 5873}, -- bullet, dark adaman
{21330, 6311}, -- bullet, decimating
{21328, 6437}, -- bullet, divine
{19198, 5822}, -- bullet, dweomer
{21331, 6271}, -- bullet, eminent
{17312, 5353}, -- bullet, iron
{19802, 5914}, -- bullet, orichalcum
{19199, 5823}, -- bullet, oberon's
{21332, 6282}, -- bullet, ra'kaznar
{17341, 5340}, -- bullet, silver
{18723, 5416}, -- bullet, steel
{18160, 5341}, -- bullet, spartan
{21335, 6209}, -- bullet, titanium
{2176, 5402}, -- card, fire
{2177, 5403}, -- card, ice
{2178, 5404}, -- card, wind
{2179, 5405}, -- card, earth
{2180, 5406}, -- card, thunder
{2181, 5407}, -- card, water
{2182, 5408}, -- card, light
{2183, 5409}, -- card, dark
}
local carnationsNeeded = 0
local giveToPlayer = {}
-- check for invalid items
for i = 0,8,1 do
local itemId = trade:getItemId(i)
if itemId > 0 and itemId ~= 948 then
local validSlot = false
for k, v in pairs(ammoList) do
if v[1] == itemId then
local itemQty = trade:getSlotQty(i)
if itemQty % 99 ~= 0 then
player:messageSpecial(ID.text.NOKKHI_BAD_COUNT)
return
end
local stacks = itemQty / 99
carnationsNeeded = carnationsNeeded + stacks
giveToPlayer[#giveToPlayer+1] = {v[2], stacks}
validSlot = true
break
end
end
if not validSlot then
player:messageSpecial(ID.text.NOKKHI_BAD_ITEM)
return
end
end
end
-- check for correct number of carnations
if carnationsNeeded == 0 or trade:getItemQty(948) ~= carnationsNeeded then
player:messageSpecial(ID.text.NOKKHI_BAD_COUNT)
return
end
-- check for enough inventory space
if player:getFreeSlotsCount() < carnationsNeeded then
player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED, giveToPlayer[1][1])
return
end
-- make the trade
player:messageSpecial(ID.text.NOKKHI_GOOD_TRADE)
for k, v in pairs(giveToPlayer) do
player:addItem(v[1], v[2])
player:messageSpecial(ID.text.ITEM_OBTAINED,v[1])
end
player:tradeComplete()
end
function onTrigger(player,npc)
player:startEvent(667,npc:getID())
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
| gpl-3.0 |
LegionXI/darkstar | scripts/zones/Port_Bastok/npcs/Zoby_Quhyo.lua | 17 | 1661 | -----------------------------------
-- Area: Port Bastok
-- NPC: Zoby Quhyo
-- Only sells when Bastok controlls Elshimo Lowlands
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(ELSHIMOLOWLANDS);
if (RegionOwner ~= NATION_BASTOK) then
player:showText(npc,ZOBYQUHYO_CLOSED_DIALOG);
else
player:showText(npc,ZOBYQUHYO_OPEN_DIALOG);
stock = {
0x0272, 234, --Black Pepper
0x0264, 55, --Kazham Peppers
0x1150, 55, --Kazham Pineapple
0x0278, 110, --Kukuru Bean
0x1126, 36, --Mithran Tomato
0x0276, 88, --Ogre Pumpkin
0x0583, 1656 --Phalaenopsis
}
showShop(player,BASTOK,stock);
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 |
greasydeal/darkstar | 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 |
greasydeal/darkstar | scripts/zones/Rolanberry_Fields/npcs/Saarlan.lua | 10 | 8608 | -----------------------------------
-- Area: Rolanberry Fields
-- NPC: Saarlan
-- Legion NPC
-- @pos 242 24.395 468
-----------------------------------
package.loaded["scripts/zones/Rolanberry_Fields/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/zones/Rolanberry_Fields/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local TITLE = 0;
local MAXIMUS = 0;
local LP = player:getCurrency("legion_point");
local MINIMUS = 0;
if (player:hasKeyItem(LEGION_TOME_PAGE_MAXIMUS)) then
MAXIMUS = 1;
end
if (player:hasKeyItem(LEGION_TOME_PAGE_MINIMUS)) then
MINIMUS = 1;
end
if (player:hasTitle(SUBJUGATOR_OF_THE_LOFTY)) then
TITLE = TITLE+1;
end
if (player:hasTitle(SUBJUGATOR_OF_THE_MIRED)) then
TITLE = TITLE+2;
end
if (player:hasTitle(SUBJUGATOR_OF_THE_SOARING)) then
TITLE = TITLE+4;
end
if (player:hasTitle(SUBJUGATOR_OF_THE_VEILED)) then
TITLE = TITLE+8;
end
if (player:hasTitle(LEGENDARY_LEGIONNAIRE)) then
TITLE = TITLE+16;
end
if (player:getVar("LegionStatus") == 0) then
player:startEvent(8004);
elseif (player:getVar("LegionStatus") == 1) then
player:startEvent(8005, 0, TITLE, MAXIMUS, LP, MINIMUS);
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);
local GIL = player:getGil();
local LP = player:getCurrency("legion_point");
local LP_COST = 0;
local ITEM = 0;
if (csid == 8004) then
player:setVar("LegionStatus",1)
elseif (csid == 8005) then
if (option == 0x0001000A) then
if (GIL >= 360000) then
player:addKeyItem(LEGION_TOME_PAGE_MAXIMUS);
player:delGil(360000);
player:messageSpecial(KEYITEM_OBTAINED, LEGION_TOME_PAGE_MAXIMUS)
else
player:messageSpecial(NOT_ENOUGH_GIL);
end
elseif(option == 0x0001000B) then
if (GIL >= 180000) then
player:addKeyItem(LEGION_TOME_PAGE_MINIMUS);
player:delGil(180000);
player:messageSpecial(KEYITEM_OBTAINED, LEGION_TOME_PAGE_MINIMUS)
else
player:messageSpecial(NOT_ENOUGH_GIL);
end
elseif(option == 0x00000002) then -- Gaiardas Ring
LP_COST = 1000;
ITEM = 10775
elseif(option == 0x00010002) then -- Gaubious Ring
LP_COST = 1000;
ITEM = 10776;
elseif(option == 0x00020002) then -- Caloussu Ring
LP_COST = 1000;
ITEM = 10777;
elseif(option == 0x00030002) then -- Nanger Ring
LP_COST = 1000;
ITEM = 10778;
elseif(option == 0x00040002) then -- Sophia Ring
LP_COST = 1000;
ITEM = 10779;
elseif(option == 0x00050002) then -- Quies Ring
LP_COST = 1000;
ITEM = 10780;
elseif(option == 0x00060002) then -- Cynosure Ring
LP_COST = 1000;
ITEM = 10781;
elseif(option == 0x00070002) then -- Ambuscade Ring
LP_COST = 1000;
ITEM = 10782;
elseif(option == 0x00080002) then -- Veneficium Ring
LP_COST = 1000;
ITEM = 10783;
elseif(option == 0x00090002) then -- Calma Armet ...Requires title: "Subjugator of the Lofty"
LP_COST = 4500;
ITEM = 10890;
elseif(option == 0x000A0002) then -- Mustela Mask ...Requires title: "Subjugator of the Lofty"
LP_COST = 4500;
ITEM = 10891;
elseif(option == 0x000B0002) then -- Magavan Beret ...Requires title: "Subjugator of the Lofty"
LP_COST = 4500;
ITEM = 10892;
elseif(option == 0x000C0002) then -- Calma Gauntlets ...Requires title: "Subjugator of the Mired"
LP_COST = 3000;
ITEM = 10512;
elseif(option == 0x000D0002) then -- Mustela Gloves ...Requires title: "Subjugator of the Mired"
LP_COST = 3000;
ITEM = 10513;
elseif(option == 0x000E0002) then -- Magavan Mitts ...Requires title: "Subjugator of the Mired"
LP_COST = 3000;
ITEM = 10514;
elseif(option == 0x000F0002) then -- Calma Hose ...Requires title: "Subjugator of the Soaring"
LP_COST = 4500;
ITEM = 11980;
elseif(option == 0x00100002) then -- Mustela Brais ...Requires title: "Subjugator of the Soaring"
LP_COST = 4500;
ITEM = 11981;
elseif(option == 0x00110002) then -- Magavan Slops ...Requires title: "Subjugator of the Soaring"
LP_COST = 4500;
ITEM = 11982;
elseif(option == 0x00120002) then -- Calma Leggings ...Requires title: "Subjugator of the Veiled"
LP_COST = 3000;
ITEM = 10610;
elseif(option == 0x00130002) then -- Mustela Boots ...Requires title: "Subjugator of the Veiled"
LP_COST = 3000;
ITEM = 10611;
elseif(option == 0x00140002) then -- Magavan Clogs ...Requires title: "Subjugator of the Veiled"
LP_COST = 3000;
ITEM = 10612;
elseif(option == 0x00150002) then -- Calma Breastplate ...Requires title: "Legendary Legionnaire"
LP_COST = 10000;
ITEM = 10462;
elseif(option == 0x00160002) then -- Mustela Harness ...Requires title: "Legendary Legionnaire"
LP_COST = 10000;
ITEM = 10463;
elseif(option == 0x00170002) then -- Magavan Frock ...Requires title: "Legendary Legionnaire"
LP_COST = 10000;
ITEM = 10464;
elseif(option == 0x00180002) then -- Corybant Pearl ...Requires title: "Subjugator of the Lofty"
LP_COST = 3000;
ITEM = 11044;
elseif(option == 0x00190002) then -- Saviesa Pearl ...Requires title: "Subjugator of the Mired"
LP_COST = 3000;
ITEM = 11045;
elseif(option == 0x001A0002) then -- Ouesk Pearl ...Requires title: "Subjugator of the Soaring"
LP_COST = 3000;
ITEM = 11046;
elseif(option == 0x001B0002) then -- Belatz Pearl ...Requires title: "Subjugator of the Soaring"
LP_COST = 3000;
ITEM = 11047;
elseif(option == 0x001C0002) then -- Cytherea Pearl ...Requires title: "Subjugator of the Veiled"
LP_COST = 3000;
ITEM = 11048;
elseif(option == 0x001D0002) then -- Myrddin Pearl ...Requires title: "Subjugator of the Veiled"
LP_COST = 3000;
ITEM = 11049;
elseif(option == 0x001E0002) then -- Puissant Pearl ...Requires title: "Subjugator of the Veiled"
LP_COST = 3000;
ITEM = 11050;
elseif(option == 0x001F0002) then -- Dhanurveda Ring ...Requires title: "Legendary Legionnaire"
LP_COST = 6000;
ITEM = 10784;
elseif(option == 0000200002) then -- Provocare Ring ......Requires title: "Legendary Legionnaire"
LP_COST = 6000;
ITEM = 10785;
elseif(option == 0000210002) then -- Mediator's Ring ...Requires title: "Legendary Legionnaire"
LP_COST = 6000;
ITEM = 10786;
end
end
if (LP < LP_COST) then
player:messageSpecial(LACK_LEGION_POINTS);
elseif (ITEM > 0) then
if (player:getFreeSlotsCount() >=1) then
player:delCurrency("legion_point", LP_COST);
player:addItem(ITEM, 1);
player:messageSpecial(ITEM_OBTAINED, ITEM);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, ITEM);
end
end
end; | gpl-3.0 |
LegionXI/darkstar | scripts/zones/RuAun_Gardens/npcs/qm2.lua | 14 | 1478 | -----------------------------------
-- Area: Ru'Aun Gardens
-- NPC: ??? (Seiryu's Spawn)
-- Allows players to spawn the HNM Seiryu with a Gem of the East and a Springstone.
-- @pos 569 -70 -80 130
-----------------------------------
package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/RuAun_Gardens/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Trade Gem of the East and Springstone
if (GetMobAction(17309981) == 0 and trade:hasItemQty(1418,1) and trade:hasItemQty(1419,1) and trade:getItemCount() == 2) then
player:tradeComplete();
SpawnMob(17309981):updateClaim(player); -- Spawn Seiryu
player:showText(npc,SKY_GOD_OFFSET + 9);
npc:setStatus(STATUS_DISAPPEAR);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(SKY_GOD_OFFSET + 1);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
greasydeal/darkstar | 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 |
greasydeal/darkstar | 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 |
greasydeal/darkstar | scripts/zones/Carpenters_Landing/Zone.lua | 27 | 3518 | -----------------------------------
--
-- Zone: Carpenters_Landing (2)
--
-----------------------------------
package.loaded["scripts/zones/Carpenters_Landing/TextIDs"] = nil;
package.loaded["scripts/globals/chocobo_digging"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/zone");
require("scripts/zones/Carpenters_Landing/TextIDs");
require("scripts/globals/chocobo_digging");
-----------------------------------
-- Chocobo Digging vars
-----------------------------------
local itemMap = {
-- itemid, abundance, requirement
{ 4504, 152, DIGREQ_NONE },
{ 688, 182, DIGREQ_NONE },
{ 697, 83, DIGREQ_NONE },
{ 4386, 3, DIGREQ_NONE },
{ 17396, 129, DIGREQ_NONE },
{ 691, 144, DIGREQ_NONE },
{ 918, 8, DIGREQ_NONE },
{ 699, 76, DIGREQ_NONE },
{ 4447, 38, DIGREQ_NONE },
{ 695, 45, DIGREQ_NONE },
{ 4096, 100, DIGREQ_NONE }, -- all crystals
{ 1255, 10, DIGREQ_NONE }, -- all ores
{ 4100, 59, DIGREQ_BURROW },
{ 4101, 59, DIGREQ_BURROW },
{ 690, 15, DIGREQ_BORE },
{ 1446, 8, DIGREQ_BORE },
{ 700, 23, DIGREQ_BORE },
{ 701, 8, DIGREQ_BORE },
{ 696, 30, DIGREQ_BORE },
{ 4570, 10, DIGREQ_MODIFIER },
{ 4487, 11, DIGREQ_MODIFIER },
{ 4409, 12, DIGREQ_MODIFIER },
{ 1188, 10, DIGREQ_MODIFIER },
{ 4532, 12, DIGREQ_MODIFIER },
};
local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED };
-----------------------------------
-- onChocoboDig
-----------------------------------
function onChocoboDig(player, precheck)
return chocoboDig(player, itemMap, precheck, messageArray);
end;
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
-- Tempest Tigon
SetRespawnTime(16785593, 900, 10800);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(6.509,-9.163,-819.333,239);
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);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
fegimanam/sa | plugins/plugins.lua | 72 | 6113 | 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 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..'. '..v..' '..status..'\n'
end
end
local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled'
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..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.'
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 '..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 '..plugin_name..' does not exists'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return 'Plugin '..name..' does not exists'
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return 'Plugin '..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 '..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 '..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
local receiver = get_receiver(msg)
local plugin = matches[2]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
-- Enable a plugin
if matches[1] == '+' and is_sudo(msg) then --after changed to moderator mode, set only sudo
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
-- Disable a plugin on a chat
if matches[1] == '-' and matches[3] == 'chat' then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
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
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 enable [plugin] : enable plugin.",
"!plugins disable [plugin] : disable plugin.",
"!plugins reload : reloads all plugins." },
},
patterns = {
"^!plugins$",
"^!plugins? (+) ([%w_%.%-]+)$",
"^!plugins? (-) ([%w_%.%-]+)$",
"^!plugins? (+) ([%w_%.%-]+) (chat)",
"^!plugins? (-) ([%w_%.%-]+) (chat)",
"^!plugins? (*)$" },
run = run,
moderated = true, -- set to moderator mode
--privileged = true
}
end
| gpl-2.0 |
greasydeal/darkstar | scripts/zones/Port_Windurst/npcs/Guruna-Maguruna.lua | 36 | 1747 | -----------------------------------
-- Area: Port Windurst
-- NPC: Guruna-Maguruna
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,GURUNAMAGURUNA_SHOP_DIALOG);
stock = {
0x3322, 4201,1, --Beetle Gorget
0x3139, 2776,1, --Linen Robe
0x31B9, 1570,1, --Linen Cuffs
0x3140, 1260,2, --Tunic
0x3131, 12355,2, --Cotton Doublet
0x3198, 324,2, --Leather Gloves
0x31C0, 589,2, --Mitts
0x31B1, 6696,2, --Cotton Gloves
0x331D, 972,3, --Hemp Gorget
0x3130, 2470,3, --Doublet
0x3138, 216,3, --Robe
0x3118, 604,3, --Leather Vest
0x31B0, 1363,3, --Gloves
0x31B8, 118,3 --Cuffs
}
showNationShop(player, WINDURST, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
greasydeal/darkstar | scripts/zones/Temenos/mobs/Temenos_Cleaner.lua | 17 | 1285 | -----------------------------------
-- Area: Temenos Central 1floor
-- NPC: Temenos_Cleaner
-----------------------------------
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(16929046)==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 |
ibm2431/darkstar | scripts/zones/Arrapago_Reef/mobs/Velionis.lua | 11 | 1944 | -----------------------------------
-- Area: Arrapago Reef
-- ZNM: Velionis
-----------------------------------
mixins = {require("scripts/mixins/rage")}
require("scripts/globals/status")
-----------------------------------
-- Todo: blaze spikes effect only activates while not in casting animation
function onMobInitialize(mob)
mob:setMobMod(dsp.mobMod.AUTO_SPIKES, 1)
mob:addStatusEffect(dsp.effect.BLAZE_SPIKES, 250, 0, 0)
mob:getStatusEffect(dsp.effect.BLAZE_SPIKES):setFlag(dsp.effectFlag.DEATH)
mob:setMobMod(dsp.mobMod.IDLE_DESPAWN, 300)
end
function onMobSpawn(mob)
mob:setLocalVar("[rage]timer", 3600) -- 60 minutes
mob:SetAutoAttackEnabled(false)
mob:setMod(dsp.mod.FASTCAST,15)
mob:setLocalVar("HPP", 90)
mob:setMobMod(dsp.mobMod.MAGIC_COOL,10)
end
function onMobFight(mob,target)
local FastCast = mob:getLocalVar("HPP")
if mob:getHPP() <= FastCast then
if mob:getHPP() > 10 then
mob:addMod(dsp.mod.FASTCAST, 15)
mob:setLocalVar("HPP", mob:getHPP() - 10)
end
end
end
function onSpikesDamage(mob, target, damage)
local INT_diff = mob:getStat(dsp.mod.INT) - target:getStat(dsp.mod.INT)
if INT_diff > 20 then
INT_diff = 20 + (INT_diff - 20) * 0.5 -- INT above 20 is half as effective.
end
local dmg = (damage + INT_diff) * 0.5 -- INT adjustment and base damage averaged together.
local params = {}
params.bonusmab = 0
params.includemab = false
dmg = addBonusesAbility(mob, dsp.magic.ele.FIRE, target, dmg, params)
dmg = dmg * applyResistanceAddEffect(mob, target, dsp.magic.ele.FIRE, 0)
dmg = adjustForTarget(target, dmg, dsp.magic.ele.FIRE)
dmg = finalMagicNonSpellAdjustments(mob, target, dsp.magic.ele.FIRE, dmg)
if dmg < 0 then
dmg = 0
end
return dsp.subEffect.BLAZE_SPIKES, dsp.msg.basic.SPIKES_EFFECT_DMG, dmg
end
function onMobDeath(mob, player, isKiller)
end
| gpl-3.0 |
LegionXI/darkstar | scripts/globals/items/coffeecake_muffin_+1.lua | 12 | 1372 | -----------------------------------------
-- ID: 5656
-- Item: coffeecake_muffin_+1
-- Food Effect: 1Hr, All Races
-----------------------------------------
-- Mind 2
-- Strength -1
-- MP % 10 (cap 90)
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5656);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MND, 2);
target:addMod(MOD_STR, -1);
target:addMod(MOD_FOOD_MPP, 10);
target:addMod(MOD_FOOD_MP_CAP, 90);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MND, 2);
target:delMod(MOD_STR, -1);
target:delMod(MOD_FOOD_MPP, 10);
target:delMod(MOD_FOOD_MP_CAP, 90);
end; | gpl-3.0 |
naclander/tome | game/modules/tome/data/maps/zones/tannen-tower-3.lua | 3 | 1677 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
startx = 12
starty = 12
endx = 19
endy = 4
-- defineTile section
defineTile("X", "HARDWALL")
defineTile("~", "DEEP_WATER")
defineTile("<", "TUP")
defineTile(">", "TDOWN")
defineTile(".", "FLOOR")
-- addSpot section
-- ASCII map section
return [[
XXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXX~~~~~XXXXXXXXXX
XXXXXXX~~~.XXX~~~~XXXXXXX
XXXXX~~~XXXXXXXXX~~~XXXXX
XXXX~~XXXXXXXXXXXXX<~XXXX
XXX~~XXXXXXXXXXXXXXX~~XXX
XXX~XX~~~~~~~~~~~~~XX~XXX
XX~~XX~XXXXXXXXXXX~XX~~XX
XX~XXX~X~~.~~~~~~X.XXX~XX
XX~XXX~X~XXXXXXX~X~XXX~XX
X~~XXX~X~X~~~~~X~X~XXX~~X
X~XXXX~X~X~XXX~X~X~XXXX~X
X~XXXX~X~X~~>X~X~X~XXXX~X
X~XXXX~X~XXXXX~X~X~XXXX~X
X~~XXX.X~~~~~~~X~X~XXX~~X
XX~XXX~XXXXXXXXX~X~XXX~XX
XX.XXX~~~~~~~~~~~X~XXX~XX
XX~~XXXXXXXXXXXXXX~XX~.XX
XXX~~~~~~~~~~~.~~~~XX~XXX
XXX~~XXXXXXXXXXXXXXX~~XXX
XXXX~~XXXXXXXXXXXXX~~XXXX
XXXXX~~~XXXXXXXXX~~~XXXXX
XXXXXXX~~~.XXX~~~~XXXXXXX
XXXXXXXXXX~~~~~XXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXX]]
| gpl-3.0 |
nesstea/darkstar | scripts/globals/mobskills/Optic_Induration.lua | 33 | 1340 | ---------------------------------------------
-- Optic Induration
--
-- Description: Charges up a powerful, calcifying beam directed at targets in a fan-shaped area of effect. Additional effect: Petrification & enmity reset
-- Type: Magical
-- Utsusemi/Blink absorb: Ignores shadows
-- Range: Unknown cone
-- Notes: Charges up (three times) before actually being used (except Jailer of Temperance, who doesn't need to charge it up). The petrification lasts a very long time.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:AnimationSub() == 2 or mob:AnimationSub() == 3) then
return 1;
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_PETRIFICATION;
MobStatusEffectMove(mob, target, typeEffect, 1, 0, 60);
local dmgmod = 1;
local accmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_DARK,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_DARK,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
mob:resetEnmity(target);
return dmg;
end;
| gpl-3.0 |
MuhammadWang/MCServer | MCServer/Plugins/APIDump/Hooks/OnLogin.lua | 8 | 1581 | return
{
HOOK_LOGIN =
{
CalledWhen = "Right before player authentication. If auth is disabled, right after the player sends their name.",
DefaultFnName = "OnLogin", -- also used as pagename
Desc = [[
This hook is called whenever a client logs in. It is called right before the client's name is sent
to be authenticated. Plugins may refuse the client from accessing the server. Note that when this
callback is called, the {{cPlayer}} object for this client doesn't exist yet - the client has no
representation in any world. To process new players when their world is known, use a later callback,
such as {{OnPlayerJoined|HOOK_PLAYER_JOINED}} or {{OnPlayerSpawned|HOOK_PLAYER_SPAWNED}}.
]],
Params =
{
{ Name = "Client", Type = "{{cClientHandle}}", Notes = "The client handle representing the connection" },
{ Name = "ProtocolVersion", Type = "number", Notes = "Versio of the protocol that the client is talking" },
{ Name = "UserName", Type = "string", Notes = "The name that the client has presented for authentication. This name will be given to the {{cPlayer}} object when it is created for this client." },
},
Returns = [[
If the function returns true, no other plugins are called for this event and the client is kicked.
If the function returns false or no value, MCServer calls other plugins' callbacks and finally
sends an authentication request for the client's username to the auth server. If the auth server
is disabled in the server settings, the player object is immediately created.
]],
}, -- HOOK_LOGIN
}
| apache-2.0 |
nesstea/darkstar | scripts/zones/West_Ronfaure/Zone.lua | 13 | 3884 | -----------------------------------
--
-- Zone: West_Ronfaure (100)
--
-----------------------------------
package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil;
package.loaded["scripts/globals/chocobo_digging"] = nil;
-----------------------------------
require("scripts/globals/zone");
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/conquest");
require("scripts/globals/icanheararainbow");
require("scripts/zones/West_Ronfaure/TextIDs");
require("scripts/globals/chocobo_digging");
-----------------------------------
-- Chocobo Digging vars
-----------------------------------
local itemMap = {
-- itemid, abundance, requirement
{ 4504, 167, DIGREQ_NONE },
{ 688, 15, DIGREQ_NONE },
{ 17396, 20, DIGREQ_NONE },
{ 698, 5, DIGREQ_NONE },
{ 840, 117, DIGREQ_NONE },
{ 691, 83, DIGREQ_NONE },
{ 833, 83, DIGREQ_NONE },
{ 639, 10, DIGREQ_NONE },
{ 694, 63, DIGREQ_NONE },
{ 918, 12, DIGREQ_NONE },
{ 4096, 100, DIGREQ_NONE }, -- all crystals
{ 4545, 5, DIGREQ_BURROW },
{ 636, 63, DIGREQ_BURROW },
{ 617, 63, DIGREQ_BORE },
{ 4570, 10, DIGREQ_MODIFIER },
{ 4487, 11, DIGREQ_MODIFIER },
{ 4409, 12, DIGREQ_MODIFIER },
{ 1188, 10, DIGREQ_MODIFIER },
{ 4532, 12, DIGREQ_MODIFIER },
{ 573, 23, DIGREQ_NIGHT },
};
local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED };
-----------------------------------
-- onChocoboDig
-----------------------------------
function onChocoboDig(player, precheck)
return chocoboDig(player, itemMap, precheck, messageArray);
end;
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local manuals = {17187570,17187571};
SetFieldManual(manuals);
SetRegionalConquestOverseers(zone:getRegionID())
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(-24.427,-53.107,140,127);
end
if (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow
cs = 0x0033;
elseif (player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1) then
cs = 0x0035;
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 == 0x0033) then
lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow
elseif (csid == 0x0035) then
player:updateEvent(0,0,0,0,0,5);
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0033) then
lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/globals/items/clump_of_batagreens.lua | 18 | 1193 | -----------------------------------------
-- ID: 4367
-- Item: clump_of_batagreens
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Agility 2
-- Vitality -4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4367);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 2);
target:addMod(MOD_VIT, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 2);
target:delMod(MOD_VIT, -4);
end;
| gpl-3.0 |
gmorishere/bot | plugins/chatter.lua | 20 | 1670 | -- Put this absolutely at the end, even after greetings.lua.
local triggers = {
'',
'^' .. bot.first_name .. ',',
'^@' .. bot.username .. ','
}
local action = function(msg)
if msg.text == '' then return end
-- This is awkward, but if you have a better way, please share.
if msg.text_lower:match('^' .. bot.first_name .. ',') then
elseif msg.text_lower:match('^@' .. bot.username .. ',') then
elseif msg.text:match('^/') then
return true
-- Uncomment the following line for Al Gore-like reply chatter.
-- elseif msg.reply_to_message and msg.reply_to_message.from.id == bot.id then
elseif msg.from.id == msg.chat.id then
else
return true
end
sendChatAction(msg.chat.id, 'typing')
local input = msg.text_lower
input = input:gsub(bot.first_name, 'simsimi')
input = input:gsub('@'..bot.username, 'simsimi')
local url = 'http://www.simsimi.com/requestChat?lc=en&ft=1.0&req=' .. URL.escape(input)
local jstr, res = HTTP.request(url)
if res ~= 200 then
sendMessage(msg.chat.id, config.errors.chatter_connection)
return
end
local jdat = JSON.decode(jstr)
local message = jdat.res.msg
if message:match('^I HAVE NO RESPONSE.') then
message = config.errors.chatter_response
end
-- Let's clean up the response a little. Capitalization & punctuation.
local filter = {
['%aimi?%aimi?'] = bot.first_name,
['^%s*(.-)%s*$'] = '%1',
['^%l'] = string.upper,
['USER'] = msg.from.first_name
}
for k,v in pairs(filter) do
message = string.gsub(message, k, v)
end
if not string.match(message, '%p$') then
message = message .. '.'
end
sendMessage(msg.chat.id, message)
end
return {
action = action,
triggers = triggers
}
| gpl-2.0 |
hamed9898/maxbot | plugins/trivia.lua | 647 | 6784 | do
-- Trivia plugin developed by Guy Spronck
-- Returns the chat hash for storing information
local function get_hash(msg)
local hash = nil
if msg.to.type == 'chat' then
hash = 'chat:'..msg.to.id..':trivia'
end
if msg.to.type == 'user' then
hash = 'user:'..msg.from.id..':trivia'
end
return hash
end
-- Sets the question variables
local function set_question(msg, question, answer)
local hash =get_hash(msg)
if hash then
redis:hset(hash, "question", question)
redis:hset(hash, "answer", answer)
redis:hset(hash, "time", os.time())
end
end
-- Returns the current question
local function get_question( msg )
local hash = get_hash(msg)
if hash then
local question = redis:hget(hash, 'question')
if question ~= "NA" then
return question
end
end
return nil
end
-- Returns the answer of the last question
local function get_answer(msg)
local hash = get_hash(msg)
if hash then
return redis:hget(hash, 'answer')
else
return nil
end
end
-- Returns the time of the last question
local function get_time(msg)
local hash = get_hash(msg)
if hash then
return redis:hget(hash, 'time')
else
return nil
end
end
-- This function generates a new question if available
local function get_newquestion(msg)
local timediff = 601
if(get_time(msg)) then
timediff = os.time() - get_time(msg)
end
if(timediff > 600 or get_question(msg) == nil)then
-- Let's show the answer if no-body guessed it right.
if(get_question(msg)) then
send_large_msg(get_receiver(msg), "The question '" .. get_question(msg) .."' has not been answered. \nThe answer was '" .. get_answer(msg) .."'")
end
local url = "http://jservice.io/api/random/"
local b,c = http.request(url)
local query = json:decode(b)
if query then
local stringQuestion = ""
if(query[1].category)then
stringQuestion = "Category: " .. query[1].category.title .. "\n"
end
if query[1].question then
stringQuestion = stringQuestion .. "Question: " .. query[1].question
set_question(msg, query[1].question, query[1].answer:lower())
return stringQuestion
end
end
return 'Something went wrong, please try again.'
else
return 'Please wait ' .. 600 - timediff .. ' seconds before requesting a new question. \nUse !triviaquestion to see the current question.'
end
end
-- This function generates a new question when forced
local function force_newquestion(msg)
-- Let's show the answer if no-body guessed it right.
if(get_question(msg)) then
send_large_msg(get_receiver(msg), "The question '" .. get_question(msg) .."' has not been answered. \nThe answer was '" .. get_answer(msg) .."'")
end
local url = "http://jservice.io/api/random/"
local b,c = http.request(url)
local query = json:decode(b)
if query then
local stringQuestion = ""
if(query[1].category)then
stringQuestion = "Category: " .. query[1].category.title .. "\n"
end
if query[1].question then
stringQuestion = stringQuestion .. "Question: " .. query[1].question
set_question(msg, query[1].question, query[1].answer:lower())
return stringQuestion
end
end
return 'Something went wrong, please try again.'
end
-- This function adds a point to the player
local function give_point(msg)
local hash = get_hash(msg)
if hash then
local score = tonumber(redis:hget(hash, msg.from.id) or 0)
redis:hset(hash, msg.from.id, score+1)
end
end
-- This function checks for a correct answer
local function check_answer(msg, answer)
if(get_answer(msg)) then -- Safety for first time use
if(get_answer(msg) == "NA")then
-- Question has not been set, give a new one
--get_newquestion(msg)
return "No question set, please use !trivia first."
elseif (get_answer(msg) == answer:lower()) then -- Question is set, lets check the answer
set_question(msg, "NA", "NA") -- Correct, clear the answer
give_point(msg) -- gives out point to player for correct answer
return msg.from.print_name .. " has answered correctly! \nUse !trivia to get a new question."
else
return "Sorry " .. msg.from.print_name .. ", but '" .. answer .. "' is not the correct answer!"
end
else
return "No question set, please use !trivia first."
end
end
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
local function get_user_score(msg, user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local hash = 'chat:'..msg.to.id..':trivia'
user_info.score = tonumber(redis:hget(hash, user_id) or 0)
user_info.name = user_print_name(user)..' ('..user_id..')'
return user_info
end
-- Function to print score
local function trivia_scores(msg)
if msg.to.type == 'chat' then
-- Users on chat
local hash = 'chat:'..msg.to.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_user_score(msg, user_id, msg.to.id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.score and b.score then
return a.score > b.score
end
end)
local text = ''
for k,user in pairs(users_info) do
text = text..user.name..' => '..user.score..'\n'
end
return text
else
return "This function is only available in group chats."
end
end
local function run(msg, matches)
if(matches[1] == "!triviascore" or matches[1] == "!triviascores") then
-- Output all scores
return trivia_scores(msg)
elseif(matches[1] == "!triviaquestion")then
return "Question: " .. get_question(msg)
elseif(matches[1] == "!triviaskip") then
if is_sudo(msg) then
return force_newquestion(msg)
end
elseif(matches[1] ~= "!trivia") then
return check_answer(msg, matches[1])
end
return get_newquestion(msg)
end
return {
description = "Trivia plugin for Telegram",
usage = {
"!trivia to obtain a new question.",
"!trivia [answer] to answer the question.",
"!triviaquestion to show the current question.",
"!triviascore to get a scoretable of all players.",
"!triviaskip to skip a question (requires sudo)"
},
patterns = {"^!trivia (.*)$",
"^!trivia$",
"^!triviaquestion$",
"^!triviascore$",
"^!triviascores$",
"^!triviaskip$"},
run = run
}
end
| gpl-2.0 |
gaohuang/DenseNet_lite | DenseLayer.lua | 1 | 2973 | require 'nn'
require 'cudnn'
require 'cunn'
local nninit = require 'nninit'
local DenseLayer, parent = torch.class('nn.DenseLayer', 'nn.Container')
function DenseLayer:__init(nInputs, nChannels, growthRate, stride)
parent.__init(self)
self.train = true
self.nInputs = nInputs
self.nChannels = nChannels
self.growthRate = growthRate or nChannels
stride = stride or 1
self.net = nn.Sequential()
self.net:add(cudnn.SpatialBatchNormalization(nChannels))
self.net:add(cudnn.ReLU(true))
self.net:add(cudnn.SpatialConvolution(nChannels, self.growthRate, 3, 3, stride, stride, 1, 1))
self.gradInput = {}
self.output = {torch.CudaTensor()}
for i = 1, nInputs do
self.output[i+1] = torch.CudaTensor()
end
self.modules = {self.net}
end
function DenseLayer:updateOutput(input)
if type(input) == 'table' then
-- copy input to a contiguous tensor
local sz = #input[1]
sz[2] = self.nChannels
local input_c = self.net:get(1).gradInput -- reuse the memory to save tmp input
input_c:resize(sz)
local nC = 1
for i = 1, self.nInputs do
self.output[i] = input[i]
input_c:narrow(2, nC, input[i]:size(2)):copy(input[i])
nC = nC + input[i]:size(2)
end
-- compute output
sz[2] = self.growthRate
self.output[self.nInputs+1]:resize(sz):copy(self.net:forward(input_c))
else
local sz = input:size()
sz[2] = self.growthRate
self.output[1]:resizeAs(input):copy(input)
self.output[2]:resize(sz):copy(self.net:forward(input))
end
return self.output
end
function DenseLayer:updateGradInput(input, gradOutput)
if type(input) == 'table' then
for i = 1, self.nInputs do
self.gradInput[i] = gradOutput[i]
end
local gOut_net = gradOutput[#gradOutput]
local input_c = self.net:get(1).gradInput -- the contiguous input is stored in the gradInput during the forward pass
local gIn = self.net:updateGradInput(input_c, gOut_net)
local nC = 1
for i = 1, self.nInputs do
self.gradInput[i]:add(gIn:narrow(2,nC,input[i]:size(2)))
nC = nC + input[i]:size(2)
end
else
self.gradInput = gradOutput[1]
self.gradInput:add(self.net:updateGradInput(input, gradOutput[2]))
end
return self.gradInput
end
function DenseLayer:accGradParameters(input, gradOutput, scale)
scale = scale or 1
local gOut_net = gradOutput[#gradOutput]
if type(input) == 'table' then
-- copy input to a contiguous tensor
local sz = #input[1]
sz[2] = self.nChannels
local input_c = self.net:get(1).gradInput -- reuse the memory to save tmp input
input_c:resize(sz)
local nC = 1
for i = 1, self.nInputs do
input_c:narrow(2, nC, input[i]:size(2)):copy(input[i])
nC = nC + input[i]:size(2)
end
self.net:accGradParameters(input_c, gOut_net, scale)
else
self.net:accGradParameters(input, gOut_net, scale)
end
end | mit |
UnfortunateFruit/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 |
bowlofstew/Macaroni | Main/Generators/LuaGlueTest.lua | 2 | 11385 | require "LuaGlue"
require "Macaroni.Parser.Pippy.PippyParser";
require "Macaroni.Parser.Parser";
require "Macaroni.Parser.ParserException";
local PippyParser = Macaroni.Parser.Pippy.PippyParser;
local function mixinContext(self, sourceCode)
self.context = Context.New("{ROOT}");
self.library = self.context:FindOrCreateLibrary("", "TypeTests", "1.5");
self.luaStateNode = self.context.Root:FindOrCreate("lua_State");
self.luaStateNode = self.context.Root:FindOrCreate("luaL_Reg");
local cppPrimitives = self.context.Root:FindOrCreate("{C++ Primitives}");
self.intNode = cppPrimitives:FindOrCreate("int");
self.boolNode = cppPrimitives:FindOrCreate("bool");
self.generator = LuaGlueGenerator.new(self.context.Root);
local parser = PippyParser.Create();
local file = FileName.Create("LuaGlueTest Made Up File.mcpp");
local root = self.context.Root;
local src = Source.Create(file, 1, 1);
self.trim = function(s)
return (s:gsub("^%s*", ""))
end;
parser:Read(self.library, src, sourceCode);
end
Test.register(
{
name = "LuaGlueTests",
tests =
{
{
name = "Type Manipulators Test",
init = function(self)
mixinContext(self, [[
~import Macaroni::Lua::LuaClass; //<-- The Annotation to use
~import Example::Polo;
~import Example::PoloPtr;
namespace Example
{
// Plain Old Lua Object, get it?
class Polo
{
@LuaClass
[
ReferenceType = PoloPtr,
]
};
class PoloPtr
{
};
}
]]);
self.polo = self.generator.RootNode:Find("Example::Polo");
self.poloPtr = self.generator.RootNode:Find("Example::PoloPtr");
self.stdstring = self.generator.RootNode:FindOrCreate("std::string");
self.stdstring = self.generator.RootNode:FindOrCreate("std::string");
self.oldLuaWrapperArguments = self.generator.LuaWrapperArguments;
--[[self.generator.LuaWrapperArguments = function(node)
log "I got called.";
if (node == self.polo) then
return {
node = node;
referenceType = self.poloPtr;
glueType = self.context.Root:FindOrCreate("PoloLuaMetaData");
};
else
error("NOPE!", 2);
end
end;]]--
end,
tests = {
["Polo"] = function(self)
local type = Type.New(self.polo, {});
local tm = self.generator:TypeManipulators(type)
Test.assertEquals([[Example::PoloPtr & blah = Example::PoloLuaMetaData::GetInstance(L, 5);]], tm.get("blah", 5));
Test.assertEquals(self.trim([[Example::PoloPtr & blah_AsRef = Example::PoloLuaMetaData::GetInstance(L, 5);]] ..
NEW_LINE .. [[Example::Polo & blah = *(*(blah_AsRef));]]), tm.convertArgument("blah", 5));
Test.assertEquals([[Example::PoloLuaMetaData::PutInstanceOnStack(L, blah);]], tm.put("blah"));
end,
["const Polo"] = function(self)
local type = Type.New(self.polo, { Const = true });
local tm = self.generator:TypeManipulators(type);
Test.assertEquals([[Example::PoloPtr & blah = Example::PoloLuaMetaData::GetInstance(L, 5);]], tm.get("blah", 5));
Test.assertEquals(self.trim(
[[Example::PoloPtr & blah_AsRef = Example::PoloLuaMetaData::GetInstance(L, 5);]] ..
NEW_LINE .. [[const Example::Polo & blah = *(*(blah_AsRef));]]), tm.convertArgument("blah", 5));
Test.assertEquals([[Example::PoloLuaMetaData::PutInstanceOnStack(L, blah);]], tm.put("blah"));
end,
["const Polo *"] = function(self)
local type = Type.New(self.polo, { Const = true, Pointer = true });
local tm = self.generator:TypeManipulators(type)
Test.assertEquals([[Example::PoloPtr & blah = Example::PoloLuaMetaData::GetInstance(L, 5);]], tm.get("blah", 5));
Test.assertEquals(self.trim([[Example::PoloPtr & blah_AsRef = Example::PoloLuaMetaData::GetInstance(L, 5);]] ..
NEW_LINE ..
[[const Example::Polo * blah = *(blah_AsRef);]]), tm.convertArgument("blah", 5));
Test.assertEquals([[Example::PoloLuaMetaData::PutInstanceOnStack(L, blah);]], tm.put("blah"));
end,
["Polo &"] = function(self)
local type = Type.New(self.polo, { Reference = true });
local tm = self.generator:TypeManipulators(type)
Test.assertEquals([[Example::PoloPtr & blah = Example::PoloLuaMetaData::GetInstance(L, 5);]], tm.get("blah", 5));
Test.assertEquals(self.trim([[Example::PoloPtr & blah_AsRef = Example::PoloLuaMetaData::GetInstance(L, 5);]] ..
NEW_LINE .. [[Example::Polo & blah = *(*(blah_AsRef));]]), tm.convertArgument("blah", 5));
Test.assertEquals([[Example::PoloLuaMetaData::PutInstanceOnStack(L, blah);]], tm.put("blah"));
end,
["const Polo &"] = function(self)
local type = Type.New(self.polo, { Const = true, Reference = true });
local tm = self.generator:TypeManipulators(type)
Test.assertEquals([[Example::PoloPtr & blah = Example::PoloLuaMetaData::GetInstance(L, 5);]], tm.get("blah", 5));
Test.assertEquals(self.trim([[Example::PoloPtr & blah_AsRef = Example::PoloLuaMetaData::GetInstance(L, 5);]] ..
NEW_LINE .. [[const Example::Polo & blah = *(*(blah_AsRef));]]), tm.convertArgument("blah", 5));
Test.assertEquals([[Example::PoloLuaMetaData::PutInstanceOnStack(L, blah);]], tm.put("blah"));
end,
["const Polo * const"] = function(self)
local type = Type.New(self.polo, { Const = true, ConstPointer = true, Pointer = true });
local tm = self.generator:TypeManipulators(type)
Test.assertEquals([[Example::PoloPtr & blah = Example::PoloLuaMetaData::GetInstance(L, 5);]], tm.get("blah", 5));
Test.assertEquals(self.trim([[Example::PoloPtr & blah_AsRef = Example::PoloLuaMetaData::GetInstance(L, 5);]] ..
NEW_LINE .. [[const Example::Polo * const blah = *(blah_AsRef);]]), tm.convertArgument("blah", 5));
Test.assertEquals([[Example::PoloLuaMetaData::PutInstanceOnStack(L, blah);]], tm.put("blah"));
end,
["int"] = function(self)
local type = Type.New(self.intNode, {});
local tm = self.generator:TypeManipulators(type)
Test.assertEquals(tm.get("blah", 5), [[int blah(luaL_checkint(L, 5));]]);
Test.assertEquals([[int blah(luaL_checkint(L, 5));]], tm.convertArgument("blah", 5));
Test.assertEquals(tm.put("blah"), [[lua_pushint(L, blah);]]);
end,
["const int"] = function(self)
local type = Type.New(self.intNode, { Const = true });
local tm = self.generator:TypeManipulators(type)
Test.assertEquals(tm.get("blah", 5), [[int blah(luaL_checkint(L, 5));]]);
Test.assertEquals([[int blah(luaL_checkint(L, 5));]], tm.convertArgument("blah", 5));
Test.assertEquals(tm.put("blah"), [[lua_pushint(L, blah);]]);
end,
["std::string"] = function(self)
local type = Type.New(self.stdstring, {});
local tm = self.generator:TypeManipulators(type)
Test.assertEquals([[const std::string blah(luaL_checkstring(L, 5));]], tm.get("blah", 5));
Test.assertEquals([[const std::string blah(luaL_checkstring(L, 5));]], tm.convertArgument("blah", 5));
Test.assertEquals(tm.put("blah"), [[lua_pushlstring(L, blah.c_str(), blah.length());]]);
end,
["undo test context"] = function(self)
self.generator.LuaWrapperArguments = self.oldLuaWrapperArguments;
end,
}
}, -- end of TypeManipulatorTests
{
name = "Wrap Methods Test",
init = function(self)
mixinContext(self, [[
~import Macaroni::Lua::LuaClass; //<-- The Annotation to use
~import Example::Action;
~import Example::ActionPtr;
~import Example::Polo;
~import Example::PoloPtr;
~import std::string;
namespace Example
{
class Action
{
@LuaClass
[ ReferenceType = ActionPtr ]
};
class ActionPtr{};
// Plain Old Lua Object, get it?
class Polo
{
@LuaClass
[
ReferenceType = PoloPtr,
]
public const string & DoSomething(const int index, const std::string & name,
const Action & action) const
{
return name;
}
};
class PoloPtr
{
};
}
]]);
self.polo = self.generator.RootNode:Find("Example::Polo");
self.poloPtr = self.generator.RootNode:Find("Example::PoloPtr");
self.poloDoSomething = self.polo:Find("DoSomething");
self.stdstring = self.generator.RootNode:FindOrCreate("std::string");
self.stdstring = self.generator.RootNode:FindOrCreate("std::string");
self.oldLuaWrapperArguments = self.generator.LuaWrapperArguments;
end,
tests = {
["wrap a function"] = function(self)
local type = Type.New(self.polo, {});
local tm = self.generator:TypeManipulators(type)
local method = self.generator:wrapMethod(self.poloDoSomething);
Test.assertEquals(self.trim("\n\tstatic int DoSomething(lua_State * L)" ..
"\n\t{" ..
"\n\t\tExample::PoloPtr & instance = Example::PoloLuaMetaData::GetInstance(L, 1);" ..
"\n\t\tint arg1(luaL_checkint(L, 2));" ..
"\n\t\tconst std::string arg2(luaL_checkstring(L, 3));" ..
"\n\t\tExample::ActionPtr & arg3_AsRef = Example::ActionLuaMetaData::GetInstance(L, 4);" ..
NEW_LINE .. "const Example::Action & arg3 = *(*(arg3_AsRef));" ..
"\n\t\tconst std::string & rtn = instance->DoSomething(arg1, arg2, arg3);" ..
"\n\t\tlua_pushlstring(L, rtn.c_str(), rtn.length());" ..
"\n\t\treturn 1;" ..
"\n\t}"),
method.text);
end,
["find all functions in Node"] = function(self)
local type = Type.New(self.polo, {});
local tm = self.generator:TypeManipulators(type)
local funcs = self.generator:findAllFunctionsInNode(self.polo);
Test.assertEquals(1, #funcs);
Test.assertEquals(self.poloDoSomething, funcs[1]);
end,
["wrap methods"] = function(self)
local type = Type.New(self.polo, {});
local tm = self.generator:TypeManipulators(type)
local text = self.generator:wrapMethods({ helperName = "PoloMethodLuaGlue", originalNode = self.polo, referenceType = self.poloPtr });
Test.assertEquals(self.trim(
"\tstruct PoloMethodLuaGlue" ..
"\n\t{" ..
"\n\t\tstatic int __index(lua_State * L)" ..
"\n\t\t{" ..
"\n\t\t\tExample::PoloPtr & ptr = Example::PoloLuaMetaData::GetInstance(L, 1);" ..
"\n\t\t\tstd::string index(luaL_checkstring(L, 2));" ..
"\n\t\t\treturn Example::PoloLuaMetaData::Index(L, ptr, index);" ..
"\n\t\t}" ..
"\n\tstatic int DoSomething(lua_State * L)" ..
"\n\t{" ..
"\n\t\tExample::PoloPtr & instance = Example::PoloLuaMetaData::GetInstance(L, 1);" ..
"\n\t\tint arg1(luaL_checkint(L, 2));" ..
"\n\t\tconst std::string arg2(luaL_checkstring(L, 3));" ..
"\n\t\tExample::ActionPtr & arg3_AsRef = Example::ActionLuaMetaData::GetInstance(L, 4);" ..
NEW_LINE .. "const Example::Action & arg3 = *(*(arg3_AsRef));" ..
"\n\t\tconst std::string & rtn = instance->DoSomething(arg1, arg2, arg3);" ..
"\n\t\tlua_pushlstring(L, rtn.c_str(), rtn.length());" ..
"\n\t\treturn 1;" ..
"\n\t}" ..
"\n\t};"),
text);
end,
}
}, -- end of wrapMethods test
} -- end of tests
} -- end of table
); -- end of register call
| apache-2.0 |
nesstea/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Tazhaal.lua | 13 | 1155 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Tazhaal
-- Admits players to the dock in Aht Urhgan
-- @pos -5.195 -1 -98.966 50
-----------------------------------
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(0x00dd,player:getGil(),100);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x00dd and option == 333) then
player:delGil(100);
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/globals/mobskills/Amplification.lua | 28 | 1256 | ---------------------------------------------------
-- Amplification
-- Enhances Magic Attack and Magic Defense. Bonus stacks when used by mobs.
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect1 = EFFECT_MAGIC_ATK_BOOST;
local typeEffect2 = EFFECT_MAGIC_DEF_BOOST;
local mabTotal = mob:getStatusEffect(EFFECT_MAGIC_ATK_BOOST);
local mdbTotal = mob:getStatusEffect(EFFECT_MAGIC_DEF_BOOST);
if (mob:getStatusEffect(EFFECT_MAGIC_ATK_BOOST) ~= nil) then -- mag atk bonus stacking
mabTotal = mabTotal:getPower() + 10;
else
mabTotal = 10;
end;
if (mob:getStatusEffect(EFFECT_MAGIC_DEF_BOOST) ~= nil) then -- mag def bonus stacking
mdbTotal = mdbTotal:getPower() + 10;
else
mdbTotal = 10;
end;
-- print(mabTotal)
-- print(mdbTotal)
skill:setMsg(MobBuffMove(mob, typeEffect1, mabTotal, 0, 180));
MobBuffMove(mob, typeEffect2, mdbTotal, 0, 180);
return typeEffect1;
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/spells/dokumori_san.lua | 11 | 1200 | -----------------------------------------
-- Spell: Dokumori: San
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local effect = EFFECT_POISON;
-- Base Stats
local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT));
--Duration Calculation
local duration = 360 * applyResistance(caster,spell,target,dINT,NINJUTSU_SKILL,0);
local power = 20;
--Calculates resist chanve from Reist Blind
if(target:hasStatusEffect(effect)) then
spell:setMsg(75); -- no effect
return effect;
end
if(math.random(0,100) >= target:getMod(MOD_POISONRES)) then
if(duration >= 120) then
if(target:addStatusEffect(effect,power,3,duration)) then
spell:setMsg(236);
else
spell:setMsg(75);
end
else
spell:setMsg(85);
end
else
spell:setMsg(284);
end
return effect;
end; | gpl-3.0 |
nesstea/darkstar | scripts/globals/mobskills/Luminous_Lance.lua | 39 | 1406 | ---------------------------------------------
-- Luminous Lance
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
require("scripts/zones/Empyreal_Paradox/TextIDs");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
local lanceTime = mob:getLocalVar("lanceTime");
local lanceOut = mob:getLocalVar("lanceOut");
if (not (target:hasStatusEffect(EFFECT_PHYSICAL_SHIELD) and target:hasStatusEffect(EFFECT_MAGIC_SHIELD)))
and (lanceTime + 60 < mob:getBattleTime()) and target:getCurrentAction() ~= ACTION_MOBABILITY_USING
and lanceOut == 1 then
return 0;
end
return 1;
end;
function onMobWeaponSkill(target, mob, skill)
mob:showText(mob, SELHTEUS_TEXT + 1);
local numhits = 1;
local accmod = 1;
local dmgmod = 1.6;
local info = MobRangedMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_RANGED,MOBPARAM_PIERCE,info.hitslanded);
mob:entityAnimationPacket("ids0");
mob:setLocalVar("lanceTime", mob:getBattleTime())
mob:setLocalVar("lanceOut", 0)
target:AnimationSub(3);
-- Cannot be resisted
target:addStatusEffect(EFFECT_STUN, 0, 0, 20);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Port_San_dOria/npcs/Bricorsant.lua | 36 | 1376 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Bricorsant
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
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)
player:startEvent(0x23a);
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 |
FailcoderAddons/supervillain-ui | SVUI_!Core/libs/AceVillain-1.0/widgets/shared/BorderWidget.lua | 3 | 7215 | -- Widget is based on the AceGUIWidget-DropDown.lua supplied with AceGUI-3.0
-- Widget created by Yssaril
local AceGUI = LibStub("AceGUI-3.0")
local Media = LibStub("LibSharedMedia-3.0")
local AceVillain = LibStub("AceVillain-1.0")
do
local widgetType = "LSM30_Border"
local widgetVersion = 999999
local contentFrameCache = {}
local function ReturnSelf(self)
self:ClearAllPoints()
self:Hide()
self.check:Hide()
table.insert(contentFrameCache, self)
end
local function ContentOnClick(this, button)
local self = this.obj
self:Fire("OnValueChanged", this.text:GetText())
if self.dropdown then
self.dropdown = AceVillain:ReturnDropDownFrame(self.dropdown)
end
end
local function ContentOnEnter(this, button)
local self = this.obj
local text = this.text:GetText()
local border = self.list[text] ~= text and self.list[text] or Media:Fetch('border',text)
this.dropdown:SetBackdrop({edgeFile = border,
bgFile=[[Interface\DialogFrame\UI-DialogBox-Background-Dark]],
tile = true, tileSize = 16, edgeSize = 16,
insets = { left = 4, right = 4, top = 4, bottom = 4 }})
end
local function GetContentLine()
local frame
if next(contentFrameCache) then
frame = table.remove(contentFrameCache)
else
frame = CreateFrame("Button", nil, UIParent)
--frame:SetWidth(320)
frame:SetHeight(18)
frame:SetHighlightTexture([[Interface\AddOns\SVUI_!Core\assets\textures\TITLE-HIGHLIGHT]], "ADD")
frame:SetScript("OnClick", ContentOnClick)
frame:SetScript("OnEnter", ContentOnEnter)
local check = frame:CreateTexture("OVERLAY")
check:SetWidth(16)
check:SetHeight(16)
check:SetPoint("LEFT",frame,"LEFT",1,-1)
check:SetTexture("Interface\\Buttons\\UI-CheckBox-Check")
check:Hide()
frame.check = check
local text = frame:CreateFontString(nil,"OVERLAY","GameFontWhite")
text:SetWordWrap(false)
text:SetPoint("LEFT", check, "RIGHT", 1, 0)
text:SetPoint("RIGHT", frame, "RIGHT", -2, 0)
text:SetJustifyH("LEFT")
text:SetText("Test Test Test Test Test Test Test")
frame.text = text
frame.ReturnSelf = ReturnSelf
end
frame:Show()
return frame
end
local function OnAcquire(self)
self:SetHeight(44)
self:SetWidth(320)
end
local function OnRelease(self)
self:SetText("")
self:SetLabel("")
self:SetDisabled(false)
self.value = nil
self.list = nil
self.open = nil
self.hasClose = nil
self.frame:ClearAllPoints()
self.frame:Hide()
end
local function SetValue(self, value) -- Set the value to an item in the List.
if self.list then
self:SetText(value or "")
end
self.value = value
end
local function GetValue(self)
return self.value
end
local function SetList(self, list) -- Set the list of values for the dropdown (key => value pairs)
self.list = list or Media:HashTable("border")
end
local function SetText(self, text) -- Set the text displayed in the box.
self.frame.text:SetText(text or "")
local border = self.list[text] ~= text and self.list[text] or Media:Fetch('border',text)
self.frame.displayButton:SetBackdrop({edgeFile = border,
bgFile=[[Interface\DialogFrame\UI-DialogBox-Background-Dark]],
tile = true, tileSize = 16, edgeSize = 16,
insets = { left = 4, right = 4, top = 4, bottom = 4 }})
end
local function SetLabel(self, text) -- Set the text for the label.
self.frame.label:SetText(text or "")
end
local function AddItem(self, key, value) -- Add an item to the list.
self.list = self.list or {}
self.list[key] = value
end
local SetItemValue = AddItem -- Set the value of a item in the list. <<same as adding a new item>>
local function SetMultiselect(self, flag) end -- Toggle multi-selecting. <<Dummy function to stay inline with the dropdown API>>
local function GetMultiselect() return false end-- Query the multi-select flag. <<Dummy function to stay inline with the dropdown API>>
local function SetItemDisabled(self, key) end-- Disable one item in the list. <<Dummy function to stay inline with the dropdown API>>
local function SetDisabled(self, disabled) -- Disable the widget.
self.disabled = disabled
if disabled then
self.frame:Disable()
else
self.frame:Enable()
end
end
local function textSort(a,b)
return string.upper(a) < string.upper(b)
end
local sortedlist = {}
local function ToggleDrop(this)
local self = this.obj
if self.dropdown then
self.dropdown = AceVillain:ReturnDropDownFrame(self.dropdown)
AceGUI:ClearFocus()
else
AceGUI:SetFocus(self)
self.dropdown = AceVillain:GetDropDownFrame()
local width = self.frame:GetWidth()
self.dropdown:SetPoint("TOPLEFT", self.frame, "BOTTOMLEFT")
self.dropdown:SetPoint("TOPRIGHT", self.frame, "BOTTOMRIGHT", width < 160 and (160 - width) or 0, 0)
for k, v in pairs(self.list) do
sortedlist[#sortedlist+1] = k
end
table.sort(sortedlist, textSort)
for i, k in ipairs(sortedlist) do
local f = GetContentLine()
f.text:SetText(k)
--print(k)
if k == self.value then
f.check:Show()
end
f.obj = self
f.dropdown = self.dropdown
self.dropdown:AddFrame(f)
end
wipe(sortedlist)
end
end
local function ClearFocus(self)
if self.dropdown then
self.dropdown = AceVillain:ReturnDropDownFrame(self.dropdown)
end
end
local function OnHide(this)
local self = this.obj
if self.dropdown then
self.dropdown = AceVillain:ReturnDropDownFrame(self.dropdown)
end
end
local function Drop_OnEnter(this)
this.obj:Fire("OnEnter")
end
local function Drop_OnLeave(this)
this.obj:Fire("OnLeave")
end
local function SetDropDownStyle(self, xTopleft, yTopleft, xBottomright, yBottomright)
self:RemoveTextures()
self:SetStyle("Frame", "Transparent")
self.Panel:SetPoint("TOPLEFT", self, "TOPLEFT", xTopleft, yTopleft)
self.Panel:SetPoint("BOTTOMRIGHT", self, "BOTTOMRIGHT", xBottomright, yBottomright)
end
local function Constructor()
local frame = AceVillain:GetBaseFrameWithWindow()
local self = {}
self.type = widgetType
self.frame = frame
frame.obj = self
frame.dropButton.obj = self
frame.dropButton:SetScript("OnEnter", Drop_OnEnter)
frame.dropButton:SetScript("OnLeave", Drop_OnLeave)
frame.dropButton:SetScript("OnClick",ToggleDrop)
frame:SetScript("OnHide", OnHide)
if(frame.SetStyle) then
SetDropDownStyle(frame, 2, -20, -2, 0)
frame.dropButton:ClearAllPoints()
frame.dropButton:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -2, 0)
if(SVUI and SVUI.API) then
SVUI.API:Set("PageButton", frame.dropButton, true)
end
frame.dropButton:SetParent(frame.Panel)
end
self.alignoffset = 31
self.OnRelease = OnRelease
self.OnAcquire = OnAcquire
self.ClearFocus = ClearFocus
self.SetText = SetText
self.SetValue = SetValue
self.GetValue = GetValue
self.SetList = SetList
self.SetLabel = SetLabel
self.SetDisabled = SetDisabled
self.AddItem = AddItem
self.SetMultiselect = SetMultiselect
self.GetMultiselect = GetMultiselect
self.SetItemValue = SetItemValue
self.SetItemDisabled = SetItemDisabled
self.ToggleDrop = ToggleDrop
AceGUI:RegisterAsWidget(self)
return self
end
AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion)
end
| mit |
ndbeals/Luabox | lua/luabox/cl_luabox.lua | 2 | 8787 | --Copyright 2014 Nathan Beals
function luabox.GetEditor()
if not luabox.Editor then
luabox.Editor = vgui.Create("Luabox_Editor_Frame")
luabox.Editor:SetDeleteOnClose( false )
luabox.Editor:Hide()
end
return luabox.Editor
end
function luabox.ShowEditor()
local editor = luabox.GetEditor()
if luabox.Editor then
editor:Show()
editor:MakePopup()
end
end
function luabox.HideEditor()
local editor = luabox.GetEditor()
if luabox.Editor then
editor:Hide()
end
end
function luabox.ToggleEditor()
luabox.GetEditor()
if luabox.Editor:IsVisible() then
luabox.HideEditor()
else
luabox.ShowEditor()
end
end
function luabox.SetCurrentScript( fs )
luabox.CurrentScript = fs
end
function luabox.GetCurrentScript()
return luabox.CurrentScript
end
concommand.Add( "luabox_toggle_ide" , luabox.ToggleEditor )
concommand.Add( "luabox_show_ide" , luabox.ShowEditor )
concommand.Add( "luabox_hide_ide" , luabox.HideEditor )
--[[
--- luabox.FileSystem Class.
--@section luabox.FileSystem
luabox.FileSystem = Class()
--- luabox.FileSystem Class Constructor.
-- Creates the FileSystem class (CLIENT ONLY).
--@param path File path for the Filesystem to load.
--@param root the root file system
function luabox.FileSystem:Initialize( path , root )
self:SetSingleFile( false )
self:SetPath( path or "luabox" )
self:SetRootFileSystem( root or self )
self:Build()
end
--- SetSingleFile.
-- Sets if the File System represents just a single file
--@param bool is single file
function luabox.FileSystem:SetSingleFile( bool )
self.SingleFile = bool
end
--- GetSingleFile.
-- Gets if the File System represents just a single file
--@return singlefile boolean if it's a single file
function luabox.FileSystem:GetSingleFile()
return self.SingleFile
end
function luabox.FileSystem:GetRootFileSystem()
return self.RootFileSystem
end
function luabox.FileSystem:SetRootFileSystem( root )
self.RootFileSystem = root
end
function luabox.FileSystem:SetPath( path )
self.Path = path
self:SetShortPath( path )
end
function luabox.FileSystem:GetPath()
return self.Path
end
function luabox.FileSystem:SetShortPath( path )
local paths = string.Explode( "/" , path )
self.ShortPath = paths[ #paths ]
end
function luabox.FileSystem:GetShortPath()
return self.ShortPath
end
luabox.FileSystem.GetName = luabox.FileSystem.GetShortPath
function luabox.FileSystem:GetFiles()
return self.Files
end
function luabox.FileSystem:GetDirectories()
return self.Directories
end
function luabox.FileSystem:Search( path )
local ret
if string.TrimRight( self:GetPath() , "/") == string.TrimRight( path , "/" ) then
return self
end
if string.find(string.TrimRight( self:GetPath() , "/") , string.TrimRight( path , "/" )) then
return self
end
for i , v in ipairs( self.Directories ) do
ret = v:Search( path )
if ret then
return ret
end
end
for i , v in ipairs( self.Files ) do
ret = v:Search( path )
if ret then
return ret
end
end
end
function luabox.FileSystem:Delete()
for i , v in ipairs( self.Files ) do
v:Delete()
end
for i , v in ipairs( self.Directories ) do
v:Delete()
end
file.Delete( self:GetPath() )
self:GetRootFileSystem():Refresh( true )
end
function luabox.FileSystem:Copy( destfs )
if not destfs then return false end
if (destfs:GetPath() .. "/" .. self:GetShortPath()) == self:GetPath() then return false end
if destfs:GetSingleFile() then return false end
local newpath = destfs:GetPath() .. "/" .. self:GetShortPath()
local newfs = luabox.FileSystem( newpath , destfs )
file.CreateDir( destfs:GetPath() .. "/" .. self:GetShortPath() )
table.insert( destfs.Directories , newfs )
for i , v in ipairs( self.Files ) do
v:Copy( newfs )
end
for i , v in ipairs( self.Directories ) do
v:Copy( newfs )
end
self:GetRootFileSystem():Refresh( true )
return true
end
function luabox.FileSystem:Move( destfs )
if not destfs then return false end
if (destfs:GetPath() .. "/" .. self:GetShortPath()) == self:GetPath() then return false end
if destfs:GetSingleFile() then return false end
local oldpath = self:GetPath()
file.CreateDir( destfs:GetPath() .. "/" .. self:GetShortPath() )
self:SetPath( destfs:GetPath() .. "/" .. self:GetShortPath() )
for i , v in ipairs( self.Files ) do
v:Move( self )
end
for i , v in ipairs( self.Directories ) do
v:Move( self )
end
file.Delete( oldpath )
self:GetRootFileSystem():Refresh( true )
return true
end
function luabox.FileSystem:AddFile( name )
if not name then return false end
if self:GetSingleFile() then return false end
if not (string.GetExtensionFromFilename( name ) == "txt") then
name = name .. ".txt"
end
local newfile = luabox.File( self:GetPath() .. "/" .. name , self )
file.Write( newfile:GetPath() , "" )
table.insert( self.Files , newfile )
self:GetRootFileSystem():Refresh( true )
return newfile
end
function luabox.FileSystem:AddDirectory( name )
if not name then return false end
if self:GetSingleFile() then return false end
local directory = luabox.FileSystem( self:GetPath() .. "/" .. name , self)
file.CreateDir( self:GetPath() .. "/" .. name )
table.insert( self.Directories , directory )
self:GetRootFileSystem():Refresh( true )
return directory
end
function luabox.FileSystem:Build()
self.Files = {}
self.Directories = {}
if self:GetSingleFile() then return end
local files , directories = file.Find( self.Path .. "/*" , "DATA" , "namedesc" )
for i , v in ipairs( files ) do
self.Files[ i ] = luabox.File( self.Path .. "/" .. v , self )
end
for i , v in ipairs( directories ) do
self.Directories[ i ] = luabox.FileSystem( self.Path .. "/" .. v , self )
end
end
function luabox.FileSystem:Refresh( recurse , changed )
if self:GetSingleFile() then return end
changed = changed or false
local files , directories = file.Find( self.Path .. "/*" , "DATA" , "namedesc" )
local i = 1
while i <= (#self.Directories) do
if not TableHasValue( directories , self.Directories[i]:GetName()) then
table.remove( self.Directories , i )
i = i - 1
changed = true
end
i = i + 1
end
for i , v in ipairs( directories ) do
local new = true
for _i , _v in ipairs( self.Directories ) do
if v == _v:GetName() then
--new = true
new = false
break
end
end
if new then
table.insert( self.Directories , i , luabox.FileSystem( self.Path .. "/" .. v , self ) )
changed = true
end
end
i = 1
while i <= (#self.Files) do
if not TableHasValue( files , self.Files[i]:GetName()) then
table.remove( self.Files , i )
i = i - 1
changed = true
end
i = i + 1
end
for i , v in ipairs( files ) do
local new = true
for _i , _v in ipairs( self.Files ) do
if v == _v:GetName() then
--new = true
new = false
break
end
end
if new then
table.insert( self.Files , i , luabox.File( self.Path .. "/" .. v , self ) )
changed = true
end
end
if recurse then
for i , v in ipairs( self.Directories ) do
changed = v:Refresh( recurse , changed )
end
for i , v in ipairs( self.Files ) do
changed = v:Refresh( recurse , changed )
end
end
return changed
end
luabox.File = Class( luabox.FileSystem )
--- luabox.File Class.
--@section luabox.File
--- luabox.File Class Constructor.
-- Creates the FileSystem class (CLIENT ONLY).
--@param path File path for the Filesystem to load.
--@param root the root file system
function luabox.File:Initialize( path , root )
self:SetSingleFile( true )
self:SetPath( path or "luabox" )
self:SetRootFileSystem( root or self )
self.Files = {}
self.Directories = {}
end
function luabox.File:Copy( destfs )
if not destfs then return false end
if (destfs:GetPath() .. "/" .. self:GetShortPath()) == self:GetPath() then return false end
if destfs:GetSingleFile() then return false end
local newpath = destfs:GetPath() .. "/" .. self:GetShortPath()
local newfs = File( newpath , destfs )
file.Write( newpath , file.Read( self:GetPath() , "DATA" ) )
newfs:SetSingleFile( true )
table.insert( destfs.Files , newfs )
return true
end
function luabox.File:Move( destfs )
if not destfs then return false end
if (destfs:GetPath() .. "/" .. self:GetShortPath()) == self:GetPath() then return false end
if destfs:GetSingleFile() then return false end
file.Write( destfs:GetPath() .. "/" .. self:GetShortPath() , file.Read( self:GetPath() , "DATA" ) )
file.Delete( self:GetPath() )
self:SetPath( destfs:GetPath() .. "/" .. self:GetShortPath() )
return true
end
function luabox.File:Read()
return file.Read( self:GetPath() , "DATA" )
end
function luabox.File:Write( str )
file.Write( self:GetPath() , str )
end
--]]
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Windurst_Waters/npcs/Ten_of_Hearts.lua | 38 | 1045 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Ten of Hearts
-- Type: Standard NPC
-- @zone: 238
-- @pos -49.441 -5.909 226.524
--
-- Auto-Script: Requires Verification (Verfied By Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x006b);
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 |
Mashape/kong | spec/03-plugins/19-hmac-auth/04-invalidations_spec.lua | 2 | 8514 | local helpers = require "spec.helpers"
local cjson = require "cjson"
local openssl_hmac = require "openssl.hmac"
for _, strategy in helpers.each_strategy() do
describe("Plugin: hmac-auth (invalidations) [#" .. strategy .. "]", function()
local proxy_client
local admin_client
local consumer
local credential
local db
lazy_setup(function()
local bp
bp, db = helpers.get_db_utils(strategy, {
"routes",
"services",
"plugins",
"consumers",
"hmacauth_credentials",
})
local route = bp.routes:insert {
hosts = { "hmacauth.com" },
}
bp.plugins:insert {
name = "hmac-auth",
route = { id = route.id },
config = {
clock_skew = 3000,
},
}
consumer = bp.consumers:insert {
username = "consumer1",
custom_id = "1234",
}
credential = bp.hmacauth_credentials:insert {
username = "bob",
secret = "secret",
consumer = { id = consumer.id },
}
assert(helpers.start_kong({
database = strategy,
nginx_conf = "spec/fixtures/custom_nginx.template",
}))
proxy_client = helpers.proxy_client()
admin_client = helpers.admin_client()
end)
lazy_teardown(function()
if proxy_client and admin_client then
proxy_client:close()
admin_client:close()
end
helpers.stop_kong(nil, true)
end)
local function hmac_sha1_binary(secret, data)
return openssl_hmac.new(secret, "sha1"):final(data)
end
local function get_authorization(username)
local date = os.date("!%a, %d %b %Y %H:%M:%S GMT")
local encodedSignature = ngx.encode_base64(hmac_sha1_binary("secret", "date: " .. date))
return [["hmac username="]] .. username
.. [[",algorithm="hmac-sha1",headers="date",signature="]]
.. encodedSignature .. [["]], date
end
describe("HMAC Auth Credentials entity invalidation", function()
it("should invalidate when Hmac Auth Credential entity is deleted", function()
-- It should work
local authorization, date = get_authorization("bob")
local res = assert(proxy_client:send {
method = "GET",
path = "/requests",
body = {},
headers = {
["HOST"] = "hmacauth.com",
date = date,
authorization = authorization
}
})
assert.res_status(200, res)
-- Check that cache is populated
local cache_key = db.hmacauth_credentials:cache_key("bob")
res = assert(admin_client:send {
method = "GET",
path = "/cache/" .. cache_key,
body = {},
})
assert.res_status(200, res)
-- Retrieve credential ID
res = assert(admin_client:send {
method = "GET",
path = "/consumers/consumer1/hmac-auth/",
body = {},
})
local body = assert.res_status(200, res)
local credential_id = cjson.decode(body).data[1].id
assert.equal(credential.id, credential_id)
-- Delete Hmac Auth credential (which triggers invalidation)
res = assert(admin_client:send {
method = "DELETE",
path = "/consumers/consumer1/hmac-auth/" .. credential_id,
body = {},
})
assert.res_status(204, res)
-- ensure cache is invalidated
helpers.wait_until(function()
local res = assert(admin_client:send {
method = "GET",
path = "/cache/" .. cache_key
})
res:read_body()
return res.status == 404
end)
-- It should not work
authorization, date = get_authorization("bob")
local res = assert(proxy_client:send {
method = "POST",
body = {},
headers = {
["HOST"] = "hmacauth.com",
date = date,
authorization = authorization
}
})
assert.res_status(401, res)
end)
it("should invalidate when Hmac Auth Credential entity is updated", function()
local res = assert(admin_client:send {
method = "POST",
path = "/consumers/consumer1/hmac-auth/",
body = {
username = "bob",
secret = "secret",
consumer = { id = consumer.id },
},
headers = {
["Content-Type"] = "application/json",
}
})
local body = assert.res_status(201, res)
credential = cjson.decode(body)
-- It should work
local authorization, date = get_authorization("bob")
local res = assert(proxy_client:send {
method = "GET",
path = "/requests",
body = {},
headers = {
["HOST"] = "hmacauth.com",
date = date,
authorization = authorization
}
})
assert.res_status(200, res)
-- It should not work
local authorization, date = get_authorization("hello123")
res = assert(proxy_client:send {
method = "GET",
path = "/requests",
body = {},
headers = {
["HOST"] = "hmacauth.com",
date = date,
authorization = authorization
}
})
assert.res_status(401, res)
-- Update Hmac Auth credential (which triggers invalidation)
res = assert(admin_client:send {
method = "PATCH",
path = "/consumers/consumer1/hmac-auth/" .. credential.id,
body = {
username = "hello123"
},
headers = {
["Content-Type"] = "application/json"
}
})
assert.res_status(200, res)
-- ensure cache is invalidated
local cache_key = db.hmacauth_credentials:cache_key("bob")
helpers.wait_until(function()
local res = assert(admin_client:send {
method = "GET",
path = "/cache/" .. cache_key
})
res:read_body()
return res.status == 404
end)
-- It should work
local authorization, date = get_authorization("hello123")
local res = assert(proxy_client:send {
method = "GET",
body = {},
headers = {
["HOST"] = "hmacauth.com",
date = date,
authorization = authorization
}
})
assert.res_status(200, res)
end)
end)
describe("Consumer entity invalidation", function()
it("should invalidate when Consumer entity is deleted", function()
-- It should work
local authorization, date = get_authorization("hello123")
local res = assert(proxy_client:send {
method = "GET",
path = "/requests",
body = {},
headers = {
["HOST"] = "hmacauth.com",
date = date,
authorization = authorization
}
})
assert.res_status(200, res)
-- Check that cache is populated
local cache_key = db.hmacauth_credentials:cache_key("hello123")
res = assert(admin_client:send {
method = "GET",
path = "/cache/" .. cache_key,
body = {},
})
assert.res_status(200, res)
-- Delete Consumer (which triggers invalidation)
res = assert(admin_client:send {
method = "DELETE",
path = "/consumers/consumer1",
body = {},
})
assert.res_status(204, res)
-- ensure cache is invalidated
helpers.wait_until(function()
local res = assert(admin_client:send {
method = "GET",
path = "/cache/" .. cache_key
})
res:read_body()
return res.status == 404
end)
-- It should not work
local authorization, date = get_authorization("bob")
local res = assert(proxy_client:send {
method = "GET",
body = {},
headers = {
["HOST"] = "hmacauth.com",
date = date,
authorization = authorization
}
})
assert.res_status(401, res)
end)
end)
end)
end
| apache-2.0 |
nesstea/darkstar | scripts/globals/items/sazanbaligi.lua | 18 | 1311 | -----------------------------------------
-- ID: 5459
-- Item: Sazanbaligi
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 4
-- Mind -6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:getRace() ~= 7) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5459);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 4);
target:addMod(MOD_MND, -6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 4);
target:delMod(MOD_MND, -6);
end;
| gpl-3.0 |
NezzKryptic/Wire-Extras | lua/entities/gmod_wire_hud_indicator_2/renderer/valid_fonts.lua | 3 | 3288 | -- Just a list of valid fonts.
--
-- Comment out any you dont want to be usable, and
-- the default font will be used where the commented
-- out font is requested.
--
-- Moggie100
print("[II]", "Loading font list...")
H2Fonts = {}
H2Fonts["Default"] = "Default"
H2Fonts["DebugFixed"] = "DebugFixed"
H2Fonts["DebugFixedSmall"] = "DebugFixedSmall"
H2Fonts["DefaultFixedOutline"] = "DefaultFixedOutline"
H2Fonts["MenuItem"] = "MenuItem"
H2Fonts["TabLarge"] = "TabLarge"
H2Fonts["DefaultBold"] = "DefaultBold"
H2Fonts["DefaultUnderline"] = "DefaultUnderline"
H2Fonts["DefaultSmall"] = "DefaultSmall"
H2Fonts["DefaultSmallDropShadow"] = "DefaultSmallDropShadow"
H2Fonts["DefaultVerySmall"] = "DefaultVerySmall"
H2Fonts["DefaultLarge"] = "DefaultLarge"
H2Fonts["UiBold"] = "UiBold"
H2Fonts["MenuLarge"] = "MenuLarge"
H2Fonts["ConsoleText"] = "ConsoleText"
H2Fonts["Marlett"] = "Marlett"
H2Fonts["Trebuchet18"] = "Trebuchet18"
H2Fonts["Trebuchet19"] = "Trebuchet19"
H2Fonts["Trebuchet20"] = "Trebuchet20"
H2Fonts["Trebuchet22"] = "Trebuchet22"
H2Fonts["Trebuchet24"] = "Trebuchet24"
H2Fonts["HUDNumber"] = "HUDNumber"
H2Fonts["HUDNumber1"] = "HUDNumber1"
H2Fonts["HUDNumber2"] = "HUDNumber2"
H2Fonts["HUDNumber3"] = "HUDNumber3"
H2Fonts["HUDNumber4"] = "HUDNumber4"
H2Fonts["HUDNumber5"] = "HUDNumber5"
H2Fonts["HudHintTextLarge"] = "HudHintTextLarge"
H2Fonts["HudHintTextSmall"] = "HudHintTextSmall"
H2Fonts["CenterPrintText"] = "CenterPrintText"
H2Fonts["HudSelectionText"] = "HudSelectionText"
H2Fonts["DefaultFixed"] = "DefaultFixed"
H2Fonts["DefaultFixedDropShadow"] = "DefaultFixedDropShadow"
H2Fonts["CloseCaption_Normal"] = "CloseCaption_Normal"
H2Fonts["CloseCaption_Bold"] = "CloseCaption_Bold"
H2Fonts["CloseCaption_BoldItalic"] = "CloseCaption_BoldItalic"
H2Fonts["TitleFont"] = "TitleFont"
H2Fonts["TitleFont2"] = "TitleFont2"
H2Fonts["ChatFont"] = "ChatFont"
H2Fonts["TargetID"] = "TargetID"
H2Fonts["TargetIDSmall"] = "TargetIDSmall"
H2Fonts["HL2MPTypeDeath"] = "HL2MPTypeDeath"
H2Fonts["BudgetLabel"] = "BugetLabel"
H2Fonts["ScoreboardText"] = "ScoreboardText"
-- Aliases, for ease of use... subject to change.
--
-- Also, self-referential, so could cause issues if elements do not exist, hence the 'or Default' part.
H2Fonts["Bold"] = H2Fonts["DefaultBold"] or "Default"
H2Fonts["Underline"] = H2Fonts["DefaultUnderline"] or "Default"
H2Fonts["Small"] = H2Fonts["DefaultSmall"] or "Default"
H2Fonts["SmallShadowed"] = H2Fonts["DefaultSmallDropShadow"] or "Default"
H2Fonts["VerySmall"] = H2Fonts["DefaultVerySmall"] or "Default"
H2Fonts["Large"] = H2Fonts["DefaultLarge"] or "Default"
H2Fonts["Console"] = H2Fonts["ConsoleText"] or "Default"
H2Fonts["LargeHint"] = H2Fonts["HudHintTextLarge"] or "Default"
H2Fonts["SmallHint"] = H2Fonts["HudHintTextSmall"] or "Default"
H2Fonts["Selected"] = H2Fonts["HudSelectionText"] or "Default"
H2Fonts["Fixed"] = H2Fonts["DefaultFixed"] or "Default"
H2Fonts["FixedShadowed"] = H2Fonts["DefaultFixedDropShadow"] or "Default"
H2Fonts["Title"] = H2Fonts["TitleFont"] or "Default"
H2Fonts["Title2"] = H2Fonts["TitleFont2"] or "Default"
H2Fonts["Chat"] = H2Fonts["ChatFont"] or "Default"
print( "[II]", "Loaded fonts!" )
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/weaponskills/vidohunir.lua | 12 | 4739 | -----------------------------------
-- Vidohunir
-- Staff weapon skill
-- Skill Level: N/A
-- Lowers target's magic defense. Duration of effect varies with TP. Laevateinn: Aftermath effect varies with TP.
-- Reduces enemy's magic defense by 10%.
-- Available only after completing the Unlocking a Myth (Black Mage) quest.
-- Aligned with the Breeze Gorget, Thunder Gorget, Aqua Gorget & Snow Gorget.
-- Aligned with the Breeze Belt, Thunder Belt, Aqua Belt & Snow Belt.
-- Element: Darkness
-- Modifiers: INT:30%
-- 100%TP 200%TP 300%TP
-- 1.75 1.75 1.75
-----------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.ftp100 = 1.75; params.ftp200 = 1.75; params.ftp300 = 1.75;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.3; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.ele = ELE_DARK;
params.skill = SKILL_STF;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.int_wsc = 0.8;
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params);
if damage > 0 then
local tp = player:getTP();
local duration = (tp/100 * 60);
if(target:hasStatusEffect(EFFECT_MAGIC_DEF_DOWN) == false) then
target:addStatusEffect(EFFECT_MAGIC_DEF_DOWN, 10, 0, duration);
end
end
if((player:getEquipID(SLOT_MAIN) == 18994) and (player:getMainJob() == JOB_BLM)) then
if(damage > 0) then
-- AFTERMATH LV1
if ((player:getTP() >= 100) and (player:getTP() <= 110)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 10, 0, 180, 0, 2);
elseif ((player:getTP() >= 111) and (player:getTP() <= 120)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 11, 0, 180, 0, 2);
elseif ((player:getTP() >= 121) and (player:getTP() <= 130)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 12, 0, 180, 0, 2);
elseif ((player:getTP() >= 131) and (player:getTP() <= 140)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 13, 0, 180, 0, 2);
elseif ((player:getTP() >= 141) and (player:getTP() <= 150)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 14, 0, 180, 0, 2);
elseif ((player:getTP() >= 151) and (player:getTP() <= 160)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 15, 0, 180, 0, 2);
elseif ((player:getTP() >= 161) and (player:getTP() <= 170)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 16, 0, 180, 0, 2);
elseif ((player:getTP() >= 171) and (player:getTP() <= 180)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 17, 0, 180, 0, 2);
elseif ((player:getTP() >= 181) and (player:getTP() <= 190)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 18, 0, 180, 0, 2);
elseif ((player:getTP() >= 191) and (player:getTP() <= 199)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 19, 0, 180, 0, 2);
-- AFTERMATH LV2
elseif ((player:getTP() >= 200) and (player:getTP() <= 210)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 24, 0, 180, 0, 3);
elseif ((player:getTP() >= 211) and (player:getTP() <= 219)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 28, 0, 180, 0, 3);
elseif ((player:getTP() >= 221) and (player:getTP() <= 229)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 32, 0, 180, 0, 3);
elseif ((player:getTP() >= 231) and (player:getTP() <= 239)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 36, 0, 180, 0, 3);
elseif ((player:getTP() >= 241) and (player:getTP() <= 249)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 40, 0, 180, 0, 3);
elseif ((player:getTP() >= 251) and (player:getTP() <= 259)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 44, 0, 180, 0, 3);
elseif ((player:getTP() >= 261) and (player:getTP() <= 269)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 48, 0, 180, 0, 3);
elseif ((player:getTP() >= 271) and (player:getTP() <= 279)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 52, 0, 180, 0, 3);
elseif ((player:getTP() >= 281) and (player:getTP() <= 289)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 56, 0, 180, 0, 3);
elseif ((player:getTP() >= 291) and (player:getTP() <= 299)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 59, 0, 180, 0, 3);
-- AFTERMATH LV3
elseif ((player:getTP() == 300)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV3, 45, 0, 120, 0, 1);
end
end
end
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
nesstea/darkstar | scripts/globals/items/bowl_of_shark_fin_soup.lua | 18 | 1843 | -----------------------------------------
-- ID: 4452
-- Item: bowl_of_shark_fin_soup
-- Food Effect: 3Hrs, All Races
-----------------------------------------
-- HP % 5
-- MP 5
-- Dexterity 4
-- Mind -4
-- HP Recovered While Healing 9
-- Attack % 14 (cap 60)
-- Ranged Attack % 14 (cap 60)
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4452);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 5);
target:addMod(MOD_FOOD_HP_CAP, 999);
target:addMod(MOD_DEX, 4);
target:addMod(MOD_MND, -4);
target:addMod(MOD_HPHEAL, 9);
target:addMod(MOD_FOOD_ATTP, 14);
target:addMod(MOD_FOOD_ATT_CAP, 60);
target:addMod(MOD_FOOD_RATTP, 14);
target:addMod(MOD_FOOD_RATT_CAP, 60);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 5);
target:delMod(MOD_FOOD_HP_CAP, 999);
target:delMod(MOD_DEX, 4);
target:delMod(MOD_MND, -4);
target:delMod(MOD_HPHEAL, 9);
target:delMod(MOD_FOOD_ATTP, 14);
target:delMod(MOD_FOOD_ATT_CAP, 60);
target:delMod(MOD_FOOD_RATTP, 14);
target:delMod(MOD_FOOD_RATT_CAP, 60);
end;
| gpl-3.0 |
twolfson/sublime-files | Packages/Lua/tests/syntax_test_lua.lua | 1 | 12576 | -- SYNTAX TEST "Packages/Lua/Lua.sublime-syntax"
--COMMENTS
-- Foo!
-- ^^^^^^^ comment.line
-- ^^ punctuation.definition.comment
--[[ Foo! ]]
-- ^^^^^^^^^^^^ comment.block
-- ^^^^ punctuation.definition.comment.begin
-- ^^ punctuation.definition.comment.end
--[=[ Foo! ]] ]=]
-- ^^^^^^^^^^^^^^^^^ comment.block
-- ^^^^^ punctuation.definition.comment.begin
-- ^^ - punctuation
-- ^^^ punctuation.definition.comment.end
--[=[
-- ^^^^^ comment.block punctuation.definition.comment.begin
]]
-- ^^^ comment.block - punctuation
]==]
-- ^^^^ comment.block - punctuation
--
-- ^^ - punctuation
[[
-- ^^ - punctuation
]=]
-- ^^^ comment.block punctuation.definition.comment.end
--VARIABLES
foo;
-- ^^^ variable.other
true_ish;
-- ^^^^^^^^ variable.other - constant
--CONSTANTS
true;
-- ^^^^ constant.language.boolean.true
false;
-- ^^^^^ constant.language.boolean.true
nil;
-- ^^^ constant.language.null
...;
-- ^^^ constant.language
self;
-- ^^^^ variable.language.this
--NUMBERS
0;
-- ^ constant.numeric.decimal
1234567890;
-- ^^^^^^^^^^ constant.numeric.decimal
12.345;
-- ^^^^^^ constant.numeric.decimal
1e10;
-- ^^^^ constant.numeric.decimal
0.5e+0;
-- ^^^^^^ constant.numeric.decimal
9e-1;
-- ^^^^ constant.numeric.decimal
0x0;
-- ^^^ constant.numeric.hexadecimal
-- ^^ punctuation.definition.numeric.hexadecimal
0XdeafBEEF42;
-- ^^^^^^^^^^^^ constant.numeric.hexadecimal
-- ^^ punctuation.definition.numeric.hexadecimal
0xa.bc;
-- ^^^^^^ constant.numeric.hexadecimal
-- ^^ punctuation.definition.numeric.hexadecimal
0x1p10;
-- ^^^^^^ constant.numeric.hexadecimal
-- ^^ punctuation.definition.numeric.hexadecimal
'foo';
-- ^^^^^ string.quoted.single
-- ^ punctuation.definition.string.begin
-- ^ punctuation.definition.string.end
--STRINGS
'foo';
-- ^^^^^ string.quoted.single
-- ^ punctuation.definition.string.begin
-- ^ punctuation.definition.string.end
'-- [[';
-- ^^^^^^^ string.quoted.single - comment
"foo";
-- ^^^^^ string.quoted.double
-- ^ punctuation.definition.string.begin
-- ^ punctuation.definition.string.end
"-- [[";
-- ^^^^^^^ string.quoted.double - comment
'\a\b\f\n\r\t\v\\\'\"\[\]';
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^ string.quoted.single
-- ^^^^^^^^^^^^^^^^^^^^^^^^ constant.character.escape
'\x1ff';
-- ^^^^ constant.character.escape.hexadecimal
-- ^ - constant
'\0 \123 \1234';
-- ^^ constant.character.escape.decimal
-- ^^^^ constant.character.escape.decimal
-- ^^^^ constant.character.escape.decimal
-- ^ - constant
'\u{0} \u{f00d}';
-- ^^^^^ constant.character.escape.unicode
-- ^^^^^^^^ constant.character.escape.unicode
'\z
-- ^^^^^ constant.character.escape - invalid
';
'\z
-- <- constant.character.escape
';
'\z done';
-- ^^^^ constant.character.escape
-- ^^^^ - constant
'\
-- ^^ constant.character.escape
-- <- - invalid
'foo\q';
-- ^^ invalid.illegal.invalid-escape
'
-- ^ invalid.illegal.unclosed-string
"foo\"\'";
-- ^^^^^^^^^ string.quoted.double
-- ^ punctuation.definition.string.begin
-- ^^^^ constant.character.escape
-- ^ punctuation.definition.string.end
[[ Foo! ]];
-- ^^^^^^^^^^ string.quoted.multiline
-- ^^ punctuation.definition.string.begin
-- ^^ punctuation.definition.string.end
[[ -- [[ ]];
-- ^^^^^^^^^^^ string.quoted.multiline - comment
[[ Foo! \a \]];
-- ^^^^^^^^^^^^^^ string.quoted.multiline
-- ^^ punctuation.definition.string.begin
-- ^^^^ - constant
-- ^^ punctuation.definition.string.end
[=[ Foo! ]] ]=];
-- ^^^^^^^^^^^^^^^ string.quoted.multiline
-- ^^^ punctuation.definition.string.begin
-- ^^ - punctuation
-- ^^^ punctuation.definition.string.end
[=[
-- ^^^ string.quoted.multiline punctuation.definition.string.begin
]]
-- ^^^ string.quoted.multiline - punctuation
]==]
-- ^^^^ string.quoted.multiline - punctuation
]=];
-- ^^^ string.quoted.multiline punctuation.definition.string.end
--OPERATORS
#'foo';
-- ^ keyword.operator.length
-1;
-- ^ keyword.operator.arithmetic
-- ^ constant.numeric.decimal
~1;
-- ^ keyword.operator.bitwise
-- ^ constant.numeric.decimal
not true;
-- ^^^ keyword.operator.logical
-- ^^^^ constant.language.boolean.true
2 + 2 - 2 * 2 / 2 // 2 % 2 ^ 2;
-- ^ keyword.operator.arithmetic
-- ^ keyword.operator.arithmetic
-- ^ keyword.operator.arithmetic
-- ^ keyword.operator.arithmetic
-- ^^ keyword.operator.arithmetic
-- ^ keyword.operator.arithmetic
-- ^ keyword.operator.arithmetic
2 >> 2 << 2 & 2 | 2 ~ 2;
-- ^^ keyword.operator.bitwise
-- ^^ keyword.operator.bitwise
-- ^ keyword.operator.bitwise
-- ^ keyword.operator.bitwise
-- ^ keyword.operator.bitwise
2 > 2; 2 < 2; 2 == 2; 2 >= 2; 2 <= 2; 2 ~= 2;
-- ^ keyword.operator.comparison
-- ^ keyword.operator.comparison
-- ^^ keyword.operator.comparison
-- ^^ keyword.operator.comparison
-- ^^ keyword.operator.comparison
-- ^^ keyword.operator.comparison
true and false or nil;
-- ^^^ keyword.operator.logical
-- ^^ keyword.operator.logical
'foo' .. 'bar';
-- ^^ keyword.operator.concatenation
x = 42;
-- ^ keyword.operator.assignment
--TABLES
{};
-- ^^ meta.mapping
-- ^ punctuation.section.block.begin
-- ^ punctuation.section.block.end
{a, b + c; c};
-- ^^^^^^^^^^^^^ meta.mapping
-- ^ punctuation.section.block.begin
-- ^ variable.other
-- ^ punctuation.separator.field
-- ^ variable.other
-- ^ variable.other
-- ^ punctuation.separator.field
-- ^ variable.other
-- ^ punctuation.section.block.end
{[a] = x, b = y};
-- ^^^ meta.brackets
-- ^ punctuation.section.brackets.begin
-- ^ variable.other
-- ^ punctuation.section.brackets.end
-- ^ punctuation.separator.key-value
-- ^ variable.other
-- ^ punctuation.separator.field
-- ^ meta.key string.unquoted.key
-- ^ punctuation.separator.key-value
-- ^ meta.mapping variable.other
--PARENS
(foo + bar);
-- ^^^^^^^^^^^ meta.group
-- ^ punctuation.section.group.begin
-- ^ punctuation.section.group.end
foo.bar;
-- ^ punctuation.accessor
-- ^^^ meta.property
foo:bar;
-- ^ punctuation.accessor
-- ^^^ meta.property
foo.baz();
-- ^ punctuation.accessor
-- ^^^ meta.property variable.function
foo.baz "";
-- ^ punctuation.accessor
-- ^^^ meta.property variable.function
foo.baz '';
-- ^ punctuation.accessor
-- ^^^ meta.property variable.function
foo.baz [=[ a string ]=];
-- ^ punctuation.accessor
-- ^^^ meta.property variable.function
foo.baz {};
-- ^ punctuation.accessor
-- ^^^ meta.property variable.function
-- ^^ meta.function-call.arguments meta.mapping
foo[bar + baz];
-- ^^^^^^^^^^^ meta.brackets
-- ^ punctuation.section.brackets.begin
-- ^ punctuation.section.brackets.end
--FUNCTION CALLS
f(42);
-- ^ variable.function
-- ^ meta.function-call.arguments meta.group
-- ^ punctuation.section.group.begin
-- ^ punctuation.section.group.end
f "argument";
-- ^ variable.function
-- ^^^^^^^^^^ meta.function-call.arguments string.quoted.double
f
'argument';
-- ^^^^^^^^^^ meta.function-call.arguments string.quoted.single
f [[ foo ]];
-- ^ variable.function
-- ^^^^^^^^^ meta.function-call.arguments string.quoted.multiline
f {};
-- ^ variable.function
-- ^^ meta.function-call.arguments meta.mapping
--FUNCTIONS
function function_name( a, b, ... )
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.function
-- ^^^^^^^^ storage.type.function
-- ^^^^^^^^^^^^^ entity.name.function
-- ^^^^^^^^^^^^^ meta.group
-- ^ punctuation.section.group.begin
-- ^ variable.parameter.function
-- ^ punctuation.separator.comma
-- ^ variable.parameter.function
-- ^ punctuation.separator.comma
-- ^^^ constant.language
-- ^ punctuation.section.group.end
end
-- ^^^ meta.function meta.block keyword.control.end
function foo.bar:baz (...) end
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.function
-- ^^^ variable.other - entity
-- ^ punctuation.accessor
-- ^^^ meta.property - entity
-- ^ punctuation.accessor
-- ^^^ meta.property entity.name.function
-- ^^^^^ meta.group
-- ^^^ keyword.control.end
function foo
.bar () end
-- ^^^^^^^^^^^ meta.function
-- ^ punctuation.accessor
-- ^^^ entity.name.function
local function foo () end
-- ^^^^^ storage.modifier
-- ^^^^^^^^^^^^^^^^^^^ meta.function
-- ^^^ entity.name.function
~function( a, b, ... ) end;
-- ^^^^^^^^^^^^^^^^^^^^^^^^^ meta.function
-- ^^^^^^^^ storage.type
-- ^^^^^^^^^^^^^ meta.group
-- ^^^ keyword.control.end
~function foo () end;
-- ^^^^^^^^^^^^^^^^^^^ meta.function
-- ^^^ entity.name.function
foo = function() end;
-- ^^^ entity.name.function
foo.bar = function() end;
-- ^^^ meta.property entity.name.function
--STATEMENTS
end;
-- ^^^ invalid.illegal.unexpected-end
do
-- ^^^ meta.block
-- ^^ keyword.control
2 + 2
end
-- ^^^^ meta.block
-- ^^^ keyword.control.end
do 2 + 2 end
-- ^^^^^^^^^^^^ meta.block
-- ^^ keyword.control
-- ^^^ keyword.control.end
if true then
-- ^^ keyword.control.conditional
-- ^^^^ keyword.control.conditional
2 + 2
elseif false then
-- ^^^^^^ keyword.control.conditional
-- ^^^^ keyword.control.conditional
else
-- ^^^^ keyword.control.conditional
end
while true do
-- ^^^^^ keyword.control.loop
-- ^^ keyword.control
2 + 2
end
-- ^^^ keyword.control.end
repeat
-- ^^^^^^ keyword.control.loop
2 + 2;
end;
-- ^^^ invalid.illegal.unexpected-end
until true;
-- ^^^^^ keyword.control.loop
-- ^^^^ constant.language.boolean.true
for x = 1, y, z do end
-- ^^^ keyword.control.loop
-- ^ variable.other
-- ^ keyword.operator.assignment
-- ^ punctuation.separator.comma
-- ^ variable.other
-- ^ punctuation.separator.comma
-- ^ variable.other
-- ^^^^^^ meta.block
-- ^^ keyword.control
-- ^^^ keyword.control.end
for x, y in a, b do end
-- ^^^ keyword.control.loop
-- ^ variable.other
-- ^ punctuation.separator.comma
-- ^ variable.other
-- ^^ keyword.control.loop
-- ^ variable.other
-- ^ punctuation.separator.comma
-- ^ variable.other
-- ^^^^^^ meta.block
-- ^^ keyword.control
-- ^^^ keyword.control.end
:: foo ::;
-- ^^ punctuation.definition.label.begin
-- ^^^ entity.name.label
-- ^^ punctuation.definition.label.end
goto foo;
-- ^^^^ keyword.control.goto
-- ^^^ variable.label
break;
-- ^^^^^ keyword.control.break
return;
-- ^^^^^^ keyword.control.return
return foo;
-- ^^^^^^ keyword.control.return
-- ^^^ variable.other
local x = 1, y = 2;
-- ^^^^^ storage.modifier
-- ^ variable.other
-- ^ keyword.operator.assignment
-- ^ constant.numeric.decimal
-- ^ punctuation.separator.comma
-- ^ variable.other
-- ^ keyword.operator.assignment
-- ^ constant.numeric.decimal
-- ^ punctuation.terminator.statement
| unlicense |
akdor1154/awesome | lib/awful/client/shape.lua | 1 | 2951 | ---------------------------------------------------------------------------
--- Handle client shapes.
--
-- @author Uli Schlachter <psychon@znc.in>
-- @copyright 2014 Uli Schlachter
-- @release @AWESOME_VERSION@
-- @module awful.client.shape
---------------------------------------------------------------------------
-- Grab environment we need
local surface = require("gears.surface")
local cairo = require("lgi").cairo
local capi =
{
client = client,
}
local shape = {}
shape.update = {}
--- Get one of a client's shapes and transform it to include window decorations
-- @client c The client whose shape should be retrieved
-- @tparam string shape_name Either "bounding" or "clip"
function shape.get_transformed(c, shape_name)
local border = shape_name == "bounding" and c.border_width or 0
local shape_img = surface.load_silently(c["client_shape_" .. shape_name], false)
if not shape_img then return end
-- Get information about various sizes on the client
local geom = c:geometry()
local _, t = c:titlebar_top()
local _, b = c:titlebar_bottom()
local _, l = c:titlebar_left()
local _, r = c:titlebar_right()
-- Figure out the size of the shape that we need
local img_width = geom.width + 2*border
local img_height = geom.height + 2*border
local result = cairo.ImageSurface(cairo.Format.A1, img_width, img_height)
local cr = cairo.Context(result)
-- Fill everything (this paints the titlebars and border)
cr:paint()
-- Draw the client's shape in the middle
cr:set_operator(cairo.Operator.SOURCE)
cr:set_source_surface(shape_img, border + l, border + t)
cr:rectangle(border + l, border + t, geom.width - l - r, geom.height - t - b)
cr:fill()
return result
end
--- Update a client's bounding shape from the shape the client set itself
-- @client c The client to act on
function shape.update.bounding(c)
local res = shape.get_transformed(c, "bounding")
c.shape_bounding = res and res._native
-- Free memory
if res then
res:finish()
end
end
--- Update a client's clip shape from the shape the client set itself
-- @client c The client to act on
function shape.update.clip(c)
local res = shape.get_transformed(c, "clip")
c.shape_clip = res and res._native
-- Free memory
if res then
res:finish()
end
end
--- Update all of a client's shapes from the shapes the client set itself
-- @client c The client to act on
function shape.update.all(c)
shape.update.bounding(c)
shape.update.clip(c)
end
capi.client.connect_signal("property::shape_client_bounding", shape.update.bounding)
capi.client.connect_signal("property::shape_client_clip", shape.update.clip)
capi.client.connect_signal("property::width", shape.update.all)
capi.client.connect_signal("property::height", shape.update.all)
return shape
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
UnfortunateFruit/darkstar | scripts/globals/spells/slowga.lua | 11 | 1209 | -----------------------------------------
-- Spell: Slow
-- Spell accuracy is most highly affected by Enfeebling Magic Skill, Magic Accuracy, and MND.
-- Slow's potency is calculated with the formula (150 + dMND*2)/1024, and caps at 300/1024 (~29.3%).
-- And MND of 75 is neccessary to reach the hardcap of Slow.
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local dMND = (caster:getStat(MOD_MND) - target:getStat(MOD_MND));
--Power.
local power = 150 + dMND * 2;
if(power > 350) then
power = 350;
end
--Duration, including resistance.
local duration = 120 * applyResistanceEffect(caster,spell,target,dMND,35,0,EFFECT_SLOW);
if(duration >= 60) then --Do it!
if(target:addStatusEffect(EFFECT_SLOW,power,0,duration, 0, 1)) then
spell:setMsg(236);
else
spell:setMsg(75);
end
else
spell:setMsg(85);
end
return EFFECT_SLOW;
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Dynamis-Windurst/mobs/Avatar_Icon.lua | 16 | 5149 | -----------------------------------
-- Area: Dynamis Windurst
-- NPC: Avatar Icon
-- Map1 Position: http://images2.wikia.nocookie.net/__cb20090312004752/ffxi/images/8/84/Win1.jpg
-- Map2 Position: http://images2.wikia.nocookie.net/__cb20090312004839/ffxi/images/6/61/Win2.jpg
-----------------------------------
package.loaded["scripts/zones/Dynamis-Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Windurst/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
local X = mob:getXPos();
local Y = mob:getYPos();
local Z = mob:getZPos();
local spawnList = windyList;
if(mob:getStatPoppedMobs() == false) then
mob:setStatPoppedMobs(true);
for nb = 1, table.getn(spawnList), 2 do
if(mob:getID() == spawnList[nb]) then
for nbi = 1, table.getn(spawnList[nb + 1]), 1 do
if((nbi % 2) == 0) then X=X+2; Z=Z+2; else X=X-2; Z=Z-2; end
local mobNBR = spawnList[nb + 1][nbi];
if(mobNBR <= 20) then
if(mobNBR == 0) then mobNBR = math.random(1,15); end -- Spawn random Vanguard (TEMPORARY)
local DynaMob = getDynaMob(target,mobNBR,1);
--printf("Avatar Icon => mob %u \n",DynaMob);
if(DynaMob ~= nil) then
-- Spawn Mob
SpawnMob(DynaMob):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(DynaMob):setPos(X,Y,Z);
GetMobByID(DynaMob):setSpawn(X,Y,Z);
-- Spawn Pet for BST, DRG, and SMN
if(mobNBR == 9 or mobNBR == 15) then
SpawnMob(DynaMob + 1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(DynaMob + 1):setPos(X,Y,Z);
GetMobByID(DynaMob + 1):setSpawn(X,Y,Z);
end
end
elseif(mobNBR > 20) then
SpawnMob(mobNBR):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
local MJob = GetMobByID(mobNBR):getMainJob();
if(MJob == 9 or MJob == 14 or MJob == 15) then
-- Spawn Pet for BST, DRG, and SMN
SpawnMob(mobNBR + 1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(mobNBR + 1):setPos(X,Y,Z);
GetMobByID(mobNBR + 1):setSpawn(X,Y,Z);
end
end
end
end
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
mobID = mob:getID();
-- Time Bonus (20min): 008
if(mobID == 17543494 and mob:isInBattlefieldList() == false) then
killer:addTimeToDynamis(20);
mob:addInBattlefieldList();
-- Time Bonus (20min): 018
elseif(mobID == 17543504 and mob:isInBattlefieldList() == false) then
killer:addTimeToDynamis(20);
mob:addInBattlefieldList();
-- Time Bonus (10min): 031
elseif(mobID == 17543514 and mob:isInBattlefieldList() == false) then
killer:addTimeToDynamis(10);
mob:addInBattlefieldList();
-- Time Bonus (20min): 041
elseif(mobID == 17543518 and mob:isInBattlefieldList() == false) then
killer:addTimeToDynamis(20);
mob:addInBattlefieldList();
-- Time Bonus (10min): 058
elseif(mobID == 17543534 and mob:isInBattlefieldList() == false) then
killer:addTimeToDynamis(10);
mob:addInBattlefieldList();
-- Time Bonus (20min): 066
elseif(mobID == 17543542 and mob:isInBattlefieldList() == false) then
killer:addTimeToDynamis(20);
mob:addInBattlefieldList();
-- Time Bonus (20min): 101
elseif(mobID == 17543577 and mob:isInBattlefieldList() == false) then
killer:addTimeToDynamis(20);
mob:addInBattlefieldList();
-- HP Bonus: 006 012 019 024 029 035 042 051 056 074 083 088 094 095 100 110 117 | 126 133 136 138
elseif(mobID == 17543492 or mobID == 17543498 or mobID == 17543505 or mobID == 17543508 or mobID == 17543512 or mobID == 17543517 or mobID == 17543393 or mobID == 17543527 or
mobID == 17543532 or mobID == 17543550 or mobID == 17543559 or mobID == 17543564 or mobID == 17543570 or mobID == 17543571 or mobID == 17543576 or mobID == 17543586 or
mobID == 17543593 or mobID == 17543601 or mobID == 17543608 or mobID == 17543611 or mobID == 17543613) then
killer:restoreHP(2000);
killer:messageBasic(024,(killer:getMaxHP()-killer:getHP()));
-- MP Bonus: 008 017 025 030 032 040 045 057 060 072 077 080 086 096 111 118 | 127 131 137 139
elseif(mobID == 17543494 or mobID == 17543503 or mobID == 17543305 or mobID == 17543513 or mobID == 17543515 or mobID == 17543392 or mobID == 17543521 or mobID == 17543533 or
mobID == 17543536 or mobID == 17543548 or mobID == 17543553 or mobID == 17543556 or mobID == 17543562 or mobID == 17543572 or mobID == 17543587 or mobID == 17543594 or
mobID == 17543602 or mobID == 17543606 or mobID == 17543612 or mobID == 17543614) then
killer:restoreMP(2000);
killer:messageBasic(025,(killer:getMaxMP()-killer:getMP()));
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Mamook/npcs/Logging_Point.lua | 29 | 1080 | -----------------------------------
-- Area: Mamook
-- NPC: Logging Point
-----------------------------------
package.loaded["scripts/zones/Mamook/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/logging");
require("scripts/zones/Mamook/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
startLogging(player,player:getZoneID(),npc,trade,0x00D7);
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(LOGGING_IS_POSSIBLE_HERE,1021);
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 |
NezzKryptic/Wire-Extras | lua/entities/gmod_wire_ramcardreader/init.lua | 4 | 5631 |
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
ENT.WireDebugName = "RAM-Card Reader"
local NEW_CARD_WAIT_TIME = 2
local CARD_IN_SOCKET_CONSTRAINT_POWER = 2000
local CARD_IN_ATTACH_RANGE = 3
function ENT:Initialize()
self:SetModel( "models/keycardspawner/keycardspawner.mdl" )
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs(self, { "Clk", "AddrRead", "AddrWrite", "Data" })
self.Outputs = Wire_CreateOutputs(self, {"Card Connected","Data","Cells"})
self.PluggedCard = nil
self.CardWeld = nil
self.CardNoCollide = nil
self:SetOverlayText("Wire RAM-Card\nReader/Writer\nNo Card plugged in")
Wire_TriggerOutput(self,"Card Connected",0)
end
function ENT:Think()
self.BaseClass.Think(self)
if (self.CardWeld && !self.CardWeld:IsValid()) then
if (self.PluggedCard && self.PluggedCard:IsValid()) then
self.PluggedCard:ResetSocket()
end
self.CardWeld = nil
self.CardNoCollide = nil
self.PluggedCard = nil
self:SetOverlayText("Wire RAM-Card\nReader/Writer\nNo Card plugged in")
Wire_TriggerOutput(self,"Card Connected",0)
Wire_TriggerOutput(self,"Cells",0)
Wire_TriggerOutput(self,"Data",0)
self:NextThink( CurTime() + NEW_CARD_WAIT_TIME )
return true
end
if (!self.PluggedCard || !self.PluggedCard:IsValid()) then
self:SearchCards()
end
if (self.PluggedCard && self.PluggedCard:IsValid()) then
self:NextThink( CurTime() + 1 )
else
self:NextThink( CurTime() + 0.2 )
end
return true
end
function ENT:SearchCards()
local sockCenter = self:GetPos() + self:GetUp() * 5
local local_ents = ents.FindInSphere( sockCenter, CARD_IN_ATTACH_RANGE )
for key, card in pairs(local_ents) do
// If we find a plug, try to attach it to us
if ( card && card:IsValid() && card:GetTable().IsRamCard ) then
// If no other sockets are using it
if (card:GetSocket() == nil || !card:GetSocket():IsValid()) then
self:PlugCard(card)
end
end
if (self.PluggedCard && self.PluggedCard:IsValid()) then
break
end
end
end
function ENT:PlugCard( card )
self.PluggedCard = card
card:SetPos( self:GetPos() + self:GetUp() * 5 )
card:SetAngles( self:GetAngles() + Angle(90,0,0) )
self.CardNoCollide = constraint.NoCollide(self, card, 0, 0)
if (!self.CardNoCollide) then
return
end
self.CardWeld = constraint.Weld( self, card, 0, 0, CARD_IN_SOCKET_CONSTRAINT_POWER, true )
if (!self.CardWeld && !self.CardWeld:IsValid()) then
self.CardNoCollide:Remove()
self.CardNoCollide = nil
return
end
card:DeleteOnRemove( self.CardWeld )
self:DeleteOnRemove( self.CardWeld )
self.CardWeld:DeleteOnRemove( self.CardNoCollide )
self.PluggedCard = card
card:SetSocket( self )
self:SetOverlayText("Wire RAM-Card\nReader/Writer\nA Card is plugged in")
Wire_TriggerOutput(self,"Card Connected",1)
Wire_TriggerOutput(self,"Cells",self.PluggedCard:GetSize())
end
--Address 0 is handled by the Reader/Writer, and says, if a card is connected. If you write a 0 to cell 0, the card will be thrown out
--Address 1 gives the size of the current card (only readable, will cause memory fault if you write)
function ENT:WriteCell( Address, value )
if (Address == 0) then
if (self.PluggedCard && self.PluggedCard:IsValid()) then
if (value <= 0) then
self.CardWeld:Remove()
self.CardNoCollide:Remove()
self.PluggedCard:ResetSocket()
self.CardWeld = nil
self.CardNoCollide = nil
self.PluggedCard = nil
self:SetOverlayText("Wire RAM-Card\nReader/Writer\nNo Card plugged in")
Wire_TriggerOutput(self,"Card Connected",0)
self:NextThink( CurTime() + NEW_CARD_WAIT_TIME )
end
end
return true
elseif (Address >= 2) then
if (self.PluggedCard && self.PluggedCard:IsValid()) then
if (self.PluggedCard:CanWrite()) then
return self.PluggedCard:WriteCell( Address - 1, value )
end
end
end
return false
end
function ENT:ReadCell( Address )
if (Address == 0) then
if (self.PluggedCard && self.PluggedCard:IsValid()) then
return 1
else
return 0
end
elseif (Address == 1) then
if (self.PluggedCard && self.PluggedCard:IsValid()) then
return self.PluggedCard:GetSize()
end
else
if (self.PluggedCard && self.PluggedCard:IsValid()) then
if (self.PluggedCard:CanRead()) then
return self.PluggedCard:ReadCell( Address - 1 )
end
end
end
return nil
end
function ENT:TriggerInput( iname, value )
if (iname == "AddrWrite") then
if (self.PluggedCard && self.PluggedCard:IsValid()) then
if (self.Inputs["Clk"].Value > 0) then
if (value >= 0 && value < self.PluggedCard:GetSize()) then
self:WriteCell(value + 2, self.Inputs["Data"].Value)
end
end
end
elseif (iname == "AddrRead") then
if (self.PluggedCard && self.PluggedCard:IsValid()) then
if (value >= 0 && value < self.PluggedCard:GetSize()) then
Wire_TriggerOutput(self,"Data",self:ReadCell(value+2))
else
Wire_TriggerOutput(self,"Data",0)
end
else
Wire_TriggerOutput(self,"Data",0)
end
elseif (iname == "Clk") then
if (self.PluggedCard && self.PluggedCard:IsValid()) then
if (self.Inputs["Clk"].Value > 0) then
if (self.Inputs["AddrWrite"].Value >= 0 && self.Inputs["AddrWrite"].Value < self.PluggedCard:GetSize()) then
self:WriteCell(self.Inputs["AddrWrite"].Value + 2, self.Inputs["Data"].Value)
end
end
end
end
end
| gpl-3.0 |
nesstea/darkstar | scripts/globals/weaponskills/fell_cleave.lua | 11 | 1392 | -----------------------------------
-- Fell Cleave
-- Great Axe weapon skill
-- Skill Level: 300
-- Delivers an area attack. Radius varies with TP.
-- Aligned with the Breeze Gorget, Thunder Gorget & Soil Gorget.
-- Aligned with the Breeze Belt, Thunder Belt & Soil Belt.
-- Element: None
-- Modifiers: STR: 60%
-- 100%TP 200%TP 300%TP
-- 2.00 2.00 2.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary)
local params = {};
params.numHits = 1;
params.ftp100 = 2.0; params.ftp200 = 2.0; params.ftp300 = 2.0;
params.str_wsc = 0.6; 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;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 2.75; params.ftp200 = 2.75; params.ftp300 = 2.75;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, primary);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
JustinZZzz/crtmpserver | builders/cmake/crtmpserver/flvplayback2.lua | 1 | 2017 | configuration=
{
daemon=false,
pathSeparator="/",
logAppenders=
{
{
name="console appender",
type="coloredConsole",
level=6
},
{
name="file appender",
type="file",
level=6,
fileName="/tmp/crtmpserver",
fileHistorySize=10,
fileLength=1024*1024,
singleLine=true
}
},
applications=
{
rootDirectory="../applications",
{
description="FLV Playback Sample",
name="flvplayback",
protocol="dynamiclinklibrary",
default=true,
aliases=
{
"simpleLive",
"vod",
"live",
"WeeklyQuest",
"SOSample",
"oflaDemo",
},
acceptors =
{
{
ip="0.0.0.0",
port=1936,
protocol="inboundRtmp"
},
--[[{
ip="0.0.0.0",
port=8081,
protocol="inboundRtmps",
sslKey="./ssl/server.key",
sslCert="./ssl/server.crt"
},
{
ip="0.0.0.0",
port=8080,
protocol="inboundRtmpt"
},]]--
{
ip="0.0.0.0",
port=6666,
protocol="inboundLiveFlv",
waitForMetadata=true,
},
{
ip="0.0.0.0",
port=9999,
protocol="inboundTcpTs"
},
--[[{
ip="0.0.0.0",
port=554,
protocol="inboundRtsp"
},]]--
},
externalStreams =
{
--[[{
uri="rtmp://edge01.fms.dutchview.nl/botr/bunny",
localStreamName="test1",
tcUrl="rtmp://edge01.fms.dutchview.nl/botr/bunny", --this one is usually required and should have the same value as the uri
}]]--
},
validateHandshake=false,
keyframeSeek=true,
seekGranularity=1.5, --in seconds, between 0.1 and 600
clientSideBuffer=12, --in seconds, between 5 and 30
--generateMetaFiles=true, --this will generate seek/meta files on application startup
--renameBadFiles=false,
mediaFolder="./media",
--[[authentication=
{
rtmp={
type="adobe",
encoderAgents=
{
"FMLE/3.0 (compatible; FMSc/1.0)",
},
usersFile="./configs/users.lua"
},
rtsp={
usersFile="./configs/users.lua"
}
},]]--
},
}
}
| gpl-3.0 |
nesstea/darkstar | scripts/zones/West_Sarutabaruta_[S]/Zone.lua | 27 | 1290 | -----------------------------------
--
-- Zone: West_Sarutabaruta_[S] (95)
--
-----------------------------------
package.loaded["scripts/zones/West_Sarutabaruta_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/West_Sarutabaruta_[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(320.018,-6.684,-45.166,189);
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 |
Mashape/kong | kong/templates/nginx_kong.lua | 1 | 8359 | return [[
charset UTF-8;
server_tokens off;
> if anonymous_reports then
${{SYSLOG_REPORTS}}
> end
error_log ${{PROXY_ERROR_LOG}} ${{LOG_LEVEL}};
> if nginx_optimizations then
>-- send_timeout 60s; # default value
>-- keepalive_timeout 75s; # default value
>-- client_body_timeout 60s; # default value
>-- client_header_timeout 60s; # default value
>-- tcp_nopush on; # disabled until benchmarked
>-- proxy_buffer_size 128k; # disabled until benchmarked
>-- proxy_buffers 4 256k; # disabled until benchmarked
>-- proxy_busy_buffers_size 256k; # disabled until benchmarked
>-- reset_timedout_connection on; # disabled until benchmarked
> end
client_max_body_size ${{CLIENT_MAX_BODY_SIZE}};
proxy_ssl_server_name on;
underscores_in_headers on;
lua_package_path '${{LUA_PACKAGE_PATH}};;';
lua_package_cpath '${{LUA_PACKAGE_CPATH}};;';
lua_socket_pool_size ${{LUA_SOCKET_POOL_SIZE}};
lua_max_running_timers 4096;
lua_max_pending_timers 16384;
lua_shared_dict kong 5m;
lua_shared_dict kong_db_cache ${{MEM_CACHE_SIZE}};
> if database == "off" then
lua_shared_dict kong_db_cache_2 ${{MEM_CACHE_SIZE}};
> end
lua_shared_dict kong_db_cache_miss 12m;
> if database == "off" then
lua_shared_dict kong_db_cache_miss_2 12m;
> end
lua_shared_dict kong_locks 8m;
lua_shared_dict kong_process_events 5m;
lua_shared_dict kong_cluster_events 5m;
lua_shared_dict kong_healthchecks 5m;
lua_shared_dict kong_rate_limiting_counters 12m;
> if database == "cassandra" then
lua_shared_dict kong_cassandra 5m;
> end
lua_socket_log_errors off;
> if lua_ssl_trusted_certificate then
lua_ssl_trusted_certificate '${{LUA_SSL_TRUSTED_CERTIFICATE}}';
> end
lua_ssl_verify_depth ${{LUA_SSL_VERIFY_DEPTH}};
# injected nginx_http_* directives
> for _, el in ipairs(nginx_http_directives) do
$(el.name) $(el.value);
> end
init_by_lua_block {
Kong = require 'kong'
Kong.init()
}
init_worker_by_lua_block {
Kong.init_worker()
}
> if #proxy_listeners > 0 then
upstream kong_upstream {
server 0.0.0.1;
balancer_by_lua_block {
Kong.balancer()
}
# injected nginx_http_upstream_* directives
> for _, el in ipairs(nginx_http_upstream_directives) do
$(el.name) $(el.value);
> end
}
server {
server_name kong;
> for i = 1, #proxy_listeners do
listen $(proxy_listeners[i].listener);
> end
error_page 400 404 408 411 412 413 414 417 494 /kong_error_handler;
error_page 500 502 503 504 /kong_error_handler;
access_log ${{PROXY_ACCESS_LOG}};
error_log ${{PROXY_ERROR_LOG}} ${{LOG_LEVEL}};
client_body_buffer_size ${{CLIENT_BODY_BUFFER_SIZE}};
> if proxy_ssl_enabled then
ssl_certificate ${{SSL_CERT}};
ssl_certificate_key ${{SSL_CERT_KEY}};
ssl_certificate_by_lua_block {
Kong.ssl_certificate()
}
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_prefer_server_ciphers on;
ssl_ciphers ${{SSL_CIPHERS}};
> end
> if client_ssl then
proxy_ssl_certificate ${{CLIENT_SSL_CERT}};
proxy_ssl_certificate_key ${{CLIENT_SSL_CERT_KEY}};
> end
real_ip_header ${{REAL_IP_HEADER}};
real_ip_recursive ${{REAL_IP_RECURSIVE}};
> for i = 1, #trusted_ips do
set_real_ip_from $(trusted_ips[i]);
> end
# injected nginx_proxy_* directives
> for _, el in ipairs(nginx_proxy_directives) do
$(el.name) $(el.value);
> end
rewrite_by_lua_block {
Kong.rewrite()
}
access_by_lua_block {
Kong.access()
}
header_filter_by_lua_block {
Kong.header_filter()
}
body_filter_by_lua_block {
Kong.body_filter()
}
log_by_lua_block {
Kong.log()
}
location / {
default_type '';
set $ctx_ref '';
set $upstream_te '';
set $upstream_host '';
set $upstream_upgrade '';
set $upstream_connection '';
set $upstream_scheme '';
set $upstream_uri '';
set $upstream_x_forwarded_for '';
set $upstream_x_forwarded_proto '';
set $upstream_x_forwarded_host '';
set $upstream_x_forwarded_port '';
set $kong_proxy_mode 'http';
proxy_http_version 1.1;
proxy_set_header TE $upstream_te;
proxy_set_header Host $upstream_host;
proxy_set_header Upgrade $upstream_upgrade;
proxy_set_header Connection $upstream_connection;
proxy_set_header X-Forwarded-For $upstream_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $upstream_x_forwarded_proto;
proxy_set_header X-Forwarded-Host $upstream_x_forwarded_host;
proxy_set_header X-Forwarded-Port $upstream_x_forwarded_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_pass_header Server;
proxy_pass_header Date;
proxy_ssl_name $upstream_host;
proxy_pass $upstream_scheme://kong_upstream$upstream_uri;
}
location @grpc {
internal;
set $kong_proxy_mode 'grpc';
grpc_set_header Host $upstream_host;
grpc_set_header X-Forwarded-For $upstream_x_forwarded_for;
grpc_set_header X-Forwarded-Proto $upstream_x_forwarded_proto;
grpc_set_header X-Forwarded-Host $upstream_x_forwarded_host;
grpc_set_header X-Forwarded-Port $upstream_x_forwarded_port;
grpc_set_header X-Real-IP $remote_addr;
grpc_pass grpc://kong_upstream;
}
location @grpcs {
internal;
set $kong_proxy_mode 'grpc';
grpc_set_header Host $upstream_host;
grpc_set_header X-Forwarded-For $upstream_x_forwarded_for;
grpc_set_header X-Forwarded-Proto $upstream_x_forwarded_proto;
grpc_set_header X-Forwarded-Host $upstream_x_forwarded_host;
grpc_set_header X-Forwarded-Port $upstream_x_forwarded_port;
grpc_set_header X-Real-IP $remote_addr;
grpc_pass grpcs://kong_upstream;
}
location = /kong_error_handler {
internal;
uninitialized_variable_warn off;
rewrite_by_lua_block {;}
access_by_lua_block {;}
content_by_lua_block {
Kong.handle_error()
}
}
}
> end
> if #admin_listeners > 0 then
server {
server_name kong_admin;
> for i = 1, #admin_listeners do
listen $(admin_listeners[i].listener);
> end
access_log ${{ADMIN_ACCESS_LOG}};
error_log ${{ADMIN_ERROR_LOG}} ${{LOG_LEVEL}};
client_max_body_size 10m;
client_body_buffer_size 10m;
> if admin_ssl_enabled then
ssl_certificate ${{ADMIN_SSL_CERT}};
ssl_certificate_key ${{ADMIN_SSL_CERT_KEY}};
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_prefer_server_ciphers on;
ssl_ciphers ${{SSL_CIPHERS}};
> end
# injected nginx_admin_* directives
> for _, el in ipairs(nginx_admin_directives) do
$(el.name) $(el.value);
> end
location / {
default_type application/json;
content_by_lua_block {
Kong.admin_content()
}
header_filter_by_lua_block {
Kong.admin_header_filter()
}
}
location /nginx_status {
internal;
access_log off;
stub_status;
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
}
> end
> if #status_listeners > 0 then
server {
server_name kong_status;
> for i = 1, #status_listeners do
listen $(status_listeners[i].listener);
> end
access_log ${{STATUS_ACCESS_LOG}};
error_log ${{STATUS_ERROR_LOG}} ${{LOG_LEVEL}};
# injected nginx_http_status_* directives
> for _, el in ipairs(nginx_http_status_directives) do
$(el.name) $(el.value);
> end
location / {
default_type application/json;
content_by_lua_block {
Kong.status_content()
}
header_filter_by_lua_block {
Kong.status_header_filter()
}
}
location /nginx_status {
internal;
access_log off;
stub_status;
}
location /robots.txt {
return 200 'User-agent: *\nDisallow: /';
}
}
> end
]]
| apache-2.0 |
UnfortunateFruit/darkstar | scripts/zones/Northern_San_dOria/npcs/Emeige_AMAN.lua | 65 | 1182 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Emeige A.M.A.N.
-- Type: Mentor Recruiter
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local var = 0;
if (player:getMentor() == 0) then
if (player:getMainLvl() >= 30 and player:getPlaytime() >= 648000) then
var = 1;
end
elseif (player:getMentor() >= 1) then
var = 2;
end
player:startEvent(0x02E3, var);
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 == 0x02E3 and option == 0) then
player:setMentor(1);
end
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/_1e9.lua | 29 | 1155 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: _1e9 (Gate: The Pit)
-- @pos 80 -1.949 -107.94
-- Used to enter "The Colosseum" zone.
-----------------------------------
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(133);
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 == 133 and option == 1) then
player:setPos(-600, 0, 40, 254, 71)
end
end; | gpl-3.0 |
dpino/snabbswitch | src/program/packetblaster/lwaftr/lib.lua | 3 | 15244 | module(...,package.seeall)
local lib = require("core.lib")
local app = require("core.app")
local packet = require("core.packet")
local link = require("core.link")
local ethernet = require("lib.protocol.ethernet")
local ipv4 = require("lib.protocol.ipv4")
local ipv6 = require("lib.protocol.ipv6")
local ipsum = require("lib.checksum").ipsum
local ffi = require("ffi")
local C = ffi.C
local cast = ffi.cast
local copy = ffi.copy
local PROTO_IPV4_ENCAPSULATION = 0x4
local PROTO_VLAN = C.htons(0x8100)
local PROTO_IPV4 = C.htons(0x0800)
local PROTO_IPV6 = C.htons(0x86DD)
local DEFAULT_TTL = 255
local MAGIC = 0xaffeface
local ether_header_t = ffi.typeof[[
struct {
uint8_t ether_dhost[6];
uint8_t ether_shost[6];
uint16_t ether_type;
} __attribute__((packed))
]]
local ether_header_ptr_type = ffi.typeof("$*", ether_header_t)
local ethernet_header_size = ffi.sizeof(ether_header_t)
local OFFSET_ETHERTYPE = 12
-- The ethernet CRC field is not included in the packet as seen by
-- Snabb, but it is part of the frame and therefore a contributor to the
-- frame size.
local ethernet_crc_size = 4
local ether_vlan_header_type = ffi.typeof([[
struct {
uint16_t tag;
uint16_t ether_type;
}
]])
ether_vlan_header_ptr_type = ffi.typeof("$*", ether_vlan_header_type)
ether_vlan_header_size = ffi.sizeof(ether_vlan_header_type)
local OFFSET_ETHERTYPE_VLAN = OFFSET_ETHERTYPE + ether_vlan_header_size
local ipv4hdr_t = ffi.typeof[[
struct {
uint16_t ihl_v_tos; // ihl:4, version:4, tos(dscp:6 + ecn:2)
uint16_t total_length;
uint16_t id;
uint16_t frag_off; // flags:3, fragmen_offset:13
uint8_t ttl;
uint8_t protocol;
uint16_t checksum;
uint8_t src_ip[4];
uint8_t dst_ip[4];
} __attribute__((packed))
]]
local ipv4_header_size = ffi.sizeof(ipv4hdr_t)
local ipv4_header_ptr_type = ffi.typeof("$*", ipv4hdr_t)
local ipv6_ptr_type = ffi.typeof([[
struct {
uint32_t v_tc_fl; // version, tc, flow_label
uint16_t payload_length;
uint8_t next_header;
uint8_t hop_limit;
uint8_t src_ip[16];
uint8_t dst_ip[16];
} __attribute__((packed))
]])
local ipv6_header_ptr_type = ffi.typeof("$*", ipv6_ptr_type)
local ipv6_header_size = ffi.sizeof(ipv6_ptr_type)
local udp_header_t = ffi.typeof[[
struct {
uint16_t src_port;
uint16_t dst_port;
uint16_t len;
uint16_t checksum;
} __attribute__((packed))
]]
local udp_header_ptr_type = ffi.typeof("$*", udp_header_t)
local udp_header_size = ffi.sizeof(udp_header_ptr_type)
local payload_t = ffi.typeof[[
struct {
uint32_t magic;
uint32_t number;
} __attribute__((packed))
]]
local payload_ptr_type = ffi.typeof("$*", payload_t)
local payload_size = ffi.sizeof(payload_t)
local uint16_ptr_t = ffi.typeof("uint16_t*")
local uint32_ptr_t = ffi.typeof("uint32_t*")
local n_cache_src_ipv6 = ipv6:pton("::")
local function rd32(offset)
return cast(uint32_ptr_t, offset)[0]
end
local function wr32(offset, val)
cast(uint32_ptr_t, offset)[0] = val
end
local function inc_ipv6(ipv6)
for i=15,0,-1 do
if ipv6[i] == 255 then
ipv6[i] = 0
else
ipv6[i] = ipv6[i] + 1
break
end
end
return ipv6
end
Lwaftrgen = {
config = {
sizes = {required=true},
dst_mac = {required=true},
src_mac = {required=true},
rate = {required=true},
vlan = {},
b4_ipv6 = {},
b4_ipv4 = {},
public_ipv4 = {},
aftr_ipv6 = {},
ipv6_only = {},
ipv4_only = {},
b4_port = {},
protocol = {},
count = {},
single_pass = {}
}
}
local receive, transmit = link.receive, link.transmit
function Lwaftrgen:new(conf)
local dst_mac = ethernet:pton(conf.dst_mac)
local src_mac = ethernet:pton(conf.src_mac)
local vlan = conf.vlan
local b4_ipv6 = conf.b4_ipv6 and ipv6:pton(conf.b4_ipv6)
local b4_ipv4 = conf.b4_ipv4 and ipv4:pton(conf.b4_ipv4)
local public_ipv4 = conf.public_ipv4 and ipv4:pton(conf.public_ipv4)
local aftr_ipv6 = conf.aftr_ipv6 and ipv6:pton(conf.aftr_ipv6)
local ipv4_pkt = packet.allocate()
ffi.fill(ipv4_pkt.data, packet.max_payload)
local eth_hdr = cast(ether_header_ptr_type, ipv4_pkt.data)
eth_hdr.ether_dhost, eth_hdr.ether_shost = dst_mac, src_mac
local ipv4_hdr, udp_offset
if vlan then
udp_offset = 38
eth_hdr.ether_type = PROTO_VLAN
local vlan_hdr = cast(ether_vlan_header_ptr_type, ipv4_pkt.data + ethernet_header_size)
vlan_hdr.ether_type = PROTO_IPV4
vlan_hdr.tag = C.htons(vlan)
ipv4_hdr = cast(ipv4_header_ptr_type, ipv4_pkt.data + ethernet_header_size + ether_vlan_header_size)
else
udp_offset = 34
eth_hdr.ether_type = PROTO_IPV4
ipv4_hdr = cast(ipv4_header_ptr_type, ipv4_pkt.data + ethernet_header_size)
end
ipv4_hdr.src_ip = public_ipv4
ipv4_hdr.dst_ip = b4_ipv4
ipv4_hdr.ttl = 15
ipv4_hdr.ihl_v_tos = C.htons(0x4500) -- v4
ipv4_hdr.id = 0
ipv4_hdr.frag_off = 0
local ipv4_udp_hdr, ipv4_payload
ipv4_hdr.protocol = 17 -- UDP(17)
ipv4_udp_hdr = cast(udp_header_ptr_type, ipv4_pkt.data + udp_offset)
ipv4_udp_hdr.src_port = C.htons(12345)
ipv4_udp_hdr.checksum = 0
ipv4_payload = cast(payload_ptr_type, ipv4_pkt.data + udp_offset + udp_header_size)
ipv4_payload.magic = MAGIC
ipv4_payload.number = 0
-- IPv4 in IPv6 packet
copy(n_cache_src_ipv6, b4_ipv6, 16)
local ipv6_pkt = packet.allocate()
ffi.fill(ipv6_pkt.data, packet.max_payload)
local eth_hdr = cast(ether_header_ptr_type, ipv6_pkt.data)
eth_hdr.ether_dhost, eth_hdr.ether_shost = dst_mac, src_mac
local ipv6_hdr, ipv6_ipv4_hdr
if vlan then
eth_hdr.ether_type = PROTO_VLAN
local vlan_hdr = cast(ether_vlan_header_ptr_type, ipv6_pkt.data + ethernet_header_size)
vlan_hdr.ether_type = PROTO_IPV6
vlan_hdr.tag = C.htons(vlan)
ipv6_hdr = cast(ipv6_header_ptr_type, ipv6_pkt.data + ethernet_header_size + ether_vlan_header_size)
ipv6_ipv4_hdr = cast(ipv4_header_ptr_type, ipv6_pkt.data + ethernet_header_size + ether_vlan_header_size + ipv6_header_size)
else
eth_hdr.ether_type = PROTO_IPV6
ipv6_hdr = cast(ipv6_header_ptr_type, ipv6_pkt.data + ethernet_header_size)
ipv6_ipv4_hdr = cast(ipv4_header_ptr_type, ipv6_pkt.data + ethernet_header_size + ipv6_header_size)
end
lib.bitfield(32, ipv6_hdr, 'v_tc_fl', 0, 4, 6) -- IPv6 Version
lib.bitfield(32, ipv6_hdr, 'v_tc_fl', 4, 8, 1) -- Traffic class
ipv6_hdr.next_header = PROTO_IPV4_ENCAPSULATION
ipv6_hdr.hop_limit = DEFAULT_TTL
ipv6_hdr.dst_ip = aftr_ipv6
ipv6_ipv4_hdr.dst_ip = public_ipv4
ipv6_ipv4_hdr.ttl = 15
ipv6_ipv4_hdr.ihl_v_tos = C.htons(0x4500) -- v4
ipv6_ipv4_hdr.id = 0
ipv6_ipv4_hdr.frag_off = 0
local ipv6_ipv4_udp_hdr, ipv6_payload
local total_packet_count = 0
for _,size in ipairs(conf.sizes) do
-- count for IPv4 and IPv6 packets (40 bytes IPv6 encap header)
if conf.ipv4_only or conf.ipv6_only then
total_packet_count = total_packet_count + 1
else
total_packet_count = total_packet_count + 2
end
end
ipv6_ipv4_hdr.protocol = 17 -- UDP(17)
ipv6_ipv4_udp_hdr = cast(udp_header_ptr_type, ipv6_pkt.data + udp_offset + ipv6_header_size)
ipv6_ipv4_udp_hdr.dst_port = C.htons(12345)
ipv6_ipv4_udp_hdr.checksum = 0
ipv6_payload = cast(payload_ptr_type, ipv6_pkt.data + udp_offset + ipv6_header_size + udp_header_size)
ipv6_payload.magic = MAGIC
ipv6_payload.number = 0
local o = {
b4_ipv6 = b4_ipv6,
b4_ipv4 = b4_ipv4,
b4_port = conf.b4_port,
current_port = conf.b4_port,
b4_ipv4_offset = 0,
ipv6_address = n_cache_src_ipv6,
count = conf.count,
single_pass = conf.single_pass,
current_count = 0,
ipv4_pkt = ipv4_pkt,
ipv4_hdr = ipv4_hdr,
ipv4_payload = ipv4_payload,
ipv6_hdr = ipv6_hdr,
ipv6_pkt = ipv6_pkt,
ipv6_payload = ipv6_payload,
ipv6_ipv4_hdr = ipv6_ipv4_hdr,
ipv4_udp_hdr = ipv4_udp_hdr,
ipv6_ipv4_udp_hdr = ipv6_ipv4_udp_hdr,
ipv4_only = conf.ipv4_only,
ipv6_only = conf.ipv6_only,
vlan = vlan,
udp_offset = udp_offset,
protocol = conf.protocol,
rate = conf.rate,
sizes = conf.sizes,
total_packet_count = total_packet_count,
bucket_content = conf.rate * 1e6,
ipv4_packets = 0, ipv4_bytes = 0,
ipv6_packets = 0, ipv6_bytes = 0,
ipv4_packet_number = 0, ipv6_packet_number = 0,
last_rx_ipv4_packet_number = 0, last_rx_ipv6_packet_number = 0,
lost_packets = 0
}
return setmetatable(o, {__index=Lwaftrgen})
end
function Lwaftrgen:pull ()
local output = self.output.output
local input = self.input.input
local ipv6_packets = self.ipv6_packets
local ipv6_bytes = self.ipv6_bytes
local ipv4_packets = self.ipv4_packets
local ipv4_bytes = self.ipv4_bytes
local lost_packets = self.lost_packets
local udp_offset = self.udp_offset
local o_ethertype = self.vlan and OFFSET_ETHERTYPE_VLAN or OFFSET_ETHERTYPE
if self.current == 0 then
main.exit(0)
end
-- count and trash incoming packets
for _=1,link.nreadable(input) do
local pkt = receive(input)
if cast(uint16_ptr_t, pkt.data + o_ethertype)[0] == PROTO_IPV6 then
ipv6_bytes = ipv6_bytes + pkt.length
ipv6_packets = ipv6_packets + 1
local payload = cast(payload_ptr_type, pkt.data + udp_offset + ipv6_header_size + udp_header_size)
if payload.magic == MAGIC then
if self.last_rx_ipv6_packet_number > 0 then
lost_packets = lost_packets + payload.number - self.last_rx_ipv6_packet_number - 1
end
self.last_rx_ipv6_packet_number = payload.number
end
else
ipv4_bytes = ipv4_bytes + pkt.length
ipv4_packets = ipv4_packets + 1
local payload = cast(payload_ptr_type, pkt.data + udp_offset + udp_header_size)
if payload.magic == MAGIC then
if self.last_rx_ipv4_packet_number > 0 then
lost_packets = lost_packets + payload.number - self.last_rx_ipv4_packet_number - 1
end
self.last_rx_ipv4_packet_number = payload.number
end
end
packet.free(pkt)
end
local cur_now = tonumber(app.now())
self.period_start = self.period_start or cur_now
local elapsed = cur_now - self.period_start
if elapsed > 1 then
local ipv6_packet_rate = ipv6_packets / elapsed / 1e6
local ipv4_packet_rate = ipv4_packets / elapsed / 1e6
local ipv6_octet_rate = ipv6_bytes * 8 / 1e9 / elapsed
local ipv4_octet_rate = ipv4_bytes * 8 / 1e9 / elapsed
local lost_rate = math.abs(lost_packets / (ipv6_octet_rate + ipv4_octet_rate) / 10000)
print(string.format('v6+v4: %.3f+%.3f = %.6f MPPS, %.3f+%.3f = %.6f Gbps, lost %.3f%%',
ipv6_packet_rate, ipv4_packet_rate, ipv6_packet_rate + ipv4_packet_rate,
ipv6_octet_rate, ipv4_octet_rate, ipv6_octet_rate + ipv4_octet_rate, lost_rate))
self.period_start = cur_now
self.ipv6_bytes, self.ipv6_packets = 0, 0
self.ipv4_bytes, self.ipv4_packets = 0, 0
self.lost_packets = 0
else
self.ipv4_bytes, self.ipv4_packets = ipv4_bytes, ipv4_packets
self.ipv6_bytes, self.ipv6_packets = ipv6_bytes, ipv6_packets
self.lost_packets = lost_packets
end
local ipv4_hdr = self.ipv4_hdr
local ipv6_hdr = self.ipv6_hdr
local ipv6_ipv4_hdr = self.ipv6_ipv4_hdr
local ipv4_udp_hdr = self.ipv4_udp_hdr
local ipv6_ipv4_udp_hdr = self.ipv6_ipv4_udp_hdr
local cur_now = tonumber(app.now())
local last_time = self.last_time or cur_now
self.bucket_content = self.bucket_content + self.rate * 1e6 * (cur_now - last_time)
self.last_time = cur_now
local limit = engine.pull_npackets
while limit > self.total_packet_count and
self.total_packet_count <= self.bucket_content do
limit = limit - 1
self.bucket_content = self.bucket_content - self.total_packet_count
ipv4_hdr.dst_ip = self.b4_ipv4
ipv6_ipv4_hdr.src_ip = self.b4_ipv4
ipv6_hdr.src_ip = self.b4_ipv6
local ipdst = C.ntohl(rd32(ipv4_hdr.dst_ip))
ipdst = C.htonl(ipdst + self.b4_ipv4_offset)
wr32(ipv4_hdr.dst_ip, ipdst)
wr32(ipv6_ipv4_hdr.src_ip, ipdst)
ipv4_udp_hdr.dst_port = C.htons(self.current_port)
ipv6_ipv4_udp_hdr.src_port = C.htons(self.current_port)
-- The sizes are frame sizes, including the 4-byte ethernet CRC
-- that we don't see in Snabb.
local vlan_size = self.vlan and ether_vlan_header_size or 0
local ethernet_total_size = ethernet_header_size + vlan_size
local minimum_size = ethernet_total_size + ipv4_header_size +
udp_header_size + ethernet_crc_size
for _,size in ipairs(self.sizes) do
assert(size >= minimum_size)
local packet_len = size - ethernet_crc_size
local ipv4_len = packet_len - ethernet_total_size
local udp_len = ipv4_len - ipv4_header_size
if not self.ipv6_only then
ipv4_hdr.total_length = C.htons(ipv4_len)
ipv4_udp_hdr.len = C.htons(udp_len)
self.ipv4_pkt.length = packet_len
ipv4_hdr.checksum = 0
ipv4_hdr.checksum = C.htons(ipsum(self.ipv4_pkt.data + ethernet_total_size, 20, 0))
if size >= minimum_size + payload_size then
self.ipv4_payload.number = self.ipv4_packet_number;
self.ipv4_packet_number = self.ipv4_packet_number + 1
end
local ipv4_pkt = packet.clone(self.ipv4_pkt)
transmit(output, ipv4_pkt)
end
if not self.ipv4_only then
-- Expectation from callers is to make packets that are SIZE
-- bytes big, *plus* the IPv6 header.
ipv6_hdr.payload_length = C.htons(ipv4_len)
ipv6_ipv4_hdr.total_length = C.htons(ipv4_len)
ipv6_ipv4_udp_hdr.len = C.htons(udp_len)
self.ipv6_pkt.length = packet_len + ipv6_header_size
if size >= minimum_size + payload_size then
self.ipv6_payload.number = self.ipv6_packet_number;
self.ipv6_packet_number = self.ipv6_packet_number + 1
end
local ipv6_pkt = packet.clone(self.ipv6_pkt)
transmit(output, ipv6_pkt)
end
end
self.b4_ipv6 = inc_ipv6(self.b4_ipv6)
self.current_port = self.current_port + self.b4_port
if self.current_port > 65535 then
self.current_port = self.b4_port
self.b4_ipv4_offset = self.b4_ipv4_offset + 1
end
self.current_count = self.current_count + 1
if self.current_count >= self.count then
if self.single_pass then
print(string.format("generated %d packets", self.current_count))
-- make sure we won't generate more packets in the same breath, then exit
self.current = 0
self.bucket_content = 0
end
self.current_count = 0
self.current_port = self.b4_port
self.b4_ipv4_offset = 0
copy(self.b4_ipv6, self.ipv6_address, 16)
end
end
end
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.