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 |
|---|---|---|---|---|---|
jshackley/darkstar | scripts/zones/The_Eldieme_Necropolis_[S]/npcs/Erlene.lua | 16 | 6794 | -----------------------------------
-- Area: The Eldieme Necropolis (S)
-- NPC: Erlene
-- Involved in Quest: "A Little Knowledge"
-- @pos 376.936 -39.999 17.914 175
-----------------------------------
package.loaded["scripts/zones/The_Eldieme_Necropolis_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Eldieme_Necropolis_[S]/TextIDs");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local ALittleKnowledge = player:getQuestStatus(CRYSTAL_WAR, A_LITTLE_KNOWLEDGE);
local ALittleKnowledgeProgress = player:getVar("ALittleKnowledge");
if (ALittleKnowledge == QUEST_ACCEPTED and ALittleKnowledgeProgress == 1) then
if (trade:hasItemQty(2550, 12) and trade:getGil() == 0 and trade:getItemCount() == 12) then
if( player:getMainJob() == JOB_BLM or
player:getMainJob() == JOB_RDM or
player:getMainJob() == JOB_SMN or
player:getMainJob() == JOB_BLU) then
player:startEvent(0x000C, 1);
else
player:startEvent(0x000C);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local ALittleKnowledge = player:getQuestStatus(CRYSTAL_WAR, A_LITTLE_KNOWLEDGE);
local ALittleKnowledgeProgress = player:getVar("ALittleKnowledge");
local mLvl = player:getMainLvl();
local mJob = player:getMainJob();
local onSabbatical = player:getQuestStatus(CRYSTAL_WAR,ON_SABBATICAL);
local onSabbaticalProgress = player:getVar("OnSabbatical");
local downwardHelix = player:getQuestStatus(CRYSTAL_WAR, DOWNWARD_HELIX);
if (ALittleKnowledge == QUEST_AVAILABLE) then
if (mLvl >= ADVANCED_JOB_LEVEL) then
player:startEvent(0x000A,1);
else
player:startEvent(0x000A);
end
elseif (ALittleKnowledgeProgress == 1 and ALittleKnowledge == QUEST_ACCEPTED) then
player:startEvent(0x000B);
elseif (ALittleKnowledgeProgress == 2 and ALittleKnowledge == QUEST_ACCEPTED) then
if (player:hasStatusEffect(EFFECT_MANAFONT) or
player:hasStatusEffect(EFFECT_CHAINSPELL) or
player:hasStatusEffect(EFFECT_ASTRAL_FLOW) or
player:hasStatusEffect(EFFECT_AZURE_LORE)) then
player:startEvent(0x000E);
else
player:startEvent(0x000D);
end
elseif (ALittleKnowledge == QUEST_COMPLETED and mJob == JOB_SCH and mLvl >= 5 and not (player:hasSpell(478) and player:hasSpell(502))) then
player:startEvent(0x002F);
elseif (onSabbatical == QUEST_AVAILABLE and mJob == JOB_SCH and mLvl >= AF1_QUEST_LEVEL) then
player:startEvent(0x0012);
elseif (onSabbatical == QUEST_ACCEPTED) then
if (onSabbaticalProgress < 3) then
player:startEvent(0x0013);
else
player:startEvent(0x0014);
end
elseif (onSabbatical == QUEST_COMPLETED and player:getVar("Erlene_Sabbatical_Timer")~=VanadielDayOfTheYear() and mJob == JOB_SCH and mLvl >= AF2_QUEST_LEVEL and downwardHelix == QUEST_AVAILABLE) then
player:startEvent(0x0017);
elseif (downwardHelix == QUEST_ACCEPTED) then
if (player:getVar("DownwardHelix") == 0) then
player:startEvent(0x0018);
elseif (player:getVar("DownwardHelix") == 1) then
player:startEvent(0x0019);
elseif (player:getVar("DownwardHelix") < 4) then
player:startEvent(0x001A);
else
player:startEvent(0x001B);
end
else
player:startEvent(0x000F);
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 == 0x000A and option == 0) then
player:addQuest(CRYSTAL_WAR, A_LITTLE_KNOWLEDGE);
player:setVar("ALittleKnowledge", 1);
elseif (csid == 0x000C) then
player:tradeComplete();
player:setVar("ALittleKnowledge", 2);
elseif (csid == 0x000E) then
player:addKeyItem(GRIMOIRE);
player:unlockJob(JOB_SCH);
player:addTitle(SCHULTZ_SCHOLAR);
player:setVar("ALittleKnowledge", 0);
player:setVar("SheetsofVellum", 0);
player:messageSpecial(YOU_CAN_NOW_BECOME_A_SCHOLAR);
player:completeQuest(CRYSTAL_WAR, A_LITTLE_KNOWLEDGE);
elseif (csid == 0x002F) then
if (player:canLearnSpell(478) and player:canLearnSpell(502)) then
player:addSpell(478, true);
player:addSpell(502, true);
player:messageSpecial(YOU_LEARN_EMBRAVA_AND_KAUSTRA);
end
elseif (csid == 0x0012) then
player:addQuest(CRYSTAL_WAR, ON_SABBATICAL);
player:addKeyItem(ULBRECHTS_SEALED_LETTER);
player:messageSpecial(KEYITEM_OBTAINED, ULBRECHTS_SEALED_LETTER);
player:setVar("OnSabbatical", 1);
elseif (csid == 0x0014) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED);
else
player:delKeyItem(ULBRECHTS_SEALED_LETTER);
player:delKeyItem(SCHULTS_SEALED_LETTER);
player:completeQuest(CRYSTAL_WAR,ON_SABBATICAL);
player:addItem(6058); --klimaform
player:messageSpecial(ITEM_OBTAINED, 6058);
player:setVar("onSabbatical",0);
player:setVar("Erlene_Sabbatical_Timer",VanadielDayOfTheYear());
end
elseif (csid == 0x0017) then
player:setVar("Erlene_Sabbatical_Timer",0);
player:addQuest(CRYSTAL_WAR, DOWNWARD_HELIX);
elseif (csid == 0x0019) then
player:setVar("DownwardHelix",2);
elseif (csid == 0x001B) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED);
else
player:completeQuest(CRYSTAL_WAR, DOWNWARD_HELIX);
player:addItem(15004); -- Schlar's Bracers
player:messageSpecial(ITEM_OBTAINED, 15004);
player:setVar("DownwardHelix",0);
end
end
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Abyssea-Altepa/Zone.lua | 32 | 1531 | -----------------------------------
--
-- Zone: Abyssea - Altepa
--
-----------------------------------
package.loaded["scripts/zones/Abyssea-Altepa/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Abyssea-Altepa/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(435 ,0 ,320 ,136)
end
if (player:getQuestStatus(ABYSSEA, THE_TRUTH_BECKONS) == QUEST_ACCEPTED
and player:getVar("1stTimeAyssea") == 0) then
player:setVar("1stTimeAyssea",1);
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 |
adminmagma/telegood | plugins/steam.lua | 645 | 2117 | -- See https://wiki.teamfortress.com/wiki/User:RJackson/StorefrontAPI
do
local BASE_URL = 'http://store.steampowered.com/api/appdetails/'
local DESC_LENTH = 200
local function unescape(str)
str = string.gsub( str, '<', '<' )
str = string.gsub( str, '>', '>' )
str = string.gsub( str, '"', '"' )
str = string.gsub( str, ''', "'" )
str = string.gsub( str, '&#(%d+);', function(n) return string.char(n) end )
str = string.gsub( str, '&#x(%d+);', function(n) return string.char(tonumber(n,16)) end )
str = string.gsub( str, '&', '&' ) -- Be sure to do this after all others
return str
end
local function get_steam_data (appid)
local url = BASE_URL
url = url..'?appids='..appid
url = url..'&cc=us'
local res,code = http.request(url)
if code ~= 200 then return nil end
local data = json:decode(res)[appid].data
return data
end
local function price_info (data)
local price = '' -- If no data is empty
if data then
local initial = data.initial
local final = data.final or data.initial
local min = math.min(data.initial, data.final)
price = tostring(min/100)
if data.discount_percent and initial ~= final then
price = price..data.currency..' ('..data.discount_percent..'% OFF)'
end
price = price..' (US)'
end
return price
end
local function send_steam_data(data, receiver)
local description = string.sub(unescape(data.about_the_game:gsub("%b<>", "")), 1, DESC_LENTH) .. '...'
local title = data.name
local price = price_info(data.price_overview)
local text = title..' '..price..'\n'..description
local image_url = data.header_image
local cb_extra = {
receiver = receiver,
url = image_url
}
send_msg(receiver, text, send_photo_from_url_callback, cb_extra)
end
local function run(msg, matches)
local appid = matches[1]
local data = get_steam_data(appid)
local receiver = get_receiver(msg)
send_steam_data(data, receiver)
end
return {
description = "Grabs Steam info for Steam links.",
usage = "",
patterns = {
"http://store.steampowered.com/app/([0-9]+)",
},
run = run
}
end
| gpl-2.0 |
Victek/wrt1900ac-aa | veriksystems/luci-0.11/contrib/luasrcdiet/lua/LuaSrcDiet.lua | 122 | 23773 | #!/usr/bin/env lua
--[[--------------------------------------------------------------------
LuaSrcDiet
Compresses Lua source code by removing unnecessary characters.
For Lua 5.1.x source code.
Copyright (c) 2008 Kein-Hong Man <khman@users.sf.net>
The COPYRIGHT file describes the conditions
under which this software may be distributed.
See the ChangeLog for more information.
----------------------------------------------------------------------]]
--[[--------------------------------------------------------------------
-- NOTES:
-- * Remember to update version and date information below (MSG_TITLE)
-- * TODO: to implement pcall() to properly handle lexer etc. errors
-- * TODO: verify token stream or double-check binary chunk?
-- * TODO: need some automatic testing for a semblance of sanity
-- * TODO: the plugin module is highly experimental and unstable
----------------------------------------------------------------------]]
-- standard libraries, functions
local string = string
local math = math
local table = table
local require = require
local print = print
local sub = string.sub
local gmatch = string.gmatch
-- support modules
local llex = require "llex"
local lparser = require "lparser"
local optlex = require "optlex"
local optparser = require "optparser"
local plugin
--[[--------------------------------------------------------------------
-- messages and textual data
----------------------------------------------------------------------]]
local MSG_TITLE = [[
LuaSrcDiet: Puts your Lua 5.1 source code on a diet
Version 0.11.2 (20080608) Copyright (c) 2005-2008 Kein-Hong Man
The COPYRIGHT file describes the conditions under which this
software may be distributed.
]]
local MSG_USAGE = [[
usage: LuaSrcDiet [options] [filenames]
example:
>LuaSrcDiet myscript.lua -o myscript_.lua
options:
-v, --version prints version information
-h, --help prints usage information
-o <file> specify file name to write output
-s <suffix> suffix for output files (default '_')
--keep <msg> keep block comment with <msg> inside
--plugin <module> run <module> in plugin/ directory
- stop handling arguments
(optimization levels)
--none all optimizations off (normalizes EOLs only)
--basic lexer-based optimizations only
--maximum maximize reduction of source
(informational)
--quiet process files quietly
--read-only read file and print token stats only
--dump-lexer dump raw tokens from lexer to stdout
--dump-parser dump variable tracking tables from parser
--details extra info (strings, numbers, locals)
features (to disable, insert 'no' prefix like --noopt-comments):
%s
default settings:
%s]]
------------------------------------------------------------------------
-- optimization options, for ease of switching on and off
-- * positive to enable optimization, negative (no) to disable
-- * these options should follow --opt-* and --noopt-* style for now
------------------------------------------------------------------------
local OPTION = [[
--opt-comments,'remove comments and block comments'
--opt-whitespace,'remove whitespace excluding EOLs'
--opt-emptylines,'remove empty lines'
--opt-eols,'all above, plus remove unnecessary EOLs'
--opt-strings,'optimize strings and long strings'
--opt-numbers,'optimize numbers'
--opt-locals,'optimize local variable names'
--opt-entropy,'tries to reduce symbol entropy of locals'
]]
-- preset configuration
local DEFAULT_CONFIG = [[
--opt-comments --opt-whitespace --opt-emptylines
--opt-numbers --opt-locals
]]
-- override configurations: MUST explicitly enable/disable everything
local BASIC_CONFIG = [[
--opt-comments --opt-whitespace --opt-emptylines
--noopt-eols --noopt-strings --noopt-numbers
--noopt-locals
]]
local MAXIMUM_CONFIG = [[
--opt-comments --opt-whitespace --opt-emptylines
--opt-eols --opt-strings --opt-numbers
--opt-locals --opt-entropy
]]
local NONE_CONFIG = [[
--noopt-comments --noopt-whitespace --noopt-emptylines
--noopt-eols --noopt-strings --noopt-numbers
--noopt-locals
]]
local DEFAULT_SUFFIX = "_" -- default suffix for file renaming
local PLUGIN_SUFFIX = "plugin/" -- relative location of plugins
--[[--------------------------------------------------------------------
-- startup and initialize option list handling
----------------------------------------------------------------------]]
-- simple error message handler; change to error if traceback wanted
local function die(msg)
print("LuaSrcDiet: "..msg); os.exit()
end
--die = error--DEBUG
if not string.match(_VERSION, "5.1", 1, 1) then -- sanity check
die("requires Lua 5.1 to run")
end
------------------------------------------------------------------------
-- prepares text for list of optimizations, prepare lookup table
------------------------------------------------------------------------
local MSG_OPTIONS = ""
do
local WIDTH = 24
local o = {}
for op, desc in gmatch(OPTION, "%s*([^,]+),'([^']+)'") do
local msg = " "..op
msg = msg..string.rep(" ", WIDTH - #msg)..desc.."\n"
MSG_OPTIONS = MSG_OPTIONS..msg
o[op] = true
o["--no"..sub(op, 3)] = true
end
OPTION = o -- replace OPTION with lookup table
end
MSG_USAGE = string.format(MSG_USAGE, MSG_OPTIONS, DEFAULT_CONFIG)
------------------------------------------------------------------------
-- global variable initialization, option set handling
------------------------------------------------------------------------
local suffix = DEFAULT_SUFFIX -- file suffix
local option = {} -- program options
local stat_c, stat_l -- statistics tables
-- function to set option lookup table based on a text list of options
-- note: additional forced settings for --opt-eols is done in optlex.lua
local function set_options(CONFIG)
for op in gmatch(CONFIG, "(%-%-%S+)") do
if sub(op, 3, 4) == "no" and -- handle negative options
OPTION["--"..sub(op, 5)] then
option[sub(op, 5)] = false
else
option[sub(op, 3)] = true
end
end
end
--[[--------------------------------------------------------------------
-- support functions
----------------------------------------------------------------------]]
-- list of token types, parser-significant types are up to TTYPE_GRAMMAR
-- while the rest are not used by parsers; arranged for stats display
local TTYPES = {
"TK_KEYWORD", "TK_NAME", "TK_NUMBER", -- grammar
"TK_STRING", "TK_LSTRING", "TK_OP",
"TK_EOS",
"TK_COMMENT", "TK_LCOMMENT", -- non-grammar
"TK_EOL", "TK_SPACE",
}
local TTYPE_GRAMMAR = 7
local EOLTYPES = { -- EOL names for token dump
["\n"] = "LF", ["\r"] = "CR",
["\n\r"] = "LFCR", ["\r\n"] = "CRLF",
}
------------------------------------------------------------------------
-- read source code from file
------------------------------------------------------------------------
local function load_file(fname)
local INF = io.open(fname, "rb")
if not INF then die("cannot open \""..fname.."\" for reading") end
local dat = INF:read("*a")
if not dat then die("cannot read from \""..fname.."\"") end
INF:close()
return dat
end
------------------------------------------------------------------------
-- save source code to file
------------------------------------------------------------------------
local function save_file(fname, dat)
local OUTF = io.open(fname, "wb")
if not OUTF then die("cannot open \""..fname.."\" for writing") end
local status = OUTF:write(dat)
if not status then die("cannot write to \""..fname.."\"") end
OUTF:close()
end
------------------------------------------------------------------------
-- functions to deal with statistics
------------------------------------------------------------------------
-- initialize statistics table
local function stat_init()
stat_c, stat_l = {}, {}
for i = 1, #TTYPES do
local ttype = TTYPES[i]
stat_c[ttype], stat_l[ttype] = 0, 0
end
end
-- add a token to statistics table
local function stat_add(tok, seminfo)
stat_c[tok] = stat_c[tok] + 1
stat_l[tok] = stat_l[tok] + #seminfo
end
-- do totals for statistics table, return average table
local function stat_calc()
local function avg(c, l) -- safe average function
if c == 0 then return 0 end
return l / c
end
local stat_a = {}
local c, l = 0, 0
for i = 1, TTYPE_GRAMMAR do -- total grammar tokens
local ttype = TTYPES[i]
c = c + stat_c[ttype]; l = l + stat_l[ttype]
end
stat_c.TOTAL_TOK, stat_l.TOTAL_TOK = c, l
stat_a.TOTAL_TOK = avg(c, l)
c, l = 0, 0
for i = 1, #TTYPES do -- total all tokens
local ttype = TTYPES[i]
c = c + stat_c[ttype]; l = l + stat_l[ttype]
stat_a[ttype] = avg(stat_c[ttype], stat_l[ttype])
end
stat_c.TOTAL_ALL, stat_l.TOTAL_ALL = c, l
stat_a.TOTAL_ALL = avg(c, l)
return stat_a
end
--[[--------------------------------------------------------------------
-- main tasks
----------------------------------------------------------------------]]
------------------------------------------------------------------------
-- a simple token dumper, minimal translation of seminfo data
------------------------------------------------------------------------
local function dump_tokens(srcfl)
--------------------------------------------------------------------
-- load file and process source input into tokens
--------------------------------------------------------------------
local z = load_file(srcfl)
llex.init(z)
llex.llex()
local toklist, seminfolist = llex.tok, llex.seminfo
--------------------------------------------------------------------
-- display output
--------------------------------------------------------------------
for i = 1, #toklist do
local tok, seminfo = toklist[i], seminfolist[i]
if tok == "TK_OP" and string.byte(seminfo) < 32 then
seminfo = "(".. string.byte(seminfo)..")"
elseif tok == "TK_EOL" then
seminfo = EOLTYPES[seminfo]
else
seminfo = "'"..seminfo.."'"
end
print(tok.." "..seminfo)
end--for
end
----------------------------------------------------------------------
-- parser dump; dump globalinfo and localinfo tables
----------------------------------------------------------------------
local function dump_parser(srcfl)
local print = print
--------------------------------------------------------------------
-- load file and process source input into tokens
--------------------------------------------------------------------
local z = load_file(srcfl)
llex.init(z)
llex.llex()
local toklist, seminfolist, toklnlist
= llex.tok, llex.seminfo, llex.tokln
--------------------------------------------------------------------
-- do parser optimization here
--------------------------------------------------------------------
lparser.init(toklist, seminfolist, toklnlist)
local globalinfo, localinfo = lparser.parser()
--------------------------------------------------------------------
-- display output
--------------------------------------------------------------------
local hl = string.rep("-", 72)
print("*** Local/Global Variable Tracker Tables ***")
print(hl.."\n GLOBALS\n"..hl)
-- global tables have a list of xref numbers only
for i = 1, #globalinfo do
local obj = globalinfo[i]
local msg = "("..i..") '"..obj.name.."' -> "
local xref = obj.xref
for j = 1, #xref do msg = msg..xref[j].." " end
print(msg)
end
-- local tables have xref numbers and a few other special
-- numbers that are specially named: decl (declaration xref),
-- act (activation xref), rem (removal xref)
print(hl.."\n LOCALS (decl=declared act=activated rem=removed)\n"..hl)
for i = 1, #localinfo do
local obj = localinfo[i]
local msg = "("..i..") '"..obj.name.."' decl:"..obj.decl..
" act:"..obj.act.." rem:"..obj.rem
if obj.isself then
msg = msg.." isself"
end
msg = msg.." -> "
local xref = obj.xref
for j = 1, #xref do msg = msg..xref[j].." " end
print(msg)
end
print(hl.."\n")
end
------------------------------------------------------------------------
-- reads source file(s) and reports some statistics
------------------------------------------------------------------------
local function read_only(srcfl)
local print = print
--------------------------------------------------------------------
-- load file and process source input into tokens
--------------------------------------------------------------------
local z = load_file(srcfl)
llex.init(z)
llex.llex()
local toklist, seminfolist = llex.tok, llex.seminfo
print(MSG_TITLE)
print("Statistics for: "..srcfl.."\n")
--------------------------------------------------------------------
-- collect statistics
--------------------------------------------------------------------
stat_init()
for i = 1, #toklist do
local tok, seminfo = toklist[i], seminfolist[i]
stat_add(tok, seminfo)
end--for
local stat_a = stat_calc()
--------------------------------------------------------------------
-- display output
--------------------------------------------------------------------
local fmt = string.format
local function figures(tt)
return stat_c[tt], stat_l[tt], stat_a[tt]
end
local tabf1, tabf2 = "%-16s%8s%8s%10s", "%-16s%8d%8d%10.2f"
local hl = string.rep("-", 42)
print(fmt(tabf1, "Lexical", "Input", "Input", "Input"))
print(fmt(tabf1, "Elements", "Count", "Bytes", "Average"))
print(hl)
for i = 1, #TTYPES do
local ttype = TTYPES[i]
print(fmt(tabf2, ttype, figures(ttype)))
if ttype == "TK_EOS" then print(hl) end
end
print(hl)
print(fmt(tabf2, "Total Elements", figures("TOTAL_ALL")))
print(hl)
print(fmt(tabf2, "Total Tokens", figures("TOTAL_TOK")))
print(hl.."\n")
end
------------------------------------------------------------------------
-- process source file(s), write output and reports some statistics
------------------------------------------------------------------------
local function process_file(srcfl, destfl)
local function print(...) -- handle quiet option
if option.QUIET then return end
_G.print(...)
end
if plugin and plugin.init then -- plugin init
option.EXIT = false
plugin.init(option, srcfl, destfl)
if option.EXIT then return end
end
print(MSG_TITLE) -- title message
--------------------------------------------------------------------
-- load file and process source input into tokens
--------------------------------------------------------------------
local z = load_file(srcfl)
if plugin and plugin.post_load then -- plugin post-load
z = plugin.post_load(z) or z
if option.EXIT then return end
end
llex.init(z)
llex.llex()
local toklist, seminfolist, toklnlist
= llex.tok, llex.seminfo, llex.tokln
if plugin and plugin.post_lex then -- plugin post-lex
plugin.post_lex(toklist, seminfolist, toklnlist)
if option.EXIT then return end
end
--------------------------------------------------------------------
-- collect 'before' statistics
--------------------------------------------------------------------
stat_init()
for i = 1, #toklist do
local tok, seminfo = toklist[i], seminfolist[i]
stat_add(tok, seminfo)
end--for
local stat1_a = stat_calc()
local stat1_c, stat1_l = stat_c, stat_l
--------------------------------------------------------------------
-- do parser optimization here
--------------------------------------------------------------------
if option["opt-locals"] then
optparser.print = print -- hack
lparser.init(toklist, seminfolist, toklnlist)
local globalinfo, localinfo = lparser.parser()
if plugin and plugin.post_parse then -- plugin post-parse
plugin.post_parse(globalinfo, localinfo)
if option.EXIT then return end
end
optparser.optimize(option, toklist, seminfolist, globalinfo, localinfo)
if plugin and plugin.post_optparse then -- plugin post-optparse
plugin.post_optparse()
if option.EXIT then return end
end
end
--------------------------------------------------------------------
-- do lexer optimization here, save output file
--------------------------------------------------------------------
optlex.print = print -- hack
toklist, seminfolist, toklnlist
= optlex.optimize(option, toklist, seminfolist, toklnlist)
if plugin and plugin.post_optlex then -- plugin post-optlex
plugin.post_optlex(toklist, seminfolist, toklnlist)
if option.EXIT then return end
end
local dat = table.concat(seminfolist)
-- depending on options selected, embedded EOLs in long strings and
-- long comments may not have been translated to \n, tack a warning
if string.find(dat, "\r\n", 1, 1) or
string.find(dat, "\n\r", 1, 1) then
optlex.warn.mixedeol = true
end
-- save optimized source stream to output file
save_file(destfl, dat)
--------------------------------------------------------------------
-- collect 'after' statistics
--------------------------------------------------------------------
stat_init()
for i = 1, #toklist do
local tok, seminfo = toklist[i], seminfolist[i]
stat_add(tok, seminfo)
end--for
local stat_a = stat_calc()
--------------------------------------------------------------------
-- display output
--------------------------------------------------------------------
print("Statistics for: "..srcfl.." -> "..destfl.."\n")
local fmt = string.format
local function figures(tt)
return stat1_c[tt], stat1_l[tt], stat1_a[tt],
stat_c[tt], stat_l[tt], stat_a[tt]
end
local tabf1, tabf2 = "%-16s%8s%8s%10s%8s%8s%10s",
"%-16s%8d%8d%10.2f%8d%8d%10.2f"
local hl = string.rep("-", 68)
print("*** lexer-based optimizations summary ***\n"..hl)
print(fmt(tabf1, "Lexical",
"Input", "Input", "Input",
"Output", "Output", "Output"))
print(fmt(tabf1, "Elements",
"Count", "Bytes", "Average",
"Count", "Bytes", "Average"))
print(hl)
for i = 1, #TTYPES do
local ttype = TTYPES[i]
print(fmt(tabf2, ttype, figures(ttype)))
if ttype == "TK_EOS" then print(hl) end
end
print(hl)
print(fmt(tabf2, "Total Elements", figures("TOTAL_ALL")))
print(hl)
print(fmt(tabf2, "Total Tokens", figures("TOTAL_TOK")))
print(hl)
--------------------------------------------------------------------
-- report warning flags from optimizing process
--------------------------------------------------------------------
if optlex.warn.lstring then
print("* WARNING: "..optlex.warn.lstring)
elseif optlex.warn.mixedeol then
print("* WARNING: ".."output still contains some CRLF or LFCR line endings")
end
print()
end
--[[--------------------------------------------------------------------
-- main functions
----------------------------------------------------------------------]]
local arg = {...} -- program arguments
local fspec = {}
set_options(DEFAULT_CONFIG) -- set to default options at beginning
------------------------------------------------------------------------
-- per-file handling, ship off to tasks
------------------------------------------------------------------------
local function do_files(fspec)
for _, srcfl in ipairs(fspec) do
local destfl
------------------------------------------------------------------
-- find and replace extension for filenames
------------------------------------------------------------------
local extb, exte = string.find(srcfl, "%.[^%.%\\%/]*$")
local basename, extension = srcfl, ""
if extb and extb > 1 then
basename = sub(srcfl, 1, extb - 1)
extension = sub(srcfl, extb, exte)
end
destfl = basename..suffix..extension
if #fspec == 1 and option.OUTPUT_FILE then
destfl = option.OUTPUT_FILE
end
if srcfl == destfl then
die("output filename identical to input filename")
end
------------------------------------------------------------------
-- perform requested operations
------------------------------------------------------------------
if option.DUMP_LEXER then
dump_tokens(srcfl)
elseif option.DUMP_PARSER then
dump_parser(srcfl)
elseif option.READ_ONLY then
read_only(srcfl)
else
process_file(srcfl, destfl)
end
end--for
end
------------------------------------------------------------------------
-- main function (entry point is after this definition)
------------------------------------------------------------------------
local function main()
local argn, i = #arg, 1
if argn == 0 then
option.HELP = true
end
--------------------------------------------------------------------
-- handle arguments
--------------------------------------------------------------------
while i <= argn do
local o, p = arg[i], arg[i + 1]
local dash = string.match(o, "^%-%-?")
if dash == "-" then -- single-dash options
if o == "-h" then
option.HELP = true; break
elseif o == "-v" then
option.VERSION = true; break
elseif o == "-s" then
if not p then die("-s option needs suffix specification") end
suffix = p
i = i + 1
elseif o == "-o" then
if not p then die("-o option needs a file name") end
option.OUTPUT_FILE = p
i = i + 1
elseif o == "-" then
break -- ignore rest of args
else
die("unrecognized option "..o)
end
elseif dash == "--" then -- double-dash options
if o == "--help" then
option.HELP = true; break
elseif o == "--version" then
option.VERSION = true; break
elseif o == "--keep" then
if not p then die("--keep option needs a string to match for") end
option.KEEP = p
i = i + 1
elseif o == "--plugin" then
if not p then die("--plugin option needs a module name") end
if option.PLUGIN then die("only one plugin can be specified") end
option.PLUGIN = p
plugin = require(PLUGIN_SUFFIX..p)
i = i + 1
elseif o == "--quiet" then
option.QUIET = true
elseif o == "--read-only" then
option.READ_ONLY = true
elseif o == "--basic" then
set_options(BASIC_CONFIG)
elseif o == "--maximum" then
set_options(MAXIMUM_CONFIG)
elseif o == "--none" then
set_options(NONE_CONFIG)
elseif o == "--dump-lexer" then
option.DUMP_LEXER = true
elseif o == "--dump-parser" then
option.DUMP_PARSER = true
elseif o == "--details" then
option.DETAILS = true
elseif OPTION[o] then -- lookup optimization options
set_options(o)
else
die("unrecognized option "..o)
end
else
fspec[#fspec + 1] = o -- potential filename
end
i = i + 1
end--while
if option.HELP then
print(MSG_TITLE..MSG_USAGE); return true
elseif option.VERSION then
print(MSG_TITLE); return true
end
if #fspec > 0 then
if #fspec > 1 and option.OUTPUT_FILE then
die("with -o, only one source file can be specified")
end
do_files(fspec)
return true
else
die("nothing to do!")
end
end
-- entry point -> main() -> do_files()
if not main() then
die("Please run with option -h or --help for usage information")
end
-- end of script
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Southern_San_dOria/npcs/Cletae.lua | 34 | 1470 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Cletae
-- Guild Merchant NPC: Leathercrafting Guild
-- @pos -189.142 -8.800 14.449 230
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/conquest");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
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)
if (player:sendGuild(5292,3,18,4)) then
player:showText(npc,CLETAE_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/globals/items/bowl_of_ocean_soup.lua | 35 | 1893 | -----------------------------------------
-- ID: 4285
-- Item: bowl_of_ocean_soup
-- Food Effect: 4Hrs, All Races
-----------------------------------------
-- HP % 5
-- MP 5
-- Dexterity 4
-- Mind -3
-- HP Recovered While Healing 9
-- Attack % 14 (cap 65)
-- Ranged Attack % 14 (cap 65)
-----------------------------------------
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,4285);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 5);
target:addMod(MOD_FOOD_HP_CAP, 999);
target:addMod(MOD_MP, 5);
target:addMod(MOD_DEX, 4);
target:addMod(MOD_MND, -3);
target:addMod(MOD_HPHEAL, 9);
target:addMod(MOD_FOOD_ATTP, 14);
target:addMod(MOD_FOOD_ATT_CAP, 65);
target:addMod(MOD_FOOD_RATTP, 14);
target:addMod(MOD_FOOD_RATT_CAP, 65);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 5);
target:delMod(MOD_FOOD_HP_CAP, 999);
target:delMod(MOD_MP, 5);
target:delMod(MOD_DEX, 4);
target:delMod(MOD_MND, -3);
target:delMod(MOD_HPHEAL, 9);
target:delMod(MOD_FOOD_ATTP, 14);
target:delMod(MOD_FOOD_ATT_CAP, 65);
target:delMod(MOD_FOOD_RATTP, 14);
target:delMod(MOD_FOOD_RATT_CAP, 65);
end;
| gpl-3.0 |
SpRoXx/GTW-RPG | [resources]/GTWtraindriver/data.lua | 1 | 2967 | --[[
********************************************************************************
Project owner: RageQuit community
Project name: GTW-RPG
Developers: Mr_Moose
Source code: https://github.com/GTWCode/GTW-RPG/
Bugtracker: http://forum.404rq.com/bug-reports/
Suggestions: http://forum.404rq.com/mta-servers-development/
Version: Open source
License: BSD 2-Clause
Status: Stable release
********************************************************************************
]]--
-- List of vehicles that are considered to be a train
train_vehicles = {
[537] = true,
[538] = true
}
-- List over all train routes
train_routes = {
-- Name of route to display in list
["Inner SA track (clockwise)"] = {
-- x, y, z, rot
[1]={ 1690.994140625, -1953.63671875, 15.099542617798, 270.02197265625 }, -- LS unity
[2]={ 783.5966796875, -1338.513671875, 0.099542617797852, 47.604400634766 },
[3]={ -1940.6318359375, 196.9970703125, 27.166990280151, 349.81826782227 },
[4]={ -171.7392578125, 1280.1787109375, 23.95253944397, 359.51934814453 },
[5]={ 1483.2880859375, 2632.25, 12.125619888306, 270.02197265625 },
[6]={ 2780.875, 1710.5732421875, 12.125619888306, 180 },
[7]={ 2864.75, 1233.017578125, 12.125619888306, 180 },
[8]={ 2827.701171875, -10.7138671875, 31.840360641479, 180.26374816895 },
[9]={ 2284.8720703125, -1364.2705078125, 25.497358322144, 180 },
},
["Inner SA track (counter clockwise)"] = {
-- x, y, z, rot
[9]={ 1690.994140625, -1953.63671875, 15.099542617798, 270.02197265625 }, -- LS unity
[8]={ 783.5966796875, -1338.513671875, 0.099542617797852, 47.604400634766 },
[7]={ -1940.6318359375, 196.9970703125, 27.166990280151, 349.81826782227 },
[6]={ -171.7392578125, 1280.1787109375, 23.95253944397, 359.51934814453 },
[5]={ 1483.2880859375, 2632.25, 12.125619888306, 270.02197265625 },
[4]={ 2780.875, 1710.5732421875, 12.125619888306, 180 },
[3]={ 2864.75, 1233.017578125, 12.125619888306, 180 },
[2]={ 2827.701171875, -10.7138671875, 31.840360641479, 180.26374816895 },
[1]={ 2284.8720703125, -1364.2705078125, 25.497358322144, 180 },
},
["Outer SA track (counter clockwise)"] = {
-- x, y, z, rot
[1]={ -1948.375, 65.9140625, 27.000619888306, 0.0439453125 }, -- SF
[2]={ 844.974609375, -1399.873046875, 0.066656351089478, 47.164825439453 }, -- LS Market
[3]={ 1779.916015625, -1957.75, 14.875619888306, 270.02197265625 },
[4]={ 2288.875, -1175.82421875, 27.525365829468, 180 },
},
["Outer SA track (clockwise)"] = {
-- x, y, z, rot
[4]={ -1948.375, 65.9140625, 27.000619888306, 0.0439453125 }, -- SF
[3]={ 844.974609375, -1399.873046875, 0.066656351089478, 47.164825439453 }, -- LS Market
[2]={ 1779.916015625, -1957.75, 14.875619888306, 270.02197265625 },
[1]={ 2288.875, -1175.82421875, 27.525365829468, 180 },
},
}
| bsd-2-clause |
jshackley/darkstar | scripts/zones/Monarch_Linn/bcnms/savage.lua | 17 | 1700 | -----------------------------------
-- Area: Monarch Linn
-- Name: savage
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/missions");
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
--printf("leavecode: %u",leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if (player:getCurrentMission(COP) == THE_SAVAGE and player:getVar("PromathiaStatus") == 1) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,1);
end
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
if (csid == 0x7d01) then
player:addExp(1500);
player:addTitle(MIST_MELTER);
if (player:getCurrentMission(COP) == THE_SAVAGE and player:getVar("PromathiaStatus") == 1) then
player:setVar("PromathiaStatus",2);
end
end
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Windurst_Woods/npcs/Bopa_Greso.lua | 19 | 1725 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Bopa Greso
-- Type: Standard NPC
-- @zone: 241
-- @pos 59.773 -6.249 216.766
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
thickAsThieves = player:getQuestStatus(WINDURST,AS_THICK_AS_THIEVES);
thickAsThievesCS = player:getVar("thickAsThievesCS");
if (thickAsThieves == QUEST_ACCEPTED) then
player:startEvent(0x01FA);
if (thickAsThievesCS == 1) then
player:setVar("thickAsThievesCS",2);
elseif (thickAsThievesCS == 3) then
player:setVar("thickAsThievesCS",4);
rand1 = math.random(2,7);
player:setVar("thickAsThievesGrapplingCS",rand1);
player:setVar("thickAsThievesGamblingCS",1);
end
else
player:startEvent(0x004d); -- standard cs
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 |
jshackley/darkstar | scripts/globals/abilities/dancers_roll.lua | 9 | 3136 | -----------------------------------
-- Ability: Dancer's Roll
-- Grants Regen status to party members within area of effect
-- Optimal Job: Dancer
-- Lucky Number: 3
-- Unlucky Number: 7
-- Level: 61
--
-- Die Roll |No DNC |With DNC
-- -------- ---------- ----------
-- 1 |3HP/Tick |7HP/Tick
-- 2 |4HP/Tick |8HP/Tick
-- 3 |12HP/Tick |16HP/Tick
-- 4 |5HP/Tick |9HP/Tick
-- 5 |6HP/Tick |10HP/Tick
-- 6 |7HP/Tick |11HP/Tick
-- 7 |1HP/Tick |5HP/Tick
-- 8 |8HP/Tick |12HP/Tick
-- 9 |9HP/Tick |13HP/Tick
-- 10 |10HP/Tick |14HP/Tick
-- 11 |16HP/Tick |20HP/Tick
-- 12+ |-4hp(regen)/Tick |-4hp(regen)/Tick
-- A bust will cause a regen effect on you to be reduced by 4, it will not drain HP from you if no regen effect is active.
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
local effectID = getCorsairRollEffect(ability:getID());
ability:setRange(ability:getRange() + player:getMod(MOD_ROLL_RANGE));
if (player:hasStatusEffect(effectID) or player:hasBustEffect(effectID)) then
return MSGBASIC_ROLL_ALREADY_ACTIVE,0;
else
player:setLocalVar("DNC_roll_bonus", 0);
return 0,0;
end
end;
-----------------------------------
-- onUseAbilityRoll
-----------------------------------
function onUseAbilityRoll(caster,target,ability,total)
local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK)
local effectpowers = {3, 4, 12, 5, 6, 7, 1, 8, 9, 10, 16, 4};
local effectpower = effectpowers[total]
local jobBonus = caster:getLocalVar("DNC_roll_bonus");
if (total < 12) then -- see chaos_roll.lua for comments
if (jobBonus == 0) then
if (caster:hasPartyJob(JOB_DNC) or math.random(0, 99) < caster:getMod(MOD_JOB_BONUS_CHANCE)) then
jobBonus = 1;
else
jobBonus = 2;
end
end
if (jobBonus == 1) then
effectpower = effectpower + 4;
end
if (target:getID() == caster:getID()) then
caster:setLocalVar("DNC_roll_bonus", jobBonus);
end
end
if (caster:getMainJob() == JOB_COR and caster:getMainLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl());
elseif (caster:getSubJob() == JOB_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_DANCERS_ROLL, effectpower, 0, duration, caster:getID(), total, MOD_REGEN) == false) then
ability:setMsg(423);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Windurst_Walls/npcs/Trail_Markings.lua | 17 | 2749 | -----------------------------------
-- Area: Windurst Walls
-- NPC: Trail Markings
-- Dynamis-Windurst Enter
-- @pos -216 0 -94 239
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/dynamis");
require("scripts/zones/Windurst_Walls/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("Dynamis_Status") == 1) then
player:startEvent(0x01c7); -- cs with Cornelia
elseif (player:getVar("DynaWindurst_Win") == 1) then
player:startEvent(0x01d1,HYDRA_CORPS_LANTERN); -- Win CS
elseif (player:hasKeyItem(VIAL_OF_SHROUDED_SAND)) then
local firstDyna = 0;
local realDay = os.time();
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if (checkFirstDyna(player,3)) then -- First Dyna-Windurst => CS
firstDyna = 1;
end
if (player:getMainLvl() < DYNA_LEVEL_MIN) then
player:messageSpecial(PLAYERS_HAVE_NOT_REACHED_LEVEL,DYNA_LEVEL_MIN);
elseif ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaWindurst]UniqueID")) then
player:startEvent(0x01c4,3,firstDyna,0,BETWEEN_2DYNA_WAIT_TIME,64,VIAL_OF_SHROUDED_SAND,4236,4237);
else
dayRemaining = math.floor(((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) - realDay)/3456);
player:messageSpecial(YOU_CANNOT_ENTER_DYNAMIS,dayRemaining,3);
end
else
player:messageSpecial(STRANDS_OF_GRASS_HERE);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("updateRESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
-- printf("finishRESULT: %u",option);
if (csid == 0x01c7) then
player:addKeyItem(VIAL_OF_SHROUDED_SAND);
player:messageSpecial(KEYITEM_OBTAINED,VIAL_OF_SHROUDED_SAND);
player:setVar("Dynamis_Status",0);
elseif (csid == 0x01d1) then
player:setVar("DynaWindurst_Win",0);
elseif (csid == 0x01c4 and option == 0) then
if (checkFirstDyna(player,3)) then
player:setVar("Dynamis_Status",player:getVar("Dynamis_Status") + 8);
end
player:setPos(-221.988,1.000,-120.184,0,0xbb);
end
end; | gpl-3.0 |
Keithenneu/Dota2-FullOverwrite | abilityUse/abilityUse_template.lua | 1 | 3951 | -------------------------------------------------------------------------------
--- AUTHOR: Nostrademous
--- GITHUB REPO: https://github.com/Nostrademous/Dota2-FullOverwrite
-------------------------------------------------------------------------------
BotsInit = require( "game/botsinit" )
local genericAbility = BotsInit.CreateGeneric()
local utils = require( GetScriptDirectory().."/utility" )
local gHeroVar = require( GetScriptDirectory().."/global_hero_data" )
function setHeroVar(var, value)
local bot = GetBot()
gHeroVar.SetVar(bot:GetPlayerID(), var, value)
end
function getHeroVar(var)
local bot = GetBot()
return gHeroVar.GetVar(bot:GetPlayerID(), var)
end
local abilityQ = ""
local abilityW = ""
local abilityE = ""
local abilityR = ""
local AttackRange = 0
local ManaPerc = 0.0
local HealthPerc = 0.0
local modeName = nil
function genericAbility:AbilityUsageThink(bot)
-- Check if we're already using an ability
if utils.IsBusy(bot) then return true end
-- Check to see if we are CC'ed
if utils.IsUnableToCast(bot) then return false end
if abilityQ == "" then abilityQ = bot:GetAbilityByName( "FILL ME OUT" ) end
if abilityW == "" then abilityW = bot:GetAbilityByName( "FILL ME OUT" ) end
if abilityE == "" then abilityE = bot:GetAbilityByName( "FILL ME OUT" ) end
if abilityR == "" then abilityR = bot:GetAbilityByName( "FILL ME OUT" ) end
AttackRange = bot:GetAttackRange()
ManaPerc = bot:GetMana()/bot:GetMaxMana()
HealthPerc = bot:GetHealth()/bot:GetMaxHealth()
modeName = bot.SelfRef:getCurrentMode():GetName()
-- CHECK BELOW TO SEE WHICH ABILITIES ARE NOT PASSIVE AND WHAT RETURN TYPES ARE --
-- Consider using each ability
local castQDesire, castQTarget = ConsiderQ()
local castWDesire = ConsiderW()
local castEDesire, castELoc = ConsiderE()
local castRDesire, castRTarget = ConsiderR()
-- CHECK BELOW TO SEE WHAT PRIORITY OF ABILITIES YOU WANT FOR THIS HERO --
if castRDesire > 0 then
gHeroVar.HeroUseAbilityOnEntity(bot, abilityR, castRTarget)
return true
end
if castEDesire > 0 then
gHeroVar.HeroUseAbilityOnLocation(bot, abilityE, castELoc)
return true
end
if castWDesire > 0 then
gHeroVar.HeroUseAbility(bot, abilityW)
return true
end
if castQDesire > 0 then
gHeroVar.HeroUseAbilityOnEntity(bot, abilityQ, castQTarget)
return true
end
return false
end
function ConsiderQ()
local bot = GetBot()
if not abilityQ:IsFullyCastable() then
return BOT_ACTION_DESIRE_NONE, nil
end
-- WRITE CODE HERE --
return BOT_ACTION_DESIRE_NONE, nil
end
function ConsiderW()
local bot = GetBot()
if not abilityW:IsFullyCastable() then
return BOT_ACTION_DESIRE_NONE
end
-- WRITE CODE HERE --
return BOT_ACTION_DESIRE_NONE
end
function ConsiderE()
local bot = GetBot()
if not abilityE:IsFullyCastable() then
return BOT_ACTION_DESIRE_NONE
end
-- WRITE CODE HERE --
return BOT_ACTION_DESIRE_NONE
end
function ConsiderR()
local bot = GetBot()
if not abilityR:IsFullyCastable() then
return BOT_ACTION_DESIRE_NONE, nil
end
-- WRITE CODE HERE --
return BOT_ACTION_DESIRE_NONE, nil
end
function genericAbility:nukeDamage( bot, enemy )
if not utils.ValidTarget(enemy) then return 0, {}, 0, 0, 0 end
local comboQueue = {}
local manaAvailable = bot:GetMana()
local dmgTotal = 0
local castTime = 0
local stunTime = 0
local slowTime = 0
local engageDist = 10000
-- WRITE CODE HERE --
return dmgTotal, comboQueue, castTime, stunTime, slowTime, engageDist
end
function genericAbility:queueNuke(bot, enemy, castQueue, engageDist)
if not utils.ValidTarget(enemy) then return false end
-- WRITE CODE HERE --
return false
end
return genericAbility
| gpl-3.0 |
robertop/pelet | premake_functions.lua | 1 | 3503 | -------------------------------------------------------------------
-- This software is released under the terms of the MIT License
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
-- @copyright 2009-2012 Roberto Perpuly
-- @license http://www.opensource.org/licenses/mit-license.php The MIT License
-------------------------------------------------------------------
-- takes a path relative to the project root and returns an absolute path that
-- this function will also enclose the path in quotes; allowing file paths with spaces to be used.
-- main purpose of this function is to generate paths that can be embedded into strings that consist
-- of system commands.
function normalizepath(path)
if os.is "windows" then
-- Windows XP doesn't like forward slashes
path = "\"" .. string.gsub(os.getcwd(), "/", "\\") .. "\\" .. string.gsub(path, "/", "\\") .. "\"";
else
path = "\"" .. os.getcwd() .. "/" .. path .. "\"";
end
return path
end
-- takes a path relative to the project root and checks that it exists in the file system. if
-- the file does not exist the program will exit.
--
-- @param pathsToCheck a table of strings or a single string
--
function existence(pathsToCheck)
paths = {}
if 'string' == type(pathsToCheck) then
table.insert(paths, pathsToCheck)
elseif 'table' == type(pathsToCheck) then
for key, value in pairs(pathsToCheck) do
table.insert(paths, value)
end
end
for key, value in pairs(paths) do
if not os.isfile(value) then
print("Required file not found: " .. value)
print "Program will now exit"
os.exit(1)
end
end
end
--
-- execute a table of commands
-- if a single command fails then the program will exit
--
-- @param basedir the directory where the commands will be executed from
-- @param cmds the list of commands
--
function batchexecute(basedir, cmds, errorMessage)
if #cmds then
cmdString = "cd " .. basedir .. " && ";
for key, cmd in ipairs(cmds) do
cmdString = cmdString .. cmd
if next(cmds, key) then
cmdString = cmdString .. " && ";
end
end
if #cmdString then
if 0 ~= os.execute(cmdString) then
if errorMessage then
print(errorMessage)
end
print "Command Failed"
print(cmdString)
print "Program will now exit"
os.exit(1)
end
end
end
end
--
-- changes into destdir and unzips file
--
function decompress(destdir, file)
batchexecute(destdir, {
"tar zxf " .. file
});
end | mit |
jshackley/darkstar | scripts/zones/Windurst_Woods/npcs/Retto-Marutto.lua | 19 | 1169 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Retto-Marutto
-- Guild Merchant NPC: Bonecrafting Guild
-- @pos -6.142 -6.55 -132.639 241
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(5142,8,23,3)) then
player:showText(npc,RETTO_MARUTTO_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
sugiartocokrowibowo/Algorithm-Implementations | Dijkstra_Search/Lua/Yonaba/dijkstra_test.lua | 26 | 3032 | -- Tests for dijkstra.lua
local Dijkstra = require 'dijkstra'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function same(t, p, comp)
for k,v in ipairs(t) do
if not comp(v, p[k]) then return false end
end
return true
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
run('Testing linear graph', function()
local comp = function(a, b) return a.value == b end
local ln_handler = require 'handlers.linear_handler'
ln_handler.init(1,5)
local dijkstra = Dijkstra(ln_handler)
local source, dest = ln_handler.getNode(1), ln_handler.getNode(5)
assert(same(dijkstra:process(source, dest), {1,2,3,4,5}, comp))
dijkstra:process(source)
assert(ln_handler.getNode(1).distance == 0)
assert(ln_handler.getNode(2).distance == 1)
assert(ln_handler.getNode(3).distance == 2)
assert(ln_handler.getNode(4).distance == 3)
assert(ln_handler.getNode(5).distance == 4)
end)
run('Testing grid graph', function()
local comp = function(a, b) return a.x == b[1] and a.y == b[2] end
local gm_handler = require 'handlers.gridmap_handler'
local dijkstra = Dijkstra(gm_handler)
local map = {{0,0,0,0,0},{0,1,1,1,1},{0,0,0,0,0}}
gm_handler.init(map)
gm_handler.diagonal = false
local source, dest = gm_handler.getNode(1,1), gm_handler.getNode(5,3)
assert(same(dijkstra:process(source, dest), {{1,1},{1,2},{1,3},{2,3},{3,3},{4,3},{5,3}}, comp))
gm_handler.diagonal = true
assert(same(dijkstra:process(source, dest), {{1,1},{1,2},{2,3},{3,3},{4,3},{5,3}}, comp))
end)
run('Testing point graph', function()
local comp = function(a, b) return a.x == b[1] and a.y == b[2] end
local pg_handler = require 'handlers.point_graph_handler'
local dijkstra = Dijkstra(pg_handler)
pg_handler.addNode('a')
pg_handler.addNode('b')
pg_handler.addNode('c')
pg_handler.addNode('d')
pg_handler.addNode('e')
pg_handler.addNode('f')
pg_handler.addEdge('a', 'b', 5)
pg_handler.addEdge('b', 'c', 10)
pg_handler.addEdge('c', 'd', 5)
pg_handler.addEdge('d', 'e', 5)
pg_handler.addEdge('e', 'f', 10)
pg_handler.addEdge('f', 'a', 5)
pg_handler.addEdge('f', 'b', 10)
pg_handler.addEdge('e', 'c', 10)
pg_handler.addEdge('a', 'd', 15)
local comp = function(a, b) return a.name == b end
local source, dest = pg_handler.getNode('a'), pg_handler.getNode('d')
assert(same(dijkstra:process(source, dest),{'a','d'}, comp))
pg_handler.setEdgeWeight('a', 'd', 40)
assert(same(dijkstra:process(source, dest),{'a','b','c', 'd'}, comp))
pg_handler.setEdgeWeight('a', 'b', 6)
assert(same(dijkstra:process(source, dest),{'a','f','e', 'd'}, comp))
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
sugiartocokrowibowo/Algorithm-Implementations | Knapsack/Lua/Yonaba/knapsack.lua | 26 | 2985 | -- Knapsack problem algorithm implementation
-- See: http://en.wikipedia.org/wiki/Knapsack_problem
-- Pops value at the head of an array
local function pop(s)
local head = s[1]
table.remove(s, 1)
return head
end
-- Note: the items to be passed should be represented this way
-- items = {
-- {name = 'item_name', w = <item_weight>, b = <benefit>},
-- {name = 'item_name', w = <item_weight>, b = <benefit>},
-- ...
-- }
-- In the returned output, each item will receive a new attribute 'p'
-- referring to how much (percentage) of the item has been added into
-- the knapsack.
-- Performs fractional Knapsack. Fractional here means we can
-- select a portion of a item. With that respect, this implementation
-- is greedy.
-- items : an array of items (see note before). This array will be
-- sorted regarding their benefits in decreasing order.
-- capacity: the maximum capacity of the knapsack
-- returns : 1. an array of items
-- 2. the maximum profit
local function fractionalKnapsack(items, capacity)
table.sort(items, function(a, b) return a.b > b.b end)
local inKnapsack, profit = {}, 0
while capacity > 0 do
local max_item = pop(items)
max_item.p = max_item.w > capacity and capacity/max_item.w or 1
max_item.b = max_item.p * max_item.b
max_item.w = max_item.p * max_item.w
capacity = capacity - max_item.w
table.insert(inKnapsack, max_item)
profit = profit + max_item.b
end
return inKnapsack, profit
end
-- Performs standard 0/1 Knapsack, meaning that an item is either
-- picked or not. This implementation uses dynamic programming.
-- items : an array of items (see note before).
-- capacity: the maximum capacity of the knapsack
-- returns : 1. an array of items
-- 2. the maximum profit
local function integerKnapsack(items, capacity)
-- Get the count of items
local numOfItems = #items
-- Auxiliary tables for dynamic search and selected items tracking
local V, K = {}, {}
-- Inits auxiliary tables with 0's. Note that although
-- Lua's arrays start at 1, we start looping at 0
for i = 0, numOfItems do
V[i], K[i] = {}, {}
for w = 0, capacity do
V[i][w], K[i][w] = 0, 0
end
end
-- Dynamic search
for i = 1, numOfItems do
local item = items[i]
for w = 0, capacity do
if item.w < w
and (item.b + V[i - 1][w - item.w] > V[i - 1][w]) then
V[i][w] = item.b + V[i-1][w - item.w]
K[i][w] = 1
else
V[i][w] = V[i - 1][w]
K[i][w] = 0
end
end
end
-- Process auxiliary tables to identify
-- selected items and evaluate the profit
local inKnapsack, profit = {}, 0
for i = numOfItems, 1, -1 do
local item = items[i]
if K[i][capacity] == 1 then
table.insert(inKnapsack, item)
capacity = capacity - item.w
profit = profit + item.b
end
end
return inKnapsack, profit
end
return {
fractional = fractionalKnapsack,
integer = integerKnapsack
}
| mit |
10sa/Advanced-Nutscript | nutscript/plugins/improveddoors/sh_commands.lua | 1 | 7575 | local PLUGIN = PLUGIN
nut.command.Register({
onRun = function(client, arguments)
local data = {}
data.start = client:GetShootPos()
data.endpos = data.start + client:GetAimVector() * 84
data.filter = client
local trace = util.TraceLine(data)
local entity = trace.Entity
if (IsValid(entity) and PLUGIN:IsDoor(entity) and !entity:GetNetVar("hidden")) then
if (entity:GetNetVar("unownable")) then
return
end
local cost = nut.config.doorCost
if (!client:CanAfford(cost)) then
nut.util.Notify(nut.lang.Get("no_afford"), client)
return
end
if (!PLUGIN:IsDoorOwned(entity)) then
PLUGIN:SetDoorOwner(entity, client);
entity:SetNetVar("title", PLUGIN:GetPluginLanguage("doors_buyed_door"));
entity:SetNetVar("desc", PLUGIN:GetPluginLanguage("doors_owner", client:Name()));
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_buy_door", nut.currency.GetName(cost)), client)
client:TakeMoney(cost)
else
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_selled_door"), client)
end
else
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_not_door"), client)
end
end
}, "doorbuy")
nut.command.Register({
onRun = function(client, arguments)
local data = {}
data.start = client:GetShootPos()
data.endpos = data.start + client:GetAimVector() * 84
data.filter = client
local trace = util.TraceLine(data)
local entity = trace.Entity
if (IsValid(entity) and PLUGIN:IsDoor(entity) and !entity:GetNetVar("hidden")) then
if (PLUGIN:EqualDoorOwner(entity, client)) then
PLUGIN:SetDoorOwner(entity, nil);
entity:SetNetVar("title", PLUGIN:GetPluginLanguage("doors_can_buy"))
local amount = nut.config.doorSellAmount
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_sell_door", nut.currency.GetName(amount)), client)
client:GiveMoney(amount)
else
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_not_owner"), client)
end
else
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_not_door"), client)
end
end
}, "doorsell")
nut.command.Register({
adminOnly = true,
onRun = function(client, arguments)
local data = {}
data.start = client:GetShootPos()
data.endpos = data.start + client:GetAimVector() * 84
data.filter = client
local trace = util.TraceLine(data)
local entity = trace.Entity
if (IsValid(entity) and PLUGIN:IsDoor(entity) and !entity:GetNetVar("hidden")) then
if (!PLUGIN:IsDoorOwned(entity)) then
nut.util.Notify(PLUGIN:GetPluginLanguage("already_ownable"), client);
else
entity:SetNetVar("owner", nil)
entity:SetNetVar("title", PLUGIN:GetPluginLanguage("doors_can_buy"));
entity:SetNetVar("desc", PLUGIN:GetPluginLanguage("doors_buy_desc"));
nut.util.Notify(PLUGIN:GetPluginLanguage("successful_selling"), client);
end;
else
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_not_door"), client)
end
end
}, "doorforcesell");
nut.command.Register({
adminOnly = true,
onRun = function(client, arguments)
local data = {}
data.start = client:GetShootPos()
data.endpos = data.start + client:GetAimVector() * 84
data.filter = client
local trace = util.TraceLine(data)
local entity = trace.Entity
local title = PLUGIN:GetPluginLanguage("doors_buyed_door")
if (#arguments > 0) then
title = table.concat(arguments, " ")
end
if (IsValid(entity) and PLUGIN:IsDoor(entity)) then
entity:SetNetVar("title", title);
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_change_title"), client);
else
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_not_door"), client);
end
end
}, "doorsettitle");
nut.command.Register({
adminOnly = true,
onRun = function(client, arguments)
local entity = AdvNut.util.GetPlayerTraceEntity(client);
local desc = PLUGIN:GetPluginLanguage("doors_buyed_door")
if (#arguments > 0) then
desc = table.concat(arguments, " ")
end
if (IsValid(entity) and PLUGIN:IsDoor(entity)) then
entity:SetNetVar("desc", desc);
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_change_title"), client);
else
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_not_door"), client);
end
end
}, "doorsetdesc");
nut.command.Register({
adminOnly = true,
onRun = function(client, arguments)
local trace = client:GetEyeTraceNoCursor()
local entity = trace.Entity
if (IsValid(entity) and PLUGIN:IsDoor(entity)) then
if (PLUGIN:IsDoorOwned(entity)) then
nut.util.Notify(PLUGIN:GetPluginLanguage("already_buyed"), client);
else
local title = PLUGIN:GetPluginLanguage("doors_cant_buy")
PLUGIN:DoorSetUnownable(entity)
entity:SetNetVar("title", PLUGIN:GetPluginLanguage("doors_cant_buy"));
entity:SetNetVar("desc", PLUGIN:GetPluginLanguage("doors_cant_buy"));
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_change_unownable"), client);
end;
else
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_not_door"), client)
end
end
}, "doorsetunownable")
nut.command.Register({
adminOnly = true,
onRun = function(client, arguments)
local trace = client:GetEyeTraceNoCursor()
local entity = trace.Entity
if (IsValid(entity) and PLUGIN:IsDoor(entity)) then
local hidden = util.tobool(arguments[1])
PLUGIN:DoorSetHidden(entity, hidden)
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_change_hidden", (hidden and PLUGIN:GetPluginLanguage("doors_hidden") or PLUGIN:GetPluginLanguage("doors_show"))), client)
else
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_not_door"), client)
end
end
}, "doorsethidden")
nut.command.Register({
adminOnly = true,
onRun = function(client, arguments)
for k, v in pairs(ents.GetAll()) do
if (IsValid(v)) then
if (PLUGIN:IsDoor(v)) then
PLUGIN:DoorSetHidden(v, true);
end
end
end
end
}, "doorssethidden");
nut.command.Register({
adminOnly = true,
onRun = function(client, arguments)
local trace = client:GetEyeTraceNoCursor()
local entity = trace.Entity
if (IsValid(entity) and PLUGIN:IsDoor(entity)) then
if (PLUGIN:IsDoorOwned(entity)) then
nut.util.Notify(PLUGIN:GetPluginLanguage("already_buyed"), client);
else
PLUGIN:DoorSetOwnable(entity);
entity:SetNetVar("title", PLUGIN:GetPluginLanguage("doors_can_buy"));
entity:SetNetVar("desc", PLUGIN:GetPluginLanguage("doors_buy_desc"));
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_change_ownable"), client);
end;
else
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_not_door"), client)
end
end
}, "doorsetownable")
nut.command.Register({
adminOnly = true,
onRun = function(client, arguments)
local data = {}
data.start = client:GetShootPos()
data.endpos = data.start + client:GetAimVector() * 84
data.filter = client
local trace = util.TraceLine(data)
local entity = trace.Entity
if (IsValid(entity) and PLUGIN:IsDoor(entity)) then
PLUGIN:LockDoor(entity)
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_open_door"), client)
else
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_not_door"), client)
end
end
}, "doorlock")
nut.command.Register({
adminOnly = true,
onRun = function(client, arguments)
local data = {}
data.start = client:GetShootPos()
data.endpos = data.start + client:GetAimVector() * 84
data.filter = client
local trace = util.TraceLine(data)
local entity = trace.Entity
if (IsValid(entity) and PLUGIN:IsDoor(entity)) then
PLUGIN:UnlockDoor(entity)
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_close_door"), client)
else
nut.util.Notify(PLUGIN:GetPluginLanguage("doors_not_door"), client)
end
end
}, "doorunlock")
| mit |
jshackley/darkstar | scripts/globals/items/bowl_of_vegetable_soup.lua | 35 | 1398 | -----------------------------------------
-- ID: 4560
-- Item: bowl_of_vegetable_soup
-- Food Effect: 3Hrs, All Races
-----------------------------------------
-- Vitality -1
-- Agility 4
-- Ranged Accuracy 5
-- HP Recovered While Healing 3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4560);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_VIT, -1);
target:addMod(MOD_AGI, 4);
target:addMod(MOD_RACC, 5);
target:addMod(MOD_HPHEAL, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_VIT, -1);
target:delMod(MOD_AGI, 4);
target:delMod(MOD_RACC, 5);
target:delMod(MOD_HPHEAL, 3);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Selbina/npcs/Vuntar.lua | 17 | 3055 | -----------------------------------
-- Area: Selbina
-- NPC: Vuntar
-- Starts and Finishes Quest: Cargo (R)
-- @pos 7 -2 -15 248
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(OTHER_AREAS,CARGO) ~= QUEST_AVAILABLE) then
realday = tonumber(os.date("%j")); -- %M for next minute, %j for next real day
starttime = player:getVar("VuntarCanBuyItem_date");
if (realday ~= starttime) then
if (trade:hasItemQty(4529,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then
player:startEvent(0x0034,1); -- Can Buy rolanberry (881 ce)
elseif (trade:hasItemQty(4530,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then
player:startEvent(0x0034,2); -- Can Buy rolanberry (874 ce)
elseif (trade:hasItemQty(4531,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then
player:startEvent(0x0034,3); -- Can Buy rolanberry (864 ce)
end
else
player:startEvent(0x046e,4365); -- Can't buy rolanberrys
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getMainLvl() >= 20 and player:getQuestStatus(OTHER_AREAS,CARGO) == QUEST_AVAILABLE) then
player:startEvent(0x0032,4365); -- Start quest "Cargo"
elseif (player:getMainLvl() < 20) then
player:startEvent(0x0035); -- Dialog for low level or low fame
else
player:startEvent(0x0033,4365); -- During & after completed quest "Cargo"
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 == 0x0032) then
player:addQuest(OTHER_AREAS,CARGO);
elseif (csid == 0x0034) then
player:setVar("VuntarCanBuyItem_date", os.date("%j")); -- %M for next minute, %j for next real day
if (player:getQuestStatus(OTHER_AREAS,CARGO) == QUEST_ACCEPTED) then
player:completeQuest(OTHER_AREAS,CARGO);
player:addFame(OTHER_AREAS,30);
end
if (option == 1) then
player:addGil(800);
player:messageSpecial(GIL_OBTAINED,800);
player:tradeComplete();
elseif (option == 2) then
player:addGil(2000);
player:messageSpecial(GIL_OBTAINED,2000);
player:tradeComplete();
elseif (option == 3) then
player:addGil(3000);
player:messageSpecial(GIL_OBTAINED,3000);
player:tradeComplete();
end
end
end;
| gpl-3.0 |
drhelius/Gearboy | platforms/ios/dependencies/SDL-2.0.4-9174/premake/projects/testscale.lua | 7 | 1052 | -- Copyright (C) 1997-2014 Sam Lantinga <slouken@libsdl.org>
--
-- This software is provided 'as-is', without any express or implied
-- warranty. In no event will the authors be held liable for any damages
-- arising from the use of this software.
--
-- Permission is granted to anyone to use this software for any purpose,
-- including commercial applications, and to alter it and redistribute it
-- freely.
--
-- Meta-build system using premake created and maintained by
-- Benjamin Henning <b.henning@digipen.edu>
--[[
testscale.lua
This file defines the testscale test project. It depends on the SDL2main,
SDL2test, and SDL2 projects. It will not build on iOS or Cygwin.
]]
SDL_project "testscale"
SDL_kind "ConsoleApp"
SDL_notos "ios|cygwin"
SDL_language "C"
SDL_sourcedir "../test"
SDL_projectLocation "tests"
-- a list of items to copy from the sourcedir to the destination
SDL_copy { "sample.bmp", "icon.bmp" }
SDL_projectDependencies { "SDL2main", "SDL2test", "SDL2" }
SDL_files { "/testscale.*" }
| gpl-3.0 |
Ombridride/minetest-minetestforfun-server | mods/carts/init.lua | 7 | 11253 |
carts = {}
carts.modpath = minetest.get_modpath("carts")
-- Maximal speed of the cart in m/s
carts.speed_max = minetest.setting_get("movement_speed_walk")*3*0.9
-- Minimal speed of the cart on brake rail
carts.brake_speed_min = minetest.setting_get("movement_speed_walk")/2
-- Set to nil to disable punching the cart from inside (min = -1)
carts.punch_speed_min = 7
-- 1 disable mesecons / 0 enable mesecons
carts.mesecon_disabled = 1
if not carts.modpath then
error("\nWrong mod directory name! Please change it to 'carts'.\n" ..
"See also: http://dev.minetest.net/Installing_Mods")
end
function vector.floor(v)
return {
x = math.floor(v.x),
y = math.floor(v.y),
z = math.floor(v.z)
}
end
dofile(carts.modpath.."/functions.lua")
dofile(carts.modpath.."/rails.lua")
if not carts.mesecon_disabled and mesecon then
dofile(carts.modpath.."/detector.lua")
end
-- Support for non-default games
if not default.player_attached then
default.player_attached = {}
end
carts.cart = {
physical = false,
collisionbox = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5},
visual = "mesh",
mesh = "cart.x",
visual_size = {x=1, y=1},
textures = {"cart.png"},
driver = nil,
punched = false, -- used to re-send velocity and position
velocity = {x=0, y=0, z=0}, -- only used on punch
old_dir = {x=1, y=0, z=0}, -- random value to start the cart on punch
old_pos = nil,
old_switch = 0,
railtype = nil,
attached_items = {}
}
function carts.cart:on_rightclick(clicker)
if not clicker or not clicker:is_player() then
return
end
local player_name = clicker:get_player_name()
if self.driver and player_name == self.driver then
self.driver = nil
carts:manage_attachment(clicker, false)
self.object:setacceleration({x=0, y=0, z=0}) -- Stops the cart when we leave it
self.object:setvelocity({x=0, y=0, z=0})
elseif not self.driver then
self.driver = player_name
carts:manage_attachment(clicker, true, self.object)
end
end
function carts.cart:on_activate(staticdata, dtime_s)
self.object:set_armor_groups({immortal=1})
if string.sub(staticdata, 1, string.len("return")) ~= "return" then
return
end
local data = minetest.deserialize(staticdata)
if not data or type(data) ~= "table" then
return
end
self.railtype = data.railtype
if data.old_dir then
self.old_dir = data.old_dir
end
end
function carts.cart:get_staticdata()
return minetest.serialize({
railtype = self.railtype,
old_dir = self.old_dir
})
end
function carts.cart:on_punch(puncher, time_from_last_punch, tool_capabilities, direction)
local pos = self.object:getpos()
if not self.railtype then
local bar = vector.floor(vector.add(pos, 0.1))
local node = minetest.get_node(bar).name
self.railtype = minetest.get_item_group(node, "connect_to_raillike")
end
if not puncher or not puncher:is_player() then
local cart_dir = carts:get_rail_direction(pos, self.old_dir, nil, nil, self.railtype)
if vector.equals(cart_dir, {x=0, y=0, z=0}) then
return
end
self.velocity = vector.multiply(cart_dir, 3)
self.old_pos = nil
self.punched = true
return
end
if puncher:get_player_control().sneak then
-- Pick up cart: Drop all attachments
if self.driver then
if self.old_pos then
self.object:setpos(self.old_pos)
end
local player = minetest.get_player_by_name(self.driver)
carts:manage_attachment(player, false)
end
for _,obj_ in ipairs(self.attached_items) do
if obj_ then
obj_:set_detach()
end
end
local leftover = puncher:get_inventory():add_item("main", "carts:cart")
if not leftover:is_empty() then
minetest.add_item(self.object:getpos(), leftover)
end
self.object:remove()
return
end
local vel = self.object:getvelocity()
if puncher:get_player_name() == self.driver then
if math.abs(vel.x + vel.z) > carts.punch_speed_min then
return
end
--end --Only the driver can punch
local punch_dir = carts:velocity_to_dir(puncher:get_look_dir())
punch_dir.y = 0
local cart_dir = carts:get_rail_direction(pos, punch_dir, nil, nil, self.railtype)
if vector.equals(cart_dir, {x=0, y=0, z=0}) then
return
end
local punch_interval = 1
if tool_capabilities and tool_capabilities.full_punch_interval then
punch_interval = tool_capabilities.full_punch_interval
end
time_from_last_punch = math.min(time_from_last_punch or punch_interval, punch_interval)
local f = 3 * (time_from_last_punch / punch_interval)
self.velocity = vector.multiply(cart_dir, f)
self.old_dir = cart_dir
self.old_pos = nil
self.punched = true
end
end
function carts.cart:on_step(dtime)
local vel = self.object:getvelocity()
local update = {}
if self.punched then
vel = vector.add(vel, self.velocity)
self.object:setvelocity(vel)
self.old_dir.y = 0
elseif vector.equals(vel, {x=0, y=0, z=0}) then
return
end
-- dir: New moving direction of the cart
-- last_switch: Currently pressed L/R key, used to ignore the key on the next rail node
local dir, last_switch
local pos = self.object:getpos()
local is_slow = ((vel.x ~= 0 and math.abs(vel.x) <= carts.brake_speed_min) or
(vel.y ~= 0 and math.abs(vel.y) <= carts.brake_speed_min) or
(vel.z ~= 0 and math.abs(vel.z) <= carts.brake_speed_min)) and
string.match(minetest.get_node(pos).name, "brake")
if self.old_pos and not self.punched then
local flo_pos = vector.round(pos)
local flo_old = vector.round(self.old_pos)
if vector.equals(flo_pos, flo_old) and not is_slow then -- Do not check one node multiple times (but check if low speed)
return
end
end
local ctrl, player
-- Get player controls
if self.driver then
player = minetest.get_player_by_name(self.driver)
if player then
ctrl = player:get_player_control()
end
end
if self.old_pos then
-- Detection for "skipping" nodes
local expected_pos = vector.add(self.old_pos, self.old_dir)
local found_path = carts:pathfinder(
pos, expected_pos, self.old_dir, ctrl, self.old_switch, self.railtype
)
if not found_path and not is_slow then
-- No rail found: reset back to the expected position
pos = expected_pos
update.pos = true
end
end
local cart_dir = carts:velocity_to_dir(vel)
local max_vel = carts.speed_max
if not dir then
dir, last_switch = carts:get_rail_direction(
pos, cart_dir, ctrl, self.old_switch, self.railtype
)
end
local new_acc = {x=0, y=0, z=0}
local speed_mod = 0
if vector.equals(dir, {x=0, y=0, z=0}) then
vel = {x=0, y=0, z=0}
pos = vector.round(pos)
update.pos = true
update.vel = true
else
-- If the direction changed
if dir.x ~= 0 and self.old_dir.z ~= 0 then
vel.x = dir.x * math.abs(vel.z)
vel.z = 0
pos.z = math.floor(pos.z + 0.5)
update.pos = true
end
if dir.z ~= 0 and self.old_dir.x ~= 0 then
vel.z = dir.z * math.abs(vel.x)
vel.x = 0
pos.x = math.floor(pos.x + 0.5)
update.pos = true
end
-- Up, down?
if dir.y ~= self.old_dir.y then
vel.y = dir.y * math.abs(vel.x + vel.z)
pos = vector.round(pos)
update.pos = true
end
-- Slow down or speed up in slopes..
local acc = dir.y * -1.8
-- MFF : Some rails have bad acceleration property, reinit them !
-- this code would be commented when all rails will be corrected
local rail = minetest.get_node(pos)
if string.match(rail.name, "power")
then minetest.get_meta(pos):set_string("cart_acceleration", "1")
elseif string.match(rail.name, "brake") then minetest.get_meta(pos):set_string("cart_acceleration", "-1")
else minetest.get_meta(pos):set_string("cart_acceleration", "0")
end
-- Change acceleration by rail (power/brake)
local speed_mod_string = minetest.get_meta(pos):get_string("cart_acceleration")
if speed_mod_string and speed_mod_string ~= ""
then speed_mod = tonumber(speed_mod_string)
else speed_mod = 0
end
if speed_mod > 0 then speed_mod = 2
elseif speed_mod < 0 then speed_mod = -2
else speed_mod = 0
end
--[[if speed_mod_string == "halt" then --stop rail, not used in MFF
vel = {x=0, y=0, z=0}
acc = 0
pos = vector.round(pos)
update.pos = true
update.vel = true
else--]]if speed_mod and speed_mod ~= 0 then
acc = acc + (speed_mod * 10)
else
--acc = acc - 0.4 --No friction (to be set as an option)
-- Handbrake
if ctrl and ctrl.down then
acc = acc - 1.2
end
end
if self.old_dir.y == 0 and not self.punched then
-- Stop the cart swing between two rail parts (handbrake)
if vector.equals(vector.multiply(self.old_dir, -1), dir) then
vel = {x=0, y=0, z=0}
acc = 0
if self.old_pos then
pos = vector.new(self.old_pos)
update.pos = true
end
dir = vector.new(self.old_dir)
update.vel = true
end
end
new_acc = vector.multiply(dir, acc)
end
if not carts.mesecon_disabled and mesecon then
carts:signal_detector_rail(vector.round(pos))
end
-- Limits
for _,v in ipairs({"x","y","z"}) do
if speed_mod > 0 and math.abs(vel[v]) > max_vel then
vel[v] = carts:get_sign(vel[v]) * max_vel
new_acc[v] = 0
update.vel = true
elseif speed_mod < 0 and vel[v] ~= 0 and math.abs(vel[v]) <= carts.brake_speed_min then
vel[v] = carts:get_sign(vel[v]) * carts.brake_speed_min
new_acc[v] = 0
update.vel = true
end
end
self.object:setacceleration(new_acc)
self.old_pos = vector.new(pos)
if not vector.equals(dir, {x=0, y=0, z=0}) then
self.old_dir = vector.new(dir)
end
self.old_switch = last_switch
if self.punched then
-- Collect dropped items
for _,obj_ in ipairs(minetest.get_objects_inside_radius(pos, 1)) do
if not obj_:is_player() and
obj_:get_luaentity() and
not obj_:get_luaentity().physical_state and
obj_:get_luaentity().name == "__builtin:item" then
obj_:set_attach(self.object, "", {x=0, y=0, z=0}, {x=0, y=0, z=0})
self.attached_items[#self.attached_items + 1] = obj_
end
end
self.punched = false
update.vel = true -- update player animation
end
if not (update.vel or update.pos) then
return
end
local yaw = 0
if self.old_dir.x < 0 then
yaw = 0.5
elseif self.old_dir.x > 0 then
yaw = 1.5
elseif self.old_dir.z < 0 then
yaw = 1
end
self.object:setyaw(yaw * math.pi)
local anim = {x=0, y=0}
if dir.y == -1 then
anim = {x=1, y=1}
elseif dir.y == 1 then
anim = {x=2, y=2}
end
self.object:set_animation(anim, 1, 0)
self.object:setvelocity(vel)
if update.pos then
self.object:setpos(pos)
end
update = nil
end
minetest.register_entity(":carts:cart", carts.cart)
minetest.register_craftitem(":carts:cart", {
description = "Cart (Sneak+Click to pick up)",
inventory_image = minetest.inventorycube("cart_top.png", "cart_side.png", "cart_side.png"),
wield_image = "cart_side.png",
on_place = function(itemstack, placer, pointed_thing)
if not pointed_thing.type == "node" then
return
end
if carts:is_rail(pointed_thing.under) then
minetest.add_entity(pointed_thing.under, "carts:cart")
elseif carts:is_rail(pointed_thing.above) then
minetest.add_entity(pointed_thing.above, "carts:cart")
else return end
itemstack:take_item()
return itemstack
end,
})
minetest.register_craft({
output = "carts:cart",
recipe = {
{"default:steel_ingot", "", "default:steel_ingot"},
{"default:steel_ingot", "default:steel_ingot", "default:steel_ingot"},
},
})
| unlicense |
jshackley/darkstar | scripts/zones/Davoi/npcs/_45i.lua | 19 | 2046 | -----------------------------------
-- Area: Davoi
-- NPC: Wailing Pond
-- Used In Quest: Whence Blows the Wind
-- @pos 380 0.1 -181 149
-----------------------------------
package.loaded["scripts/zones/Davoi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Davoi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0034);
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 == 0x0034 and player:getVar("miniQuestForORB_CS") == 1) then
local c = player:getVar("countRedPoolForORB");
if (c == 0) then
player:setVar("countRedPoolForORB", c + 2);
player:delKeyItem(WHITE_ORB);
player:addKeyItem(PINK_ORB);
player:messageSpecial(KEYITEM_OBTAINED, PINK_ORB);
elseif (c == 1 or c == 4 or c == 8) then
player:setVar("countRedPoolForORB", c + 2);
player:delKeyItem(PINK_ORB);
player:addKeyItem(RED_ORB);
player:messageSpecial(KEYITEM_OBTAINED, RED_ORB);
elseif (c == 5 or c == 9 or c == 12) then
player:setVar("countRedPoolForORB", c + 2);
player:delKeyItem(RED_ORB);
player:addKeyItem(BLOOD_ORB);
player:messageSpecial(KEYITEM_OBTAINED, BLOOD_ORB);
elseif (c == 13) then
player:setVar("countRedPoolForORB", c + 2);
player:delKeyItem(BLOOD_ORB);
player:addKeyItem(CURSED_ORB);
player:messageSpecial(KEYITEM_OBTAINED, CURSED_ORB);
player:addStatusEffect(EFFECT_PLAGUE,0,0,900);
end
end
end; | gpl-3.0 |
Sourceless/bullet-hell-game | bullet-hell/class/statemanager.lua | 1 | 1874 | -- StateManager
--
-- Manage gamestates, and maintain a stack of said states.
-- Run the state at the top of the stack, and draw any visible states (this
-- allows for transparency on pause screens, etc)
package.path = ";../?.lua"
class = require "lib/30log/30log"
-- class boilerplate
StateManager = class ( )
StateManager.__init = { stack = {}, canvas = love.graphics.newCanvas() }
function StateManager:any()
if #self.stack > 0 then
return true
else
return false
end
end
function StateManager:top()
if self:any() then
return self.stack[#self.stack]
else
return nil
end
end
function StateManager:push_state(state)
table.insert(self.stack, state)
state:init()
end
function StateManager:pop_state()
if self:any() then
table.remove(self.stack)
end
end
function StateManager:tick()
-- Perform a tick on the top state.
--
-- Virtually every system except things involving
-- graphics will happen here. Graphics are only
-- special because states can be stacked, and one drawn
-- underneath another.
if self:any() then
self:top():tick()
end
end
function StateManager:draw()
-- Do a draw on each of the visible states
self.canvas:clear()
-- Kind of an odd way to do it, but this sets
-- this local canvas as the one that's drawn to
-- by default. All this means is that any draw calls
-- made inside states end up here before being rendered,
-- which means they get stacked properly.
love.graphics.setCanvas(self.canvas)
if self:any() then
-- iterate from bottom to top, drawing visible states onto the canvas
for _, state in ipairs(self.stack) do
if state.visible then state:draw() end
end
end
love.graphics.setCanvas()
return self.canvas
end
return StateManager
| mit |
yagop/telegram-bot | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
birkett/MCServer | Server/Plugins/APIDump/Hooks/OnTakeDamage.lua | 44 | 1214 | return
{
HOOK_TAKE_DAMAGE =
{
CalledWhen = "An {{cEntity|entity}} is taking any kind of damage",
DefaultFnName = "OnTakeDamage", -- also used as pagename
Desc = [[
This hook is called when any {{cEntity}} descendant, such as a {{cPlayer|player}} or a
{{cMonster|mob}}, takes any kind of damage. The plugins may modify the amount of damage or effects
with this hook by editting the {{TakeDamageInfo}} object passed.</p>
<p>
This hook is called after the final damage is calculated, including all the possible weapon
{{cEnchantments|enchantments}}, armor protection and potion effects.
]],
Params =
{
{ Name = "Receiver", Type = "{{cEntity}} descendant", Notes = "The entity taking damage" },
{ Name = "TDI", Type = "{{TakeDamageInfo}}", Notes = "The damage type, cause and effects. Plugins may modify this object to alter the final damage applied." },
},
Returns = [[
If the function returns false or no value, other plugins' callbacks are called and then the server
applies the final values from the TDI object to Receiver. If the function returns true, no other
callbacks are called, and no damage nor effects are applied.
]],
}, -- HOOK_TAKE_DAMAGE
}
| apache-2.0 |
jshackley/darkstar | scripts/zones/Crawlers_Nest/TextIDs.lua | 22 | 1594 | --- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6569; -- You cannot obtain the item <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6574; -- Obtained: <item>.
GIL_OBTAINED = 6575; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6577; -- Obtained key item: <keyitem>.
-- Treasure Coffer/Chest Dialog
CHEST_UNLOCKED = 7247; -- You unlock the chest!
CHEST_FAIL = 7248; -- Fails to open the chest.
CHEST_TRAP = 7249; -- The chest was trapped!
CHEST_WEAK = 7250; -- You cannot open the chest when you are in a weakened state.
CHEST_MIMIC = 7251; -- The chest was a mimic!
CHEST_MOOGLE = 7252; -- You cannot open the chest while participating in the moogle event.
CHEST_ILLUSION = 7253; -- The chest was but an illusion...
CHEST_LOCKED = 7254; -- The chest appears to be locked.
-- Quest Dialog
SENSE_OF_FOREBODING = 6589; -- You are suddenly overcome with a sense of foreboding...
NOTHING_WILL_HAPPEN_YET = 7261; -- It seems that nothing will happen yet.
NOTHING_SEEMS_TO_HAPPEN = 7262; -- Nothing seems to happen.
SOMEONE_HAS_BEEN_DIGGING_HERE = 7255; -- Someone has been digging here.
EQUIPMENT_COMPLETELY_PURIFIED = 7256; -- Your equipment has not been completely purified.
YOU_BURY_THE = 7258; -- You bury the
-- conquest Base
CONQUEST_BASE = 0;
-- Strange Apparatus
DEVICE_NOT_WORKING = 173; -- The device is not working.
SYS_OVERLOAD = 182; -- arning! Sys...verload! Enterin...fety mode. ID eras...d
YOU_LOST_THE = 187; -- You lost the #.
| gpl-3.0 |
jshackley/darkstar | scripts/globals/spells/bluemagic/hecatomb_wave.lua | 18 | 1947 | -----------------------------------------
-- Spell: Hecatomb Wave
-- Deals wind damage to enemies within a fan-shaped area originating from the caster. Additional effect: Blindness
-- Spell cost: 116 MP
-- Monster Type: Demons
-- Spell Type: Magical (Wind)
-- Blue Magic Points: 3
-- Stat Bonus: AGI+1
-- Level: 54
-- Casting Time: 5.25 seconds
-- Recast Time: 33.75 seconds
-- Magic Bursts on: Detonation, Fragmentation, Light
-- Combos: Max MP Boost
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT) - target:getStat(MOD_INT),BLUE_SKILL,1.0);
local params = {};
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.multiplier = 1.375;
params.tMultiplier = 1.0;
params.duppercap = 54;
params.str_wsc = 0.0;
params.dex_wsc = 0.0;
params.vit_wsc = 0.0;
params.agi_wsc = 0.0;
params.int_wsc = 0.0;
params.mnd_wsc = 0.3;
params.chr_wsc = 0.0;
damage = BlueMagicalSpell(caster, target, spell, params, MND_BASED);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
if (damage > 0 and resist > 0.125) then
local typeEffect = EFFECT_BLINDNESS;
target:delStatusEffect(typeEffect);
target:addStatusEffect(typeEffect,5,0,getBlueEffectDuration(caster,resist,typeEffect));
end
return damage;
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/The_Garden_of_RuHmet/npcs/_0zs.lua | 17 | 1272 | -----------------------------------
-- Area: The_Garden_of_RuHmet
-- NPC: _0zs
-----------------------------------
package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/The_Garden_of_RuHmet/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
return 1;
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasCompletedMission(COP,WHEN_ANGELS_FALL)) then
player:startEvent(0x0070);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("onUpdate CSID: %u",csid);
--printf("onUpdate RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if (csid== 0x0070 and option == 1) then
player:setPos(-20,0,-355,192,34);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/weaponskills/shockwave.lua | 29 | 1477 | -----------------------------------
-- Shockwave
-- Great Sword weapon skill
-- Skill level: 150
-- Delivers an area of effect attack. Sleeps enemies. Duration of effect varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Aqua Gorget.
-- Aligned with the Aqua Belt.
-- Element: None
-- Modifiers: STR:30% ; MND:30%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.3; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
if (damage > 0 and target:hasStatusEffect(EFFECT_SLEEP_I) == false) then
local tp = player:getTP();
local duration = (tp/100 * 60);
target:addStatusEffect(EFFECT_SLEEP_I, 1, 0, duration);
end
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end | gpl-3.0 |
jshackley/darkstar | scripts/globals/weaponskills/torcleaver.lua | 30 | 1559 | -----------------------------------
-- Torcleaver
-- Skill Level: N/A
-- Description: Deals triple damage. Damage varies with TP. Caladbolg: Aftermath.
-- Available only when equipped with Caladbolg (85)/(90)/(95) or Espafut +1/+2/+3.
-- Aligned with the Light Gorget, Aqua Gorget & Snow Gorget.
-- Aligned with the Light Belt, Aqua Belt & Snow Belt.
-- Element: None
-- Skillchain Properties: Light/Distortion
-- Modifiers: VIT:60%
-- Damage Multipliers by TP:
-- 100%TP 200%TP 300%TP
-- 4.75 5.75 6.5
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 4.75; params.ftp200 = 5.75; params.ftp300 = 6.5;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.6; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.00; params.crit200 = 0.00; params.crit300 = 0.00;
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 = 4.75; params.ftp200 = 7.5; params.ftp300 = 9.6875;
params.vit_wsc = 0.8;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end | gpl-3.0 |
Victek/wrt1900ac-aa | veriksystems/luci-0.11/modules/admin-mini/luasrc/model/cbi/mini/passwd.lua | 14 | 1177 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: passwd.lua 5448 2009-10-31 15:54:11Z jow $
]]--
f = SimpleForm("password", translate("Admin Password"), translate("Change the password of the system administrator (User <code>root</code>)"))
pw1 = f:field(Value, "pw1", translate("Password"))
pw1.password = true
pw1.rmempty = false
pw2 = f:field(Value, "pw2", translate("Confirmation"))
pw2.password = true
pw2.rmempty = false
function pw2.validate(self, value, section)
return pw1:formvalue(section) == value and value
end
function f.handle(self, state, data)
if state == FORM_VALID then
local stat = luci.sys.user.setpasswd("root", data.pw1) == 0
if stat then
f.message = translate("Password successfully changed")
else
f.errmessage = translate("Unknown Error")
end
data.pw1 = nil
data.pw2 = nil
end
return true
end
return f | gpl-2.0 |
jshackley/darkstar | scripts/zones/Davoi/npcs/Sedal-Godjal.lua | 19 | 3630 | -----------------------------------
-- Area: Davoi
-- NPC: Sedal-Godjal
-- Mini Quest used in : Whence Blows the Wind
-- @pos 185 -3 -116 149
-----------------------------------
package.loaded["scripts/zones/Davoi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Davoi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local CurrentMission = player:getCurrentMission(WINDURST);
local MissionStatus = player:getVar("MissionStatus");
if (trade:hasItemQty(17437,1)) then
if (CurrentMission == VAIN and MissionStatus == 3 and player:hasKeyItem(MAGIC_DRAINED_STAR_SEEKER) == true) then
player:startEvent(0x0078);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local CurrentMission = player:getCurrentMission(WINDURST);
local MissionStatus = player:getVar("MissionStatus");
if (player:getCurrentMission(WINDURST) == THE_JESTER_WHO_D_BE_KING and player:getVar("MissionStatus") == 1) then
player:startEvent(0x007A,0,276);
elseif (CurrentMission == VAIN and MissionStatus >= 2) then -- wiki says it doesnt matter whether you get cs or kill first
if (player:hasKeyItem(STAR_SEEKER) == true) then
player:startEvent(0x0076,0,17437,STAR_SEEKER);
elseif (player:hasKeyItem(MAGIC_DRAINED_STAR_SEEKER) and MissionStatus == 4) then
player:startEvent(0x0079);
else
player:startEvent(0x0077,0,17437);
end
elseif (player:hasKeyItem(CRIMSON_ORB) == false) then
local miniQuestForORB_CS = player:getVar("miniQuestForORB_CS");
local countRedPoolForORB = player:getVar("countRedPoolForORB");
if (miniQuestForORB_CS == 0) then
player:startEvent(0x0018); --
elseif (miniQuestForORB_CS == 99) then
player:startEvent(0x0016); -- Start mini quest
elseif (miniQuestForORB_CS == 1 and countRedPoolForORB ~= 15) then
player:startEvent(0x0015); -- During mini quest
elseif (miniQuestForORB_CS == 1 and countRedPoolForORB == 15) then
player:startEvent(0x0019,0,0,0,CRIMSON_ORB); -- Finish mini quest
end
else
player:startEvent(0x0018); -- Standard dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0016 and option == 1) then
player:setVar("miniQuestForORB_CS",1);
player:addKeyItem(WHITE_ORB);
player:messageSpecial(KEYITEM_OBTAINED, WHITE_ORB);
elseif (csid == 0x0019) then
player:setVar("miniQuestForORB_CS",0);
player:setVar("countRedPoolForORB",0);
player:delKeyItem(CURSED_ORB);
player:addKeyItem(CRIMSON_ORB);
player:messageSpecial(KEYITEM_OBTAINED, CRIMSON_ORB);
elseif (csid == 0x0076) then
player:delKeyItem(STAR_SEEKER);
player:addKeyItem(MAGIC_DRAINED_STAR_SEEKER);
player:setVar("MissionStatus",3);
elseif (csid == 0x0078) then
player:tradeComplete();
player:setVar("MissionStatus",4);
elseif (csid == 0x007A) then
player:addKeyItem(AURASTERY_RING);
player:messageSpecial(KEYITEM_OBTAINED,AURASTERY_RING);
if (player:hasKeyItem(OPTISTERY_RING) and player:hasKeyItem(RHINOSTERY_RING)) then
player:setVar("MissionStatus",2)
end
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/pathfind.lua | 18 | 2553 | -- Util methods for pathfinding
pathfind = {};
PATHFLAG_NONE = 0
PATHFLAG_RUN = 1
PATHFLAG_WALLHACK = 2
PATHFLAG_REVERSE = 4
-- returns the point at the given index
function pathfind.get(points, index)
local pos = {};
if (index < 0) then
index = (#points + index - 2) / 3;
end
pos[1] = points[index*3-2];
pos[2] = points[index*3-1];
pos[3] = points[index*3];
return pos;
end;
function pathfind.length(points)
return #points / 3;
end
function pathfind.first(points)
return pathfind.get(points, 1);
end;
function pathfind.equal(point1, point2)
return point1[1] == point2[1] and point1[2] == point2[2] and point1[3] == point2[3];
end;
-- returns the last point
function pathfind.last(points)
local length = #points;
return pathfind.get(points, length/3);
end;
-- returns a random point from given point array
function pathfind.random(points)
local length = #points;
return pathfind.get(points, math.random(1, length));
end;
-- returns the start path without the first element
function pathfind.fromStart(points, start)
start = start or 1;
local t2 = {}
local maxLength = 50;
local length = pathfind.length(points);
local count = 1;
local pos = start + 1;
local index = 1;
while pos <= length and count <= maxLength do
local pt = pathfind.get(points, pos);
t2[index] = pt[1];
t2[index+1] = pt[2];
t2[index+2] = pt[3];
pos = pos + 1;
count = count + 1;
index = index + 3;
end
return t2
end;
-- reverses the array and removes the first element
function pathfind.fromEnd(points, start)
start = start or 1
local t2 = {}
-- do not add the last element
local length = #points / 3;
start = length - start;
local index = 1;
for i=start,1,-1 do
local pt = pathfind.get(points, i);
t2[index] = pt[1]
t2[index+1] = pt[2]
t2[index+2] = pt[3]
index = index + 3
if (i > 50) then
break;
end
end
return t2
end;
-- continusly runs the path
function pathfind.patrol(npc, points, flags)
if (npc:atPoint(pathfind.first(points)) or npc:atPoint(pathfind.last(points))) then
npc:pathThrough(pathfind.fromStart(points), flags);
else
local length = #points / 3;
local currentLength = 0;
local i = 51;
-- i'm some where inbetween
while(i <= length) do
if (npc:atPoint(pathfind.get(points, i))) then
npc:pathThrough(pathfind.fromStart(points, i), flags);
break;
end
i = i + 50;
end
end
end; | gpl-3.0 |
mohammadclashclash/sina20160 | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
jshackley/darkstar | scripts/zones/Bhaflau_Thickets/mobs/Colibri.lua | 8 | 1757 | -----------------------------------
-- Area: Bhaflau Thickets
-- MOB: Colibri
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob, target)
local delay = mob:getLocalVar("delay");
local LastCast = mob:getLocalVar("LAST_CAST");
local spell = mob:getLocalVar("COPY_SPELL");
if (mob:AnimationSub() == 1) then
if (mob:getBattleTime() - LastCast > 30) then
mob:setLocalVar("COPY_SPELL", 0);
mob:setLocalVar("delay", 0);
mob:AnimationSub(0);
end
if (spell > 0 and mob:hasStatusEffect(EFFECT_SILENCE) == false) then
if (delay >= 3) then
mob:castSpell(spell);
mob:setLocalVar("COPY_SPELL", 0);
mob:setLocalVar("delay", 0);
mob:AnimationSub(0);
else
mob:setLocalVar("delay", delay+1);
end
end
end
end;
-----------------------------------
-- onMagicHit
-----------------------------------
function onMagicHit(caster, target, spell)
if (spell:tookEffect() and (caster:isPC() or caster:isPet()) and spell:getSpellGroup() ~= SPELLGROUP_BLUE ) then
target:setLocalVar("COPY_SPELL", spell:getID());
target:setLocalVar("LAST_CAST", target:getBattleTime());
target:AnimationSub(1);
-- elseif (spell:isHeal() and caster:isPC()) then
-- Todo: handle curing party members in response to being cured.
end
return 1;
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer,ally)
end; | gpl-3.0 |
Victek/wrt1900ac-aa | veriksystems/luci-0.11/applications/luci-freifunk-widgets/luasrc/model/cbi/freifunk/widgets/widgets_overview.lua | 78 | 2041 | --[[
LuCI - Lua Configuration Interface
Copyright 2012 Manuel Munz <freifunk at somakoma dot de>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local uci = require "luci.model.uci".cursor()
local fs = require "luci.fs"
local utl = require "luci.util"
m = Map("freifunk-widgets", translate("Widgets"),
translate("Configure installed widgets."))
wdg = m:section(TypedSection, "widget", translate("Widgets"))
wdg.addremove = true
wdg.extedit = luci.dispatcher.build_url("admin/freifunk/widgets/widget/%s")
wdg.template = "cbi/tblsection"
wdg.sortable = true
--[[
function wdg.create(...)
local sid = TypedSection.create(...)
luci.http.redirect(wdg.extedit % sid)
end
]]--
local en = wdg:option(Flag, "enabled", translate("Enable"))
en.rmempty = false
--en.default = "0"
function en.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "0"
end
local tmpl = wdg:option(ListValue, "template", translate("Template"))
for k, v in ipairs(fs.dir('/usr/lib/lua/luci/view/freifunk/widgets/')) do
if v ~= "." and v ~= ".." then
tmpl:value(v)
end
end
local title = wdg:option(Value, "title", translate("Title"))
title.rmempty = true
local width = wdg:option(Value, "width", translate("Width"))
width.rmempty = true
local height = wdg:option(Value, "height", translate("Height"))
height.rmempty = true
local pr = wdg:option(Value, "paddingright", translate("Padding right"))
pr.rmempty = true
function m.on_commit(self)
-- clean custom text files whose config has been deleted
local dir = "/usr/share/customtext/"
local active = {}
uci:foreach("freifunk-widgets", "widget", function(s)
if s["template"] == "html" then
table.insert(active, s[".name"])
end
end )
for k, v in ipairs(fs.dir(dir)) do
filename = string.gsub(v, ".html", "")
if not utl.contains(active, filename) then
fs.unlink(dir .. v)
end
end
end
return m
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Windurst_Woods/npcs/HomePoint#4.lua | 17 | 1253 | -----------------------------------
-- Area: Windurst Woods
-- NPC: HomePoint#4
-- @pos 74 -7.5 -139 241
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Windurst_Woods/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21ff, 28);
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 == 0x21ff) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/items/steamed_crab.lua | 35 | 1308 | -----------------------------------------
-- ID: 4342
-- Item: steamed_crab
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Vitality 3
-- Defense % 27
-- Defense Cap 55
-----------------------------------------
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,4342);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_VIT, 3);
target:addMod(MOD_FOOD_DEFP, 27);
target:addMod(MOD_FOOD_DEF_CAP, 55);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_VIT, 3);
target:delMod(MOD_FOOD_DEFP, 27);
target:delMod(MOD_FOOD_DEF_CAP, 55);
end;
| gpl-3.0 |
bsmr-games/OpenRA | mods/d2k/maps/atreides-01a/atreides01a.lua | 18 | 4859 |
HarkonnenReinforcements = { }
HarkonnenReinforcements["Easy"] =
{
{ "light_inf", "light_inf" }
}
HarkonnenReinforcements["Normal"] =
{
{ "light_inf", "light_inf" },
{ "light_inf", "light_inf", "light_inf" },
{ "light_inf", "trike" },
}
HarkonnenReinforcements["Hard"] =
{
{ "light_inf", "light_inf" },
{ "trike", "trike" },
{ "light_inf", "light_inf", "light_inf" },
{ "light_inf", "trike" },
{ "trike", "trike" }
}
HarkonnenEntryWaypoints = { HarkonnenWaypoint1.Location, HarkonnenWaypoint2.Location, HarkonnenWaypoint3.Location, HarkonnenWaypoint4.Location }
HarkonnenAttackDelay = DateTime.Seconds(30)
HarkonnenAttackWaves = { }
HarkonnenAttackWaves["Easy"] = 1
HarkonnenAttackWaves["Normal"] = 5
HarkonnenAttackWaves["Hard"] = 12
ToHarvest = { }
ToHarvest["Easy"] = 2500
ToHarvest["Normal"] = 3000
ToHarvest["Hard"] = 3500
AtreidesReinforcements = { "light_inf", "light_inf", "light_inf" }
AtreidesEntryPath = { AtreidesWaypoint.Location, AtreidesRally.Location }
Messages =
{
"Build a concrete foundation before placing your buildings.",
"Build a Wind Trap for power.",
"Build a Refinery to collect Spice.",
"Build a Silo to store additional Spice."
}
IdleHunt = function(actor)
if not actor.IsDead then
Trigger.OnIdle(actor, actor.Hunt)
end
end
Tick = function()
if HarkonnenArrived and harkonnen.HasNoRequiredUnits() then
player.MarkCompletedObjective(KillHarkonnen)
end
if player.Resources > ToHarvest[Map.Difficulty] - 1 then
player.MarkCompletedObjective(GatherSpice)
end
-- player has no Wind Trap
if (player.PowerProvided <= 20 or player.PowerState ~= "Normal") and DateTime.GameTime % DateTime.Seconds(32) == 0 then
HasPower = false
Media.DisplayMessage(Messages[2], "Mentat")
else
HasPower = true
end
-- player has no Refinery and no Silos
if HasPower and player.ResourceCapacity == 0 and DateTime.GameTime % DateTime.Seconds(32) == 0 then
Media.DisplayMessage(Messages[3], "Mentat")
end
if HasPower and player.Resources > player.ResourceCapacity * 0.8 and DateTime.GameTime % DateTime.Seconds(32) == 0 then
Media.DisplayMessage(Messages[4], "Mentat")
end
UserInterface.SetMissionText("Harvested resources: " .. player.Resources .. "/" .. ToHarvest[Map.Difficulty], player.Color)
end
WorldLoaded = function()
player = Player.GetPlayer("Atreides")
harkonnen = Player.GetPlayer("Harkonnen")
InitObjectives()
Trigger.OnRemovedFromWorld(AtreidesConyard, function()
local refs = Map.ActorsInBox(Map.TopLeft, Map.BottomRight, function(actor)
return actor.Type == "refinery"
end)
if #refs == 0 then
harkonnen.MarkCompletedObjective(KillAtreides)
else
Trigger.OnAllRemovedFromWorld(refs, function()
harkonnen.MarkCompletedObjective(KillAtreides)
end)
end
end)
Media.DisplayMessage(Messages[1], "Mentat")
Trigger.AfterDelay(DateTime.Seconds(25), function()
Media.PlaySpeechNotification(player, "Reinforce")
Reinforcements.Reinforce(player, AtreidesReinforcements, AtreidesEntryPath)
end)
WavesLeft = HarkonnenAttackWaves[Map.Difficulty]
SendReinforcements()
end
SendReinforcements = function()
local units = HarkonnenReinforcements[Map.Difficulty]
local delay = Utils.RandomInteger(HarkonnenAttackDelay - DateTime.Seconds(2), HarkonnenAttackDelay)
HarkonnenAttackDelay = HarkonnenAttackDelay - (#units * 3 - 3 - WavesLeft) * DateTime.Seconds(1)
if HarkonnenAttackDelay < 0 then HarkonnenAttackDelay = 0 end
Trigger.AfterDelay(delay, function()
Reinforcements.Reinforce(harkonnen, Utils.Random(units), { Utils.Random(HarkonnenEntryWaypoints) }, 10, IdleHunt)
WavesLeft = WavesLeft - 1
if WavesLeft == 0 then
Trigger.AfterDelay(DateTime.Seconds(1), function() HarkonnenArrived = true end)
else
SendReinforcements()
end
end)
end
InitObjectives = function()
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
KillAtreides = harkonnen.AddPrimaryObjective("Kill all Atreides units.")
GatherSpice = player.AddPrimaryObjective("Harvest " .. tostring(ToHarvest[Map.Difficulty]) .. " Solaris worth of Spice.")
KillHarkonnen = player.AddSecondaryObjective("Eliminate all Harkonnen units and reinforcements\nin the area.")
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerLost(player, function()
Trigger.AfterDelay(DateTime.Seconds(1), function()
Media.PlaySpeechNotification(player, "Lose")
end)
end)
Trigger.OnPlayerWon(player, function()
Trigger.AfterDelay(DateTime.Seconds(1), function()
Media.PlaySpeechNotification(player, "Win")
end)
end)
end
| gpl-3.0 |
shagu/pfQuest | db/koKR/zones.lua | 1 | 33951 | pfDB["zones"]["koKR"] = {
[1] = "Dun Morogh",
[2] = "기나긴 해안",
[3] = "Badlands",
[4] = "Blasted Lands",
[7] = "검은바다 만",
[8] = "Swamp of Sorrows",
[9] = "노스샤이어 계곡",
[10] = "Duskwood",
[11] = "Wetlands",
[12] = "Elwynn Forest",
[13] = "세계수",
[14] = "Durotar",
[15] = "Dustwallow Marsh",
[16] = "Azshara",
[17] = "The Barrens",
[18] = "수정 호수",
[19] = "줄구룹",
[20] = "문브룩",
[21] = "Kul Tiras",
[22] = "Programmer Isle",
[23] = "노스샤이어 강",
[24] = "노스샤이어 수도원",
[25] = "Blackrock Mountain",
[26] = "등대",
[28] = "Western Plaguelands",
[30] = "Nine",
[32] = "묘지",
[33] = "Stranglethorn Vale",
[34] = "메아리 광산",
[35] = "무법항",
[36] = "Alterac Mountains",
[37] = "나즈페리티 호수",
[38] = "Loch Modan",
[40] = "Westfall",
[41] = "Deadwind Pass",
[42] = "다크샤이어",
[43] = "거친 해안",
[44] = "Redridge Mountains",
[45] = "Arathi Highlands",
[46] = "Burning Steppes",
[47] = "The Hinterlands",
[49] = "사자의 구멍",
[51] = "Searing Gorge",
[53] = "도둑 야영지",
[54] = "석영 광산",
[55] = "영웅의 계곡",
[56] = "수호영웅의 안식처",
[57] = "개미굴 광산",
[59] = "노스샤이어 포도밭",
[60] = "숲 가장자리",
[61] = "천둥 폭포",
[62] = "브랙웰 호박밭",
[63] = "스톤필드 농장",
[64] = "맥클루어 포도밭",
[65] = "*** 야외 던전 ***",
[66] = "*** 야외 던전 ***",
[67] = "*** 야외 던전 ***",
[68] = "영원의 호수",
[69] = "레이크샤이어",
[70] = "돌망루 요새",
[71] = "함락된 돌망루 요새",
[72] = "어둠의 문",
[73] = "타락의 흉터",
[74] = "눈물의 연못",
[75] = "스토나드",
[76] = "드레노어 성역",
[77] = "앤빌마",
[80] = "스톰윈드 산맥",
[81] = "제프의 북동 사분면",
[82] = "제프의 북서 사분면",
[83] = "제프의 남동 사분면",
[84] = "제프의 남서 사분면",
[85] = "Tirisfal Glades",
[86] = "돌무덤 호수",
[87] = "골드샤이어",
[88] = "동부 벌목지",
[89] = "거울 호수 과수원",
[91] = "아조라의 탑",
[92] = "거울 호수",
[93] = "벌골 오우거 소굴",
[94] = "까마귀 언덕",
[95] = "붉은마루 협곡",
[96] = "일갈라의 탑",
[97] = "앨더의 제재소",
[98] = "레스밴 동굴",
[99] = "반란군 야영지",
[100] = "네싱워리 원정대",
[101] = "쿠르젠 주둔지",
[102] = "줄쿤다의 폐허",
[103] = "줄맘웨의 폐허",
[104] = "썩은내 산호초",
[105] = "모쉬오그 오우거 소굴",
[106] = "보급창",
[107] = "살딘 농장",
[108] = "감시의 언덕",
[109] = "펄브로우 호박밭",
[111] = "장고로드 광산",
[113] = "황금해안 채석장",
[115] = "서부 몰락지대 등대",
[116] = "안개 골짜기",
[117] = "그롬골 주둔지",
[118] = "웰가르의 발굴현장",
[120] = "서부 주둔지",
[121] = "고요의 정원 묘지",
[122] = "줄다이아 폐허",
[123] = "발랄 폐허",
[125] = "칼아이 폐허",
[126] = "트카시 폐허",
[127] = "발리아마 폐허",
[128] = "지아타자이 폐허",
[129] = "미즈자 폐허",
[130] = "Silverpine Forest",
[131] = "카라노스",
[132] = "눈마루 골짜기",
[133] = "놈리건",
[134] = "골볼라 채석장",
[135] = "서리갈기 소굴",
[136] = "은빛 동굴",
[137] = "브루날 마을",
[138] = "안개소나무 은거처",
[139] = "Eastern Plaguelands",
[141] = "Teldrassil",
[142] = "아이언밴드의 발굴현장",
[143] = "모그로쉬 소굴",
[144] = "텔사마",
[145] = "알가즈 관문",
[146] = "돌다지 댐",
[147] = "순찰자의 오두막",
[148] = "Darkshore",
[149] = "은여울 광산",
[150] = "메네실 항구",
[151] = "Designer Island",
[152] = "보루",
[153] = "로데론의 폐허",
[154] = "데스넬",
[155] = "검은그물 거미굴",
[156] = "솔리덴 농장",
[157] = "아가만드 밀농장",
[158] = "아가만드가 납골당",
[159] = "브릴",
[160] = "속삭임의 정원",
[161] = "평온의 정원",
[162] = "청명 호수",
[163] = "군터의 은거지",
[164] = "가렌의 흉가",
[165] = "발니르 농장",
[166] = "버려진 장원",
[167] = "붉은십자군 전초기지",
[168] = "북부 해안",
[169] = "속삭임의 해안",
[170] = "Lordamere Lake",
[172] = "펜리스 섬",
[173] = "파올의 안식처",
[186] = "돌라나르",
[187] = "다르나서스",
[188] = "그늘 협곡",
[189] = "스틸그릴의 정비소",
[190] = "하스글렌",
[192] = "북마루 벌목지",
[193] = "안돌할 폐허",
[195] = "강령술 학교",
[196] = "우서 경의 무덤",
[197] = "슬픔의 언덕",
[198] = "진흙탕 동굴",
[199] = "펠스톤 농장",
[200] = "달슨의 눈물",
[201] = "가론의 흉가",
[202] = "고통의 흉가",
[203] = "마르덴홀드 요새",
[204] = "장작나무 마을",
[205] = "던 모드르",
[206] = "Westfall",
[207] = "The Great Sea",
[208] = "Unused Ironcladcove",
[209] = "Shadowfang Keep",
[210] = "*** 야외 던전 ***",
[211] = "얼음 호수",
[212] = "투구바닥 호수",
[213] = "심원 광산",
[214] = "The Great Sea",
[215] = "Mulgore",
[219] = "알렉스턴 농장",
[220] = "붉은구름 고원",
[221] = "나라체 야영지",
[222] = "블러드후프 마을",
[223] = "황소바위 호수",
[224] = "습격당한 짐마차 행렬",
[225] = "붉은 바위 언덕",
[226] = "암흑 땅거미굴",
[227] = "발간 농장",
[228] = "공동묘지",
[229] = "올슨 농장",
[230] = "그레이메인 성벽",
[231] = "베렌의 동굴",
[232] = "여명의 섬",
[233] = "앰버밀",
[235] = "펜리스 요새",
[236] = "그림자송곳니 성채",
[237] = "오래된 나루터",
[238] = "말덴의 과수원",
[239] = "이바르 호박밭",
[240] = "죽음의 농장",
[241] = "오염된 과수원",
[242] = "밝은숲",
[243] = "버려진 흉가",
[244] = "휘플가 저택",
[245] = "요르겐 농장",
[246] = "용광로",
[247] = "검댕가루 발굴현장",
[249] = "우레망치 바위굴",
[250] = "타우릿산의 폐허",
[251] = "화염 마루",
[252] = "검은바위 요새",
[253] = "잿빛 기둥",
[254] = "검은바위 산",
[255] = "폭풍의 제단",
[256] = "알드랏실",
[257] = "그늘 거미굴",
[258] = "악마 바위굴",
[259] = "알아메스 호수",
[260] = "별바람 마을",
[261] = "나무옹이 요새",
[262] = "바네실 지하굴",
[263] = "바위 동굴",
[264] = "신탁의 숲",
[265] = "생명의 강",
[266] = "생명의 호수",
[267] = "Hillsbrad Foothills",
[268] = "Azshara Crater",
[269] = "Dun Algaz",
[271] = "사우스쇼어",
[272] = "타렌 밀농장",
[275] = "던홀드 요새",
[276] = "UNUSED Stonewrought Pass",
[277] = "구릉지 동굴",
[278] = "로다미어 포로수용소",
[279] = "달라란",
[280] = "스트란브래드",
[281] = "알터랙 폐허",
[282] = "산사태 오우거 소굴",
[283] = "살육의 동굴",
[284] = "고원",
[285] = "남부 경비탑",
[286] = "힐스브래드 농장",
[287] = "힐스브래드",
[288] = "청금석 광산",
[289] = "네산더 농장",
[290] = "던 가록",
[293] = "Thoradin\'s Wall",
[294] = "동부 해안",
[295] = "서부 해안",
[296] = "South seas UNUSED",
[297] = "자구에로 섬",
[298] = "바라딘 만",
[299] = "메네실 만",
[300] = "안개갈대 해안",
[301] = "폭풍 해안",
[302] = "수정 해안",
[303] = "조개껍질 해안",
[305] = "북부 해안가",
[306] = "남부 해안가",
[307] = "전망대 절벽",
[308] = "The Forbidding Sea",
[309] = "아이언비어드의 고분",
[310] = "수정 광산",
[311] = "아보라즈의 폐허",
[312] = "자네이로 섬",
[313] = "북부습곡 장원",
[314] = "고셰크 농장",
[315] = "다비리 농장",
[316] = "돌주먹일족 소굴",
[317] = "마른나무껍질 마을",
[318] = "마른수염 골짜기",
[320] = "임시 주둔지",
[321] = "해머폴",
[322] = "검은바다 난파지",
[323] = "오브린의 야영지",
[324] = "스트롬가드 요새",
[325] = "아라소르의 탑",
[326] = "성소",
[327] = "팔디르의 만",
[328] = "가라앉은 산호초",
[330] = "Thandol Span",
[331] = "Ashenvale",
[332] = "The Great Sea",
[333] = "동쪽 봉인의 마법진",
[334] = "서쪽 봉인의 마법진",
[335] = "내부 봉인의 마법진",
[336] = "외부 봉인의 마법진",
[337] = "아포크리판의 안식처",
[338] = "고통의 요새",
[339] = "레슬로 협곡",
[340] = "카르가스",
[341] = "코쉬 야영지",
[342] = "보프 야영지",
[343] = "우르그 야영지",
[344] = "카그 야영지",
[345] = "아그몬드의 최후",
[346] = "해머토의 발굴현장",
[347] = "먼지목도리 소굴",
[348] = "맹금의 봉우리",
[349] = "와일드해머 요새",
[350] = "쿠엘다닐 오두막",
[351] = "굼벵이 바위굴",
[352] = "준와타",
[353] = "샤드라알로",
[354] = "진타알로",
[355] = "줄의 제단",
[356] = "세라데인",
[357] = "Feralas",
[358] = "칼날가시 협곡",
[359] = "바엘 모단",
[360] = "투자개발회사 광산",
[361] = "Felwood",
[362] = "칼바위 언덕",
[363] = "시험의 골짜기",
[364] = "동굴 막사",
[365] = "불타는 칼날 소굴",
[366] = "콜카르 바윗골",
[367] = "센진 마을",
[368] = "메아리 섬",
[369] = "천둥 골짜기",
[370] = "모래바람 협곡",
[371] = "먼지바람 동굴",
[372] = "타이라가드 요새",
[373] = "가라앉은 해안",
[374] = "칼날주먹 만",
[375] = "데드아이 해안",
[377] = "Southfury River",
[378] = "타우라조 야영지",
[379] = "전초 기지",
[380] = "크로스로드",
[381] = "돌무더기 광산",
[382] = "진흙늪",
[383] = "메마른 언덕",
[384] = "공포의 안개봉우리",
[385] = "북부 전초기지",
[386] = "잊혀진 웅덩이",
[387] = "푸른 오아시스",
[388] = "죽은 오아시스",
[390] = "거인의 들판",
[391] = "무역 해안",
[392] = "톱니항",
[393] = "검은창 해안",
[394] = "Darrowmere Lake UNUSED",
[395] = "카엘 다로우",
[396] = "윈터후프 우물",
[397] = "썬더혼 우물",
[398] = "와일드메인 우물",
[399] = "지평선 마루",
[400] = "Thousand Needles",
[401] = "타이더스 계단",
[403] = "그늘 쉼터 여관",
[404] = "바엘던 발굴현장",
[405] = "Desolace",
[406] = "Stonetalon Mountains",
[407] = "오그리마",
[408] = "Gillijim\'s Isle",
[409] = "Island of Doctor Lapidis",
[410] = "칼바람 협곡",
[411] = "배스랜 서식지",
[412] = "오르딜아란의 폐허",
[413] = "마에스트라 주둔지",
[414] = "조람 해안",
[415] = "아스트라나르",
[416] = "아에시나의 제단",
[417] = "불타버린 신전",
[418] = "별가루의 폐허",
[419] = "울부짖는 골짜기",
[420] = "실바람 산장",
[421] = "미스트랄 호수",
[422] = "유성 호수",
[424] = "아이리스 호수",
[425] = "달샘",
[426] = "라이네나무 은신처",
[427] = "그늘 동굴",
[428] = "어둠의 터",
[429] = "사비안",
[430] = "사티르나르",
[431] = "토막나무 주둔지",
[432] = "도르다닐 지하굴",
[433] = "팔파렌 강",
[434] = "지옥불 언덕",
[435] = "악마벼락 협곡",
[436] = "악마벼락 마루",
[437] = "전쟁노래부족 벌목기지",
[438] = "어둠의 나무",
[439] = "소금 평원",
[440] = "Tanaris",
[441] = "팔라딤 호수",
[442] = "아우버다인",
[443] = "마시스트라의 폐허",
[444] = "알살락스의 탑",
[445] = "절벽 폭포",
[446] = "바샬아란",
[447] = "아메스아란",
[448] = "고대정령의 숲",
[449] = "지배자의 무덤",
[450] = "렘트레블의 발굴현장",
[452] = "안개 해안",
[453] = "침식지",
[454] = "성난굽이 강",
[455] = "검은나무일족 소굴",
[456] = "폭포수 강",
[457] = "The Veiled Sea",
[458] = "황금길",
[459] = "붉은십자군 경비초소",
[460] = "해바위 야영지",
[461] = "칼바람 바위산",
[463] = "바위웅덩이 호수",
[464] = "땅거미 호수",
[465] = "잿더미 계곡",
[466] = "혈폭풍일족의 골짜기",
[467] = "돌발톱 봉우리",
[468] = "갈퀴발톱굴",
[469] = "큰소나무 계곡",
[470] = "썬더 블러프",
[471] = "용사의 바람절벽",
[472] = "부싯돌 고원",
[473] = "바람막이 바위",
[474] = "수렵의 봉우리",
[475] = "정기의 봉우리",
[476] = "장로의 봉우리",
[477] = "주부왈의 폐허",
[478] = "아리스리엔 연못",
[479] = "녹슨망치 발굴현장",
[480] = "에톡 야영지",
[481] = "갈래발굽 바윗골",
[482] = "마루둥지",
[483] = "회오리 협곡",
[484] = "높새바람 봉우리",
[485] = "구름 승강장",
[486] = "갈라크 소굴",
[487] = "하피 동굴",
[488] = "비바람 바위굴",
[489] = "탈라나르",
[490] = "Un\'Goro Crater",
[491] = "Razorfen Kraul",
[492] = "까마귀 언덕 묘지",
[493] = "Moonglade",
[495] = "DELETE ME",
[496] = "담쟁이 마을",
[497] = "늪지기 오두막",
[498] = "붉은늪지 동굴",
[499] = "암흑안개 거미굴",
[500] = "모글 야영지",
[501] = "비질의 추락지",
[502] = "마녀 언덕",
[503] = "감시초소",
[504] = "북부 경비탑",
[505] = "서부 경비탑",
[506] = "버려진 경비탑",
[507] = "푸른늪지",
[508] = "돌망치일족 폐허",
[509] = "화염의 둥지",
[510] = "용의 늪",
[511] = "용의 둥지",
[512] = "오닉시아의 둥지",
[513] = "테라모어 섬",
[514] = "거점 요새",
[515] = "철갑 감옥",
[516] = "먼지진흙 만",
[517] = "성난파도 만",
[518] = "몸서리 해안",
[536] = "에이들의 은신처",
[537] = "불기둥 마루",
[538] = "락카리 잿구덩이",
[539] = "공포의 터",
[540] = "갈래굽이 구렁",
[541] = "마샬의 야영지",
[542] = "버섯 바위굴",
[543] = "골락카 간헐천",
[556] = "대호수",
[576] = "부랑자 소굴",
[596] = "코도 무덤",
[597] = "침묵의 초소",
[598] = "살데리스 해안",
[599] = "천둥도끼 요새",
[600] = "볼간의 구덩이",
[602] = "만노로크 소굴",
[603] = "살게론",
[604] = "마그람 마을",
[606] = "겔키스 마을",
[607] = "뾰족바위 골짜기",
[608] = "나이젤의 야영지",
[609] = "콜카르 마을",
[616] = "Hyjal",
[618] = "Winterspring",
[636] = "검은늑대 강",
[637] = "코도 바위",
[638] = "비밀의 길",
[639] = "정기 바위",
[640] = "희미한 불꽃의 제단",
[656] = "엘룬아라 호수",
[657] = "피난처",
[676] = "Outland",
[696] = "장인의 정원",
[697] = "상인의 정원",
[698] = "신전 정원",
[699] = "엘룬의 신전",
[700] = "세나리온 자치령",
[701] = "전사의 정원",
[702] = "루테란 마을",
[716] = "아이언밴드 야영지",
[717] = "The Stockade",
[718] = "Wailing Caverns",
[719] = "Blackfathom Deeps",
[720] = "격투의 섬",
[721] = "Gnomeregan",
[722] = "Razorfen Downs",
[736] = "바네실 동굴",
[796] = "Scarlet Monastery",
[797] = "제로드 선착장",
[798] = "마루목 감시탑",
[799] = "어스름 강둑",
[800] = "눈마루 고개",
[801] = "찬바람 골짜기",
[802] = "쉼머 마루",
[803] = "앰버스틸 목장",
[804] = "툰드리드 언덕",
[805] = "남부 관문 통행로",
[806] = "남부 관문 전초기지",
[807] = "북부 관문 통행로",
[808] = "북부 관문 전초기지",
[809] = "아이언포지 성문",
[810] = "고요의 연못",
[811] = "악몽의 골짜기",
[812] = "독그물 골짜기",
[813] = "보루",
[814] = "분노의 강",
[815] = "분노의 강",
[816] = "서슬갈기일족 영토",
[817] = "해골 바위굴",
[818] = "회색갈기일족 바위굴",
[819] = "성난바람 마루",
[820] = "황금 초원",
[821] = "구릉 초원",
[836] = "던 알가즈",
[837] = "던 알가즈",
[838] = "북부 관문 통행로",
[839] = "남부 관문 통행로",
[856] = "황혼의 숲",
[876] = "GM Island",
[877] = "Delete ME",
[878] = "분노의 강",
[879] = "분노의 강",
[880] = "탄돌 교각",
[881] = "탄돌 교각",
[896] = "속죄의 섬",
[916] = "얀센 농장",
[917] = "메마른 논밭",
[918] = "몰센 농장",
[919] = "스텐들의 연못",
[920] = "비수 언덕",
[921] = "데몬트의 집터",
[922] = "먼지 언덕",
[923] = "가루바위 골짜기",
[924] = "왕의 계곡",
[925] = "알가즈 주둔지",
[926] = "버클브리 농장",
[927] = "반짝이는 호숫가",
[928] = "북부 해안 골짜기",
[936] = "곰발바닥 마루",
[956] = "The Verdant Fields",
[976] = "가젯잔",
[977] = "스팀휘들 항구",
[978] = "줄파락",
[979] = "슬픈모래 감시탑",
[980] = "덤불나무 골짜기",
[981] = "모래지옥 협곡",
[982] = "맹독의 둥지",
[983] = "모래망치 주둔지",
[984] = "동쪽 달의 폐허",
[985] = "샘솟는 벌판",
[986] = "잘라쉬지의 굴",
[987] = "끝자락 해안",
[988] = "파도타기 해안",
[989] = "울둠",
[990] = "감시자의 골짜기",
[991] = "건스탠의 야영지",
[992] = "서쪽 달의 폐허",
[996] = "약탈의 야영지",
[997] = "약탈의 계곡",
[998] = "약탈의 바위굴",
[999] = "돌망루 탑",
[1000] = "갈라델 골짜기",
[1001] = "호수마루 오솔길",
[1002] = "붉은마루 삼거리",
[1016] = "불길한 언덕",
[1017] = "랩터 마루",
[1018] = "검은바닥 습지대",
[1019] = "녹지대",
[1020] = "이끼가죽 수렁",
[1021] = "텔겐 바위굴",
[1022] = "푸른아가미 습지대",
[1023] = "소금물 습지대",
[1024] = "해몰이 늪",
[1025] = "녹지대",
[1036] = "성난송곳니 야영지",
[1037] = "그림 바톨",
[1038] = "용아귀부족 관문",
[1039] = "잃어버린 해안",
[1056] = "다로우 언덕",
[1057] = "소라딘의 성벽",
[1076] = "그물누비 고개",
[1097] = "고요의 강둑",
[1098] = "미스트맨틀 장원",
[1099] = "모자케 야영지",
[1100] = "그림토템 주둔지",
[1101] = "고통의 구덩이",
[1102] = "갈기바람 호수",
[1103] = "골두니 전초기지",
[1104] = "모크골둔",
[1105] = "거친흉터 골짜기",
[1106] = "공작날개 고원",
[1107] = "산들바람 호수",
[1108] = "잊혀진 해안",
[1109] = "동쪽 기둥",
[1110] = "서쪽 기둥",
[1111] = "꿈나무",
[1112] = "비취비늘 호수",
[1113] = "오네이로스",
[1114] = "까마귀바람 폐허",
[1115] = "무쇠설인 소굴",
[1116] = "페더문 요새",
[1117] = "솔라살 폐허",
[1118] = "낮은벌",
[1119] = "쌍둥이 바위산",
[1120] = "살도르 섬",
[1121] = "공포의 터",
[1136] = "높은벌",
[1137] = "낮은벌",
[1156] = "불모의 땅 남부",
[1157] = "남부 황금길",
[1176] = "Zul\'Farrak",
[1196] = "UNUSEDAlcaz Island",
[1216] = "나무구렁 요새",
[1217] = "반디르 야영지",
[1218] = "아즈샤라",
[1219] = "레가쉬 야영지",
[1220] = "탈라시안 주둔지",
[1221] = "엘다라스 폐허",
[1222] = "헤타에라의 손아귀",
[1223] = "진말로의 신전",
[1224] = "곰마루",
[1225] = "우르솔란",
[1226] = "아크코란의 신전",
[1227] = "폭풍의 만",
[1228] = "조각난 해안",
[1229] = "엘다라의 탑",
[1230] = "톱니 산호초",
[1231] = "남녘마루 해안",
[1232] = "레이븐크레스트 기념비",
[1233] = "쓸쓸한 마루",
[1234] = "멘나르 호수",
[1235] = "섀도송 제단",
[1236] = "할다르 야영지",
[1237] = "발로르모크",
[1256] = "버려진 착륙장",
[1276] = "돌발톱 토굴길",
[1277] = "돌발톱 토굴길",
[1296] = "바위어금니 농장",
[1297] = "톱니멧돼지 농장",
[1316] = "가시덩굴 구릉",
[1336] = "해적단 소굴",
[1337] = "Uldaman",
[1338] = "로다미어 호수",
[1339] = "로다미어 호수",
[1357] = "갤로우 삼거리",
[1377] = "Silithus",
[1397] = "Emerald Forest",
[1417] = "Sunken Temple",
[1437] = "우레망치 요새",
[1438] = "네더가드 요새",
[1439] = "우레망치 주둔지",
[1440] = "뱀의 보금자리",
[1441] = "폭풍의 제단",
[1442] = "불망루 마루",
[1443] = "잿가루 채석장",
[1444] = "잿더미 바다",
[1445] = "검은바위 산",
[1446] = "토륨 조합 거점",
[1457] = "요새 무기고",
[1477] = "The Temple of Atal\'Hakkar",
[1497] = "Undercity",
[1517] = "울다만",
[1518] = "죽음의 폐광",
[1519] = "Stormwind City",
[1537] = "Ironforge",
[1557] = "갈래발굽 소굴",
[1577] = "가시덤불 봉우리",
[1578] = "폭풍 해안 남부",
[1579] = "Unused The Deadmines 002",
[1580] = "철갑 동굴",
[1581] = "The Deadmines",
[1582] = "철갑 동굴",
[1583] = "Blackrock Spire",
[1584] = "Blackrock depths",
[1597] = "랩터 서식지",
[1598] = "그롤돔 농장",
[1599] = "몰샨 주둔지",
[1600] = "Honor\'s Stand UNUSED",
[1601] = "검은가시 마루",
[1602] = "가시덩굴 벌판",
[1603] = "아가마고르",
[1617] = "영웅의 계곡",
[1637] = "Orgrimmar",
[1638] = "Thunder Bluff",
[1639] = "장로의 봉우리",
[1640] = "정기의 봉우리",
[1641] = "수렵의 봉우리",
[1657] = "Darnassus",
[1658] = "세나리온 자치령",
[1659] = "장인의 정원",
[1660] = "전사의 정원",
[1661] = "신전 정원",
[1662] = "상인의 정원",
[1677] = "가빈 절벽",
[1678] = "소페라 절벽",
[1679] = "코란의 비수",
[1680] = "마루터기",
[1681] = "물안개 호숫가",
[1682] = "단드레드 장원",
[1683] = "침묵의 동굴",
[1684] = "서리바람 거점",
[1697] = "랩터 서식지",
[1698] = "가시덩굴 벌판",
[1699] = "가시덩굴 언덕",
[1700] = "아가마고르",
[1701] = "검은가시 마루",
[1702] = "명예의 감시탑",
[1703] = "몰샨의 망루",
[1704] = "그롤돔 농장",
[1717] = "가시덩굴 우리",
[1718] = "구름 승강장",
[1737] = "안개계곡 골짜기",
[1738] = "네크마니 수원지",
[1739] = "붉은해적단 주둔지",
[1740] = "투자개발회사 탐사기지",
[1741] = "구루바시 투기장",
[1742] = "정기의 동굴",
[1757] = "크림슨 베일호",
[1758] = "립타이드호",
[1759] = "담셀의 행운호",
[1760] = "투자개발회사 기계조작실",
[1761] = "마른가지 마을",
[1762] = "악령발 마을",
[1763] = "자에데나르",
[1764] = "피멍울 강",
[1765] = "피멍울 폭포",
[1766] = "불벼락 골짜기",
[1767] = "강철나무 숲",
[1768] = "강철나무 굴",
[1769] = "나무구렁 요새",
[1770] = "어둠의 요새",
[1771] = "책략가의 사원",
[1777] = "이타리우스의 동굴",
[1778] = "슬픔의 그늘",
[1779] = "드레닐두르 마을",
[1780] = "부러진창 교차로",
[1797] = "진흙늪",
[1798] = "변화의 늪",
[1817] = "진흙탕 동굴",
[1837] = "마른나무껍질 동굴",
[1857] = "소라딘의 성벽",
[1858] = "돌주먹 언덕",
[1877] = "송곳니 골짜기",
[1878] = "먼지받이",
[1879] = "신기루 벌판",
[1880] = "페더비어드의 오두막",
[1881] = "신디거의 야영지",
[1882] = "역병안개 협곡",
[1883] = "돌개바람 호수",
[1884] = "아골와타",
[1885] = "히리와타",
[1886] = "굼벵이 폐허",
[1887] = "보겐의 절벽",
[1897] = "창조주의 정원",
[1898] = "먼지바람 협곡",
[1917] = "샤올와타",
[1937] = "해그늘 폐허",
[1938] = "무너진 기둥",
[1939] = "끝없는 사막",
[1940] = "거친파도 해안",
[1941] = "Caverns of Time",
[1942] = "늪지대",
[1943] = "강철바위 고원",
[1957] = "검은재 동굴",
[1958] = "무두장이 야영지",
[1959] = "먼지불 골짜기",
[1977] = "Zul\'Gurub",
[1978] = "안개갈대 주둔지",
[1997] = "피멍울 초소",
[1998] = "갈퀴가지 숲",
[2017] = "Stratholme",
[2037] = "UNUSEDShadowfang Keep 003",
[2057] = "Scholomance",
[2077] = "황혼의 계곡",
[2078] = "황혼의 해안",
[2079] = "알카즈 섬",
[2097] = "먹구름 봉우리",
[2098] = "새벽숲 지하묘지",
[2099] = "돌망루 요새",
[2100] = "Maraudon",
[2101] = "스타우트라거 여관",
[2102] = "썬더브루 양조장",
[2103] = "메네실 요새",
[2104] = "깊은바다 선술집",
[2117] = "암흑의 무덤",
[2118] = "브릴 마을회관",
[2119] = "갤로우 선술집",
[2137] = "예언의 웅덩이",
[2138] = "공포의 안개굴",
[2157] = "바엘던 요새",
[2158] = "엠버스트라이프의 굴",
[2159] = "Onyxia\'s Lair",
[2160] = "칼바람 광산",
[2161] = "롤랜드 광산",
[2177] = "투기장",
[2197] = "예언의 웅덩이",
[2198] = "동트는 협곡",
[2217] = "부러진창 마을",
[2237] = "백사장 야영지",
[2238] = "고르니아",
[2239] = "제인의 눈동자 분화구",
[2240] = "신기루 경주장",
[2241] = "눈호랑이 바위",
[2242] = "숨겨진 숲",
[2243] = "나무구렁 야영지",
[2244] = "눈사태일족 마을",
[2245] = "마즈소릴",
[2246] = "얼음불꽃 온천",
[2247] = "얼음엉겅퀴 언덕",
[2248] = "던 만다르",
[2249] = "서리속삭임 골짜기",
[2250] = "올빼미날개 숲",
[2251] = "켈테릴 호수",
[2252] = "켈테릴의 폐허",
[2253] = "별똥별 마을",
[2254] = "반탈로우 지하굴",
[2255] = "눈망루 마을",
[2256] = "검은속삭임 협곡",
[2257] = "Deeprun Tram",
[2258] = "곰팡이 계곡",
[2259] = "마리스 농장",
[2260] = "마리스 농장",
[2261] = "지하 납골당",
[2262] = "다로우샤이어",
[2263] = "산마루 경비탑",
[2264] = "코린 삼거리",
[2265] = "붉은십자군 주둔지",
[2266] = "티르의 손 수도원",
[2267] = "붉은십자군 대성당",
[2268] = "희망의 빛 예배당",
[2269] = "브라우만 밀농장",
[2270] = "맹독의 숲",
[2271] = "동부방벽 경비탑",
[2272] = "노스데일",
[2273] = "줄마샤르",
[2274] = "마즈라알로",
[2275] = "북부관문 경비탑",
[2276] = "쿠엘리시엔 오두막",
[2277] = "역병의 숲",
[2278] = "스컬지 요새",
[2279] = "스트라솔름",
[2280] = "UNUSED Stratholme",
[2297] = "다로미어 호수",
[2298] = "카엘 다로우",
[2299] = "다로미어 호수",
[2300] = "시간의 동굴",
[2301] = "엉겅퀴 마을",
[2302] = "먼지 수렁",
[2303] = "갈기바람 협곡",
[2317] = "남쪽 바다",
[2318] = "대해",
[2319] = "대해",
[2320] = "대해",
[2321] = "대해",
[2322] = "장막의 바다",
[2323] = "장막의 바다",
[2324] = "장막의 바다",
[2325] = "장막의 바다",
[2326] = "장막의 바다",
[2337] = "칼바람 언덕 병영",
[2338] = "남쪽 바다",
[2339] = "대해",
[2357] = "붉은송곳니 야영지",
[2358] = "숲의 노래",
[2359] = "푸른발 마을",
[2360] = "은빛날개 전초기지",
[2361] = "나이트헤이븐",
[2362] = "레물로스의 제단",
[2363] = "스톰레이지 지하굴",
[2364] = "대해",
[2365] = "대해",
[2366] = "The Black Morass",
[2367] = "Old Hillsbrad Foothills",
[2368] = "타렌 밀농장",
[2369] = "사우스쇼어",
[2370] = "던홀드 요새",
[2371] = "던 가록",
[2372] = "힐스브래드 농장",
[2373] = "동부 해안",
[2374] = "네산더 농장",
[2375] = "다로우 언덕",
[2376] = "남부 경비탑",
[2377] = "소라딘의 성벽",
[2378] = "서부 해안",
[2379] = "청금석 광산",
[2397] = "대해",
[2398] = "대해",
[2399] = "대해",
[2400] = "성난 바다",
[2401] = "성난 바다",
[2402] = "성난 바다",
[2403] = "성난 바다",
[2404] = "테드리스 아란",
[2405] = "에텔 레소르",
[2406] = "라나즈자르 섬",
[2407] = "코르메크의 오두막",
[2408] = "그늘수렵 마을",
[2417] = "검은바위 고개",
[2418] = "모건의 망루",
[2419] = "뱀갈퀴 바위굴",
[2420] = "공포의 날개 골짜기",
[2421] = "드라코다르",
[2437] = "Ragefire Chasm",
[2457] = "별빛노래 숲",
[2477] = "장막의 바다",
[2478] = "모를로스아란",
[2479] = "에메랄드 성소",
[2480] = "비취불꽃 숲",
[2481] = "콘스텔라스 폐허",
[2497] = "시련의 산마루",
[2517] = "파멸자의 봉우리",
[2518] = "라리스 정자",
[2519] = "덩굴발 언덕",
[2520] = "덩굴발일족 소굴",
[2521] = "베르단티스 강",
[2522] = "이실디엔 폐허",
[2537] = "그림토템 초소",
[2538] = "아파라제 야영지",
[2539] = "말라카진",
[2540] = "구릉바위 협곡",
[2541] = "시쉬르 협곡",
[2557] = "Dire Maul",
[2558] = "죽음의 협곡",
[2559] = "다이아몬드 강",
[2560] = "아리덴의 야영지",
[2561] = "악의 소굴",
[2562] = "카라잔",
[2563] = "모건의 터",
[2577] = "혈투의 전장",
[2597] = "Alterac Valley",
[2617] = "스크래블스크류의 야영지",
[2618] = "비취불꽃 비탈",
[2619] = "톤드로릴 강",
[2620] = "톤드로릴 강",
[2621] = "메렐다르 호수",
[2622] = "전염의 흉터",
[2623] = "오염의 흉터",
[2624] = "검은나무 호수",
[2625] = "동부방벽 관문",
[2626] = "공포의 거미굴",
[2627] = "테러데일",
[2637] = "카르가시아 요새",
[2657] = "뼈의 골짜기",
[2677] = "Blackwing Lair",
[2697] = "사자의 길",
[2717] = "Molten Core",
[2737] = "스카라베 성벽",
[2738] = "마파람 마을",
[2739] = "황혼의 망치단 주둔지",
[2740] = "수정 골짜기",
[2741] = "스카라베 제단",
[2742] = "하이브아쉬",
[2743] = "하이브조라",
[2744] = "하이브레갈",
[2757] = "전사한 용사의 제단",
[2777] = "알터랙 계곡",
[2797] = "검은심연의 나락",
[2817] = "*** 야외 던전 ***",
[2837] = "지배자의 지하실",
[2838] = "돌다지 고개",
[2839] = "알터랙 계곡",
[2857] = "싸움 우리",
[2877] = "땅덩어리 시험용",
[2897] = "조람가르 전초기지",
[2917] = "Hall of Legends",
[2918] = "Champions\' Hall",
[2937] = "그로쉬고크 주둔지",
[2938] = "수면의 협곡",
[2957] = "깊은무쇠 광산",
[2958] = "돌심장 전초기지",
[2959] = "던 발다르",
[2960] = "얼음날개 고개",
[2961] = "서리늑대 마을",
[2962] = "거점 보초탑",
[2963] = "얼음이빨 광산",
[2964] = "겨울도끼 요새",
[2977] = "얼음피 주둔지",
[2978] = "서리늑대 요새",
[2979] = "톨크렌 농장",
[3017] = "서리비수 고개",
[3037] = "강철바위 야영지",
[3038] = "위젤의 분화구",
[3039] = "타혼다 폐허",
[3057] = "투쟁의 벌판",
[3058] = "얼음날개 동굴",
[3077] = "용사의 안식처",
[3097] = "벌레무리 기둥",
[3098] = "황혼의 초소",
[3099] = "황혼의 전초기지",
[3100] = "파괴된 황혼의 야영지",
[3117] = "샬자루의 둥지",
[3137] = "탈렌드리스 초소",
[3138] = "레스리스 성소",
[3139] = "공포의 달빛 동굴",
[3140] = "비늘수염 동굴",
[3157] = "구릉바위 동굴",
[3177] = "전쟁노래부족 노동기지",
[3197] = "서리바람 야영지",
[3217] = "검투장",
[3237] = "검투장",
[3257] = "그락카론드의 무덤",
[3277] = "Warsong Gulch",
[3297] = "서리늑대 무덤",
[3298] = "서리늑대 고개",
[3299] = "던 발다르 고개",
[3300] = "얼음피 무덤",
[3301] = "눈사태 무덤",
[3302] = "돌심장 무덤",
[3303] = "스톰파이크 무덤",
[3304] = "얼음날개 참호",
[3305] = "돌심장 참호",
[3306] = "자갈발 마루",
[3317] = "레반터스크 마을",
[3318] = "듀로탄 바위",
[3319] = "은빛날개 숲",
[3320] = "전쟁노래부족 벌목기지",
[3321] = "은빛날개 요새",
[3337] = "자갈발 동굴",
[3338] = "장막의 틈",
[3357] = "요잠바 섬",
[3358] = "Arathi Basin",
[3377] = "증오의 또아리",
[3378] = "히리크의 제단",
[3379] = "샤드라자르",
[3380] = "학카리 광장",
[3381] = "시르밸라의 절벽",
[3382] = "베데크 신전",
[3383] = "혈화의 구덩이",
[3384] = "혈신의 제단",
[3397] = "잔자의 언덕",
[3398] = "광란의 경계",
[3417] = "트롤베인 전당",
[3418] = "파멸의 전당",
[3419] = "페이글의 낚시터",
[3420] = "농장",
[3421] = "대장간",
[3422] = "제재소",
[3423] = "금광",
[3424] = "마구간",
[3425] = "세나리온 요새",
[3426] = "스테그헬름 거점",
[3427] = "브론즈비어드 야영지",
[3428] = "Ahn\'Qiraj",
[3429] = "Ruins of Ahn\'Qiraj",
[3446] = "황혼의 숲",
[3447] = "오르텔의 은신처",
[3448] = "스카라베 정원",
[3449] = "장군의 정원",
[3450] = "안퀴라즈 저장실",
[3451] = "안퀴라즈 부화장",
[3452] = "안퀴라즈 둥지",
[3453] = "감시자의 정원",
[3454] = "안퀴라즈 폐허",
[3456] = "Naxxramas",
[3459] = "City",
[3478] = "Gates of Ahn\'Qiraj",
[3486] = "라벤홀트 장원",
}
| mit |
jshackley/darkstar | scripts/globals/weaponskills/tachi_rana.lua | 18 | 4583 | -----------------------------------
-- Tachi Rana
-- Great Katana weapon skill
-- Skill Level: N/A
-- Delivers a three-fold attack. params.accuracy varies with TP. Aftermath effect varies with TP. See Kogarasumaru.
-- In order to obtain Tachi: Rana, the Unlocking a Myth (Samurai) quest must be completed.
-- Will stack with Sneak Attack (first hit only).
-- Aligned with the Shadow Gorget, Soil Gorget & Snow Gorget.
-- Aligned with the Shadow Belt, Soil Belt & Snow Belt.
-- Element: None
-- Modifiers: STR:50%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 3;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.5; 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.8; params.acc200= 0.9; params.acc300= 1;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.5;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
if ((player:getEquipID(SLOT_MAIN) == 19002) and (player:getMainJob() == JOB_SAM)) 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, 1);
elseif ((player:getTP() >= 111) and (player:getTP() <= 120)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 11, 0, 180, 0, 1);
elseif ((player:getTP() >= 121) and (player:getTP() <= 130)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 12, 0, 180, 0, 1);
elseif ((player:getTP() >= 131) and (player:getTP() <= 140)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 13, 0, 180, 0, 1);
elseif ((player:getTP() >= 141) and (player:getTP() <= 150)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 14, 0, 180, 0, 1);
elseif ((player:getTP() >= 151) and (player:getTP() <= 160)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 15, 0, 180, 0, 1);
elseif ((player:getTP() >= 161) and (player:getTP() <= 170)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 16, 0, 180, 0, 1);
elseif ((player:getTP() >= 171) and (player:getTP() <= 180)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 17, 0, 180, 0, 1);
elseif ((player:getTP() >= 181) and (player:getTP() <= 190)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 18, 0, 180, 0, 1);
elseif ((player:getTP() >= 191) and (player:getTP() <= 199)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 19, 0, 180, 0, 1);
-- AFTERMATH LV2
elseif ((player:getTP() >= 200) and (player:getTP() <= 210)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 24, 0, 180, 0, 1);
elseif ((player:getTP() >= 211) and (player:getTP() <= 219)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 28, 0, 180, 0, 1);
elseif ((player:getTP() >= 221) and (player:getTP() <= 229)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 32, 0, 180, 0, 1);
elseif ((player:getTP() >= 231) and (player:getTP() <= 239)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 36, 0, 180, 0, 1);
elseif ((player:getTP() >= 241) and (player:getTP() <= 249)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 40, 0, 180, 0, 1);
elseif ((player:getTP() >= 251) and (player:getTP() <= 259)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 44, 0, 180, 0, 1);
elseif ((player:getTP() >= 261) and (player:getTP() <= 269)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 48, 0, 180, 0, 1);
elseif ((player:getTP() >= 271) and (player:getTP() <= 279)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 52, 0, 180, 0, 1);
elseif ((player:getTP() >= 281) and (player:getTP() <= 289)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 56, 0, 180, 0, 1);
elseif ((player:getTP() >= 291) and (player:getTP() <= 299)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 59, 0, 180, 0, 1);
-- 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 |
VincentGong/chess | cocos2d-x/cocos/scripting/lua-bindings/auto/api/TMXTiledMap.lua | 6 | 2826 |
--------------------------------
-- @module TMXTiledMap
-- @extend Node
--------------------------------
-- @function [parent=#TMXTiledMap] setObjectGroups
-- @param self
-- @param #array_table array
--------------------------------
-- @function [parent=#TMXTiledMap] getProperty
-- @param self
-- @param #string str
-- @return Value#Value ret (return value: cc.Value)
--------------------------------
-- @function [parent=#TMXTiledMap] setMapSize
-- @param self
-- @param #size_table size
--------------------------------
-- @function [parent=#TMXTiledMap] getObjectGroup
-- @param self
-- @param #string str
-- @return TMXObjectGroup#TMXObjectGroup ret (return value: cc.TMXObjectGroup)
--------------------------------
-- overload function: getObjectGroups()
--
-- overload function: getObjectGroups()
--
-- @function [parent=#TMXTiledMap] getObjectGroups
-- @param self
-- @return array_table#array_table ret (retunr value: array_table)
--------------------------------
-- @function [parent=#TMXTiledMap] getTileSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
-- @function [parent=#TMXTiledMap] getMapSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
-- @function [parent=#TMXTiledMap] getProperties
-- @param self
-- @return map_table#map_table ret (return value: map_table)
--------------------------------
-- @function [parent=#TMXTiledMap] setTileSize
-- @param self
-- @param #size_table size
--------------------------------
-- @function [parent=#TMXTiledMap] setProperties
-- @param self
-- @param #map_table map
--------------------------------
-- @function [parent=#TMXTiledMap] getLayer
-- @param self
-- @param #string str
-- @return TMXLayer#TMXLayer ret (return value: cc.TMXLayer)
--------------------------------
-- @function [parent=#TMXTiledMap] getMapOrientation
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- @function [parent=#TMXTiledMap] setMapOrientation
-- @param self
-- @param #int int
--------------------------------
-- @function [parent=#TMXTiledMap] create
-- @param self
-- @param #string str
-- @return TMXTiledMap#TMXTiledMap ret (return value: cc.TMXTiledMap)
--------------------------------
-- @function [parent=#TMXTiledMap] createWithXML
-- @param self
-- @param #string str
-- @param #string str
-- @return TMXTiledMap#TMXTiledMap ret (return value: cc.TMXTiledMap)
--------------------------------
-- @function [parent=#TMXTiledMap] getDescription
-- @param self
-- @return string#string ret (return value: string)
return nil
| mit |
jshackley/darkstar | scripts/zones/RuLude_Gardens/npcs/_6r9.lua | 17 | 2864 | -----------------------------------
-- Area: Ru'Lude Gardens
-- NPC: Audience Chamber
-- Involved in Mission: Magicite
-- @pos 0 -5 66 243
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/missions");
require("scripts/zones/RuLude_Gardens/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
CurrentMission = player:getCurrentMission(player:getNation());
if ( player:getCurrentMission(COP) ==MORE_QUESTIONS_THAN_ANSWERS and player:getVar("PromathiaStatus")==1) then
player:startEvent(0x2742);
elseif (player:hasKeyItem(ARCHDUCAL_AUDIENCE_PERMIT) and CurrentMission == 255 and player:getVar("MissionStatus") == 1) then
player:startEvent(0x0080);
elseif (player:hasKeyItem(MAGICITE_OPTISTONE) and player:hasKeyItem(MAGICITE_AURASTONE) and player:hasKeyItem(MAGICITE_ORASTONE)) then
if (player:hasKeyItem(AIRSHIP_PASS)) then
player:startEvent(0x003c,1);
else
player:startEvent(0x003c);
end
elseif (player:hasKeyItem(ARCHDUCAL_AUDIENCE_PERMIT)) then
player:messageSpecial(SOVEREIGN_WITHOUT_AN_APPOINTMENT);
else
player:startEvent(0x008a); -- you don't have a permit
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0080) then
player:setVar("MissionStatus",2);
player:addMission(player:getNation(),13);
player:addKeyItem(LETTERS_TO_ALDO);
player:messageSpecial(KEYITEM_OBTAINED,LETTERS_TO_ALDO);
elseif (csid == 0x003c) then
player:delKeyItem(MAGICITE_OPTISTONE);
player:delKeyItem(MAGICITE_AURASTONE);
player:delKeyItem(MAGICITE_ORASTONE);
if (player:hasKeyItem(AIRSHIP_PASS)) then
player:addGil(GIL_RATE*20000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*20000);
player:addTitle(CONQUEROR_OF_FATE);
else
player:addKeyItem(AIRSHIP_PASS);
player:messageSpecial(KEYITEM_OBTAINED,AIRSHIP_PASS);
player:addTitle(HAVE_WINGS_WILL_FLY);
end
player:setVar("MissionStatus",6); -- all that's left is to go back to the embassy
elseif (csid == 0x2742) then
player:setVar("PromathiaStatus",2);
end
end; | gpl-3.0 |
kjmac123/metabuilder | metabuilder/metabase/writer_ndk.lua | 1 | 8193 | import "writer_common.lua"
g_makeOutputDirAbs = mbwriter.global.makeoutputdirabs
g_makeOutputDirAbsRoot = nil
g_makeOutputDirAbsTargetConfig = nil
----------------------------------------------------------------------------------------------------------------------------------------------------------------
function GetWorkspaceDir(currentTargetName, configName)
return g_makeOutputDirAbs .. "/" .. currentTargetName .. "/" .. configName
end
function GetJNIDir(currentTargetName, configName)
return GetWorkspaceDir(currentTargetName, configName) .. "/jni"
end
----------------------------------------------------------------------------------------------------------------------------------------------------------------
--FILE WRITING
----------------------------------------------------------------------------------------------------------------------------------------------------------------
function WriteApplicationMk(currentTarget, config)
local jniDir = GetJNIDir(currentTarget.name, config.name)
mbwriter.mkdir(jniDir)
local wsDir = GetWorkspaceDir(currentTarget.name, config.name)
local markerFile = mbfile.open(wsDir .. "/BUILD_CONFIG_" .. config.name, "w")
markerFile:close()
local makeFilename = jniDir .. "/Application.mk"
local file = mbfile.open(makeFilename, "w")
file:write("APP_MODULES := " .. currentTarget.name .. " ")
for i = 1, #currentTarget.depends do
local dependency = currentTarget.depends[i]
local path, filename, ext = mbfilepath.decompose(dependency)
file:write(filename .. " ")
end
file:write("\n\n")
if config.options.ndkoptions ~= nil then
for jOption = 1, #config.options.ndkoptions do
local keyValue = split(config.options.ndkoptions[jOption], "=")
local key = keyValue[1]
local value = keyValue[2]
file:write(key .. " := " .. value .. "\n")
end
end
file:close()
mbwriter.reportoutputfile(makeFilename)
end
function WriteAndroidMk(currentTarget, config)
local localLDLibs = {}
local localSharedLibs = {}
local localStaticLibs = {}
if currentTarget.targettype == "app" then
--Build LD lib, shared lib and static lib arrays
for i = 1, #config.libs do
local f = config.libs[i]
local path, filename, ext = mbfilepath.decompose(f)
if string.find(f, "-l") then
table.insert(localLDLibs, filename)
elseif ext == "so" then
table.insert(localSharedLibs, f)
else
table.insert(localStaticLibs, f)
end
end
end
--[[
local workspaceDir = GetWorkspaceDir(currentTarget.name, config.name);
for i = 1, #currentTarget.resources do
local f = currentTarget.resources[i]
CreateResourceDirLink(currentTarget, config, f)
end
]]
local jniDir = GetJNIDir(currentTarget.name, config.name)
mbwriter.mkdir(jniDir)
local makeFilename = jniDir .. "/Android.mk"
local file = mbfile.open(makeFilename, "w")
for i = 1, #currentTarget.depends do
local dependency = currentTarget.depends[i]
local path, filename, ext = mbfilepath.decompose(dependency)
file:write("SOURCE_ROOT := " .. jniDir .. "\n")
file:write("include $(SOURCE_ROOT)/../../../" .. filename .. "/" .. config.name .. "/jni/Android.mk\n")
file:write("include $(CLEAR_VARS)\n\n")
end
--file:write("MY_LOCAL_PATH := $(call my-dir)\n")
file:write("MY_GENERAL_FLAGS := \\\n")
--Write defines
for iDefine = 1, #config.defines do
tmp = string.gsub(config.defines[iDefine], "\"", "\\\"")
file:write(" -D" .. tmp .. " \\\n")
end
file:write("\n")
file:write("MY_LOCAL_CPPFLAGS := $(MY_GENERAL_FLAGS)\n")
file:write("MY_LOCAL_CFLAGS := $(MY_GENERAL_FLAGS)\n")
-- Add Neon Support for armeabi-v7a
file:write("ifeq ($(TARGET_ARCH_ABI),armeabi-v7a)\n")
file:write("LOCAL_ARM_NEON := true\n")
file:write("endif # TARGET_ARCH_ABI == armeabi-v7a\n")
file:write("SOURCE_ROOT := " .. mbwriter.global.currentmetamakedirabs .. "\n")
file:write("MY_LOCAL_C_INCLUDES := \\\n")
for i = 1, #config.includedirs do
file:write(" $(SOURCE_ROOT)/" .. config.includedirs[i] .. " \\\n")
end
file:write("\n")
-- Add project lib search paths
file:write("MY_LIB_SEARCH_PATHS:= \\\n")
local abi = mbutil.getkvvalue(config.options.ndkoptions, "APP_ABI")
if abi == nil then
-- TODO error
end
f = mbwriter.global.makeoutputdirabs .. "/obj/local/" .. abi
file:write(" -L" .. f .. " \\\n")
file:write("\n")
--Include static libs
for i = 1, #localStaticLibs do
local f = localStaticLibs[i]
local path, filename, ext = mbfilepath.decompose(f)
filename = string.gsub(filename, "%.a", "")
filename = mbfilepath.trimrawmarker(filename)
file:write("include $(CLEAR_VARS)\n")
file:write("LOCAL_MODULE := " .. filename .. "\n")
--file:write("LOCAL_SRC_FILES := " .. mbwriter.getoutputrelfilepath(f) .. "\n")
file:write("LOCAL_SRC_FILES := " .. mbwriter.getabsfilepath(f) .. "\n")
file:write("include $(PREBUILT_STATIC_LIBRARY)\n\n")
end
--Include shared libs
for i = 1, #localSharedLibs do
local f = localSharedLibs[i]
local path, filename, ext = mbfilepath.decompose(f)
filename = mbfilepath.trimrawmarker(filename)
file:write("include $(CLEAR_VARS)\n")
file:write("LOCAL_MODULE := " .. filename .. "\n")
--file:write("LOCAL_SRC_FILES := " .. mbwriter.getoutputrelfilepath(f) .. "\n")
file:write("LOCAL_SRC_FILES := " .. mbwriter.getabsfilepath(f) .. "\n")
file:write("include $(PREBUILT_SHARED_LIBRARY)\n\n")
end
file:write("MY_LOCAL_SRC_FILES := \\\n")
for i = 1, #currentTarget.files do
local f = currentTarget.files[i]
local ext = mbfilepath.getextension(f)
if ext == "c" or ext == "cpp" then
file:write(" $(SOURCE_ROOT)/" .. f .. "\\\n")
end
end
file:write("\n")
file:write("include $(CLEAR_VARS)\n")
file:write("LOCAL_PATH := $(MY_LOCAL_PATH)\n")
file:write("LOCAL_MODULE := " .. currentTarget.name .. "\n")
file:write("LOCAL_C_INCLUDES := $(MY_LOCAL_C_INCLUDES)\n")
file:write("LOCAL_CPPFLAGS := $(MY_LOCAL_CPPFLAGS)\n")
file:write("LOCAL_CFLAGS := $(MY_LOCAL_CFLAGS)\n")
file:write("LOCAL_SRC_FILES := $(MY_LOCAL_SRC_FILES)\n")
file:write("\n")
if currentTarget.targettype == "app" then
file:write("LOCAL_LDLIBS := $(MY_LIB_SEARCH_PATHS) $(MY_LIBS) \\\n")
for i = 1, #localLDLibs do
local f = localLDLibs[i]
local path, filename, ext = mbfilepath.decompose(f)
file:write(" " .. filename .. " \\\n")
end
file:write("\n")
file:write("LOCAL_SHARED_LIBRARIES := \\\n")
for i = 1, #localSharedLibs do
local f = localSharedLibs[i]
local path, filename, ext = mbfilepath.decompose(f)
file:write(" " .. filename .. " \\\n")
end
file:write("\n")
file:write("LOCAL_STATIC_LIBRARIES := \\\n")
for i = 1, #localStaticLibs do
local f = localStaticLibs[i]
local path, filename, ext = mbfilepath.decompose(f)
filename = string.gsub(filename, "%.a", "")
filename = mbfilepath.trimrawmarker(filename)
file:write(" " .. filename .. " \\\n")
end
for i = 1, #currentTarget.depends do
local f = currentTarget.depends[i]
local path, filename, ext = mbfilepath.decompose(f)
file:write(" " .. filename .. " \\\n")
end
file:write("\n")
file:write("include $(BUILD_SHARED_LIBRARY)\n")
elseif currentTarget.targettype == "module" or currentTarget.targettype == "staticlib" then
file:write("include $(BUILD_STATIC_LIBRARY)\n")
else
--TODO - error here
end
file:close()
mbwriter.reportoutputfile(makeFilename)
end
function WriteJNI(currentTarget, config)
WriteApplicationMk(currentTarget, config)
WriteAndroidMk(currentTarget, config)
end
----------------------------------------------------------------------------------------------------------------------------------------------------------------
--MAIN
----------------------------------------------------------------------------------------------------------------------------------------------------------------
local currentTarget = mbwriter.solution.targets[1]
for i = 1, #currentTarget.configs do
local config = currentTarget.configs[i]
g_makeOutputDirAbsRoot = mbwriter.global.makeoutputdirabs
g_makeOutputDirAbsTargetConfig = GetJNIDir(currentTarget.name, config.name)
WriteJNI(currentTarget, config)
end
| mit |
jshackley/darkstar | scripts/zones/Bastok_Markets/npcs/Ken.lua | 38 | 1395 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Ken
-- Type: Quest NPC
-- @pos -340.857 -11.003 -149.008 235
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatBastok = player:getVar("WildcatBastok");
if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,13) == false) then
player:startEvent(0x01b0);
else
player:startEvent(0x0169);
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 == 0x01b0) then
player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",13,true);
end
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Port_Bastok/npcs/Valeriano.lua | 36 | 1723 | -----------------------------------
-- Area: Port Bastok
-- NPC: Valeriano
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,VALERIANO_SHOP_DIALOG);
stock = {
0x112A, 10, --Ginger Cookie
0x43C1, 43, --Flute
0x43C3, 990, --Piccolo
0x1399, 585, --Scroll of Scop's Operetta
0x139A, 16920, --Scroll of Puppet's Operetta
0x1395, 2916, --Scroll of Fowl Aubade
0x13A3, 2059, --Scroll of Advancing March
0x13D0, 90000, --Scroll of Goddess's Hymnus
0x13B9, 27140, --Scroll of Earth Carol II
0x13BB, 28520, --Scroll of Water Carol II
0x1384,123880 --Scroll of Mage's Ballad III
}
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 |
jshackley/darkstar | scripts/globals/effects/afflatus_misery.lua | 18 | 1194 | -----------------------------------
--
-- EFFECT_AFFLATUS_MISERY
--
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:setMod(MOD_AFFLATUS_MISERY,0);
if (target:hasStatusEffect(EFFECT_AUSPICE)) then
local power = target:getStatusEffect(EFFECT_AUSPICE):getPower();
target:addMod(MOD_ENSPELL,18);
target:addMod(MOD_ENSPELL_DMG, power);
end
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
target:setMod(MOD_AFFLATUS_MISERY,0);
--Clean Up Afflatus Misery Bonuses
local accuracyBonus = effect:getSubPower();
--printf("AUSPICE: Removing Accuracy Bonus +%d!", accuracyBonus);
target:delMod(MOD_ACC, accuracyBonus);
if (target:hasStatusEffect(EFFECT_AUSPICE)) then
target:setMod(MOD_ENSPELL,0);
target:setMod(MOD_ENSPELL_DMG, 0);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Metalworks/npcs/Invincible_Shield.lua | 38 | 1383 | -----------------------------------
-- Area: Metalworks
-- NPC: Invincible Shield
-- Type: Ballista
-- @pos -51.083 -11 2.126 237
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatBastok = player:getVar("WildcatBastok");
if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,6) == false) then
player:startEvent(0x03a4);
else
player:startEvent(0x032a);
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 == 0x03a4) then
player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",6,true);
end
end;
| gpl-3.0 |
jac8/TelebitsTG | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
Ombridride/minetest-minetestforfun-server | mods/markers/init.lua | 9 | 19185 |
-- markers are useful for measuring distances and for marking areas
-- markers are protected from digging by other players for one day
-- (the protection for the *marker* auto-expires then, and it can be digged)
markers = {}
dofile(minetest.get_modpath("markers").."/config.lua");
dofile(minetest.get_modpath("markers").."/areas.lua");
dofile(minetest.get_modpath("markers").."/marker_stone.lua");
dofile(minetest.get_modpath("markers").."/land_title_register.lua");
-- returns the first area found
markers.get_area_by_pos1_pos2 = function(pos1, pos2)
for id, area in pairs(areas.areas) do
if( ((area.pos1.x == pos1.x and area.pos1.z == pos1.z )
or (area.pos1.x == pos1.x and area.pos1.z == pos2.z )
or (area.pos1.x == pos2.x and area.pos1.z == pos1.z )
or (area.pos1.x == pos2.x and area.pos1.z == pos2.z ))
and((area.pos2.x == pos1.x and area.pos2.z == pos1.z )
or (area.pos2.x == pos1.x and area.pos2.z == pos2.z )
or (area.pos2.x == pos2.x and area.pos2.z == pos1.z )
or (area.pos2.x == pos2.x and area.pos2.z == pos2.z ))) then
-- at least pos1 needs to have a hight value that fits in
if( (area.pos1.y <= pos1.y and area.pos2.y >= pos1.y)
or (area.pos1.y >= pos1.y and area.pos2.y <= pos1.y)) then
local found = area;
found[ 'id' ] = id;
return found;
end
end
end
return nil;
end
-- this function is supposed to return a text string describing the price of the land between po1 and pos2
-- You can return somethiing like "for free" or "the promise to build anything good" as well as any
-- real prices in credits or materials - it's really just a text here.
-- Make sure you do not charge the player more than what you ask here.
markers.calculate_area_price_text = function( pos1, pos2, playername )
local price = ( math.abs( pos1.x - pos2.x )+1 )
* ( math.abs( pos1.z - pos2.z )+1 );
-- * math.ceil( ( math.abs( pos1.y - pos2.y )+1 )/10);
return tostring( price )..' credits';
end
markers.marker_placed = function( pos, placer, itemstack )
if( not( pos ) or not( placer )) then
return;
end
local meta = minetest.get_meta( pos );
local name = placer:get_player_name();
meta:set_string( 'infotext', 'Marker at '..minetest.pos_to_string( pos )..
' (placed by '..tostring( name )..'). '..
'Right-click to update.');
meta:set_string( 'owner', name );
-- this allows protection of this particular marker to expire
meta:set_string( 'time', tostring( os.time()) );
local txt = '';
if( not( markers.positions[ name ] ) or #markers.positions[name]<1) then
markers.positions[ name ] = {};
markers.positions[ name ][ 1 ] = pos;
minetest.chat_send_player( name,
'First marker set to position '..
minetest.pos_to_string( markers.positions[ name ][ 1 ] )..
'. Please place a second marker to measure distance. '..
'Place four markers in a square to define an area.');
else
table.insert( markers.positions[ name ], pos );
local n = #markers.positions[ name ];
local dx = markers.positions[ name ][ n ].x - markers.positions[ name ][ n-1 ].x;
local dy = markers.positions[ name ][ n ].y - markers.positions[ name ][ n-1 ].y;
local dz = markers.positions[ name ][ n ].z - markers.positions[ name ][ n-1 ].z;
local dir_name = "unknown";
local d = 0;
if( dx == 0 and dz > 0 ) then dir_name = "north"; d = math.abs(dz);
elseif( dx == 0 and dz < 0 ) then dir_name = "south"; d = math.abs(dz);
elseif( dz == 0 and dx > 0 ) then dir_name = "east"; d = math.abs(dx);
elseif( dz == 0 and dx < 0 ) then dir_name = "west"; d = math.abs(dx);
elseif( dx == 0 and dz == 0 and dy > 0 ) then dir_name = "above"; d = math.abs(dy);
elseif( dx == 0 and dz == 0 and dy < 0 ) then dir_name = "below"; d = math.abs(dy);
else
local area = (math.abs( dx )+1)
* (math.abs( dz )+1);
local volume = area * (math.abs( dy )+1);
minetest.chat_send_player( name, 'This marker is at '..
minetest.pos_to_string( markers.positions[ name ][ n ] )..', while the last one is at '..
minetest.pos_to_string( markers.positions[ name ][ n-1 ] )..'. Distance (x/y/z): '..
tostring(math.abs(dx))..'/'..
tostring(math.abs(dy))..'/'..
tostring(math.abs(dz))..
'. Area: '..tostring( area )..' m^2. Volume: '..tostring( volume )..' m^3.');
end
-- this marker is aligned to the last one
if( d > 0 ) then
minetest.chat_send_player( name, 'Marker placed at '..minetest.pos_to_string( pos )..
'. Relative to the marker you placed before, this one is '..
tostring( d )..' m '..dir_name..'.');
end
-- make sure the list does not grow too large
if( n > markers.MAX_MARKERS and minetest.get_player_privs(name)["megabuilder"] ~= true) then
table.remove( markers.positions[ name ], 1 );
end
end
end
markers.marker_can_dig = function(pos,player)
if( not( pos ) or not( player )) then
return true;
end
local meta = minetest.get_meta( pos );
local owner = meta:get_string( 'owner' );
local time = meta:get_string( 'time' );
-- can the marker be removed?
if( not( owner )
or owner==''
or not( time )
or time==''
or (os.time() - tonumber( time )) > markers.EXPIRE_AFTER ) then
return true;
-- marker whose data got lost anyway
elseif( not( markers.positions[ owner ] )
or #markers.positions[ owner ] < 1 ) then
return true;
-- marker owned by someone else and still in use
elseif( owner ~= player:get_player_name()) then
minetest.chat_send_player( player:get_player_name(),
'Sorry, this marker belongs to '..tostring( owner )..
'. If you still want to remove it, try again in '..
( tostring( markers.EXPIRE_AFTER + tonumber( time ) - os.time()))..' seconds.');
return false;
end
return true;
end
markers.marker_after_dig_node = function(pos, oldnode, oldmetadata, digger)
if( not(oldmetadata ) or not(oldmetadata['fields'])) then
return;
end
local owner = oldmetadata['fields']['owner'];
if( not( owner )
or owner==''
or not( markers.positions[ owner ] )
or #markers.positions[ owner ] < 1 ) then
return;
end
-- remove the markers position from our table of stored positions
local found = 0;
for i,v in ipairs( markers.positions[ owner ] ) do
if( v.x == pos.x
and v.y == pos.y
and v.z == pos.z ) then
found = i;
end
end
if( found ~= 0 ) then
table.remove( markers.positions[ owner ], found );
end
return true;
end
--this function returns a min_pos and max_pos that are the corners
--of a box that contains ALL of the players active markers.
markers.get_box_from_markers = function(name)
if (not name) or (not (markers.positions[ name ][ 1 ] )) then
return {x=0,y=0,z=0},{x=1,y=1,z=1}
end
local min_pos={}
min_pos.x = markers.positions[ name ][ 1 ].x
min_pos.y = markers.positions[ name ][ 1 ].y
min_pos.z = markers.positions[ name ][ 1 ].z
local max_pos={}
max_pos.x = markers.positions[ name ][ 1 ].x
max_pos.y = markers.positions[ name ][ 1 ].y
max_pos.z = markers.positions[ name ][ 1 ].z
for i,p in ipairs( markers.positions[ name ] ) do
if p.x < min_pos.x then min_pos.x = p.x end
if p.x > max_pos.x then max_pos.x = p.x end
if p.y < min_pos.y then min_pos.y = p.y end
if p.y > max_pos.y then max_pos.y = p.y end
if p.z < min_pos.z then min_pos.z = p.z end
if p.z > max_pos.z then max_pos.z = p.z end
end
--print("getbox: min_pos.x="..min_pos.x.." y="..min_pos.y.." z="..min_pos.z)
--print(" : max_pos.x="..max_pos.x.." y="..max_pos.y.." z="..max_pos.z)
return min_pos, max_pos
end --get_box_from_markers
markers.get_marker_formspec = function(player, pos, error_msg)
local formspec = "";
local meta = minetest.get_meta( pos );
local owner = meta:get_string( 'owner' );
local name = player:get_player_name();
local formspec_info = "size[6,4]"..
"button_exit[2,2.5;1,0.5;abort;OK]"..
"textarea[1,1;4,2;info;Information;";
if( owner ~= nil and owner ~= '' and owner ~= name ) then
return formspec_info.."This marker\ncan only be used by\n"..tostring( owner )..", who\nplaced the markers.]";
end
if( not( markers.positions[ name ]) or #markers.positions[name]<1) then
return formspec_info.."Information about the positions\nof your other markers\ngot lost.\nPlease dig and place\nyour markers again!]";
end
local n = #markers.positions[ name ];
if ( n < 2 ) then
return formspec_info.."Please place 2 or more markers\n - at least one in each corner\n of your area first]";
end
local coords={}
coords[1],coords[2] = markers.get_box_from_markers(name)
-- save data
meta:set_string( 'coords', minetest.serialize( coords ) );
if( not( coords ) or #coords < 2 or not( coords[1] ) or not( coords[2] )) then
return formspec_info.."Error in markers.]";
end
-- the coordinates are set; we may present an input form now
-- has the area already been defined?
local area = markers.get_area_by_pos1_pos2( coords[1], coords[2] );
local size = (math.abs( coords[1].x - coords[2].x )+1)
* (math.abs( coords[1].z - coords[2].z )+1);
-- check if area is too large
if( markers.MAX_SIZE < size and minetest.get_player_privs(name)["megabuilder"] ~= true) then
return formspec_info.."Error: You can only protect\nareas of up to "..tostring( markers.MAX_SIZE ).."m^2.\n"..
"Your marked area is "..tostring( size ).." m^2 large.]";
end
local formspec = 'size[10,7]'..
'label[0.5,1;The area you marked extends from]'..
'label[4.7,1;'..minetest.pos_to_string( coords[ 1 ] )..' to '..minetest.pos_to_string( coords[ 2 ] )..'.]'..
'label[4.7,1.5;It spans '..tostring( math.abs( coords[1].x - coords[2].x )+1 )..
' x '..tostring( math.abs( coords[1].z - coords[2].z )+1 )..
' = '..tostring( size )..' m^2.]';
-- display the error message (if there is any)
if( error_msg ~= nil ) then
formspec = formspec..
'label[0.5,0.0;Error: ]'..
'textarea[5.0,0;4,1.5;info;;'..error_msg..']';
end
if( area and area['id'] ) then
formspec = formspec..
'label[0.5,2.0;This is area number ]'..
'label[4.7,2.0;'..tostring( area['id'] )..'.]'..
'label[0.5,2.5;It is owned by ]'..
'label[4.7,2.5;'..tostring( area['owner'] )..'.]'..
'label[0.5,3.0;The area is called ]'..
'label[4.7,3.0;'..tostring( area['name'] )..'.]'..
"button_exit[2,6.0;2,0.5;abort;OK]";
else
formspec = formspec..
-- 'label[0.5,2.0;Buying this area will cost you ]'..
-- 'label[4.7,2.0;'..markers.calculate_area_price_text( coords[1], coords[2], name )..'.]'..
'label[0.5,3.0;Your area ought to go..]'..
'label[0.5,3.5;this many blocks up:]'..
'field[5.0,4.0;1,0.5;add_height;;40]'..
'label[6.0,3.5;(above '..coords[2].y..' )]'..
'label[0.5,4.0;and this many blocks down:]'..
'field[5.0,4.5;1,0.5;add_depth;;10]'..
'label[6.0,4.0;(below '..coords[1].y..' )]'..
'label[0.5,4.5;The area shall be named]'..
'field[5.0,5.0;6,0.5;set_area_name;;please enter a name]'..
"button_exit[2,6.0;2,0.5;abort;Abort]"..
-- code the position in the "Buy area" field
"button_exit[6,6.0;2,0.5;"..minetest.pos_to_string(pos)..";Protect area]";
end
return formspec;
end
-- protect/buy an area
markers.marker_on_receive_fields = function(pos, formname, fields, sender)
if( not( pos )) then
minetest.chat_send_player( name, 'Sorry, could not find the marker you where using to access this formspec.' );
return;
end
local meta = minetest.get_meta( pos );
local name = sender:get_player_name();
local coords_string = meta:get_string( 'coords' );
if( not( coords_string ) or coords_string == '' ) then
minetest.chat_send_player( name, 'Could not find marked area. Please dig and place your markers again!');
return;
end
local coords = minetest.deserialize( coords_string );
-- do not protect areas twice
local area = markers.get_area_by_pos1_pos2( coords[1], coords[2] );
if( area ) then
minetest.chat_send_player( name, 'This area is already protected.');
return;
end
-- check input
local add_height = tonumber( fields['add_height'] );
local add_depth = tonumber( fields['add_depth'] );
local error_msg = '';
if( not( add_height ) or add_height < 0 or (add_height > markers.MAX_HEIGHT and minetest.get_player_privs(name)["megabuilder"] ~= true)) then
minetest.chat_send_player( name, 'Please enter a number between 0 and '..tostring( markers.MAX_HEIGHT )..
' in the field where the height of your area is requested. Your area will stretch that many blocks '..
'up into the sky from the position of this marker onward.');
error_msg = 'The height value\nhas to be larger than 0\nand smaller than '..tostring( markers.MAX_HEIGHT );
elseif( not( add_depth ) or add_depth < 0 or (add_depth > markers.MAX_HEIGHT and minetest.get_player_privs(name)["megabuilder"] ~= true)) then
minetest.chat_send_player( name, 'Please enter a number between 0 and '..tostring( markers.MAX_HEIGHT )..
' in the field where the depth of your area is requested. Your area will stretch that many blocks '..
'into the ground from the position of this marker onward.');
error_msg = 'The depth value\nhas to be larger than 0\nand smaller than '..tostring( markers.MAX_HEIGHT );
elseif( add_height + add_depth > markers.MAX_HEIGHT ) and minetest.get_player_privs(name)["megabuilder"] ~= true then
minetest.chat_send_player( name, 'Sorry, your area exceeds the height limit. Height and depth added have to '..
'be smaller than '..tostring( markers.MAX_HEIGHT )..'.');
error_msg = 'height + depth has to\nbe smaller than '..tostring( markers.MAX_HEIGHT )..'.'
elseif( not( fields[ 'set_area_name' ] ) or fields['set_area_name'] == 'please enter a name' ) then
minetest.chat_send_player( name, 'Please provide a name for your area, i.e. \"'..
tostring( name )..'s first house\" The name ought to describe what you intend to build here.');
error_msg = 'Please provide a\nname for your area!';
else
error_msg = nil;
end
if( error_msg ~= nil ) then
minetest.show_formspec( name, "markers:mark", markers.get_marker_formspec(sender, pos, error_msg));
return;
end
-- those coords lack the height component
local pos1 = coords[1];
local pos2 = coords[2];
-- apply height values from the formspeck
pos1.y = pos1.y - add_depth;
pos2.y = pos2.y + add_height;
pos1, pos2 = areas:sortPos( pos1, pos2 );
--minetest.chat_send_player('singleplayer','INPUT: '..minetest.serialize( pos1 )..' pos2: '..minetest.serialize( pos2 ));
minetest.log("action", "[markers] /protect invoked, owner="..name..
" areaname="..fields['set_area_name']..
" startpos="..minetest.pos_to_string(pos1)..
" endpos=" ..minetest.pos_to_string(pos2));
local canAdd, errMsg = areas:canPlayerAddArea(pos1, pos2, name)
if not canAdd then
minetest.chat_send_player(name, "You can't protect that area: "..errMsg)
minetest.show_formspec( name, "markers:mark", markers.get_marker_formspec(sender, pos, errMsg));
return
end
local id = areas:add(name, fields['set_area_name'], pos1, pos2, nil)
areas:save()
minetest.chat_send_player(name, "Area protected. ID: "..id)
minetest.show_formspec( name, "markers:mark", markers.get_marker_formspec(sender, pos, nil));
end
-- formspec input needs to be handled diffrently
markers.form_input_handler = function( player, formname, fields)
if( formname == "markers:mark" ) then
if( not(fields) or fields['abort']) then
return true;
end
--- decode the position of the marker (which is hidden in the Buy-buttons name
local pos = {};
for k, v in pairs( fields ) do
if( v == 'Protect area' ) then
pos = minetest.string_to_pos( k );
end
end
if( pos and pos.x and pos.y and pos.z ) then
markers.marker_on_receive_fields(pos, formname, fields, player);
end
return true;
elseif( formname == "markers:info"
and player
and markers.menu_data_by_player[ player:get_player_name() ] ) then
local res = markers.form_input_handler_areas( player, formname, fields);
if( res ) then
return true;
end
-- TODO
-- minetest.chat_send_player('singleplayer','MARKERS:INFO WITH '..minetest.serialize( fields ));
else
-- TODO
-- minetest.chat_send_player('singleplayer','YOU CALLED '..tostring( formname )..' WITH '..minetest.serialize( fields ));
end
return false;
end
minetest.register_on_player_receive_fields( markers.form_input_handler)
minetest.register_node("markers:mark", {
description = "Marker",
tiles = {"markers_mark.png"},
drawtype = "nodebox",
paramtype = "light",
paramtype2 = "facedir",
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=1}, --fixed on both buttons dig client crash
light_source = 1,
node_box = {
type = "fixed",
fixed = {
{ -0.1, -0.5, -0.1, 0.1, 1.5, 0.1 },
},
},
after_place_node = function(pos, placer, itemstack)
markers.marker_placed( pos, placer, itemstack );
end,
-- the node is digged immediately, so we may as well do all the work in can_dig (any wrong digs are not that critical)
can_dig = function(pos,player)
return markers.marker_can_dig( pos, player );
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
return markers.marker_after_dig_node( pos, oldnode, oldmetadata, digger );
end,
on_rightclick = function(pos, node, clicker)
minetest.show_formspec( clicker:get_player_name(),
"markers:mark",
markers.get_marker_formspec(clicker, pos, nil)
);
end,
})
minetest.register_craft({
output = "markers:mark 4",
recipe = { { "group:stick" },
{ "default:apple" },
{ "group:stick" },
} });
| unlicense |
snorecore/spooplights | LED.lua | 1 | 2916 | -- Copyright (C) 2015 snorecore
-- LED Library to drive a single RGB LED
-- Created: Sat 24th Oct 2015
local LED = {}
LED.__index = LED
-- Default values
LED.DEFAULT_RED_PIN = 5
LED.DEFAULT_BLUE_PIN = 6
LED.DEFAULT_GREEN_PIN = 7
LED.DEFAULT_PWM_FREQ = 100
-- Gamma Correction
local GAMMA = {
[0] = 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4,
5, 5, 6, 6, 7, 7, 8, 9, 9, 10, 11, 11, 12, 13, 14, 15, 16, 16, 17,
18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 30, 31, 32, 34, 35, 36, 38,
39, 41, 42, 44, 46, 47, 49, 51, 52, 54, 56, 58, 60, 61, 63, 65, 67,
69, 71, 73, 76, 78, 80, 82, 84, 87, 89, 91, 94, 96, 98, 101, 103,
106, 109, 111, 114, 117, 119, 122, 125, 128, 130, 133, 136, 139,
142, 145, 148, 151, 155, 158, 161, 164, 167, 171, 174, 177, 181,
184, 188, 191, 195, 198, 202, 206, 209, 213, 217, 221, 225, 228,
232, 236, 240, 244, 248, 252, 257, 261, 265, 269, 274, 278, 282,
287, 291, 295, 300, 304, 309, 314, 318, 323, 328, 333, 337, 342,
347, 352, 357, 362, 367, 372, 377, 382, 387, 393, 398, 403, 408,
414, 419, 425, 430, 436, 441, 447, 452, 458, 464, 470, 475, 481,
487, 493, 499, 505, 511, 517, 523, 529, 535, 542, 548, 554, 561,
567, 573, 580, 586, 593, 599, 606, 613, 619, 626, 633, 640, 647,
653, 660, 667, 674, 681, 689, 696, 703, 710, 717, 725, 732, 739,
747, 754, 762, 769, 777, 784, 792, 800, 807, 815, 823, 831, 839,
847, 855, 863, 871, 879, 887, 895, 903, 912, 920, 928, 937, 945,
954, 962, 971, 979, 988, 997, 1005, 1014, 1023
}
-- LED Constructor
local function construct(self, red, green, blue, common_anode)
self = self or {}
-- Setup properties
self.red_pin = red or LED.DEFAULT_RED_PIN
self.green_pin = green or LED.DEFAULT_GREEN_PIN
self.blue_pin = blue or LED.DEFAULT_BLUE_PIN
self.common_anode = true or common_anode
setmetatable(self, LED)
return self
end
setmetatable(LED, {__call = construct})
-- Setup PWM on LED pins
function LED:start_PWM(freq)
freq = freq or LED.DEFAULT_PWM_FREQ
-- Setup pins with LEDs off.
local col = 0
if self.common_anode then
col = 1023
end
pwm.setup(self.red_pin, freq, col)
pwm.setup(self.green_pin, freq, col)
pwm.setup(self.blue_pin, freq, col)
-- Start PWM
pwm.start(self.red_pin)
pwm.start(self.green_pin)
pwm.start(self.blue_pin)
end
function LED:stop_PWM()
pwm.close(self.red_pin)
pwm.close(self.green_pin)
pwm.close(self.blue_pin)
end
-- Set RGB LED Colour using PWM
function LED:set_col(red, green, blue)
-- PWM has 10-bit resolution, but just work with 8-bits.
-- Assuming 0-255 input.
red = GAMMA[red]
green = GAMMA[green]
blue = GAMMA[blue]
-- Using a common-anode LED so high means turned off.
if self.common_anode then
red = 1023 - red
green = 1023 - green
blue = 1023 - blue
end
pwm.setduty(self.red_pin, red)
pwm.setduty(self.blue_pin, green)
pwm.setduty(self.green_pin, blue)
end
return LED
| gpl-2.0 |
Ombridride/minetest-minetestforfun-server | mods/multitest/nodes.lua | 9 | 5694 | -- nodes
minetest.register_node("multitest:rubberblock", {
description = "Rubber Block",
tiles = {"multitest_rubberblock.png"},
groups = {oddly_breakable_by_hand=5,crumbly=3},
})
minetest.register_node("multitest:blackstone", {
description = "Blackstone",
tiles = {"multitest_blackstone.png"},
groups = {cracky=3, stone=1},
drop = 'multitest:blackcobble',
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("multitest:blackcobble", {
description = "Black Cobblestone",
tiles = {"multitest_blackcobble.png"},
groups = {cracky=2, stone=2},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("multitest:blackstone_paved", {
description = "Paved Blackstone",
tiles = {"multitest_blackstone_paved.png"},
groups = {cracky=2, stone=1},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("multitest:blackstone_paved", {
description = "Paved Blackstone",
tiles = {"multitest_blackstone_paved.png"},
groups = {cracky=2, stone=1},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("multitest:blackstone_brick", {
description = "Blackstone Bricks",
tiles = {"multitest_blackstone_brick.png"},
groups = {cracky=2, stone=1},
sounds = default.node_sound_stone_defaults(),
})
--[[ maintenant dans farming redo
minetest.register_node("multitest:hayblock", {
description = "Hay Bale",
tiles = {"multitest_hayblock_top.png", "multitest_hayblock_top.png", "multitest_hayblock.png"},
paramtype2 = "facedir",
groups = {snappy=1,flammable=2,crumbly=1,cracky=4,oddly_breakable_by_hand=2},
sounds = default.node_sound_sand_defaults(),
on_place = minetest.rotate_node
})
--]]
minetest.register_node("multitest:checkered_floor", {
description = "Checkered Floor",
tiles = {"multitest_checkered_floor.png"},
groups = {cracky=2, oddly_breakable_by_hand=4},
sounds = default.node_sound_stone_defaults(),
})
--[[
minetest.register_node("multitest:lamp", {
description = "Lamp",
tiles = {"multitest_lamp.png"},
paramtype = "light",
sunlight_propagates = true,
light_source = LIGHT_MAX-1,
groups = {snappy=2,cracky=3,oddly_breakable_by_hand=3},
sounds = default.node_sound_glass_defaults(),
})
]]
minetest.register_alias("multitest:lamp", "lantern:lantern")
minetest.register_node("multitest:andesite", {
description = "Andesite",
tiles = {"multitest_andesite.png"},
groups = {cracky=3,},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("multitest:diorite", {
description = "Diorite",
tiles = {"multitest_diorite.png"},
groups = {cracky=3,},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("multitest:granite", {
description = "Granite",
tiles = {"multitest_granite.png"},
groups = {cracky=3,},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("multitest:andesite_smooth", {
description = "Smooth Andesite",
tiles = {"multitest_andesite_smooth.png"},
groups = {cracky=3,},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("multitest:diorite_smooth", {
description = "Smooth Diorite",
tiles = {"multitest_diorite_smooth.png"},
groups = {cracky=3,},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("multitest:granite_smooth", {
description = "Smooth Granite",
tiles = {"multitest_granite_smooth.png"},
groups = {cracky=3,},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("multitest:sandstone_carved", {
description = "Carved Sandstone",
tiles = {"multitest_sandstone_carved_top.png", "multitest_sandstone_carved_top.png", "multitest_sandstone_carved.png"},
groups = {crumbly=2,cracky=4,},
sounds = default.node_sound_sand_defaults(),
})
-- stairs:stair_blackstone
stairs.register_stair_and_slab("blackstone", "multitest:blackstone",
{cracky=3, stone=1},
{"multitest_blackstone.png"},
"Blackstone Stairs",
"Blackstone Slab", nil)
stairs.register_stair_and_slab("blackcobble", "multitest:blackcobble",
{cracky=3, stone=1},
{"multitest_blackcobble.png"},
"Black Cobble Stairs",
"Black Cobble Slab", nil)
stairs.register_stair_and_slab("blackstone_bricks", "multitest:blackstone_brick",
{cracky=3, stone=1},
{"multitest_blackstone_brick.png"},
"Blackstonestone brick Stairs",
"Blackstone Brick Slab", nil)
stairs.register_stair_and_slab("blackstone_paved", "multitest:blackstone_paved",
{cracky=3, stone=1},
{"multitest_blackstone_paved.png"},
"Paved Blackstone Stairs",
"Paved Blackstone Slab", nil)
-- others
for i, v in ipairs(multitest.colors) do
minetest.register_node("multitest:carpet_"..v, {
tiles = {"wool_"..v..".png"},
description = multitest.colornames[i].."Carpet",
groups = {oddly_breakable_by_hand=2,flammable=3},
drawtype="nodebox",
paramtype = "light",
node_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, -0.4, 0.5},
}
}
})
end
minetest.register_node("multitest:door_mat", {
description = "Door Mat",
tiles = {"multitest_door_mat.png"},
inventory_image = "multitest_door_mat.png",
wield_image = "multitest_door_mat.png",
groups = {oddly_breakable_by_hand=2,flammable=3},
drawtype = "nodebox",
paramtype = "light",
paramtype2 = "facedir",
node_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.363675, 0.5, -0.454674, 0.426703},
}
}
})
minetest.register_node("multitest:sponge_block", {
description = "Sponge Block (Decorative)",
tiles = {"multitest_sponge_block.png"},
groups = {oddly_breakable_by_hand=3,},
})
| unlicense |
Keithenneu/Dota2-FullOverwrite | team_think.lua | 1 | 14309 | -------------------------------------------------------------------------------
--- AUTHOR: Nostrademous
--- GITHUB REPO: https://github.com/Nostrademous/Dota2-FullOverwrite
-------------------------------------------------------------------------------
_G._savedEnv = getfenv()
module( "team_think", package.seeall )
require( GetScriptDirectory().."/buildings_status" )
require( GetScriptDirectory().."/global_game_state" )
require( GetScriptDirectory().."/debugging" )
local gHeroVar = require( GetScriptDirectory().."/global_hero_data" )
local utils = require( GetScriptDirectory().."/utility" )
local enemyData = require( GetScriptDirectory().."/enemy_data" )
local function setHeroVar(id, var, value)
gHeroVar.SetVar(id, var, value)
end
local function getHeroVar(id, var)
return gHeroVar.GetVar(id, var)
end
local glyphTimer = -1000
-- This is at top as all item purchases are Immediate actions,
-- and therefore won't affect any other decision making.
-- Intent is to smartly determine when we should use our Glyph
-- to protect our towers.
function ConsiderGlyphUse()
local vulnerableTowers = buildings_status.GetDestroyableTowers(GetTeam())
for i, building_id in pairs(vulnerableTowers) do
local tower = buildings_status.GetHandle(GetTeam(), building_id)
if tower:GetHealth() < math.max(tower:GetMaxHealth()*0.15, 165) and tower:TimeSinceDamagedByAnyHero() < 3
and tower:TimeSinceDamagedByCreep() < 3 then
if GetGlyphCooldown() == 0 and (GameTime() - glyphTimer > 1.0) then
GetBot():ActionImmediate_Glyph()
glyphTimer = GameTime() + 5.0
end
end
end
end
-- This is at top as all item purchases are Immediate actions,
-- and therefore won't affect any other decision making.
-- Intent is to smartly determine which heroes should purchases
-- Team items like Tome of Knowledge, Wards, Dust/Sentry, and
-- even stuff like picking up Gem, Aegis, Cheese, etc.
function ConsiderTeamWideItemAcquisition(playerAssignment)
--[[
local listAlly = GetUnitList(UNIT_LIST_ALLIED_HEROES)
-- only add TeamBuy if list is 'nil' or empty
local lowestLevelAlly = nil
for _, ally in pairs(listAlly) do
if not ally:IsIllusion() and gHeroVar.HasID(ally:GetPlayerID()) then
if not lowestLevelAlly or lowestLevelAlly:GetLevel() > ally:GetLevel() then
lowestLevelAlly = ally
end
end
end
if lowestLevelAlly and #getHeroVar(lowestLevelAlly:GetPlayerID(), "TeamBuy") == 0 then
local tomes = GetItemStockCount("item_tome_of_knowledge")
while tomes > 0 do
utils.myPrint("Buying Tome of Knowledge for '"..utils.GetHeroName(lowestLevelAlly).."'")
table.insert(getHeroVar(lowestLevelAlly:GetPlayerID(), "TeamBuy"), 1, "item_tome_of_knowledge")
tomes = tomes - 1
end
end
--]]
end
-- This is at top as all courier actions are Immediate actions,
-- and therefore won't affect any other decision making.
-- Intent is to make courier use more efficient by aligning
-- the purchases of multiple localized heroes together.
function ConsiderTeamWideCourierUse()
end
-- This is a fight orchestration evaluator. It will determine,
-- based on the global picture and location of all enemy and
-- friendly units, whether we should pick a fight, whether in
-- the middle of nowhere, as part of a push/defense of a lane,
-- or even as part of an ally defense. All Heroes involved will
-- have their actionQueues filled out by this function and
-- their only responsibility will be to do those actions. Note,
-- heroes with Global skills (Invoker Sun Strike, Zeus Ult, etc.)
-- can be part of this without actually being present in the area.
function ConsiderTeamFightAssignment(playerActionQueues)
--global_game_state.GlobalFightDetermination()
end
-- Determine which lanes should be pushed and which Heroes should
-- be part of the push.
function ConsiderTeamLanePush()
end
-- Determine which lanes should be defended and which Heroes should
-- be part of the defense.
function ConsiderTeamLaneDefense()
local lane, building, numEnemies = global_game_state.DetectEnemyPush()
local listAlly = GetUnitList(UNIT_LIST_ALLIED_HEROES)
for _, ally in pairs(listAlly) do
if not ally:IsIllusion() and ally:IsBot() then
gHeroVar.SetVar(ally:GetPlayerID(), "DoDefendLane", {}) -- reset this for all
end
end
-- reset some states
global_game_state.LaneState(LANE_TOP).dontdefend = false
global_game_state.LaneState(LANE_MID).dontdefend = false
global_game_state.LaneState(LANE_BOT).dontdefend = false
if lane == nil or building == nil or numEnemies == nil then return end
local hBuilding = buildings_status.GetHandle(GetTeam(), building)
if hBuilding == nil then return end
local listAlliesAtBuilding = {}
local listAlliesCanReachBuilding = {}
local listAlliesCanTPToBuildling = {}
local defending = {}
for _, ally in pairs(listAlly) do
if not ally:IsIllusion() and ally:IsBot() and ally:IsAlive() then -- TODO: is IsAlive needed?
if gHeroVar.GetVar(ally:GetPlayerID(), "Self"):getCurrentMode():GetName() == "defendlane" then
table.insert(defending, ally)
else
if ally:GetHealth()/ally:GetMaxHealth() >= 0.5 then
local distFromBuilding = GetUnitToUnitDistance(ally, hBuilding)
local timeToReachBuilding = distFromBuilding/ally:GetCurrentMovementSpeed()
if timeToReachBuilding <= 3.0 then
table.insert(listAlliesAtBuilding, ally)
elseif timeToReachBuilding <= 10.0 then
table.insert(listAlliesCanReachBuilding, ally)
else
local haveTP = utils.HaveItem(ally, "item_tpscroll") -- TODO: check tp boots, NP tp spell (utils?)
if haveTP and haveTP:IsFullyCastable() then
table.insert(listAlliesCanTPToBuildling, ally)
end
end
end
end
end
end
local numNeeded = Max(Max(numEnemies - 1, 1) - #defending, 0)
if (#listAlliesAtBuilding + #listAlliesCanReachBuilding + #listAlliesCanTPToBuildling) >= numNeeded then
local numGoing = 0
for _, ally in pairs(defending) do -- reassign defending heros
gHeroVar.SetVar(ally:GetPlayerID(), "DoDefendLane", {lane, building, numEnemies})
end
for _, ally in pairs(listAlliesAtBuilding) do -- make everyone sitting on the tower defend it
gHeroVar.SetVar(ally:GetPlayerID(), "DoDefendLane", {lane, building, numEnemies})
numGoing = numGoing + 1
end
if numGoing < numNeeded then -- still need more?
for _, ally in pairs(listAlliesCanReachBuilding) do -- get the guys around
gHeroVar.SetVar(ally:GetPlayerID(), "DoDefendLane", {lane, building, numEnemies})
numGoing = numGoing + 1
if numGoing >= numNeeded then break end -- k, thats enough
end
end
if numGoing < numNeeded then -- still more?
for _, ally in pairs(listAlliesCanTPToBuildling) do -- tp them in
gHeroVar.SetVar(ally:GetPlayerID(), "DoDefendLane", {lane, building, numEnemies})
numGoing = numGoing + 1
if numGoing >= numNeeded then break end -- k, thats enough
end
end
else
global_game_state.LaneState(lane).dontdefend = true -- run away!
end
end
-- Determine which hero (based on their role) should farm where. By
-- default it is best to probably leave their default lane assignment,
-- but if they are getting killed repeatedly we could rotate them. This
-- also considers jungling assignments and lane rotations.
function ConsiderTeamFarmDesignation()
end
-- Determine if we should Roshan and which Heroes should be part of it.
function ConsiderTeamRoshan()
local numAlive = enemyData.GetNumAlive()
local isRoshanAlive = DotaTime() - GetRoshanKillTime() > (11*60)
if (numAlive < 3 and (GetRoshanKillTime() == 0 or isRoshanAlive)) then
-- FIXME: Implement
end
end
-- Determine if we should seek out a specific enemy for a kill attempt
-- and which Heroes should be part of the kill.
function ConsiderTeamRoam()
end
-- If we see a rune, determine if any specific Heroes should get it
-- (to fill a bottle for example). If not, the hero that saw it will
-- pick it up. Also consider obtaining Rune vision if lacking.
function ConsiderTeamRune(playerAssignment)
local listAlly = GetUnitList(UNIT_LIST_ALLIED_HEROES)
for _, rune in pairs(constants.RuneSpots) do
if GetRuneStatus(rune) == RUNE_STATUS_AVAILABLE then
local runeLoc = GetRuneSpawnLocation(rune)
local bestDist = 5000
local bestAlly = nil
for _, ally in pairs(listAlly) do
if ally:IsAlive() and not ally:IsIllusion() and ally:IsBot() then
local dist = GetUnitToLocationDistance(ally, runeLoc)
if dist < bestDist then
bestDist = dist
bestAlly = ally
end
end
end
if bestAlly then
playerAssignment[bestAlly:GetPlayerID()].GetRune = {rune, runeLoc}
end
elseif GetRuneStatus(rune) == RUNE_STATUS_MISSING then
for _, ally in pairs(listAlly) do
if not ally:IsIllusion() and ally:IsBot() then
if playerAssignment[ally:GetPlayerID()].GetRune ~= nil then
if playerAssignment[ally:GetPlayerID()].GetRune[1] == rune then
playerAssignment[ally:GetPlayerID()].GetRune = nil
end
end
end
end
end
end
end
-- If any of our Heroes needs to heal up, Shrines are an option.
-- However, we should be smart about the use and see if any other
-- friends could benefit as well rather than just being selfish.
function ConsiderTeamShrine(playerAssignment)
--[[
local bestShrine = nil
local distToShrine = 100000
local Team = GetTeam()
local listAlly = GetUnitList(UNIT_LIST_ALLIED_HEROES)
local shrineUseList = {}
-- determine which allies need to use the shrine and which shrine is best
-- for them
for _, ally in pairs(listAlly) do
if ally:IsAlive() and ally:IsBot() and not ally:IsIllusion() and ally:GetHealth()/ally:GetMaxHealth() < 0.3
and playerAssignment[ally:GetPlayerID()].UseShrine == nil then
local SJ1 = GetShrine(Team, SHRINE_JUNGLE_1)
if SJ1 and SJ1:GetHealth() > 0 and GetShrineCooldown(SJ1) == 0 then
local dist = GetUnitToUnitDistance(ally, SJ1)
if dist < distToShrine then
distToShrine = dist
bestShrine = SHRINE_JUNGLE_1
end
end
local SJ2 = GetShrine(Team, SHRINE_JUNGLE_2)
if SJ2 and SJ2:GetHealth() > 0 and GetShrineCooldown(SJ2) == 0 then
local dist = GetUnitToUnitDistance(ally, SJ2)
if dist < distToShrine then
distToShrine = dist
bestShrine = SHRINE_JUNGLE_2
end
end
local SB1 = GetShrine(Team, SHRINE_BASE_1)
if SB1 and SB1:GetHealth() > 0 and GetShrineCooldown(SB1) == 0 then
local dist = GetUnitToUnitDistance(ally, SB1)
if dist < distToShrine then
distToShrine = dist
bestShrine = SHRINE_BASE_1
end
end
local SB2 = GetShrine(Team, SHRINE_BASE_2)
if SB2 and SB2:GetHealth() > 0 and GetShrineCooldown(SB2) == 0 then
local dist = GetUnitToUnitDistance(ally, SB2)
if dist < distToShrine then
distToShrine = dist
bestShrine = SHRINE_BASE_2
end
end
local SB3 = GetShrine(Team, SHRINE_BASE_3)
if SB3 and SB3:GetHealth() > 0 and GetShrineCooldown(SB3) == 0 then
local dist = GetUnitToUnitDistance(ally, SB3)
if dist < distToShrine then
distToShrine = dist
bestShrine = SHRINE_BASE_3
end
end
local SB4 = GetShrine(Team, SHRINE_BASE_4)
if SB4 and SB4:GetHealth() > 0 and GetShrineCooldown(SB4) == 0 then
local dist = GetUnitToUnitDistance(ally, SB4)
if dist < distToShrine then
distToShrine = dist
bestShrine = SHRINE_BASE_4
end
end
local SB5 = GetShrine(Team, SHRINE_BASE_5)
if SB5 and SB5:GetHealth() > 0 and GetShrineCooldown(SB5) == 0 then
local dist = GetUnitToUnitDistance(ally, SB5)
if dist < distToShrine then
distToShrine = dist
bestShrine = SHRINE_BASE_5
end
end
if bestShrine and (ally.useShrine == nil or ally.useShrine == -1) then
if (utils.InTeamFight(GetBot(), 750) or GetBot().SelfRef:getCurrentMode():GetName() == "fighting") and distToShrine <= 400 then
table.insert(global_game_state.GetShrineState(bestShrine).pidsLookingForHeal, ally:GetPlayerID())
ally.useShrine = bestShrine
end
if (GetBot():DistanceFromFountain() + 3500) > distToShrine then
--utils.myPrint("Adding ID: '", ally:GetPlayerID(), "' to Shrine: ", bestShrine)
table.insert(global_game_state.GetShrineState(bestShrine).pidsLookingForHeal, ally:GetPlayerID())
ally.useShrine = bestShrine
end
end
end
end
--]]
end
for k,v in pairs( team_think ) do _G._savedEnv[k] = v end
| gpl-3.0 |
jshackley/darkstar | scripts/globals/items/puffball.lua | 35 | 1188 | -----------------------------------------
-- ID: 4448
-- Item: puffball
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Strength -4
-- Mind 2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4448);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, -4);
target:addMod(MOD_MND, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, -4);
target:delMod(MOD_MND, 2);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/globals/items/fire_sword.lua | 41 | 1068 | -----------------------------------------
-- ID: 16543
-- Item: Fire Sword
-- Additional Effect: Fire Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 5;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(3,10);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_FIRE, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_FIRE,0);
dmg = adjustForTarget(target,dmg,ELE_FIRE);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_FIRE,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_FIRE_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
DarkRainX/ufoai | base/ufos/ui/ufox.datatable.lua | 2 | 10046 | --!usr/bin/lua
--[[
-- @file
-- @brief DataTable builder extension
--]]
--[[
Copyright (C) 2002-2020 UFO: Alien Invasion.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
--]]
-- ufox.build_datatable Header Guard
if (ufox.datatable == nil) then
require("ufox.lua")
ufox.datatable = {
sortfunction = {
ascending = function (a, b)
if (tonumber(a[2]) ~= nil and tonumber(b[2]) ~= nil) then
return tonumber(a[2]) < tonumber(b[2])
else
return a[2] < b[2]
end
end,
descending = function (a, b)
if (tonumber(a[2]) ~= nil and tonumber(b[2]) ~= nil) then
return tonumber(b[2]) < tonumber(a[2])
else
return b[2] < a[2]
end
end,
},
sort = function (sender, field, direction)
local currentSortField = sender:child("sortField")
local currentSortDirection = sender:child("sortDirection")
-- Figure out the parameters
if (field == nil) then
return
end
-- toggle direction unless specified, default to ascending on new fields
if (direction == nil) then
if (currentSortField:text() == field:name()) then
if (currentSortDirection:text() == "ascending") then
direction = "descending"
else
direction = "ascending"
end
else
direction = "ascending"
end
end
local dataSpace = sender:child("data")
-- copy data to a temp table
local sortTable = {}
local row = dataSpace:first()
while (row ~= nil) do
local cell = row:child(field:name())
local value
if (cell == nil) then
value = ""
elseif (cell:child("value") ~= nil) then
value = cell:child("value"):text()
else
value = cell:text()
end
table.insert(sortTable, {row:name(), value})
row = row:next()
end
-- sort
if (direction == "descending") then
table.sort(sortTable, ufox.datatable.sortfunction.descending)
else
table.sort(sortTable, ufox.datatable.sortfunction.ascending)
end
-- move the nodes around
local previous = nil
for idx, record in ipairs(sortTable) do
dataSpace:move_node(dataSpace:child(record[1]), previous)
previous = dataSpace:child(record[1])
end
currentSortField:set_text(field:name())
currentSortDirection:set_text(direction)
end,
--[[
-- @brief Add header fields to the table
-- @param sender Reference to the dataTable node
-- @param fields List of (partial) header node definitions:
-- name (Required) Name of the table column
-- width (Required) Width of the column.
-- @note These field names and widths are going to be used for data cells too
--]]
add_headerFields = function (sender, fields)
local header = sender:child("header")
if (header == nil) then
ufo.print(string.format("ufox.datatable %s has no header\n", sender:name()))
return
end
if (type(fields) ~= "table") then
ufo.print("ufox.datatable:add_headerFields() was called with incompatible fields parameter\n")
return
end
local left = 0;
local node = header:first()
while (node ~= nil) do
left = left + node:width()
node = node:next()
end
local headerFieldDefaults = {
class = "string",
height = 20,
contentalign = ufo.ALIGN_CC,
on_click = function (sender)
sender:parent():parent():sort(sender)
end,
}
for i, field in pairs(fields) do
-- fill missing data
for key, value in pairs(headerFieldDefaults) do
if (field[key] == nil) then
field[key] = value
end
end
local field = ufox.build(field, header)
if (field == nil) then
ufo.print(string.format("ufox.datatable.build encountered error on creating field no. %d\n", i))
return
end
field:set_left(left)
left = left + field:width()
end
return header
end,
--[[
-- @brief Add data cells to a data row
-- @param sender data row node
-- @param cellData Table with the data cell
--]]
addCell = function (sender, cellData)
local header = sender:parent():parent():child("header")
if (header == nil) then
ufo.print("ufox.datatable has no header\n")
return
end
if (type(cellData) ~= "table") then
ufo.print(string.format("ufox.datatable %s has no data space\n", sender:name()))
return
end
if (cellData.name == nil or header:child(cellData.name) == nil) then
ufo.print(string.format("ufox.datatable tried to add data to a non-existent field\n", sender:name()))
return
end
local column = header:child(cellData.name)
local cellDefaults = {
class = "string",
left = column:left(),
top = 0,
width = column:width(),
height = sender:height(),
}
-- fill missing data
for key, value in pairs(cellDefaults) do
if (cellData[key] == nil) then
cellData[key] = value
end
end
local cell = ufox.build(cellData, sender)
return cell
end,
--[[
-- @brief Adds a datarow to the table
-- @param sender Reference to the data table node
-- @param rowData Table with row properties:
-- name (Required) name (id) of the data row
-- @param fields Array of tables with dataCell properties
-- @sa addCell
--]]
add_dataRow = function (sender, rowData, fields)
local header = sender:child("header")
if (header == nil) then
ufo.print(string.format("ufox.datatable %s has no header\n", sender:name()))
return
end
local dataSpace = sender:child("data")
if (dataSpace == nil) then
ufo.print(string.format("ufox.datatable %s has no data space\n", sender:name()))
return
end
local dataRowDefaults = {
class = "panel",
width = sender:width(),
height = 20,
addCell = ufox.datatable.addCell,
}
for key, value in pairs(dataRowDefaults) do
if (rowData[key] == nil) then
rowData[key] = value
end
end
local row = ufox.build(rowData, dataSpace)
if (row == nil) then
ufo.print("ufox.datatable:add_dataRow() was called with incompatible parameter\n")
return
end
if (type(fields) == "table") then
for i, field in ipairs(fields) do
row:addCell(field)
end
end
return row
end,
--[[
-- @brief Clears the entire datatable (both header and data)
-- @param sender UI node reference to the data table
--]]
clear = function (sender)
sender:clear_data()
sender:child("header"):remove_children()
end,
--[[
-- @brief Clears all data from the table
-- @param sender UI node reference to the data table
--]]
clear_data = function (sender)
sender:child("data"):remove_children()
end,
--[[
-- @brief Function builds a generic datatable
-- @param rootNode UI node in that the table should be created in
-- @param tableData Table describes the base node:
-- name (Required) Name of the dataTable
-- pos (Recommended) Position of the dataTable. Defaults to (0, 0)
-- size (Recommended) Size of the dataTable. Fills the entire rootNode by default
--]]
build = function (rootNode, tableData, headerProperties)
if (rootNode == nil or tableData == nil or tableData.name == nil) then
ufo.print("ufox.datatable.build was called with missing parameters\n")
return
end
local tableDefaults = {
class = "panel",
pos = {0, 0},
size = {rootNode:width(), rootNode:height()},
backgroundcolor = {0.5, 0.5, 0.5, 0.2},
{
name = "sortField",
class = "string",
text = "",
invisible = true,
},
{
name = "sortDirection",
class = "string",
text = "",
invisible = true,
},
{
name = "selected",
class = "string",
text = "",
invisible = true,
},
}
for key, value in pairs(tableDefaults) do
if (tableData[key] == nil) then
tableData[key] = value
end
end
local dataTable = ufox.build(tableData, rootNode)
if (dataTable == nil) then
ufo.print("ufox.datatable.build failed due to incompatible parameters\n")
return
end
local header = ufox.build({
name = "header",
class = "panel",
pos = {0, 0},
size = {dataTable:width(), 20},
backgroundcolor = {0.527, 0.6, 0.21, 0.2},
}, dataTable)
-- Allow override properties
if (headerProperties ~= nil) and (type(headerProperties) == "table") then
ufox.build_properties(headerProperties, dataTable, header)
end
-- add data space
ufox.build_properties({
{
name = "data",
class = "panel",
pos = {0, header:height()},
size = {dataTable:width() - 20, dataTable:height() - header:height()},
layout = ufo.LAYOUT_TOP_DOWN_FLOW,
wheelscrollable = true,
on_viewchange = function (sender)
local scrollbar = sender:parent():child("data_scrollbar")
scrollbar:set_fullsize(sender:fullsize())
scrollbar:set_current(sender:viewpos())
scrollbar:set_viewsize(sender:viewsize())
end,
on_wheel = function (sender)
local scrollbar = sender:parent():child("data_scrollbar")
scrollbar:set_current(sender:viewpos())
end,
},
{
name = "data_scrollbar",
class = "vscrollbar",
image = "ui/scrollbar_v",
pos = {dataTable:width() - 20, 20},
height = (dataTable:height() - 20),
current = 0,
viewsize = 10,
fullsize = 0,
autoshowscroll = true,
on_change = function (sender)
local panel = sender:parent():child("data")
panel:set_viewpos(sender:current())
end,
},
-- Add commands
add_headerFields = ufox.datatable.add_headerFields,
clear = ufox.datatable.clear,
clear_data = ufox.datatable.clear_data,
add_dataRow = ufox.datatable.add_dataRow,
sort = ufox.datatable.sort,
}, rootnode, dataTable)
ufox.build_properties({
}, rootnode, dataTable)
return dataTable
end,
}
-- ufox.datatable Header Guard
end
| gpl-2.0 |
jshackley/darkstar | scripts/globals/items/bluetail.lua | 18 | 1257 | -----------------------------------------
-- ID: 4399
-- Item: Bluetail
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 3
-- Mind -5
-----------------------------------------
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,4399);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 3);
target:addMod(MOD_MND, -5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 3);
target:delMod(MOD_MND, -5);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/globals/items/inferno_sword.lua | 42 | 1071 | -----------------------------------------
-- ID: 16594
-- Item: Inferno Sword
-- Additional Effect: Fire Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 5;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(3,10);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_FIRE, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_FIRE,0);
dmg = adjustForTarget(target,dmg,ELE_FIRE);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_FIRE,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_FIRE_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
opentibia/server | data/scripts/spells/attack/energy_wave.lua | 3 | 1115 | local energyWave = Spell:new("Energy Wave")
energyWave.words = "exevo mort hur"
energyWave.vocation = {"Sorcerer", "Master Sorcerer"}
energyWave.damageType = COMBAT_ENERGYDAMAGE
energyWave.level = 38
energyWave.magicLevel = 40
energyWave.mana = 170
energyWave.aggressive = true
energyWave.areaEffect = MAGIC_EFFECT_ENERGY_AREA
energyWave.area =
{
{" ", " ", " ", " ", "n", "n", "n", " ", " ", " ", " "},
{" ", " ", " ", " ", "n", "n", "n", " ", " ", " ", " "},
{" ", " ", " ", " ", "n", "n", "n", " ", " ", " ", " "},
{" ", " ", " ", " ", " ", "n", " ", " ", " ", " ", " "},
{"w", "w", "w", " ", " ", "n", " ", " ", "e", "e", "e"},
{"w", "w", "w", "w", "w", " ", "e", "e", "e", "e", "e"},
{"w", "w", "w", " ", " ", "s", " ", " ", "e", "e", "e"},
{" ", " ", " ", " ", " ", "s", " ", " ", " ", " ", " "},
{" ", " ", " ", " ", "s", "s", "s", " ", " ", " ", " "},
{" ", " ", " ", " ", "s", "s", "s", " ", " ", " ", " "},
{" ", " ", " ", " ", "s", "s", "s", " ", " ", " ", " "},
}
energyWave.formula = formulaLevelMagic(0, 4.5, 0, 9.0)
energyWave:register()
| gpl-2.0 |
babak136222/babakgroup | bot/utils.lua | 494 | 23873 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(msg.to.id)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local groups = 'groups'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(msg.to.id)] then
var = true
end
return var
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list !\n\n"
for k,v in pairs(list) do
local user_info = redis:hgetall('user:'..v)
if user_info and user_info.print_name then
text = text..k.." - "..string.gsub(user_info.print_name, "_", " ").." ["..v.."]\n"
else
text = text..k.." - "..v.."\n"
end
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "global bans !\n\n"
for k,v in pairs(list) do
local user_info = redis:hgetall('user:'..v)
if user_info and user_info.print_name then
text = text..k.." - "..string.gsub(user_info.print_name, "_", " ").." ["..v.."]\n"
else
text = text..k.." - "..v.."\n"
end
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "User "..result.from.id.." Unbanned")
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered")
else
return 'Use This in Your Groups'
end
end
| gpl-2.0 |
luastoned/turbo | turbo/signal.lua | 7 | 6575 | --- Turbo.lua Signal Module
--
-- Copyright John Abrahamsen 2011, 2012, 2013 < JhnAbrhmsn@gmail.com >
--
-- "Permission is hereby granted, free of charge, to any person obtaining a copy of
-- this software and associated documentation files (the "Software"), to deal in
-- the Software without restriction, including without limitation the rights to
-- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-- of the Software, and to permit persons to whom the Software is furnished to do
-- so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE."
local ffi = require "ffi"
require "turbo.cdef"
local platform = require "turbo.platform"
if ffi.arch == "mipsel" then
return {
signal = ffi.C.signal
-- For sigprocmask(2)
, SIG_BLOCK = 1
, SIG_UNBLOCK = 2
, SIG_SETMASK = 3
-- Fake signal functions.
, SIG_ERR = ffi.cast("sighandler_t", -1) --[[ Error return. ]]
, SIG_DFL = ffi.cast("sighandler_t", 0) --[[ Default action. ]]
, SIG_IGN = ffi.cast("sighandler_t", 1) --[[ Ignore signal. ]]
-- Signals.
, SIGHUP = 1 --[[ Hangup (POSIX). ]]
, SIGINT = 2 --[[ Interrupt (ANSI). ]]
, SIGQUIT = 3 --[[ Quit (POSIX). ]]
, SIGILL = 4 --[[ Illegal instruction (ANSI). ]]
, SIGTRAP = 5 --[[ Trace trap (POSIX). ]]
, SIGIOT = 6 --[[ IOT trap (4.2 BSD). ]]
, SIGABRT = SIGIOT --[[ Abort (ANSI). ]]
, SIGBUS = 10 --[[ BUS error (4.2 BSD). ]]
, SIGFPE = 8 --[[ Floating-point exception (ANSI). ]]
, SIGKILL = 9 --[[ Kill, unblockable (POSIX). ]]
, SIGUSR1 = 16 --[[ User-defined signal 1 (POSIX). ]]
, SIGSEGV = 11 --[[ Segmentation violation (ANSI). ]]
, SIGUSR2 = 17 --[[ User-defined signal 2 (POSIX). ]]
, SIGPIPE = 13 --[[ Broken pipe (POSIX). ]]
, SIGALRM = 14 --[[ Alarm clock (POSIX). ]]
, SIGTERM = 15 --[[ Termination (ANSI). ]]
, SIGSTKFLT = 16 --[[ Stack fault. ]]
, SIGCLD = SIGCHLD --[[ Same as SIGCHLD (System V). ]]
, SIGCHLD = 18 --[[ Child status has changed (POSIX). ]]
, SIGCONT = 25 --[[ Continue (POSIX). ]]
, SIGSTOP = 23 --[[ Stop, unblockable (POSIX). ]]
, SIGTSTP = 24 --[[ Keyboard stop (POSIX). ]]
, SIGTTIN = 26 --[[ Background read from tty (POSIX). ]]
, SIGTTOU = 27 --[[ Background write to tty (POSIX). ]]
, SIGURG = 21 --[[ Urgent condition on socket (4.2 BSD). ]]
, SIGXCPU = 30 --[[ CPU limit exceeded (4.2 BSD). ]]
, SIGXFSZ = 31 --[[ File size limit exceeded (4.2 BSD). ]]
, SIGVTALRM = 28 --[[ Virtual alarm clock (4.2 BSD). ]]
, SIGPROF = 29 --[[ Profiling alarm clock (4.2 BSD). ]]
, SIGWINCH = 20 --[[ Window size change (4.3 BSD, Sun). ]]
, SIGIO = 22 --[[ I/O now possible (4.2 BSD). ]]
, SIGPOLL = SIGIO --[[ Pollable event occurred (System V). ]]
, SIGPWR = 19 --[[ Power failure restart (System V). ]]
, SIGSYS = 12 --[[ Bad system call. ]]
-- , SIGUNUSED = 31 --[[ Not defined in MIPSEL ]]
, _NSIG = 128 --[[ Biggest signal number + 1 (including real-time signals). ]]
}
else
return {
signal = ffi.C.signal
-- For sigprocmask(2)
, SIG_BLOCK = 0
, SIG_UNBLOCK = 1
, SIG_SETMASK = 2
-- Fake signal functions.
, SIG_ERR = ffi.cast("sighandler_t", -1) --[[ Error return. ]]
, SIG_DFL = ffi.cast("sighandler_t", 0) --[[ Default action. ]]
, SIG_IGN = ffi.cast("sighandler_t", 1) --[[ Ignore signal. ]]
-- Signals.
, SIGHUP = 1 --[[ Hangup (POSIX). ]]
, SIGINT = 2 --[[ Interrupt (ANSI). ]]
, SIGQUIT = 3 --[[ Quit (POSIX). ]]
, SIGILL = 4 --[[ Illegal instruction (ANSI). ]]
, SIGTRAP = 5 --[[ Trace trap (POSIX). ]]
, SIGABRT = 6 --[[ Abort (ANSI). ]]
, SIGIOT = 6 --[[ IOT trap (4.2 BSD). ]]
, SIGBUS = 7 --[[ BUS error (4.2 BSD). ]]
, SIGFPE = 8 --[[ Floating-point exception (ANSI). ]]
, SIGKILL = 9 --[[ Kill, unblockable (POSIX). ]]
, SIGUSR1 = 10 --[[ User-defined signal 1 (POSIX). ]]
, SIGSEGV = 11 --[[ Segmentation violation (ANSI). ]]
, SIGUSR2 = 12 --[[ User-defined signal 2 (POSIX). ]]
, SIGPIPE = 13 --[[ Broken pipe (POSIX). ]]
, SIGALRM = 14 --[[ Alarm clock (POSIX). ]]
, SIGTERM = 15 --[[ Termination (ANSI). ]]
, SIGSTKFLT = 16 --[[ Stack fault. ]]
, SIGCLD = SIGCHLD --[[ Same as SIGCHLD (System V). ]]
, SIGCHLD = 17 --[[ Child status has changed (POSIX). ]]
, SIGCONT = 18 --[[ Continue (POSIX). ]]
, SIGSTOP = 19 --[[ Stop, unblockable (POSIX). ]]
, SIGTSTP = 20 --[[ Keyboard stop (POSIX). ]]
, SIGTTIN = 21 --[[ Background read from tty (POSIX). ]]
, SIGTTOU = 22 --[[ Background write to tty (POSIX). ]]
, SIGURG = 23 --[[ Urgent condition on socket (4.2 BSD). ]]
, SIGXCPU = 24 --[[ CPU limit exceeded (4.2 BSD). ]]
, SIGXFSZ = 25 --[[ File size limit exceeded (4.2 BSD). ]]
, SIGVTALRM = 26 --[[ Virtual alarm clock (4.2 BSD). ]]
, SIGPROF = 27 --[[ Profiling alarm clock (4.2 BSD). ]]
, SIGWINCH = 28 --[[ Window size change (4.3 BSD, Sun). ]]
, SIGPOLL = SIGIO --[[ Pollable event occurred (System V). ]]
, SIGIO = 29 --[[ I/O now possible (4.2 BSD). ]]
, SIGPWR = 30 --[[ Power failure restart (System V). ]]
, SIGSYS = 31 --[[ Bad system call. ]]
, SIGUNUSED = 31
, _NSIG = 65 --[[ Biggest signal number + 1 (including real-time signals). ]]
}
end | apache-2.0 |
jshackley/darkstar | scripts/zones/Lower_Delkfutts_Tower/Zone.lua | 17 | 3688 | -----------------------------------
--
-- Zone: Lower_Delkfutts_Tower (184)
--
-----------------------------------
package.loaded["scripts/zones/Lower_Delkfutts_Tower/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/zone");
require("scripts/globals/missions");
require("scripts/zones/Lower_Delkfutts_Tower/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local tomes = {17531228,17531229,17531230};
SetGroundsTome(tomes);
zone:registerRegion(1, 403, -34, 83, 409, -33, 89); -- Third Floor G-6 porter to Middle Delkfutt's Tower
zone:registerRegion(2, 390, -34, -49, 397, -33, -43); -- Third Floor F-10 porter to Middle Delkfutt's Tower "1"
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;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(460.022,-1.77,-103.442,188);
end
if (player:getCurrentMission(ZILART) == RETURN_TO_DELKFUTTS_TOWER and player:getVar("ZilartStatus") <= 1) then
cs = 0x000f;
elseif (ENABLE_COP == 1 and prevZone == 126 and player:getCurrentMission(COP) == ANCIENT_FLAMES_BECKON) then
cs = 0x0016;
elseif (player:getCurrentMission(ACP) == BORN_OF_HER_NIGHTMARES and prevZone == 126) then
cs = 0x0022;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
switch (region:GetRegionID()): caseof
{
[1] = function (x)
player:setVar("option",1);
player:startEvent(4);
end,
[2] = function (x)
player:setVar("option",2);
player:startEvent(4);
end,
}
end;
-----------------------------------
-- onRegionLeave
-----------------------------------
function onRegionLeave(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x000f) then
player:setVar("ZilartStatus",2);
elseif (csid == 0x0004 and option == 1) then
if (player:getVar("option") == 1) then
player:setPos(-28, -48, 80, 111, 157);
else
player:setPos(-51, -48, -40, 246, 157);
end
player:setVar("option",0);
elseif (csid == 0x0004 and (option == 0 or option >= 3)) then
player:setVar("option",0);
elseif (csid == 0x0016) then
player:startEvent(0x0024);
elseif (csid == 0x0022) then
player:completeMission(ACP,BORN_OF_HER_NIGHTMARES);
player:addMission(ACP,BANISHING_THE_ECHO);
elseif (csid == 0x0024) then
player:startEvent(0x0025);
elseif (csid == 0x0025) then
player:startEvent(0x0026);
elseif (csid == 0x0026) then
player:startEvent(0x0027);
elseif (csid == 0x0027) then
player:completeMission(COP,ANCIENT_FLAMES_BECKON);
player:addMission(COP,THE_RITES_OF_LIFE);
player:setVar("COP1",1);
end
end; | gpl-3.0 |
elbamos/nn | Max.lua | 4 | 2174 | local Max, parent = torch.class('nn.Max', 'nn.Module')
function Max:__init(dimension, nInputDims)
parent.__init(self)
dimension = dimension or 1
self.dimension = dimension
-- do not assign default value to nInputDims or it will break backward compatibility
self.nInputDims = nInputDims
end
function Max:_getPositiveDimension(input)
local dimension = self.dimension
if dimension < 0 then
dimension = input:dim() + dimension + 1
elseif self.nInputDims and input:dim()==(self.nInputDims+1) then
dimension = dimension + 1
end
return dimension
end
function Max:_lazyInit()
self._output = self._output or self.output.new()
self._indices = self._indices or
(torch.type(self.output) == 'torch.CudaTensor' and torch.CudaTensor() or torch.LongTensor())
end
function Max:updateOutput(input)
self:_lazyInit()
local dimension = self:_getPositiveDimension(input)
torch.max(self._output, self._indices, input, dimension)
if input:dim() > 1 then
self.output = self._output:select(dimension, 1)
else
self.output = self._output
end
return self.output
end
function Max:updateGradInput(input, gradOutput)
self:_lazyInit()
local dimension = self:_getPositiveDimension(input)
local gradOutputView
if input:dim() > 1 then
gradOutputView = nn.utils.addSingletonDimension(gradOutput, dimension)
else
gradOutputView = gradOutput
end
self.gradInput:resizeAs(input):zero():scatter(dimension, self._indices, gradOutputView)
return self.gradInput
end
function Max:type(type, tensorCache)
-- torch.max expects a LongTensor as indices, whereas cutorch.max expects a CudaTensor.
if type == 'torch.CudaTensor' then
parent.type(self, type, tensorCache)
else
-- self._indices must be a LongTensor. Setting it to nil temporarily avoids
-- unnecessary memory allocations.
local indices
indices, self._indices = self._indices, nil
parent.type(self, type, tensorCache)
self._indices = indices and indices:long() or nil
end
return self
end
function Max:clearState()
nn.utils.clear(self, '_indices', '_output')
return parent.clearState(self)
end
| bsd-3-clause |
jshackley/darkstar | scripts/globals/spells/hyoton_san.lua | 17 | 1619 | -----------------------------------------
-- Spell: Hyoton: San
-- Deals ice damage to an enemy and lowers its resistance against fire.
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
--doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus)
local duration = 15 + caster:getMerit(MERIT_HYOTON_EFFECT) -- T1 bonus debuff duration
local bonusAcc = 0;
local bonusMab = caster:getMerit(MERIT_HYOTON_EFFECT) + caster:getMod(MOD_NIN_NUKE_BONUS); -- T1 mag atk + "enhances Ninjustu damage" mod
if(caster:getMerit(MERIT_HYOTON_SAN) ~= 0) then -- T2 mag atk/mag acc, don't want to give a penalty to entities that can cast this without merits
bonusMab = bonusMab + caster:getMerit(MERIT_HYOTON_SAN) - 5; -- merit gives 5 power but no bonus with one invest, thus subtract 5
bonusAcc = bonusAcc + caster:getMerit(MERIT_HYOTON_SAN) - 5;
end;
if (caster:isBehind(target,15) and caster:hasStatusEffect(EFFECT_INNIN)) then -- Innin mag atk bonus from behind, guesstimating angle at 15 degrees
bonusMab = bonusMab + caster:getStatusEffect(EFFECT_INNIN):getPower();
end
local dmg = doNinjutsuNuke(134,1,caster,spell,target,false,bonusAcc,bonusMab);
handleNinjutsuDebuff(caster,target,spell,30,duration,MOD_FIRERES);
return dmg;
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/items/pot-au-feu_+1.lua | 32 | 1707 | -----------------------------------------
-- ID: 5753
-- Item: Pot-au-feu
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Strength 4
-- Agility 4
-- Intelligence -3
-- Ranged Attk % 16 Cap 65
-- Ranged ACC % 11 Cap 55
-- Enmity -3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5753);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 4);
target:addMod(MOD_AGI, 4);
target:addMod(MOD_INT, -3);
target:addMod(MOD_FOOD_RATTP, 16);
target:addMod(MOD_FOOD_RATT_CAP, 65);
target:addMod(MOD_FOOD_RACCP, 11);
target:addMod(MOD_FOOD_RACC_CAP, 55);
target:addMod(MOD_ENMITY, -3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 4);
target:delMod(MOD_AGI, 4);
target:delMod(MOD_INT, -3);
target:delMod(MOD_FOOD_RATTP, 16);
target:delMod(MOD_FOOD_RATT_CAP, 65);
target:delMod(MOD_FOOD_RACCP, 11);
target:delMod(MOD_FOOD_RACC_CAP, 55);
target:delMod(MOD_ENMITY, -3);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Bastok_Markets/npcs/Brygid.lua | 17 | 6299 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Brygid
-- Start & Finishes Quest: Brygid the Stylist & Brygid the Stylist Returns
-- Involved in Quests: Riding on the Clouds
-- @zone 235
-- @pos -90 -4 -108
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/keyitems");
require("scripts/globals/equipment");
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/zones/Bastok_Markets/TextIDs");
body_list = {12554,13712,12594,13723,12603,13699,12610,13783,12572,12611,13796,12571,13750,12604,13752,12544,13730,12578,12553,12595}
legs_list = {12829,12800,12866,12809,12810,12850,12828,12859,12837,14243,12838,12867,12827,12836,12860,12851}
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local BrygidReturns = player:getQuestStatus(BASTOK,BRYGID_THE_STYLIST_RETURNS);
local wantsSubligar = player:getVar("BrygidWantsSubligar");
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_2") == 3) then
if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_2",0);
player:tradeComplete();
player:addKeyItem(SMILING_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SMILING_STONE);
end
elseif (BrygidReturns == QUEST_ACCEPTED and wantsSubligar ~= 0) then
if (wantsSubligar==13) then
if (trade:getItemCount() == 1 and trade:hasItemQty(15375+wantsSubligar,1)) then
player:tradeComplete();
player:startEvent(383);
end
else
if (trade:getItemCount() == 1 and trade:hasItemQty(15374+wantsSubligar,1)) then
player:tradeComplete();
player:startEvent(383);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local BrygidTheStylist = player:getQuestStatus(BASTOK,BRYGID_THE_STYLIST);
local BrygidReturns = player:getQuestStatus(BASTOK,BRYGID_THE_STYLIST_RETURNS);
local head = player:getEquipID(SLOT_HEAD);
local body = player:getEquipID(SLOT_BODY);
local hands = player:getEquipID(SLOT_HANDS);
local legs = player:getEquipID(SLOT_LEGS);
local feet = player:getEquipID(SLOT_FEET);
local getBody = player:getVar("BrygidGetBody");
local getLegs = player:getVar("BrygidGetLegs");
local wantsSubligar = player:getVar("BrygidWantsSubligar");
local BrygidSet = 0;
if (body == 12600 and legs == 12832) then BrygidSet = 1 end;
if (BrygidTheStylist == QUEST_ACCEPTED and BrygidSet == 1) then
player:startEvent(0x0137);
elseif ((BrygidReturns ~= QUEST_ACCEPTED and BrygidTheStylist == QUEST_COMPLETED) and
(isArtifactArmor(head) or isArtifactArmor(body) or isArtifactArmor(hands)
or isArtifactArmor(legs) or isArtifactArmor(feet))) then
-- Randomize and store sets here
repeat
getBody = body_list[math.random(1,20)];
until(player:canEquipItem(getBody,false))
repeat
getLegs = legs_list[math.random(1,16)];
until(player:canEquipItem(getLegs,false))
player:setVar("BrygidGetBody",getBody);
player:setVar("BrygidGetLegs",getLegs);
--printf("Body %u Legs %u\n",getBody,getLegs);
player:startEvent(380,BrygidSet,getBody,getLegs,player:getMainJob());
elseif (BrygidReturns == QUEST_ACCEPTED and body == getBody and legs == getLegs and wantsSubligar == 0) then
-- Have the right equips, proceed with quest
player:startEvent(382);
elseif (BrygidReturns == QUEST_ACCEPTED and wantsSubligar == 0) then
-- Remind player what they need to wear
player:startEvent(381,BrygidSet,getBody,getLegs,player:getMainJob());
elseif (BrygidReturns == QUEST_ACCEPTED and wantsSubligar ~= 0) then
-- Remind player what subligar they need to turn in and the reward
if (wantsSubligar==13) then
player:startEvent(385,0,14400+wantsSubligar,15375+wantsSubligar);
else
player:startEvent(385,0,14400+wantsSubligar,15374+wantsSubligar);
end
elseif (BrygidTheStylist ~= QUEST_COMPLETED) then
player:startEvent(0x0136);
else
player:startEvent(0x0077);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 382) then
local canEquip = 0;
local hasBody = 0;
if (player:canEquipItem(14400+option,true)) then canEquip = 1; end
if not(player:hasItem(14400+option)) then hasBody = 1; end
player:updateEvent(0,option-1,hasBody,canEquip);
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
local wantsSubligar = player:getVar("BrygidWantsSubligar");
if (csid == 0x0136 and player:getQuestStatus(BASTOK,BRYGID_THE_STYLIST) == QUEST_AVAILABLE) then
player:addQuest(BASTOK,BRYGID_THE_STYLIST);
elseif (csid == 0x0137) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12720);
else
player:addTitle(BRYGIDAPPROVED);
player:addItem(12720);
player:messageSpecial(ITEM_OBTAINED,12720);
player:addFame(BASTOK,BAS_FAME*30);
player:completeQuest(BASTOK,BRYGID_THE_STYLIST);
end
elseif (csid == 380) then
player:delQuest(BASTOK,BRYGID_THE_STYLIST_RETURNS);
player:addQuest(BASTOK,BRYGID_THE_STYLIST_RETURNS);
elseif (csid == 382 and option ~= 99) then
player:setVar("BrygidWantsSubligar",option);
elseif (csid == 383) then
player:setVar("BrygidGetBody",0);
player:setVar("BrygidGetLegs",0);
player:setVar("BrygidWantsSubligar",0);
player:addTitle(BASTOKS_SECOND_BEST_DRESSED);
player:addItem(14400+wantsSubligar);
player:messageSpecial(ITEM_OBTAINED,14400+wantsSubligar);
player:addFame(BASTOK,BAS_FAME*30);
player:completeQuest(BASTOK,BRYGID_THE_STYLIST_RETURNS);
end
end; | gpl-3.0 |
Ombridride/minetest-minetestforfun-server | mods/WorldEdit/worldedit_infinity/init.lua | 18 | 2775 | worldedit = rawget(_G, "worldedit") or {}
local minetest = minetest --local copy of global
local get_pointed = function(pos, nearest, distance)
if distance > 100 then
return false
end
--check for collision with node
local nodename = minetest.get_node(pos).name
if nodename ~= "air"
and nodename ~= "default:water_source"
and nodename ~= "default:water_flowing" then
if nodename ~= "ignore" then
return nearest
end
return false
end
end
local use = function(itemstack, user, pointed_thing)
if pointed_thing.type == "nothing" then --pointing at nothing
local placepos = worldedit.raytrace(user:getpos(), user:get_look_dir(), get_pointed)
if placepos then --extended reach
pointed_thing.type = "node"
pointed_thing.under = nil --wip
pointed_thing.above = nil --wip
end
end
return minetest.item_place_node(itemstack, user, pointed_thing)
end
--
worldedit.raytrace = function(pos, dir, callback)
local base = {x=math.floor(pos.x), y=math.floor(pos.y), z=math.floor(pos.z)}
local stepx, stepy, stepz = 0, 0, 0
local componentx, componenty, componentz = 0, 0, 0
local intersectx, intersecty, intersectz = 0, 0, 0
if dir.x == 0 then
intersectx = math.huge
elseif dir.x > 0 then
stepx = 1
componentx = 1 / dir.x
intersectx = ((base.x - pos.x) + 1) * componentx
else
stepx = -1
componentx = 1 / -dir.x
intersectx = (pos.x - base.x) * componentx
end
if dir.y == 0 then
intersecty = math.huge
elseif dir.y > 0 then
stepy = 1
componenty = 1 / dir.y
intersecty = ((base.y - pos.y) + 1) * componenty
else
stepy = -1
componenty = 1 / -dir.y
intersecty = (pos.y - base.y) * componenty
end
if dir.z == 0 then
intersectz = math.huge
elseif dir.z > 0 then
stepz = 1
componentz = 1 / dir.z
intersectz = ((base.z - pos.z) + 1) * componentz
else
stepz = -1
componentz = 1 / -dir.z
intersectz = (pos.z - base.z) * componentz
end
local distance = 0
local nearest = {x=base.x, y=base.y, z=base.z}
while true do
local values = {callback(base, nearest, distance)}
if #values > 0 then
return unpack(values)
end
nearest.x, nearest.y, nearest.z = base.x, base.y, base.z
if intersectx < intersecty then
if intersectx < intersectz then
base.x = base.x + stepx
distance = intersectx
intersectx = intersectx + componentx
else
base.z = base.z + stepz
distance = intersectz
intersectz = intersectz + componentz
end
elseif intersecty < intersectz then
base.y = base.y + stepy
distance = intersecty
intersecty = intersecty + componenty
else
base.z = base.z + stepz
distance = intersectz
intersectz = intersectz + componentz
end
end
end
| unlicense |
tridge/ardupilot | libraries/AP_Scripting/examples/Mission_test.lua | 22 | 1972 | -- This script is a test for AP_Mission bindings
local last_mission_index = mission:get_current_nav_index()
function update() -- this is the loop which periodically runs
-- check for scripting DO commands in the mission
local time_ms, param1, param2, param3, param4 = mission_receive()
if time_ms then
gcs:send_text(0, string.format("Scripting CMD @ %u ms, %i, %0.2f, %0.2f, %0.2f", time_ms:tofloat(), param1, param2, param3, param4))
end
local mission_state = mission:state()
-- make sure the mission is running
if mission_state == mission.MISSION_COMPLETE then
gcs:send_text(0, "LUA: Mission Complete")
return update, 1000 -- reschedules the loop
elseif mission_state == mission.MISSION_STOPPED then
gcs:send_text(0, "LUA: Mission stopped")
return update, 1000 -- reschedules the loop
end
local mission_index = mission:get_current_nav_index()
-- see if we have changed since we last checked
if mission_index ~= last_mission_index then
gcs:send_text(0, "LUA: New Mission Item") -- we spotted a change
-- print the current and previous nav commands
gcs:send_text(0, string.format("Prev: %d, Current: %d",mission:get_prev_nav_cmd_id(),mission:get_current_nav_id()))
last_mission_index = mission_index;
-- num commands includes home so - 1
local mission_length = mission:num_commands() - 1
if mission_length > 1 and mission_index == mission_length then
local jump_to = 1
if mission_length > 2 then
-- jump back to a random mission item
jump_to = math.random(mission_length - 1) -- no point jump to the end so - 1
end
if mission:set_current_cmd(jump_to) then
gcs:send_text(0, string.format("LUA: jumped to mission item %d",jump_to))
else
gcs:send_text(0, "LUA: mission item jump failed")
end
end
end
return update, 1000 -- reschedules the loop
end
return update() -- run immediately before starting to reschedule
| gpl-3.0 |
hanxi/quick-cocos2d-x-2048 | scripts/scenes/MainScene.lua | 1 | 7725 | --[[=============================================================================
# FileName: MainScene.lua
# Desc: mainScene for 2048 game
# full edition in https://github.com/hanxi/quick-cocos2d-x-2048/tree/release
# Author: hanxi
# Email: hanxi.info@gmail.com
# HomePage: http://www.hanxi.info
# Version: 0.0.1
# LastChange: 2014-05-09 09:13:11
# History:
=============================================================================]]
local totalScore = 0
local bestScore = 0
local WINSTR = ""
local touchStart={0,0}
local configFile = device.writablePath.."hxgame.config"
local MainScene = class("MainScene", function()
return display.newScene("MainScene")
end)
local function doOpList(op_list)
for _,op in ipairs(op_list or {}) do
local o = op[1]
if o=='setnum' then
local i,j,num = op[2],op[3],op[4]
setnum(gridShow[i][j],num,i,j)
end
end
end
function getPosFormIdx(mx,my)
local cellsize=150 -- cell size
local cdis = 2*cellsize-cellsize/2
local origin = {x=display.cx-cdis,y=display.cy+cdis}
local x = (my-1)*cellsize+origin.x
local y = -(mx-1)*cellsize+origin.y - 100
return x,y
end
function MainScene:show(cell,mx,my)
local x,y = getPosFormIdx(mx,my)
local bsz = cell.backgroundsize/2
cell.background:setPosition(ccp(x-bsz,y-bsz))
self:addChild(cell.background)
cell.num:align(display.CENTER,x,y):addTo(self)
end
local colors = {
[-1] = ccc4(0xee, 0xe4, 0xda, 100),
[0] = ccc3(0xee, 0xe4, 0xda),
[2] = ccc3(0xee, 0xe4, 0xda),
[4] = ccc3(0xed, 0xe0, 0xc8),
[8] = ccc3(0xf2, 0xb1, 0x79),
[16] = ccc3(0xf5, 0x95, 0x63),
[32] = ccc3(0xf6, 0x7c, 0x5f),
[64] = ccc3(0xf6, 0x5e, 0x3b),
[128] = ccc3(0xed, 0xcf, 0x72),
[256] = ccc3(0xed, 0xcc, 0x61),
[512] = ccc3(0xed, 0xc8, 0x50),
[1024] = ccc3(0xed, 0xc5, 0x3f),
[2048] = ccc3(0xed, 0xc2, 0x2e),
[4096] = ccc3(0x3c, 0x3a, 0x32),
}
local numcolors = {
[0] = ccc3(0x77,0x6e,0x65),
[2] = ccc3(0x77,0x6e,0x65),
[4] = ccc3(0x77,0x6e,0x65),
[8] = ccc3(0x77,0x6e,0x65),
[16] = ccc3(0x77,0x6e,0x65),
[32] = ccc3(0x77,0x6e,0x65),
[64] = ccc3(0x77,0x6e,0x65),
[128] = ccc3(0x77,0x6e,0x65),
}
function setnum(self,num,i,j)
local s = tostring(num)
--s = s.."("..i..","..j..")"
if s=='0' then
s=''
self.background:setOpacity(100)
else
self.background:setOpacity(255)
end
local c=colors[num]
if not c then
c=colors[4096]
end
self.num:setString(s)
self.background:setColor(c)
local nc = numcolors[num]
if not nc then
nc = numcolors[128]
end
self.num:setColor(nc)
end
function saveStatus()
local gridstr = serialize(grid)
local isOverstr = "false"
if isOver then isOverstr = "true" end
local str = string.format("do local grid,bestScore,totalScore,WINSTR,isOver \
=%s,%d,%d,\'%s\',%s return grid,bestScore,totalScore,WINSTR,isOver end",
gridstr,bestScore,totalScore,WINSTR,isOverstr)
io.writefile(configFile,str)
end
function MainScene:loadStatus()
if io.exists(configFile) then
local str = io.readfile(configFile)
if str then
local f = loadstring(str)
local _grid,_bestScore,_totalScore,_WINSTR,_isOver = f()
if _grid and _bestScore and _totalScore and _WINSTR then
grid,bestScore,totalScore,WINSTR,isOver = _grid,_bestScore,_totalScore,_WINSTR,_isOver
end
end
end
self:reLoadGame()
end
function MainScene:createLabel(title)
cc.ui.UILabel.new({text = "== " .. title .. " ==", size = 20, color = display.COLOR_BLACK})
:align(display.CENTER, display.cx, display.top - 20)
:addTo(self)
self.scoreLabel = cc.ui.UILabel.new({
text = "SCORE:0",
size = 30,
color = display.COLOR_BLUE,
})
self.scoreLabel:align(display.CENTER,display.cx,display.top - 100):addTo(self)
end
function MainScene:onTouch(event, x, y)
if isOver then
return true
end
if event=='began' then
touchStart={x,y}
elseif event=='ended' then
local tx,ty=x-touchStart[1],y-touchStart[2]
if tx==0 then
tx = tx+1
ty = ty+1
end
local dis = tx*tx+ty*ty
if dis<3 then -- touch move too short will ignore
return true
end
local dt = ty/tx
local op_list,score,win
if dt>=-1 and dt<=1 then
if tx>0 then
op_list,score,win = touch_op(grid,'right')
else
op_list,score,win = touch_op(grid,'left')
end
else
if ty>0 then
op_list,score,win = touch_op(grid,'up')
else
op_list,score,win = touch_op(grid,'down')
end
end
doOpList(op_list)
if win then
WINSTR = "YOUR ARE WINER"
end
totalScore = totalScore + score
if totalScore>bestScore then
bestScore = totalScore
end
self.scoreLabel:setString(string.format("BEST:%d \nSCORE:%d \n%s",bestScore,totalScore,WINSTR or ""))
isOver = not canMove(grid)
saveStatus()
end
return true
end
function MainScene:createGridShow()
gridShow = {}
for tmp=0,15 do
local i,j = math.floor(tmp/4)+1,math.floor(tmp%4)+1
local num = grid[i][j]
local s = tostring(num)
--s = s.."("..i..","..j..")"
if s=='0' then
s=''
end
if not gridShow[i] then
gridShow[i] = {}
end
local cell = {
backgroundsize = 140,
background = CCLayerColor:create(colors[-1], 140, 140),
num = cc.ui.UILabel.new({
text = s,
size = 40,
color = numcolors[0],
}),
}
gridShow[i][j] = cell
self:show(gridShow[i][j],i,j)
end
end
function MainScene:reLoadGame()
local m = #grid
local n = #grid[1]
for i=1,m do
for j=1,n do
setnum(gridShow[i][j],grid[i][j],i,j)
end
end
self.scoreLabel:setString(string.format("BEST:%d \nSCORE:%d \n%s",bestScore,totalScore,WINSTR or ""))
end
function MainScene:restartGame()
grid = initGrid(4,4)
totalScore = 0
WINSTR = ""
isOver = false
self:reLoadGame()
saveStatus()
end
function MainScene:createButtons()
local images = {
normal = "GreenButton.png",
pressed = "GreenScale9Block.png",
disabled = "GreenButton.png",
}
cc.ui.UIPushButton.new(images, {scale9 = true})
:setButtonSize(200, 60)
:setButtonLabel("normal", ui.newTTFLabel({
text = "New Game",
size = 32
}))
:onButtonClicked(function(event)
self:restartGame()
end)
:align(display.CENTER_TOP, display.left+display.width/2, display.top - 170)
:addTo(self)
end
function MainScene:ctor()
WINSTR = ""
display.newColorLayer(ccc4(0xfa,0xf8,0xef, 255)):addTo(self)
grid = initGrid(4,4)
self:createLabel("2048")
self:createGridShow()
self:createButtons()
self:loadStatus()
if isOver then
self:restartGame()
end
end
function MainScene:onEnter()
local layer = display.newLayer()
layer:addTouchEventListener(function (event,x,y)
return self:onTouch(event,x,y)
end)
layer:setTouchEnabled(true)
self:addChild(layer)
end
return MainScene
| mit |
jshackley/darkstar | scripts/globals/atma.lua | 3 | 41204 | -----------------------------------
--
-- EFFECT_ATMA
--
-- Also used for Voidwatch Atmacite
-- (it is a single effect in the client).
-- Todo: table this BS / ditch these functions
-----------------------------------
require("scripts/globals/status");
-----------------------------------
function atmaEffectGain(target, effect)
local pwr = effect:getPower();
if (pwr == 1) then -- ATMA of the Lion
target:addMod(MOD_TRIPLE_ATTACK, 7);
target:addMod(MOD_DMGPHYS, -10);
target:addMod(MOD_THUNDERATT, 30);
elseif (pwr == 2) then -- ATMA_OF_THE_STOUT_ARM
target:addMod(MOD_STR, 40);
target:addMod(MOD_ATT, 50);
target:addMod(MOD_RATT, 40);
elseif (pwr == 3) then -- ATMA_OF_THE_TWIN_CLAW
target:addMod(MOD_DEF, 40);
target:addMod(MOD_MDEF, 20);
target:addMod(MOD_CHARMRES, 20);
elseif (pwr == 4) then -- ATMA_OF_ALLURE
target:addMod(MOD_MPP, 30);
target:addMod(MOD_MND, 30);
target:addMod(MOD_ENMITY, -30);
elseif (pwr == 5) then -- ATMA_OF_ETERNITY
target:addMod(MOD_ENEMYCRITRATE, -20);
target:addMod(MOD_SLOWRES, 30);
target:addMod(MOD_CURSERES, 30);
elseif (pwr == 6) then -- ATMA_OF_THE_HEAVENS
target:addMod(MOD_MACC, 30);
target:addMod(MOD_DMGPHYS, -10);
target:addMod(MOD_PARALYZERES, 30);
elseif (pwr == 7) then -- ATMA_OF_THE_BAYING_MOON
target:addMod(MOD_ATT, 30);
target:addMod(MOD_MATT, 30);
elseif (pwr == 8) then -- ATMA_OF_THE_EBON_HOOF
target:addMod(MOD_HPP, 30);
target:addMod(MOD_SLEEPRES, 50);
elseif (pwr == 9) then -- ATMA_OF_TREMORS
target:addMod(MOD_DMG, -20);
target:addMod(MOD_SILENCERES, 40);
elseif (pwr == 10) then -- ATMA_OF_THE_SAVAGE_TIGER
target:addMod(MOD_AGI, 30);
target:addMod(MOD_DOUBLE_ATTACK, 10);
elseif (pwr == 11) then -- ATMA_OF_THE_VORACIOUS_VIOLET
target:addMod(MOD_STR, 50);
target:addMod(MOD_DOUBLE_ATTACK, 10);
target:addMod(MOD_REGAIN, 20);
elseif (pwr == 12) then -- ATMA_OF_CLOAK_AND_DAGGER
target:addMod(MOD_ACC, 40);
target:addMod(MOD_EVA, 40);
elseif (pwr == 13) then -- ATMA_OF_THE_STORMBIRD
target:addMod(MOD_ACC, 40);
target:addMod(MOD_THUNDERATT, 40);
target:addMod(MOD_REFRESH, 5);
elseif (pwr == 14) then -- ATMA_OF_THE_NOXIOUS_FANG
target:addMod(MOD_SUBTLE_BLOW, 40);
target:addMod(MOD_WATERATT, 40);
target:addMod(MOD_POISONRES, 40);
elseif (pwr == 15) then -- ATMA_OF_VICISSITUDE
target:addMod(MOD_DEF, 40);
target:addMod(MOD_MDEF, 20);
target:addMod(MOD_REGEN, 15);
elseif (pwr == 16) then -- ATMA_OF_THE_BEYOND
target:addMod(MOD_MATT, 30);
target:addMod(MOD_ICEATT, 30);
target:addMod(MOD_LIGHTATT, 30);
elseif (pwr == 17) then -- ATMA_OF_STORMBREATH
target:addMod(MOD_VIT, 30);
target:addMod(MOD_DMGBREATH, -30);
elseif (pwr == 18) then -- ATMA_OF_GALES
target:addMod(MOD_WINDATT, 30);
target:addMod(MOD_WINDACC, 30);
elseif (pwr == 19) then -- ATMA_OF_THRASHING_TENDRILS
target:addMod(MOD_CHR, 30);
target:addMod(MOD_CRITHITRATE, 20);
elseif (pwr == 20) then -- ATMA_OF_THE_DRIFTER
target:addMod(MOD_RATT, 30);
target:addMod(MOD_RACC, 40);
elseif (pwr == 21) then -- ATMA_OF_THE_STRONGHOLD
target:addMod(MOD_ATT, 40);
target:addMod(MOD_DEF, 40);
target:addMod(MOD_REGEN, 15);
elseif (pwr == 22) then -- ATMA_OF_THE_HARVESTER
target:addMod(MOD_STR, 30);
target:addMod(MOD_DOUBLE_ATTACK, 10);
target:addMod(MOD_SLEEPRES, 40);
elseif (pwr == 23) then -- ATMA_OF_DUNES
target:addMod(MOD_STORETP, 20);
target:addMod(MOD_SLOWRES, 40);
elseif (pwr == 24) then -- ATMA_OF_THE_COSMOS
target:addMod(MOD_DARKATT, 40);
-- not implemented yet target:addMod(MOD_AMNESIARES, 40);
target:addMod(MOD_SILENCERES, 40);
elseif (pwr == 25) then -- ATMA_OF_THE_SIREN_SHADOW
target:addMod(MOD_ATT, 40);
target:addMod(MOD_EVA, 40);
target:addMod(MOD_PARALYZERES, 40);
elseif (pwr == 26) then -- ATMA_OF_THE_IMPALER
target:addMod(MOD_DOUBLE_ATTACK, 20);
target:addMod(MOD_BINDRES, 40);
target:addMod(MOD_BLINDRES, 40);
elseif (pwr == 27) then -- ATMA_OF_THE_ADAMANTINE
target:addMod(MOD_VIT, 20);
target:addMod(MOD_DEF, 40);
elseif (pwr == 28) then -- ATMA_OF_CALAMITY
target:addMod(MOD_SLOWRES, 40);
target:addMod(MOD_BLINDRES, 40);
elseif (pwr == 29) then -- ATMA_OF_THE_CLAW
target:addMod(MOD_EARTHATT, 30);
target:addMod(MOD_EARTHACC, 40);
elseif (pwr == 30) then -- ATMA_OF_BALEFUL_BONES
target:addMod(MOD_STR, 20);
target:addMod(MOD_DARKACC, 40)
elseif (pwr == 31) then -- ATMA_OF_THE_CLAWED_BUTTERFLY
target:addMod(MOD_FIREACC, 40);
target:addMod(MOD_INT, 30);
elseif (pwr == 32) then -- ATMA_OF_THE_DESERT_WORM
target:addMod(MOD_MND, 20);
target:addMod(MOD_ACC, 40);
target:addMod(MOD_MAGIC_NULL, 5);
elseif (pwr == 33) then -- ATMA_OF_THE_UNDYING
target:addMod(MOD_MND, 40);
target:addMod(MOD_CONSERVE_MP, 10);
target:addMod(MOD_ICEATT, 20);
elseif (pwr == 34) then -- ATMA_OF_THE_IMPREGNABLE_TOWER
target:addMod(MOD_HP, 50);
target:addMod(MOD_MACC, 40);
target:addMod(MOD_MATT, 40);
elseif (pwr == 35) then -- ATMA_OF_THE_SMOLDERING_SKY
target:addMod(MOD_ATT, 20);
target:addMod(MOD_MACC, 40);
target:addMod(MOD_FIREATT, 30);
elseif (pwr == 36) then -- ATMA_OF_THE_DEMONIC_SKEWER
target:addMod(MOD_STR, 20);
target:addMod(MOD_TP_BONUS, 20);
target:addMod(MOD_NULL_PHYSICAL_DAMAGE, 5);
elseif (pwr == 37) then -- ATMA_OF_THE_GOLDEN_CLAW
target:addMod(MOD_SKILLCHAINBONUS, 20);
target:addMod(MOD_STR, 20);
elseif (pwr == 38) then -- ATMA_OF_THE_GLUTINOUS_OOZE
target:addMod(MOD_MND, 20);
target:addMod(MOD_WATERACC, 20);
elseif (pwr == 39) then -- ATMA_OF_THE_LIGHTNING_BEAST
target:addMod(MOD_UFASTCAST, 20);
target:addMod(MOD_SPELLINTERRUPT, 20);
elseif (pwr == 40) then -- ATMA_OF_THE_NOXIOUS_BLOOM
target:addMod(MOD_STORETP, 20);
target:addMod(MOD_WALTZ_POTENTCY, 10);
elseif (pwr == 41) then -- ATMA_OF_THE_GNARLED_HORN
target:addMod(MOD_AGI, 50);
target:addMod(MOD_CRITHITRATE, 20);
target:addMod(MOD_COUNTER, 10);
elseif (pwr == 42) then -- ATMA_OF_THE_STRANGLING_WIND
target:addMod(MOD_STR, 20);
target:addMod(MOD_VIT, 20);
target:addMod(MOD_AGI, 30);
elseif (pwr == 43) then -- ATMA_OF_THE_DEEP_DEVOURER
target:addMod(MOD_SUBTLE_BLOW, 5);
target:addMod(MOD_STORETP, 5);
-- target:addMod(MOD_SONG_CASTING_TIME, -20); Doesnt exist
elseif (pwr == 44) then -- ATMA_OF_THE_MOUNTED_CHAMPION
target:addMod(MOD_VIT, 50);
target:addMod(MOD_REGEN, 20);
target:addMod(MOD_ENMITY_REDUCTION_PHYSICAL, -20);
elseif (pwr == 45) then -- ATMA_OF_THE_RAZED_RUINS
target:addMod(MOD_DEX, 50);
target:addMod(MOD_CRITHITRATE, 30);
target:addMod(MOD_CRIT_DMG_INCREASE, 10);
elseif (pwr == 46) then -- ATMA_OF_THE_BLUDGEONING_BRUTE
target:addMod(MOD_REGAIN, 1);
target:addMod(MOD_THUNDERRES, 50);
target:addMod(MOD_WATERRES, 50);
elseif (pwr == 47) then -- ATMA_OF_THE_RAPID_REPTILIAN
target:addMod(MOD_TRIPLE_ATTACK, 5);
target:addMod(MOD_DMGBREATH, -40);
elseif (pwr == 48) then -- ATMA_OF_THE_WINGED_ENIGMA
target:addMod(MOD_HASTE_GEAR, 5);
elseif (pwr == 49) then -- ATMA_OF_THE_CRADLE
target:addMod(MOD_VIT, 20);
target:addMod(MOD_DEX, 20);
elseif (pwr == 50) then -- ATMA_OF_THE_UNTOUCHED
target:addMod(MOD_CHR, 20);
target:addMod(MOD_TRIPLE_ATTACK, 5);
elseif (pwr == 51) then -- ATMA_OF_THE_SANGUINE_SCYTHE
target:addMod(MOD_HPP, 20);
target:addMod(MOD_CRIT_DMG_INCREASE, 10);
target:addMod(MOD_ENMITY, 20);
elseif (pwr == 52) then -- ATMA_OF_THE_TUSKED_TERROR
target:addMod(MOD_UFASTCAST, 20);
target:addMod(MOD_WATERATT, 20);
target:addMod(MOD_WATERACC, 20);
elseif (pwr == 53) then -- ATMA_OF_THE_MINIKIN_MONSTROSITY
target:addMod(MOD_REFRESH, 10);
target:addMod(MOD_INT, 50);
target:addMod(MOD_ENMITY, -20);
elseif (pwr == 54) then -- ATMA_OF_THE_WOULD_BE_KING
target:addMod(MOD_REGAIN, 10);
target:addMod(MOD_STORETP, 20);
target:addMod(MOD_TP_BONUS, 20);
elseif (pwr == 55) then -- ATMA_OF_THE_BLINDING_HORN
target:addMod(MOD_CONSERVE_MP, 20);
target:addMod(MOD_THUNDERATT, 30);
target:addMod(MOD_DMGMAGIC, -20);
elseif (pwr == 56) then -- ATMA_OF_THE_DEMONIC_LASH
target:addMod(MOD_ATT, 40);
target:addMod(MOD_DOUBLE_ATTACK, 10);
target:addMod(MOD_MAGIC_ABSORB, 20);
elseif (pwr == 57) then -- ATMA_OF_APPARITIONS
target:addMod(MOD_EVA, 20);
target:addMod(MOD_WINDRES, 50);
elseif (pwr == 58) then -- ATMA_OF_THE_SHIMMERING_SHELL
target:addMod(MOD_AGI, 20);
target:addMod(MOD_FIRERES, 50);
elseif (pwr == 59) then -- ATMA_OF_THE_MURKY_MIASMA
target:addMod(MOD_DARKRES, 50);
target:addMod(MOD_STUNRES, 30);
elseif (pwr == 60) then -- ATMA_OF_THE_AVARICIOUS_APE
target:addMod(MOD_HASTE_GEAR, 5);
-- not implemented: Monster Correlation
elseif (pwr == 61) then -- ATMA_OF_THE_MERCILESS_MATRIARCH
target:addMod(MOD_MACC, 50);
target:addMod(MOD_FASTCAST, 20);
target:addMod(MOD_ENMITY, -50);
elseif (pwr == 62) then -- ATMA_OF_THE_BROTHER_WOLF
target:addMod(MOD_MATT, 20);
target:addMod(MOD_MDEF, 20);
target:addMod(MOD_FIRERES, 100);
elseif (pwr == 63) then -- ATMA_OF_THE_EARTH_WYRM
target:addMod(MOD_EARTHRES, 100);
target:addMod(MOD_DMG, -20);
-- not implemented: Gain full benefit of Earthsday/earth weather bonuses
elseif (pwr == 64) then -- ATMA_OF_THE_ASCENDING_ONE
target:addMod(MOD_WINDRES, 100);
target:addMod(MOD_HASTE_GEAR, 5);
target:addMod(MOD_SNAP_SHOT, 5);
elseif (pwr == 65) then -- ATMA_OF_THE_SCORPION_QUEEN
target:addMod(MOD_STORETP, 20);
target:addMod(MOD_CRITHITRATE, 30);
target:addMod(MOD_BINDRES, 50);
elseif (pwr == 66) then -- ATMA_OF_A_THOUSAND_NEEDLES
target:addMod(MOD_HPP, 20);
target:addMod(MOD_MPP, 20);
target:addMod(MOD_DEX, 10);
elseif (pwr == 67) then -- ATMA_OF_THE_BURNING_EFFIGY
target:addMod(MOD_STR, 20);
target:addMod(MOD_FIRE_AFFINITY, 3);
target:addMod(MOD_FIREATT, 1);
target:addMod(MOD_FIREACC, 1);
elseif (pwr == 68) then -- ATMA_OF_THE_SMITING_BLOW
target:addMod(MOD_TP_BONUS, 50);
target:addMod(MOD_WSACC, 50);
elseif (pwr == 69) then -- ATMA_OF_THE_LONE_WOLF
target:addMod(MOD_ATT, 20);
target:addMod(MOD_FIREATT, 30);
elseif (pwr == 70) then -- ATMA_OF_THE_CRIMSON_SCALE
target:addMod(MOD_HASTE_GEAR, 5);
target:addMod(MOD_ENMITY, -20);
elseif (pwr == 71) then -- ATMA_OF_THE_SCARLET_WING
target:addMod(MOD_ELEM, 10);
target:addMod(MOD_WIND_AFFINITY, 5);
elseif (pwr == 72) then -- ATMA_OF_THE_RAISED_TAIL
target:addMod(MOD_ATT, 40);
target:addMod(MOD_EVA, 40);
elseif (pwr == 73) then -- ATMA_OF_THE_SAND_EMPEROR
target:addMod(MOD_ACC, 40);
target:addMod(MOD_EVA, 40);
elseif (pwr == 74) then -- ATMA_OF_THE_OMNIPOTENT
target:addMod(MOD_DEX, 50);
target:addMod(MOD_HASTE_GEAR, 10);
target:addMod(MOD_ENMITY, 20);
elseif (pwr == 75) then -- ATMA_OF_THE_WAR_LION
target:addMod(MOD_DEX, 20);
target:addMod(MOD_THUNDERRES, 100);
target:addMod(MOD_THUNDER_AFFINITY, 10);
elseif (pwr == 76) then -- ATMA_OF_THE_FROZEN_FETTERS
target:addMod(MOD_INT, 20);
target:addMod(MOD_ICERES, 100);
target:addMod(MOD_ICE_AFFINITY, 10);
elseif (pwr == 77) then -- ATMA_OF_THE_PLAGUEBRINGER
target:addMod(MOD_REGEN, 10);
target:addMod(MOD_STORETP, 20);
target:addMod(MOD_DOUBLE_ATTACK, 7);
elseif (pwr == 78) then -- ATMA_OF_THE_SHRIEKING_ONE
target:addMod(MOD_DEF, 60);
target:addMod(MOD_MDEF, 20);
target:addMod(MOD_STORETP, 20);
elseif (pwr == 79) then -- ATMA_OF_THE_HOLY_MOUNTAIN
target:addMod(MOD_LIGHTRES, 100);
target:addMod(MOD_LIGHTACC, 50);
target:addMod(MOD_LIGHT_AFFINITY, 10);
elseif (pwr == 80) then -- ATMA_OF_THE_LAKE_LURKER
target:addMod(MOD_MND, 20);
target:addMod(MOD_WATERRES, 100);
target:addMod(MOD_WATER_AFFINITY, 10);
elseif (pwr == 81) then -- ATMA_OF_THE_CRUSHING_CUDGEL
target:addMod(MOD_ACC, 20);
target:addMod(MOD_SKILLCHAINDMG, 5);
elseif (pwr == 82) then -- ATMA_OF_PURGATORY
target:addMod(MOD_VIT, 40);
target:addMod(MOD_INT, 40);
elseif (pwr == 83) then -- ATMA_OF_BLIGHTED_BREATH
-- target:addMod(MOD_SONG_CASTING_TIME, -40); Doesnt exist
target:addMod(MOD_LIGHTACC, 40);
elseif (pwr == 84) then -- ATMA_OF_THE_PERSISTENT_PREDATOR
target:addMod(MOD_STORETP, 40);
target:addMod(MOD_TP_BONUS, 10);
elseif (pwr == 85) then -- ATMA_OF_THE_STONE_GOD
target:addMod(MOD_SUBTLE_BLOW, 40);
target:addMod(MOD_ENMITY, 40);
elseif (pwr == 86) then -- ATMA_OF_THE_SUN_EATER
target:addMod(MOD_STORETP, 40);
target:addMod(MOD_TP_BONUS, 40);
elseif (pwr == 87) then -- ATMA_OF_THE_DESPOT
target:addMod(MOD_CHR, 50);
target:addMod(MOD_MAGIC_ABSORB, 15);
target:addMod(MOD_TP_BONUS, 40);
elseif (pwr == 88) then -- ATMA_OF_THE_SOLITARY_ONE
target:addMod(MOD_TRIPLE_ATTACK, 7);
target:addMod(MOD_DMGBREATH, -25);
target:addMod(MOD_ZANSHIN, 10);
elseif (pwr == 89) then -- ATMA_OF_THE_WINGED_GLOOM
target:addMod(MOD_DMG, -25);
target:addMod(MOD_REGEN, 2);
elseif (pwr == 90) then -- ATMA_OF_THE_SEA_DAUGHTER
target:addMod(MOD_REGAIN, 5);
target:addMod(MOD_HASTE_GEAR, -12);
target:addMod(MOD_REGEN, 30);
elseif (pwr == 91) then -- ATMA_OF_THE_HATEFUL_STREAM
-- Not yet implemented
-- http://wiki.ffxiclopedia.org/wiki/Atma_of_the_Hateful_Stream
-- No easy way to do this ATMA, no way I am doing bit crap in onTick for it..
elseif (pwr == 92) then -- ATMA_OF_THE_FOE_FLAYER
target:addMod(MOD_MPP, 20);
target:addMod(MOD_REFRESH, 20);
target:addMod(MOD_FASTCAST, 20);
target:addMod(MOD_MACC, 50);
elseif (pwr == 93) then -- ATMA_OF_THE_ENDLESS_NIGHTMARE
target:addMod(MOD_MND, 20);
target:addMod(MOD_DARKRES, 100);
target:addMod(MOD_DARK_AFFINITY, 10);
elseif (pwr == 94) then -- ATMA_OF_THE_SUNDERING_SLASH
target:addMod(MOD_ATT, 20);
target:addMod(MOD_REGAIN, 3);
elseif (pwr == 95) then -- ATMA_OF_ENTWINED_SERPENTS
target:addMod(MOD_ATT, 20);
target:addMod(MOD_DOUBLE_ATTACK, 15);
elseif (pwr == 96) then -- ATMA_OF_THE_HORNED_BEAST
target:addMod(MOD_ACC, 60);
target:addMod(MOD_PETRIFYRES, 50);
elseif (pwr == 97) then -- ATMA_OF_AQUATIC_ARDOR
target:addMod(MOD_ABSORB_DMG_CHANCE, 6);
target:addMod(MOD_MAGIC_ABSORB, 6);
elseif (pwr == 98) then -- ATMA_OF_THE_FALLEN_ONE
target:addMod(MOD_INT, 30);
target:addMod(MOD_MND, 30);
elseif (pwr == 99) then -- ATMA_OF_FIRES_AND_FLARES
target:addMod(MOD_AGI, 20);
target:addMod(MOD_RATT, 40);
elseif (pwr == 100) then -- ATMA_OF_THE_APOCALYPSE
target:addMod(MOD_TRIPLE_ATTACK, 15);
target:addMod(MOD_GRIMOIRE_INSTANT_CAST, 10); -- Wrong modifier, correct one not yet implimented.
target:addMod(MOD_RERAISE_III, 1);
elseif (pwr == 101) then -- ATMA_OF_THE_HEIR KI ID = 1655;
elseif (pwr == 102) then -- ATMA_OF_THE_HERO KI ID = 1656;
elseif (pwr == 103) then -- ATMA_OF_THE_FULL_MOON KI ID = 1657;
elseif (pwr == 104) then -- ATMA_OF_ILLUSIONS KI ID = 1658;
elseif (pwr == 105) then -- ATMA_OF_THE_BANISHER KI ID = 1659;
elseif (pwr == 106) then -- ATMA_OF_THE_SELLSWORD KI ID = 1660;
elseif (pwr == 107) then -- ATMA_OF_A_FUTURE_FABULOUS KI ID = 1661;
elseif (pwr == 108) then -- ATMA_OF_CAMARADERIE KI ID = 1662;
elseif (pwr == 109) then -- ATMA_OF_THE_TRUTHSEEKER KI ID = 1663;
elseif (pwr == 110) then -- ATMA_OF_THE_AZURE_SKY KI ID = 1664;
elseif (pwr == 111) then -- ATMA_OF_ECHOES KI ID = 1665;
elseif (pwr == 112) then -- ATMA_OF_DREAD KI ID = 1666;
elseif (pwr == 113) then -- ATMA_OF_AMBITION KI ID = 1667;
elseif (pwr == 114) then -- ATMA_OF_THE_BEAST_KING KI ID = 1668;
elseif (pwr == 115) then -- ATMA_OF_THE_KIRIN KI ID = 1669;
elseif (pwr == 116) then -- ATMA_OF_HELLS_GUARDIAN KI ID = 1670;
elseif (pwr == 117) then -- ATMA_OF_LUMINOUS_WINGS KI ID = 1671;
elseif (pwr == 118) then -- ATMA_OF_THE_DRAGON_RIDER KI ID = 1672;
elseif (pwr == 119) then -- ATMA_OF_THE_IMPENETRABLE KI ID = 1673;
elseif (pwr == 120) then -- ATMA_OF_ALPHA_AND_OMEGA KI ID = 1674;
elseif (pwr == 121) then -- ATMA_OF_THE_ULTIMATE KI ID = 1675;
elseif (pwr == 122) then -- ATMA_OF_THE_HYBRID_BEAST KI ID = 1676;
elseif (pwr == 123) then -- ATMA_OF_THE_DARK_DEPTHS KI ID = 1677;
elseif (pwr == 124) then -- ATMA_OF_THE_ZENITH KI ID = 1678;
elseif (pwr == 125) then -- ATMA_OF_PERFECT_ATTENDANCE KI ID = 1679;
elseif (pwr == 126) then -- ATMA_OF_THE_RESCUER KI ID = 1680;
elseif (pwr == 127) then -- ATMA_OF_NIGHTMARES KI ID = 1681;
elseif (pwr == 128) then -- ATMA_OF_THE_EINHERJAR KI ID = 1682;
elseif (pwr == 129) then -- ATMA_OF_THE_ILLUMINATOR KI ID = 1683;
elseif (pwr == 130) then -- ATMA_OF_THE_BUSHIN KI ID = 1684;
elseif (pwr == 131) then -- ATMA_OF_THE_ACE_ANGLER KI ID = 1685;
elseif (pwr == 132) then -- ATMA_OF_THE_MASTER_CRAFTER KI ID = 1686;
elseif (pwr == 133) then -- ATMA_OF_INGENUITY KI ID = 1687;
elseif (pwr == 134) then -- ATMA_OF_THE_GRIFFONS_CLAW KI ID = 1688;
elseif (pwr == 135) then -- ATMA_OF_THE_FETCHING_FOOTPAD KI ID = 1689;
elseif (pwr == 136) then -- ATMA_OF_UNDYING_LOYALTY KI ID = 1690;
elseif (pwr == 137) then -- ATMA_OF_THE_ROYAL_LINEAGE KI ID = 1691;
elseif (pwr == 138) then -- ATMA_OF_THE_SHATTERING_STAR KI ID = 1692;
elseif (pwr == 139) then -- ATMA_OF_THE_COBRA_COMMANDER KI ID = 1693;
elseif (pwr == 140) then -- ATMA_OF_ROARING_LAUGHTER KI ID = 1694;
elseif (pwr == 141) then -- ATMA_OF_THE_DARK_BLADE KI ID = 1695;
elseif (pwr == 142) then -- ATMA_OF_THE_DUCAL_GUARD KI ID = 1696;
elseif (pwr == 143) then -- ATMA_OF_HARMONY KI ID = 1697;
elseif (pwr == 144) then -- ATMA_OF_REVELATIONS KI ID = 1698;
elseif (pwr == 145) then -- ATMA_OF_THE_SAVIOR KI ID = 1699;
end
end;
function atmaEffectLose(target, effect)
local pwr = effect:getPower();
if (pwr == 1) then -- ATMA of the Lion
target:delMod(MOD_TRIPLE_ATTACK, 7);
target:delMod(MOD_DMGPHYS, -10);
target:delMod(MOD_THUNDERATT, 30);
elseif (pwr == 2) then -- ATMA_OF_THE_STOUT_ARM
target:delMod(MOD_STR, 40);
target:delMod(MOD_ATT, 50);
target:delMod(MOD_RATT, 40);
elseif (pwr == 3) then -- ATMA_OF_THE_TWIN_CLAW
target:delMod(MOD_DEF, 40);
target:delMod(MOD_MDEF, 20);
target:delMod(MOD_CHARMRES, 20);
elseif (pwr == 4) then -- ATMA_OF_ALLURE
target:delMod(MOD_MPP, 30);
target:delMod(MOD_MND, 30);
target:delMod(MOD_ENMITY, -30);
elseif (pwr == 5) then -- ATMA_OF_ETERNITY
target:delMod(MOD_ENEMYCRITRATE, -20);
target:delMod(MOD_SLOWRES, 30);
target:delMod(MOD_CURSERES, 30);
elseif (pwr == 6) then -- ATMA_OF_THE_HEAVENS
target:delMod(MOD_MACC, 30);
target:delMod(MOD_DMGPHYS, -10);
target:delMod(MOD_PARALYZERES, 30);
elseif (pwr == 7) then -- ATMA_OF_THE_BAYING_MOON
target:delMod(MOD_ATT, 30);
target:delMod(MOD_MATT, 30);
elseif (pwr == 8) then -- ATMA_OF_THE_EBON_HOOF
target:delMod(MOD_HPP, 30);
target:delMod(MOD_SLEEPRES, 50);
elseif (pwr == 9) then -- ATMA_OF_TREMORS
target:delMod(MOD_DMG, -20);
target:delMod(MOD_SILENCERES, 40);
elseif (pwr == 10) then -- ATMA_OF_THE_SAVAGE_TIGER
target:delMod(MOD_AGI, 30);
target:delMod(MOD_DOUBLE_ATTACK, 10);
elseif (pwr == 11) then -- ATMA_OF_THE_VORACIOUS_VIOLET
target:delMod(MOD_STR, 50);
target:delMod(MOD_DOUBLE_ATTACK, 10);
target:delMod(MOD_REGAIN, 20);
elseif (pwr == 12) then -- ATMA_OF_CLOAK_AND_DAGGER
target:delMod(MOD_ACC, 40);
target:delMod(MOD_EVA, 40);
elseif (pwr == 13) then -- ATMA_OF_THE_STORMBIRD
target:delMod(MOD_ACC, 40);
target:delMod(MOD_THUNDERATT, 40);
target:delMod(MOD_REFRESH, 5);
elseif (pwr == 14) then -- ATMA_OF_THE_NOXIOUS_FANG
target:delMod(MOD_SUBTLE_BLOW, 40);
target:delMod(MOD_WATERATT, 40);
target:delMod(MOD_POISONRES, 40);
elseif (pwr == 15) then -- ATMA_OF_VICISSITUDE
target:delMod(MOD_DEF, 40);
target:delMod(MOD_MDEF, 20);
target:delMod(MOD_REGEN, 15);
elseif (pwr == 16) then -- ATMA_OF_THE_BEYOND
target:delMod(MOD_MATT, 30);
target:delMod(MOD_ICEATT, 30);
target:delMod(MOD_LIGHTATT, 30);
elseif (pwr == 17) then -- ATMA_OF_STORMBREATH
target:delMod(MOD_VIT, 30);
target:delMod(MOD_DMGBREATH, -30);
elseif (pwr == 18) then -- ATMA_OF_GALES
target:delMod(MOD_WINDATT, 30);
target:delMod(MOD_WINDACC, 30);
elseif (pwr == 19) then -- ATMA_OF_THRASHING_TENDRILS
target:delMod(MOD_CHR, 30);
target:delMod(MOD_CRITHITRATE, 20);
elseif (pwr == 20) then -- ATMA_OF_THE_DRIFTER
target:delMod(MOD_RATT, 30);
target:delMod(MOD_RACC, 40);
elseif (pwr == 21) then -- ATMA_OF_THE_STRONGHOLD
target:delMod(MOD_ATT, 40);
target:delMod(MOD_DEF, 40);
target:delMod(MOD_REGEN, 15);
elseif (pwr == 22) then -- ATMA_OF_THE_HARVESTER
target:delMod(MOD_STR, 30);
target:delMod(MOD_DOUBLE_ATTACK, 10);
target:delMod(MOD_SLEEPRES, 40);
elseif (pwr == 23) then -- ATMA_OF_DUNES
target:delMod(MOD_STORETP, 20);
target:delMod(MOD_SLOWRES, 40);
elseif (pwr == 24) then -- ATMA_OF_THE_COSMOS
target:delMod(MOD_DARKATT, 40);
-- target:delMod(MOD_AMNESIARES, 40);
target:delMod(MOD_SILENCERES, 40);
elseif (pwr == 25) then -- ATMA_OF_THE_SIREN_SHADOW
target:delMod(MOD_ATT, 40);
target:delMod(MOD_EVA, 40);
target:delMod(MOD_PARALYZERES, 40);
elseif (pwr == 26) then -- ATMA_OF_THE_IMPALER
target:delMod(MOD_DOUBLE_ATTACK, 20);
target:delMod(MOD_BINDRES, 40);
target:delMod(MOD_BLINDRES, 40);
elseif (pwr == 27) then -- ATMA_OF_THE_ADAMANTINE
target:delMod(MOD_VIT, 20);
target:delMod(MOD_DEF, 40);
elseif (pwr == 28) then -- ATMA_OF_CALAMITY
target:delMod(MOD_SLOWRES, 40);
target:delMod(MOD_BLINDRES, 40);
elseif (pwr == 29) then -- ATMA_OF_THE_CLAW
target:delMod(MOD_EARTHATT, 30);
target:delMod(MOD_EARTHACC, 40);
elseif (pwr == 30) then -- ATMA_OF_BALEFUL_BONES
target:delMod(MOD_STR, 20);
target:delMod(MOD_DARKACC, 40)
elseif (pwr == 31) then -- ATMA_OF_THE_CLAWED_BUTTERFLY
target:delMod(MOD_FIREACC, 40);
target:delMod(MOD_INT, 30);
elseif (pwr == 32) then -- ATMA_OF_THE_DESERT_WORM
target:delMod(MOD_MND, 20);
target:delMod(MOD_ACC, 40);
target:delMod(MOD_MAGIC_NULL, 5);
elseif (pwr == 33) then -- ATMA_OF_THE_UNDYING
target:delMod(MOD_MND, 40);
target:delMod(MOD_CONSERVE_MP, 10);
target:delMod(MOD_ICEATT, 20);
elseif (pwr == 34) then -- ATMA_OF_THE_IMPREGNABLE_TOWER
target:delMod(MOD_HP, 50);
target:delMod(MOD_MACC, 40);
target:delMod(MOD_MATT, 40);
elseif (pwr == 35) then -- ATMA_OF_THE_SMOLDERING_SKY
target:delMod(MOD_ATT, 20);
target:delMod(MOD_MACC, 40);
target:delMod(MOD_FIREATT, 30);
elseif (pwr == 36) then -- ATMA_OF_THE_DEMONIC_SKEWER
target:delMod(MOD_STR, 20);
target:delMod(MOD_TP_BONUS, 20);
target:delMod(MOD_NULL_PHYSICAL_DAMAGE, 5);
elseif (pwr == 37) then -- ATMA_OF_THE_GOLDEN_CLAW
target:delMod(MOD_SKILLCHAINBONUS, 20);
target:delMod(MOD_STR, 20);
elseif (pwr == 38) then -- ATMA_OF_THE_GLUTINOUS_OOZE
target:delMod(MOD_MND, 20);
target:delMod(MOD_WATERACC, 20);
elseif (pwr == 39) then -- ATMA_OF_THE_LIGHTNING_BEAST
target:delMod(MOD_UFASTCAST, 20);
target:delMod(MOD_SPELLINTERRUPT, 20);
elseif (pwr == 40) then -- ATMA_OF_THE_NOXIOUS_BLOOM
target:delMod(MOD_STORETP, 20);
target:delMod(MOD_WALTZ_POTENTCY, 10);
elseif (pwr == 41) then -- ATMA_OF_THE_GNARLED_HORN
target:delMod(MOD_AGI, 50);
target:delMod(MOD_CRITHITRATE, 20);
target:delMod(MOD_COUNTER, 10);
elseif (pwr == 42) then -- ATMA_OF_THE_STRANGLING_WIND
target:delMod(MOD_STR, 20);
target:delMod(MOD_VIT, 20);
target:delMod(MOD_AGI, 30);
elseif (pwr == 43) then -- ATMA_OF_THE_DEEP_DEVOURER
target:delMod(MOD_SUBTLE_BLOW, 5);
target:delMod(MOD_STORETP, 5);
-- target:delMod(MOD_SONG_CASTING_TIME, -20); Doesnt exist
elseif (pwr == 44) then -- ATMA_OF_THE_MOUNTED_CHAMPION
target:delMod(MOD_VIT, 50);
target:delMod(MOD_REGEN, 20);
target:delMod(MOD_ENMITY_REDUCTION_PHYSICAL, -20);
elseif (pwr == 45) then -- ATMA_OF_THE_RAZED_RUINS
target:delMod(MOD_DEX, 50);
target:delMod(MOD_CRITHITRATE, 30);
target:delMod(MOD_CRIT_DMG_INCREASE, 10);
elseif (pwr == 46) then -- ATMA_OF_THE_BLUDGEONING_BRUTE
target:delMod(MOD_REGAIN, 1);
target:delMod(MOD_THUNDERRES, 50);
target:delMod(MOD_WATERRES, 50);
elseif (pwr == 47) then -- ATMA_OF_THE_RAPID_REPTILIAN
target:delMod(MOD_TRIPLE_ATTACK, 5);
target:delMod(MOD_DMGBREATH, -40);
elseif (pwr == 48) then -- ATMA_OF_THE_WINGED_ENIGMA
target:delMod(MOD_HASTE_GEAR, 5);
elseif (pwr == 49) then -- ATMA_OF_THE_CRADLE
target:delMod(MOD_VIT, 20);
target:delMod(MOD_DEX, 20);
elseif (pwr == 50) then -- ATMA_OF_THE_UNTOUCHED
target:delMod(MOD_CHR, 20);
target:delMod(MOD_TRIPLE_ATTACK, 5);
elseif (pwr == 51) then -- ATMA_OF_THE_SANGUINE_SCYTHE
target:delMod(MOD_HPP, 20);
target:delMod(MOD_CRIT_DMG_INCREASE, 10);
target:delMod(MOD_ENMITY, 20);
elseif (pwr == 52) then -- ATMA_OF_THE_TUSKED_TERROR
target:delMod(MOD_UFASTCAST, 20);
target:delMod(MOD_WATERATT, 20);
target:delMod(MOD_WATERACC, 20);
elseif (pwr == 53) then -- ATMA_OF_THE_MINIKIN_MONSTROSITY
target:delMod(MOD_REFRESH, 10);
target:delMod(MOD_INT, 50);
target:delMod(MOD_ENMITY, -20);
elseif (pwr == 54) then -- ATMA_OF_THE_WOULD_BE_KING
target:delMod(MOD_REGAIN, 10);
target:delMod(MOD_STORETP, 20);
target:delMod(MOD_TP_BONUS, 20);
elseif (pwr == 55) then -- ATMA_OF_THE_BLINDING_HORN
target:delMod(MOD_CONSERVE_MP, 20);
target:delMod(MOD_THUNDERATT, 30);
target:delMod(MOD_DMGMAGIC, -20);
elseif (pwr == 56) then -- ATMA_OF_THE_DEMONIC_LASH
target:delMod(MOD_ATT, 40);
target:delMod(MOD_DOUBLE_ATTACK, 10);
target:delMod(MOD_MAGIC_ABSORB, 20);
elseif (pwr == 57) then -- ATMA_OF_APPARITIONS
target:delMod(MOD_EVA, 20);
target:delMod(MOD_WINDRES, 50);
elseif (pwr == 58) then -- ATMA_OF_THE_SHIMMERING_SHELL
target:delMod(MOD_AGI, 20);
target:delMod(MOD_FIRERES, 50);
elseif (pwr == 59) then -- ATMA_OF_THE_MURKY_MIASMA
target:delMod(MOD_DARKRES, 50);
target:delMod(MOD_STUNRES, 30);
elseif (pwr == 60) then -- ATMA_OF_THE_AVARICIOUS_APE
target:delMod(MOD_HASTE_GEAR, 5);
target:delMod(MOD_FIREACC, 5);
target:delMod(MOD_ICEACC, 5);
target:delMod(MOD_WINDACC, 5);
target:delMod(MOD_EARTHACC, 5);
target:delMod(MOD_THUNDERACC, 5);
target:delMod(MOD_WATERACC, 5);
target:delMod(MOD_LIGHTACC, 5);
target:delMod(MOD_DARKACC, 5);
elseif (pwr == 61) then -- ATMA_OF_THE_MERCILESS_MATRIARCH
target:delMod(MOD_MACC, 50);
target:delMod(MOD_FASTCAST, 20);
target:delMod(MOD_ENMITY, -50);
elseif (pwr == 62) then -- ATMA_OF_THE_BROTHER_WOLF
target:delMod(MOD_MATT, 20);
target:delMod(MOD_MDEF, 20);
target:delMod(MOD_FIRERES, 100);
elseif (pwr == 63) then -- ATMA_OF_THE_EARTH_WYRM
target:delMod(MOD_EARTHRES, 100);
target:delMod(MOD_DMG, -20);
target:delMod(MOD_FIRE_AFFINITY, 1);
target:delMod(MOD_EARTH_AFFINITY, 1);
target:delMod(MOD_WATER_AFFINITY, 1);
target:delMod(MOD_ICE_AFFINITY, 1);
target:delMod(MOD_THUNDER_AFFINITY, 1);
target:delMod(MOD_WIND_AFFINITY, 1);
target:delMod(MOD_LIGHT_AFFINITY, 1);
target:delMod(MOD_DARK_AFFINITY, 1);
elseif (pwr == 64) then -- ATMA_OF_THE_ASCENDING_ONE
target:delMod(MOD_WINDRES, 100);
target:delMod(MOD_HASTE_GEAR, 5);
target:delMod(MOD_SNAP_SHOT, 5);
elseif (pwr == 65) then -- ATMA_OF_THE_SCORPION_QUEEN
target:delMod(MOD_STORETP, 20);
target:delMod(MOD_CRITHITRATE, 30);
target:delMod(MOD_BINDRES, 50);
elseif (pwr == 66) then -- ATMA_OF_A_THOUSAND_NEEDLES
target:delMod(MOD_HPP, 20);
target:delMod(MOD_MPP, 20);
target:delMod(MOD_DEX, 10);
elseif (pwr == 67) then -- ATMA_OF_THE_BURNING_EFFIGY
target:delMod(MOD_STR, 20);
target:delMod(MOD_FIRE_AFFINITY, 3);
target:delMod(MOD_FIREATT, 1);
target:delMod(MOD_FIREACC, 1);
elseif (pwr == 68) then -- ATMA_OF_THE_SMITING_BLOW
target:delMod(MOD_TP_BONUS, 50);
target:delMod(MOD_WSACC, 50);
elseif (pwr == 69) then -- ATMA_OF_THE_LONE_WOLF
target:delMod(MOD_ATT, 20);
target:delMod(MOD_FIREATT, 30);
elseif (pwr == 70) then -- ATMA_OF_THE_CRIMSON_SCALE
target:delMod(MOD_HASTE_GEAR, 5);
target:delMod(MOD_ENMITY, -20);
elseif (pwr == 71) then -- ATMA_OF_THE_SCARLET_WING
target:delMod(MOD_ELEM, 10);
target:delMod(MOD_WIND_AFFINITY, 5);
elseif (pwr == 72) then -- ATMA_OF_THE_RAISED_TAIL
target:delMod(MOD_ATT, 40);
target:delMod(MOD_EVA, 40);
elseif (pwr == 73) then -- ATMA_OF_THE_SAND_EMPEROR
target:delMod(MOD_ACC, 40);
target:delMod(MOD_EVA, 40);
elseif (pwr == 74) then -- ATMA_OF_THE_OMNIPOTENT
target:delMod(MOD_DEX, 50);
target:delMod(MOD_HASTE_GEAR, 10);
target:delMod(MOD_ENMITY, 20);
elseif (pwr == 75) then -- ATMA_OF_THE_WAR_LION
target:delMod(MOD_DEX, 20);
target:delMod(MOD_THUNDERRES, 100);
target:delMod(MOD_THUNDER_AFFINITY, 10);
elseif (pwr == 76) then -- ATMA_OF_THE_FROZEN_FETTERS
target:delMod(MOD_INT, 20);
target:delMod(MOD_ICERES, 100);
target:delMod(MOD_ICE_AFFINITY, 10);
elseif (pwr == 77) then -- ATMA_OF_THE_PLAGUEBRINGER
target:delMod(MOD_REGEN, 10);
target:delMod(MOD_STORETP, 20);
target:delMod(MOD_DOUBLE_ATTACK, 7);
elseif (pwr == 78) then -- ATMA_OF_THE_SHRIEKING_ONE
target:delMod(MOD_DEF, 60);
target:delMod(MOD_MDEF, 20);
target:delMod(MOD_STORETP, 20);
elseif (pwr == 79) then -- ATMA_OF_THE_HOLY_MOUNTAIN
target:delMod(MOD_LIGHTRES, 100);
target:delMod(MOD_LIGHTACC, 50);
target:delMod(MOD_LIGHT_AFFINITY, 10);
elseif (pwr == 80) then -- ATMA_OF_THE_LAKE_LURKER
target:delMod(MOD_MND, 20);
target:delMod(MOD_WATERRES, 100);
target:delMod(MOD_WATER_AFFINITY, 10);
elseif (pwr == 81) then -- ATMA_OF_THE_CRUSHING_CUDGEL
target:delMod(MOD_ACC, 20);
target:delMod(MOD_SKILLCHAINDMG, 5);
elseif (pwr == 82) then -- ATMA_OF_PURGATORY
target:delMod(MOD_VIT, 40);
target:delMod(MOD_INT, 40);
elseif (pwr == 83) then -- ATMA_OF_BLIGHTED_BREATH
-- target:delMod(MOD_SONG_CASTING_TIME, -40); Doesnt exist
target:delMod(MOD_LIGHTACC, 40);
elseif (pwr == 84) then -- ATMA_OF_THE_PERSISTENT_PREDATOR
target:delMod(MOD_STORETP, 40);
target:delMod(MOD_TP_BONUS, 10);
elseif (pwr == 85) then -- ATMA_OF_THE_STONE_GOD
target:delMod(MOD_SUBTLE_BLOW, 40);
target:delMod(MOD_ENMITY, 40);
elseif (pwr == 86) then -- ATMA_OF_THE_SUN_EATER
target:delMod(MOD_STORETP, 40);
target:delMod(MOD_TP_BONUS, 40);
elseif (pwr == 87) then -- ATMA_OF_THE_DESPOT
target:delMod(MOD_CHR, 50);
target:delMod(MOD_MAGIC_ABSORB, 15);
target:delMod(MOD_TP_BONUS, 40);
elseif (pwr == 88) then -- ATMA_OF_THE_SOLITARY_ONE
target:delMod(MOD_TRIPLE_ATTACK, 7);
target:delMod(MOD_DMGBREATH, -25);
target:delMod(MOD_ZANSHIN, 10);
elseif (pwr == 89) then -- ATMA_OF_THE_WINGED_GLOOM
target:delMod(MOD_DMG, -25);
target:delMod(MOD_REGEN, 2);
elseif (pwr == 90) then -- ATMA_OF_THE_SEA_DAUGHTER
target:delMod(MOD_REGAIN, 5);
target:delMod(MOD_HASTE_GEAR, -12);
target:delMod(MOD_REGEN, 30);
elseif (pwr == 91) then -- ATMA_OF_THE_HATEFUL_STREAM
-- Not yet implemented
-- http://wiki.ffxiclopedia.org/wiki/Atma_of_the_Hateful_Stream
-- No easy way to do this ATMA, no way I am doing bit crap in onTick for it..
elseif (pwr == 92) then -- ATMA_OF_THE_FOE_FLAYER
target:delMod(MOD_MPP, 20);
target:delMod(MOD_REFRESH, 20);
target:delMod(MOD_FASTCAST, 20);
target:delMod(MOD_MACC, 50);
elseif (pwr == 93) then -- ATMA_OF_THE_ENDLESS_NIGHTMARE
target:delMod(MOD_MND, 20);
target:delMod(MOD_DARKRES, 100);
target:delMod(MOD_DARK_AFFINITY, 10);
elseif (pwr == 94) then -- ATMA_OF_THE_SUNDERING_SLASH
target:delMod(MOD_ATT, 20);
target:delMod(MOD_REGAIN, 3);
elseif (pwr == 95) then -- ATMA_OF_ENTWINED_SERPENTS
target:delMod(MOD_ATT, 20);
target:delMod(MOD_DOUBLE_ATTACK, 15);
elseif (pwr == 96) then -- ATMA_OF_THE_HORNED_BEAST
target:delMod(MOD_ACC, 60);
target:delMod(MOD_PETRIFYRES, 50);
elseif (pwr == 97) then -- ATMA_OF_AQUATIC_ARDOR
target:delMod(MOD_ABSORB_DMG_CHANCE, 6);
target:delMod(MOD_MAGIC_ABSORB, 6);
elseif (pwr == 98) then -- ATMA_OF_THE_FALLEN_ONE
target:delMod(MOD_INT, 30);
target:delMod(MOD_MND, 30);
elseif (pwr == 99) then -- ATMA_OF_FIRES_AND_FLARES
target:delMod(MOD_AGI, 20);
target:delMod(MOD_RATT, 40);
elseif (pwr == 100) then -- ATMA_OF_THE_APOCALYPSE
target:delMod(MOD_TRIPLE_ATTACK, 15);
target:delMod(MOD_GRIMOIRE_INSTANT_CAST, 10);
target:delMod(MOD_RERAISE_III, 1);
elseif (pwr == 101) then -- ATMA_OF_THE_HEIR = 1655;
elseif (pwr == 102) then -- ATMA_OF_THE_HERO = 1656;
elseif (pwr == 103) then -- ATMA_OF_THE_FULL_MOON = 1657;
elseif (pwr == 104) then -- ATMA_OF_ILLUSIONS = 1658;
elseif (pwr == 105) then -- ATMA_OF_THE_BANISHER = 1659;
elseif (pwr == 106) then -- ATMA_OF_THE_SELLSWORD = 1660;
elseif (pwr == 107) then -- ATMA_OF_A_FUTURE_FABULOUS = 1661;
elseif (pwr == 108) then -- ATMA_OF_CAMARADERIE = 1662;
elseif (pwr == 109) then -- ATMA_OF_THE_TRUTHSEEKER = 1663;
elseif (pwr == 110) then -- ATMA_OF_THE_AZURE_SKY = 1664;
elseif (pwr == 111) then -- ATMA_OF_ECHOES = 1665;
elseif (pwr == 112) then -- ATMA_OF_DREAD = 1666;
elseif (pwr == 113) then -- ATMA_OF_AMBITION = 1667;
elseif (pwr == 114) then -- ATMA_OF_THE_BEAST_KING = 1668;
elseif (pwr == 115) then -- ATMA_OF_THE_KIRIN = 1669;
elseif (pwr == 116) then -- ATMA_OF_HELLS_GUARDIAN = 1670;
elseif (pwr == 117) then -- ATMA_OF_LUMINOUS_WINGS = 1671;
elseif (pwr == 118) then -- ATMA_OF_THE_DRAGON_RIDER = 1672;
elseif (pwr == 119) then -- ATMA_OF_THE_IMPENETRABLE = 1673;
elseif (pwr == 120) then -- ATMA_OF_ALPHA_AND_OMEGA = 1674;
elseif (pwr == 121) then -- ATMA_OF_THE_ULTIMATE = 1675;
elseif (pwr == 122) then -- ATMA_OF_THE_HYBRID_BEAST = 1676;
elseif (pwr == 123) then -- ATMA_OF_THE_DARK_DEPTHS = 1677;
elseif (pwr == 124) then -- ATMA_OF_THE_ZENITH = 1678;
elseif (pwr == 125) then -- ATMA_OF_PERFECT_ATTENDANCE = 1679;
elseif (pwr == 126) then -- ATMA_OF_THE_RESCUER = 1680;
elseif (pwr == 127) then -- ATMA_OF_NIGHTMARES = 1681;
elseif (pwr == 128) then -- ATMA_OF_THE_EINHERJAR = 1682;
elseif (pwr == 129) then -- ATMA_OF_THE_ILLUMINATOR = 1683;
elseif (pwr == 130) then -- ATMA_OF_THE_BUSHIN = 1684;
elseif (pwr == 131) then -- ATMA_OF_THE_ACE_ANGLER = 1685;
elseif (pwr == 132) then -- ATMA_OF_THE_MASTER_CRAFTER = 1686;
elseif (pwr == 133) then -- ATMA_OF_INGENUITY = 1687;
elseif (pwr == 134) then -- ATMA_OF_THE_GRIFFONS_CLAW = 1688;
elseif (pwr == 135) then -- ATMA_OF_THE_FETCHING_FOOTPAD = 1689;
elseif (pwr == 136) then -- ATMA_OF_UNDYING_LOYALTY = 1690;
elseif (pwr == 137) then -- ATMA_OF_THE_ROYAL_LINEAGE = 1691;
elseif (pwr == 138) then -- ATMA_OF_THE_SHATTERING_STAR = 1692;
elseif (pwr == 139) then -- ATMA_OF_THE_COBRA_COMMANDER = 1693;
elseif (pwr == 140) then -- ATMA_OF_ROARING_LAUGHTER = 1694;
elseif (pwr == 141) then -- ATMA_OF_THE_DARK_BLADE = 1695;
elseif (pwr == 142) then -- ATMA_OF_THE_DUCAL_GUARD = 1696;
elseif (pwr == 143) then -- ATMA_OF_HARMONY = 1697;
elseif (pwr == 144) then -- ATMA_OF_REVELATIONS = 1698;
elseif (pwr == 145) then -- ATMA_OF_THE_SAVIOR = 1699;
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/West_Sarutabaruta/npcs/Harvesting_Point.lua | 29 | 1125 | -----------------------------------
-- Area: West Sarutabaruta
-- NPC: Harvesting Point
-----------------------------------
package.loaded["scripts/zones/West_Sarutabaruta/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/harvesting");
require("scripts/zones/West_Sarutabaruta/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
startHarvesting(player,player:getZoneID(),npc,trade,0x0385);
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(HARVESTING_IS_POSSIBLE_HERE,1020);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/spells/slowga.lua | 18 | 1212 | -----------------------------------------
-- 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 |
jshackley/darkstar | scripts/globals/spells/regen_iii.lua | 18 | 1391 | -----------------------------------------
-- Spell: Regen III
-- Gradually restores target's HP.
-----------------------------------------
-- Cleric's Briault enhances the effect
-- Scale down duration based on level
-- Composure increases duration 3x
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local hp = 20;
local meritBonus = caster:getMerit(MERIT_REGEN_EFFECT);
--printf("Regen III: Merit Bonus = Extra +%d", meritBonus);
local body = caster:getEquipID(SLOT_BODY);
if (body == 15089 or body == 14502) then
hp = hp+3;
end
hp = hp + caster:getMod(MOD_REGEN_EFFECT) + meritBonus;
local duration = 60;
duration = duration + caster:getMod(MOD_REGEN_DURATION);
duration = calculateDurationForLvl(duration, 66, target:getMainLvl());
if (target:hasStatusEffect(EFFECT_REGEN) and target:getStatusEffect(EFFECT_REGEN):getTier() == 1) then
target:delStatusEffect(EFFECT_REGEN);
end
if (target:addStatusEffect(EFFECT_REGEN,hp,3,duration,0,0,0)) then
spell:setMsg(230);
else
spell:setMsg(75); -- no effect
end
return EFFECT_REGEN;
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/mobskills/Trample.lua | 2 | 1038 | ---------------------------------------------------
-- Trample
-- Family: Bahamut
-- Description: Deals physical damage to enemies in an area of effect. Additional effect: Knockback + Bind
-- Type: Physical
-- Utsusemi/Blink absorb: 2-3 shadows
-- Range:
-- Notes:
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_BIND;
local duration = 30;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, duration);
local numhits = 1;
local accmod = 1;
local dmgmod = 3;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,MOBPARAM_3_SHADOW);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
jshackley/darkstar | scripts/globals/spells/bluemagic/tail_slap.lua | 28 | 1767 | -----------------------------------------
-- Spell: Tail Slap
-- Delivers an area attack. Additional effect: "Stun." Damage varies with TP
-- Spell cost: 77 MP
-- Monster Type: Beastmen
-- Spell Type: Physical (Blunt)
-- Blue Magic Points: 4
-- Stat Bonus: MND+2
-- Level: 69
-- Casting Time: 1 seconds
-- Recast Time: 28.5 seconds
-- Skillchain Element: Water (can open Impaction and Induration; can close Reverberation and Fragmentation)
-- Combos: Store TP
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local params = {};
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.tpmod = TPMOD_ATTACK;
params.dmgtype = DMGTYPE_H2H;
params.scattr = SC_REVERBERATION;
params.numhits = 1;
params.multiplier = 1.625;
params.tp150 = 1.625;
params.tp300 = 1.625;
params.azuretp = 1.625;
params.duppercap = 75;
params.str_wsc = 0.2;
params.dex_wsc = 0.0;
params.vit_wsc = 0.5;
params.agi_wsc = 0.0;
params.int_wsc = 0.0;
params.mnd_wsc = 0.0;
params.chr_wsc = 0.0;
damage = BluePhysicalSpell(caster, target, spell, params);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
return damage;
end; | gpl-3.0 |
hockeychaos/Core-Scripts-1 | CoreScriptsRoot/Modules/Settings/Pages/Record.lua | 1 | 7515 | --[[r
Filename: Record.lua
Written by: jeditkacheff
Version 1.0
Description: Takes care of the Record Tab in Settings Menu
--]]
-------------- SERVICES --------------
local CoreGui = game:GetService("CoreGui")
local RobloxGui = CoreGui:WaitForChild("RobloxGui")
local GuiService = game:GetService("GuiService")
local TextService = game:GetService("TextService")
local Settings = UserSettings()
local GameSettings = Settings.GameSettings
----------- UTILITIES --------------
RobloxGui:WaitForChild("Modules"):WaitForChild("TenFootInterface")
local utility = require(RobloxGui.Modules.Settings.Utility)
local isTenFootInterface = require(RobloxGui.Modules.TenFootInterface):IsEnabled()
local enablePortraitModeSuccess, enablePortraitModeValue = pcall(function() return settings():GetFFlag("EnablePortraitMode") end)
local enablePortraitMode = enablePortraitModeSuccess and enablePortraitModeValue
------------ Variables -------------------
local PageInstance = nil
----------- CLASS DECLARATION --------------
local function Initialize()
local settingsPageFactory = require(RobloxGui.Modules.Settings.SettingsPageFactory)
local this = settingsPageFactory:CreateNewPage()
local isRecordingVideo = false
local recordingEvent = Instance.new("BindableEvent")
recordingEvent.Name = "RecordingEvent"
this.RecordingChanged = recordingEvent.Event
function this:IsRecording()
return isRecordingVideo
end
------ TAB CUSTOMIZATION -------
this.TabHeader.Name = "RecordTab"
this.TabHeader.Icon.Image = "rbxasset://textures/ui/Settings/MenuBarIcons/RecordTab.png"
this.TabHeader.Icon.AspectRatioConstraint.AspectRatio = 41 / 40
this.TabHeader.Icon.Title.Text = "Record"
------ PAGE CUSTOMIZATION -------
this.Page.Name = "Record"
local function makeTextLabel(name, text, isTitle, parent, layoutOrder)
local leftPadding, rightPadding, bottomPadding, textSize, font = 10, 0, 10, 24, Enum.Font.SourceSans
if isTitle then
leftPadding, rightPadding, bottomPadding, textSize, font = 10, 0, 0, 36, Enum.Font.SourceSansBold
end
local container = utility:Create'Frame'
{
Name = name .. "Container",
BackgroundTransparency = 1,
ZIndex = 2,
LayoutOrder = layoutOrder,
Parent = parent
};
local textLabel = utility:Create'TextLabel'
{
Name = name,
BackgroundTransparency = 1,
Text = text,
TextWrapped = true,
Font = font,
TextSize = textSize,
TextColor3 = Color3.new(1,1,1),
TextXAlignment = Enum.TextXAlignment.Left,
TextYAlignment = Enum.TextYAlignment.Top,
Position = UDim2.new(0, leftPadding, 0, 0),
Size = UDim2.new(1, -(leftPadding + rightPadding), 1, 0),
ZIndex = 2,
Parent = container
};
local function onResized(prop)
if prop == "AbsoluteSize" then
local textSize = TextService:GetTextSize(text, textLabel.TextSize, textLabel.Font, Vector2.new(parent.AbsoluteSize.X - leftPadding - rightPadding, 1e4))
container.Size = UDim2.new(1, 0, 0, textSize.Y + bottomPadding)
end
end
onResized("AbsoluteSize")
parent.Changed:connect(onResized)
return textLabel, container
end
local makeTextLabelOld
if not enablePortraitMode then
makeTextLabelOld = function(name, text, bold, size, pos, parent)
local textLabel = utility:Create'TextLabel'
{
Name = name,
BackgroundTransparency = 1,
Text = text,
TextWrapped = true,
Font = Enum.Font.SourceSans,
FontSize = Enum.FontSize.Size24,
TextColor3 = Color3.new(1,1,1),
Size = size,
Position = pos,
TextXAlignment = Enum.TextXAlignment.Left,
TextYAlignment = Enum.TextYAlignment.Top,
ZIndex = 2,
Parent = parent
};
if bold then textLabel.Font = Enum.Font.SourceSansBold end
return textLabel
end
end
-- need to override this function from SettingsPageFactory
-- DropDown menus require hub to to be set when they are initialized
function this:SetHub(newHubRef)
this.HubRef = newHubRef
---------------------------------- SCREENSHOT -------------------------------------
local closeSettingsFunc = function()
this.HubRef:SetVisibility(false, true)
end
local screenshotTitle, screenshotBody
if enablePortraitMode then
screenshotTitle = makeTextLabel("ScreenshotTitle", "Screenshot", true, this.Page, 1)
screenshotBody = makeTextLabel("ScreenshotBody", "By clicking the 'Take Screenshot' button, the menu will close and take a screenshot and save it to your computer.", false, this.Page, 2)
this.ScreenshotButtonRow, this.ScreenshotButton = utility:AddButtonRow(this, "ScreenshotButton", "Take Screenshot", UDim2.new(0, 300, 0, 44), closeSettingsFunc)
this.ScreenshotButtonRow.LayoutOrder = 3
else
screenshotTitle = makeTextLabelOld("ScreenshotTitle", "Screenshot", true, UDim2.new(1,0,0,36), UDim2.new(0,10,0.05,0), this.Page)
screenshotTitle.FontSize = Enum.FontSize.Size36
screenshotBody = makeTextLabelOld("ScreenshotBody", "By clicking the 'Take Screenshot' button, the menu will close and take a screenshot and save it to your computer.", false, UDim2.new(1,-10,0,70), UDim2.new(0,0,1,0), screenshotTitle)
this.ScreenshotButton = utility:MakeStyledButton("ScreenshotButton", "Take Screenshot", UDim2.new(0,300,0,44), closeSettingsFunc, this)
this.ScreenshotButton.Position = UDim2.new(0,400,1,0)
this.ScreenshotButton.Parent = screenshotBody
end
---------------------------------- VIDEO -------------------------------------
local videoTitle, videoBody
if enablePortraitMode then
videoTitle = makeTextLabel("VideoTitle", "Video", true, this.Page, 4)
videoBody = makeTextLabel("VideoBody", "By clicking the 'Record Video' button, the menu will close and start recording your screen.", false, this.Page, 5)
else
videoTitle = makeTextLabelOld("VideoTitle", "Video", true, UDim2.new(1,0,0,36), UDim2.new(0,10,0.5,0), this.Page)
videoTitle.FontSize = Enum.FontSize.Size36
videoBody = makeTextLabelOld("VideoBody", "By clicking the 'Record Video' button, the menu will close and start recording your screen.", false, UDim2.new(1,-10,0,70), UDim2.new(0,0,1,0), videoTitle)
end
local recordButtonRow, recordButton
if enablePortraitMode then
recordButtonRow, recordButton = utility:AddButtonRow(this, "RecordButton", "Record Video", UDim2.new(0, 300, 0, 44), closeSettingsFunc)
recordButtonRow.LayoutOrder = 6
recordButton.MouseButton1Click:connect(function()
recordingEvent:Fire(not isRecordingVideo)
end)
else
recordButton = utility:MakeStyledButton("RecordButton", "Record Video", UDim2.new(0,300,0,44), closeSettingsFunc, this)
recordButton.Position = UDim2.new(0,400,1,0)
recordButton.Parent = videoBody
end
local gameOptions = settings():FindFirstChild("Game Options")
if gameOptions then
gameOptions.VideoRecordingChangeRequest:connect(function(recording)
isRecordingVideo = recording
if recording then
recordButton.RecordButtonTextLabel.Text = "Stop Recording"
else
recordButton.RecordButtonTextLabel.Text = "Record Video"
end
end)
end
recordButton:SetVerb("RecordToggle")
this.ScreenshotButton:SetVerb("Screenshot")
this.Page.Size = UDim2.new(1,0,0,400)
end
return this
end
----------- Public Facing API Additions --------------
PageInstance = Initialize()
PageInstance.Displayed.Event:connect(function(switchedFromGamepadInput)
if switchedFromGamepadInput then
GuiService.SelectedCoreObject = PageInstance.ScreenshotButton
end
end)
return PageInstance
| apache-2.0 |
jshackley/darkstar | scripts/globals/items/bowl_of_eyeball_soup.lua | 35 | 1403 | -----------------------------------------
-- ID: 4453
-- Item: Bowl of Eyeball Soup
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Charisma -10
-- Health Regen While Healing 4
-- Accuracy 12
-- Ranged ACC 12
-----------------------------------------
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,4453);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_CHR, -10);
target:addMod(MOD_HPHEAL, 4);
target:addMod(MOD_ACC, 12);
target:addMod(MOD_RACC, 12);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_CHR, -10);
target:delMod(MOD_HPHEAL, 4);
target:delMod(MOD_ACC, 12);
target:delMod(MOD_RACC, 12);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/globals/fieldsofvalor.lua | 1 | 18848 | -------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/conquest");
-- require("scripts/globals/teleports");
require("scripts/globals/status");
require("scripts/globals/regimereward");
require("scripts/globals/regimeinfo");
require("scripts/globals/common");
--require("scripts/globals/spell_definitions");
-------------------------------------------------
TABS = 12; -- What is this for? Where is it used?
--key item IDs
ELITE_TRAINING_INTRODUCTION = 1116;
ELITE_TRAINING_CHAPTER_1 = 1117;
ELITE_TRAINING_CHAPTER_2 = 1118;
ELITE_TRAINING_CHAPTER_3 = 1119;
ELITE_TRAINING_CHAPTER_4 = 1120;
ELITE_TRAINING_CHAPTER_5 = 1121;
ELITE_TRAINING_CHAPTER_6 = 1122;
ELITE_TRAINING_CHAPTER_7 = 1123;
--EVENT PARAM ID CONSTANTS (change these if even seqs displayed break!)
--onEventUpdate params
FOV_MENU_PAGE_1 = 18;
FOV_MENU_PAGE_2 = 34;
FOV_MENU_PAGE_3 = 50;
FOV_MENU_PAGE_4 = 66;
FOV_MENU_PAGE_5 = 82;
FOV_MENU_VIEW_REGIME = 1;
FOV_MENU_LEVEL_RANGE = 6;
--onEventFinish params
FOV_MENU_REGEN = 53;
FOV_MENU_REFRESH = 69;
FOV_MENU_PROTECT = 85;
FOV_MENU_SHELL = 101;
FOV_MENU_DRIED_MEAT = 117;
FOV_MENU_SALTED_FISH = 133;
FOV_MENU_HARD_COOKIE = 149;
FOV_MENU_INSTANT_NOODLES = 165;
FOV_MENU_RERAISE = 37;
FOV_MENU_HOME_NATION = 21;
FOV_MENU_CANCEL_REGIME = 3;
FOV_MENU_REPEAT_REGIME1 = -2147483630; -- 2147483666;
FOV_MENU_REPEAT_REGIME2 = -2147483614; -- 2147483682;
FOV_MENU_REPEAT_REGIME3 = -2147483598; -- 2147483698;
FOV_MENU_REPEAT_REGIME4 = -2147483582; -- 2147483714;
FOV_MENU_REPEAT_REGIME5 = -2147483566; -- 2147483730;
FOV_MENU_ELITE_INTRO = 36;
FOV_MENU_ELITE_CHAP1 = 52;
FOV_MENU_ELITE_CHAP2 = 68;
FOV_MENU_ELITE_CHAP3 = 84;
FOV_MENU_ELITE_CHAP4 = 100;
FOV_MENU_ELITE_CHAP5 = 116;
FOV_MENU_ELITE_CHAP6 = 132;
FOV_MENU_ELITE_CHAP7 = 148;
--Special Message IDs (these usually don't break)
--Found in Dialog Tables under "Other>System Messages (4)"
FOV_MSG_KILLED_TARGET = 558;
FOV_MSG_COMPLETED_REGIME = 559;
FOV_MSG_GET_GIL = 565;
FOV_MSG_GET_TABS = 566;
FOV_MSG_BEGINS_ANEW = 643;
--MESSAGE ID CONSTANTS (msg id of "new training regime registered!": change this if msg ids break!)
FOV_MSG_EAST_RONFAURE = 9767;
FOV_MSG_WEST_RONFAURE = 10346;
FOV_MSG_NORTH_GUSTABERG = 10317;
FOV_MSG_SOUTH_GUSTABERG = 9795;
FOV_MSG_WEST_SARUTA = 10126;
FOV_MSG_EAST_SARUTA = 9840;
FOV_MSG_KONSCHTAT = 9701;
FOV_MSG_TAHRONGI = 9720;
FOV_MSG_LA_THEINE = 10039;
FOV_MSG_PASHHOW = 10611;
FOV_MSG_JUGNER = 10757;
FOV_MSG_MERIPH = 10490;
FOV_MSG_BATALLIA = 9921;
FOV_MSG_SAUROMAGUE = 9711;
FOV_MSG_ROLANBERRY = 9672;
FOV_MSG_VALKURM = 10166;
FOV_MSG_BUBURIMU = 10177;
FOV_MSG_QUFIM = 10252;
FOV_MSG_RUAUN_GARDENS = 9672;
FOV_MSG_BEAUCEDINE = 10649;
FOV_MSG_YUHTUNGA = 9971;
FOV_MSG_YHOATOR = 9920;
FOV_MSG_WEST_ALTEPA = 9731;
FOV_MSG_EAST_ALTEPA = 9868;
FOV_MSG_XARCABARD = 10156;
FOV_MSG_BEHEMOTH = 9362;
FOV_MSG_ZITAH = 10188;
FOV_MSG_ROMAEVE = 9537;
FOV_MSG_TERIGGAN = 10031;
FOV_MSG_SORROWS = 9517;
--Event IDs
FOV_EVENT_RUAUN_GARDENS = 0x0049;
FOV_EVENT_EAST_RONFAURE = 0x003d;
FOV_EVENT_WEST_RONFAURE = 0x003d;
FOV_EVENT_WEST_SARUTA = 0x0034;
FOV_EVENT_EAST_SARUTA = 0x003d;
FOV_EVENT_NORTH_GUSTABERG = 0x010a;
FOV_EVENT_SOUTH_GUSTABERG = 0x003d;
FOV_EVENT_LA_THEINE = 0x003d;
FOV_EVENT_KONSCHTAT = 0x003d;
FOV_EVENT_TAHRONGI = 0x003d;
FOV_EVENT_PASHHOW = 0x001c;
FOV_EVENT_JUGNER = 0x0020;
FOV_EVENT_MERIPH = 0x002e;
FOV_EVENT_BATALLIA = 0x003d;
FOV_EVENT_SAUROMAGUE = 0x003d;
FOV_EVENT_ROLANBERRY = 0x003d;
FOV_EVENT_VALKURM = 0x002f;
FOV_EVENT_BUBURIMU = 0x0033;
FOV_EVENT_QUFIM = 0x0021;
FOV_EVENT_YUHTUNGA = 0x003d;
FOV_EVENT_YHOATOR = 0x003d;
FOV_EVENT_WEST_ALTEPA = 0x003d;
FOV_EVENT_EAST_ALTEPA = 0x003d; --test
FOV_EVENT_BEAUCEDINE = 0x00da;
FOV_EVENT_XARCABARD = 0x0030;
FOV_EVENT_BEHEMOTH = 0x003d;
FOV_EVENT_ZITAH = 0x003d;
FOV_EVENT_ROMAEVE = 0x003d;
FOV_EVENT_TERIGGAN = 0x003d; --test
FOV_EVENT_SORROWS = 0x003d;
----------------------------------
-- Start FoV onTrigger
----------------------------------
function startFov(eventid,player)
if (FIELD_MANUALS == 1) then
local hasRegime = player:getVar("fov_regimeid");
local tabs = player:getCurrency("valor_point");
player:startEvent(eventid,0,0,0,0,0,0,tabs,hasRegime);
end;
end
----------------------------------
-- Update FoV onEventUpdate
----------------------------------
function updateFov(player,csid,menuchoice,r1,r2,r3,r4,r5)
if (menuchoice==FOV_MENU_PAGE_1) then
local info = getRegimeInfo(r1);
player:updateEvent(info.n1,info.n2,info.n3,info.n4,0,info.sl,info.el,r1);
elseif (menuchoice==FOV_MENU_PAGE_2) then
local info = getRegimeInfo(r2);
player:updateEvent(info.n1,info.n2,info.n3,info.n4,0,info.sl,info.el,r2);
elseif (menuchoice==FOV_MENU_PAGE_3) then
local info = getRegimeInfo(r3);
player:updateEvent(info.n1,info.n2,info.n3,info.n4,0,info.sl,info.el,r3);
elseif (menuchoice==FOV_MENU_PAGE_4) then
local info = getRegimeInfo(r4);
player:updateEvent(info.n1,info.n2,info.n3,info.n4,0,info.sl,info.el,r4);
elseif (menuchoice==FOV_MENU_PAGE_5) then
local info = getRegimeInfo(r5);
player:updateEvent(info.n1,info.n2,info.n3,info.n4,0,info.sl,info.el,r5);
elseif (menuchoice==FOV_MENU_VIEW_REGIME) then --View Regime (this option is only available if they have a regime active!)
--get regime id and numbers killed...
local regid = player:getVar("fov_regimeid");
local info = getRegimeInfo(regid);
if (info.n1 ~= 0) then n1 = player:getVar("fov_numkilled1"); else n1 = 0; end;
if (info.n2 ~= 0) then n2 = player:getVar("fov_numkilled2"); else n2 = 0; end;
if (info.n3 ~= 0) then n3 = player:getVar("fov_numkilled3"); else n3 = 0; end;
if (info.n4 ~= 0) then n4 = player:getVar("fov_numkilled4"); else n4 = 0; end;
player:updateEvent(info.n1,info.n2,info.n3,info.n4,n1,n2,n3,n4);
elseif (menuchoice==FOV_MENU_LEVEL_RANGE) then --Level range and training area on View Regime...
local regid = player:getVar("fov_regimeid");
local info = getRegimeInfo(regid);
player:updateEvent(0,0,0,0,0,info.sl,info.el,0);
end
end
------------------------------------------
-- Finish FoV onEventFinish
------------------------------------------
function finishFov(player,csid,option,r1,r2,r3,r4,r5,msg_offset)
local msg_accept = msg_offset;
local msg_jobs = msg_offset+1;
local msg_cancel = msg_offset+2;
local tabs = player:getCurrency("valor_point");
local HAS_FOOD = player:hasStatusEffect(EFFECT_FOOD);
local HAS_SUPPORT_FOOD = player:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD);
local fov_repeat = bit.band(option, 0x80000000);
if (fov_repeat ~= 0) then
fov_repeat = 1
end
option = bit.band(option, 0x7FFFFFFF);
-- ================= FIELD SUPPORT ===============================================
if (option==FOV_MENU_REGEN) then --Chose Regen. Regen from FoV removes all forms of regen.
--Decrease tabs
if (tabs >= 20) then
player:delCurrency("valor_point", 20);
--Removes regen if on player
player:delStatusEffect(EFFECT_REGEN);
--Adds regen
player:addStatusEffect(EFFECT_REGEN,1,3,3600);
end
elseif (option==FOV_MENU_REFRESH) then --Chose Refresh, removes all other refresh.
--Decrease tabs
if (tabs >= 20) then
player:delCurrency("valor_point", 20);
--Removes refresh if on player
player:delStatusEffect(EFFECT_REFRESH);
player:delStatusEffect(EFFECT_SUBLIMATION_COMPLETE);
player:delStatusEffect(EFFECT_SUBLIMATION_ACTIVATED);
--Add refresh
player:addStatusEffect(EFFECT_REFRESH,1,3,3600, 0, 3);
end
elseif (option==FOV_MENU_PROTECT) then --Chose Protect, removes all other protect.
--Decrease tabs
if (tabs >= 15) then
player:delCurrency("valor_point", 15);
--Removes protect if on player
player:delStatusEffect(EFFECT_PROTECT);
--Work out how much def to give (highest tier dependant on level)
local def = 0;
if (player:getMainLvl()<27) then --before protect 2, give protect 1
def=15;
elseif (player:getMainLvl()<47) then --after p2, before p3
def=40;
elseif (player:getMainLvl()<63) then --after p3, before p4
def=75;
else --after p4
def=120;
end
--Add protect
player:addStatusEffect(EFFECT_PROTECT,def,0,1800);
end
elseif (option==FOV_MENU_SHELL) then --Chose Shell, removes all other shell.
--Decrease tabs
if (tabs >= 15) then
player:delCurrency("valor_point", 15);
--Removes shell if on player
player:delStatusEffect(EFFECT_SHELL);
--Work out how much mdef to give (highest tier dependant on level)
--values taken from Shell scripts by Tenjou.
local def = 0;
if (player:getMainLvl()<37) then --before shell 2, give shell 1
def=24;
elseif (player:getMainLvl()<57) then --after s2, before s3
def=36;
elseif (player:getMainLvl()<68) then --after s3, before s4
def=48;
else --after s4
def=56;
end
--Add shell
player:addStatusEffect(EFFECT_SHELL,def,0,1800);
end
elseif (option==FOV_MENU_RERAISE) then --Reraise chosen.
--Decrease tabs
if (tabs >= 10) then
player:delCurrency("valor_point", 10);
--Remove any other RR
player:delStatusEffect(EFFECT_RERAISE);
--apply RR1, 2 hour duration.
player:addStatusEffect(EFFECT_RERAISE,1,0,7200);
end
elseif (option==FOV_MENU_HOME_NATION) then --Return to home nation.
--Decrease tabs
if (tabs >= 50) then
player:delCurrency("valor_point", 50);
toHomeNation(player); -- Needs an entry in scripts/globals/teleports.lua?
end
elseif (option == FOV_MENU_DRIED_MEAT) then -- Dried Meat: STR+4, Attack +22% (caps at 63)
if (tabs >= 50) then
if (HAS_FOOD == true or HAS_SUPPORT_FOOD == true) then
player:messageBasic(246);
else
player:delCurrency("valor_point", 50);
player:addStatusEffectEx(EFFECT_FIELD_SUPPORT_FOOD, 251, 1, 0, 1800);
end
end
elseif (option == FOV_MENU_SALTED_FISH) then -- Salted Fish: VIT+2 DEF+30% (Caps at 86)
if (tabs >= 50) then
if (HAS_FOOD == true or HAS_SUPPORT_FOOD == true) then
player:messageBasic(246);
else
player:delCurrency("valor_point", 50);
player:addStatusEffectEx(EFFECT_FIELD_SUPPORT_FOOD, 251, 2, 0, 1800);
end
end
elseif (option == FOV_MENU_HARD_COOKIE) then --- Hard Cookie: INT+4, MaxMP+30
if (tabs >= 50) then
if (HAS_FOOD == true or HAS_SUPPORT_FOOD == true) then
player:messageBasic(246);
else
player:delCurrency("valor_point", 50);
player:addStatusEffectEx(EFFECT_FIELD_SUPPORT_FOOD, 251, 3, 0, 1800);
end
end
elseif (option == FOV_MENU_INSTANT_NOODLES) then -- Instant Noodles: VIT+1, Max HP+27% (caps at 75), StoreTP+5
if (tabs >= 50) then
if (HAS_FOOD == true or HAS_SUPPORT_FOOD == true) then
player:messageBasic(246);
else
player:delCurrency("valor_point", 50);
player:addStatusEffectEx(EFFECT_FIELD_SUPPORT_FOOD, 251, 4, 0, 1800);
end
end
elseif (option==FOV_MENU_CANCEL_REGIME) then --Cancelled Regime.
player:setVar("fov_regimeid",0);
player:setVar("fov_numkilled1",0);
player:setVar("fov_numkilled2",0);
player:setVar("fov_numkilled3",0);
player:setVar("fov_numkilled4",0);
player:showText(player,msg_cancel);
elseif (option==FOV_MENU_PAGE_1) then --Page 1
writeRegime(player,r1,msg_accept,msg_jobs,fov_repeat);
elseif (option==FOV_MENU_PAGE_2) then --Page 2
writeRegime(player,r2,msg_accept,msg_jobs,fov_repeat);
elseif (option==FOV_MENU_PAGE_3) then --Page 3
writeRegime(player,r3,msg_accept,msg_jobs,fov_repeat);
elseif (option==FOV_MENU_PAGE_4) then --Page 4
writeRegime(player,r4,msg_accept,msg_jobs,fov_repeat);
elseif (option==FOV_MENU_PAGE_5) then --Page 5
writeRegime(player,r5,msg_accept,msg_jobs,fov_repeat);
elseif (option==FOV_MENU_ELITE_INTRO) then --Want elite, 100tabs
--giveEliteRegime(player,ELITE_TRAINING_CHAPTER_7,100);
elseif (option==FOV_MENU_ELITE_CHAP1) then --Want elite, 150tabs
--local tabs = player:getVar("tabs");
--local newtabs = tabs-150;
--player:setVar("tabs",newtabs);
elseif (option==FOV_MENU_ELITE_CHAP2) then --Want elite, 200tabs
--local tabs = player:getVar("tabs");
--local newtabs = tabs-200;
--player:setVar("tabs",newtabs);
elseif (option==FOV_MENU_ELITE_CHAP3) then --Want elite, 250tabs
elseif (option==FOV_MENU_ELITE_CHAP4) then --Want elite, 300tabs
elseif (option==FOV_MENU_ELITE_CHAP5) then --Want elite, 350tabs
elseif (option==FOV_MENU_ELITE_CHAP6) then --Want elite, 400tabs
elseif (option==FOV_MENU_ELITE_CHAP7) then --Want elite, 450tabs
else
--print("opt is "..option);
end
end
function giveEliteRegime(player,keyitem,cost)
if (player:hasKeyItem(keyitem)) then
--print("has");
--player:messageBasic(98,keyitem);
else
player:delCurrency("valor_point", cost);
player:addKeyItem(keyitem);
end
end
-----------------------------------
--Writes the chosen Regime to the SQL database
-----------------------------------
function writeRegime(player,rid,msg_accept,msg_jobs,regrepeat)
player:setVar("fov_regimeid",rid);
player:setVar("fov_repeat",regrepeat);
player:setVar("fov_numkilled1",0);
player:setVar("fov_numkilled2",0);
player:setVar("fov_numkilled3",0);
player:setVar("fov_numkilled4",0);
local info = getRegimeInfo(rid);
player:setVar("fov_numneeded1",info.n1);
player:setVar("fov_numneeded2",info.n2);
player:setVar("fov_numneeded3",info.n3);
player:setVar("fov_numneeded4",info.n4);
player:showText(player,msg_accept);
player:showText(player,msg_jobs);
end
-----------------------------------
-- killer, mob, regime ID, index in the list of mobs to kill that this mob corresponds to (1-4)
-----------------------------------
function checkRegime(killer,mob,rid,index)
-- dead people get no point
if (killer == nil or killer:getHP() == 0) then
return;
end
partyType = killer:checkSoloPartyAlliance();
if (killer:checkFovAllianceAllowed() == 1) then
partyType = 1;
end
if (killer:getVar("fov_regimeid") == rid) then --player is doing this regime
-- Need to add difference because a lvl1 can xp with a level 75 at ro'maeve
local difference = math.abs(mob:getMainLvl() - killer:getMainLvl());
if ((partyType < 2 and mob:checkBaseExp() and killer:checkDistance(mob) < 100 and difference <= 15) or killer:checkFovDistancePenalty() == 0) then
--get the number of mobs needed/killed
local needed = killer:getVar("fov_numneeded"..index);
local killed = killer:getVar("fov_numkilled"..index);
if (killed < needed) then --increment killed number and save.
killed = killed+1;
killer:messageBasic(FOV_MSG_KILLED_TARGET,killed,needed);
killer:setVar("fov_numkilled"..index,killed);
if (killed == needed) then
local fov_info = getRegimeInfo(rid);
local k1 = killer:getVar("fov_numkilled1");
local k2 = killer:getVar("fov_numkilled2");
local k3 = killer:getVar("fov_numkilled3");
local k4 = killer:getVar("fov_numkilled4");
if (k1==fov_info.n1 and k2==fov_info.n2 and k3==fov_info.n3 and k4==fov_info.n4) then
--complete regime
killer:messageBasic(FOV_MSG_COMPLETED_REGIME);
local reward = getFoVregimeReward(rid);
local tabs = (math.floor(reward/10)*TABS_RATE);
local VanadielEpoch = vanaDay();
-- Award gil and tabs once per day.
if (killer:getVar("fov_LastReward") < VanadielEpoch) then
killer:messageBasic(FOV_MSG_GET_GIL,reward);
killer:addGil(reward);
killer:addCurrency("valor_point", tabs);
killer:messageBasic(FOV_MSG_GET_TABS,tabs,killer:getCurrency("valor_point")); -- Careful about order.
if (REGIME_WAIT == 1) then
killer:setVar("fov_LastReward",VanadielEpoch);
end
end
--TODO: display msgs (based on zone annoyingly, so will need killer:getZoneID() then a lookup)
killer:addExp(reward);
if (k1 ~= 0) then killer:setVar("fov_numkilled1",0); end
if (k2 ~= 0) then killer:setVar("fov_numkilled2",0); end
if (k3 ~= 0) then killer:setVar("fov_numkilled3",0); end
if (k4 ~= 0) then killer:setVar("fov_numkilled4",0); end
if (killer:getVar("fov_repeat") ~= 1) then
killer:setVar("fov_regimeid",0);
killer:setVar("fov_numneeded1",0);
killer:setVar("fov_numneeded2",0);
killer:setVar("fov_numneeded3",0);
killer:setVar("fov_numneeded4",0);
else
killer:messageBasic(FOV_MSG_BEGINS_ANEW);
end
end
end
end
end
end
end
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Southern_San_dOria/npcs/Ostalie.lua | 36 | 2286 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Ostalie
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/globals/conquest");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
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:showText(npc,OSTALIE_SHOP_DIALOG);
stock = {0x1020,4445,1, -- Ether
0x1010,837,1, -- Potion
0x1037,736,2, -- Echo Drops
0x1034,290,3, -- Antidote
0x30b8,144,3, -- Circlet
0x31b8,118,3, -- Cuffs
0x1036,2387,3, -- Eye Drops
0x03fd,450,3, -- Hatchet
0x3388,382,3, -- Leather Belt
0x3389,2430,3, -- Lizard Belt
0x025D,180,3, -- Pickaxe
0x3138,216,3, -- Robe
0x3238,172,3} -- Slops
rank = getNationRank(SANDORIA);
if (rank ~= 1) then
table.insert(stock,0x03fe); --Thief's Tools
table.insert(stock,3643);
table.insert(stock,3);
end
if (rank == 3) then
table.insert(stock,0x03ff); --Living Key
table.insert(stock,5520);
table.insert(stock,3);
end
showNationShop(player, SANDORIA, 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 |
jshackley/darkstar | scripts/globals/abilities/healing_waltz.lua | 18 | 1630 | -----------------------------------
-- Ability: Healing Waltz
-- Removes one detrimental status effect from target party member.
-- Obtained: Dancer Level 35
-- TP Required: 20%
-- Recast Time: 00:15
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (target:getHP() == 0) then
return MSGBASIC_CANNOT_ON_THAT_TARG,0;
elseif (player:hasStatusEffect(EFFECT_SABER_DANCE)) then
return MSGBASIC_UNABLE_TO_USE_JA2, 0;
elseif (player:hasStatusEffect(EFFECT_TRANCE)) then
return 0,0;
elseif (player:getTP() < 20) then
return MSGBASIC_NOT_ENOUGH_TP,0;
else
-- apply waltz recast modifiers
if (player:getMod(MOD_WALTZ_RECAST)~=0) then
local recastMod = -150 * (player:getMod(MOD_WALTZ_RECAST)); -- 750 ms or 5% per merit
if (recastMod <0) then
--TODO
end
end
return 0,0;
end;
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
-- Only remove TP if the player doesn't have Trance.
if not player:hasStatusEffect(EFFECT_TRANCE) then
player:delTP(20);
end;
local effect = target:healingWaltz();
if (effect == EFFECT_NONE) then
ability:setMsg(283); -- no effect
else
ability:setMsg(123);
end
return effect;
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Northern_San_dOria/TextIDs.lua | 8 | 8825 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6587; -- Come back after sorting your inventory.
ITEM_OBTAINED = 6592; -- Obtained: <<<Unknown Parameter (Type: 80) 1>>><<<Possible Special Code: 01>>><<<Possible Special Code: 05>>>
GIL_OBTAINED = 6593; -- Obtained <<<Numeric Parameter 0>>> gil.
KEYITEM_OBTAINED = 6595; -- Obtained key item: <<<Unknown Parameter (Type: 80) 1>>>
NOT_HAVE_ENOUGH_GIL = 6597; -- You do not have enough gil.
HOMEPOINT_SET = 188; -- Home point set!
IMAGE_SUPPORT = 6946; -- Your ?Multiple Choice (Parameter 1)?[fishing/woodworking/smithing/goldsmithing/clothcraft/leatherworking/bonecraft/alchemy/cooking] skills went up ...
GUILD_TERMINATE_CONTRACT = 6960; -- You have terminated your trading contract with the ?Multiple Choice (Parameter 1)?[Fishermen's/Carpenters'/Blacksmiths'/Goldsmiths'/Weavers'/Tanners'/Boneworkers'/Alchemists'/Culinarians'] Guild and formed a new one with the ?Multiple Choice (Parameter 0)?[Fishermen's/Carpenters'/Blacksmiths'/Goldsmiths'/Weavers'/Tanners'/Boneworkers'/Alchemists'/Culinarians'] Guild.?Prompt?
GUILD_NEW_CONTRACT = 6968; -- You have formed a new trading contract with the ?Multiple Choice (Parameter 0)?[Fishermen's/Carpenters'/Blacksmiths'/Goldsmiths'/Weavers'/Tanners'/Boneworkers'/Alchemists'/Culinarians'] Guild.?Prompt?
NO_MORE_GP_ELIGIBLE = 6975; -- You are not eligible to receive guild points at this time
GP_OBTAINED = 6964; -- Obtained <<<Numeric Parameter 0>>> guild points.
NOT_HAVE_ENOUGH_GP = 6981; -- You do not have enough guild points.
MOGHOUSE_EXIT = 12335; -- You have learned your way through the back alleys of San d'Oria! Now you can exit to any area from your residence.
FISHING_MESSAGE_OFFSET = 7408; -- You can't fish here.
-- Conquest System
CONQUEST = 11690; -- You've earned conquest points!
-- Mission Dialogs
ORIGINAL_MISSION_OFFSET = 16; -- Bring me one of those axes, and your mission will be a success. No running away now; we've a proud country to defend!
YOU_ACCEPT_THE_MISSION = 5; -- You accept the mission.
-- Quest Dialog
OLBERGIEUT_DIALOG = 11255; -- Friar Faurbellant is on retreat at the Crag of Holla. Please give
FLYER_REFUSED = 11503; -- Your flyer is refused.
FLYER_ACCEPTED = 12041; -- Your flyer is accepted!
FLYER_ALREADY = 12042; -- This person already has a flyer.
SHIVA_UNLOCKED = 12780; -- You are now able to summon
-- Other Dialog
GUILBERDRIER_DIALOG = 11131; -- A magic shop, you say? A bit of magic would come in handy... I know! I'll have my daughter study it for me!
ABIOLEGET_DIALOG = 11207; -- All of Altana's children are welcome here.
PELLIMIE_DIALOG = 11208; -- Is this your first time here? Join us in prayer!
FITTESEGAT_DIALOG = 11209; -- Paradise is a place without fear, without death!
MAURINE_DIALOG = 11210; -- Papsque Shamonde sometimes addresses the city from the balcony, you know. I long for his blessing, if but once!
PRERIVON_DIALOG = 11211; -- With each sermon, I take another step closer to Paradise.
MALFINE_DIALOG = 11212; -- Truly fortunate are we that words of sacrament are read every day!
COULLENE_DIALOG = 11213; -- Goddess above, deliver us to Paradise!
GUILERME_DIALOG = 11327; -- Behold Chateau d'Oraguille, the greatest fortress in the realm!
PHAVIANE_DIALOG = 11331; -- This is Victory Arch. Beyond lies Southern San d'Oria.
SOCHIENE_DIALOG = 11332; -- You stand before Victory Arch. Southern San d'Oria is on the other side.
PEPIGORT_DIALOG = 11333; -- This gate leads to Port San d'Oria.
RODAILLECE_DIALOG = 11334; -- This is Ranperre Gate. Fiends lurk in the lands beyond, so take caution!
GALAHAD_DIALOG = 11347; -- Welcome to the Consulate of Jeuno. I am Galahad, Consul to San d'Oria.
ISHWAR_DIALOG = 11348; -- May I assist you?
ARIENH_DIALOG = 11349; -- If you have business with Consul Galahad, you'll find him inside.
EMILIA_DIALOG = 11347; -- Welcome to the Consulate of Jeuno.
HELAKU_DIALOG = 11379; -- Leave this building, and you'll see a great fortress to the right. That's Chateau d'Oraguille. And be polite; San d'Orians can be quite touchy.
KASARORO_DIALOG = 11418; -- Step right outside, and you'll see a big castle on the left. That's Chateau d'Oraguille. They're a little touchy in there, so mind your manners!
MAURINNE_DIALOG = 11455; -- This part of town is so lively, I like watching everybody just go about their business.
AIVEDOIR_DIALOG = 11489; -- That's funny. I could have sworn she asked me to meet her here...
CAPIRIA_DIALOG = 11490; -- He's late! I do hope he hasn't forgotten.
BERTENONT_DIALOG = 11491; -- Stars are more beautiful up close. Don't you agree?
GILIPESE_DIALOG = 11512; -- Nothing to report!
BONCORT_DIALOG = 12037; -- Hmm... With magic, I could get hold of materials a mite easier. I'll have to check this art out.
CAPIRIA_DIALOG = 12038; -- A flyer? For me? Some reading material would be a welcome change of pace, indeed!
VILLION_DIALOG = 12039; -- Opening a shop of magic, without consulting me first? I must pay this Regine a visit!
COULLENE_DIALOG = 12040; -- Magic could be of use on my journey to Paradise. Thank you so much!
COULLENE_MESSAGE = 13347; -- Coullene looks over curiously for a moment.
GUILBERDRIER_MESSAGE = 13348; -- Guilberdrier looks over curiously for a moment.
BONCORT_MESSAGE = 13349; -- Boncort looks over curiously for a moment.
CAPIRIA_MESSAGE = 13350; -- Capiria looks over curiously for a moment.
VILLION_MESSAGE = 13351; -- Villion looks over curiously for a moment.
-- Shop Texts
DOGGOMEHR_SHOP_DIALOG = 11525; -- Welcome to the Blacksmiths' Guild shop.
LUCRETIA_SHOP_DIALOG = 11526; -- Blacksmiths' Guild shop, at your service!
CAUZERISTE_SHOP_DIALOG = 11593; -- Welcome! San d'Oria Carpenters' Guild shop, at your service.
ANTONIAN_OPEN_DIALOG = 11608; -- Interested in goods from Aragoneu?
BONCORT_SHOP_DIALOG = 11609; -- Welcome to the Phoenix Perch!
PIRVIDIAUCE_SHOP_DIALOG = 11610; -- Care to see what I have?
PALGUEVION_OPEN_DIALOG = 11611; -- I've got a shipment straight from Valdeaunia!
VICHUEL_OPEN_DIALOG = 11612; -- Fauregandi produce for sale!
ARLENNE_SHOP_DIALOG = 11613; -- Welcome to the Royal Armory!
TAVOURINE_SHOP_DIALOG = 11614; -- Looking for a weapon? We've got many in stock!
ANTONIAN_CLOSED_DIALOG = 11618; -- The Kingdom's influence is waning in Aragoneu. I cannot import goods from that region, though I long to.
PALGUEVION_CLOSED_DIALOG = 11619; -- Would that Valdeaunia came again under San d'Orian dominion, I could then import its goods!
VICHUEL_CLOSED_DIALOG = 11620; -- I'd make a killing selling Fauregandi produce here, but that region's not under San d'Orian control!
ATTARENA_CLOSED_DIALOG = 11621; -- Once all of Li'Telor is back under San d'Orian influence, I'll fill my stock with unique goods from there!
EUGBALLION_CLOSED_DIALOG = 11622; -- I'd be making a fortune selling goods from Qufim Island...if it were only under San d'Orian control!
EUGBALLION_OPEN_DIALOG = 11623; -- Have a look at these goods imported direct from Qufim Island!
CHAUPIRE_SHOP_DIALOG = 11624; -- San d'Orian woodcraft is the finest in the land!
GAUDYLOX_SHOP_DIALOG = 12595; -- You never see Goblinshhh from underworld? Me no bad. Me sell chipshhh. You buy. Use with shhhtone heart. You get lucky!
MILLECHUCA_CLOSED_DIALOG = 12596; -- I've been trying to import goods from Vollbow, but it's so hard to get items from areas that aren't under San d'Orian control.
ATTARENA_OPEN_DIALOG = 12681; -- Good day! Take a look at my selection from Li'Telor!
MILLECHUCA_OPEN_DIALOG = 12682; -- Specialty goods from Vollbow! Specialty goods from Vollbow!
ARACHAGNON_SHOP_DIALOG = 12884; -- Would you be interested in purchasing some adventurer-issue armor? Be careful when selecting, as we accept no refunds.
JUSTI_SHOP_DIALOG = 13537; -- Hello!
-- Harvest Festival
TRICK_OR_TREAT = 13027; -- Trick or treat...
THANK_YOU_TREAT = 13028; -- And now for your treat...
HERE_TAKE_THIS = 12060; -- Here, take this...
IF_YOU_WEAR_THIS = 13030; -- If you put this on and walk around, something...unexpected might happen...
THANK_YOU = 13028; -- Thank you...
-- conquest Base
CONQUEST_BASE = 7249; -- Tallying conquest results...
-- Porter Moogle
RETRIEVE_DIALOG_ID = 18074; -- You retrieve a <item> from the porter moogle's care.
| gpl-3.0 |
opentibia/server | data/scripts/otstd/classes/tile.lua | 3 | 4565 |
function Tile:new(position)
return map:getTile(position)
end
function Tile:type() return "Tile" end
function Tile:getX() return self.x end
function Tile:getY() return self.y end
function Tile:getZ() return self.z end
function Tile:getPosition() return {x = self.x, y = self.y, z = self.z} end
function Tile:northOf(steps) return map:getTile{x = self.x, y = self.y - (steps or 1), z = self.z} end
function Tile:southOf(steps) return map:getTile{x = self.x, y = self.y + (steps or 1), z = self.z} end
function Tile:westOf(steps) return map:getTile{x = self.x - (steps or 1), y = self.y, z = self.z} end
function Tile:eastOf(steps) return map:getTile{x = self.x + (steps or 1), y = self.y, z = self.z} end
function Tile:northeastOf(steps) return map:getTile{x = self.x + (steps or 1), y = self.y - (steps or 1), z = self.z} end
function Tile:northwestOf(steps) return map:getTile{x = self.x - (steps or 1), y = self.y - (steps or 1), z = self.z} end
function Tile:southeastOf(steps) return map:getTile{x = self.x + (steps or 1), y = self.y + (steps or 1), z = self.z} end
function Tile:southwestOf(steps) return map:getTile{x = self.x - (steps or 1), y = self.y + (steps or 1), z = self.z} end
function Tile:getTileInDirection(dir, steps)
if dir == NORTH then return self:northOf(steps)
elseif dir == SOUTH then return self:southOf(steps)
elseif dir == EAST then return self:eastOf(steps)
elseif dir == WEST then return self:westOf(steps)
elseif dir == NORTHEAST then return self:northeastOf(steps)
elseif dir == NORTHWEST then return self:northwestOf(steps)
elseif dir == SOUTHEAST then return self:southeastOf(steps)
elseif dir == SOUTHWEST then return self:southwestOf(steps)
else error "Unknown direction!"
end
end
function Tile:getGround()
return self:getThing(0)
end
function Tile:getPlayers()
local creatures = self:getCreatures()
local players = {}
for _, creature in ipairs(creatures) do
if creature:type() == "Player" then
players:append(creature)
end
end
return players
end
function Tile:getTopThing()
return self:getThing(-1)
end
function Tile:getTopItem()
return self:getItem(-1)
end
function Tile:getTopCreature()
local creatures = self:getCreatures()
for _, creature in ipairs(creatures) do
return creature
end
end
function Tile:getTopMoveableThing()
local t = self:getThing(-1)
if t and not t:isMoveable() then
return nil
end
return t
end
function Tile:pushTo(newPosition)
-- Go by direction?
if typeof(newPosition, "Direction") then
newPosition = self:getTileInDirection(newPosition)
end
for i, thing in ipairs(self:getMoveableItems()) do
thing:moveTo(newPosition)
end
local dir = nil
if self.x - newPosition.x == 1 then
dir = WEST
elseif self.x - newPosition.x == -1 then
dir = EAST
elseif self.y - newPosition.y == 1 then
dir = NORTH
elseif self.y - newPosition.y == -1 then
dir = SOUTH
end
for i, thing in ipairs(self:getCreatures()) do
if dir then
thing:walk(dir, true)
else
thing:moveTo(newPosition)
end
end
end
function Tile:teleportTo(newPosition)
for i, thing in ipairs(self:getMoveableItems()) do
thing:moveTo(newPosition)
end
for i, thing in ipairs(self:getCreatures()) do
thing:moveTo(newPosition)
end
sendMagicEffect(self, MAGIC_EFFECT_POFF)
sendMagicEffect(newPosition, MAGIC_EFFECT_BLUE_BUBBLE)
end
function Tile:isPz()
return self:hasProperty(TILEPROP_PROTECTIONZONE)
end
function Tile:isInHouse()
return self:hasProperty(TILEPROP_HOUSE_TILE)
end
function Tile:isNoPVP()
return self:hasProperty(TILEPROP_NOPVPZONE)
end
function Tile:isNoLogout()
return self:hasProperty(TILEPROP_NOLOGOUT)
end
function Tile:isPVP()
return self:hasProperty(TILEPROP_PVPZONE)
end
function Tile:doesRefresh()
return self:hasProperty(TILEPROP_REFRESH)
end
function Tile:isBlocking()
return self:hasProperty(TILEPROP_BLOCKSOLID)
end
function Tile:floorChange()
return self:hasProperty(TILEPROP_FLOORCHANGE)
end
function Tile:positionChange()
return self:hasProperty(TILEPROP_POSITIONCHANGE)
end
function Tile:floorChangeDown()
return self:hasProperty(TILEPROP_FLOORCHANGE_DOWN)
end
function Tile:floorChangeNorth()
return self:hasProperty(TILEPROP_FLOORCHANGE_NORTH)
end
function Tile:floorChangeSouth()
return self:hasProperty(TILEPROP_FLOORCHANGE_SOUTH)
end
function Tile:floorChangeEast()
return self:hasProperty(TILEPROP_FLOORCHANGE_EAST)
end
function Tile:floorChangeWest()
return self:hasProperty(TILEPROP_FLOORCHANGE_WEST)
end
function Tile:blockProjectile()
return self:hasProperty(TILEPROP_BLOCKPROJECTILE)
end
| gpl-2.0 |
VincentGong/chess | cocos2d-x/cocos/scripting/lua-bindings/auto/api/lua_cocos2dx_extension_auto_api.lua | 11 | 2940 | --------------------------------
-- @module cc
--------------------------------------------------------
-- the cc Scale9Sprite
-- @field [parent=#cc] Scale9Sprite#Scale9Sprite Scale9Sprite preloaded module
--------------------------------------------------------
-- the cc Control
-- @field [parent=#cc] Control#Control Control preloaded module
--------------------------------------------------------
-- the cc ControlButton
-- @field [parent=#cc] ControlButton#ControlButton ControlButton preloaded module
--------------------------------------------------------
-- the cc ControlHuePicker
-- @field [parent=#cc] ControlHuePicker#ControlHuePicker ControlHuePicker preloaded module
--------------------------------------------------------
-- the cc ControlSaturationBrightnessPicker
-- @field [parent=#cc] ControlSaturationBrightnessPicker#ControlSaturationBrightnessPicker ControlSaturationBrightnessPicker preloaded module
--------------------------------------------------------
-- the cc ControlColourPicker
-- @field [parent=#cc] ControlColourPicker#ControlColourPicker ControlColourPicker preloaded module
--------------------------------------------------------
-- the cc ControlPotentiometer
-- @field [parent=#cc] ControlPotentiometer#ControlPotentiometer ControlPotentiometer preloaded module
--------------------------------------------------------
-- the cc ControlSlider
-- @field [parent=#cc] ControlSlider#ControlSlider ControlSlider preloaded module
--------------------------------------------------------
-- the cc ControlStepper
-- @field [parent=#cc] ControlStepper#ControlStepper ControlStepper preloaded module
--------------------------------------------------------
-- the cc ControlSwitch
-- @field [parent=#cc] ControlSwitch#ControlSwitch ControlSwitch preloaded module
--------------------------------------------------------
-- the cc ScrollView
-- @field [parent=#cc] ScrollView#ScrollView ScrollView preloaded module
--------------------------------------------------------
-- the cc TableViewCell
-- @field [parent=#cc] TableViewCell#TableViewCell TableViewCell preloaded module
--------------------------------------------------------
-- the cc TableView
-- @field [parent=#cc] TableView#TableView TableView preloaded module
--------------------------------------------------------
-- the cc EditBox
-- @field [parent=#cc] EditBox#EditBox EditBox preloaded module
--------------------------------------------------------
-- the cc AssetsManager
-- @field [parent=#cc] AssetsManager#AssetsManager AssetsManager preloaded module
--------------------------------------------------------
-- the cc CCBAnimationManager
-- @field [parent=#cc] CCBAnimationManager#CCBAnimationManager CCBAnimationManager preloaded module
--------------------------------------------------------
-- the cc CCBReader
-- @field [parent=#cc] CCBReader#CCBReader CCBReader preloaded module
return nil
| mit |
jshackley/darkstar | scripts/zones/Southern_San_dOria/npcs/Aubejart.lua | 36 | 1466 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Aubejart
-- General Info NPC
-- @zone 230
-- @pos 3 -2 46
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
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(0x246);
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 |
birkett/MCServer | Server/Plugins/APIDump/Hooks/OnCraftingNoRecipe.lua | 36 | 1325 | return
{
HOOK_CRAFTING_NO_RECIPE =
{
CalledWhen = " No built-in crafting recipe is found. Plugin may provide a recipe.",
DefaultFnName = "OnCraftingNoRecipe", -- also used as pagename
Desc = [[
This callback is called when a player places items in their {{cCraftingGrid|crafting grid}} and
Cuberite cannot find a built-in {{cCraftingRecipe|recipe}} for the combination. Plugins may provide
a recipe for the ingredients given.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player whose crafting is reported in this hook" },
{ Name = "Grid", Type = "{{cCraftingGrid}}", Notes = "Contents of the player's crafting grid" },
{ Name = "Recipe", Type = "{{cCraftingRecipe}}", Notes = "The recipe that will be used (can be filled by plugins)" },
},
Returns = [[
If the function returns false or no value, no recipe will be used. If the function returns true, no
other plugin will have their callback called for this event and Cuberite will use the crafting
recipe in Recipe.</p>
<p>
FIXME: To allow plugins give suggestions and overwrite other plugins' suggestions, we should change
the behavior with returning false, so that the recipe will still be used, but fill the recipe with
empty values by default.
]],
}, -- HOOK_CRAFTING_NO_RECIPE
}
| apache-2.0 |
SwadicalRag/hash.js | plugins/lua/sand_modules/timer.lua | 1 | 2342 | local tostring = require "stostring"
local scall = require "scall"
local timers = {}
local simple_timers = {}
local function CreateSimpleTimerPacket( id, delay )
local header = HEADERSTART .. "SimpleTimer," ..
PacketSafe(id, 2) .. ":" .. PacketSafe(delay, 3) .. HEADEREND
return header
end
local function CreateTimerPacket( id, delay, reps )
local header = HEADERSTART .. "Timer," ..
PacketSafe(id, 2) .. ":" .. PacketSafe(delay, 3) .. HEADEREND ..
PacketSafe(reps, 4)
return header
end
local simple_index = 1;
local function Simple( delay, callback )
if ( type( callback ) ~= "function" ) then
error( "bad argument #2 to 'Simple' (function expected, got " .. type( callback ) .. ")", 2 )
end
simple_timers[simple_index] = callback;
writepacket(CreateSimpleTimerPacket(simple_index, delay));
writepacket(EOF);
simple_index = simple_index + 1;
end
function SimpleTimerCallback( id )
local f = simple_timers[id];
simple_timers[id] = nil;
if(f) then
f();
end
end
local function Create( id, delay, reps, callback )
id = tostring(id); -- implementation limitation: all ids must be strings
if ( type( delay ) ~= "number" ) then
error( "bad argument #2 to 'Create' (number expected, got " .. type( delay ) .. ")", 2 )
end
if ( type( reps ) ~= "number" ) then
error( "bad argument #3 to 'Create' (number expected, got " .. type( reps ) .. ")", 2 )
end
if ( reps < 0 ) then
error( "bad argument #3 to 'Create' (number is less than zero)", 2 )
end
if ( type( callback ) ~= "function" ) then
error( "bad argument #4 to 'Create' (function expected, got " .. type( callback ) .. ")", 2 )
end
timers[ "t"..id ] = callback
writepacket(CreateTimerPacket("t"..id, delay, reps)); -- "t"..id because limitations in my regex string i cba to fix
writepacket(EOF);
end
function TimerCallback( id, remove )
local f = timers[id];
if(remove) then timers[id] = nil; end
if(f) then
f();
end
end
local function Remove( id )
timers[ id ] = nil
writepacket(CreateTimerPacket(id, delay, -1));
writepacket(EOF);
end
local function RemoveAll()
for k,v in pairs( timers ) do
writepacket(CreateTimerPacket(id, delay, -1));
writepacket(EOF);
end
timers = {}
simple_timers = {}
end
return {
Simple = Simple,
Create = Create,
Remove = Remove,
RemoveAll = RemoveAll,
}
| cc0-1.0 |
jshackley/darkstar | scripts/zones/Abyssea-Uleguerand/npcs/qm22.lua | 17 | 1386 | -----------------------------------
-- Zone: Abyssea-Ullegrand
-- NPC: ???
-- Spawns: Resheph
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--[[
if (GetMobAction(17813913) == ACTION_NONE) then -- NM not already spawned from this
if (player:hasKeyItem(DECAYING_DIREMITE_FANG)) then
player:startEvent(1020, DECAYING_DIREMITE_FANG); -- Ask if player wants to use KIs
else
player:startEvent(1025, DECAYING_DIREMITE_FANG); -- Do not ask, because player is missing at least 1.
end
end
]]
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 1020 and option == 1) then
SpawnMob(17813913):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:delKeyItem(DECAYING_DIREMITE_FANG);
end
end; | gpl-3.0 |
bsmr-games/OpenRA | mods/ra/maps/monster-tank-madness/monster-tank-madness.lua | 23 | 13934 | AlliedUnits =
{
{ 0, { "1tnk", "1tnk", "2tnk", "2tnk" } },
{ DateTime.Seconds(3), { "e1", "e1", "e1", "e3", "e3" } },
{ DateTime.Seconds(7), { "e6" } }
}
ReinforceBaseUnits = { "1tnk", "1tnk", "2tnk", "arty", "arty" }
CivilianEvacuees = { "c1", "c2", "c5", "c7", "c8" }
USSROutpostFlameTurrets = { FlameTurret1, FlameTurret2 }
ExplosiveBarrels = { ExplosiveBarrel1, ExplosiveBarrel2 }
SuperTanks = { stnk1, stnk2, stnk3 }
SuperTankMoveWaypoints = { HospitalSuperTankPoint, AlliedBaseBottomRight, DemitriTriggerAreaCenter, DemitriLZ }
SuperTankMove = 1
SuperTankHuntWaypoints = { SuperTankHuntWaypoint1, SuperTankHuntWaypoint2, SuperTankHuntWaypoint3, SuperTankHuntWaypoint4 }
SuperTankHunt = 1
SuperTankHuntCounter = 1
ExtractionHeli = "tran"
ExtractionWaypoint = CPos.New(DemitriLZ.Location.X, 0)
ExtractionLZ = DemitriLZ.Location
BeachTrigger = { CPos.New(19, 44), CPos.New(20, 44), CPos.New(21, 44), CPos.New(22, 44), CPos.New(22, 45), CPos.New(23, 45), CPos.New(22, 44), CPos.New(24, 45), CPos.New(24, 46), CPos.New(24, 47), CPos.New(25, 47), CPos.New(25, 48) }
DemitriAreaTrigger = { CPos.New(32, 98), CPos.New(32, 99), CPos.New(33, 99), CPos.New(33, 100), CPos.New(33, 101), CPos.New(33, 102), CPos.New(32, 102), CPos.New(32, 103) }
HospitalAreaTrigger = { CPos.New(43, 41), CPos.New(44, 41), CPos.New(45, 41), CPos.New(46, 41), CPos.New(46, 42), CPos.New(46, 43), CPos.New(46, 44), CPos.New(46, 45), CPos.New(46, 46), CPos.New(45, 46), CPos.New(44, 46), CPos.New(43, 46) }
EvacuateCivilians = function()
local evacuees = Reinforcements.Reinforce(neutral, CivilianEvacuees, { HospitalCivilianSpawnPoint.Location }, 0)
Trigger.OnAnyKilled(evacuees, function()
player.MarkFailedObjective(RescueCivilians)
end)
Trigger.OnAllRemovedFromWorld(evacuees, function()
player.MarkCompletedObjective(RescueCivilians)
end)
Utils.Do(evacuees, function(civ)
Trigger.OnIdle(civ, function()
if civ.Location == AlliedBaseEntryPoint.Location then
civ.Destroy()
else
civ.Move(AlliedBaseEntryPoint.Location)
end
end)
end)
end
SpawnAndMoveAlliedBaseUnits = function()
Media.PlaySpeechNotification(player, "ReinforcementsArrived")
Reinforcements.Reinforce(player, ReinforceBaseUnits, { AlliedBaseEntryPoint.Location, AlliedBaseMovePoint.Location }, 18)
end
SetupAlliedBase = function()
local alliedOutpost = Map.ActorsInBox(AlliedBaseTopLeft.CenterPosition, AlliedBaseBottomRight.CenterPosition,
function(self) return self.Owner == outpost end)
Media.PlaySoundNotification(player, "BaseSetup")
Utils.Do(alliedOutpost, function(building)
building.Owner = player
end)
AlliedBaseHarv.Owner = player
AlliedBaseHarv.FindResources()
FindDemitri = player.AddPrimaryObjective("Find Dr. Demitri. He is likely hiding in the village\n to the far south.")
InfiltrateRadarDome = player.AddPrimaryObjective("Reprogram the super tanks by sending a spy into\n the Soviet radar dome.")
DefendOutpost = player.AddSecondaryObjective("Defend and repair our outpost.")
player.MarkCompletedObjective(FindOutpost)
Trigger.AfterDelay(DateTime.Seconds(1), function() -- don't fail the Objective instantly
Trigger.OnAllRemovedFromWorld(alliedOutpost, function() player.MarkFailedObjective(DefendOutpost) end)
end)
Trigger.AfterDelay(DateTime.Minutes(1) + DateTime.Seconds(40), function()
if not SuperTankDomeIsInfiltrated then
SuperTankAttack = true
Utils.Do(SuperTanks, function(tnk)
if not tnk.IsDead then
Trigger.ClearAll(tnk)
Trigger.AfterDelay(0, function()
Trigger.OnIdle(tnk, function()
if SuperTankAttack then
if tnk.Location == SuperTankMoveWaypoints[SuperTankMove].Location then
SuperTankMove = SuperTankMove + 1
if SuperTankMove == 5 then
SuperTankAttack = false
end
else
tnk.AttackMove(SuperTankMoveWaypoints[SuperTankMove].Location, 2)
end
end
end)
end)
end
end)
end
end)
end
SendAlliedUnits = function()
InitObjectives()
Camera.Position = StartEntryPoint.CenterPosition
Media.PlaySpeechNotification(player, "ReinforcementsArrived")
Utils.Do(AlliedUnits, function(table)
Trigger.AfterDelay(table[1], function()
Reinforcements.Reinforce(player, table[2], { StartEntryPoint.Location, StartMovePoint.Location }, 18)
end)
end)
Trigger.AfterDelay(DateTime.Seconds(1), function() InitialUnitsArrived = true end)
end
SuperTankDomeInfiltrated = function()
turkey.SetStance(player, "Ally")
turkey.SetStance(neutral, "Ally")
SuperTankAttack = true
Utils.Do(SuperTanks, function(tnk)
if not tnk.IsDead then
Trigger.ClearAll(tnk)
tnk.Stop()
if tnk.Location.Y > 61 then
SuperTankHunt = 4
SuperTankHuntCounter = -1
end
Trigger.AfterDelay(0, function()
Trigger.OnIdle(tnk, function()
if SuperTankAttack then
if tnk.Location == SuperTankHuntWaypoints[SuperTankHunt].Location then
SuperTankHunt = SuperTankHunt + SuperTankHuntCounter
if SuperTankHunt == 0 or SuperTankHunt == 5 then
SuperTankAttack = false
end
else
tnk.AttackMove(SuperTankHuntWaypoints[SuperTankHunt].Location, 2)
end
else
tnk.Hunt()
end
end)
end)
end
end)
player.MarkCompletedObjective(InfiltrateRadarDome)
Trigger.AfterDelay(DateTime.Minutes(3), SuperTanksDestruction)
ticked = DateTime.Minutes(3)
Trigger.AfterDelay(DateTime.Seconds(2), function()
Media.PlaySpeechNotification(player, "ControlCenterDeactivated")
Trigger.AfterDelay(DateTime.Seconds(4), function()
Media.DisplayMessage("In 3 minutes the super tanks will self-destruct.")
Media.PlaySpeechNotification(player, "WarningThreeMinutesRemaining")
end)
end)
end
SuperTanksDestruction = function()
local badGuys = Map.ActorsInBox(Map.TopLeft, Map.BottomRight,
function(self) return self.Owner == badguy and self.HasProperty("Health") end)
Utils.Do(badGuys, function(unit)
unit.Kill()
end)
Utils.Do(SuperTanks, function(tnk)
if not tnk.IsDead then
local camera = Actor.Create("camera", true, { Owner = player, Location = tnk.Location })
Trigger.AfterDelay(DateTime.Seconds(3), camera.Destroy)
Trigger.ClearAll(tnk)
tnk.Kill()
end
end)
player.MarkCompletedObjective(DefendOutpost)
end
CreateDemitri = function()
local demitri = Actor.Create("demitri", true, { Owner = player, Location = DemitriChurchSpawnPoint.Location })
demitri.Move(DemitriTriggerAreaCenter.Location)
Media.PlaySpeechNotification(player, "TargetFreed")
EvacuateDemitri = player.AddPrimaryObjective("Evacuate Dr. Demitri with the helicopter waiting\n at our outpost.")
player.MarkCompletedObjective(FindDemitri)
local flarepos = CPos.New(DemitriLZ.Location.X, DemitriLZ.Location.Y - 1)
local demitriLZFlare = Actor.Create("flare", true, { Owner = player, Location = flarepos })
Trigger.AfterDelay(DateTime.Seconds(3), function() Media.PlaySpeechNotification(player, "SignalFlareNorth") end)
local demitriChinook = Reinforcements.ReinforceWithTransport(player, ExtractionHeli, nil, { ExtractionWaypoint, ExtractionLZ })[1]
Trigger.OnAnyKilled({ demitri, demitriChinook }, function()
player.MarkFailedObjective(EvacuateDemitri)
end)
Trigger.OnRemovedFromWorld(demitriChinook, function()
if not demitriChinook.IsDead then
Media.PlaySpeechNotification(player, "TargetRescued")
Trigger.AfterDelay(DateTime.Seconds(1), function() player.MarkCompletedObjective(EvacuateDemitri) end)
Trigger.AfterDelay(DateTime.Seconds(3), SpawnAndMoveAlliedBaseUnits)
end
end)
Trigger.OnRemovedFromWorld(demitri, function()
if not demitriChinook.IsDead and demitriChinook.HasPassengers then
demitriChinook.Move(ExtractionWaypoint)
Trigger.OnIdle(demitriChinook, demitriChinook.Destroy)
demitriLZFlare.Destroy()
end
end)
end
ticked = -1
Tick = function()
ussr.Resources = ussr.Resources - (0.01 * ussr.ResourceCapacity / 25)
if InitialUnitsArrived then -- don't fail the mission straight at the beginning
if not DemitriFound or not SuperTankDomeIsInfiltrated then
if player.HasNoRequiredUnits() then
player.MarkFailedObjective(EliminateSuperTanks)
end
end
end
if ticked > 0 then
UserInterface.SetMissionText("The super tanks self-destruct in " .. Utils.FormatTime(ticked), TimerColor)
ticked = ticked - 1
elseif ticked == 0 then
FinishTimer()
ticked = ticked - 1
end
end
FinishTimer = function()
for i = 0, 9, 1 do
local c = TimerColor
if i % 2 == 0 then
c = HSLColor.White
end
Trigger.AfterDelay(DateTime.Seconds(i), function() UserInterface.SetMissionText("The super tanks are destroyed!", c) end)
end
Trigger.AfterDelay(DateTime.Seconds(10), function() UserInterface.SetMissionText("") end)
end
SetupMission = function()
TestCamera = Actor.Create("camera" ,true , { Owner = player, Location = ProvingGroundsCameraPoint.Location })
Camera.Position = ProvingGroundsCameraPoint.CenterPosition
TimerColor = player.Color
Trigger.AfterDelay(DateTime.Seconds(12), function()
Media.PlaySpeechNotification(player, "StartGame")
Trigger.AfterDelay(DateTime.Seconds(2), SendAlliedUnits)
end)
end
InitPlayers = function()
player = Player.GetPlayer("Greece")
neutral = Player.GetPlayer("Neutral")
outpost = Player.GetPlayer("Outpost")
badguy = Player.GetPlayer("BadGuy")
ussr = Player.GetPlayer("USSR")
ukraine = Player.GetPlayer("Ukraine")
turkey = Player.GetPlayer("Turkey")
player.Cash = 0
ussr.Cash = 2000
Trigger.AfterDelay(0, function() badguy.Resources = badguy.ResourceCapacity * 0.75 end)
Trigger.OnCapture(USSROutpostSilo, function() -- getting money through capturing doesn't work
player.Cash = player.Cash + Utils.RandomInteger(1200, 1300)
end)
end
InitObjectives = function()
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
EliminateSuperTanks = player.AddPrimaryObjective("Eliminate these super tanks.")
CrossRiver = player.AddPrimaryObjective("Find a way to transport your forces to the mainland.")
FindOutpost = player.AddPrimaryObjective("Find our outpost and start repairs on it.")
RescueCivilians = player.AddSecondaryObjective("Evacuate all civilians from the hospital.")
BadGuyObj = badguy.AddPrimaryObjective("Deny the destruction of the super tanks.")
USSRObj = ussr.AddPrimaryObjective("Deny the destruction of the super tanks.")
UkraineObj = ukraine.AddPrimaryObjective("Survive.")
TurkeyObj = turkey.AddPrimaryObjective("Destroy.")
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerLost(player, function()
Media.PlaySpeechNotification(player, "MissionFailed")
ussr.MarkCompletedObjective(USSRObj)
badguy.MarkCompletedObjective(BadGuyObj)
ukraine.MarkCompletedObjective(UkraineObj)
turkey.MarkCompletedObjective(TurkeyObj)
end)
Trigger.OnPlayerWon(player, function()
Media.PlaySpeechNotification(player, "MissionAccomplished")
Media.DisplayMessage("Dr. Demitri has been extracted and the super tanks have been dealt with.")
ussr.MarkFailedObjective(USSRObj)
badguy.MarkFailedObjective(BadGuyObj)
ukraine.MarkFailedObjective(UkraineObj)
turkey.MarkFailedObjective(TurkeyObj)
end)
end
InitTriggers = function()
Trigger.OnAllKilled(SuperTanks, function()
Trigger.AfterDelay(DateTime.Seconds(3), function() player.MarkCompletedObjective(EliminateSuperTanks) end)
end)
Trigger.OnKilled(SuperTankDome, function()
if not SuperTankDomeIsInfiltrated then
player.MarkFailedObjective(InfiltrateRadarDome)
end
end)
Trigger.OnInfiltrated(SuperTankDome, function()
if not SuperTankDomeIsInfiltrated then
SuperTankDomeIsInfiltrated = true
SuperTankDomeInfiltrated()
end
end)
Trigger.OnCapture(SuperTankDome, function()
if not SuperTankDomeIsInfiltrated then
SuperTankDomeIsInfiltrated = true
SuperTankDomeInfiltrated()
end
end)
Trigger.OnKilled(UkraineBarrel, function()
if not UkraineBuilding.IsDead then UkraineBuilding.Kill() end
end)
Trigger.OnAnyKilled(USSROutpostFlameTurrets, function()
Utils.Do(ExplosiveBarrels, function(barrel)
if not barrel.IsDead then barrel.Kill() end
end)
end)
Trigger.OnKilled(DemitriChurch, function()
if not DemitriFound then
player.MarkFailedObjective(FindDemitri)
end
end)
Trigger.OnKilled(Hospital, function()
if not HospitalEvacuated then
HospitalEvacuated = true
player.MarkFailedObjective(RescueCivilians)
end
end)
beachReached = false
Trigger.OnEnteredFootprint(BeachTrigger, function(a, id)
if not beachReached and a.Owner == player then
beachReached = true
Trigger.RemoveFootprintTrigger(id)
player.MarkCompletedObjective(CrossRiver)
end
end)
Trigger.OnPlayerDiscovered(outpost, function(_, discoverer)
if not outpostReached and discoverer == player then
outpostReached = true
SetupAlliedBase()
end
end)
Trigger.OnEnteredFootprint(DemitriAreaTrigger, function(a, id)
if not DemitriFound and a.Owner == player then
DemitriFound = true
Trigger.RemoveFootprintTrigger(id)
CreateDemitri()
end
end)
Trigger.OnEnteredFootprint(HospitalAreaTrigger, function(a, id)
if not HospitalEvacuated and a.Owner == player then
HospitalEvacuated = true
Trigger.RemoveFootprintTrigger(id)
EvacuateCivilians()
end
end)
local tanksLeft = 0
Trigger.OnExitedProximityTrigger(ProvingGroundsCameraPoint.CenterPosition, WDist.New(10 * 1024), function(a, id)
if a.Type == "5tnk" then
tanksLeft = tanksLeft + 1
if tanksLeft == 3 then
if TestCamera.IsInWorld then TestCamera.Destroy() end
Trigger.RemoveProximityTrigger(id)
end
end
end)
end
WorldLoaded = function()
InitPlayers()
InitTriggers()
SetupMission()
end
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Zubyahn.lua | 34 | 1032 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Zubyahn
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x02A2);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Giddeus/npcs/Uu_Zhoumo.lua | 17 | 1973 | -----------------------------------
-- Area: Giddeus
-- NPC: Uu Zhoumo
-- Involved in Mission 2-3
-- @pos -179 16 155 145
-----------------------------------
package.loaded["scripts/zones/Giddeus/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Giddeus/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getCurrentMission(BASTOK) == THE_EMISSARY_WINDURST and trade:hasItemQty(16509,1) and trade:getItemCount() == 1) then -- Trade Aspir Knife
player:startEvent(0x0029);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(SHIELD_OFFERING)) then
player:startEvent(0x002a);
elseif (player:getCurrentMission(BASTOK) == THE_EMISSARY_WINDURST) then
if (player:hasKeyItem(DULL_SWORD)) then
player:startEvent(0x0028);
elseif (player:getVar("MissionStatus") == 5) then
player:startEvent(0x002b);
else
player:startEvent(0x002c);
end
else
player:startEvent(0x002c);
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 == 0x0028) then
player:setVar("MissionStatus",5);
player:delKeyItem(DULL_SWORD);
elseif (csid == 0x0029) then
player:tradeComplete();
player:setVar("MissionStatus",6);
elseif (csid == 0x002a) then
player:setVar("MissionStatus",6);
player:delKeyItem(SHIELD_OFFERING);
end
end;
| gpl-3.0 |
Victek/wrt1900ac-aa | veriksystems/luci-0.11/libs/rpcc/luasrc/rpcc.lua | 93 | 2227 | --[[
LuCIRPCc
(c) 2009 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local util = require "luci.util"
local json = require "luci.json"
local ltn12 = require "luci.ltn12"
local nixio = require "nixio", require "nixio.util"
local tostring, assert, setmetatable = tostring, assert, setmetatable
local error = error
--- LuCI RPC Client.
-- @cstyle instance
module "luci.rpcc"
RQLIMIT = 32 * nixio.const.buffersize
--- Create a new JSON-RPC stream client.
-- @class function
-- @param fd File descriptor
-- @param v1 Use protocol version 1.0
-- @return RPC Client
Client = util.class()
function Client.__init__(self, fd, v1)
self.fd = fd
self.uniqueid = tostring(self):match("0x([a-f0-9]+)")
self.msgid = 1
self.v1 = v1
end
--- Request an RP call and get the response.
-- @param method Remote method
-- @param params Parameters
-- @param notification Notification only?
-- @return response
function Client.request(self, method, params, notification)
local oldchunk = self.decoder and self.decoder.chunk
self.decoder = json.ActiveDecoder(self.fd:blocksource(nil, RQLIMIT))
self.decoder.chunk = oldchunk
local reqid = self.msgid .. self.uniqueid
local reqdata = json.Encoder({
id = (not notification) and (self.msgid .. self.uniqueid) or nil,
jsonrpc = (not self.v1) and "2.0" or nil,
method = method,
params = params
})
ltn12.pump.all(reqdata:source(), self.fd:sink())
if not notification then
self.msgid = self.msgid + 1
local response = self.decoder:get()
assert(response.id == reqid, "Invalid response id")
if response.error then
error(response.error.message or response.error)
end
return response.result
end
end
--- Create a transparent RPC proxy.
-- @param prefix Method prefix
-- @return RPC Proxy object
function Client.proxy(self, prefix)
prefix = prefix or ""
return setmetatable({}, {
__call = function(proxy, ...)
return self:request(prefix, {...})
end,
__index = function(proxy, name)
return self:proxy(prefix .. name .. ".")
end
})
end | gpl-2.0 |
Ombridride/minetest-minetestforfun-server | mods/unifieddyes/init.lua | 8 | 8664 | --[[
Unified Dyes
This mod provides an extension to the Minetest 0.4.x dye system
==============================================================================
Copyright (C) 2012-2013, Vanessa Ezekowitz
Email: vanessaezekowitz@gmail.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
==============================================================================
--]]
--=====================================================================
-- Boilerplate to support localized strings if intllib mod is installed.
local S
if minetest.get_modpath("intllib") then
S = intllib.Getter()
else
S = function(s) return s end
end
-- Items/recipes needed to generate the few base colors that are not
-- provided by the standard dyes mod.
-- Lime
minetest.register_craftitem(":dye:lime", {
description = S("Lime Dye"),
inventory_image = "unifieddyes_lime.png",
groups = { dye=1, excolor_lime=1, unicolor_lime=1 }
})
minetest.register_craft( {
output = "dye:lime 2",
recipe = {{"dye:yellow", "dye:green"}}
})
-- Aqua
minetest.register_craftitem(":dye:aqua", {
description = S("Aqua Dye"),
inventory_image = "unifieddyes_aqua.png",
groups = { dye=1, excolor_aqua=1, unicolor_aqua=1 }
})
minetest.register_craft( {
output = "dye:aqua 2",
recipe = {{"dye:green", "dye:cyan"}},
})
-- Sky blue
minetest.register_craftitem(":dye:skyblue", {
description = S("Sky-blue Dye"),
inventory_image = "unifieddyes_skyblue.png",
groups = { dye=1, excolor_sky_blue=1, unicolor_sky_blue=1 }
})
minetest.register_craft( {
output = "dye:skyblue 2",
recipe = {{"dye:cyan", "dye:blue"}},
})
-- Red-violet
minetest.register_craftitem(":dye:redviolet", {
description = S("Red-violet Dye"),
inventory_image = "unifieddyes_redviolet.png",
groups = { dye=1, excolor_red_violet=1, unicolor_red_violet=1 }
})
minetest.register_craft( {
output = "dye:redviolet 2",
recipe = {{"dye:magenta", "dye:red"}},
})
-- Light grey
minetest.register_craftitem(":dye:light_grey", {
description = S("Light Grey Dye"),
inventory_image = "unifieddyes_lightgrey.png",
groups = { dye=1, excolor_lightgrey=1, unicolor_light_grey=1 }
})
minetest.register_craft( {
output = "dye:light_grey 2",
recipe = {{"dye:grey", "dye:white"}},
})
--[[ Extra craft for black dye
minetest.register_craft( {
type = "shapeless",
output = "dye:black 4",
recipe = {
"default:coal_lump",
},
})]]
-- Extra craft for dark grey dye
minetest.register_craft( {
type = "shapeless",
output = "dye:dark_grey 3",
recipe = {
"dye:black",
"dye:black",
"dye:white",
},
})
-- Extra craft for light grey dye
minetest.register_craft( {
type = "shapeless",
output = "dye:light_grey 3",
recipe = {
"dye:black",
"dye:white",
"dye:white",
},
})
-- Extra craft for green dye
minetest.register_craft( {
type = "shapeless",
output = "dye:green 4",
recipe = {
"default:cactus",
},
})
-- =================================================================
-- Generate all of additional variants of hue, saturation, and
-- brightness.
-- "s50" in a file/item name means "saturation: 50%".
-- Brightness levels in the textures are 33% ("dark"), 66% ("medium"),
-- 100% ("full", but not so-named), and 150% ("light").
local HUES = {
"red",
"orange",
"yellow",
"lime",
"green",
"aqua",
"cyan",
"skyblue",
"blue",
"violet",
"magenta",
"redviolet"
}
local HUES2 = {
"Red",
"Orange",
"Yellow",
"Lime",
"Green",
"Aqua",
"Cyan",
"Sky-blue",
"Blue",
"Violet",
"Magenta",
"Red-violet"
}
for i = 1, 12 do
local hue = HUES[i]
local hue2 = HUES2[i]
minetest.register_craft( {
output = "unifieddyes:dark_" .. hue .. "_s50 2",
recipe = {{"dye:" .. hue, "dye:dark_grey"}},
})
minetest.register_craft( {
type = "shapeless",
output = "unifieddyes:dark_" .. hue .. "_s50 4",
recipe = {
"dye:" .. hue,
"dye:black",
"dye:black",
"dye:white"
},
})
if hue == "green" then
minetest.register_craft( {
type = "shapeless",
output = "dye:dark_green 3",
recipe = {
"dye:" .. hue,
"dye:black",
"dye:black",
},
})
else
minetest.register_craft( {
type = "shapeless",
output = "unifieddyes:dark_" .. hue .. " 3",
recipe = {
"dye:" .. hue,
"dye:black",
"dye:black",
},
})
end
minetest.register_craft( {
output = "unifieddyes:medium_" .. hue .. "_s50 2",
recipe = {{"dye:" .. hue, "dye:grey"}},
})
minetest.register_craft( {
type = "shapeless",
output = "unifieddyes:medium_" .. hue .. "_s50 3",
recipe = {
"dye:" .. hue,
"dye:black",
"dye:white",
},
})
minetest.register_craft( {
output = "unifieddyes:medium_" .. hue .. " 2",
recipe = {
{"dye:" .. hue, "dye:black"},
}
})
minetest.register_craft( {
type = "shapeless",
output = "unifieddyes:" .. hue .. "_s50 2",
recipe = {
"dye:" .. hue,
"dye:grey",
"dye:white",
},
})
minetest.register_craft( {
type = "shapeless",
output = "unifieddyes:" .. hue .. "_s50 4",
recipe = {
"dye:" .. hue,
"dye:white",
"dye:white",
"dye:black",
},
})
if hue ~= "red" then
minetest.register_craft( {
output = "unifieddyes:light_" .. hue .. " 2",
recipe = {{"dye:" .. hue, "dye:white"}},
})
end
minetest.register_craftitem("unifieddyes:dark_" .. hue .. "_s50", {
description = S("Dark " .. hue2 .. " Dye (low saturation)"),
inventory_image = "unifieddyes_dark_" .. hue .. "_s50.png",
groups = { dye=1, ["unicolor_dark_"..hue.."_s50"]=1 }
})
if hue ~= "green" then
minetest.register_craftitem("unifieddyes:dark_" .. hue, {
description = S("Dark " .. hue2 .. " Dye"),
inventory_image = "unifieddyes_dark_" .. hue .. ".png",
groups = { dye=1, ["unicolor_dark_"..hue]=1 }
})
end
minetest.register_craftitem("unifieddyes:medium_" .. hue .. "_s50", {
description = S("Medium " .. hue2 .. " Dye (low saturation)"),
inventory_image = "unifieddyes_medium_" .. hue .. "_s50.png",
groups = { dye=1, ["unicolor_medium_"..hue.."_s50"]=1 }
})
minetest.register_craftitem("unifieddyes:medium_" .. hue, {
description = S("Medium " .. hue2 .. " Dye"),
inventory_image = "unifieddyes_medium_" .. hue .. ".png",
groups = { dye=1, ["unicolor_medium_"..hue]=1 }
})
minetest.register_craftitem("unifieddyes:" .. hue .. "_s50", {
description = S(hue2 .. " Dye (low saturation)"),
inventory_image = "unifieddyes_" .. hue .. "_s50.png",
groups = { dye=1, ["unicolor_"..hue.."_s50"]=1 }
})
if hue ~= "red" then
minetest.register_craftitem("unifieddyes:light_" .. hue, {
description = S("Light " .. hue2 .. " Dye"),
inventory_image = "unifieddyes_light_" .. hue .. ".png",
groups = { dye=1, ["unicolor_light_"..hue]=1 }
})
end
minetest.register_alias("unifieddyes:"..hue, "dye:"..hue)
minetest.register_alias("unifieddyes:pigment_"..hue, "dye:"..hue)
end
minetest.register_alias("unifieddyes:light_red", "dye:pink")
minetest.register_alias("unifieddyes:dark_green", "dye:dark_green")
minetest.register_alias("unifieddyes:white_paint", "dye:white")
minetest.register_alias("unifieddyes:titanium_dioxide", "dye:white")
minetest.register_alias("unifieddyes:lightgrey_paint", "dye:light_grey")
minetest.register_alias("unifieddyes:grey_paint", "dye:grey")
minetest.register_alias("unifieddyes:darkgrey_paint", "dye:dark_grey")
minetest.register_alias("unifieddyes:carbon_black", "dye:black")
minetest.log("action", S("[UnifiedDyes] Loaded!"))
| unlicense |
jshackley/darkstar | scripts/globals/weaponskills/aeolian_edge.lua | 30 | 1342 | -- Aeolian Edge
-- Dagger weapon skill
-- Delivers an area attack that deals wind elemental damage. Damage varies with TP.
-- Skill Level: 290
-- Aligned with the Breeze Gorget, Soil Gorget & Thunder Gorget.
-- Aligned with the Breeze Belt, Soil Belt & Thunder Belt.
-- Element: Wind
-- Skillchain Properties: Impaction / Scission / Detonation
-- Modifiers: DEX:28%; INT:28%
-- 100%TP 200%TP 300%TP
-- 2.75 3.50 4
-----------------------------------
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 = 2.75; params.ftp200 = 3.50; params.ftp300 = 4;
params.str_wsc = 0.0; params.dex_wsc = 0.28; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.28; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.ele = ELE_WIND;
params.skill = SKILL_DAG;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.dex_wsc = 0.4;params.int_wsc = 0.4;
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Upper_Jeuno/npcs/Mairee.lua | 28 | 1800 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Mairee
-- Type: Chocobo Renter
-----------------------------------
require("scripts/globals/chocobo");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local level = player:getMainLvl();
local gil = player:getGil();
if (player:hasKeyItem(CHOCOBO_LICENSE) and level >= 20) then
local price = getChocoboPrice(player);
player:setLocalVar("chocoboPriceOffer",price);
player:startEvent(0x2712,price,gil);
else
player:startEvent(0x2715);
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);
local price = player:getLocalVar("chocoboPriceOffer");
if (csid == 0x2712 and option == 0) then
if (player:delGil(price)) then
updateChocoboPrice(player, price);
local duration = 1800 + (player:getMod(MOD_CHOCOBO_RIDING_TIME) * 60)
player:addStatusEffectEx(EFFECT_CHOCOBO,EFFECT_CHOCOBO,1,0,duration,true);
player:setPos(486,8,-160,0x80,0x69);
end
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Port_Jeuno/npcs/Dohhel.lua | 38 | 1031 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Dohhel
-- Type: Event Scene Replayer
-- @zone: 246
-- @pos -156.031 -2 6.051
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x272c);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
LiberatorUSA/GUCEF | dependencies/agar/gui/premake.lua | 1 | 4243 | --
-- Do not edit!
-- This file was generated from Makefile by BSDbuild 3.2.
--
-- To regenerate this file, get the latest BSDbuild release from
-- http://hypertriton.com/bsdbuild/, the latest Premake release
-- (v3 series) from http://premake.sourceforge.net/, and execute:
--
-- $ make proj
--
package = newpackage()
package.name = "ag_gui_static"
package.kind = "lib"
package.language = "c"
package.guid = "71a13512-13e7-44a6-ba69-e868296cdc34"
dofile("../configure.lua")
tinsert(package.links,{"ag_core_static"})
tinsert(package.links,{"pthreadVC2"})
tinsert(package.links,{"winmm"})
tinsert(package.links,{"wsock32"})
tinsert(package.links,{"ws2_32"})
tinsert(package.links,{"iphlpapi"})
tinsert(package.links,{"SDL"})
tinsert(package.links,{"freetype"})
tinsert(package.links,{"opengl32"})
package.files = {
"drv_sdl_common.c",
"drv_sdlfb.c",
"drv_sdlgl.c",
"drv_gl_common.c",
"drv_wgl.c",
"drv.c",
"drv_sw.c",
"drv_mw.c",
"gui.c",
"widget.c",
"window.c",
"iconmgr.c",
"geometry.c",
"colors.c",
"cursors.c",
"ttf.c",
"text.c",
"keymap.c",
"keymap_latin1.c",
"keymap_compose.c",
"keysyms.c",
"editable.c",
"box.c",
"label.c",
"button.c",
"checkbox.c",
"textbox.c",
"radio.c",
"fixed_plotter.c",
"tlist.c",
"scrollbar.c",
"spinbutton.c",
"titlebar.c",
"toolbar.c",
"fspinbutton.c",
"combo.c",
"ucombo.c",
"units.c",
"nlunits.c",
"hsvpal.c",
"mspinbutton.c",
"mfspinbutton.c",
"statusbar.c",
"menu.c",
"menu_view.c",
"treetbl.c",
"separator.c",
"notebook.c",
"pixmap.c",
"file_dlg.c",
"objsel.c",
"fixed.c",
"numerical.c",
"table.c",
"glview.c",
"mpane.c",
"pane.c",
"console.c",
"graph.c",
"socket.c",
"icon.c",
"progress_bar.c",
"slider.c",
"text_cache.c",
"load_surface.c",
"load_color.c",
"load_xcf.c",
"file_selector.c",
"scrollview.c",
"font_selector.c",
"time_sdl.c",
"debugger.c",
"surface.c",
"widget_legacy.c",
"global_keys.c",
"input_device.c",
"mouse.c",
"keyboard.c",
"packedpixel.c",
"load_bmp.c",
"load_jpg.c",
"load_png.c",
"dir_dlg.c",
"anim.c",
"stylesheet.c",
}
tinsert(package.defines,{"_AGAR_INTERNAL"})
tinsert(package.defines,{"_BSD_SOURCE"})
tinsert(package.includepaths,{"/home/vedge/src/agar-1.5.0/include"})
tinsert(package.defines,{"_AGAR_GUI_INTERNAL"})
package = newpackage()
package.name = "ag_gui"
package.kind = "dll"
package.language = "c"
package.guid = "71a13512-13e7-44a6-ba69-e868296cdc34"
dofile("../configure.lua")
tinsert(package.links,{"ag_core_static"})
tinsert(package.links,{"pthreadVC2"})
tinsert(package.links,{"winmm"})
tinsert(package.links,{"wsock32"})
tinsert(package.links,{"ws2_32"})
tinsert(package.links,{"iphlpapi"})
tinsert(package.links,{"SDL"})
tinsert(package.links,{"freetype"})
tinsert(package.links,{"opengl32"})
package.files = {
"drv_sdl_common.c",
"drv_sdlfb.c",
"drv_sdlgl.c",
"drv_gl_common.c",
"drv_wgl.c",
"drv.c",
"drv_sw.c",
"drv_mw.c",
"gui.c",
"widget.c",
"window.c",
"iconmgr.c",
"geometry.c",
"colors.c",
"cursors.c",
"ttf.c",
"text.c",
"keymap.c",
"keymap_latin1.c",
"keymap_compose.c",
"keysyms.c",
"editable.c",
"box.c",
"label.c",
"button.c",
"checkbox.c",
"textbox.c",
"radio.c",
"fixed_plotter.c",
"tlist.c",
"scrollbar.c",
"spinbutton.c",
"titlebar.c",
"toolbar.c",
"fspinbutton.c",
"combo.c",
"ucombo.c",
"units.c",
"nlunits.c",
"hsvpal.c",
"mspinbutton.c",
"mfspinbutton.c",
"statusbar.c",
"menu.c",
"menu_view.c",
"treetbl.c",
"separator.c",
"notebook.c",
"pixmap.c",
"file_dlg.c",
"objsel.c",
"fixed.c",
"numerical.c",
"table.c",
"glview.c",
"mpane.c",
"pane.c",
"console.c",
"graph.c",
"socket.c",
"icon.c",
"progress_bar.c",
"slider.c",
"text_cache.c",
"load_surface.c",
"load_color.c",
"load_xcf.c",
"file_selector.c",
"scrollview.c",
"font_selector.c",
"time_sdl.c",
"debugger.c",
"surface.c",
"widget_legacy.c",
"global_keys.c",
"input_device.c",
"mouse.c",
"keyboard.c",
"packedpixel.c",
"load_bmp.c",
"load_jpg.c",
"load_png.c",
"dir_dlg.c",
"anim.c",
"stylesheet.c",
}
tinsert(package.defines,{"_AGAR_INTERNAL"})
tinsert(package.defines,{"_BSD_SOURCE"})
tinsert(package.includepaths,{"/home/vedge/src/agar-1.5.0/include"})
tinsert(package.defines,{"_AGAR_GUI_INTERNAL"})
| apache-2.0 |
kubernetes/ingress-nginx | rootfs/etc/nginx/lua/test/util/nodemap_test.lua | 4 | 5660 | local util = require("util")
local nodemap = require("util.nodemap")
local function get_test_backend_single()
return {
name = "access-router-production-web-80",
endpoints = {
{ address = "10.184.7.40", port = "8080", maxFails = 0, failTimeout = 0 }
}
}
end
local function get_test_backend_multi()
return {
name = "access-router-production-web-80",
endpoints = {
{ address = "10.184.7.40", port = "8080", maxFails = 0, failTimeout = 0 },
{ address = "10.184.7.41", port = "8080", maxFails = 0, failTimeout = 0 }
}
}
end
local function get_test_nodes_ignore(endpoint)
local ignore = {}
ignore[endpoint] = true
return ignore
end
describe("Node Map", function()
local test_backend_single = get_test_backend_single()
local test_backend_multi = get_test_backend_multi()
local test_salt = test_backend_single.name
local test_nodes_single = util.get_nodes(test_backend_single.endpoints)
local test_nodes_multi = util.get_nodes(test_backend_multi.endpoints)
local test_endpoint1 = test_backend_multi.endpoints[1].address .. ":" .. test_backend_multi.endpoints[1].port
local test_endpoint2 = test_backend_multi.endpoints[2].address .. ":" .. test_backend_multi.endpoints[2].port
local test_nodes_ignore = get_test_nodes_ignore(test_endpoint1)
describe("new()", function()
context("when no salt has been provided", function()
it("random() returns an unsalted key", function()
local nodemap_instance = nodemap:new(test_nodes_single, nil)
local expected_endpoint = test_endpoint1
local expected_hash_key = ngx.md5(expected_endpoint)
local actual_endpoint
local actual_hash_key
actual_endpoint, actual_hash_key = nodemap_instance:random()
assert.equal(actual_endpoint, expected_endpoint)
assert.equal(expected_hash_key, actual_hash_key)
end)
end)
context("when a salt has been provided", function()
it("random() returns a salted key", function()
local nodemap_instance = nodemap:new(test_nodes_single, test_salt)
local expected_endpoint = test_endpoint1
local expected_hash_key = ngx.md5(test_salt .. expected_endpoint)
local actual_endpoint
local actual_hash_key
actual_endpoint, actual_hash_key = nodemap_instance:random()
assert.equal(actual_endpoint, expected_endpoint)
assert.equal(expected_hash_key, actual_hash_key)
end)
end)
context("when no nodes have been provided", function()
it("random() returns nil", function()
local nodemap_instance = nodemap:new({}, test_salt)
local actual_endpoint
local actual_hash_key
actual_endpoint, actual_hash_key = nodemap_instance:random()
assert.equal(actual_endpoint, nil)
assert.equal(expected_hash_key, nil)
end)
end)
end)
describe("find()", function()
before_each(function()
package.loaded["util.nodemap"] = nil
nodemap = require("util.nodemap")
end)
context("when a hash key is valid", function()
it("find() returns the correct endpoint", function()
local nodemap_instance = nodemap:new(test_nodes_single, test_salt)
local test_hash_key
local expected_endpoint
local actual_endpoint
expected_endpoint, test_hash_key = nodemap_instance:random()
assert.not_equal(expected_endpoint, nil)
assert.not_equal(test_hash_key, nil)
actual_endpoint = nodemap_instance:find(test_hash_key)
assert.equal(actual_endpoint, expected_endpoint)
end)
end)
context("when a hash key is invalid", function()
it("find() returns nil", function()
local nodemap_instance = nodemap:new(test_nodes_single, test_salt)
local test_hash_key = "invalid or nonexistent hash key"
local actual_endpoint
actual_endpoint = nodemap_instance:find(test_hash_key)
assert.equal(actual_endpoint, nil)
end)
end)
end)
describe("random_except()", function()
before_each(function()
package.loaded["util.nodemap"] = nil
nodemap = require("util.nodemap")
end)
context("when nothing has been excluded", function()
it("random_except() returns the correct endpoint", function()
local nodemap_instance = nodemap:new(test_nodes_single, test_salt)
local expected_endpoint = test_endpoint1
local test_hash_key
local actual_endpoint
actual_endpoint, test_hash_key = nodemap_instance:random_except({})
assert.equal(expected_endpoint, actual_endpoint)
assert.not_equal(test_hash_key, nil)
end)
end)
context("when everything has been excluded", function()
it("random_except() returns nil", function()
local nodemap_instance = nodemap:new(test_nodes_single, test_salt)
local actual_hash_key
local actual_endpoint
actual_endpoint, actual_hash_key = nodemap_instance:random_except(test_nodes_ignore)
assert.equal(actual_endpoint, nil)
assert.equal(actual_hash_key, nil)
end)
end)
context("when an endpoint has been excluded", function()
it("random_except() does not return it", function()
local nodemap_instance = nodemap:new(test_nodes_multi, test_salt)
local expected_endpoint = test_endpoint2
local actual_endpoint
local test_hash_key
actual_endpoint, test_hash_key = nodemap_instance:random_except(test_nodes_ignore)
assert.equal(actual_endpoint, expected_endpoint)
assert.not_equal(test_hash_key, nil)
end)
end)
end)
end)
| apache-2.0 |
jshackley/darkstar | scripts/zones/Castle_Oztroja/npcs/Brass_Statue.lua | 19 | 1377 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: Brass Statue
-- Type: Passageway Machine
-- @pos -60.061 -4.348 -61.538 151 (1)
-- @pos -18.599 -19.307 20.024 151 (2)
-- @pos -60 22 -100 151 (3)
-- @pos -100 -72 -19 151 (4)
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Castle_Oztroja/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local Z = npc:getZPos();
if (Z < -15 and Z > -19) then
local DoorID = npc:getID() - 1;
local DoorA = GetNPCByID(DoorID):getAnimation();
if (DoorA == 9) then
GetNPCByID(DoorID):openDoor(6);
end
end
end;
--player:startEvent(0x000d); -- Password event
-----------------------------------
-- 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 |
DarkRainX/ufoai | base/ufos/ui/base.section.production.lua | 2 | 2097 | --!usr/bin/lua
--[[
-- @file
-- @brief Production base menu section
--]]
--[[
Copyright (C) 2002-2020 UFO: Alien Invasion.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
--]]
do
require("ufox.lua")
require("base.section.lua")
local sectionProduction = {
register = function (root_node, base_idx)
local section = base.build_section(root_node, "production", "_Production", "icons/wrench")
section:child("header").on_click = function (sender)
ufo.push_window("production", nil, nil)
end
local add = ufox.build({
name = "show_production",
class = "confunc",
--[[
- @brief Show the production item closest to completion in the base overview (not used in default UI)
- @param production_idx
- @param item_name
- @param completition
--]]
on_click = function (sender, production_idx, item_name, completition)
local content_node = sender:parent():child("content")
local production = ufox.build({
name = "production_" .. production_idx,
-- @todo build a progressbar widget eliminate the component
class = "ProgressBar",
{ name = "label", class = "string", text = "_" .. item_name, },
{ name = "data_bar", class = "bar", value = completition},
}, content_node)
content_node:set_left(29)
content_node:update_height()
end,
}, section)
ufo.cmd(string.format("prod_show_active %d;", base_idx + 0))
end,
}
return sectionProduction
end
| gpl-2.0 |
Ombridride/minetest-minetestforfun-server | mods/mobs/crafts.lua | 8 | 1939 | -- nametag
minetest.register_craftitem("mobs:nametag", {
description = "Nametag",
inventory_image = "mobs_nametag.png",
})
core.register_craft({
type = "shapeless",
output = "mobs:nametag",
recipe = {"default:paper", "dye:black", "farming:string"},
})
-- leather
minetest.register_craftitem("mobs:leather", {
description = "Leather",
inventory_image = "mobs_leather.png",
})
-- raw meat
minetest.register_craftitem("mobs:meat_raw", {
description = "Raw Meat",
inventory_image = "mobs_meat_raw.png",
on_use = minetest.item_eat(3),
})
-- cooked meat
minetest.register_craftitem("mobs:meat", {
description = "Meat",
inventory_image = "mobs_meat.png",
on_use = minetest.item_eat(8),
})
minetest.register_craft({
type = "cooking",
output = "mobs:meat",
recipe = "mobs:meat_raw",
cooktime = 5,
})
-- golden lasso
minetest.register_tool("mobs:magic_lasso", {
description = "Magic Lasso (right-click animal to put in inventory)",
inventory_image = "mobs_magic_lasso.png",
})
minetest.register_craft({
output = "mobs:magic_lasso",
recipe = {
{"farming:string", "default:gold_lump", "farming:string"},
{"default:gold_lump", "default:diamondblock", "default:gold_lump"},
{"farming:string", "default:gold_lump", "farming:string"},
}
})
-- net
minetest.register_tool("mobs:net", {
description = "Net (right-click animal to put in inventory)",
inventory_image = "mobs_net.png",
})
minetest.register_craft({
output = "mobs:net",
recipe = {
{"default:stick", "", "default:stick"},
{"default:stick", "", "default:stick"},
{"farming:string", "default:stick", "farming:string"},
}
})
-- shears (right click to shear animal)
minetest.register_tool("mobs:shears", {
description = "Steel Shears (right-click to shear)",
inventory_image = "mobs_shears.png",
})
minetest.register_craft({
output = 'mobs:shears',
recipe = {
{'', 'default:steel_ingot', ''},
{'', 'group:stick', 'default:steel_ingot'},
}
}) | unlicense |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.