repo_name stringlengths 6 78 | path stringlengths 4 206 | copies stringclasses 281
values | size stringlengths 4 7 | content stringlengths 625 1.05M | license stringclasses 15
values |
|---|---|---|---|---|---|
nyczducky/darkstar | scripts/zones/Windurst_Woods/npcs/Umumu.lua | 14 | 3046 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Umumu
-- Involved In Quest: Making Headlines
-- @pos 32.575 -5.250 141.372 241
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
function testflag(set,flag)
return (set % (2*flag) >= flag)
end
local MakingHeadlines = player:getQuestStatus(WINDURST,MAKING_HEADLINES);
local WildcatWindurst = player:getVar("WildcatWindurst");
if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,3) == false) then
player:startEvent(0x02db);
elseif (MakingHeadlines == 1) then
local prog = player:getVar("QuestMakingHeadlines_var");
-- Variable to track if player has talked to 4 NPCs and a door
-- 1 = Kyume
-- 2 = Yujuju
-- 4 = Hiwom
-- 8 = Umumu
-- 16 = Mahogany Door
if (testflag(tonumber(prog),16) == true) then
player:startEvent(0x017f); -- Advised to go to Naiko
elseif (testflag(tonumber(prog),8) == false) then
player:startEvent(0x017d); -- Get scoop and asked to validate
else
player:startEvent(0x017e); -- Reminded to validate
end
elseif (MakingHeadlines == 2) then
local rand = math.random(1,3);
if (rand == 1) then
player:startEvent(0x0181); -- Conversation after quest completed
elseif (rand == 2) then
player:startEvent(0x0182); -- Conversation after quest completed
elseif (rand == 3) then
player:startEvent(0x019e); -- Standard Conversation
end
else
player:startEvent(0x019e); -- Standard Conversation
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x017d) then
prog = player:getVar("QuestMakingHeadlines_var");
player:addKeyItem(WINDURST_WOODS_SCOOP);
player:messageSpecial(KEYITEM_OBTAINED,WINDURST_WOODS_SCOOP);
player:setVar("QuestMakingHeadlines_var",prog+8);
elseif (csid == 0x02db) then
player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",3,true);
end
end;
| gpl-3.0 |
Stackvana/stack | json.lua | 2 | 7158 | --[[ json.lua
A compact pure-Lua JSON library.
The main functions are: json.stringify, json.parse.
## json.stringify:
This expects the following to be true of any tables being encoded:
* They only have string or number keys. Number keys must be represented as
strings in json; this is part of the json spec.
* They are not recursive. Such a structure cannot be specified in json.
A Lua table is considered to be an array if and only if its set of keys is a
consecutive sequence of positive integers starting at 1. Arrays are encoded like
so: `[2, 3, false, "hi"]`. Any other type of Lua table is encoded as a json
object, encoded like so: `{"key1": 2, "key2": false}`.
Because the Lua nil value cannot be a key, and as a table value is considerd
equivalent to a missing key, there is no way to express the json "null" value in
a Lua table. The only way this will output "null" is if your entire input obj is
nil itself.
An empty Lua table, {}, could be considered either a json object or array -
it's an ambiguous edge case. We choose to treat this as an object as it is the
more general type.
To be clear, none of the above considerations is a limitation of this code.
Rather, it is what we get when we completely observe the json specification for
as arbitrary a Lua object as json is capable of expressing.
## json.parse:
This function parses json, with the exception that it does not pay attention to
\u-escaped unicode code points in strings.
It is difficult for Lua to return null as a value. In order to prevent the loss
of keys with a null value in a json string, this function uses the one-off
table value json.null (which is just an empty table) to indicate null values.
This way you can check if a value is null with the conditional
`val == json.null`.
If you have control over the data and are using Lua, I would recommend just
avoiding null values in your data to begin with.
--]]
local json = {}
-- Internal functions.
local function kind_of(obj)
if type(obj) ~= 'table' then return type(obj) end
local i = 1
for _ in pairs(obj) do
if obj[i] ~= nil then i = i + 1 else return 'table' end
end
if i == 1 then return 'table' else return 'array' end
end
local function escape_str(s)
local in_char = {'\\', '"', '/', '\b', '\f', '\n', '\r', '\t'}
local out_char = {'\\', '"', '/', 'b', 'f', 'n', 'r', 't'}
for i, c in ipairs(in_char) do
s = s:gsub(c, '\\' .. out_char[i])
end
return s
end
-- Returns pos, did_find; there are two cases:
-- 1. Delimiter found: pos = pos after leading space + delim; did_find = true.
-- 2. Delimiter not found: pos = pos after leading space; did_find = false.
-- This throws an error if err_if_missing is true and the delim is not found.
local function skip_delim(str, pos, delim, err_if_missing)
pos = pos + #str:match('^%s*', pos)
if str:sub(pos, pos) ~= delim then
if err_if_missing then
error('Expected ' .. delim .. ' near position ' .. pos)
end
return pos, false
end
return pos + 1, true
end
-- Expects the given pos to be the first character after the opening quote.
-- Returns val, pos; the returned pos is after the closing quote character.
local function parse_str_val(str, pos, val)
val = val or ''
local early_end_error = 'End of input found while parsing string.'
if pos > #str then error(early_end_error) end
local c = str:sub(pos, pos)
if c == '"' then return val, pos + 1 end
if c ~= '\\' then return parse_str_val(str, pos + 1, val .. c) end
-- We must have a \ character.
local esc_map = {b = '\b', f = '\f', n = '\n', r = '\r', t = '\t'}
local nextc = str:sub(pos + 1, pos + 1)
if not nextc then error(early_end_error) end
return parse_str_val(str, pos + 2, val .. (esc_map[nextc] or nextc))
end
-- Returns val, pos; the returned pos is after the number's final character.
local function parse_num_val(str, pos)
local num_str = str:match('^-?%d+%.?%d*[eE]?[+-]?%d*', pos)
local val = tonumber(num_str)
if not val then error('Error parsing number at position ' .. pos .. '.') end
return val, pos + #num_str
end
-- Public values and functions.
function json.stringify(obj, as_key)
local s = {} -- We'll build the string as an array of strings to be concatenated.
local kind = kind_of(obj) -- This is 'array' if it's an array or type(obj) otherwise.
if kind == 'array' then
if as_key then error('Can\'t encode array as key.') end
s[#s + 1] = '['
for i, val in ipairs(obj) do
if i > 1 then s[#s + 1] = ', ' end
s[#s + 1] = json.stringify(val)
end
s[#s + 1] = ']'
elseif kind == 'table' then
if as_key then error('Can\'t encode table as key.') end
s[#s + 1] = '{'
for k, v in pairs(obj) do
if #s > 1 then s[#s + 1] = ', ' end
s[#s + 1] = json.stringify(k, true)
s[#s + 1] = ':'
s[#s + 1] = json.stringify(v)
end
s[#s + 1] = '}'
elseif kind == 'string' then
return '"' .. escape_str(obj) .. '"'
elseif kind == 'number' then
if as_key then return '"' .. tostring(obj) .. '"' end
return tostring(obj)
elseif kind == 'boolean' then
return tostring(obj)
elseif kind == 'nil' then
return 'null'
else
error('Unjsonifiable type: ' .. kind .. '.')
end
return table.concat(s)
end
json.null = {} -- This is a one-off table to represent the null value.
function json.parse(str, pos, end_delim)
pos = pos or 1
if pos > #str then error('Reached unexpected end of input.') end
local pos = pos + #str:match('^%s*', pos) -- Skip whitespace.
local first = str:sub(pos, pos)
if first == '{' then -- Parse an object.
local obj, key, delim_found = {}, true, true
pos = pos + 1
while true do
key, pos = json.parse(str, pos, '}')
if key == nil then return obj, pos end
if not delim_found then error('Comma missing between object items.') end
pos = skip_delim(str, pos, ':', true) -- true -> error if missing.
obj[key], pos = json.parse(str, pos)
pos, delim_found = skip_delim(str, pos, ',')
end
elseif first == '[' then -- Parse an array.
local arr, val, delim_found = {}, true, true
pos = pos + 1
while true do
val, pos = json.parse(str, pos, ']')
if val == nil then return arr, pos end
if not delim_found then error('Comma missing between array items.') end
arr[#arr + 1] = val
pos, delim_found = skip_delim(str, pos, ',')
end
elseif first == '"' then -- Parse a string.
return parse_str_val(str, pos + 1)
elseif first == '-' or first:match('%d') then -- Parse a number.
return parse_num_val(str, pos)
elseif first == end_delim then -- End of an object or array.
return nil, pos + 1
else -- Parse true, false, or null.
local literals = {['true'] = true, ['false'] = false, ['null'] = json.null}
for lit_str, lit_val in pairs(literals) do
local lit_end = pos + #lit_str - 1
if str:sub(pos, lit_end) == lit_str then return lit_val, lit_end + 1 end
end
local pos_info_str = 'position ' .. pos .. ': ' .. str:sub(pos, pos + 10)
error('Invalid json syntax starting at ' .. pos_info_str)
end
end
return json | mit |
wenhulove333/ScutServer | Sample/GameRanking/Client/release/lua/lib/ZyMessageBoxEx.lua | 2 | 14107 |
MB_STYLE_TITLE = 1 --±êÌâ
MB_STYLE_MESSAGE = 2 --ÄÚÈÝ
MB_STYLE_LBUTTON = 3
MB_STYLE_RBUTTON = 4
MB_STYLE_MODIFY = 5
MB_STYLE_THEME = 6
MB_STYLE_GOTO_PAGE = 7
MB_STYLE_CLOSE = 8
MB_STYLE_PROMPT = 9
MB_STYLE_RENAME = 10 --¸üÃû
ID_MBOK = 1 --×ó±ß
ID_MBCANCEL = 2
MB_THEME_NORMAL = 1
--×ÊÔ´
local BackGroundPath="common/black.png";
local BgBox="common/panle_1069.png"
local closeButton="button/list_1046.png"
local ButtonNor="button/button_1011.png"
local ButtonClk="button/button_1012.png"
local topHeight=SY(12)
local edgeWidth=SX(10)
ZyMessageBoxEx = {
_parent = nil,
_layerBox = nil,
_layerBG = nil,
_funCallback = nil,
_nTag = 0,
_userInfo = {},
_tableStyle = {[MB_STYLE_THEME] = MB_THEME_NORMAL},
_tableParam = {},
_edit = nil,
_size = nil,
_bShow = nil,
_editx =nil,
_edity =nil,
_titleColor = nil,
_message = nil
}
-- ´´½¨ÊµÀý
function ZyMessageBoxEx:new()
local instance = {}
setmetatable(instance, self)
self.__index = self
instance:initStyle()
return instance
end
-- ÓÒ°´Å¥(È¡Ïû)°´ÏÂ
function actionMessageboxRightButton(pSender)
local bClose = true
local box = gClassPool[pSender]
if box._funCallback ~= nil then
box._funCallback(ID_MBCANCEL, nil,box._nTag)
end
if bClose then
box:onCloseMessagebox()
end
end
function actionMessageboxLeftButton(pNode)
local bClose= true;
local box = gClassPool[pNode]
if box._tableStyle[MB_STYLE_MODIFY] == true then
box._userInfo.content=box._edit:GetEditText()
elseif box._tableStyle[MB_STYLE_RENAME] == true then
box._userInfo.content=box._edit:GetEditText()
end
if box._funCallback ~= nil then
box._funCallback(ID_MBOK, box._userInfo.content,box._nTag)
end
if bClose then
box:onCloseMessagebox()
end
end
-- ÉèÖòÎÊýº¯Êý
function ZyMessageBoxEx:setTag(tag)
self._nTag = tag
end
-- Ìáʾ¿ò
-- Èç¹û²ÎÊýstrButtonΪnil, ÔòÔÚÓÒÉϽÇÏÔʾһ¸öÍ˳ö°´Å¥
function ZyMessageBoxEx:doPrompt(parent, strTitle, strMessage, strButton,funCallBack)
if ZyMessageBoxEx == self and self._bShow then
return
end
if strMessage==nil or string.len(strMessage)<=0 then
return
end
if funCallBack~=nil then
self._funCallback = funCallBack
end
self._parent = parent
if strTitle then
self._tableStyle[MB_STYLE_TITLE] = strTitle
end
if strMessage then
self._tableStyle[MB_STYLE_MESSAGE] = strMessage
end
if strButton then
self._tableStyle[MB_STYLE_RBUTTON] = strButton
else
self._tableStyle[MB_STYLE_CLOSE] = true
end
self:initMessageBox()
end
-- ѯÎÊ¿ò
function ZyMessageBoxEx:doQuery(parent, strTitle, strMessage, strButtonL, strButtonR, funCallBack,Color)
if ZyMessageBoxEx == self and self._bShow then
return
end
self._parent = parent
self._funCallback = funCallBack
if strTitle then
self._tableStyle[MB_STYLE_TITLE] = strTitle
end
if strMessage then
self._tableStyle[MB_STYLE_MESSAGE] = strMessage
end
if strButtonR then
self._tableStyle[MB_STYLE_RBUTTON] = strButtonR
end
if strButtonL then
self._tableStyle[MB_STYLE_LBUTTON] = strButtonL
end
if Color then
-- self._tableStyle[MB_STYLE_LBUTTON] = strButtonL
end
self:initMessageBox()
end
-- ÐÞ¸Ä
function ZyMessageBoxEx:doModify(parent, title, prompt,strButtonR, strButtonL,funCallback)
self._parent = parent
self._funCallback = funCallback
self._tableParam.prompt = prompt
self._tableStyle[MB_STYLE_MODIFY] = true
if title then
self._tableStyle[MB_STYLE_TITLE] = title
end
if strButtonR then
self._tableStyle[MB_STYLE_RBUTTON] = strButtonR
end
if strButtonL then
self._tableStyle[MB_STYLE_LBUTTON] = strButtonL
end
self:initMessageBox()
end
--¸ÄÃû
function ZyMessageBoxEx:doRename(parent,title,oldName,oldNameStr,newName,strButtonR,strButtonL,funCallback)
self._parent = parent
self._funCallback = funCallback
self._tableParam.oldName = oldName
self._tableParam.oldNameStr = oldNameStr
self._tableParam.newName = newName
self._tableStyle[MB_STYLE_RENAME] = true
if title then
self._tableStyle[MB_STYLE_TITLE] = title
end
if strButtonR then
self._tableStyle[MB_STYLE_RBUTTON] = strButtonR
end
if strButtonL then
self._tableStyle[MB_STYLE_LBUTTON] = strButtonL
end
self:initMessageBox()
end
--£££££££££££££££££££ ÒÔÏÂΪ˽ÓÐ½Ó¿Ú £££££££££££££££££££££££
--
-- ×Ô¶¯Òþ²Ø
function ZyMessageBoxEx:autoHide(fInterval)
if fInterval == nil then
fInterval = 3
end
gClassPool[1] = self
CCScheduler:sharedScheduler():scheduleScriptFunc("timerMBAutoHide", fInterval, false)
end
-- ³õʼ»¯Ò»Ð©²ÎÊý
function ZyMessageBoxEx:initStyle()
self._parent = nil
self._layerBox = nil
self._layerBG = nil
self._funCallback = nil
self._nTag = 0
self._userInfo = {}
self._tableStyle = {[MB_STYLE_THEME] = MB_THEME_NORMAL}
self._tableParam = {}
self._edit = nil
self._size = nil
self._bShow = false
self._editx =nil
self._edity =nil
end
-- ¹Ø±Õ¶Ô»°¿ò
function ZyMessageBoxEx:onCloseMessagebox()
if self._edit ~= nil then
self._edit:release()
self._edit = nil
end
if self._funCallback==nil then
isNetCall=false
end
if self._tableStyle[MB_STYLE_CONTRIBUTE] == true then
for key, value in ipairs(self._tableParam.edit) do
value:release()
end
end
self._parent:removeChild(self._layerBox, true)
self._parent:removeChild(self._layerBG, true)
self:initStyle()
end
function ZyMessageBoxEx:isShow()
return self._bShow
end
-- ³õʼ»¯½çÃæ
function ZyMessageBoxEx:initMessageBox()
self._bShow = true
--´ó±³¾°
local winSize = CCDirector:sharedDirector():getWinSize()
local menuBG = ZyButton:new(BackGroundPath, BackGroundPath)
menuBG:setScaleX(winSize.width / menuBG:getContentSize().width)
menuBG:setScaleY(winSize.height / menuBG:getContentSize().height)
-- menuBG:registerScriptTapHandler(handlerMessageboxBGClick)
menuBG:setPosition(CCPoint(0, 0))
menuBG:addto(self._parent,9)
self._layerBG = menuBG:menu()
-----------------------
--С±³¾°
local messageBox = CCNode:create()
local bg
bg=ZyImage:new(BgBox)
self._size = bg:getContentSize()
bg:resize(self._size)
topHeight=self._size.height*0.1
messageBox:addChild(bg:image(), 0, 0)
messageBox:setContentSize(bg:getContentSize())
messageBox:setPosition(PT((self._parent:getContentSize().width - messageBox:getContentSize().width) / 2,
(self._parent:getContentSize().height - messageBox:getContentSize().height) / 2))
local parentSize = self._parent:getContentSize()
local boxSize = messageBox:getContentSize()
local offsetY = boxSize.height
local offsetX = 0
-- Í˳ö°´Å¥
if self._tableStyle[MB_STYLE_CLOSE] ~= nil then
local button = ZyButton:new(closeButton)
offsetX = boxSize.width - button:getContentSize().width - SPACE_X
offsetY = boxSize.height - button:getContentSize().height - SPACE_Y
button:setPosition(CCPoint(offsetX, offsetY))
button:setTag(1)
button:registerScriptHandler(actionMessageboxRightButton)
button:addto(messageBox)
gClassPool[button:menuItem()] = self
end
-- ±êÌâ
if self._tableStyle[MB_STYLE_TITLE] ~= nil then
local label = CCLabelTTF:labelWithString(self._tableStyle[MB_STYLE_TITLE], FONT_NAME, FONT_SM_SIZE)
if boxSize.height >= parentSize.height * 0.8 then
offsetY = boxSize.height - SPACE_Y * 5 - label:getContentSize().height
else
offsetY = boxSize.height - SPACE_Y * 3.6 - label:getContentSize().height
end
label:setPosition(CCPoint(boxSize.width * 0.5, offsetY))
label:setAnchorPoint(CCPoint(0.5, 0))
messageBox:addChild(label, 0, 0)
end
-- ÄÚÈÝÏûÏ¢
if self._tableStyle[MB_STYLE_MESSAGE] ~= nil then
local size = CCSize(boxSize.width - edgeWidth * 2, offsetY - topHeight * 2)
if self._tableStyle[MB_STYLE_RBUTTON] == nil and self._tableStyle[MB_STYLE_LBUTTON] == nil then
size.height = offsetY - topHeight * 2
else
size.height = offsetY - topHeight * 3 - ZyImage:imageSize(P(Image.image_button_red_c_0)).height
end
--ÎÄ×Ö
local labelWidth= boxSize.width*0.9 - edgeWidth * 2
--local contentStr=string.format("<label>%s</label>",self._tableStyle[MB_STYLE_MESSAGE] )
local contentStr=self._tableStyle[MB_STYLE_MESSAGE]
contentLabel= CCLabelTTF:create(contentStr,FONT_NAME,FONT_SMM_SIZE)
--contentLabel:addto(messageBox,0)
messageBox:addChild(contentLabel,0);
contentLabel:setAnchorPoint(PT(0.5,0.5));
local posX=boxSize.width/2-contentLabel:getContentSize().width/2
local posY=boxSize.height*0.42-contentLabel:getContentSize().height/2
contentLabel:setPosition(PT(posX,posY))
end
--×óÓÒ°´Å¥
if self._tableStyle[MB_STYLE_RBUTTON] ~= nil and self._tableStyle[MB_STYLE_LBUTTON] == nil then
local button, item = UIHelper.Button(P(ButtonNor), P(ButtonClk), actionMessageboxRightButton,
self._tableStyle[MB_STYLE_RBUTTON], kCCTextAlignmentCenter, FONT_SMM_SIZE)
offsetX = (boxSize.width - button:getContentSize().width) / 2
button:setPosition(CCPoint(offsetX, topHeight))
messageBox:addChild(button, 0, 0)
gClassPool[item] = self
elseif self._tableStyle[MB_STYLE_RBUTTON] ~= nil and self._tableStyle[MB_STYLE_LBUTTON] ~= nil then
local button, item = UIHelper.Button(P(ButtonNor), P(ButtonClk), actionMessageboxLeftButton,
self._tableStyle[MB_STYLE_LBUTTON], kCCTextAlignmentCenter, FONT_SMM_SIZE);
offsetX = boxSize.width*0.9-button:getContentSize().width-edgeWidth+SX(5)
button:setPosition(CCPoint(offsetX, topHeight))
messageBox:addChild(button, 0, 0)
gClassPool[item] = self
button, item = UIHelper.Button(P(ButtonNor), P(ButtonClk), actionMessageboxRightButton,
self._tableStyle[MB_STYLE_RBUTTON], kCCTextAlignmentCenter, FONT_SMM_SIZE);
offsetX =edgeWidth -SX(5)+boxSize.width*0.1
button:setPosition(CCPoint(offsetX, topHeight));
messageBox:addChild(button, 0, 0)
gClassPool[item] = self
end
-- ÐÞ¸Ä
if self._tableStyle[MB_STYLE_MODIFY] ~= nil then
local offsetX =edgeWidth+SX(4)
local offsetY =boxSize.height/2+SY(6)
local label = CCLabelTTF:labelWithString(self._tableParam.prompt, FONT_NAME, FONT_SM_SIZE)
label:setAnchorPoint(CCPoint(0, 1))
label:setPosition(CCPoint(offsetX, offsetY))
messageBox:addChild(label, 0)
-- offsetY = offsetY + label:getContentSize().height/2
-- ±à¼¿ò
local size = CCSize(boxSize.width/3, SY(22))
local edit = CScutEdit:new()
edit:init(false, false)
offsetX = messageBox:getPosition().x + edgeWidth+label:getContentSize().width+SY(6)
offsetY =pWinSize.height-messageBox:getPosition().y-boxSize.height/2-SY(6)-size.height+label:getContentSize().height
edit:setRect(CCRect(offsetX, offsetY, size.width, size.height))
self._edit = edit
end
-- ´øÌáʾµÄÊäÈë¿ò
if self._tableStyle[MB_STYLE_PROMPT] ~= nil then
--Ìáʾ
offsetX = parentSize.width/4
offsetY = parentSize.height/5
local prompt = CCLabelTTF:labelWithString(self._message, FONT_NAME, FONT_SM_SIZE)
prompt:setAnchorPoint(CCPoint(0.5, 1))
prompt:setPosition(CCPoint(offsetX, offsetY))
messageBox:addChild(prompt, 0)
end
--¸ÄÃûÊäÈë¿ò
if self._tableStyle[MB_STYLE_RENAME] ~= nil then
local offsetX = nil
local offsetY =boxSize.height*0.5 --+SY(6)
local nameW = 0
local oldLabel = CCLabelTTF:labelWithString(self._tableParam.oldName..": ", FONT_NAME, FONT_SM_SIZE)
oldLabel:setAnchorPoint(CCPoint(0, 1))
messageBox:addChild(oldLabel, 0)
local newLabel = CCLabelTTF:labelWithString(self._tableParam.newName..": ", FONT_NAME, FONT_SM_SIZE)
newLabel:setAnchorPoint(CCPoint(0, 1))
messageBox:addChild(newLabel, 0)
if oldLabel:getContentSize().width > newLabel:getContentSize().width then
nameW = oldLabel:getContentSize().width
else
nameW = newLabel:getContentSize().width
end
offsetX = (boxSize.width/2-nameW)/2
offsetY = offsetY+oldLabel:getContentSize().height+SY(5)
oldLabel:setPosition(CCPoint(offsetX, offsetY))
offsetY =boxSize.height*0.5
newLabel:setPosition(CCPoint(offsetX, offsetY))
local oldStr = CCLabelTTF:labelWithString(self._tableParam.oldNameStr, FONT_NAME, FONT_SM_SIZE)
oldStr:setPosition(CCPoint(offsetX+nameW, oldLabel:getPosition().y))
oldStr:setAnchorPoint(CCPoint(0, 1))
messageBox:addChild(oldStr, 0)
-- ±à¼¿ò
local size = CCSize(boxSize.width/2, newLabel:getContentSize().height)
local edit = CScutEdit:new()
edit:init(false, false)
offsetX = messageBox:getPosition().x + offsetX+nameW
offsetY = parentSize.height/2--size.height/2+oldLabel:getContentSize().height-SY(5)
edit:setRect(CCRect(offsetX, offsetY, size.width, size.height))
self._edit = edit
end
self._layerBox = messageBox
self._parent:addChild(messageBox, 9, 0)
end
function ZyMessageBoxEx:setEditTextSize(size)
self._edit:setMaxText(size)
end
-- ´øÌáʾµÄÊäÈë¿ò
function ZyMessageBoxEx:doModifyWithPrompt(parent, title, prompt,message,strButtonR, strButtonL,funCallback)
self._parent = parent
self._funCallback = funCallback
self._message=message
self._tableStyle[MB_STYLE_PROMPT] = true
if title then
self._tableStyle[MB_STYLE_TITLE] = title
end
if prompt then
self._tableStyle[MB_STYLE_MODIFY] = true
self._tableParam.prompt = prompt
end
if strButtonR then
self._tableStyle[MB_STYLE_RBUTTON] = strButtonR
end
if strButtonL then
self._tableStyle[MB_STYLE_LBUTTON] = strButtonL
end
self:initMessageBox()
end
-- »Øµ÷ÔÐÍ function funCallback(int clickedButtonIndex, void userInfo, int tag)
function ZyMessageBoxEx:setCallbackFun(fun)
self._funCallback = fun
end
| mit |
mehrpouya81/giantbot | plugins/bugzilla.lua | 611 | 3983 | do
local BASE_URL = "https://bugzilla.mozilla.org/rest/"
local function bugzilla_login()
local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password
print("accessing " .. url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_check(id)
-- data = bugzilla_login()
local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey
-- print(url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_listopened(email)
local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey
local res,code = https.request( url )
print(res)
local data = json:decode(res)
return data
end
local function run(msg, matches)
local response = ""
if matches[1] == "status" then
local data = bugzilla_check(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
response = response .. "\n Last update: "..data.bugs[1].last_change_time
response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
print(response)
end
elseif matches[1] == "list" then
local data = bugzilla_listopened(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
-- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
-- response = response .. "\n Last update: "..data.bugs[1].last_change_time
-- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
-- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
-- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
local total = table.map_length(data.bugs)
print("total bugs: " .. total)
local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2]
if total > 0 then
response = response .. ": "
for tableKey, bug in pairs(data.bugs) do
response = response .. "\n #" .. bug.id
response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution
response = response .. "\n Whiteboard: " .. bug.whiteboard
response = response .. "\n Summary: " .. bug.summary
end
end
end
end
return response
end
-- (table)
-- [bugs] = (table)
-- [1] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 927704
-- [whiteboard] = (string) [approved][full processed]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/
-- [2] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 1049337
-- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/
-- total bugs: 2
return {
description = "Lookup bugzilla status update",
usage = "/bot bugzilla [bug number]",
patterns = {
"^/bugzilla (status) (.*)$",
"^/bugzilla (list) (.*)$"
},
run = run
}
end | gpl-2.0 |
nyczducky/darkstar | scripts/globals/mobskills/Lethe_Arrows.lua | 29 | 1094 | ---------------------------------------------
-- Lethe Arrows
--
-- Description: Deals a ranged attack to target. Additional effect: Knockback, Bind, and Amnesia
-- Type: Ranged
-- Utsusemi/Blink absorb: Ignores Utsusemi
-- Range: Unknown
-- 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;
MobStatusEffectMove(mob, target, typeEffect, 1, 0, 120);
typeEffect = EFFECT_AMNESIA;
MobStatusEffectMove(mob, target, typeEffect, 1, 0, 120);
local numhits = 1;
local accmod = 3;
local dmgmod = 4;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,1,2,3);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_RANGED,MOBPARAM_PIERCE,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/commands/changejob.lua | 21 | 1062 | ---------------------------------------------------------------------------------------------------
-- func: changejob
-- desc: Changes the players current job.
---------------------------------------------------------------------------------------------------
require("scripts/globals/status");
cmdprops =
{
permission = 1,
parameters = "si"
};
function onTrigger(player, jobId, level)
jobId = tonumber(jobId) or JOBS[string.upper(jobId)];
if (jobId == nil) then
player:PrintToPlayer("You must enter a job ID or short-name.");
return;
end
if (jobId <= 0 or jobId >= MAX_JOB_TYPE) then
player:PrintToPlayer(string.format("Invalid job '%s' given. Use short-name or id. e.g. WAR", jobId));
return;
end
-- Change the players job..
player:changeJob(jobId);
-- Attempt to set the players level..
if (level ~= nil and level > 0 and level <= 99) then
player:setLevel(level);
else
player:PrintToPlayer("Invalid level given. Level must be between 1 and 99!");
end
end
| gpl-3.0 |
timn/roslua | src/roslua/master_proxy.lua | 1 | 5979 |
----------------------------------------------------------------------------
-- master_proxy.lua - Master XML-RPC proxy
--
-- Created: Thu Jul 22 11:31:05 2010 (at Intel Research, Pittsburgh)
-- License: BSD, cf. LICENSE file of roslua
-- Copyright 2010 Tim Niemueller [www.niemueller.de]
-- 2010 Carnegie Mellon University
-- 2010 Intel Research Pittsburgh
----------------------------------------------------------------------------
--- Master XML-RPC API proxy.
-- This module contains the MasterProxy class to call methods provided via
-- XML-RPC by the ROS master.
-- <br /><br />
-- The user should not have to directly interact with the master. It is used
-- register and unregister topic publishers/subscribers and services, to
-- lookup nodes and services, and to gather information about the master.
-- @copyright Tim Niemueller, Carnegie Mellon University, Intel Research Pittsburgh
-- @release Released under BSD license
module("roslua.master_proxy", package.seeall)
require("roslua")
require("xmlrpc")
require("xmlrpc.http")
assert(xmlrpc._VERSION_MAJOR and (xmlrpc._VERSION_MAJOR > 1 or xmlrpc._VERSION_MAJOR == 1 and xmlrpc._VERSION_MINOR >= 2),
"You must use version 1.2 or newer of lua-xmlrpc")
require("roslua.xmlrpc_post")
__DEBUG = false
MasterProxy = { ros_master_uri = nil, node_name = nil }
--- Constructor.
-- @param ros_master_uri XML-RPC HTTP URI of ROS master
-- @param node_name name of this node
function MasterProxy:new()
local o = {}
setmetatable(o, self)
self.__index = self
return o
end
-- (internal) execute XML-RPC call
-- Will always prefix the arguments with the caller ID.
-- @param method_name name of the method to execute
-- @param ... Arguments depending on the method call
function MasterProxy:do_call(method_name, ...)
local ok, res = xmlrpc.http.call(roslua.master_uri,
method_name, roslua.node_name, ...)
assert(ok, string.format("XML-RPC call %s failed on client: %s",
method_name, tostring(res)))
if res[1] ~= 1 then
error(string.format("XML-RPC call %s failed on server: %s",
method_name, tostring(res[2])), 0)
end
if __DEBUG then
print(string.format("Ok: %s Code: %d Error: %s",
tostring(ok), res[1], res[2]))
end
return res
end
--- Get master system state.
-- @return three array of registered publishers, subscribers, and services
function MasterProxy:getSystemState()
local res = self:do_call("getSystemState")
local publishers = {}
local subscribers = {}
local services = {}
for i, v in ipairs(res[3][1]) do
publishers[v[1]] = v[2]
end
for i, v in ipairs(res[3][2]) do
subscribers[v[1]] = v[2]
end
for i, v in ipairs(res[3][3]) do
services[v[1]] = v[2]
end
return publishers, subscribers, services
end
--- Lookup node by name.
-- @param name of node to lookup
-- @return Slave API XML-RPC HTTP URI
function MasterProxy:lookupNode(node_name)
local res = self:do_call("lookupNode", node_name)
return tostring(res[3])
end
--- Get published topics.
-- @param subgraph subgraph to query from master
-- @return graph of topics
function MasterProxy:getPublishedTopics(subgraph)
local subgraph = subgraph or ""
local res = self:do_call("getPublishedTopics", subgraph)
return res[3]
end
--- Get master URI.
-- Considering that you need to know the URI to call this method is's quite
-- useless.
-- @return ROS master URI
function MasterProxy:getUri()
local res = self:do_call("getUri")
return res[3]
end
--- Lookup service by name.
-- @param service name of service to lookup
-- @return ROS RPC URI of service provider
function MasterProxy:lookupService(service)
local res = self:do_call("lookupService", roslua.resolve(service))
return res[3]
end
--- Start a lookup request.
-- This starts a concurrent execution of lookupService().
-- @param service service to lookup
-- @return XmlRpcRequest handle for the started request
function MasterProxy:lookupService_conc(service)
return roslua.xmlrpc_post.XmlRpcRequest:new(roslua.master_uri, "lookupService",
roslua.node_name,
roslua.resolve(service))
end
--- Register a service with the master.
-- @param service name of service to register
-- @param service_api ROS RPC URI of service
function MasterProxy:registerService(service, service_api)
self:do_call("registerService", roslua.resolve(service),
service_api, roslua.slave_uri)
end
--- Unregister a service from master.
-- @param service name of service to register
-- @param service_api ROS RPC URI of service
function MasterProxy:unregisterService(service, service_api)
self:do_call("unregisterService", roslua.resolve(service), service_api)
end
--- Register subscriber with the master.
-- @param topic topic to register for
-- @param topic_type type of the topic
function MasterProxy:registerSubscriber(topic, topic_type)
local res = self:do_call("registerSubscriber", roslua.resolve(topic),
topic_type, roslua.slave_uri)
return res[3]
end
--- Unregister subscriber from master.
-- @param topic topic to register for
function MasterProxy:unregisterSubscriber(topic)
self:do_call("unregisterSubscriber", roslua.resolve(topic), roslua.slave_uri)
end
--- Register Publisher with the master.
-- @param topic topic to register for
-- @param topic_type type of the topic
function MasterProxy:registerPublisher(topic, topic_type)
local res = self:do_call("registerPublisher",
roslua.resolve(topic), topic_type, roslua.slave_uri)
return res[3]
end
--- Unregister publisher from master.
-- @param topic topic to register for
function MasterProxy:unregisterPublisher(topic)
self:do_call("unregisterPublisher", roslua.resolve(topic), roslua.slave_uri)
end
| bsd-3-clause |
jakianroy/NGUI_To_Be_Best | Assets/LuaFramework/ToLua/Lua/socket/url.lua | 16 | 11058 | -----------------------------------------------------------------------------
-- URI parsing, composition and relative URL resolution
-- LuaSocket toolkit.
-- Author: Diego Nehab
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module
-----------------------------------------------------------------------------
local string = require("string")
local base = _G
local table = require("table")
local socket = require("socket")
socket.url = {}
local _M = socket.url
-----------------------------------------------------------------------------
-- Module version
-----------------------------------------------------------------------------
_M._VERSION = "URL 1.0.3"
-----------------------------------------------------------------------------
-- Encodes a string into its escaped hexadecimal representation
-- Input
-- s: binary string to be encoded
-- Returns
-- escaped representation of string binary
-----------------------------------------------------------------------------
function _M.escape(s)
return (string.gsub(s, "([^A-Za-z0-9_])", function(c)
return string.format("%%%02x", string.byte(c))
end))
end
-----------------------------------------------------------------------------
-- Protects a path segment, to prevent it from interfering with the
-- url parsing.
-- Input
-- s: binary string to be encoded
-- Returns
-- escaped representation of string binary
-----------------------------------------------------------------------------
local function make_set(t)
local s = {}
for i,v in base.ipairs(t) do
s[t[i]] = 1
end
return s
end
-- these are allowed withing a path segment, along with alphanum
-- other characters must be escaped
local segment_set = make_set {
"-", "_", ".", "!", "~", "*", "'", "(",
")", ":", "@", "&", "=", "+", "$", ",",
}
local function protect_segment(s)
return string.gsub(s, "([^A-Za-z0-9_])", function (c)
if segment_set[c] then return c
else return string.format("%%%02x", string.byte(c)) end
end)
end
-----------------------------------------------------------------------------
-- Encodes a string into its escaped hexadecimal representation
-- Input
-- s: binary string to be encoded
-- Returns
-- escaped representation of string binary
-----------------------------------------------------------------------------
function _M.unescape(s)
return (string.gsub(s, "%%(%x%x)", function(hex)
return string.char(base.tonumber(hex, 16))
end))
end
-----------------------------------------------------------------------------
-- Builds a path from a base path and a relative path
-- Input
-- base_path
-- relative_path
-- Returns
-- corresponding absolute path
-----------------------------------------------------------------------------
local function absolute_path(base_path, relative_path)
if string.sub(relative_path, 1, 1) == "/" then return relative_path end
local path = string.gsub(base_path, "[^/]*$", "")
path = path .. relative_path
path = string.gsub(path, "([^/]*%./)", function (s)
if s ~= "./" then return s else return "" end
end)
path = string.gsub(path, "/%.$", "/")
local reduced
while reduced ~= path do
reduced = path
path = string.gsub(reduced, "([^/]*/%.%./)", function (s)
if s ~= "../../" then return "" else return s end
end)
end
path = string.gsub(reduced, "([^/]*/%.%.)$", function (s)
if s ~= "../.." then return "" else return s end
end)
return path
end
-----------------------------------------------------------------------------
-- Parses a url and returns a table with all its parts according to RFC 2396
-- The following grammar describes the names given to the URL parts
-- <url> ::= <scheme>://<authority>/<path>;<params>?<query>#<fragment>
-- <authority> ::= <userinfo>@<host>:<port>
-- <userinfo> ::= <user>[:<password>]
-- <path> :: = {<segment>/}<segment>
-- Input
-- url: uniform resource locator of request
-- default: table with default values for each field
-- Returns
-- table with the following fields, where RFC naming conventions have
-- been preserved:
-- scheme, authority, userinfo, user, password, host, port,
-- path, params, query, fragment
-- Obs:
-- the leading '/' in {/<path>} is considered part of <path>
-----------------------------------------------------------------------------
function _M.parse(url, default)
-- initialize default parameters
local parsed = {}
for i,v in base.pairs(default or parsed) do parsed[i] = v end
-- empty url is parsed to nil
if not url or url == "" then return nil, "invalid url" end
-- remove whitespace
-- url = string.gsub(url, "%s", "")
-- get fragment
url = string.gsub(url, "#(.*)$", function(f)
parsed.fragment = f
return ""
end)
-- get scheme
url = string.gsub(url, "^([%w][%w%+%-%.]*)%:",
function(s) parsed.scheme = s; return "" end)
-- get authority
url = string.gsub(url, "^//([^/]*)", function(n)
parsed.authority = n
return ""
end)
-- get query string
url = string.gsub(url, "%?(.*)", function(q)
parsed.query = q
return ""
end)
-- get params
url = string.gsub(url, "%;(.*)", function(p)
parsed.params = p
return ""
end)
-- path is whatever was left
if url ~= "" then parsed.path = url end
local authority = parsed.authority
if not authority then return parsed end
authority = string.gsub(authority,"^([^@]*)@",
function(u) parsed.userinfo = u; return "" end)
authority = string.gsub(authority, ":([^:%]]*)$",
function(p) parsed.port = p; return "" end)
if authority ~= "" then
-- IPv6?
parsed.host = string.match(authority, "^%[(.+)%]$") or authority
end
local userinfo = parsed.userinfo
if not userinfo then return parsed end
userinfo = string.gsub(userinfo, ":([^:]*)$",
function(p) parsed.password = p; return "" end)
parsed.user = userinfo
return parsed
end
-----------------------------------------------------------------------------
-- Rebuilds a parsed URL from its components.
-- Components are protected if any reserved or unallowed characters are found
-- Input
-- parsed: parsed URL, as returned by parse
-- Returns
-- a stringing with the corresponding URL
-----------------------------------------------------------------------------
function _M.build(parsed)
local ppath = _M.parse_path(parsed.path or "")
local url = _M.build_path(ppath)
if parsed.params then url = url .. ";" .. parsed.params end
if parsed.query then url = url .. "?" .. parsed.query end
local authority = parsed.authority
if parsed.host then
authority = parsed.host
if string.find(authority, ":") then -- IPv6?
authority = "[" .. authority .. "]"
end
if parsed.port then authority = authority .. ":" .. parsed.port end
local userinfo = parsed.userinfo
if parsed.user then
userinfo = parsed.user
if parsed.password then
userinfo = userinfo .. ":" .. parsed.password
end
end
if userinfo then authority = userinfo .. "@" .. authority end
end
if authority then url = "//" .. authority .. url end
if parsed.scheme then url = parsed.scheme .. ":" .. url end
if parsed.fragment then url = url .. "#" .. parsed.fragment end
-- url = string.gsub(url, "%s", "")
return url
end
-----------------------------------------------------------------------------
-- Builds a absolute URL from a base and a relative URL according to RFC 2396
-- Input
-- base_url
-- relative_url
-- Returns
-- corresponding absolute url
-----------------------------------------------------------------------------
function _M.absolute(base_url, relative_url)
local base_parsed
if base.type(base_url) == "table" then
base_parsed = base_url
base_url = _M.build(base_parsed)
else
base_parsed = _M.parse(base_url)
end
local relative_parsed = _M.parse(relative_url)
if not base_parsed then return relative_url
elseif not relative_parsed then return base_url
elseif relative_parsed.scheme then return relative_url
else
relative_parsed.scheme = base_parsed.scheme
if not relative_parsed.authority then
relative_parsed.authority = base_parsed.authority
if not relative_parsed.path then
relative_parsed.path = base_parsed.path
if not relative_parsed.params then
relative_parsed.params = base_parsed.params
if not relative_parsed.query then
relative_parsed.query = base_parsed.query
end
end
else
relative_parsed.path = absolute_path(base_parsed.path or "",
relative_parsed.path)
end
end
return _M.build(relative_parsed)
end
end
-----------------------------------------------------------------------------
-- Breaks a path into its segments, unescaping the segments
-- Input
-- path
-- Returns
-- segment: a table with one entry per segment
-----------------------------------------------------------------------------
function _M.parse_path(path)
local parsed = {}
path = path or ""
--path = string.gsub(path, "%s", "")
string.gsub(path, "([^/]+)", function (s) table.insert(parsed, s) end)
for i = 1, #parsed do
parsed[i] = _M.unescape(parsed[i])
end
if string.sub(path, 1, 1) == "/" then parsed.is_absolute = 1 end
if string.sub(path, -1, -1) == "/" then parsed.is_directory = 1 end
return parsed
end
-----------------------------------------------------------------------------
-- Builds a path component from its segments, escaping protected characters.
-- Input
-- parsed: path segments
-- unsafe: if true, segments are not protected before path is built
-- Returns
-- path: corresponding path stringing
-----------------------------------------------------------------------------
function _M.build_path(parsed, unsafe)
local path = ""
local n = #parsed
if unsafe then
for i = 1, n-1 do
path = path .. parsed[i]
path = path .. "/"
end
if n > 0 then
path = path .. parsed[n]
if parsed.is_directory then path = path .. "/" end
end
else
for i = 1, n-1 do
path = path .. protect_segment(parsed[i])
path = path .. "/"
end
if n > 0 then
path = path .. protect_segment(parsed[n])
if parsed.is_directory then path = path .. "/" end
end
end
if parsed.is_absolute then path = "/" .. path end
return path
end
return _M
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Quicksand_Caves/npcs/Treasure_Coffer.lua | 13 | 4641 | -----------------------------------
-- Area: Quicksand Caves
-- NPC: Treasure Coffer
-- @zone 208
-- @pos 615 -6 -681
-----------------------------------
package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/treasure");
require("scripts/globals/quests");
require("scripts/zones/Quicksand_Caves/TextIDs");
local TreasureType = "Coffer";
local TreasureLvL = 53;
local TreasureMinLvL = 43;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- trade:hasItemQty(1054,1); -- Treasure Key
-- trade:hasItemQty(1115,1); -- Skeleton Key
-- trade:hasItemQty(1023,1); -- Living Key
-- trade:hasItemQty(1022,1); -- Thief's Tools
local questItemNeeded = 0;
-- Player traded a key.
if ((trade:hasItemQty(1054,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then
-- IMPORTANT ITEM: AF Keyitems, AF Items, & Map -----------
local mJob = player:getMainJob();
local zone = player:getZoneID();
if (player:hasKeyItem(MAP_OF_THE_QUICKSAND_CAVES) == false) then
questItemNeeded = 3;
end
local listAF = getAFbyZone(zone);
for nb = 1,#listAF,3 do
if (player:getQuestStatus(JEUNO,listAF[nb + 1]) ~= QUEST_AVAILABLE and mJob == listAF[nb] and player:hasItem(listAF[nb + 2]) == false) then
questItemNeeded = 2;
break
end
end
--------------------------------------
local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded);
local success = 0;
if (pack[2] ~= nil) then
player:messageSpecial(pack[2]);
success = pack[1];
else
success = pack[1];
end
if (success ~= -2) then
player:tradeComplete();
if (math.random() <= success) then
-- Succeded to open the coffer
player:messageSpecial(CHEST_UNLOCKED);
if (questItemNeeded == 3) then
player:addKeyItem(MAP_OF_THE_QUICKSAND_CAVES);
player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_QUICKSAND_CAVES); -- Map of the Quicksand Caves (KI)
elseif (questItemNeeded == 2) then
for nb = 1,#listAF,3 do
if (mJob == listAF[nb]) then
player:addItem(listAF[nb + 2]);
player:messageSpecial(ITEM_OBTAINED,listAF[nb + 2]);
break
end
end
else
player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME));
local loot = cofferLoot(zone,npc);
-- print("loot array: "); -- debug
-- print("[1]", loot[1]); -- debug
-- print("[2]", loot[2]); -- debug
if (loot[1]=="gil") then
player:addGil(loot[2]);
player:messageSpecial(GIL_OBTAINED,loot[2]);
else
-- Item
player:addItem(loot[2]);
player:messageSpecial(ITEM_OBTAINED,loot[2]);
end
end
UpdateTreasureSpawnPoint(npc:getID());
else
player:messageSpecial(CHEST_MIMIC);
spawnMimic(zone,npc,player);
UpdateTreasureSpawnPoint(npc:getID(), true);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(CHEST_LOCKED,1054);
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 |
maxha651/NotZombies | evilboxInit.lua | 1 | 1331 | -- Some glue to make STI and evilbox.lua stick together
-- Overall not very nice code
evilboxInit = {}
-- Create evilbox objects from Tiled stuff
function evilboxInit.initLayer(map, layer, world)
local objects = map.layers[layer].objects
-- Do cool initialization
local coolObject
local coolObjects = {}
for _, object in pairs(objects) do
coolObject = love.filesystem.load("evilbox.lua")()
-- Make sure we always update STI object
-- I'm not sure whether this is a good way to do it...
-- Probably not needed since I don't seem to get STI to do what I want
-- anyway...
local oldUpdate = coolObject.update
local function funkyUpdateFunc(self, dt)
oldUpdate(self, dt)
object.x = coolObject:getX()
object.y = coolObject:getY()
end
-- Converting from bottom-left coordinate to center coordinate
coolObject:load(world, object.x + map.tilewidth/2,
object.y - map.tileheight/2,
object.width, object.height)
coolObject.update = funkyUpdateFunc
coolObjects[#coolObjects +1] = coolObject
end
-- Tell STI that we're handling stuff
map:convertToCustomLayer(layer)
return coolObjects
end
return evilboxInit
| mit |
nyczducky/darkstar | scripts/zones/FeiYin/npcs/Treasure_Chest.lua | 17 | 3611 | -----------------------------------
-- Area: Fei'Yin
-- NPC: Treasure Chest
-- @zone 204
-----------------------------------
package.loaded["scripts/zones/FeiYin/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/treasure");
require("scripts/globals/quests");
require("scripts/zones/FeiYin/TextIDs");
local TreasureType = "Chest";
local TreasureLvL = 53;
local TreasureMinLvL = 43;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- trade:hasItemQty(1037,1); -- Treasure Key
-- trade:hasItemQty(1115,1); -- Skeleton Key
-- trade:hasItemQty(1023,1); -- Living Key
-- trade:hasItemQty(1022,1); -- Thief's Tools
local questItemNeeded = 0;
-- Player traded a key.
if ((trade:hasItemQty(1037,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then
local zone = player:getZoneID();
-- IMPORTANT ITEM: Sorcery of the North QUEST -----------
if (player:getQuestStatus(SANDORIA,SORCERY_OF_THE_NORTH) == QUEST_ACCEPTED and player:hasKeyItem(FEIYIN_MAGIC_TOME) == false) then
questItemNeeded = 1;
end
--------------------------------------
local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded);
local success = 0;
if (pack[2] ~= nil) then
player:messageSpecial(pack[2]);
success = pack[1];
else
success = pack[1];
end
if (success ~= -2) then
player:tradeComplete();
if (math.random() <= success) then
-- Succeded to open the coffer
player:messageSpecial(CHEST_UNLOCKED);
if (questItemNeeded == 1) then
player:addKeyItem(FEIYIN_MAGIC_TOME);
player:messageSpecial(KEYITEM_OBTAINED,FEIYIN_MAGIC_TOME); -- Fei'yin Magic Tome
else
player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME));
local loot = chestLoot(zone,npc);
-- print("loot array: "); -- debug
-- print("[1]", loot[1]); -- debug
-- print("[2]", loot[2]); -- debug
if (loot[1]=="gil") then
player:addGil(loot[2]);
player:messageSpecial(GIL_OBTAINED,loot[2]);
else
-- Item
player:addItem(loot[2]);
player:messageSpecial(ITEM_OBTAINED,loot[2]);
end
end
UpdateTreasureSpawnPoint(npc:getID());
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(CHEST_LOCKED,1037);
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 |
ahmedjabbar/uor | plugins/stats.lua | 15 | 4017 | do
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(receiver, chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false)
return --text
end
local function chat_stats2(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nGroups: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == 'devpoint' then -- Put everything you like :)
local about = _config.about_text
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /devpoint ")
return about
end
if matches[1]:lower() == "statslist" then
if not is_momod(msg) then
return "For mods only !"
end
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats2(chat_id)
end
if matches[1]:lower() == "stats" then
if not matches[2] then
if not is_momod(msg) then
return "For mods only !"
end
if msg.to.type == 'chat' or msg.to.type == 'channel' then
local receiver = get_receiver(msg)
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats(receiver, chat_id)
else
return
end
end
if matches[2] == "devpoint" then -- Put everything you like :)
if not is_admin1(msg) then
return "For admins only !"
else
return bot_stats()
end
end
if matches[2] == "group" then
if not is_admin1(msg) then
return "For admins only !"
else
return chat_stats(matches[3])
end
end
end
end
return {
patterns = {
"^[#!/]([Ss]tats)$",
"^[#!/]([Ss]tatslist)$",
"^[#!/]([Ss]tats) (group) (%d+)",
"^[#!/]([Ss]tats) (devpoint)",
"^[#!/]([Dd]evpoint)"
},
run = run
}
end
| gpl-2.0 |
nyczducky/darkstar | scripts/globals/items/plate_of_octopus_sushi.lua | 12 | 1586 | -----------------------------------------
-- ID: 5693
-- Item: plate_of_octopus_sushi
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Strength 1
-- Accuracy % 14 (cap 68)
-- Ranged Accuracy % 14 (cap 68)
-- Resist Sleep +1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5693);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 1);
target:addMod(MOD_FOOD_ACCP, 14);
target:addMod(MOD_FOOD_ACC_CAP, 68);
target:addMod(MOD_FOOD_RACCP, 14);
target:addMod(MOD_FOOD_RACC_CAP, 68);
target:addMod(MOD_SLEEPRES, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 1);
target:delMod(MOD_FOOD_ACCP, 14);
target:delMod(MOD_FOOD_ACC_CAP, 68);
target:delMod(MOD_FOOD_RACCP, 14);
target:delMod(MOD_FOOD_RACC_CAP, 68);
target:delMod(MOD_SLEEPRES, 1);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/globals/weaponskills/one_inch_punch.lua | 25 | 1590 | -----------------------------------
-- One Inch Punch
-- Hand-to-Hand weapon skill
-- Skill level: 75
-- Delivers an attack that ignores target's defense. Amount ignored varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Shadow Gorget.
-- Aligned with the Shadow Belt.
-- Element: None
-- Modifiers: VIT:100%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.4; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
-- Defense ignored is 0%, 25%, 50% as per http://www.bg-wiki.com/bg/One_Inch_Punch
params.ignoresDef = true;
params.ignored100 = 0;
params.ignored200 = 0.25;
params.ignored300 = 0.5;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.vit_wsc = 1.0;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
sevu/wesnoth | data/campaigns/World_Conquest/lua/map/tools/filter_converter.lua | 6 | 5020 |
----------------------------------------------------------
---- A helper tool, that works (mostly) indpendently ----
---- of the rest to convert location filter wml to ----
---- the filter syntax used in this addon ----
---- (map:find) ----
----------------------------------------------------------
local and_to_all = {
["and"] = "all",
["or"] = "any",
["not"] = "none"
}
local comp_tags = {
any = true,
all = true,
none = true,
notall = true,
}
function compose_filter_1(tag, f1, f2)
if tag == f1[1] then
if tag == f2[1] then
for i = 2, #f2 do
table.insert(f1, f2[i])
end
else
table.insert(f1, f2)
end
return f1
else
if tag == f2[1] then
table.insert(f2, 2, f1)
return f2
else
return {tag, f1, f2}
end
end
end
function compose_filter(tag, f1, f2)
local res = compose_filter_1(tag, f1, f2)
if #res == 2 then
return res[2]
end
return res
end
function parse_wml_filter(cfg)
local res = { "all" }
if cfg.x then
table.insert(res, { "x", cfg.x})
end
if cfg.y then
table.insert(res, { "y", cfg.y})
end
if cfg.terrain then
table.insert(res, { "terrain", cfg.terrain})
end
if cfg.find_in then
table.insert(res, { "find_in_wml", cfg.find_in})
end
for ad in wml.child_range(cfg, "filter_adjacent_location") do
table.insert(res, { "adjacent", parse_wml_filter(ad), adjacent = ad.adjacent, count = ad.count })
end
if #res == 1 then
print("empty filter")
end
if #res == 2 then
res = res[2]
end
for i, v in ipairs(cfg) do
local tag = and_to_all[v[1]]
local content = v[2]
if tag ~= nil then
local subfilter = parse_wml_filter(content)
if tag == "none" then
subfilter = { "none", subfilter }
tag = "all"
end
res = compose_filter(tag, res, subfilter)
end
end
if cfg.radius then
local filter_radius = wml.get_child(cfg, "filter_radius")
filter_radius = filter_radius and parse_wml_filter(filter_radius)
res = { "radius", cfg.radius, res, filter_radius = filter_radius }
end
return res
end
local function value_to_str(val)
if val == nil then
return "nil"
elseif type(val) == "number" or type(val) == "boolean" then
return tostring(val)
elseif type(val) == "string" then
return string.format("%q", val)
else
error("unknown type:'" .. type(val) .. "'")
end
end
function print_filter(f, indent)
local res = {}
indent = indent or 0
local function write(str)
res[#res + 1] = str
end
local function write_newline()
res[#res + 1] = "\n" .. string.rep("\t", indent)
end
local function write_filter(filter)
if filter[1] == "adjacent" then
write("f.adjacent(")
write_filter(filter[2])
if (filter.adjacent or filter.count) then
write(", " .. value_to_str(filter.adjacent))
write(", " .. value_to_str(filter.count))
end
write(")")
end
if filter[1] == "x" or filter[1] == "y" or filter[1] == "terrain" or filter[1] == "find_in_wml" then
write("f." .. filter[1] .. "(")
write(value_to_str(filter[2]))
write(")")
end
if filter[1] == "radius" then
--f_radius(r, f, f_r)
write("f.radius(")
write(value_to_str(filter[2]))
write(", ")
write_filter(filter[3])
if filter.filter_radius then
write(", ")
write_filter(filter.filter_radius)
end
write(")")
end
if comp_tags[filter[1]] then
write("f." .. filter[1] .. "(")
indent = indent + 1
for i = 2, #filter do
local is_last = (i == #filter)
write_newline()
write_filter(filter[i])
if not is_last then
write(",")
end
end
indent = indent - 1
write_newline()
write(")")
end
end
write_filter(f)
return table.concat(res, "")
end
function print_set_terrain(filter, terrain, extra)
std_print("set_terrain { " .. value_to_str(terrain) .. ",")
std_print("\t" .. print_filter(filter, 1) .. ",")
for k, v in pairs(extra) do
std_print("\t" .. k .. " = " .. value_to_str(v) .. ",")
end
std_print("}")
end
function convert_filter()
local cfg = wml.parse(filesystem.read_file("./filterdata.cfg"))
std_print("")
for i, v in ipairs(cfg) do
local tag = v[1]
local content = v[2]
if tag == "terrain" then
local terrain = content.terrain
content.terrain = nil
local f = parse_wml_filter(content)
print_set_terrain(f, terrain, { layer = content.layer })
end
if tag == "wc2_terrain" then
for change in wml.child_range(content, "change") do
local terrain = change.terrain
local f = parse_wml_filter(wml.get_child(change, "filter"))
local extras = {}
for k, val in pairs(change) do
if type(k) == "string" and k ~= "terrain" then
extras[k] = val
end
end
print_set_terrain(f, terrain, extras)
end
end
if tag == "store_locations" then
local variable = content.variable
local f = parse_wml_filter(content)
std_print("local " .. variable .. " = map:find(" .. print_filter(f, 1) .. ")")
end
end
--local filter = parse_wml_filter(cfg)
--std_print(print_filter(filter))
end
convert_filter()
| gpl-2.0 |
benloz10/FinalFrontier | gamemodes/finalfrontier/gamemode/cl_room.lua | 3 | 5727 | -- Copyright (c) 2014 James King [metapyziks@gmail.com]
--
-- This file is part of Final Frontier.
--
-- Final Frontier is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as
-- published by the Free Software Foundation, either version 3 of
-- the License, or (at your option) any later version.
--
-- Final Frontier is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public License
-- along with Final Frontier. If not, see <http://www.gnu.org/licenses/>.
local ROOM_UPDATE_FREQ = 0.5
local _mt = {}
_mt.__index = _mt
_mt._lastUpdate = 0
_mt._ship = nil
_mt._doorlist = nil
_mt._bounds = nil
_mt._system = nil
_mt._convexPolys = nil
_mt._lerptime = 0
_mt._temperature = nil
_mt._airvolume = nil
_mt._shields = nil
_mt._nwdata = nil
function _mt:IsCurrent()
return self:GetShip() and self:GetShip():IsValid() and self:GetName() and self._nwdata:IsCurrent()
end
function _mt:GetName()
return self._nwdata.name
end
function _mt:GetIndex()
return self._nwdata.index or 0
end
function _mt:GetShip()
return self._ship
end
function _mt:_UpdateBounds()
local bounds = Bounds()
for _, v in ipairs(self:GetCorners()) do
bounds:AddPoint(v.x, v.y)
end
self._bounds = bounds
end
function _mt:GetBounds()
return self._bounds
end
function _mt:GetSystemName()
return self._nwdata.systemname
end
function _mt:_UpdateSystem()
self._system = sys.Create(self:GetSystemName(), self)
end
function _mt:HasSystem()
return self._system ~= nil
end
function _mt:GetSystem()
return self._system
end
function _mt:GetVolume()
return self._nwdata.volume or 0
end
function _mt:GetSurfaceArea()
return self._nwdata.surfacearea or 0
end
function _mt:AddDoor(door)
if table.HasValue(self._doorlist, door) then return end
table.insert(self._doorlist, door)
end
function _mt:GetDoors()
return self._doorlist
end
function _mt:GetCorners()
return self._nwdata.corners
end
function _mt:GetDetails()
return self._nwdata.details
end
function _mt:GetModule(type)
local index = self._nwdata.modules[type]
if not index then return nil end
local mdl = ents.GetByIndex(index)
if not IsValid(mdl) then return nil end
return mdl
end
function _mt:GetSlot(module)
for i, v in pairs(self._nwdata.modules) do
if v == module:EntIndex() then return i end
end
return nil
end
function _mt:_UpdateConvexPolys()
self._convexPolys = FindConvexPolygons(self:GetCorners())
end
function _mt:GetConvexPolys()
return self._convexPolys
end
function _mt:_GetLerp()
return math.Clamp((CurTime() - self._lerptime) / ROOM_UPDATE_FREQ, 0, 1)
end
function _mt:_GetLerpedValue(value)
return value.old + (value.cur - value.old) * self:_GetLerp()
end
function _mt:_NextValue(value, next)
value.old = value.cur
value.cur = next or 0
end
function _mt:GetUnitTemperature()
return self:_GetLerpedValue(self._temperature)
end
function _mt:GetTemperature()
return self:GetUnitTemperature() * 600 / self:GetVolume()
end
function _mt:GetAirVolume()
return self:_GetLerpedValue(self._airvolume)
end
function _mt:GetAtmosphere()
return self:GetAirVolume() / self:GetVolume()
end
function _mt:GetUnitShields()
return self:_GetLerpedValue(self._shields)
end
function _mt:GetShields()
return self:GetUnitShields() / self:GetSurfaceArea()
end
function _mt:GetPowerRatio()
if self:HasSystem() and self:GetSystem():GetPowerNeeded() > 0 then
return math.min(1, self:GetSystem():GetPower()
/ self:GetSystem():GetPowerNeeded())
end
return 0
end
function _mt:GetPermissionsName()
return self:GetShip():GetName() .. "_" .. self:GetIndex()
end
function _mt:HasPlayerWithSecurityPermission()
for _, ply in ipairs(player.GetAll()) do
if IsValid(ply) and ply:HasPermission(self, permission.SECURITY, true) then
return true
end
end
return false
end
local ply_mt = FindMetaTable("Player")
function ply_mt:GetRoom()
local shipName = self:GetShipName()
if not shipName or string.len(shipName) == 0 then return nil end
return self:GetShip():GetRoomByIndex(self:GetRoomIndex())
end
function ply_mt:IsInRoom(room)
return self:GetShipName() == room:GetShip():GetName()
and self:GetRoomIndex() == room:GetIndex()
end
function _mt:Think()
if self:_GetLerp() >= 1.0 then
self:_NextValue(self._temperature, self._nwdata.temperature)
self:_NextValue(self._airvolume, self._nwdata.airvolume)
self:_NextValue(self._shields, self._nwdata.shields)
self._lerptime = CurTime()
end
if self:GetSystemName() and not self:GetSystem() then
self:_UpdateSystem()
end
if not self:GetBounds() and self:GetCorners() then
self:_UpdateBounds()
end
if not self:GetConvexPolys() and self:GetCorners() then
self:_UpdateConvexPolys()
end
end
function _mt:Remove()
self._nwdata:Forget()
if self:GetSystem() then
self:GetSystem():Remove()
end
end
function Room(name, ship, index)
local room = {}
room._temperature = { old = 0, cur = 0 }
room._airvolume = { old = 0, cur = 0 }
room._shields = { old = 0, cur = 0 }
room._nwdata = NetworkTable(name)
room._nwdata.name = name
room._nwdata.index = index
room._ship = ship
room._doorlist = {}
return setmetatable(room, _mt)
end
| lgpl-3.0 |
timn/roslua | src/roslua/slave_proxy.lua | 1 | 4386 |
----------------------------------------------------------------------------
-- slave_proxy.lua - Slave XML-RPC proxy
--
-- Created: Mon Jul 26 11:58:27 2010 (at Intel Research, Pittsburgh)
-- License: BSD, cf. LICENSE file of roslua
-- Copyright 2010 Tim Niemueller [www.niemueller.de]
-- 2010 Carnegie Mellon University
-- 2010 Intel Research Pittsburgh
----------------------------------------------------------------------------
--- Slave XML-RPC API proxy.
-- This module contains the SlaveProxy class to call methods provided via
-- XML-RPC by ROS slaves.
-- <br /><br />
-- The user should not have to directly interact with the slave. It is used
-- to initiate topic connections and get information about the slave.
-- It can also be used to remotely shutdown a slave.
-- @copyright Tim Niemueller, Carnegie Mellon University, Intel Research Pittsburgh
-- @release Released under BSD license
module("roslua.slave_proxy", package.seeall)
require("xmlrpc")
require("xmlrpc.http")
assert(xmlrpc._VERSION_MAJOR and
(xmlrpc._VERSION_MAJOR > 1 or
xmlrpc._VERSION_MAJOR == 1 and xmlrpc._VERSION_MINOR >= 2),
"You must use version 1.2 or newer of lua-xmlrpc")
require("roslua.xmlrpc_post")
__DEBUG = false
SlaveProxy = { slave_uri = nil, node_name = nil }
--- Constructor.
-- @param slave_uri XML-RPC HTTP slave URI
-- @param node_name name of this node
function SlaveProxy:new(slave_uri, node_name)
local o = {}
setmetatable(o, self)
self.__index = self
o.slave_uri = slave_uri
o.node_name = node_name
return o
end
-- (internal) execute XML-RPC call
-- Will always prefix the arguments with the caller ID.
-- @param method_name name of the method to execute
-- @param ... Arguments depending on the method call
function SlaveProxy:do_call(method_name, ...)
local ok, res = xmlrpc.http.call(self.slave_uri,
method_name, self.node_name, ...)
assert(ok, string.format("XML-RPC call %s failed on client: %s", method_name, tostring(res)))
assert(res[1] == 1, string.format("XML-RPC call %s failed on server: %s",
method_name, tostring(res[2])))
if __DEBUG then
print(string.format("Ok: %s Code: %d Error: %s arrlen: %i",
tostring(ok), tostring(res[1]), tostring(res[2]), #res))
end
return res
end
--- Get bus stats.
-- @return bus stats
function SlaveProxy:getBusStats()
local res = self:do_call("getBusStats")
return res[3]
end
--- Get bus info.
-- @return bus info
function SlaveProxy:getBusInfo()
local res = self:do_call("getBusInfo")
return res[3]
end
--- Get slaves master URI.
-- @return slaves master URI
function SlaveProxy:getMasterUri()
local res = self:do_call("getMasterUri")
return res[3]
end
--- Shutdown remote node.
-- @param msg shutdown message
function SlaveProxy:shutdown(msg)
local res = self:do_call("shutdown", msg or "")
end
--- Get PID of remote slave.
-- Can be used to "ping" the remote node.
function SlaveProxy:getPid()
local res = self:do_call("getPid")
return res[3]
end
--- Get all subscriptions of remote node.
-- @return list of subscriptions
function SlaveProxy:getSubscriptions()
local res = self:do_call("getSubscriptions")
return res[3]
end
--- Get all publications of remote node.
-- @return list of publications
function SlaveProxy:getPublications()
local res = self:do_call("getPublications")
return res[3]
end
function SlaveProxy:connection_params()
local protocols = {}
local tcpros = {"TCPROS"}
table.insert(protocols, xmlrpc.newTypedValue(tcpros, xmlrpc.newArray()))
return xmlrpc.newTypedValue(protocols, xmlrpc.newArray("array"))
end
--- Request a TCPROS connection for a specific topic.
-- @param topic name of topic
-- @return TCPROS communication parameters
function SlaveProxy:requestTopic(topic)
local res = self:do_call("requestTopic", topic, self:connection_params())
return res[3]
end
--- Start a topic request.
-- This starts a concurrent execution of requestTopic().
-- @param topic topic to request
-- @return XmlRpcRequest handle for the started request
function SlaveProxy:requestTopic_conc(topic)
return roslua.xmlrpc_post.XmlRpcRequest:new(self.slave_uri, "requestTopic",
self.node_name, topic,
self:connection_params())
end
| bsd-3-clause |
benloz10/FinalFrontier | gamemodes/finalfrontier/entities/effects/trans_sparks.lua | 3 | 2353 | -- Copyright (c) 2014 James King [metapyziks@gmail.com]
--
-- This file is part of Final Frontier.
--
-- Final Frontier is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as
-- published by the Free Software Foundation, either version 3 of
-- the License, or (at your option) any later version.
--
-- Final Frontier is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public License
-- along with Final Frontier. If not, see <http://www.gnu.org/licenses/>.
function EFFECT:Init(data)
local low = data:GetOrigin()
local high = data:GetStart()
local offset = (low + high) / 2
local size = high - low
local count = math.Clamp(size.x * size.y * size.z / 256, 32, 128)
local emitter = ParticleEmitter(offset)
for i = 1, count do
local pos = Vector(
math.Rand(low.x, high.x),
math.Rand(low.y, high.y),
math.Rand(low.z,high.z)
)
local particle = emitter:Add("effects/spark", pos)
if particle then
if math.random() < 0.5 then
particle:SetVelocity((pos - offset) * (5 + math.random() * 5))
particle:SetGravity(Vector(0, 0, -600))
particle:SetAirResistance(100)
particle:SetDieTime(math.Rand(1.5, 2.5))
else
particle:SetVelocity((pos - offset) * 1)
particle:SetGravity(Vector(0, 0, -100))
particle:SetAirResistance(100)
particle:SetDieTime(math.Rand( 0.5, 1.0 ))
end
particle:SetLifeTime(0)
particle:SetStartAlpha(math.Rand(191, 255))
particle:SetEndAlpha(0)
particle:SetStartSize(2)
particle:SetEndSize(0)
particle:SetRoll(math.Rand(0, 360))
particle:SetRollDelta(0)
particle:SetCollide(true)
particle:SetBounce(0.3)
end
end
emitter:Finish()
end
function EFFECT:Think()
return false
end
function EFFECT:Render()
return
end
| lgpl-3.0 |
TeamBliss-LP/android_external_skia | tools/lua/bitmap_statistics.lua | 207 | 1862 | function string.startsWith(String,Start)
return string.sub(String,1,string.len(Start))==Start
end
function string.endsWith(String,End)
return End=='' or string.sub(String,-string.len(End))==End
end
local canvas = nil
local num_perspective_bitmaps = 0
local num_affine_bitmaps = 0
local num_scaled_bitmaps = 0
local num_translated_bitmaps = 0
local num_identity_bitmaps = 0
local num_scaled_up = 0
local num_scaled_down = 0
function sk_scrape_startcanvas(c, fileName)
canvas = c
end
function sk_scrape_endcanvas(c, fileName)
canvas = nil
end
function sk_scrape_accumulate(t)
-- dump the params in t, specifically showing the verb first, which we
-- then nil out so it doesn't appear in tostr()
if (string.startsWith(t.verb,"drawBitmap")) then
matrix = canvas:getTotalMatrix()
matrixType = matrix:getType()
if matrixType.perspective then
num_perspective_bitmaps = num_perspective_bitmaps + 1
elseif matrixType.affine then
num_affine_bitmaps = num_affine_bitmaps + 1
elseif matrixType.scale then
num_scaled_bitmaps = num_scaled_bitmaps + 1
if matrix:getScaleX() > 1 or matrix:getScaleY() > 1 then
num_scaled_up = num_scaled_up + 1
else
num_scaled_down = num_scaled_down + 1
end
elseif matrixType.translate then
num_translated_bitmaps = num_translated_bitmaps + 1
else
num_identity_bitmaps = num_identity_bitmaps + 1
end
end
end
function sk_scrape_summarize()
io.write( "identity = ", num_identity_bitmaps,
", translated = ", num_translated_bitmaps,
", scaled = ", num_scaled_bitmaps, " (up = ", num_scaled_up, "; down = ", num_scaled_down, ")",
", affine = ", num_affine_bitmaps,
", perspective = ", num_perspective_bitmaps,
"\n")
end
| bsd-3-clause |
dtrip/awesome | tests/test-focus.lua | 4 | 2567 | --- Tests for focus signals / property.
-- Test for https://github.com/awesomeWM/awesome/issues/134.
local runner = require("_runner")
local awful = require("awful")
local gdebug = require("gears.debug")
local beautiful = require("beautiful")
beautiful.border_color_normal = "#0000ff"
beautiful.border_color_active = "#00ff00"
client.connect_signal("focus", function(c)
c.border_color = "#ff0000"
end)
local function assert_equals(a, b)
if a == b then
return
end
error(string.format("Assertion failed: %s == %s", a, b))
end
local steps = {
-- border_color should get applied via focus signal for first client on tag.
function(count)
if count == 1 then
awful.spawn("xterm")
else
local c = client.get()[1]
if c then
assert_equals(c.border_color, "#ff0000")
return true
end
end
end,
-- border_color should get applied via focus signal for second client on tag.
function(count)
if count == 1 then
awful.spawn("xterm")
else
if #client.get() == 2 then
local c = client.get()[1]
assert_equals(c, client.focus)
if c then
assert_equals(c.border_color, "#ff0000")
return true
end
end
end
end,
-- Test if alpha works as intended
function()
local c = client.get()[1]
local function test(set, expected)
expected = expected or set
c.border_color = set
assert_equals(c.border_color, expected)
end
test("#123456")
test("#12345678")
test("#123456ff", "#123456")
return true
end,
function()
assert(client.focus)
local called, called2 = false, false
gdebug.print_warning = function() called = true end
local c2 = client.focus
client.focus.active = false
assert(called)
assert(not client.focus)
assert(not c2.active)
called = false
local real_assert = assert
assert = function() called2 = true end --luacheck: globals assert
c2.active = true
assert = real_assert --luacheck: globals assert
assert(called2)
assert(not called)
assert(c2.active)
assert(client.focus == c2)
return true
end,
}
runner.run_steps(steps)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Jugner_Forest_[S]/npcs/Telepoint.lua | 17 | 1245 | -----------------------------------
-- Area: Jugner Forest [S]
-- NPC: Telepoint
-----------------------------------
package.loaded["scripts/zones/Jugner_Forest_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Jugner_Forest_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(JUGNER_GATE_CRYSTAL) == false) then
player:addKeyItem(JUGNER_GATE_CRYSTAL);
player:messageSpecial(KEYITEM_OBTAINED,JUGNER_GATE_CRYSTAL);
else
player:messageSpecial(ALREADY_OBTAINED_TELE);
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 |
abcdefg30/OpenRA | mods/ra/maps/allies-06b/allies06b.lua | 7 | 7952 | --[[
Copyright 2007-2022 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
AlliedReinforcementsA = { "e1", "e1", "e1", "e1", "e1" }
AlliedReinforcementsB = { "e1", "e1", "e3", "e3", "e3" }
AlliedBoatReinforcements = { "pt", "pt" }
BadGuys = { BadGuy1, BadGuy2, BadGuy3, BadGuy4 }
SovietDogPatrols =
{
{ Patrol_1_e1, Patrol_1_dog },
{ Patrol_2_e1, Patrol_2_dog },
{ Patrol_3_e1, Patrol_3_dog },
{ Patrol_4_e1, Patrol_4_dog }
}
SovietDogPatrolPaths =
{
{ Patrol6.Location, Patrol7.Location, Patrol8.Location, Patrol1.Location, Patrol2.Location, Patrol3.Location, Patrol4.Location, Patrol5.Location },
{ Patrol8.Location, Patrol1.Location, Patrol2.Location, Patrol3.Location, Patrol4.Location, Patrol5.Location, Patrol6.Location, Patrol7.Location },
{ Patrol1.Location, Patrol2.Location, Patrol3.Location, Patrol4.Location, Patrol5.Location, Patrol6.Location, Patrol7.Location, Patrol8.Location },
{ Patrol2.Location, Patrol3.Location, Patrol4.Location, Patrol5.Location, Patrol6.Location, Patrol7.Location, Patrol8.Location, Patrol1.Location }
}
Mammoths = { Mammoth1, Mammoth2, Mammoth3 }
SovietMammothPaths =
{
{ TnkPatrol1.Location, TnkPatrol2.Location,TnkPatrol3.Location, TnkPatrol4.Location, TnkPatrol5.Location, TnkPatrol6.Location },
{ TnkPatrol5.Location, TnkPatrol6.Location, TnkPatrol1.Location, TnkPatrol2.Location, TnkPatrol3.Location, TnkPatrol4.Location },
{ TnkPatrol6.Location, TnkPatrol1.Location, TnkPatrol2.Location, TnkPatrol3.Location, TnkPatrol4.Location, TnkPatrol5.Location }
}
SubPaths = {
{ SubPatrol1_1.Location, SubPatrol1_2.Location },
{ SubPatrol2_1.Location, SubPatrol2_2.Location },
{ SubPatrol3_1.Location, SubPatrol3_2.Location },
{ SubPatrol4_1.Location, SubPatrol4_2.Location },
{ SubPatrol5_1.Location, SubPatrol5_2.Location }
}
ParadropWaypoints =
{
easy = { UnitBStopLocation },
normal = { UnitBStopLocation, UnitAStopLocation },
hard = { UnitBStopLocation, UnitCStopLocation, UnitAStopLocation }
}
SovietTechLabs = { TechLab1, TechLab2 }
GroupPatrol = function(units, waypoints, delay)
local i = 1
local stop = false
Utils.Do(units, function(unit)
Trigger.OnIdle(unit, function()
if stop then
return
end
if unit.Location == waypoints[i] then
local bool = Utils.All(units, function(actor) return actor.IsIdle end)
if bool then
stop = true
i = i + 1
if i > #waypoints then
i = 1
end
Trigger.AfterDelay(delay, function() stop = false end)
end
else
unit.AttackMove(waypoints[i])
end
end)
end)
end
InitialSovietPatrols = function()
-- Dog Patrols
BeachDog.Patrol({ BeachPatrol1.Location, BeachPatrol2.Location, BeachPatrol3.Location })
for i = 1, 4 do
GroupPatrol(SovietDogPatrols[i], SovietDogPatrolPaths[i], DateTime.Seconds(5))
end
-- Mammoth Patrols
for i = 1, 3 do
Trigger.AfterDelay(DateTime.Seconds(6 * (i - 1)), function()
Trigger.OnIdle(Mammoths[i], function()
Mammoths[i].Patrol(SovietMammothPaths[i])
end)
end)
end
-- Sub Patrols
Patrol1Sub.Patrol(SubPaths[1])
Patrol2Sub.Patrol(SubPaths[2])
Patrol3Sub.Patrol(SubPaths[3])
Patrol4Sub.Patrol(SubPaths[4])
Patrol5Sub.Patrol(SubPaths[5])
end
InitialAlliedReinforcements = function()
local camera = Actor.Create("Camera", true, { Owner = player, Location = DefaultCameraPosition.Location })
Trigger.AfterDelay(DateTime.Seconds(30), camera.Destroy)
Trigger.AfterDelay(DateTime.Seconds(1), function()
Reinforcements.Reinforce(player, AlliedReinforcementsA, { AlliedEntry3.Location, UnitCStopLocation.Location }, 2)
Reinforcements.Reinforce(player, AlliedReinforcementsB, { AlliedEntry2.Location, UnitAStopLocation.Location }, 2)
end)
Trigger.AfterDelay(DateTime.Seconds(3), function()
Reinforcements.Reinforce(player, { "mcv" }, { AlliedEntry1.Location, UnitBStopLocation.Location })
Reinforcements.Reinforce(player, AlliedBoatReinforcements, { AlliedBoatEntry.Location, AlliedBoatStop.Location })
end)
end
CaptureRadarDome = function()
Trigger.OnKilled(RadarDome, function()
player.MarkFailedObjective(CaptureRadarDomeObj)
end)
Trigger.OnCapture(RadarDome, function()
player.MarkCompletedObjective(CaptureRadarDomeObj)
Utils.Do(SovietTechLabs, function(a)
if a.IsDead then
return
end
Beacon.New(player, a.CenterPosition)
if Difficulty ~= "hard" then
Actor.Create("TECH.CAM", true, { Owner = player, Location = a.Location + CVec.New(1, 1) })
end
end)
Media.DisplayMessage("Coordinates of the Soviet tech centers discovered.")
if Difficulty == "easy" then
Actor.Create("Camera", true, { Owner = player, Location = Weapcam.Location })
end
end)
end
InfiltrateTechCenter = function()
Utils.Do(SovietTechLabs, function(a)
Trigger.OnInfiltrated(a, function()
if infiltrated then
return
end
infiltrated = true
DestroySovietsObj = player.AddObjective("Destroy all Soviet buildings and units in the area.")
player.MarkCompletedObjective(InfiltrateTechCenterObj)
end)
Trigger.OnCapture(a, function()
if not infiltrated then
Media.DisplayMessage("Do not capture the tech centers! Infiltrate one with a spy.")
end
end)
end)
Trigger.OnAllKilledOrCaptured(SovietTechLabs, function()
if not player.IsObjectiveCompleted(InfiltrateTechCenterObj) then
player.MarkFailedObjective(InfiltrateTechCenterObj)
end
end)
end
Tick = function()
if player.HasNoRequiredUnits() then
player.MarkFailedObjective(InfiltrateTechCenterObj)
end
if DestroySovietsObj and ussr.HasNoRequiredUnits() then
player.MarkCompletedObjective(DestroySovietsObj)
end
end
WorldLoaded = function()
player = Player.GetPlayer("Greece")
ussr = Player.GetPlayer("USSR")
InitObjectives(player)
InfiltrateTechCenterObj = player.AddObjective("Infiltrate one of the Soviet tech centers with a spy.")
CaptureRadarDomeObj = player.AddObjective("Capture the Radar Dome at the shore.", "Secondary", false)
Camera.Position = DefaultCameraPosition.CenterPosition
if Difficulty == "easy" then
Trigger.OnEnteredProximityTrigger(SovietDefenseCam.CenterPosition, WDist.New(1024 * 7), function(a, id)
if a.Owner == player then
Trigger.RemoveProximityTrigger(id)
local cam1 = Actor.Create("TECH.CAM", true, { Owner = player, Location = SovietDefenseCam.Location })
Trigger.AfterDelay(DateTime.Seconds(15), cam1.Destroy)
if not DefenseFlame1.IsDead then
local cam2 = Actor.Create("TECH.CAM", true, { Owner = player, Location = DefenseFlame1.Location })
Trigger.AfterDelay(DateTime.Seconds(15), cam2.Destroy)
end
if not DefenseFlame2.IsDead then
local cam3 = Actor.Create("TECH.CAM", true, { Owner = player, Location = DefenseFlame2.Location })
Trigger.AfterDelay(DateTime.Seconds(15), cam3.Destroy)
end
end
end)
end
if Difficulty ~= "hard" then
Trigger.OnKilled(DefBrl1, function(a, b)
if not DefenseFlame1.IsDead then
DefenseFlame1.Kill()
end
end)
Trigger.OnKilled(DefBrl2, function(a, b)
if not DefenseFlame2.IsDead then
DefenseFlame2.Kill()
end
end)
end
Utils.Do(BadGuys, function(a)
a.AttackMove(UnitCStopLocation.Location)
end)
InitialAlliedReinforcements()
Trigger.AfterDelay(DateTime.Seconds(1), function()
InitialSovietPatrols()
end)
Trigger.OnEnteredProximityTrigger(SovietMiniBaseCam.CenterPosition, WDist.New(1024 * 14), function(a, id)
if a.Owner == player then
Trigger.RemoveProximityTrigger(id)
local cam = Actor.Create("Camera", true, { Owner = player, Location = SovietMiniBaseCam.Location })
Trigger.AfterDelay(DateTime.Seconds(15), cam.Destroy)
end
end)
CaptureRadarDome()
InfiltrateTechCenter()
Trigger.AfterDelay(0, ActivateAI)
end
| gpl-3.0 |
Devilmore/GoalBabbling | build/premake4.lua | 4 | 13286 | ----------------------------------------------------------------------
-- Premake4 configuration script for OpenDE
-- Contributed by Jason Perkins (starkos@industriousone.com)
-- For more information on Premake: http://industriousone.com/premake
----------------------------------------------------------------------
----------------------------------------------------------------------
-- Demo list: add/remove demos from here and the rest of the build
-- should just work.
----------------------------------------------------------------------
local demos = {
"boxstack",
"buggy",
"cards",
"chain1",
"chain2",
"collision",
"crash",
"cylvssphere",
"feedback",
"friction",
"gyroscopic",
"heightfield",
"hinge",
"I",
"jointPR",
"jointPU",
"joints",
"kinematic",
"motion",
"motor",
"ode",
"piston",
"plane2d",
"slider",
"space",
"space_stress",
"step",
}
local trimesh_demos = {
"basket",
"cyl",
"moving_trimesh",
"trimesh",
"tracks"
}
if not _OPTIONS["no-trimesh"] then
demos = table.join(demos, trimesh_demos)
end
----------------------------------------------------------------------
-- Configuration options
----------------------------------------------------------------------
newoption {
trigger = "with-demos",
description = "Builds the demo applications and DrawStuff library"
}
newoption {
trigger = "with-tests",
description = "Builds the unit test application"
}
newoption {
trigger = "with-gimpact",
description = "Use GIMPACT for trimesh collisions (experimental)"
}
newoption {
trigger = "all-collis-libs",
description = "Include sources of all collision libraries into the project"
}
newoption {
trigger = "with-libccd",
description = "Uses libccd for handling some collision tests absent in ODE."
}
newoption {
trigger = "no-dif",
description = "Exclude DIF (Dynamics Interchange Format) exports"
}
newoption {
trigger = "no-trimesh",
description = "Exclude trimesh collision geometry"
}
newoption {
trigger = "with-ou",
description = "Use TLS for global caches (experimental)"
}
newoption {
trigger = "16bit-indices",
description = "Use 16-bit indices for trimeshes (default is 32-bit)"
}
newoption {
trigger = "old-trimesh",
description = "Use old OPCODE trimesh-trimesh collider"
}
newoption {
trigger = "to",
value = "path",
description = "Set the output location for the generated project files"
}
newoption {
trigger = "only-shared",
description = "Only build shared (DLL) version of the library"
}
newoption {
trigger = "only-static",
description = "Only build static versions of the library"
}
newoption {
trigger = "only-single",
description = "Only use single-precision math"
}
newoption {
trigger = "only-double",
description = "Only use double-precision math"
}
-- always clean all of the optional components and toolsets
if _ACTION == "clean" then
_OPTIONS["with-demos"] = ""
_OPTIONS["with-tests"] = ""
for action in premake.action.each() do
os.rmdir(action.trigger)
end
os.remove("../ode/src/config.h")
end
-- special validation for Xcode
if _ACTION == "xcode3" and (not _OPTIONS["only-single"] and not _OPTIONS["only-double"]) then
error(
"Xcode does not support different library types in a single project.\n" ..
"Please use one of the flags: --only-static or --only-shared", 0)
end
-- build the list of configurations, based on the flags. Ends up
-- with configurations like "Debug", "DebugSingle" or "DebugSingleShared"
local configs = { "Debug", "Release" }
local function addconfigs(...)
local newconfigs = { }
for _, root in ipairs(configs) do
for _, suffix in ipairs(arg) do
table.insert(newconfigs, root .. suffix)
end
end
configs = newconfigs
end
if not _OPTIONS["only-single"] and not _OPTIONS["only-double"] then
addconfigs("Single", "Double")
end
if not _OPTIONS["only-shared"] and not _OPTIONS["only-static"] then
addconfigs("DLL", "Lib")
end
----------------------------------------------------------------------
-- The solution, and solution-wide settings
----------------------------------------------------------------------
solution "ode"
language "C++"
uuid "4DA77C12-15E5-497B-B1BB-5100D5161E15"
location ( _OPTIONS["to"] or _ACTION )
includedirs {
"../include",
"../ode/src"
}
-- apply the configuration list built above
configurations (configs)
configuration { "Debug*" }
defines { "_DEBUG" }
flags { "Symbols" }
configuration { "Release*" }
flags { "OptimizeSpeed", "NoFramePointer" }
configuration { "only-single or *Single*" }
defines { "dSINGLE", "CCD_SINGLE" }
configuration { "only-double or *Double*" }
defines { "dDOUBLE", "CCD_DOUBLE" }
configuration { "Windows" }
defines { "WIN32" }
configuration { "MacOSX" }
linkoptions { "-framework Carbon" }
-- give each configuration a unique output directory
for _, name in ipairs(configurations()) do
configuration { name }
targetdir ( "../lib/" .. name )
end
-- disable Visual Studio security warnings
configuration { "vs*" }
defines { "_CRT_SECURE_NO_DEPRECATE" }
-- don't remember why we had to do this
configuration { "vs2002 or vs2003", "*Lib" }
flags { "StaticRuntime" }
----------------------------------------------------------------------
-- The demo projects, automated from list above. These go first so
-- they will be selected as the active project automatically in IDEs
----------------------------------------------------------------------
if _OPTIONS["with-demos"] then
for _, name in ipairs(demos) do
project ( "demo_" .. name )
kind "ConsoleApp"
location ( _OPTIONS["to"] or _ACTION )
files { "../ode/demo/demo_" .. name .. ".*" }
links { "ode", "drawstuff" }
configuration { "Windows" }
files { "../drawstuff/src/resources.rc" }
links { "user32", "winmm", "gdi32", "opengl32", "glu32" }
configuration { "MacOSX" }
linkoptions { "-framework Carbon -framework OpenGL -framework AGL" }
configuration { "not Windows", "not MacOSX" }
links { "GL", "GLU" }
end
end
----------------------------------------------------------------------
-- The ODE library project
----------------------------------------------------------------------
project "ode"
-- kind "StaticLib"
location ( _OPTIONS["to"] or _ACTION )
includedirs {
"../ode/src/joints",
"../OPCODE",
"../GIMPACT/include",
"../ou/include",
"../libccd/src"
}
files {
"../include/ode/*.h",
"../ode/src/joints/*.h",
"../ode/src/joints/*.cpp",
"../ode/src/*.h",
"../ode/src/*.c",
"../ode/src/*.cpp",
}
excludes {
"../ode/src/collision_std.cpp",
}
configuration { "no-dif" }
excludes { "../ode/src/export-dif.cpp" }
configuration { "no-trimesh" }
excludes {
"../ode/src/collision_trimesh_colliders.h",
"../ode/src/collision_trimesh_internal.h",
"../ode/src/collision_trimesh_opcode.cpp",
"../ode/src/collision_trimesh_gimpact.cpp",
"../ode/src/collision_trimesh_box.cpp",
"../ode/src/collision_trimesh_ccylinder.cpp",
"../ode/src/collision_cylinder_trimesh.cpp",
"../ode/src/collision_trimesh_distance.cpp",
"../ode/src/collision_trimesh_ray.cpp",
"../ode/src/collision_trimesh_sphere.cpp",
"../ode/src/collision_trimesh_trimesh.cpp",
"../ode/src/collision_trimesh_plane.cpp"
}
configuration { "not no-trimesh", "with-gimpact or all-collis-libs" }
files { "../GIMPACT/**.h", "../GIMPACT/**.cpp" }
configuration { "not no-trimesh", "not with-gimpact" }
files { "../OPCODE/**.h", "../OPCODE/**.cpp" }
configuration { "with-ou" }
files { "../ou/**.h", "../ou/**.cpp" }
defines { "_OU_NAMESPACE=odeou" }
configuration { "with-libccd" }
files { "../libccd/src/ccd/*.h", "../libccd/src/*.c" }
defines { "dLIBCCD_ENABLED", "dLIBCCD_CYL_CYL" }
configuration { "not with-libccd" }
excludes { "../ode/src/collision_libccd.cpp", "../ode/src/collision_libccd.h" }
configuration { "windows" }
links { "user32" }
configuration { "only-static or *Lib" }
kind "StaticLib"
defines "ODE_LIB"
configuration { "only-shared or *DLL" }
kind "SharedLib"
defines "ODE_DLL"
configuration { "Debug" }
targetname "oded"
configuration { "Release" }
targetname "ode"
configuration { "DebugSingle*" }
targetname "ode_singled"
configuration { "ReleaseSingle*" }
targetname "ode_single"
configuration { "DebugDouble*" }
targetname "ode_doubled"
configuration { "ReleaseDouble*" }
targetname "ode_double"
----------------------------------------------------------------------
-- Write a custom <config.h> to build, based on the supplied flags
----------------------------------------------------------------------
if _ACTION and _ACTION ~= "clean" then
io.input("config-default.h")
local text = io.read("*a")
if _OPTIONS["no-trimesh"] then
text = string.gsub(text, "#define dTRIMESH_ENABLED 1", "/* #define dTRIMESH_ENABLED 1 */")
text = string.gsub(text, "#define dTRIMESH_OPCODE 1", "/* #define dTRIMESH_OPCODE 1 */")
elseif (_OPTIONS["with-gimpact"]) then
text = string.gsub(text, "#define dTRIMESH_OPCODE 1", "#define dTRIMESH_GIMPACT 1")
end
if _OPTIONS["with-ou"] then
text = string.gsub(text, "/%* #define dOU_ENABLED 1 %*/", "#define dOU_ENABLED 1")
text = string.gsub(text, "/%* #define dATOMICS_ENABLED 1 %*/", "#define dATOMICS_ENABLED 1")
text = string.gsub(text, "/%* #define dTLS_ENABLED 1 %*/", "#define dTLS_ENABLED 1")
end
if _OPTIONS["16bit-indices"] then
text = string.gsub(text, "#define dTRIMESH_16BIT_INDICES 0", "#define dTRIMESH_16BIT_INDICES 1")
end
if _OPTIONS["old-trimesh"] then
text = string.gsub(text, "#define dTRIMESH_OPCODE_USE_OLD_TRIMESH_TRIMESH_COLLIDER 0", "#define dTRIMESH_OPCODE_USE_OLD_TRIMESH_TRIMESH_COLLIDER 1")
end
io.output("../ode/src/config.h")
io.write(text)
io.close()
end
----------------------------------------------------------------------
-- The DrawStuff library project
----------------------------------------------------------------------
if _OPTIONS["with-demos"] then
project "drawstuff"
location ( _OPTIONS["to"] or _ACTION )
files {
"../include/drawstuff/*.h",
"../drawstuff/src/internal.h",
"../drawstuff/src/drawstuff.cpp"
}
configuration { "Debug*" }
targetname "drawstuffd"
configuration { "only-static or *Lib" }
kind "StaticLib"
defines { "DS_LIB" }
configuration { "only-shared or *DLL" }
kind "SharedLib"
defines { "DS_DLL", "USRDLL" }
configuration { "Windows" }
files { "../drawstuff/src/resource.h", "../drawstuff/src/resources.rc", "../drawstuff/src/windows.cpp" }
links { "user32", "opengl32", "glu32", "winmm", "gdi32" }
configuration { "MacOSX" }
defines { "HAVE_APPLE_OPENGL_FRAMEWORK" }
files { "../drawstuff/src/osx.cpp" }
linkoptions { "-framework Carbon -framework OpenGL -framework AGL" }
configuration { "not Windows", "not MacOSX" }
files { "../drawstuff/src/x11.cpp" }
links { "X11", "GL", "GLU" }
end
----------------------------------------------------------------------
-- The automated test application
----------------------------------------------------------------------
if _OPTIONS["with-tests"] then
project "tests"
kind "ConsoleApp"
location ( _OPTIONS["to"] or _ACTION )
includedirs {
"../tests/UnitTest++/src"
}
files {
"../tests/*.cpp",
"../tests/joints/*.cpp",
"../tests/UnitTest++/src/*"
}
links { "ode" }
configuration { "Windows" }
files { "../tests/UnitTest++/src/Win32/*" }
configuration { "not Windows" }
files { "../tests/UnitTest++/src/Posix/*" }
-- add post-build step to automatically run test executable
local path_to_lib = path.getrelative(location(), "../lib")
local command = path.translate(path.join(path_to_lib, "%s/tests"))
for _, name in ipairs(configurations()) do
configuration { name }
postbuildcommands { command:format(name) }
end
end
| lgpl-2.1 |
nyczducky/darkstar | scripts/zones/Cloister_of_Frost/bcnms/trial_by_ice.lua | 27 | 1938 | -----------------------------------
-- Area: Cloister of Frost
-- BCNM: Trial by Ice
-- @pos 558 0.1 596 203
-----------------------------------
package.loaded["scripts/zones/Cloister_of_Frost/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/zones/Cloister_of_Frost/TextIDs");
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if (player:hasCompleteQuest(SANDORIA,TRIAL_BY_ICE)) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0);
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)
-- print("bc finish csid "..csid.." and option "..option);
if (csid == 0x7d01) then
player:delKeyItem(TUNING_FORK_OF_ICE);
player:addKeyItem(WHISPER_OF_FROST);
player:addTitle(HEIR_OF_THE_GREAT_ICE);
player:messageSpecial(KEYITEM_OBTAINED,WHISPER_OF_FROST);
end
end; | gpl-3.0 |
nyczducky/darkstar | scripts/zones/Rolanberry_Fields/npcs/Cavernous_Maw.lua | 27 | 2925 | -----------------------------------
-- Area: Rolanberry Fields
-- NPC: Cavernous Maw
-- @pos -198 8 361 110
-- Teleports Players to Rolanberry Fields [S]
-----------------------------------
package.loaded["scripts/zones/Rolanberry_Fields/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/teleports");
require("scripts/globals/missions");
require("scripts/globals/campaign");
require("scripts/zones/Rolanberry_Fields/TextIDs");
require("scripts/globals/titles");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (ENABLE_WOTG == 1 and player:hasKeyItem(PURE_WHITE_FEATHER) == false) then
player:startEvent(500,1);
elseif (ENABLE_WOTG == 1 and hasMawActivated(player,1)) then
if (player:getCurrentMission(WOTG) == BACK_TO_THE_BEGINNING and
(player:getQuestStatus(CRYSTAL_WAR, CLAWS_OF_THE_GRIFFON) == QUEST_COMPLETED or
player:getQuestStatus(CRYSTAL_WAR, THE_TIGRESS_STRIKES) == QUEST_COMPLETED or
player:getQuestStatus(CRYSTAL_WAR, FIRES_OF_DISCONTENT) == QUEST_COMPLETED)) then
player:startEvent(501);
else
player:startEvent(904);
end
else
player:messageSpecial(NOTHING_HAPPENS);
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:",csid);
-- printf("RESULT:",option);
if (csid == 500) then
local r = math.random(1,3);
player:addKeyItem(PURE_WHITE_FEATHER);
player:messageSpecial(KEYITEM_OBTAINED,PURE_WHITE_FEATHER);
player:completeMission(WOTG,CAVERNOUS_MAWS);
player:addMission(WOTG,BACK_TO_THE_BEGINNING);
if (r == 1) then
player:addNationTeleport(MAW,1);
toMaw(player,1); -- go to Batallia_Downs[S]
elseif (r == 2) then
player:addNationTeleport(MAW,2);
toMaw(player,3); -- go to Rolanberry_Fields_[S]
elseif (r == 3) then
player:addNationTeleport(MAW,4);
toMaw(player,5); -- go to Sauromugue_Champaign_[S]
end;
elseif (csid == 904 and option == 1) then
toMaw(player,3); -- go to Rolanberry_Fields_[S]
elseif (csid == 501) then
player:completeMission(WOTG, BACK_TO_THE_BEGINNING);
player:addMission(WOTG, CAIT_SITH);
player:addTitle(CAIT_SITHS_ASSISTANT);
toMaw(player,3);
end;
end; | gpl-3.0 |
nyczducky/darkstar | scripts/globals/items/handful_of_sunflower_seeds.lua | 12 | 1202 | -----------------------------------------
-- ID: 4505
-- Item: handful_of_sunflower_seeds
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Dexterity -3
-- Intelligence 1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4505);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, -3);
target:addMod(MOD_INT, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, -3);
target:delMod(MOD_INT, 1);
end;
| gpl-3.0 |
Mariappan/rcfiles | home/.notion/cfg_tiling.lua | 1 | 2701 | --
-- Notion tiling module configuration file
--
-- Bindings for the tilings.
defbindings("WTiling", {
bdoc("Split current frame vertically."),
kpress(META.."S", "WTiling.split_at(_, _sub, 'bottom', true)"),
bdoc("Go to frame above/below/right/left of current frame."),
kpress(META.."P", "ioncore.goto_next(_sub, 'up', {no_ascend=_})"),
kpress(META.."N", "ioncore.goto_next(_sub, 'down', {no_ascend=_})"),
-- kpress(META.."K", "ioncore.goto_next(_sub, 'down', {no_ascend=_})"),
kpress(META.."Tab", "ioncore.goto_next(_sub, 'right')"),
submap(META.."W", {
kpress("Tab", "ioncore.goto_next(_sub, 'left')"),
kpress("H", "WTiling.split_at(_, _sub, 'bottom', true)"),
kpress("V", "WTiling.split_at(_, _sub, 'right', true)"),
bdoc("Split current frame horizontally."),
kpress("S", "WTiling.split_at(_, _sub, 'right', true)"),
bdoc("Destroy current frame."),
kpress("X", "WTiling.unsplit_at(_, _sub)"),
}),
})
-- Frame bindings
defbindings("WFrame.floating", {
submap(META.."W", {
bdoc("Tile frame, if no tiling exists on the workspace"),
kpress("B", "mod_tiling.mkbottom(_)"),
}),
})
-- Context menu for tiled workspaces.
defctxmenu("WTiling", "Tiling", {
menuentry("Destroy frame",
"WTiling.unsplit_at(_, _sub)"),
menuentry("Split vertically",
"WTiling.split_at(_, _sub, 'bottom', true)"),
menuentry("Split horizontally",
"WTiling.split_at(_, _sub, 'right', true)"),
menuentry("Flip", "WTiling.flip_at(_, _sub)"),
menuentry("Transpose", "WTiling.transpose_at(_, _sub)"),
menuentry("Untile", "mod_tiling.untile(_)"),
submenu("Float split", {
menuentry("At left",
"WTiling.set_floating_at(_, _sub, 'toggle', 'left')"),
menuentry("At right",
"WTiling.set_floating_at(_, _sub, 'toggle', 'right')"),
menuentry("Above",
"WTiling.set_floating_at(_, _sub, 'toggle', 'up')"),
menuentry("Below",
"WTiling.set_floating_at(_, _sub, 'toggle', 'down')"),
}),
submenu("At root", {
menuentry("Split vertically",
"WTiling.split_top(_, 'bottom')"),
menuentry("Split horizontally",
"WTiling.split_top(_, 'right')"),
menuentry("Flip", "WTiling.flip_at(_)"),
menuentry("Transpose", "WTiling.transpose_at(_)"),
}),
})
-- Extra context menu extra entries for floatframes.
defctxmenu("WFrame.floating", "Floating frame", {
append=true,
menuentry("New tiling", "mod_tiling.mkbottom(_)"),
})
| gpl-2.0 |
ld-test/lzmq-ffi | examples/perf2/runner.lua | 16 | 4452 | local DIR_SEP = package.config:sub(1,1)
local msg_size
local msg_count
local N
local function exec(cmd)
local f, err = io.popen(cmd, "r")
if not f then return err end
local data, err = f:read("*all")
f:close()
return data, err
end
local function parse_thr(result)
local msgps = assert(
tonumber((result:match("mean throughput: (%S+) %[msg/s%]")))
, result)
local mbps = assert(
tonumber((result:match("mean throughput: (%S+) %[Mb/s%]")))
, result)
return msgps, mbps
end
local function parse_lat(result)
return assert(
tonumber((result:match("average latency: (%S+) %[us%]")))
, result)
end
local function exec_thr(cmd)
local msg = assert(exec(cmd))
return parse_thr(msg)
end
local function exec_lat(cmd)
local msg = assert(exec(cmd))
return parse_lat(msg)
end
local function field(wdt, fmt, value)
local str = string.format(fmt, value)
if wdt > #str then str = str .. (' '):rep(wdt - #str) end
return str
end
local function print_row(row)
print('|' .. table.concat(row, '|') .. '|')
end
function luajit_thr(result, dir, ffi)
local cmd =
"cd " .. dir .. " && " ..
"luajit ." .. DIR_SEP .."inproc_thr.lua " .. msg_size .. " " .. msg_count .. " " .. ffi ..
" && cd .."
for i = 1, N do
table.insert(result, {exec_thr(cmd)})
end
end
function bin_thr(result, dir)
local cmd =
"cd " .. dir .. " && " ..
"." .. DIR_SEP .."inproc_thr " .. msg_size .. " " .. msg_count ..
" && cd .."
for i = 1, N do
table.insert(result, {exec_thr(cmd)})
end
end
function luajit_lat(result, dir, ffi)
local cmd =
"cd " .. dir .. " && " ..
"luajit ." .. DIR_SEP .."inproc_lat.lua " .. msg_size .. " " .. msg_count .. " " .. ffi ..
" && cd .."
for i = 1, N do
table.insert(result, {exec_lat(cmd)})
end
end
function bin_lat(result, dir)
local cmd =
"cd " .. dir .. " && " ..
"." .. DIR_SEP .."inproc_lat " .. msg_size .. " " .. msg_count ..
" && cd .."
for i = 1, N do
table.insert(result, {exec_lat(cmd)})
end
end
msg_size = 30
msg_count = 10000
N = 10
local libzmq_thr = {}
local nomsg_thr = {}
local nomsg_thr_ffi = {}
local msg_thr = {}
local msg_thr_ffi = {}
bin_thr(libzmq_thr, "libzmq")
luajit_thr(nomsg_thr, "thr_nomsg", "" )
luajit_thr(nomsg_thr_ffi, "thr_nomsg", "ffi" )
luajit_thr(msg_thr, "thr", "" )
luajit_thr(msg_thr_ffi, "thr", "ffi" )
print("\n----")
print("###Inproc Throughput Test:\n")
print(string.format("message size: %d [B]<br/>", msg_size ))
print(string.format("message count: %d<br/>", msg_count ))
print(string.format("mean throughput [Mb/s]:<br/>\n" ))
print_row{
field(3, " # ");
field(12, " libzmq");
field(12, " str");
field(12, " str(ffi)");
field(12, " msg");
field(12, " msg(ffi)");
}
print_row{
("-"):rep(3);
("-"):rep(12);
("-"):rep(12);
("-"):rep(12);
("-"):rep(12);
("-"):rep(12);
}
for i = 1, N do
print_row{
field(3, " %d", i);
field(12,"%.3f", libzmq_thr [i][2]);
field(12,"%.3f", nomsg_thr [i][2]);
field(12,"%.3f", nomsg_thr_ffi [i][2]);
field(12,"%.3f", msg_thr [i][2]);
field(12,"%.3f", msg_thr_ffi [i][2]);
}
end
msg_size = 1
msg_count = 10000
N = 10
local libzmq_lat = {}
local nomsg_lat = {}
local nomsg_lat_ffi = {}
local msg_lat = {}
local msg_lat_ffi = {}
bin_lat(libzmq_lat, "libzmq")
luajit_lat(nomsg_lat, "lat_nomsg", "" )
luajit_lat(nomsg_lat_ffi, "lat_nomsg", "ffi" )
luajit_lat(msg_lat, "lat", "" )
luajit_lat(msg_lat_ffi, "lat", "ffi" )
print("\n----")
print("###Inproc Latency Test:\n")
print(string.format("message size: %d [B]<br/>", msg_size ))
print(string.format("message count: %d<br/>", msg_count ))
print(string.format("average latency [us]:<br/>\n" ))
print_row{
field(3, " # ");
field(12, " libzmq");
field(12, " str");
field(12, " str(ffi)");
field(12, " msg");
field(12, " msg(ffi)");
}
print_row{
("-"):rep(3);
("-"):rep(12);
("-"):rep(12);
("-"):rep(12);
("-"):rep(12);
("-"):rep(12);
}
for i = 1, N do
print_row{
field(3, " %d", i);
field(12,"%.3f", libzmq_lat [i][1]);
field(12,"%.3f", nomsg_lat [i][1]);
field(12,"%.3f", nomsg_lat_ffi [i][1]);
field(12,"%.3f", msg_lat [i][1]);
field(12,"%.3f", msg_lat_ffi [i][1]);
}
end
| mit |
pakozm/april-pi-cnn-line-follower | offline_learn.lua | 1 | 1546 | local offline_controller
local brickpi = {
sensorValue = function()
return offline_controller:get_info().sensor
end
}
setmetatable(brickpi,
{
__index = function() return function() return true end end
})
package.preload.brickpi = function() return brickpi end
package.path = "%s?.lua;%s"%{ arg[0]:get_path(), package.path }
local utils = require "utils"
--
offline_controller = utils.offline_controller("%sdata/"%{arg[0]:get_path()})
--
local filename = arg[1] or "nets/default.net"
local out_filename = arg[2] or "nets/last.net"
-- QLearning parameters
local DISCOUNT = 0.6
local PENALTY = -0.5
local REWARD = 2.0
-- MAIN
local trainer = utils.trainer(filename, DISCOUNT)
local sensor = utils.sensor(utils.LIGHT_SENSOR,
REWARD, PENALTY)
local finished = false
signal.register(signal.SIGINT, function() finished = true end)
while offline_controller:next() and not finished do
collectgarbage("collect")
local img_path = offline_controller:get_input_path()
local info = offline_controller:get_info()
sensor.BLACK_MEAN = info.mean
sensor.BLACK_V = info.var
sensor.slope = (REWARD - PENALTY) / (sensor.BLACK_V * 2)
trainer.prev_action = info.action
local action,qs = trainer:one_step(img_path, sensor)
trainer:save(out_filename)
local w1 = trainer.tr:weights("w1")
local sz = math.sqrt(w1:dim(2))
local img = ann.connections.input_filters_image(w1, {sz,sz})
ImageIO.write(img,"data/wop.png")
end
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/The_Garden_of_RuHmet/mobs/Jailer_of_Faith.lua | 23 | 1527 | -----------------------------------
-- Area: The Garden of Ru'Hmet
-- NPC: Jailer_of_Faith
-----------------------------------
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
-- Give it two hour
mob:setMod(MOBMOD_MAIN_2HOUR, 1);
-- Change animation to open
mob:AnimationSub(2);
end;
-----------------------------------
-- onMobFight Action
-- Randomly change forms
-----------------------------------
function onMobFight(mob)
-- Forms: 0 = Closed 1 = Closed 2 = Open 3 = Closed
local randomTime = math.random(45,180);
local changeTime = mob:getLocalVar("changeTime");
if (mob:getBattleTime() - changeTime > randomTime) then
-- Change close to open.
if (mob:AnimationSub() == 1) then
mob:AnimationSub(2);
else -- Change from open to close
mob:AnimationSub(1);
end
mob:setLocalVar("changeTime", mob:getBattleTime());
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob)
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
local qm3 = GetNPCByID(Jailer_of_Faith_QM);
qm3:updateNPCHideTime(FORCE_SPAWN_QM_RESET_TIME);
local qm3position = math.random(1,5);
qm3:setPos(Jailer_of_Faith_QM_POS[qm3position][1], Jailer_of_Faith_QM_POS[qm3position][2], Jailer_of_Faith_QM_POS[qm3position][3]);
end; | gpl-3.0 |
jbeich/Aquaria | files/scripts/entities/nudibranchtemplate.lua | 6 | 2979 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
v.n = 0
v.noteDown = -1
v.note1 = -1
v.note2 = -1
v.note3 = -1
function v.commonInit(me, gfxNum, n1, n2, n3)
setupEntity(me)
entity_setTexture(me, string.format("NudiBranch/NudiBranch%d", gfxNum))
entity_setEntityType(me, ET_ENEMY)
entity_setAllDamageTargets(me, false)
entity_setCollideRadius(me, 48)
v.note1 = n1
v.note2 = n2
v.note3 = n3
entity_setState(me, STATE_IDLE)
entity_setMaxSpeed(me, 700)
entity_offset(me, 0, 10, 1, -1, 1, 1)
entity_update(me, math.random(100)/100.0)
entity_setUpdateCull(me, 2000)
entity_setDamageTarget(me, DT_AVATAR_VINE, true)
end
function postInit(me)
v.n = getNaija()
entity_setTarget(me, v.n)
end
function update(me, dt)
if v.noteDown ~= -1 and entity_isEntityInRange(me, v.n, 800) then
local rotspd = 0.8
if v.noteDown == v.note2 then
entity_moveTowardsTarget(me, dt, 1000)
if entity_doEntityAvoidance(me, dt, 128, 1.0) then
entity_setMaxSpeedLerp(me, 0.2)
else
entity_setMaxSpeedLerp(me, 2.0, 0.2)
end
entity_rotateToVel(me, rotspd)
elseif v.noteDown == v.note1 or v.noteDown == v.note3 then
entity_moveTowardsTarget(me, dt, 500)
if entity_doEntityAvoidance(me, dt, 128, 1.0) then
entity_setMaxSpeedLerp(me, 0.2)
else
entity_setMaxSpeedLerp(me, 1, 0.2)
end
entity_rotateToVel(me, rotspd)
end
else
v.noteDown = -1
entity_rotate(me, 0, 0.5, 0, 0, 1)
end
entity_doFriction(me, dt, 300)
entity_updateMovement(me, dt)
entity_handleShotCollisions(me)
if isForm(FORM_NATURE) then
entity_touchAvatarDamage(me, entity_getCollideRadius(me), 0.5, 500, 0)
else
entity_touchAvatarDamage(me, entity_getCollideRadius(me), 1.0, 500, 0)
end
end
function enterState(me)
if entity_isState(me, STATE_IDLE) then
end
end
function exitState(me)
end
function damage(me, attacker, bone, damageType, dmg)
return false
end
function animationKey(me, key)
end
function hitSurface(me)
end
function songNote(me, note)
v.noteDown = note
end
function songNoteDone(me, note)
v.noteDown = -1
end
function song(me, song)
end
function activate(me)
end
| gpl-2.0 |
francot514/CardGamePRO-Simulator | data/cards/c1084.lua | 1 | 1077 | --War elephant
function c1084.initial_effect(c)
--destroy
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DESTROY)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_BATTLE_DAMAGE)
e1:SetCondition(c1084.condition)
e1:SetTarget(c1084.target)
e1:SetOperation(c1084.operation)
c:RegisterEffect(e1)
end
function c1084.condition(e,tp,eg,ep,ev,re,r,rp)
return ep~=tp
end
function c1084.filter(c)
return c:IsDestructable()
end
function c1084.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(1-tp) and chkc:IsLocation(LOCATION_MZONE) and c1084.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c1084.filter,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,c1084.filter,tp,0,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c1084.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| gpl-2.0 |
mehrpouya81/giantbot | plugins/media.lua | 376 | 1679 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
usage = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
AquariaOSE/Aquaria | files/scripts/entities/anemone2.lua | 12 | 2819 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
-- ================================================================================================
-- A N E M O N E
-- ================================================================================================
-- ================================================================================================
-- FUNCTIONS
-- ================================================================================================
function init(me)
setupBasicEntity(
me,
"Anemone-0002", -- texture
9, -- health
1, -- manaballamount
1, -- exp
0, -- money
128, -- collideRadius (for hitting entities + spells)
STATE_IDLE, -- initState
128, -- sprite width
256, -- sprite height
1, -- particle "explosion" type, maps to particleEffects.txt -1 = none
1, -- 0/1 hit other entities off/on (uses collideRadius)
4000 -- updateCull -1: disabled, default: 4000
)
entity_setSegs(me, 2, 10, 6.0, 4.0, -0.02, 0, 2.5, 1)
entity_setDeathParticleEffect(me, "AnemoneExplode")
entity_setDamageTarget(me, DT_AVATAR_ENERGYBLAST, false)
entity_setDamageTarget(me, DT_AVATAR_SHOCK, false)
entity_setDamageTarget(me, DT_AVATAR_LIZAP, false)
entity_setDamageTarget(me, DT_AVATAR_PET, false)
entity_setTargetPriority(me, -1)
end
function update(me, dt)
entity_handleShotCollisions(me)
local dmg = 0.5
if isForm(FORM_NATURE) then
dmg = 0
end
if entity_touchAvatarDamage(me, 70, dmg, 1200, 0, 0, -60) then
--entity_push(getNaija(), 1200, 1, 0)
end
local range = 1024
local size = 1.0
if entity_isEntityInRange(me, getNaija(), range) then
local dist = entity_getDistanceToEntity(me, getNaija())
dist = size - (dist/range)*size
local sz = 1 + dist
entity_scale(me, 1, sz)
end
end
function damage(me, attacker, bone, damageType, dmg)
return true
end
function enterState()
end
function exitState()
end
function hitSurface()
end
| gpl-2.0 |
sudheesh001/RFID-DBSync | cardpeek-0.8.3/dot_cardpeek_dir/scripts/etc/paris-metro.lua | 17 | 9555 | METRO_LIST = {
[01] = {
["name"] = "Cité",
[01] = "Saint-Michel",
[04] = "Odéon",
[05] = "Cluny - La Sorbonne",
[06] = "Maubert - Mutualité",
[07] = "Luxembourg",
[08] = "Châtelet",
[09] = "Les Halles",
[10] = "Les Halles",
[12] = "Louvre - Rivoli",
[13] = "Pont Neuf",
[14] = "Cité",
[15] = "Hôtel de Ville"
},
[02] = {
["name"] = "Rennes",
[02] = "Cambronne",
[03] = "Sèvres - Lecourbe",
[04] = "Ségur",
[06] = "Saint-François-Xavier",
[07] = "Duroc",
[08] = "Vaneau",
[09] = "Sèvres - Babylone",
[10] = "Rue du Bac",
[11] = "Rennes",
[12] = "Saint-Sulpice",
[14] = "Mabillon",
[15] = "Saint-Germain-des-Prés"
},
[03] = {
["name"] = "Villette",
[04] = "Porte de la Villette",
[05] = "Aubervilliers - Pantin - Quatre Chemins",
[06] = "Fort d'Aubervilliers",
[07] = "La Courneuve - 8 Mai 1945",
[09] = "Hoche",
[10] = "Église de Pantin",
[11] = "Bobigny - Pantin - Raymond Queneau",
[12] = "Bobigny - Pablo Picasso"
},
[04] = {
["name"] = "Montparnasse",
[02] = "Pernety",
[03] = "Plaisance",
[04] = "Gaîté",
[06] = "Edgar Quinet",
[07] = "Vavin",
[08] = "Montparnasse - Bienvenüe",
[12] = "Saint-Placide",
[14] = "Notre-Dame-des-Champs"
},
[05] = {
["name"] = "Nation",
[02] = "Robespierre",
[03] = "Porte de Montreuil",
[04] = "Maraîchers",
[05] = "Buzenval",
[06] = "Rue des Boulets",
[07] = "Porte de Vincennes",
[09] = "Picpus",
[10] = "Nation",
[12] = "Avron",
[13] = "Alexandre Dumas"
},
[06] = {
["name"] = "Saint-Lazare",
[01] = "Malesherbes",
[02] = "Monceau",
[03] = "Villiers",
[04] = "Quatre-Septembre",
[05] = "Opéra",
[06] = "Auber",
[07] = "Havre - Caumartin",
[08] = "Saint-Lazare",
[09] = "Saint-Lazare",
[10] = "Saint-Augustin",
[12] = "Europe",
[13] = "Liège"
},
[07] = {
["name"] = "Auteuil",
[03] = "Porte de Saint-Cloud",
[07] = "Porte d'Auteuil",
[08] = "Église d'Auteuil",
[09] = "Michel-Ange - Auteuil",
[10] = "Michel-Ange - Molitor",
[11] = "Chardon-Lagache",
[12] = "Mirabeau",
[14] = "Exelmans",
[15] = "Jasmin"
},
[08] = {
["name"] = "République",
[01] = "Rambuteau",
[03] = "Arts et Métiers",
[04] = "Jacques Bonsergent",
[05] = "Goncourt",
[06] = "Temple",
[07] = "République",
[10] = "Oberkampf",
[11] = "Parmentier",
[12] = "Filles du Calvaire",
[13] = "Saint-Sébastien - Froissart",
[14] = "Richard-Lenoir",
[15] = "Saint-Ambroise"
},
[09] = {
["name"] = "Austerlitz",
[01] = "Quai de la Gare",
[02] = "Chevaleret",
[04] = "Saint-Marcel",
[07] = "Gare d'Austerlitz",
[08] = "Gare de Lyon",
[10] = "Quai de la Rapée"
},
[10] = {
["name"] = "Invalides",
[01] = "Champs-Élysées - Clemenceau",
[02] = "Concorde",
[03] = "Madeleine",
[04] = "Bir-Hakeim",
[07] = "École Militaire",
[08] = "La Tour-Maubourg",
[09] = "Invalides",
[11] = "Saint-Denis - Université",
[12] = "Varenne",
[13] = "Assemblée nationale",
[14] = "Solférino"
},
[11] = {
["name"] = "Sentier",
[01] = "Tuileries",
[02] = "Palais Royal - Musée du Louvre",
[03] = "Pyramides",
[04] = "Bourse",
[06] = "Grands Boulevards",
[07] = "Richelieu - Drouot",
[08] = "Bonne Nouvelle",
[10] = "Strasbourg - Saint-Denis",
[11] = "Château d'Eau",
[13] = "Sentier",
[14] = "Réaumur - Sébastopol",
[15] = "Étienne Marcel"
},
[12] = {
["name"] = "Île Saint-Louis",
[01] = "Faidherbe - Chaligny",
[02] = "Reuilly - Diderot",
[03] = "Montgallet",
[04] = "Censier - Daubenton",
[05] = "Place Monge",
[06] = "Cardinal Lemoine",
[07] = "Jussieu",
[08] = "Sully - Morland",
[09] = "Pont Marie",
[10] = "Saint-Paul",
[12] = "Bastille",
[13] = "Chemin Vert",
[14] = "Bréguet - Sabin",
[15] = "Ledru-Rollin"
},
[13] = {
["name"] = "Daumesnil",
[01] = "Porte Dorée",
[03] = "Porte de Charenton",
[07] = "Bercy",
[08] = "Dugommier",
[10] = "Michel Bizot",
[11] = "Daumesnil",
[12] = "Bel-Air"
},
[14] = {
["name"] = "Italie",
[02] = "Porte de Choisy",
[03] = "Porte d'Italie",
[04] = "Cité universitaire",
[09] = "Maison Blanche",
[10] = "Tolbiac",
[11] = "Nationale",
[12] = "Campo-Formio",
[13] = "Les Gobelins",
[14] = "Place d'Italie",
[15] = "Corvisart"
},
[15] = {
["name"] = "Denfert",
[01] = "Cour Saint-Emilion",
[02] = "Porte d'Orléans",
[03] = "Bibliothèque François Mitterrand",
[04] = "Mouton-Duvernet",
[05] = "Alésia",
[06] = "Olympiades",
[08] = "Glacière",
[09] = "Saint-Jacques",
[10] = "Raspail",
[14] = "Denfert-Rochereau"
},
[16] = {
["name"] = "Félix Faure",
[01] = "Falguière",
[02] = "Pasteur",
[03] = "Volontaires",
[04] = "Vaugirard",
[05] = "Convention",
[06] = "Porte de Versailles",
[09] = "Balard",
[10] = "Lourmel",
[11] = "Boucicaut",
[12] = "Félix Faure",
[13] = "Charles Michels",
[14] = "Javel - André Citroën"
},
[17] = {
["name"] = "Passy",
[02] = "Porte Dauphine",
[04] = "La Motte-Picquet - Grenelle",
[05] = "Commerce",
[06] = "Avenue Émile Zola",
[07] = "Dupleix",
[08] = "Passy",
[09] = "Ranelagh",
[11] = "La Muette",
[13] = "Rue de la Pompe",
[14] = "Boissière",
[15] = "Trocadéro"
},
[18] = {
["name"] = "Étoile",
[01] = "Iéna",
[03] = "Alma - Marceau",
[04] = "Miromesnil",
[05] = "Saint-Philippe du Roule",
[07] = "Franklin D. Roosevelt",
[08] = "George V",
[09] = "Kléber",
[10] = "Victor Hugo",
[11] = "Argentine",
[12] = "Charles de Gaulle - ?~Itoile",
[14] = "Ternes",
[15] = "Courcelles"
},
[19] = {
["name"] = "Clichy - Saint Ouen",
[01] = "Mairie de Clichy",
[02] = "Gabriel Péri",
[03] = "Les Agnettes",
[04] = "Asnières - Gennevilliers - Les Courtilles",
[09] = "La Chapelle)",
[10] = "Garibaldi",
[11] = "Mairie de Saint-Ouen",
[13] = "Carrefour Pleyel",
[14] = "Saint-Denis - Porte de Paris",
[15] = "Basilique de Saint-Denis"
},
[20] = {
["name"] = "Montmartre",
[01] = "Porte de Clignancourt",
[06] = "Porte de la Chapelle",
[07] = "Marx Dormoy",
[09] = "Marcadet - Poissonniers",
[10] = "Simplon",
[11] = "Jules Joffrin",
[12] = "Lamarck - Caulaincourt"
},
[21] = {
["name"] = "Lafayette",
[01] = "Chaussée d'Antin - La Fayette",
[02] = "Le Peletier",
[03] = "Cadet",
[04] = "Château Rouge",
[07] = "Barbès - Rochechouart",
[08] = "Gare du Nord",
[09] = "Gare de l'Est",
[10] = "Poissonnière",
[11] = "Château-Landon"
},
[22] = {
["name"] = "Buttes Chaumont",
[01] = "Porte de Pantin",
[02] = "Ourcq",
[04] = "Corentin Cariou",
[06] = "Crimée",
[08] = "Riquet",
[09] = "La Chapelle",
[10] = "Louis Blanc",
[11] = "Stalingrad",
[12] = "Jaurès",
[13] = "Laumière",
[14] = "Bolivar",
[15] = "Colonel Fabien"
},
[23] = {
["name"] = "Belleville",
[02] = "Porte des Lilas",
[03] = "Mairie des Lilas",
[04] = "Porte de Bagnolet",
[05] = "Gallieni",
[08] = "Place des Fêtes",
[09] = "Botzaris",
[10] = "Danube",
[11] = "Pré Saint-Gervais",
[13] = "Buttes Chaumont",
[14] = "Jourdain",
[15] = "Télégraphe"
},
[24] = {
["name"] = "Père Lachaise",
[01] = "Voltaire",
[02] = "Charonne",
[04] = "Père Lachaise",
[05] = "Ménilmontant",
[06] = "Rue Saint-Maur",
[07] = "Philippe Auguste",
[08] = "Saint-Fargeau",
[09] = "Pelleport",
[10] = "Gambetta",
[12] = "Belleville",
[13] = "Couronnes",
[14] = "Pyrénées"
},
[25] = {
["name"] = "Charenton",
[02] = "Croix de Chavaux",
[03] = "Mairie de Montreuil",
[04] = "Maisons-Alfort - Les Juilliottes",
[05] = "Créteil - L'Échat",
[06] = "Créteil - Université",
[07] = "Créteil - Préfecture",
[08] = "Saint-Mandé",
[10] = "Bérault",
[11] = "Château de Vincennes",
[12] = "Liberté",
[13] = "Charenton - Écoles",
[14] = "École vétérinaire de Maisons-Alfort",
[15] = "Maisons-Alfort - Stade"
},
[26] = {
["name"] = "Ivry - Villejuif",
[03] = "Porte d'Ivry",
[04] = "Pierre et Marie Curie",
[05] = "Mairie d'Ivry",
[06] = "Le Kremlin-Bicêtre",
[07] = "Villejuif - Léo Lagrange",
[08] = "Villejuif - Paul Vaillant-Couturier",
[09] = "Villejuif - Louis Aragon"
},
[27] = {
["name"] = "Vanves",
[02] = "Porte de Vanves",
[07] = "Malakoff - Plateau de Vanves",
[08] = "Malakoff - Rue Étienne Dolet",
[09] = "Châtillon - Montrouge"
},
[28] = {
["name"] = "Issy",
[02] = "Corentin Celton",
[03] = "Mairie d'Issy",
[08] = "Marcel Sembat",
[09] = "Billancourt",
[10] = "Pont de Sèvres"
},
[29] = {
["name"] = "Levallois",
[00] = "La Défense (correspondance RER)",
[04] = "Boulogne - Jean Jaurès",
[05] = "Boulogne - Pont de Saint-Cloud",
[08] = "Les Sablons",
[09] = "Pont de Neuilly",
[10] = "Esplanade de la Défense",
[11] = "La Défense",
[12] = "Porte de Champerret",
[13] = "Louise Michel",
[14] = "Anatole France",
[15] = "Pont de Levallois - Bécon"
},
[30] = {
["name"] = "Péreire",
[01] = "Porte Maillot",
[04] = "Wagram",
[05] = "Pereire",
[08] = "Brochant",
[09] = "Porte de Clichy",
[12] = "Guy Môquet",
[13] = "Porte de Saint-Ouen"
},
[31] = {
["name"] = "Pigalle",
[02] = "Funiculaire de Montmartre (station inférieure)",
[03] = "Funiculaire de Montmartre (station supérieure)",
[04] = "Anvers",
[05] = "Abbesses",
[06] = "Pigalle",
[07] = "Blanche",
[08] = "Trinité - d'Estienne d'Orves",
[09] = "Notre-Dame-de-Lorette",
[10] = "Saint-Georges",
[12] = "Rome",
[13] = "Place de Clichy",
[14] = "La Fourche"
}
}
| gpl-2.0 |
ArmanIr/restore | plugins/stats.lua | 33 | 3680 | do
local NUM_MSG_MAX = 6
local TIME_CHECK = 4 -- seconds
local function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ('..user_id..')'
return user_info
end
local function chat_stats(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = ''
for k,user in pairs(users_info) do
text = text..user.name..' => '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
print('Service message')
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
-- Check flood
local kick = chat_del_user(chat_id , user_id, ok_cb, true)
vardump(kick)
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
chat_del_user('chat#id'..msg.to.id,'user#id'..msg.from.id,ok_cb,false)
print('User '..msg.from.id..'is flooding '..msgs)
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nChats: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == "stats" then
if not matches[2] then
if msg.to.type == 'chat' then
local chat_id = msg.to.id
return chat_stats(chat_id)
else
return 'Stats works only on chats'
end
end
if matches[2] == "bot" then
if not is_sudo(msg) then
return "Bot stats requires privileged user"
else
return bot_stats()
end
end
if matches[2] == "chat" then
if not is_sudo(msg) then
return "This command requires privileged user"
else
return chat_stats(matches[3])
end
end
end
end
return {
description = "Plugin to update user stats.",
usage = {
"!stats: Returns a list of Username [telegram_id]: msg_num",
"!stats chat <chat_id>: Show stats for chat_id",
"!stats bot: Shows bot stats (sudo users)"
},
patterns = {
"^!([Ss]tats)$",
"^!([Ss]tats) (chat) (%d+)",
"^!([Ss]tats) (bot)"
},
run = run,
pre_process = pre_process
}
end
| gpl-2.0 |
nyczducky/darkstar | scripts/globals/items/culinarians_belt.lua | 12 | 1180 | -----------------------------------------
-- ID: 15451
-- Item: Culinarian's Belt
-- Enchantment: Synthesis image support
-- 2Min, All Races
-----------------------------------------
-- Enchantment: Synthesis image support
-- Duration: 2Min
-- Alchemy Skill +3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_COOKING_IMAGERY) == true) then
result = 243;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_COOKING_IMAGERY,3,0,120);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_SKILL_COK, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_SKILL_COK, 1);
end; | gpl-3.0 |
alinoroz/pop_tm | plugins/gif.lua | 15 | 1758 | do
local BASE_URL = 'http://api.giphy.com/v1'
local API_KEY = 'dc6zaTOxFJmzC' -- public beta key
local function get_image(response)
local images = json:decode(response).data
if #images == 0 then return nil end -- No images
local i = math.random(#images)
local image = images[i] -- A random one
if image.images.downsized then
return image.images.downsized.url
end
if image.images.original then
return image.original.url
end
return nil
end
local function get_random_top()
local url = BASE_URL.."/gifs/trending?api_key="..API_KEY
local response, code = http.request(url)
if code ~= 200 then return nil end
return get_image(response)
end
local function search(text)
text = URL.escape(text)
local url = BASE_URL.."/gifs/search?q="..text.."&api_key="..API_KEY
local response, code = http.request(url)
if code ~= 200 then return nil end
return get_image(response)
end
local function run(msg, matches)
local gif_url = nil
-- If no search data, a random trending GIF will be sent
if matches[1] == "gif" or matches[1] == "giphy" then
gif_url = get_random_top()
else
gif_url = search(matches[1])
end
if not gif_url then
return "خطا گیف مورد نظر پیدا نشد"
end
local receiver = get_receiver(msg)
print("GIF URL"..gif_url)
send_document_from_url(receiver, gif_url)
end
return {
description = "GIFs from telegram with Giphy API",
usage = {
"!gif (term): Search and sends GIF from Giphy. If no param, sends a trending GIF.",
"!giphy (term): Search and sends GIF from Giphy. If no param, sends a trending GIF."
},
patterns = {
"^[!/#](gif)$",
"^[!/#](gif) (.*)",
"^[!/#](giphy) (.*)",
"^[!/#](giphy)$"
},
run = run
}
end
| gpl-2.0 |
AquariaOSE/Aquaria | files/scripts/entities/collectibleenergystatue.lua | 6 | 1296 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
-- song cave collectible
dofile("scripts/include/collectibletemplate.lua")
function init(me)
v.commonInit(me, "Collectibles/energystatue", FLAG_COLLECTIBLE_ENERGYSTATUE)
end
function update(me, dt)
v.commonUpdate(me, dt)
end
function enterState(me, state)
v.commonEnterState(me, state)
if entity_isState(me, STATE_COLLECTEDINHOUSE) then
--createEntity("Walker", "", entity_x(me), entity_y(me))
end
end
function exitState(me, state)
v.commonExitState(me, state)
end
| gpl-2.0 |
nyczducky/darkstar | scripts/globals/items/death_scythe.lua | 42 | 1065 | -----------------------------------------
-- ID: 16777
-- Item: Death Scythe
-- Additional Effect: Drains HP
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 10;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local power = 10;
local params = {};
params.bonusmab = 0;
params.includemab = false;
power = addBonusesAbility(player, ELE_DARK, target, power, params);
power = power * applyResistanceAddEffect(player,target,ELE_DARK,0);
power = adjustForTarget(target,power,ELE_DARK);
power = finalMagicNonSpellAdjustments(player,target,ELE_DARK,power );
if (power < 0) then
power = 0;
else
player:addHP(power)
end
return SUBEFFECT_HP_DRAIN, MSGBASIC_ADD_EFFECT_HP_DRAIN, power;
end
end; | gpl-3.0 |
nyczducky/darkstar | scripts/zones/RaKaznar_Inner_Court/npcs/HomePoint#1.lua | 9 | 1287 | -----------------------------------
-- Area: RaKaznar_Inner_Court
-- NPC: HomePoint#1
-- @pos 757 120 17.5 276
-----------------------------------
package.loaded["scripts/zones/RaKaznar_Inner_Court/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/RaKaznar_Inner_Court/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 116);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
nyczducky/darkstar | scripts/globals/weaponskills/final_heaven.lua | 19 | 2208 | -------------------------------
-- Skill: Final Heaven
-- H2H weapon skill
-- Skill Level N/A
-- Additional effect: temporarily enhances Subtle Blow effect.
-- Mods : VIT:60%
-- 100%TP 200%TP 300%TP
-- 3.0x 3.0x 3.0x
-- +10 Subtle Blow for a short duration after using the weapon skill. (Not implemented)
-------------------------------
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
require("scripts/globals/weaponskills");
-------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
-- number of normal hits for ws
params.numHits = 1;
-- stat-modifiers (0.0 = 0%, 0.2 = 20%, 0.5 = 50%..etc)
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;
-- ftp damage mods (for Damage Varies with TP; lines are calculated in the function params.ftp)
params.ftp100 = 3.0; params.ftp200 = 3.0; params.ftp300 = 3.0;
-- critical modifiers (0.0 = 0%, 0.2 = 20%, 0.5 = 50%..etc)
params.crit100 = 0.0; params.crit200=0.0; params.crit300=0.0;
params.canCrit = false;
-- accuracy modifiers (0.0 = 0%, 0.2 = 20%, 0.5 = 50%..etc) Keep 0 if ws doesn't have accuracy modification.
params.acc100 = 0.0; params.acc200=0.0; params.acc300=0.0;
-- attack multiplier (only some WSes use this, this varies the actual ratio value, see Tachi: Kasha) 1 is default.
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.vit_wsc = 0.8;
end
-- damage = damage * ftp(tp, ftp100, ftp200, ftp300);
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
-- TODO: Whoever codes those level 85 weapons with the latent that grants this WS needs to code a check to not give the aftermath effect.
if (damage > 0) then
local amDuration = 20 * math.floor(tp/1000);
player:addStatusEffect(EFFECT_AFTERMATH, 10, 0, amDuration, 0, 1);
end
return tpHits, extraHits, criticalHit, damage;
end | gpl-3.0 |
nyczducky/darkstar | scripts/globals/spells/bluemagic/smite_of_rage.lua | 33 | 1678 | -----------------------------------------
-- Spell: Smite of Rage
-- Damage varies with TP
-- Spell cost: 28 MP
-- Monster Type: Arcana
-- Spell Type: Physical (Slashing)
-- Blue Magic Points: 3
-- Stat Bonus: AGI+3
-- Level: 34
-- Casting Time: 0.5 seconds
-- Recast Time: 13 seconds
-- Skillchain Element(s): Wind (can open Scission or Gravitation; can close Detonation)
-- Combos: Undead Killer
-----------------------------------------
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_DAMAGE;
params.dmgtype = DMGTYPE_SLASH;
params.scattr = SC_DETONATION;
params.numhits = 1;
params.multiplier = 1.5;
params.tp150 = 2.25;
params.tp300 = 2.5;
params.azuretp = 2.53125;
params.duppercap = 35;
params.str_wsc = 0.2;
params.dex_wsc = 0.2;
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;
damage = BluePhysicalSpell(caster, target, spell, params);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
return damage;
end; | gpl-3.0 |
nyczducky/darkstar | scripts/zones/Tavnazian_Safehold/npcs/Maturiri.lua | 14 | 1064 | ----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Maturiri
-- Type: Item Deliverer
-- @zone 26
-- @pos -77.366 -20 -71.128
--
-----------------------------------
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
require("scripts/zones/Tavnazian_Safehold/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, ITEM_DELIVERY_DIALOG);
player:openSendBox();
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/East_Ronfaure/TextIDs.lua | 7 | 1411 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6401; -- You cannot obtain the item <item> come back again after sorting your inventory.
ITEM_OBTAINED = 6407; -- Obtained: <item>.
GIL_OBTAINED = 6408; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6410; -- Obtained key item: <keyitem>.
FISHING_MESSAGE_OFFSET = 7227; -- You can't fish here.
-- Logging
LOGGING_IS_POSSIBLE_HERE = 7483; -- Logging is possible here if you have
-- General Dialog
RAYOCHINDOT_DIALOG = 7407; -- If you are outmatched, run to the city as quickly as you can.
CROTEILLARD_DIALOG = 7408; -- Sorry, no chatting while I'm on duty.
BLESSED_WATERSKIN = 7452; -- To get water, radethe waterskin you hold with the river.
CHEVAL_RIVER_WATER = 7433; -- You fill your waterskin with water from the river. You now have
NOTHING_OUT_OF_ORDINARY = 6421; -- There is nothing out of the ordinary here.
-- Other Dialog
NOTHING_HAPPENS = 7327; -- Nothing happens...
-- conquest Base
CONQUEST_BASE = 7068; -- Tallying conquest results...
-- chocobo digging
DIG_THROW_AWAY = 7240; -- You dig up ?Possible Special Code: 01??Possible Special Code: 01??Possible Special Code: 01? ?Possible Special Code: 01??Possible Special Code: 05?$?BAD CHAR: 8280??BAD CHAR: 80??BAD CHAR: 80?, but your inventory is full.
FIND_NOTHING = 7242; -- You dig and you dig, but find nothing.
| gpl-3.0 |
nyczducky/darkstar | scripts/globals/items/heart_chocolate.lua | 12 | 1132 | -----------------------------------------
-- ID: 4497
-- Item: heart_chocolate
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Magic Regen While Healing 4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,4497);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MPHEAL, 4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MPHEAL, 4);
end;
| gpl-3.0 |
wenhulove333/ScutServer | Sample/GameRanking/Client/release/lua/mainapp.lua | 1 | 4607 | ------------------------------------------------------------------
-- mainapp.lua
-- Author : Xin Zhang
-- Version : 1.0.0.0
-- Date : 2011-10-15
-- Description:
------------------------------------------------------------------
local strModuleName = "mainapp"
CCLuaLog("Module ".. strModuleName.. " loaded.")
strModuleName = nil
function PushReceiverCallback(pScutScene, lpExternalData)
end
local function ScutMain()
---[[
------------------------------------------------------------------
-- ¡ý¡ý ³õʼ»¯»·¾³±äÁ¿ ¿ªÊ¼ ¡ý¡ý
------------------------------------------------------------------
local strRootDir = ScutDataLogic.CFileHelper:getPath("lua");
local strTmpPkgPath = package.path;
local strSubDirs =
{
"scenes",
"layers",
"datapool",
"config",
"action",
"lib",
"commupdate",
"payment",
-- ÔÚ´ËÌí¼ÓеÄĿ¼
};
--package.path = string.format("%s/?.lua;%s/lib/?.lua;%s/action/?.lua;%s/common/?.lua;%s/datapool/?.lua;%s/Global/?.lua;%s/layers/?.lua;%s/LuaClass/?.lua;%s/scenes/?.lua;%s/titleMap/?.lua;%s",strRootDir,strRootDir,strRootDir,strRootDir,strRootDir,strRootDir,strRootDir,strRootDir,strRootDir,strRootDir, strTmpPkgPath);
-- Öð¸öÌí¼Ó×ÓÎļþ¼Ð
for key, value in ipairs(strSubDirs) do
local strOld = strTmpPkgPath;
if(1 == key) then
strTmpPkgPath = string.format("%s/%s/?.lua%s", strRootDir, value, strOld);
else
strTmpPkgPath = string.format("%s/%s/?.lua;%s", strRootDir, value, strOld);
end
-- CCLuaLog(value.. " added.");
strOld = nil;
end
package.path = string.format("%s/?.lua;%s", strRootDir, strTmpPkgPath);
strTmpPkgPath = nil;
------------------------------------------------------------------
-- ¡ü¡ü ³õʼ»¯»·¾³±äÁ¿ ½áÊø ¡ü¡ü
------------------------------------------------------------------
-- require±ØÐëÔÚ»·¾³±äÁ¿³õʼ»¯Ö®ºó£¬±ÜÃâÎļþÕÒ²»µ½µÄÇé¿ö·¢Éú
require("lib.lib")
require("lib.ScutScene")
require("lib.FrameManager")
require("datapool.Image")
require("testScene")
g_frame_mgr = FrameManager:new()
g_frame_mgr:init()
function OnHandleData(pScene, nTag, nNetRet, pData)
pScene = tolua.cast(pScene, "CCScene")
g_scenes[pScene]:execCallback(nTag, nNetRet, pData)
end
math.randomseed(os.time());
__NETWORK__=true
------------------------------------------------------------------
-- ¡ý¡ý ÐÒé½âÎöº¯Êý×¢²á ¿ªÊ¼ ¡ý¡ý
------------------------------------------------------------------
function processCommonData(lpScene)
return true;
end
function netDecodeEnd(pScutScene, nTag)
-- ZyLoading.hide(pScutScene, nTag)
end
--×¢²á·þÎñÆ÷push»Øµ÷
CCDirector:sharedDirector():RegisterSocketPushHandler("PushReceiverCallback")
--NDFixSDK.FixCocos2dx:CreateFixCocos2dx():RegisterSocketPushHandler("PushReceiverLayer.PushReceiverCallback")
--ScutScene:registerNetCommonDataFunc("processCommonData");
--ScutScene:registerNetErrorFunc("LoginScene.netConnectError2")
ScutScene:registerNetDecodeEnd("netDecodeEnd");
--NdUpdate.CUpdateEngine:getInstance():registerResPackageUpdateLuaHandleFunc("CommandDataResove.resourceUpdated")
CCDirector:sharedDirector():RegisterBackHandler("MainScene.closeApp")
--×¢²ácrash log»Øµ÷
CCDirector:sharedDirector():RegisterErrorHandler("err_handler")
--
function err_handler(str)
ZyRequestCounter = ZyRequestCounter + 1
ZyWriter:writeString("ActionId",404 );
ZyWriter:writeString("ErrorInfo", str)
ZyExecRequest(ScutScene, nil,isLoading)
-- ScutDataLogic.CDataRequest:Instance():AsyncExecRequest(ScutScene, ZyWriter:generatePostData(), ZyRequestCounter, nil);
-- ScutDataLogic.CNetWriter:resetData()
end
------------------------------------------------------------------
-- ¡ü¡ü ÐÒé½âÎöº¯Êý×¢²á ½áÊø ¡ü¡ü
------------------------------------------------------------------
---]]
end
-- for CCLuaEngine traceback
function __G__TRACKBACK__(msg)
print("----------------------------------------")
print("LUA ERROR: " .. tostring(msg) .. "\n")
print(debug.traceback())
print("----------------------------------------")
end
local function main()
ScutMain()
testScene.init()
end
xpcall(main, __G__TRACKBACK__) | mit |
nyczducky/darkstar | scripts/globals/weaponskills/fast_blade.lua | 25 | 1373 | -----------------------------------
-- Fast Blade
-- Sword weapon skill
-- Skill Level: 5
-- Delivers a two-hit attack. Damage varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Soil Gorget.
-- Aligned with the Soil Belt.
-- Element: None
-- Modifiers: STR:20% ; DEX:20%
-- 100%TP 200%TP 300%TP
-- 1.00 1.50 2.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 2;
params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 2;
params.str_wsc = 0.2; params.dex_wsc = 0.2; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.4; params.dex_wsc = 0.4;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Qufim_Island/npcs/Nightflowers.lua | 14 | 1556 | -----------------------------------
-- Area: Qufim Island
-- NPC: Nightflowers
-- Involved in Quest: Save My Son (Beastmaster Flag #1)
-- @pos -264.775 -3.718 28.767 126
-----------------------------------
package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Qufim_Island/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local currentTime = VanadielHour();
if (currentTime >= 22 or currentTime <= 4) then
if (player:getQuestStatus(JEUNO,SAVE_MY_SON) == QUEST_ACCEPTED and player:getVar("SaveMySon_Event") == 0) then
player:startEvent(0x0000);
else
player:messageSpecial(NOW_THAT_NIGHT_HAS_FALLEN);
end
else
player:messageSpecial(THESE_WITHERED_FLOWERS);
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 == 0x0000) then
player:setVar("SaveMySon_Event",1);
end
end; | gpl-3.0 |
abosalah22/memo | plugins/tagall.lua | 3 | 1486 | --[[
$ :)
-- - ( #ابو_شهوده ) - --
$ :)
-- - ( @abo_shosho98 ) - --
$ :)
--Channel-( @aboaloshbot )--
$ :)
]]--
local function tagall(cb_extra, success, result)
local receiver = cb_extra.receiver
local text = ''
local msgss = 0
for k,v in pairs(result.members) do
if v.username then
msgss = msgss + 1
text = text..msgss.."- @"..v.username.."\n"
end
end
text = text.."\n"..cb_extra.msg_text
send_large_msg(receiver, text)
end
local function tagall2(cb_extra, success, result)
local receiver = cb_extra.receiver
local text = ''
local msgss = 0
for k,v in pairs(result) do
if v.username then
msgss = msgss + 1
text = text..msgss.."- @"..v.username.."\n"
end
end
text = text.."\n"..cb_extra.msg_text
send_large_msg(receiver, text)
end
local function IQ_ABS(msg, matches)
local receiver = get_receiver(msg)
if not is_momod(msg) then
return "لايمكنك استخدام الامر للمدراء فقط !"
end
if matches[1] then
if msg.to.type == 'chat' then
chat_info(receiver, tagall, {receiver = receiver,msg_text = matches[1]})
elseif msg.to.type == 'channel' then
channel_get_users(receiver, tagall2, {receiver = receiver,msg_text = matches[1]})
end
end
return
end
return {
description = "Will tag all ppl with a msg.",
usage = {
"/tagall [msg]."
},
patterns = {
"^[!/]tagall +(.+)$"
},
run = IQ_ABS
}
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Tavnazian_Safehold/npcs/Latteaune.lua | 14 | 1070 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Latteaune
-- Type: Event Scene Replayer
-- @zone 26
-- @pos -16.426 -28.889 109.626
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0064);
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 |
jbeich/Aquaria | files/scripts/entities/rotworm.lua | 6 | 6549 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
-- entity specific
local STATE_GOTOHOLE = 1001
local STATE_HIDE = 1002
local STATE_SHOW = 1003
v.chaseDelay = 0
v.lastHole = 0
v.node = 0
v.holeDelay = 0
v.holeSpd = 0
v.nextHoleDelay = 8
v.segDist = 32
v.dist = 0
function init(me)
setupBasicEntity(me,
"rotworm/head", -- texture
9, -- health
1, -- manaballamount
2, -- exp
1, -- money
32, -- collideRadius (only used if hit entities is on)
STATE_IDLE, -- initState
128, -- sprite width
128, -- sprite height
0, -- particle "explosion" type, maps to particleEffects.txt -1 = none
0, -- 0/1 hit other entities off/on (uses collideRadius)
5000 -- updateCull -1: disabled, default: 4000
)
--entity_flipVertical(me) -- fix the head orientation
entity_initSegments(me,
9, -- num segments
0, -- minDist
v.segDist, -- maxDist
"rotworm/segment", -- body tex
"rotworm/tail", -- tail tex
128, -- width
128, -- height
0.05, -- taper
0 -- reverse segment direction
)
entity_setDeathParticleEffect(me, "TinyGreenExplode")
entity_setEatType(me, EAT_NONE)
end
function update(me, dt)
if entity_isState(me, STATE_HIDE) then
v.dist = v.dist - dt*48
if v.dist < 1 then
v.dist = 1
entity_alpha(me, 0, 0.1)
end
entity_setSegsMaxDist(me, v.dist)
entity_clearVel(me)
entity_updateMovement(me, dt)
end
if not (entity_isState(me, STATE_HIDE) or entity_isState(me, STATE_SHOW)) then
entity_handleShotCollisions(me)
if entity_touchAvatarDamage(me, 64, 1, 400) then
setPoison(1, 16)
end
--[[
if entity_hasTarget(me) then
if entity_isTargetInRange(me, 64) then
entity_hurtTarget(me, 1)
entity_pushTarget(me, 400)
end
end
]]--
end
if v.chaseDelay > 0 then
v.chaseDelay = v.chaseDelay - dt
if v.chaseDelay < 0 then
v.chaseDelay = 0
end
end
if entity_isState(me, STATE_IDLE) then
v.holeDelay = v.holeDelay + dt
if v.holeDelay > v.nextHoleDelay then
v.holeDelay = 0
entity_setState(me, STATE_GOTOHOLE)
end
end
if entity_isState(me, STATE_GOTOHOLE) then
--[[
if not entity_isFollowingPath(me) then
entity_setState(me, STATE_HIDE, 4)
end
x=node_x(v.node)
y=node_y(v.node)
]]--
if v.node ~= 0 then
if entity_isPositionInRange(me, node_x(v.node), node_y(v.node), 64) then
entity_setState(me, STATE_HIDE, 4+math.random(3))
else
v.holeSpd = v.holeSpd + 200*dt
--[[
if v.holeSpd > 1500 then
v.holeSpd = 1500
end
]]--
local x = node_x(v.node)-entity_x(me)
local y = node_y(v.node)-entity_y(me)
x, y = vector_setLength(x, y, v.holeSpd*dt)
entity_addVel(me, x, y)
end
entity_doCollisionAvoidance(me, dt, 5, 1)
entity_updateMovement(me, dt)
--entity_rotateToVel(me, 0.1)
entity_rotateToVel(me, 0)
else
entity_setState(me, STATE_IDLE)
end
--entity_rotateToVec(me, x-entity_x(me), y-entity_y(me), 0.1, -180)
end
if entity_getState(me)==STATE_IDLE then
if not entity_hasTarget(me) then
entity_findTarget(me, 700)
else
--if v.chaseDelay==0 then
if entity_isTargetInRange(me, 1000) then
if entity_getHealth(me) < 6 then
entity_setMaxSpeed(me, 450)
entity_moveTowardsTarget(me, dt, 1500)
else
entity_setMaxSpeed(me, 380)
entity_moveTowardsTarget(me, dt, 1000)
end
else
entity_setMaxSpeed(me, 100)
end
--end
entity_doEntityAvoidance(me, dt, 200, 0.1)
if entity_getHealth(me) < 4 then
entity_doSpellAvoidance(me, dt, 64, 0.5);
end
entity_doCollisionAvoidance(me, dt, 5, 1)
entity_updateMovement(me, dt)
--entity_rotateToVel(me, 0.1)
entity_rotateToVel(me, 0)
--entity_rotate(me, 0)
end
end
end
function enterState(me)
if entity_getState(me)==STATE_IDLE then
v.nextHoleDelay = 6 + math.random(6)
entity_setSegsMaxDist(me, v.segDist)
--entity_flipVertical(me)
elseif entity_isState(me, STATE_GOTOHOLE) then
v.holeSpd = 300
--entity_flipVertical(me)
if chance(50) then
v.node = entity_getNearestNode(getNaija(), "ROTWORM-HOLE")
else
v.node = entity_getNearestNode(me, "ROTWORM-HOLE")
end
if v.node ~= 0 then
v.lastHole = v.node
end
entity_setMaxSpeedLerp(me, 2)
entity_setStateTime(me, 6+math.random(4))
--[[
v.node = entity_getNearestNode(me, "ROTWORM-HOLE")
if v.node ~= 0 then
v.lastHole = v.node
entity_swimToNode(me, v.node, SPEED_NORMAL)
end
]]--
elseif entity_isState(me, STATE_HIDE) then
entity_clearVel(me)
--entity_alpha(me, 0.0, 1.0)
v.dist = v.segDist
entity_setPosition(me, node_x(v.node), node_y(v.node), 0.2)
entity_setDamageTarget(me, DT_AVATAR_ENERGYBLAST, false)
entity_setDamageTarget(me, DT_AVATAR_SHOCK, false)
entity_setDamageTarget(me, DT_AVATAR_PET, false)
entity_setDamageTarget(me, DT_AVATAR_LIZAP, false)
elseif entity_isState(me, STATE_SHOW) then
v.node = entity_getNearestNode(me, "ROTWORM-HOLE", v.lastHole)
if v.node ~= 0 then
entity_setPosition(me, node_x(v.node), node_y(v.node))
entity_warpSegments(me)
end
entity_clearVel(me)
entity_alpha(me, 1, 0.5)
end
end
function exitState(me)
if entity_isState(me, STATE_SHOW) then
entity_setDamageTarget(me, DT_AVATAR_ENERGYBLAST, true)
entity_setDamageTarget(me, DT_AVATAR_SHOCK, true)
entity_setDamageTarget(me, DT_AVATAR_PET, true)
entity_setDamageTarget(me, DT_AVATAR_LIZAP, true)
entity_setState(me, STATE_IDLE)
elseif entity_isState(me, STATE_HIDE) then
entity_setState(me, STATE_SHOW, 0.5)
elseif entity_isState(me, STATE_GOTOHOLE) then
entity_setMaxSpeedLerp(me, 1)
entity_setState(me, STATE_IDLE)
end
end
| gpl-2.0 |
rkoval/dotfiles | nvim/lua/plugins.lua | 1 | 3267 | return require('packer').startup(function()
use('wbthomason/packer.nvim')
use({ 'folke/tokyonight.nvim', commit = '8223c970677e4d88c9b6b6d81bda23daf11062bb' })
--
-- nvim dependencies
--
use('nvim-lua/plenary.nvim')
use('kyazdani42/nvim-web-devicons')
use('tami5/sqlite.lua')
--
-- nvim plugins
--
use({
'nvim-treesitter/nvim-treesitter',
run = 'TSUpdate',
commit = '57f4dbd47b2af3898a6153cd915b106eb72fc980',
})
use('nvim-treesitter/nvim-treesitter-textobjects')
use({
'nvim-telescope/telescope.nvim',
requires = { { 'nvim-lua/plenary.nvim' } },
})
use({
'nvim-telescope/telescope-frecency.nvim',
requires = { { 'tami5/sqlite.lua' } },
})
use({
'nvim-telescope/telescope-fzf-native.nvim',
requires = { { 'nvim-telescope/telescope.nvim' } },
run = 'make',
})
use({
'nvim-telescope/telescope-smart-history.nvim',
run = 'mkdir -p ~/.local/share/nvim/databases',
requires = { { 'nvim-telescope/telescope.nvim', 'tami5/sqlite.lua' } },
})
use('neovim/nvim-lspconfig')
use('williamboman/nvim-lsp-installer')
use('hrsh7th/nvim-cmp')
use('hrsh7th/cmp-nvim-lsp')
use('hrsh7th/cmp-buffer')
use('hrsh7th/cmp-cmdline')
use('hrsh7th/cmp-path')
use({ 'L3MON4D3/LuaSnip', commit = '2f948d4bd1196d4b9a3bc6c6db2537c572e814d5' })
use('saadparwaiz1/cmp_luasnip')
use({
'rkoval/neo-tree.nvim',
branch = 'v2.x',
requires = {
'nvim-lua/plenary.nvim',
'kyazdani42/nvim-web-devicons',
'MunifTanjim/nui.nvim',
},
})
use({
'nvim-lualine/lualine.nvim',
requires = { 'kyazdani42/nvim-web-devicons' },
})
use('lukas-reineke/indent-blankline.nvim')
use('xiyaowong/nvim-cursorword')
use('lewis6991/gitsigns.nvim')
use('mg979/vim-visual-multi')
use('rcarriga/nvim-notify')
use('mfussenegger/nvim-treehopper')
use('windwp/nvim-autopairs')
use('windwp/nvim-ts-autotag')
use('petertriho/nvim-scrollbar')
--
-- evaluating nvim plugins
--
use({
'seblj/nvim-tabline',
requires = { 'kyazdani42/nvim-web-devicons' },
})
use('folke/lua-dev.nvim')
use('phaazon/hop.nvim')
use('ethanholz/nvim-lastplace')
use({
'ray-x/lsp_signature.nvim',
})
--
-- older, but still useful vim plugins
--
use('AndrewRadev/splitjoin.vim')
use('tpope/vim-unimpaired')
use({
'kylechui/nvim-surround',
tag = '*', -- Use for stability; omit for the latest features
})
use('tpope/vim-repeat')
use('tommcdo/vim-exchange')
use('wellle/targets.vim')
use('editorconfig/editorconfig-vim')
use({
'terrortylor/nvim-comment',
config = function()
require('ryankoval.nvim-comment')
end,
})
use({
'kshenoy/vim-signature',
config = function()
require('ryankoval.vim-signature')
end,
})
use('ruanyl/vim-gh-line')
use({
'tpope/vim-fugitive',
config = function()
require('ryankoval.vim-fugitive')
end,
})
use({
'tpope/vim-rhubarb',
requires = { { 'vim-fugitive' } },
})
--
-- probably keep
--
use({
'mattn/emmet-vim',
ft = { 'html', 'css', 'less', 'javascriptreact', 'typescriptreact', 'scss', 'vue', 'markdown' },
config = function()
require('ryankoval.emmet-vim')
end,
})
end)
| mit |
lgeek/koreader | frontend/ui/widget/screensaverwidget.lua | 3 | 2270 | local Device = require("device")
local Geom = require("ui/geometry")
local GestureRange = require("ui/gesturerange")
local FrameContainer = require("ui/widget/container/framecontainer")
local InputContainer = require("ui/widget/container/inputcontainer")
local UIManager = require("ui/uimanager")
local Screen = Device.screen
local ScreenSaverWidget = InputContainer:new{
widget = nil,
background = nil,
}
function ScreenSaverWidget:init()
if Device:hasKeys() then
self.key_events = {
Close = { {"Back"}, doc = "close widget" },
}
end
if Device:isTouchDevice() then
local range = Geom:new{
x = 0, y = 0,
w = Screen:getWidth(),
h = Screen:getHeight(),
}
self.ges_events = {
Tap = { GestureRange:new{ ges = "tap", range = range } },
}
end
self:update()
end
function ScreenSaverWidget:update()
self.height = Screen:getHeight()
self.width = Screen:getWidth()
self.region = Geom:new{
x = 0, y = 0,
w = self.width,
h = self.height,
}
self.main_frame = FrameContainer:new{
radius = 0,
bordersize = 0,
padding = 0,
margin = 0,
background = self.background,
width = self.width,
height = self.height,
self.widget,
}
self[1] = self.main_frame
UIManager:setDirty("all", function()
local update_region = self.main_frame.dimen
return "partial", update_region
end)
end
function ScreenSaverWidget:onShow()
UIManager:setDirty(self, function()
return "full", self.main_frame.dimen
end)
return true
end
function ScreenSaverWidget:onTap(_, ges)
if ges.pos:intersectWith(self.main_frame.dimen) then
self:onClose()
UIManager:setDirty("all", "full")
end
return true
end
function ScreenSaverWidget:onClose()
UIManager:close(self)
UIManager:setDirty("all", "full")
return true
end
function ScreenSaverWidget:onAnyKeyPressed()
self:onClose()
return true
end
function ScreenSaverWidget:onCloseWidget()
UIManager:setDirty(nil, function()
return "partial", self.main_frame.dimen
end)
return true
end
return ScreenSaverWidget
| agpl-3.0 |
abcdefg30/OpenRA | mods/ra/maps/allies-09a/allies09a.lua | 7 | 5887 | --[[
Copyright 2007-2022 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
lstReinforcements =
{
actors = { "mcv" },
entryPath = { AlliedMCVEntry.Location, Unload1.Location },
exitPath = { AlliedMCVEntry.Location }
}
ExtractionHelicopterType = "tran.extraction"
ExtractionPath = { HeliWP01.Location, HeliWP02.Location, HeliWP03.Location }
Dog5PatrolPath = { WP94.Location, WP93.Location }
Dog6PatrolPath = { WP90.Location, WP91.Location, WP92.Location, WP91.Location }
TankGroup10 = { TankGroup101, TankGroup102 }
TankGroup10PatrolPath = { WP81.Location, WP82.Location, WP83.Location, WP84.Location, WP85.Location, WP84.Location, WP83.Location, WP82.Location }
HuntDogsGroup = { Dog701, Dog702, Dog703, Dog704, Dog705, Dog706 }
KosyginType = "gnrl"
KosyginContacted = false
InitialAlliedReinforcements = function()
Trigger.AfterDelay(DateTime.Seconds(1), function()
Media.PlaySpeechNotification(Greece, "ReinforcementsArrived")
Reinforcements.ReinforceWithTransport(Greece, "lst.reinforcement", lstReinforcements.actors, lstReinforcements.entryPath, lstReinforcements.exitPath)
end)
end
RescueFailed = function()
Media.PlaySpeechNotification(Greece, "ObjectiveNotMet")
Greece.MarkFailedObjective(KosyginSurviveObjective)
end
InitialSovietPatrols = function()
Dog5.Patrol(Dog5PatrolPath, true, DateTime.Seconds(60))
Dog6.Patrol(Dog6PatrolPath, true, DateTime.Seconds(90))
for i = 1, 2 do
TankGroup10[i].Patrol(TankGroup10PatrolPath, true, DateTime.Seconds(30))
end
end
CreateKosygin = function()
Greece.MarkCompletedObjective(UseSpyObjective)
Media.PlaySpeechNotification(Greece, "ObjectiveMet")
local kosygin = Actor.Create(KosyginType, true, { Location = KosyginSpawnPoint.Location, Owner = Greece })
Trigger.OnKilled(kosygin, RescueFailed)
ExtractObjective = Greece.AddObjective("Extract Kosygin and\nget him back to your base.")
Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlaySpeechNotification(Greece, "TargetFreed") end)
end
DogsGuardGates = function()
if not Dog707.IsDead then
Dog707.AttackMove(WP89.Location)
end
if not Dog708.IsDead then
Dog708.AttackMove(WP81.Location)
end
if not Dog709.IsDead then
Dog709.AttackMove(WP79.Location)
end
end
InfiltrateForwardCenter = function()
Trigger.OnInfiltrated(USSRFC, function()
if not KosyginContacted then
KosyginContacted = true
CreateKosygin()
DogsGuardGates()
end
end)
Trigger.OnKilledOrCaptured(USSRFC, function()
if not Greece.IsObjectiveCompleted(UseSpyObjective) then
Greece.MarkFailedObjective(UseSpyObjective)
end
end)
end
Tick = function()
USSR.Cash = 5000
if Greece.HasNoRequiredUnits() then
USSR.MarkCompletedObjective(USSRObj)
end
end
TriggerHuntKosygin = function()
Trigger.OnEnteredProximityTrigger(WP79.CenterPosition, WDist.FromCells(4), function(actor, triggerflee)
if actor.Type == KosyginType then
Trigger.RemoveProximityTrigger(triggerflee)
for i = 1, 6 do
if not HuntDogsGroup[i].IsDead then
HuntDogsGroup[i].Attack(actor)
end
end
end
end)
Trigger.OnEnteredProximityTrigger(WP81.CenterPosition, WDist.FromCells(4), function(actor, triggerflee)
if actor.Type == KosyginType then
Trigger.RemoveProximityTrigger(triggerflee)
for i = 1, 6 do
if not HuntDogsGroup[i].IsDead then
HuntDogsGroup[i].Attack(actor)
end
end
end
end)
Trigger.OnEnteredProximityTrigger(WP89.CenterPosition, WDist.FromCells(4), function(actor, triggerflee)
if actor.Type == KosyginType then
Trigger.RemoveProximityTrigger(triggerflee)
for i = 1, 6 do
if not HuntDogsGroup[i].IsDead then
HuntDogsGroup[i].Attack(actor)
end
end
end
end)
end
TriggerRevealUSSRBase = function()
Trigger.OnEnteredProximityTrigger(LowerBaseWP.CenterPosition, WDist.FromCells(10), function(a, id)
if a.Owner == Greece then
Trigger.RemoveProximityTrigger(id)
local cam = Actor.Create("Camera", true, { Owner = Greece, Location = RevealLowerBase.Location })
Trigger.AfterDelay(DateTime.Seconds(15), cam.Destroy)
end
end)
end
TriggerRevealUSSRFC = function()
Trigger.OnEnteredProximityTrigger(UpperBaseWP.CenterPosition, WDist.FromCells(10), function(a, id)
if a.Owner == Greece then
Trigger.RemoveProximityTrigger(id)
local cam = Actor.Create("Camera", true, { Owner = Greece, Location = KosyginSpawnPoint.Location })
Trigger.AfterDelay(DateTime.Seconds(15), cam.Destroy)
end
end)
end
TriggerExtractKosygin = function()
Trigger.OnEnteredProximityTrigger(KosyginExtractPoint.CenterPosition, WDist.FromCells(10), function(actor, triggerflee)
if actor.Type == KosyginType then
Reinforcements.ReinforceWithTransport(Greece, ExtractionHelicopterType, nil, ExtractionPath)
Trigger.RemoveProximityTrigger(triggerflee)
Trigger.AfterDelay(DateTime.Seconds(10), function()
Greece.MarkCompletedObjective(KosyginSurviveObjective)
Greece.MarkCompletedObjective(ExtractObjective)
Media.PlaySpeechNotification(Greece, "ObjectiveMet")
end)
end
end)
end
WorldLoaded = function()
Greece = Player.GetPlayer("Greece")
USSR = Player.GetPlayer("USSR")
Camera.Position = DefaultCameraPosition.CenterPosition
InitObjectives(Greece)
UseSpyObjective = Greece.AddObjective("Infiltrate the Soviet command center and\ncontact Kosygin.")
KosyginSurviveObjective = Greece.AddObjective("Kosygin must survive.")
USSRObj = USSR.AddObjective("Eliminate all Allied forces.")
InitialAlliedReinforcements()
InfiltrateForwardCenter()
InitialSovietPatrols()
TriggerRevealUSSRBase()
TriggerRevealUSSRFC()
TriggerExtractKosygin()
TriggerHuntKosygin()
ActivateAI()
end
| gpl-3.0 |
abosalah22/memo | plugins/lk_emoji.lua | 3 | 2347 | --[[
$ :)
-- - ( #ابو_شهوده ) - --
$ :)
-- - ( @abo_shosho98 ) - --
$ :)
--Channel-( @aboaloshbot )--
$ :)
]]--
local function run(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)]['settings']['emoji'] == 'yes' then
if not is_momod(msg) then
delete_msg(msg.id, ok_cb, true)
end
end
end
return {patterns = {
"😞(.+)",
"😞",
"😐(.+)",
"😐",
"🙁(.+)",
"🙁",
"🌝(.+)",
"🌝",
"🤖(.+)",
"🤖",
"😲(.+)",
"😲",
"💋(.+)",
"💋",
"🙄(.+)",
"🙄",
"🤗(.+)",
"🤗",
"😱(.+)",
"😱",
"🤐(.+)",
"🤐",
"💩(.+)",
"💩",
"🌹(.+)",
"🌹",
"🖐(.+)",
"🖐",
"❤️(.+)",
"❤️",
"💗(.+)",
"💗",
"🤔(.+)",
"🤔",
"😖(.+)",
"😖",
"☹️(.+)",
"☹️",
"😔(.+)",
"😔",
"👾(.+)",
"👾",
"🚀(.+)",
"🚀",
"🌎🌍(.+)",
"🌍",
"🍦",
"😸(.+)",
"😺",
"😯(.+)",
"😯",
"🤒(.+)",
"🤒",
"😷(.+)",
"😷",
"🙀(.+)",
"🙀",
"🎪(.+)",
"🌚",
"🌚(.+)",
"😂",
"😂(.+)",
"😳",
"😳(.+)",
"😛",
"😛(.+)",
"😢",
"😢(.+)",
"😓",
"😓(.+)",
"😾",
"😾(.+)",
"👊🏻",
"👊🏻(.+)",
"✊🏻",
"✊🏻(.+)",
"👿",
"👿(.+)",
"👅",
"👅(.+)",
"🖕🏿",
"🖕🏿(.+)",
"😲",
"😲(.+)",
"👹",
"👹(.+)",
"😴",
"😴(.+)",
"☂",
"☂(.+)",
"🗣",
"🗣(.+)",
"⛄️",
"⛄️(.+)",
"😻",
"😻(.+)",
"😀(.+)",
"😀",
"😬(.+)",
"😬",
"😁(.+)",
"😁",
"😂(.+)",
"😂",
"😃(.+)",
"😃",
"😄(.+)",
"😄",
"😅",
"😆(.+)",
"😆",
"😇(.+)",
"😇",
"😉(.+)",
"😉",
"😊(.+)",
"😊",
"🙂(.+)",
"🙂",
"🙃(.+)",
"🙃",
"☺️(.+)",
"☺️",
"😋(.+)",
"😋",
"😌",
"😍(.+)",
"😍",
"😘(.+)",
"😘",
"😗(.+)",
"😗",
"😙(.+)",
"😙",
"😚(.+)",
"😚",
"😜(.+)",
"😜",
"😝(.+)",
"😝",
"🤑(.+)",
"🤑",
"🤓(.+)",
"🤓",
"😎(.+)",
"😎",
"🤗(.+)",
"🤗",
"😏(.+)",
"😏",
"😶(.+)",
"😶",
"😺(.+)",
"😺",
"😹",
"😼",
"😿",
"🌝",
"🌚",
"🌶",
"🖐🏼",
},run = run}
| gpl-2.0 |
lgeek/koreader | spec/unit/touch_probe_spec.lua | 13 | 2044 | describe("touch probe module", function()
local x, y
setup(function()
require("commonrequire")
end)
it("should probe properly for kobo touch", function()
local Device = require("device")
local TouchProbe = require("tools/kobo_touch_probe"):new{}
local need_to_switch_xy
TouchProbe.saveSwitchXYSetting = function(_, new_need_to_switch_xy)
need_to_switch_xy = new_need_to_switch_xy
end
-- for kobo touch, we have mirror_x, then switch_xy
-- tap lower right corner
x, y = Device.screen:getWidth()-40, Device.screen:getHeight()-40
need_to_switch_xy = nil
TouchProbe:onTapProbe(nil, {
pos = {
x = y,
y = Device.screen:getWidth()-x,
}
})
assert.is.same(TouchProbe.curr_probe_step, 1)
assert.truthy(need_to_switch_xy)
-- now only test mirror_x
-- tap lower right corner
x, y = Device.screen:getWidth()-40, Device.screen:getHeight()-40
need_to_switch_xy = nil
TouchProbe:onTapProbe(nil, {
pos = {
x = Device.screen:getWidth()-x,
y = y,
}
})
assert.is.same(TouchProbe.curr_probe_step, 1)
assert.falsy(need_to_switch_xy)
-- now only test switch_xy
-- tap lower right corner
x, y = Device.screen:getWidth()-40, Device.screen:getHeight()-40
need_to_switch_xy = nil
TouchProbe:onTapProbe(nil, {
pos = {
x = y,
y = x,
}
})
assert.is.same(TouchProbe.curr_probe_step, 2)
assert.falsy(need_to_switch_xy)
-- tap upper right corner
x, y = Device.screen:getWidth()-40, 40
TouchProbe:onTapProbe(nil, {
pos = {
x = y,
y = x,
}
})
assert.is.same(TouchProbe.curr_probe_step, 2)
assert.truthy(need_to_switch_xy)
end)
end)
| agpl-3.0 |
nyczducky/darkstar | scripts/zones/The_Garden_of_RuHmet/npcs/qm3.lua | 14 | 1715 | -----------------------------------
-- Area: The_Garden_of_RuHmet
-- NPC: ??? (Jailer of Faith Spawn)
-- Allows players to spawn the Jailer of Faith by trading 1 High-Quality Euvhi Organ to a ???.
-- @pos -260 0 -645
-----------------------------------
package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Garden_of_RuHmet/TextIDs");
require("scripts/zones/The_Garden_of_RuHmet/MobIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
--Trade 1 High-Quality Euvhi Organ
if (GetMobAction(Jailer_of_Faith) == 0 and trade:hasItemQty(1899,1) and trade:getItemCount() == 1) then
local qm3 = GetNPCByID(Jailer_of_Faith_QM);
player:tradeComplete();
-- Hide the ???
qm3:setStatus(STATUS_DISAPPEAR);
-- Change MobSpawn to ???'s pos.
GetMobByID(Jailer_of_Faith):setSpawn(qm3:getXPos(),qm3:getYPos(),qm3:getZPos());
-- Spawn Jailer of Faith
SpawnMob(Jailer_of_Faith):updateClaim(player);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
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);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/globals/abilities/pets/tail_whip.lua | 30 | 1284 | ---------------------------------------------------
-- Tail Whip M=5
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
require("scripts/globals/summon");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onPetAbility(target, pet, skill)
local numhits = 1;
local accmod = 1;
local dmgmod = 5;
local totaldamage = 0;
local damage = AvatarPhysicalMove(pet,target,skill,numhits,accmod,dmgmod,0,TP_NO_EFFECT,1,2,3);
totaldamage = AvatarFinalAdjustments(damage.dmg,pet,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_PIERCE,numhits);
local duration = 120;
local resm = applyPlayerResistance(pet,-1,target,pet:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL, 5);
if resm < 0.25 then
resm = 0;
end
duration = duration * resm
if (duration > 0 and AvatarPhysicalHit(skill, totaldamage) and target:hasStatusEffect(EFFECT_WEIGHT) == false) then
target:addStatusEffect(EFFECT_WEIGHT, 50, 0, duration);
end
target:delHP(totaldamage);
target:updateEnmityFromDamage(pet,totaldamage);
return totaldamage;
end | gpl-3.0 |
nyczducky/darkstar | scripts/globals/items/danceshroom.lua | 12 | 1190 | -----------------------------------------
-- ID: 4375
-- Item: danceshroom
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Strength -5
-- Mind 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,300,4375);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, -5);
target:addMod(MOD_MND, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, -5);
target:delMod(MOD_MND, 3);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/South_Gustaberg/npcs/Cavernous_Maw.lua | 58 | 1907 | -----------------------------------
-- Area: South Gustaberg
-- NPC: Cavernous Maw
-- @pos 340 -0.5 -680
-- Teleports Players to Abyssea - Altepa
-----------------------------------
package.loaded["scripts/zones/South_Gustaberg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/abyssea");
require("scripts/zones/South_Gustaberg/TextIDs");
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (ENABLE_ABYSSEA == 1 and player:getMainLvl() >= 30) then
local HasStone = getTravStonesTotal(player);
if (HasStone >= 1 and player:getQuestStatus(ABYSSEA, DAWN_OF_DEATH) == QUEST_ACCEPTED
and player:getQuestStatus(ABYSSEA, A_BEAKED_BLUSTERER) == QUEST_AVAILABLE) then
player:startEvent(0);
else
player:startEvent(914,0,1); -- No param = no entry.
end
else
player:messageSpecial(NOTHING_HAPPENS);
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 == 0) then
player:addQuest(ABYSSEA, A_BEAKED_BLUSTERER);
elseif (csid == 1) then
-- Killed Bennu
elseif (csid == 914 and option == 1) then
player:setPos(432, 0, 321, 125, 218);
end
end; | gpl-3.0 |
matinbot/webamooz | plugins/Boobs.lua | 150 | 1613 | do
-- Recursive function
local function getRandomButts(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.obutts.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt <= 3 then
print('Cannot get that butts, trying another one...')
return getRandomButts(attempt)
end
return 'http://media.obutts.ru/' .. data.preview
end
local function getRandomBoobs(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.oboobs.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt < 10 then
print('Cannot get that boobs, trying another one...')
return getRandomBoobs(attempt)
end
return 'http://media.oboobs.ru/' .. data.preview
end
local function run(msg, matches)
local url = nil
if matches[1] == "!boobs" then
url = getRandomBoobs()
end
if matches[1] == "!butts" then
url = getRandomButts()
end
if url ~= nil then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, url)
else
return 'Error getting boobs/butts for you, please try again later.'
end
end
return {
description = "Gets a random boobs or butts pic",
usage = {
"!boobs: Get a boobs NSFW image. ًں”",
"!butts: Get a butts NSFW image. ًں”"
},
patterns = {
"^!boobs$",
"^!butts$"
},
run = run
}
end
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Oldton_Movalpolos/npcs/Tarnotik.lua | 14 | 1772 | -----------------------------------
-- Area: Oldton Movalpolos
-- NPC: Tarnotik
-- Type: Standard NPC
-- @pos 160.896 10.999 -55.659 11
-----------------------------------
package.loaded["scripts/zones/Oldton_Movalpolos/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Oldton_Movalpolos/TextIDs");
require("scripts/globals/missions");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getCurrentMission(COP) >= THREE_PATHS) then
if (trade:getItemCount() == 1 and trade:hasItemQty(1725,1)) then
player:tradeComplete();
player:startEvent(0x0020);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Louverance_s_Path") == 7 ) then
player:startEvent(0x0022);
else
if (math.random()<0.5) then -- this isnt retail at all.
player:startEvent(0x001e);
else
player:startEvent(0x001f);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0020) then
player:setPos(-116,-119,-620,253,13);
elseif (csid == 0x0022) then
player:setVar("COP_Louverance_s_Path",8);
end
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/globals/items/serving_of_leadafry.lua | 12 | 1190 | -----------------------------------------
-- ID: 5161
-- Item: serving_of_leadafry
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Agility 5
-- Vitality 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,14400,5161);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 5);
target:addMod(MOD_VIT, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 5);
target:delMod(MOD_VIT, 2);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Windurst_Woods/npcs/Mushuhi-Metahi.lua | 59 | 1052 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Mushuhi-Metahi
-- Type: Weather Reporter
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x82718,0,0,0,0,0,0,0,VanadielTime());
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
nyczducky/darkstar | scripts/zones/Sealions_Den/bcnms/warriors_path.lua | 26 | 2441 | -----------------------------------
-- Area: Sealion's Den
-- Name: warriors_path
-- bcnmID : 993
-----------------------------------
package.loaded["scripts/zones/Sealions_Den/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Sealions_Den/TextIDs");
-----------------------------------
--Tarutaru
--Tenzen group 860 3875
--Makki-Chebukki (RNG) , 16908311 16908315 16908319 group 853 2492
--Kukki-Chebukki (BLM) 16908312 16908316 16908320 group 852 2293
--Cherukiki (WHM). 16908313 16908317 16908321 group 851 710
--instance 1 @pos -780 -103 -90
--instance 2 @pos -140 -23 -450
--instance 3 @pos 500 56 -810
-- 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)
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
player:addExp(1000);
if (player:getCurrentMission(COP) == THE_WARRIOR_S_PATH) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0);
player:setVar("PromathiaStatus",0);
player:completeMission(COP,THE_WARRIOR_S_PATH);
player:addMission(COP,GARDEN_OF_ANTIQUITY);
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)
-- print("bc finish csid "..csid.." and option "..option);
if (csid == 0x7d01) then
player:setPos(-25,-1 ,-620 ,208 ,33);-- al'taieu
player:addTitle(THE_CHEBUKKIS_WORST_NIGHTMARE);
end
end; | gpl-3.0 |
AinaSG/Crunchy | roach.lua | 1 | 4153 | roach = {}
roach.width = 84
roach.offset = 41
roach.height = 108
function roach.loadAssets(snowman)
if snowman then
roach.img = love.graphics.newImage("assets/snowmant.png")
else
roach.img = love.graphics.newImage("assets/blushed3.png")
end
roach.isSnowMan = snowman or false
roach.sprites = {}
roach.sprites[1] = love.graphics.newQuad(0, 0, roach.width, roach.height, roach.img:getDimensions())
roach.sprites[2] = love.graphics.newQuad(roach.width, 0, roach.width, roach.height, roach.img:getDimensions())
roach.sprites[3] = love.graphics.newQuad(roach.width*2, 0, roach.width, roach.height, roach.img:getDimensions())
roach.sprites[4] = love.graphics.newQuad(roach.width*3, 0, roach.width, roach.height, roach.img:getDimensions())
end
function roach.init()
roach.x = 0
roach.y = groundHeight - roach.height
roach.xSpeed = 0
roach.ySpeed = 0
roach.runSpeed = 5000
roach.jumpSpeed = -800
roach.friction = 10
roach.canJump = false
roach.state = "alive"
roach.soundIsPlaying = false;
roach.health = 100
roach.actualsprite = 1
roach.direction = 1
end
function roach.die(fromHand)
if fromHand then
system:setPosition( hand.x + hand.fingerOffset, hand.y + hand.height )
system:start()
system2:setPosition( hand.x + hand.fingerOffset, hand.y + hand.height )
system2:start()
if roach.state ~= "dead" then TEsound.play("assets/splat.wav", "sfx") end
end
if roach.soundIsPlaying then roach.pauseSound() end
roach.state = "dead"
roach.actualsprite = 4
end
function roach.jump()
if roach.canJump then
roach.ySpeed = roach.jumpSpeed
roach.canJump = false
end
end
function roach.moveRight(dt)
roach.xSpeed = roach.xSpeed + (roach.runSpeed * dt)
roach.xSpeed = math.min(roach.xSpeed, roach.runSpeed)
roach.state = "moveRight"
roach.direction = -1
end
function roach.moveLeft(dt)
roach.xSpeed = roach.xSpeed - (roach.runSpeed * dt)
roach.xSpeed = math.max(roach.xSpeed, -roach.runSpeed)
roach.state = "moveLeft"
roach.direction = 1
end
function roach.stop()
roach.xSpeed = 0
end
function roach.hitFloor(maxY)
roach.y = maxY - roach.height
roach.ySpeed = 0
roach.canJump = true
end
function roach.pauseSound()
TEsound.pause("roachsound")
roach.soundIsPlaying = false
end
function roach.draw()
if (roach.direction == 1 ) then
love.graphics.draw(roach.img, roach.sprites[roach.actualsprite], roach.x, roach.y, 0, 1, 1)
else
love.graphics.draw(roach.img, roach.sprites[roach.actualsprite], roach.x, roach.y, 0, -1, 1, roach.width)
end
end
function roach.update(dt)
if (gas.checkRoach()) then
roach.health = roach.health - dt*100/2
end
--Posició
roach.x = roach.x + (roach.xSpeed * dt)
roach.y = roach.y + (roach.ySpeed * dt)
--Gravetat
roach.ySpeed = roach.ySpeed + (gravity * dt)
roach.xSpeed = roach.xSpeed * (1 - math.min(dt * roach.friction, 1))
--Update estat
if not (roach.canJump) then
if roach.ySpeed < 0 then
roach.state = "jump"
elseif roach.ySpeed > 0 then
roach.state = "fall"
end
else
if roach.xSpeed > 2 then
roach.state = "moveRight"
elseif roach.xSpeed < -2 then
roach.state = "moveLeft"
else
roach.xSpeed = 0
roach.state = "stand"
end
end
if roach.x > scEnd - roach.width then roach.x = scEnd - roach.width end
if roach.x < scStart then roach.x = scStart end
if roach.y > groundHeight - roach.height then
roach.hitFloor(460)
end
if (roach.state == "moveRight" or roach.state == "moveLeft") then
TEsound.resume("roachsound")
roach.soundIsPlaying = true
else
roach.pauseSound()
end
if (keys["a"] or keys["d"])then
local temp_frame = (love.timer.getTime()*3000)%480
if temp_frame > 320 then
roach.actualsprite = 2
elseif temp_frame > 240 then
roach.actualsprite = 1
elseif temp_frame > 120 then
roach.actualsprite = 3
else -- temp_frame <= 120
roach.actualsprite = 1
end
else
if roach.state == "jump" then
roach.actualsprite = 3
else
roach.actualsprite = 1
end
end
if keys["d"] then
roach.moveRight(dt)
end
if keys["a"] then
roach.moveLeft(dt)
end
if keys["w"] then
roach.jump()
end
end
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Windurst_Waters/npcs/Koko_Lihzeh.lua | 14 | 1858 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Koko Lihzeh
-- Involved in Quest: Making the Grade, Riding on the Clouds
-- @zone 238
-- @pos 135 -6 162
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_4") == 1) then
if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_4",0);
player:tradeComplete();
player:addKeyItem(SPIRITED_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SPIRITED_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(WINDURST,MAKING_THE_GRADE) == QUEST_ACCEPTED) then
player:startEvent(0x01c3); -- During Making the GRADE
else
player:startEvent(0x01ac); -- Standard conversation
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
nyczducky/darkstar | scripts/globals/spells/frost.lua | 9 | 1850 | -----------------------------------------
-- Spell: Frost
-- Deals ice damage that lowers an enemy's agility and gradually reduces its HP.
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
if (target:getStatusEffect(EFFECT_BURN) ~= nil) then
spell:setMsg(75); -- no effect
else
local dINT = caster:getStat(MOD_INT)-target:getStat(MOD_INT);
local resist = applyResistance(caster,spell,target,dINT,36,0);
if (resist <= 0.125) then
spell:setMsg(85);
else
if (target:getStatusEffect(EFFECT_CHOKE) ~= nil) then
target:delStatusEffect(EFFECT_CHOKE);
end;
local sINT = caster:getStat(MOD_INT);
local DOT = getElementalDebuffDOT(sINT);
local effect = target:getStatusEffect(EFFECT_FROST);
local noeffect = false;
if (effect ~= nil) then
if (effect:getPower() >= DOT) then
noeffect = true;
end;
end;
if (noeffect) then
spell:setMsg(75); -- no effect
else
if (effect ~= nil) then
target:delStatusEffect(EFFECT_FROST);
end;
spell:setMsg(237);
local duration = math.floor(ELEMENTAL_DEBUFF_DURATION * resist);
target:addStatusEffect(EFFECT_FROST,DOT, 3, ELEMENTAL_DEBUFF_DURATION,FLAG_ERASABLE);
end;
end;
end;
return EFFECT_FROST;
end; | gpl-3.0 |
nyczducky/darkstar | scripts/zones/Quicksand_Caves/mobs/Centurio_IV-VII.lua | 11 | 1351 | -----------------------------------
-- Area: Quicksand Caves
-- MOB: Centurio IV-VII
-- Pops in Bastok mission 8-1 "The Chains that Bind Us"
-----------------------------------
package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Quicksand_Caves/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobDisengage Action
-----------------------------------
function onMobDisengage(mob)
local self = mob:getID();
DespawnMob(self, 120);
end;
-----------------------------------
-- onMobDeath Action
-----------------------------------
function onMobDeath(mob, player, isKiller)
if (player:getCurrentMission(BASTOK) == THE_CHAINS_THAT_BIND_US and player:getVar("MissionStatus") == 1) then
SetServerVariable("Bastok8-1LastClear", os.time());
end
end;
-----------------------------------
-- onMobDespawn Action
-----------------------------------
function onMobDespawn(mob)
local mobsup = GetServerVariable("BastokFight8_1");
SetServerVariable("BastokFight8_1",mobsup - 1);
if (GetServerVariable("BastokFight8_1") == 0) then
local npc = GetNPCByID(17629738); -- qm6
npc:setStatus(0); -- Reappear
end
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Southern_San_dOria/npcs/Raminel.lua | 14 | 5118 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Raminel
-- Involved in Quests: Riding on the Clouds
-- @pos -56 2 -21 230
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Southern_San_dOria/TextIDs");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/pathfind");
local path =
{
-138.436340, -2.000000, 16.227097,
-137.395432, -2.000000, 15.831898,
-136.317108, -2.000000, 15.728185,
-134.824036, -2.000000, 15.816396,
-108.897049, -2.000000, 16.508110,
-107.823288, -2.000000, 16.354126,
-106.804962, -2.000000, 15.973084,
-105.844963, -2.000000, 15.462379,
-104.922585, -2.000000, 14.885456,
-104.020050, -2.000000, 14.277813,
-103.138374, -2.000000, 13.640303,
-101.501289, -2.000000, 12.422975,
-77.636841, 2.000000, -5.771687,
-59.468536, 2.000000, -19.632719,
-58.541172, 2.000000, -20.197826,
-57.519985, 2.000000, -20.570829,
-56.474659, 2.000000, -20.872238,
-55.417450, 2.000000, -21.129019,
-54.351425, 2.000000, -21.365578,
-53.286743, 2.000000, -21.589529,
-23.770412, 2.000000, -27.508755,
-13.354427, 1.700000, -29.593290,
-14.421194, 1.700000, -29.379389, -- auction house
-43.848141, 2.000000, -23.492155,
-56.516224, 2.000000, -20.955723,
-57.555450, 2.000000, -20.638817,
-58.514832, 2.000000, -20.127840,
-59.426712, 2.000000, -19.534536,
-60.322998, 2.000000, -18.917839,
-61.203823, 2.000000, -18.279247,
-62.510002, 2.000000, -17.300892,
-86.411278, 2.000000, 0.921999,
-105.625214, -2.000000, 15.580724,
-106.582047, -2.000000, 16.089426,
-107.647263, -2.000000, 16.304668,
-108.732132, -2.000000, 16.383970,
-109.819397, -2.000000, 16.423687,
-110.907364, -2.000000, 16.429226,
-111.995232, -2.000000, 16.411282,
-140.205811, -2.000000, 15.668728, -- package Lusiane
-139.296539, -2.000000, 16.786556
};
function onSpawn(npc)
npc:initNpcAi();
npc:setPos(pathfind.first(path));
onPath(npc);
-- test fromStart
local start = pathfind.fromStart(path, 2);
local startFirst = pathfind.get(path, 3);
if (start[1] ~= startFirst[1] or start[2] ~= startFirst[2] or start[3] ~= startFirst[3]) then
printf("[Error] start path is not right %f %f %f actually = %f %f %f", startFirst[1], startFirst[2], startFirst[3], start[1], start[2], start[3]);
end
-- test fromEnd
-- local endPt = pathfind.fromEnd(path, 2);
-- local endFirst = pathfind.get(path, 37);
-- if (endPt[1] ~= endFirst[1] or endPt[2] ~= endFirst[2] or endPt[3] ~= endFirst[3]) then
-- printf("[Error] endPt path is not right %f %f %f actually = %f %f %f", endFirst[1], endFirst[2], endFirst[3], endPt[1], endPt[2], endPt[3]);
-- end
end;
function onPath(npc)
if (npc:atPoint(pathfind.get(path, 23))) then
local arp = GetNPCByID(17719409);
npc:lookAt(arp:getPos());
npc:wait();
elseif (npc:atPoint(pathfind.get(path, -1))) then
local lus = GetNPCByID(17719350);
-- give package to Lusiane
lus:showText(npc, RAMINEL_DELIVERY);
npc:showText(lus, LUSIANE_THANK);
-- wait default duration 4 seconds
-- then continue path
npc:wait();
elseif (npc:atPoint(pathfind.last(path))) then
local lus = GetNPCByID(17719350);
-- when I walk away stop looking at me
lus:clearTargID();
end
-- go back and forth the set path
pathfind.patrol(npc, path);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart Flyer
player:messageSpecial(FLYER_REFUSED);
end
end
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_1") == 1) then
if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_1",0);
player:tradeComplete();
player:addKeyItem(SCOWLING_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SCOWLING_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0266);
npc:wait(-1);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,npc)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
npc:wait(0);
end;
| gpl-3.0 |
micdah/LrControl | Docs/Lightroom SDK 6.0/Sample Plugins/flickr.lrdevplugin/FlickrUser.lua | 1 | 9479 | --[[----------------------------------------------------------------------------
FlickrUser.lua
Flickr user account management
--------------------------------------------------------------------------------
ADOBE SYSTEMS INCORPORATED
Copyright 2007 Adobe Systems Incorporated
All Rights Reserved.
NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
with the terms of the Adobe license agreement accompanying it. If you have received
this file from a source other than Adobe, then your use, modification, or distribution
of it requires the prior written permission of Adobe.
------------------------------------------------------------------------------]]
-- Lightroom SDK
local LrDialogs = import 'LrDialogs'
local LrFunctionContext = import 'LrFunctionContext'
local LrTasks = import 'LrTasks'
local logger = import 'LrLogger'( 'FlickrAPI' )
require 'FlickrAPI'
--============================================================================--
FlickrUser = {}
--------------------------------------------------------------------------------
local function storedCredentialsAreValid( propertyTable )
return propertyTable.username and string.len( propertyTable.username ) > 0
and propertyTable.nsid
and propertyTable.auth_token
end
--------------------------------------------------------------------------------
local function notLoggedIn( propertyTable )
propertyTable.token = nil
propertyTable.nsid = nil
propertyTable.username = nil
propertyTable.fullname = ''
propertyTable.auth_token = nil
propertyTable.accountStatus = LOC "$$$/Flickr/AccountStatus/NotLoggedIn=Not logged in"
propertyTable.loginButtonTitle = LOC "$$$/Flickr/LoginButton/NotLoggedIn=Log In"
propertyTable.loginButtonEnabled = true
propertyTable.validAccount = false
end
--------------------------------------------------------------------------------
local doingLogin = false
function FlickrUser.login( propertyTable )
if doingLogin then return end
doingLogin = true
LrFunctionContext.postAsyncTaskWithContext( 'Flickr login',
function( context )
-- Clear any existing login info, but only if creating new account.
-- If we're here on an existing connection, that's because the login
-- token was rejected. We need to retain existing account info so we
-- can cross-check it.
if not propertyTable.LR_editingExistingPublishConnection then
notLoggedIn( propertyTable )
end
propertyTable.accountStatus = LOC "$$$/Flickr/AccountStatus/LoggingIn=Logging in..."
propertyTable.loginButtonEnabled = false
LrDialogs.attachErrorDialogToFunctionContext( context )
-- Make sure login is valid when done, or is marked as invalid.
context:addCleanupHandler( function()
doingLogin = false
if not storedCredentialsAreValid( propertyTable ) then
notLoggedIn( propertyTable )
end
-- Hrm. New API doesn't make it easy to show what operation failed.
-- LrDialogs.message( LOC "$$$/Flickr/LoginFailed=Failed to log in." )
end )
-- Make sure we have an API key.
FlickrAPI.getApiKeyAndSecret()
-- Show request for authentication dialog.
local authRequestDialogResult = LrDialogs.confirm(
LOC "$$$/Flickr/AuthRequestDialog/Message=Lightroom needs your permission to upload images to Flickr.",
LOC "$$$/Flickr/AuthRequestDialog/HelpText=If you click Authorize, you will be taken to a web page in your web browser where you can log in. When you're finished, return to Lightroom to complete the authorization.",
LOC "$$$/Flickr/AuthRequestDialog/AuthButtonText=Authorize",
LOC "$$$/LrDialogs/Cancel=Cancel" )
if authRequestDialogResult == 'cancel' then
return
end
-- Request the frob that we need for authentication.
propertyTable.accountStatus = LOC "$$$/Flickr/AccountStatus/WaitingForFlickr=Waiting for response from flickr.com..."
require 'FlickrAPI'
local frob = FlickrAPI.openAuthUrl()
local waitForAuthDialogResult = LrDialogs.confirm(
LOC "$$$/Flickr/WaitForAuthDialog/Message=Return to this window once you've authorized Lightroom on flickr.com.",
LOC "$$$/Flickr/WaitForAuthDialog/HelpText=Once you've granted permission for Lightroom (in your web browser), click the Done button below.",
LOC "$$$/Flickr/WaitForAuthDialog/DoneButtonText=Done",
LOC "$$$/LrDialogs/Cancel=Cancel" )
if waitForAuthDialogResult == 'cancel' then
return
end
-- User has OK'd authentication. Get the user info.
propertyTable.accountStatus = LOC "$$$/Flickr/AccountStatus/WaitingForFlickr=Waiting for response from flickr.com..."
local data = FlickrAPI.callRestMethod( propertyTable, { method = 'flickr.auth.getToken', frob = frob, suppressError = true, skipAuthToken = true } )
local auth = data.auth
if not auth then
return
end
-- If editing existing connection, make sure user didn't try to change user ID on us.
if propertyTable.LR_editingExistingPublishConnection then
if auth.user and propertyTable.nsid ~= auth.user.nsid then
LrDialogs.message( LOC "$$$/Flickr/CantChangeUserID=You can not change Flickr accounts on an existing publish connection. Please log in again with the account you used when you first created this connection." )
return
end
end
-- Now we can read the Flickr user credentials. Save off to prefs.
propertyTable.nsid = auth.user.nsid
propertyTable.username = auth.user.username
propertyTable.fullname = auth.user.fullname
propertyTable.auth_token = auth.token._value
FlickrUser.updateUserStatusTextBindings( propertyTable )
end )
end
--------------------------------------------------------------------------------
local function getDisplayUserNameFromProperties( propertyTable )
local displayUserName = propertyTable.fullname
if ( not displayUserName or #displayUserName == 0 )
or displayUserName == propertyTable.username
then
displayUserName = propertyTable.username
else
displayUserName = LOC( "$$$/Flickr/AccountStatus/UserNameAndLoginName=^1 (^2)",
propertyTable.fullname,
propertyTable.username )
end
return displayUserName
end
--------------------------------------------------------------------------------
function FlickrUser.verifyLogin( propertyTable )
-- Observe changes to prefs and update status message accordingly.
local function updateStatus()
logger:trace( "verifyLogin: updateStatus() was triggered." )
LrTasks.startAsyncTask( function()
logger:trace( "verifyLogin: updateStatus() is executing." )
if storedCredentialsAreValid( propertyTable ) then
local displayUserName = getDisplayUserNameFromProperties( propertyTable )
propertyTable.accountStatus = LOC( "$$$/Flickr/AccountStatus/LoggedIn=Logged in as ^1", displayUserName )
if propertyTable.LR_editingExistingPublishConnection then
propertyTable.loginButtonTitle = LOC "$$$/Flickr/LoginButton/LogInAgain=Log In"
propertyTable.loginButtonEnabled = false
propertyTable.validAccount = true
else
propertyTable.loginButtonTitle = LOC "$$$/Flickr/LoginButton/LoggedIn=Switch User?"
propertyTable.loginButtonEnabled = true
propertyTable.validAccount = true
end
else
notLoggedIn( propertyTable )
end
FlickrUser.updateUserStatusTextBindings( propertyTable )
end )
end
propertyTable:addObserver( 'auth_token', updateStatus )
updateStatus()
end
--------------------------------------------------------------------------------
function FlickrUser.updateUserStatusTextBindings( settings )
local nsid = settings.nsid
if nsid and string.len( nsid ) > 0 then
LrFunctionContext.postAsyncTaskWithContext( 'Flickr account status check',
function( context )
context:addFailureHandler( function()
-- Login attempt failed. Offer chance to re-establish connection.
if settings.LR_editingExistingPublishConnection then
local displayUserName = getDisplayUserNameFromProperties( settings )
settings.accountStatus = LOC( "$$$/Flickr/AccountStatus/LogInFailed=Log in failed, was logged in as ^1", displayUserName )
settings.loginButtonTitle = LOC "$$$/Flickr/LoginButton/LogInAgain=Log In"
settings.loginButtonEnabled = true
settings.validAccount = false
settings.isUserPro = false
settings.accountTypeMessage = LOC "$$$/Flickr/AccountStatus/LoginFailed/Message=Could not verify this Flickr account. Please log in again. Please note that you can not change the Flickr account for an existing publish connection. You must log in to the same account."
end
end )
local userinfo = FlickrAPI.getUserInfo( settings, { userId = nsid } )
if userinfo and ( not userinfo.ispro ) then
settings.accountTypeMessage = LOC( "$$$/Flickr/NonProAccountLimitations=This account is not a Flickr Pro account, and is subject to limitations. Once a photo has been uploaded, it will not be automatically updated if it changes. In addition, there is an upload bandwidth limit each month." )
settings.isUserPro = false
else
settings.accountTypeMessage = LOC( "$$$/Flickr/ProAccountDescription=This Flickr Pro account can utilize collections, modified photos will be automatically be re-published, and there is no monthly bandwidth limit." )
settings.isUserPro = true
end
end )
else
settings.accountTypeMessage = LOC( "$$$/Flickr/SignIn=Sign in with your Flickr account." )
settings.isUserPro = false
end
end
| gpl-3.0 |
AquariaOSE/Aquaria | files/scripts/entities/lightcrystalcommon.lua | 6 | 2121 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
-- LIGHT CRYSTAL
v.charge = 0
v.delay = 1
v.glow = 0
function init(me)
setupEntity(me)
entity_setDamageTarget(me, DT_AVATAR_ENERGYBLAST, false)
entity_setProperty(me, EP_MOVABLE, true)
entity_setCollideRadius(me, 32)
entity_setWeight(me, 300)
entity_setMaxSpeed(me, 450)
entity_setEntityType(me, ET_NEUTRAL)
entity_initSkeletal(me, "LightCrystal")
entity_animate(me, "idle", -1)
v.bone_glow = entity_getBoneByName(me, "Glow")
bone_alpha(v.bone_glow, 0)
v.glow = createQuad("Naija/LightFormGlow", 13)
quad_scale(v.glow, 6, 6)
quad_alpha(v.glow, 0)
end
function update(me, dt)
entity_updateMovement(me, dt)
entity_updateCurrents(me)
quad_setPosition(v.glow, entity_getPosition(me))
end
function enterState(me)
if entity_isState(me, STATE_CHARGED) then
quad_alpha(v.glow, 1)
bone_alpha(v.bone_glow, 1)
elseif entity_isState(me, STATE_CHARGE) then
quad_alpha(v.glow, 1, 1.5)
bone_alpha(v.bone_glow, 1, 1.5)
playSfx("SunForm")
elseif entity_isState(me, STATE_DEAD) then
quad_delete(v.glow)
end
end
function exitState(me)
end
function hitSurface(me)
--entity_sound(me, "rock-hit")
end
function damage(me, attacker, bone, damageType, dmg)
return false
end
function activate(me)
end
| gpl-2.0 |
francot514/CardGamePRO-Simulator | data/cards/c1041.lua | 1 | 1134 | --Chariot Archer
function c1041.initial_effect(c)
--destroy trap
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DESTROY)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_ATTACK_ANNOUNCE)
e1:SetCondition(c1041.ctlcon)
e1:SetTarget(c1041.target)
e1:SetOperation(c1041.operation)
c:RegisterEffect(e1)
end
function c1041.filter(c)
return c:IsType(TYPE_TRAP) and c:IsDestructable()
end
function c1041.ctlcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetAttackTarget()~=nil
end
function c1041.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and c1041.filter(chkc) end
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,c1041.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
if g:GetCount()>0 and g:GetFirst():IsFaceup() then
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
end
function c1041.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
Duel.NegateActivation(tc)
Duel.Destroy(tc,REASON_EFFECT)
end
end | gpl-2.0 |
nyczducky/darkstar | scripts/zones/Selbina/npcs/Isacio.lua | 14 | 3124 | -----------------------------------
-- Area: Selbina
-- NPC: Isacio
-- Finishes Quest: Elder Memories
-- @pos -54 -1 -44 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)
local questStatus = player:getQuestStatus(OTHER_AREAS,ELDER_MEMORIES);
if (questStatus == QUEST_ACCEPTED and trade:getItemCount() == 1) then
local IsacioElderMemVar = player:getVar("IsacioElderMemVar");
if (IsacioElderMemVar == 1 and trade:hasItemQty(538,1)) then
player:startEvent(0x0073,537);
elseif (IsacioElderMemVar == 2 and trade:hasItemQty(537,1)) then
player:startEvent(0x0074,539);
elseif (IsacioElderMemVar == 3 and trade:hasItemQty(539,1)) then
player:startEvent(0x0075);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local questStatus = player:getQuestStatus(OTHER_AREAS, ELDER_MEMORIES);
if (player:getQuestStatus(OTHER_AREAS, THE_OLD_LADY) ~= QUEST_AVAILABLE) then
player:startEvent(0x0063);
elseif (questStatus == QUEST_COMPLETED) then
player:startEvent(0x0076);
elseif (questStatus == QUEST_ACCEPTED) then
IsacioElderMemVar = player:getVar("IsacioElderMemVar");
if (IsacioElderMemVar == 1) then
player:startEvent(0x0072,538);
elseif (IsacioElderMemVar == 2) then
player:startEvent(0x0072,537);
elseif (IsacioElderMemVar == 3) then
player:startEvent(0x0072,539);
end
else
if (player:getMainLvl() >= SUBJOB_QUEST_LEVEL) then
player:startEvent(0x006f,538);
else
player:startEvent(0x0077);
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 == 0x006f and option == 40) then
player:addQuest(OTHER_AREAS, ELDER_MEMORIES);
player:setVar("IsacioElderMemVar", 1);
elseif (csid == 0x0073) then
player:tradeComplete();
player:setVar("IsacioElderMemVar", 2);
elseif (csid == 0x0074) then
player:tradeComplete();
player:setVar("IsacioElderMemVar", 3);
elseif (csid == 0x0075) then
player:tradeComplete();
player:unlockJob(0);
player:setVar("IsacioElderMemVar", 0);
player:messageSpecial(SUBJOB_UNLOCKED);
player:completeQuest(OTHER_AREAS, ELDER_MEMORIES);
end
end; | gpl-3.0 |
nyczducky/darkstar | scripts/globals/spells/phalanx.lua | 27 | 1151 | -----------------------------------------
-- Spell: PHALANX
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local enhskill = caster:getSkillLevel(ENHANCING_MAGIC_SKILL);
local final = 0;
local duration = 180;
if (caster:hasStatusEffect(EFFECT_COMPOSURE) == true and caster:getID() == target:getID()) then
duration = duration * 3;
end
if (enhskill<=300) then
final = (enhskill/10) -2;
if (final<0) then
final = 0;
end
elseif (enhskill>300) then
final = ((enhskill-300)/29) + 28;
else
print("Warning: Unknown enhancing magic skill for phalanx.");
end
if (final>35) then
final = 35;
end
if (target:addStatusEffect(EFFECT_PHALANX,final,0,duration)) then
spell:setMsg(230);
else
spell:setMsg(75);
end
return EFFECT_PHALANX;
end; | gpl-3.0 |
hanikk/tele-you | bot/utils.lua | 239 | 13499 | 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")()
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
| gpl-2.0 |
jbeich/Aquaria | files/scripts/maps/node_killcreator.lua | 6 | 1380 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
function init(me)
if isDeveloperKeys() then
node_setCursorActivation(me, true)
end
end
local function kill(me, name)
local ent = node_getNearestEntity(me, name)
if ent ~=0 then
entity_setState(ent, STATE_TRANSITION)
end
end
function activate(me)
if isDeveloperKeys() then
kill(me, "CreatorForm1")
kill(me, "CreatorForm2")
kill(me, "CreatorForm3")
kill(me, "CreatorForm4")
kill(me, "CreatorForm5")
kill(me, "CreatorForm6")
end
end
function update(me, dt)
end
| gpl-2.0 |
fegimanam/plggod | plugins/inpm.lua | 1114 | 3008 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
aqasaeed/ali | plugins/inpm.lua | 1114 | 3008 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
rpav-eso/ThiefsKnapsack | libs/LibAddonMenu-2.0/controls/description.lua | 6 | 2085 | --[[descriptionData = {
type = "description",
title = "My Title", --(optional)
text = "My description text to display.",
width = "full", --or "half" (optional)
reference = "MyAddonDescription" --(optional) unique global reference to control
} ]]
local widgetVersion = 5
local LAM = LibStub("LibAddonMenu-2.0")
if not LAM:RegisterWidget("description", widgetVersion) then return end
local wm = WINDOW_MANAGER
local tinsert = table.insert
local function UpdateValue(control)
if control.title then
control.title:SetText(control.data.title)
end
control.desc:SetText(control.data.text)
end
function LAMCreateControl.description(parent, descriptionData, controlName)
local control = wm:CreateControl(controlName or descriptionData.reference, parent.scroll or parent, CT_CONTROL)
control:SetResizeToFitDescendents(true)
local isHalfWidth = descriptionData.width == "half"
if isHalfWidth then
control:SetDimensionConstraints(250, 55, 250, 100)
control:SetDimensions(250, 55)
else
control:SetDimensionConstraints(510, 40, 510, 100)
control:SetDimensions(510, 30)
end
control.desc = wm:CreateControl(nil, control, CT_LABEL)
local desc = control.desc
desc:SetVerticalAlignment(TEXT_ALIGN_TOP)
desc:SetFont("ZoFontGame")
desc:SetText(descriptionData.text)
desc:SetWidth(isHalfWidth and 250 or 510)
if descriptionData.title then
control.title = wm:CreateControl(nil, control, CT_LABEL)
local title = control.title
title:SetWidth(isHalfWidth and 250 or 510)
title:SetAnchor(TOPLEFT, control, TOPLEFT)
title:SetFont("ZoFontWinH4")
title:SetText(descriptionData.title)
desc:SetAnchor(TOPLEFT, title, BOTTOMLEFT)
else
desc:SetAnchor(TOPLEFT)
end
control.panel = parent.panel or parent --if this is in a submenu, panel is its parent
control.data = descriptionData
control.UpdateValue = UpdateValue
if control.panel.data.registerForRefresh or control.panel.data.registerForDefaults then --if our parent window wants to refresh controls, then add this to the list
tinsert(control.panel.controlsToRefresh, control)
end
return control
end | bsd-2-clause |
jbeich/Aquaria | files/scripts/entities/architect.lua | 6 | 2032 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
v.n = 0
function init(me)
setupEntity(me)
entity_setEntityType(me, ET_NEUTRAL)
entity_initSkeletal(me, "Lumerean")
entity_scale(me, 0.5, 0.5)
entity_setState(me, STATE_IDLE)
entity_animate(me, "idle", -1)
entity_offset(me, 0, 32, 1, -1, 1, 1)
entity_setCullRadius(me, 1024)
end
function postInit(me)
v.n = getNaija()
entity_setTarget(me, v.n)
local w = entity_getNearestNode(me, "WORSHIP")
if w ~= 0 and node_isEntityIn(w, me) then
entity_animate(me, "worship", -1)
end
local f = entity_getNearestNode(me, "FLIP")
if f ~= 0 and node_isEntityIn(f, me) then
entity_fh(me)
end
local p = entity_getNearestNode(me, "PAIN")
if p ~= 0 and node_isEntityIn(p, me) then
entity_animate(me, "pain", -1)
end
end
function update(me, dt)
end
function enterState(me)
if entity_isState(me, STATE_IDLE) then
end
end
function exitState(me)
end
function damage(me, attacker, bone, damageType, dmg)
return false
end
function animationKey(me, key)
end
function hitSurface(me)
end
function songNote(me, note)
end
function songNoteDone(me, note)
end
function song(me, song)
end
function activate(me)
end
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Castle_Oztroja/npcs/_47l.lua | 14 | 1632 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: _47l (Torch Stand)
-- Notes: Opens door _471 near password #3
-- @pos -45.228 -17.832 22.392 151
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Castle_Oztroja/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local DoorID = npc:getID() - 3;
local DoorA = GetNPCByID(DoorID):getAnimation();
local TorchStandA = npc:getAnimation();
local Torch1 = npc:getID();
local Torch2 = npc:getID() + 1;
if (DoorA == 9 and TorchStandA == 9) then
player:startEvent(0x000a);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
local Torch1 = GetNPCByID(17396173):getID();
local Torch2 = GetNPCByID(Torch1):getID() + 1;
local DoorID = GetNPCByID(Torch1):getID() - 3;
if (option == 1) then
GetNPCByID(Torch1):openDoor(10); -- Torch Lighting
GetNPCByID(Torch2):openDoor(10); -- Torch Lighting
GetNPCByID(DoorID):openDoor(6);
end
end;
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option); | gpl-3.0 |
alirezafodaji/tele-IR | plugins/spm.lua | 1 | 1041 | -- Liberbot-compliant floodcontrol.
-- Put this after moderation.lua or blacklist.lua.
floodcontrol = floodcontrol or {}
local triggers = {
''
}
local action = function(msg)
if floodcontrol[-msg.chat.id] then
return
end
local input = msg.text_lower:match('^/floodcontrol[@'..bot.username..']* (.+)')
if not input then return true end
if msg.from.id ~= 100547061 and msg.from.id ~= config.admin then
return -- Only run for Liberbot or the admin.
end
input = JSON.decode(input)
if not input.groupid then
return
end
if not input.duration then
input.duration = 600
end
floodcontrol[input.groupid] = os.time() + input.duration
print(input.groupid .. ' silenced for ' .. input.duration .. ' seconds.')
end
local cron = function()
for k,v in pairs(floodcontrol) do
if os.time() > v then
floodcontrol[k] = nil
end
end
end
return {
action = action,
triggers = triggers,
cron = cron
}
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Labyrinth_of_Onzozo/TextIDs.lua | 7 | 1092 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6385; -- Obtained: <item>.
GIL_OBTAINED = 6386; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6388; -- Obtained key item: <keyitem>.
FISHING_MESSAGE_OFFSET = 7205; -- You can't fish here.
-- Treasure Coffer/Chest Dialog
CHEST_UNLOCKED = 7312; -- You unlock the chest!
CHEST_FAIL = 7313; -- Fails to open the chest.
CHEST_TRAP = 7314; -- The chest was trapped!
CHEST_WEAK = 7315; -- You cannot open the chest when you are in a weakened state.
CHEST_MIMIC = 7316; -- The chest was a mimic!
CHEST_MOOGLE = 7317; -- You cannot open the chest while participating in the moogle event.
CHEST_ILLUSION = 7318; -- The chest was but an illusion...
CHEST_LOCKED = 7319; -- The chest appears to be locked.
-- Other Dialogs
NOTHING_OUT_OF_ORDINARY = 6399; -- There is nothing out of the ordinary here.
-- conquest Base
CONQUEST_BASE = 7046; -- Tallying conquest results...
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Lower_Delkfutts_Tower/npcs/_540.lua | 14 | 2241 | -----------------------------------
-- Area: Lower Delkfutt's Tower
-- NPC: Cermet Door
-- Cermet Door for Windy Ambassador
-- Windurst Mission 3.3 "A New Journey"
-- @pos 636 16 59 184
-----------------------------------
package.loaded["scripts/zones/Lower_Delkfutts_Tower/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Lower_Delkfutts_Tower/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getCurrentMission(WINDURST) == A_NEW_JOURNEY and player:getVar("MissionStatus") == 2) then
if (trade:hasItemQty(549,1) and trade:getItemCount() == 1) then -- Trade Delkfutt Key
player:startEvent(0x0002);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local currentMission = player:getCurrentMission(WINDURST);
if (currentMission == A_NEW_JOURNEY and player:getVar("MissionStatus") == 2 and player:hasKeyItem(DELKFUTT_KEY) == false) then
player:messageSpecial(THE_DOOR_IS_FIRMLY_SHUT_OPEN_KEY);
elseif (currentMission == A_NEW_JOURNEY and player:getVar("MissionStatus") == 2 and player:hasKeyItem(DELKFUTT_KEY)) then
player:startEvent(0x0002);
else
player:messageSpecial(DOOR_FIRMLY_SHUT);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--print("CSID:",csid);
--print("RESULT:",option);
if (csid == 0x0002) then
if (player:hasKeyItem(DELKFUTT_KEY) == false) then
player:tradeComplete();
player:addKeyItem(DELKFUTT_KEY);
player:messageSpecial(KEYITEM_OBTAINED,DELKFUTT_KEY);
end
player:setVar("MissionStatus",3);
end
end; | gpl-3.0 |
nyczducky/darkstar | scripts/zones/Castle_Oztroja/npcs/qm1.lua | 14 | 1540 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: qm1 (???)
-- Involved in Quest: True Strength
-- @pos -100 -71 -132 151
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Castle_Oztroja/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(BASTOK,TRUE_STRENGTH) == QUEST_ACCEPTED and player:hasItem(1100) == false) then
if (trade:hasItemQty(4558,1) and trade:getItemCount() == 1) then -- Trade Yagudo Drink
player:tradeComplete();
player:messageSpecial(SENSE_OF_FOREBODING);
SpawnMob(17396140):updateClaim(player);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
nyczducky/darkstar | scripts/zones/Metalworks/npcs/Savae_E_Paleade.lua | 14 | 2812 | -----------------------------------
-- Area: Metalworks
-- NPC: Savae E Paleade
-- Involved In Mission: Journey Abroad
-- @pos 23.724 -17.39 -43.360 237
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getCurrentMission(SANDORIA) == JOURNEY_TO_BASTOK and player:getVar("MissionStatus") == 5) then
if (trade:hasItemQty(599,1) and trade:getItemCount() == 1) then -- Trade Mythril Sand
player:startEvent(0x00cd);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- San d'Oria Mission 2-3 Part I - Bastok > Windurst
if (player:getCurrentMission(SANDORIA) == JOURNEY_ABROAD and player:getVar("MissionStatus") == 2) then
player:startEvent(0x00cc);
-- San d'Oria Mission 2-3 Part II - Windurst > Bastok
elseif (player:getCurrentMission(SANDORIA) == JOURNEY_ABROAD and player:getVar("MissionStatus") == 7) then
player:startEvent(0x00ce);
elseif (player:getCurrentMission(SANDORIA) == JOURNEY_TO_BASTOK2 and player:getVar("MissionStatus") == 11) then
player:startEvent(0x00cf);
-----------------
elseif (player:getCurrentMission(SANDORIA) ~= 255) then
player:startEvent(0x00d0);
else
player:startEvent(0x00c8);
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 == 0x00cc) then
player:addMission(SANDORIA,JOURNEY_TO_BASTOK);
player:setVar("MissionStatus",3);
player:delKeyItem(LETTER_TO_THE_CONSULS_SANDORIA);
elseif (csid == 0x00cd) then
player:tradeComplete();
player:setVar("MissionStatus",6);
player:addMission(SANDORIA,JOURNEY_ABROAD);
elseif (csid == 0x00ce) then
player:addMission(SANDORIA,JOURNEY_TO_BASTOK2);
player:setVar("MissionStatus",8);
elseif (csid == 0x00cf) then
player:addMission(SANDORIA,JOURNEY_ABROAD);
player:delKeyItem(KINDRED_CREST);
player:addKeyItem(KINDRED_REPORT);
player:messageSpecial(KEYITEM_OBTAINED,KINDRED_REPORT);
end
end; | gpl-3.0 |
nyczducky/darkstar | scripts/globals/effects/battlefield.lua | 19 | 1156 | -----------------------------------
--
-- EFFECT_BATTLEFIELD
--
-----------------------------------
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
if (target:getPet()) then
target:getPet():addStatusEffect(effect);
end
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
if (target:getPet()) then
target:getPet():delStatusEffect(EFFECT_BATTLEFIELD);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdate CSID: %u",csid);
-- printf("onUpdate RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinish CSID: %u",csid);
-- printf("onFinish RESULT: %u",option);
end; | gpl-3.0 |
sjznxd/lc-20121231 | modules/freifunk/luasrc/model/cbi/freifunk/profile.lua | 20 | 2607 | --[[
LuCI - Lua Configuration Interface
Copyright 2011-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
httc://www.apache.org/licenses/LICENSE-2.0
]]--
local uci = require "luci.model.uci".cursor()
local ipkg = require "luci.model.ipkg"
local community = uci:get("freifunk", "community", "name")
if community == nil then
luci.http.redirect(luci.dispatcher.build_url("admin", "freifunk", "profile_error"))
return
else
community = "profile_" .. community
m = Map(community, translate("Community settings"), translate("These are the settings of your local community."))
c = m:section(NamedSection, "profile", "community")
local name = c:option(Value, "name", "Name")
name.rmempty = false
local homepage = c:option(Value, "homepage", translate("Homepage"))
local cc = c:option(Value, "country", translate("Country code"))
function cc.cfgvalue(self, section)
return uci:get(community, "wifi_device", "country")
end
function cc.write(self, sec, value)
if value then
uci:set(community, "wifi_device", "country", value)
uci:save(community)
end
end
local ssid = c:option(Value, "ssid", translate("ESSID"))
ssid.rmempty = false
local prefix = c:option(Value, "mesh_network", translate("Mesh prefix"))
prefix.datatype = "ip4addr"
prefix.rmempty = false
local splash_net = c:option(Value, "splash_network", translate("Network for client DHCP addresses"))
splash_net.datatype = "ip4addr"
splash_net.rmempty = false
local splash_prefix = c:option(Value, "splash_prefix", translate("Client network size"))
splash_prefix.datatype = "range(0,32)"
splash_prefix.rmempty = false
local ipv6 = c:option(Flag, "ipv6", translate("Enable IPv6"))
ipv6.rmempty = true
local ipv6_config = c:option(ListValue, "ipv6_config", translate("IPv6 Config"))
ipv6_config:depends("ipv6", 1)
ipv6_config:value("static")
if ipkg.installed ("auto-ipv6-ib") then
ipv6_config:value("auto-ipv6-random")
ipv6_config:value("auto-ipv6-fromv4")
end
ipv6_config.rmempty = true
local ipv6_prefix = c:option(Value, "ipv6_prefix", translate("IPv6 Prefix"), translate("IPv6 network in CIDR notation."))
ipv6_prefix:depends("ipv6", 1)
ipv6_prefix.datatype = "ip6addr"
ipv6_prefix.rmempty = true
local lat = c:option(Value, "latitude", translate("Latitude"))
lat.datatype = "range(-180, 180)"
lat.rmempty = false
local lon = c:option(Value, "longitude", translate("Longitude"))
lon.rmempty = false
return m
end
| apache-2.0 |
hacker44-h44/teleguard-v2 | plugins/google.lua | 722 | 1037 | local function googlethat(query)
local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
local parameters = "q=".. (URL.escape(query) or "")
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=""
for key,val in ipairs(results) do
stringresults=stringresults..val[1].." - "..val[2].."\n"
end
return stringresults
end
local function run(msg, matches)
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = "Searches Google and send results",
usage = "!google [terms]: Searches Google and send results",
patterns = {
"^!google (.*)$",
"^%.[g|G]oogle (.*)$"
},
run = run
}
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Port_Windurst/npcs/Degong.lua | 53 | 1826 | -----------------------------------
-- Area: Port Windurst
-- NPC: Degong
-- Type: Fishing Synthesis Image Support
-- @pos -178.400 -3.835 60.480 240
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,5);
local SkillCap = getCraftSkillCap(player,SKILL_FISHING);
local SkillLevel = player:getSkillLevel(SKILL_FISHING);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_FISHING_IMAGERY) == false) then
player:startEvent(0x271D,SkillCap,SkillLevel,2,239,player:getGil(),0,30,0); -- p1 = skill level
else
player:startEvent(0x271D,SkillCap,SkillLevel,2,239,player:getGil(),19293,30,0);
end
else
player:startEvent(0x271D); -- Standard Dialogue
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x271D and option == 1) then
player:messageSpecial(FISHING_SUPPORT,0,0,2);
player:addStatusEffect(EFFECT_FISHING_IMAGERY,1,0,3600);
end
end; | gpl-3.0 |
datamachine/tg | test.lua | 210 | 2571 | started = 0
our_id = 0
function vardump(value, depth, key)
local linePrefix = ""
local spaces = ""
if key ~= nil then
linePrefix = "["..key.."] = "
end
if depth == nil then
depth = 0
else
depth = depth + 1
for i=1, depth do spaces = spaces .. " " end
end
if type(value) == 'table' then
mTable = getmetatable(value)
if mTable == nil then
print(spaces ..linePrefix.."(table) ")
else
print(spaces .."(metatable) ")
value = mTable
end
for tableKey, tableValue in pairs(value) do
vardump(tableValue, depth, tableKey)
end
elseif type(value) == 'function' or
type(value) == 'thread' or
type(value) == 'userdata' or
value == nil
then
print(spaces..tostring(value))
else
print(spaces..linePrefix.."("..type(value)..") "..tostring(value))
end
end
print ("HI, this is lua script")
function ok_cb(extra, success, result)
end
-- Notification code {{{
function get_title (P, Q)
if (Q.type == 'user') then
return P.first_name .. " " .. P.last_name
elseif (Q.type == 'chat') then
return Q.title
elseif (Q.type == 'encr_chat') then
return 'Secret chat with ' .. P.first_name .. ' ' .. P.last_name
else
return ''
end
end
local lgi = require ('lgi')
local notify = lgi.require('Notify')
notify.init ("Telegram updates")
local icon = os.getenv("HOME") .. "/.telegram-cli/telegram-pics/telegram_64.png"
function do_notify (user, msg)
local n = notify.Notification.new(user, msg, icon)
n:show ()
end
-- }}}
function on_msg_receive (msg)
if started == 0 then
return
end
if msg.out then
return
end
do_notify (get_title (msg.from, msg.to), msg.text)
if (msg.text == 'ping') then
if (msg.to.id == our_id) then
send_msg (msg.from.print_name, 'pong', ok_cb, false)
else
send_msg (msg.to.print_name, 'pong', ok_cb, false)
end
return
end
if (msg.text == 'PING') then
if (msg.to.id == our_id) then
fwd_msg (msg.from.print_name, msg.id, ok_cb, false)
else
fwd_msg (msg.to.print_name, msg.id, ok_cb, false)
end
return
end
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
--vardump (chat)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
function cron()
-- do something
postpone (cron, false, 1.0)
end
function on_binlog_replay_end ()
started = 1
postpone (cron, false, 1.0)
end
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Northern_San_dOria/npcs/Prerivon.lua | 14 | 1038 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Prerivon
-- Type: Standard Dialogue NPC
-- @zone 231
-- @pos 142.324 0.000 132.515
--
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,PRERIVON_DIALOG);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
jakianroy/NGUI_To_Be_Best | Assets/LuaFramework/Lua/3rd/luabitop/bitbench.lua | 17 | 1661 | -- Microbenchmark for bit operations library. Public domain.
local bit = require"bit"
if not bit.rol then -- Replacement function if rotates are missing.
local bor, shl, shr = bit.bor, bit.lshift, bit.rshift
function bit.rol(a, b) return bor(shl(a, b), shr(a, 32-b)) end
end
if not bit.bswap then -- Replacement function if bswap is missing.
local bor, band, shl, shr = bit.bor, bit.band, bit.lshift, bit.rshift
function bit.bswap(a)
return bor(shr(a, 24), band(shr(a, 8), 0xff00),
shl(band(a, 0xff00), 8), shl(a, 24));
end
end
local base = 0
local function bench(name, t)
local n = 2000000
repeat
local tm = os.clock()
t(n)
tm = os.clock() - tm
if tm > 1 then
local ns = tm*1000/(n/1000000)
io.write(string.format("%-15s %6.1f ns\n", name, ns-base))
return ns
end
n = n + n
until false
end
-- The overhead for the base loop is subtracted from the other measurements.
base = bench("loop baseline", function(n)
local x = 0; for i=1,n do x = x + i end
end)
bench("tobit", function(n)
local f = bit.tobit or bit.cast
local x = 0; for i=1,n do x = x + f(i) end
end)
bench("bnot", function(n)
local f = bit.bnot
local x = 0; for i=1,n do x = x + f(i) end
end)
bench("bor/band/bxor", function(n)
local f = bit.bor
local x = 0; for i=1,n do x = x + f(i, 1) end
end)
bench("shifts", function(n)
local f = bit.lshift
local x = 0; for i=1,n do x = x + f(i, 1) end
end)
bench("rotates", function(n)
local f = bit.rol
local x = 0; for i=1,n do x = x + f(i, 1) end
end)
bench("bswap", function(n)
local f = bit.bswap
local x = 0; for i=1,n do x = x + f(i) end
end)
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Eastern_Altepa_Desert/TextIDs.lua | 7 | 1060 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6385; -- Obtained: <item>.
GIL_OBTAINED = 6386; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6388; -- Obtained key item: <keyitem>.
BEASTMEN_BANNER = 7127; -- There is a beastmen's banner.
FISHING_MESSAGE_OFFSET = 7547; -- You can't fish here.
ALREADY_OBTAINED_TELE = 7656; -- You already possess the gate crystal for this telepoint.
-- Conquest
CONQUEST = 7214; -- You've earned conquest points!
-- Quest Dialog
SENSE_OF_FOREBODING = 6400; -- You are suddenly overcome with a sense of foreboding...
NOTHING_OUT_OF_ORDINARY = 7662; -- There is nothing out of the ordinary here.
-- conquest Base
CONQUEST_BASE = 7046; -- Tallying conquest results...
--chocobo digging
DIG_THROW_AWAY = 7560; -- You dig up$, but your inventory is full. You regretfully throw the # away.
FIND_NOTHING = 7562; -- You dig and you dig, but find nothing.
| gpl-3.0 |
Mariappan/rcfiles | home/.notion/looks/look_awesome_yaarg.lua | 4 | 5383 | -- Authors: James Gray <j.gray@ed.ac.uk>
-- License: Unknown
-- Last Changed: 2006-02-03
--
--[[
look_awesome_yaarg.lua (based on look awesome )
To completely yaargify Ion, the terminal emulator background is recommended to
be set to gray25 as does the root window. Transparent frames by default
wallpaper can be good sometimes... Also note this theme uses terminus font.
Setup: Drop into ~/.ion3/ or install in the relevant system-wide directory
Author: James Gray <j dot gray at ed dot ac dot uk> (yaarg in #ion)
Date: Fri Feb 3 00:13:43 GMT 2006
]]
if not gr.select_engine("de") then return end
de.reset()
de.defstyle("*", {
shadow_colour = "gray25",
highlight_colour = "gray25",
padding_colour = "gray25",
foreground_colour = "white",
background_colour = "gray25",
border_style = "inlaid",
highlight_pixels = 0,
shadow_pixels = 0,
padding_pixels = 0,
spacing = 0,
font = "-*-terminus-*-*-normal--12-*-*-*-*-*-*-*",
text_align = "center",
})
de.defstyle("frame", {
based_on = "*",
background_colour = "gray25",
transparent_background = true,
shadow_pixels = 1,
padding_pixels = 0,
highlight_pixels = 0,
spacing = 1,
shadow_colour = "gray30",
highlight_colour = "gray28",
})
de.defstyle("frame-floatframe", {
based_on = "frame",
padding_pixels = 1,
de.substyle("active", {
padding_colour = "gray30",
}),
de.substyle("inactive", {
padding_colour = "#808080",
}),
})
de.defstyle("tab", {
based_on = "*",
highlight_pixels = 1,
shadow_pixels = 1,
padding_pixels = 0,
spacing = 0,
transparent_background = false,
text_align = "center",
de.substyle("active-selected", {
shadow_colour = "#808080",
highlight_colour = "#808080",
background_colour = "gray33",
foreground_colour = "white",
}),
de.substyle("active-unselected", {
shadow_colour = "#808080",
highlight_colour = "#808080",
background_colour = "gray30",
foreground_colour = "white",
}),
de.substyle("inactive-selected", {
shadow_colour = "#808080",
highlight_colour = "#808080",
background_colour = "gray33",
foreground_colour = "white",
}),
de.substyle("inactive-unselected", {
shadow_colour = "#808080",
highlight_colour = "#808080",
background_colour = "gray30",
foreground_colour = "white",
}),
})
de.defstyle("stdisp", {
padding = 0,
shadow_pixels = 0,
padding_pixels = 0,
spacing = 1,
highlight_pixels = 0,
shadow_colour = "black",
highlight_colour = "black",
background_colour = "gray40",
foreground_colour = "white",
})
de.defstyle("tab-frame", {
based_on = "tab",
font = "-*-terminus-*-*-normal--12-*-*-*-*-*-*-*",
padding_pixels = 1,
spacing = 0,
shadow_colour = "red",
padding_colour = "red",
highlight_colour = "red",
background_colour = "red",
de.substyle("active-*-*-*-activity", {
shadow_colour = "red",
highlight_colour = "red",
background_colour = "#808080",
foreground_colour = "white",
}),
de.substyle("inactive-*-*-*-activity", {
shadow_colour = "#808080",
highlight_colour = "#808080",
background_colour = "#808080",
foreground_colour = "#808080",
}),
})
de.defstyle("tab-frame-ionframe", {
based_on = "tab-frame",
})
de.defstyle("tab-frame-floatframe", {
based_on = "tab-frame",
padding_pixels = 0,
})
de.defstyle("tab-menuentry", {
based_on = "tab",
padding_pixels = 1,
spacing = 2,
text_align = "left",
})
de.defstyle("tab-menuentry-bigmenu", {
based_on = "tab-menuentry",
padding_pixels = 7,
})
de.defstyle("tab-menuentry-pmenu", {
based_on = "tab-menuentry",
de.substyle("inactive-selected", {
shadow_colour = "#808080",
highlight_colour = "#808080",
background_colour = "#CCCCCC",
foreground_colour = "#FFF",
}),
de.substyle("inactive-unselected", {
shadow_colour = "#667",
highlight_colour = "#667",
background_colour = "#334",
foreground_colour = "#999",
}),
})
de.defstyle("input", {
based_on = "*",
foreground_colour = "white",
background_colour = "grey30",
padding_colour = "white",
transparent_background = false,
border_style = "elevated",
padding_pixels = 2,
})
de.defstyle("input-edln", {
based_on = "input",
de.substyle("*-cursor", {
background_colour = "white",
foreground_colour = "black",
}),
de.substyle("*-selection", {
background_colour = "#AAA",
foreground_colour = "#334",
}),
})
de.defstyle("input-message", {
based_on = "input",
})
de.defstyle("input-menu", {
based_on = "input",
transparent_background = false,
highlight_pixels = 0,
shadow_pixels = 0,
padding_pixels = 0,
spacing = 0,
})
de.defstyle("input-menu-bigmenu", {
based_on = "input-menu",
})
de.defstyle("moveres_display", {
based_on = "input",
})
de.defstyle("dock", {
based_on = "*",
})
gr.refresh()
| gpl-2.0 |
SNiLD/TabletopSimulatorAgricola | src/Global.lua | 1 | 19704 | --[[ Helpers ]]
function table.contains(table, element)
for _, value in pairs(table) do
if value == element then
return true
end
end
return false
end
function table.toString(table, separator)
result = ""
for _, value in pairs(table) do
if (string.len(result) == 0) then
result = result .. value
else
result = result .. separator .. value
end
end
return result
end
function table.isEmpty(table)
if (table == nil) then
return true
end
if (next(table) == nil) then
return true
end
return false
end
function dummy()
end
--[[ Globals ]]
gameStarted = false
playerCount = 0
currentRoundNumber = 0
deckTypes = {}
playerColors = {}
actionsRemaining = {}
playerFarmScriptingZoneGUIDs = { White = "5f165b", Red = "f1ea9d", Green = "baae38", Blue = "f12186", Purple = "8e8f24" }
workerGUIDs =
{
White = { "982e0c", "1d658c", "91230a", "339556", "8acc12" },
Red = { "f5f9c6", "3adf43", "8c1ca6", "aed233", "e7f696" },
Green = { "a8f720", "306232", "e3babc", "b57c85", "758634" },
Blue = { "cc5517", "d8d05d", "6b18da", "7c565a", "35d880" },
Purple = { "317185", "1da0ea", "96be86", "8898f4", "c1abc2" }
}
homeZoneGUIDs = { White = "cddcd1", Red = "9d9005", Green = "0f79a9", Blue = "b4d2b7", Purple = "d9e998" }
resourceBagGUIDs = { Wood = "57458b", Clay = "8a147c", Stone = "c64ad7", Reed = "141313", Grain = "61fc77", Vegetable = "e7cb62", Food = "f249ab", Sheep = "f851b2", Boar = "e7b33c", Cattle = "f0c5e7" }
actionCardScriptingZoneGUIDs = { "26d1fc", "2a6c15", "0e1397", "0af55c", "c6e3f3", "8fdd38" }
actionBoardScriptingZoneGUIDs = { "a08297", "e9469a", "3a7f4d", "aa671d", "241264", "292428", "ac920e", "6e8819", "04f5b0", "e01044" }
actionRoundScriptingZoneGUIDs = { "8658b7", "fe050d", "ce9a11", "2cd64d", "833759", "ba2965", "5b711c", "b4381a", "5b99b7", "a2c5f0", "dce35e", "f62afb", "ccfdc4", "934f90" }
stage1CardDeckGUID = "77c9f7"
stage2CardDeckGUID = "ac1369"
stage3CardDeckGUID = "ceb91a"
stage4CardDeckGUID = "8f6c74"
stage5CardDeckGUID = "d78dfb"
kDeckBagGUID = "236391"
eDeckBagGUID = "5b947c"
iDeckBagGUID = "c4551b"
occupationDeckGUIDs = { "5fd15d", "ba39bf", "61f6d6", "5c1922", "eec2e8", "1e6207", "997c19", "9879ec", "e4d037" }
occupationShufflingZoneGUID = "d46db2"
minorImprovementDeckGUIDs = { "fd9eea", "aaa166", "6de5b0" }
minorImprovementShufflingZoneGUID = "286fa6"
--[[ These are hack functions because the API does not work correctly atm. ]]
function getObjectPositionTable(object, adjustment)
local position = object.getPosition()
result = {}
positionKeys = {'x','y','z'}
if (adjustment == nil) then
result = { position['x'], position['y'], position['z'] }
else
for key, value in pairs(adjustment) do
result[key] = position[positionKeys[key]] + value
end
end
return result
end
function setDeckTypes(types)
deckTypes = types
end
function lock(object, parameters)
object.lock()
end
--[[ Private functions ]]
function dealCards(deck, rotation, positions)
local parameters = {}
parameters.rotation = rotation
for _, position in pairs(positions) do
parameters.position = position
card = deck.takeObject(parameters)
card.setPosition(position)
card.setRotation(rotation)
end
end
function initializeGameStage(stageCardDeckGUID, positions)
stageCardDeck = getObjectFromGUID(stageCardDeckGUID)
print("Shuffling " .. stageCardDeck.getName() .. " cards")
stageCardDeck.shuffle()
dealCards(stageCardDeck, {0.0, 180.0, 180.0}, positions)
end
function initializeFamilyBoard()
mainBoard = getObjectFromGUID("7db9f8")
boardBag = getObjectFromGUID("a11e39")
local parameters = {}
parameters.position = getObjectPositionTable(mainBoard, nil)
parameters.rotation = {0.0, 180.0, 0.0}
parameters.callback = "lock"
parameters.params = {}
mainBoard.unlock()
mainBoard.setPositionSmooth(getObjectPositionTable(boardBag, {0.0, 1.5, 0.0}))
familyBoard = boardBag.takeObject(parameters)
familyBoard.setPosition(parameters.position)
end
function initializeGameStageCards()
initializeGameStage(
stage1CardDeckGUID,
{
getObjectFromGUID(actionRoundScriptingZoneGUIDs[1]).getPosition(),
getObjectFromGUID(actionRoundScriptingZoneGUIDs[2]).getPosition(),
getObjectFromGUID(actionRoundScriptingZoneGUIDs[3]).getPosition(),
getObjectFromGUID(actionRoundScriptingZoneGUIDs[4]).getPosition()
})
initializeGameStage(
stage2CardDeckGUID,
{
getObjectFromGUID(actionRoundScriptingZoneGUIDs[5]).getPosition(),
getObjectFromGUID(actionRoundScriptingZoneGUIDs[6]).getPosition(),
getObjectFromGUID(actionRoundScriptingZoneGUIDs[7]).getPosition()
})
initializeGameStage(
stage3CardDeckGUID,
{
getObjectFromGUID(actionRoundScriptingZoneGUIDs[8]).getPosition(),
getObjectFromGUID(actionRoundScriptingZoneGUIDs[9]).getPosition()
})
initializeGameStage(
stage4CardDeckGUID,
{
getObjectFromGUID(actionRoundScriptingZoneGUIDs[10]).getPosition(),
getObjectFromGUID(actionRoundScriptingZoneGUIDs[11]).getPosition()
})
initializeGameStage(
stage5CardDeckGUID,
{
getObjectFromGUID(actionRoundScriptingZoneGUIDs[12]).getPosition(),
getObjectFromGUID(actionRoundScriptingZoneGUIDs[13]).getPosition()
})
end
function initializeActionCards(playerCount, isFamilyGame)
print("Initializing player cards for " .. playerCount .. " players family mode " .. tostring(isFamilyGame))
actionCards5Players = getObjectFromGUID("590540")
actionCards4Players = getObjectFromGUID("2dd967")
actionCards3Players = getObjectFromGUID("4bdd23")
actionCardsBag = getObjectFromGUID("87e8b1")
actionCardsBagPosition = getObjectPositionTable(actionCardsBag, {0.0, 1.5, 0.0})
rotation = {0.0, 180.0, 0.0}
if (isFamilyGame) then
rotation[3] = 180.0
end
if (playerCount == 5) then
actionCards4Players.setPositionSmooth(actionCardsBagPosition)
actionCards3Players.setPositionSmooth(actionCardsBagPosition)
dealCards(
actionCards5Players,
rotation,
{
{-13.1315432, 1.35851169,-8.331627},
{-10.2916288, 1.35850871, 0.2497616},
{-10.1748323, 1.35851026, -4.013337},
{-10.298852, 1.35851181, -8.452009},
{-13.19608, 1.35850859, 0.2789259},
{-13.1250954, 1.35851014, -3.91666961}
})
elseif (playerCount == 4) then
actionCards5Players.setPositionSmooth(actionCardsBagPosition)
actionCards3Players.setPositionSmooth(actionCardsBagPosition)
dealCards(
actionCards4Players,
rotation,
{
{-13.2538042, 1.35851169, -8.345971},
{-10.3602352, 1.35850859, 0.282183915},
{-10.3508177, 1.35851014, -4.06672955},
{-10.3133535, 1.35851169, -8.395471},
{-13.2757206, 1.35850871, 0.223956347},
{-13.2007608, 1.35851014, -3.87375879}
})
elseif (playerCount == 3) then
actionCards5Players.setPositionSmooth(actionCardsBagPosition)
actionCards4Players.setPositionSmooth(actionCardsBagPosition)
dealCards(
actionCards3Players,
rotation,
{
{-10.4203014, 1.35851014, -4.19282},
{-10.407362, 1.35851181, -8.453454},
{-13.1756124, 1.35851026, -4.16184473},
{-13.2102251, 1.35851169, -8.382444}
})
elseif (playerCount == 2 or playerCount == 1) then
actionCards5Players.setPositionSmooth(actionCardsBagPosition)
actionCards4Players.setPositionSmooth(actionCardsBagPosition)
actionCards3Players.setPositionSmooth(actionCardsBagPosition)
end
end
function initializeOneOccupationType(isCorrect, playerCount, occupations1Player, occupations3Players, occupations4Players, occupationDeckPosition, occupationBagPosition)
if (isCorrect) then
occupations1Player.flip()
occupations1Player.setPosition(occupationDeckPosition)
if (playerCount >= 3) then
occupations3Players.flip()
occupations3Players.setPosition(occupationDeckPosition)
if (playerCount >= 4) then
occupations4Players.flip()
occupations4Players.setPosition(occupationDeckPosition)
else
occupations4Players.setPositionSmooth(occupationBagPosition)
end
else
occupations3Players.setPositionSmooth(occupationBagPosition)
occupations4Players.setPositionSmooth(occupationBagPosition)
end
else
occupations1Player.setPositionSmooth(occupationBagPosition)
occupations3Players.setPositionSmooth(occupationBagPosition)
occupations4Players.setPositionSmooth(occupationBagPosition)
end
end
function initializeOccupations(playerCount, deckTypes)
occupationShufflingZone = getObjectFromGUID(occupationShufflingZoneGUID)
occupationDeckPosition = getObjectPositionTable(occupationShufflingZone, nil)
initializeOneOccupationType(
table.contains(deckTypes, "K"),
playerCount,
getObjectFromGUID(occupationDeckGUIDs[1]),
getObjectFromGUID(occupationDeckGUIDs[2]),
getObjectFromGUID(occupationDeckGUIDs[3]),
occupationDeckPosition,
getObjectPositionTable(getObjectFromGUID(kDeckBagGUID), {0.0, 1.5, 0.0}))
initializeOneOccupationType(
table.contains(deckTypes, "E"),
playerCount,
getObjectFromGUID(occupationDeckGUIDs[4]),
getObjectFromGUID(occupationDeckGUIDs[5]),
getObjectFromGUID(occupationDeckGUIDs[6]),
occupationDeckPosition,
getObjectPositionTable(getObjectFromGUID(eDeckBagGUID), {0.0, 1.5, 0.0}))
initializeOneOccupationType(
table.contains(deckTypes, "I"),
playerCount,
getObjectFromGUID(occupationDeckGUIDs[7]),
getObjectFromGUID(occupationDeckGUIDs[8]),
getObjectFromGUID(occupationDeckGUIDs[9]),
occupationDeckPosition,
getObjectPositionTable(getObjectFromGUID(iDeckBagGUID), {0.0, 1.5, 0.0}))
end
function initializeOneMinorImprovementType(isCorrect, minorImprovements, minorImprovementDeckPosition, minorImprovementBagPosition)
if (isCorrect) then
minorImprovements.flip()
minorImprovements.setPosition(minorImprovementDeckPosition)
else
minorImprovements.setPositionSmooth(minorImprovementBagPosition)
end
end
function initializeMinorImprovements(deckTypes)
minorImprovementShufflingZone = getObjectFromGUID(minorImprovementShufflingZoneGUID)
minorImprovementDeckPosition = getObjectPositionTable(minorImprovementShufflingZone, nil)
initializeOneMinorImprovementType(
table.contains(deckTypes, "K"),
getObjectFromGUID(minorImprovementDeckGUIDs[1]),
minorImprovementDeckPosition,
getObjectPositionTable(getObjectFromGUID(kDeckBagGUID), {0.0, 1.5, 0.0}))
initializeOneMinorImprovementType(
table.contains(deckTypes, "E"),
getObjectFromGUID(minorImprovementDeckGUIDs[2]),
minorImprovementDeckPosition,
getObjectPositionTable(getObjectFromGUID(eDeckBagGUID), {0.0, 1.5, 0.0}))
initializeOneMinorImprovementType(
table.contains(deckTypes, "I"),
getObjectFromGUID(minorImprovementDeckGUIDs[3]),
minorImprovementDeckPosition,
getObjectPositionTable(getObjectFromGUID(iDeckBagGUID), {0.0, 1.5, 0.0}))
end
--[[ Global functions ]]
function initializeBoard()
if (gameStarted) then
print("Game already started.")
return
end
gameStarted = true
isFamilyGame = false
players = getSeatedPlayers()
if (playerCount < #players) then
print("Game was setup for " .. playerCount .. " players but currently " .. #players .. " players seated. Adjusting for seated player count.")
playerCount = #players
end
print("Initializing board for " .. playerCount .. " players with decks '" .. table.toString(deckTypes, ",") .. "'")
if (next(deckTypes) == nil) then
print("No decks were chosen, using family rules")
isFamilyGame = true
initializeFamilyBoard()
end
if (playerCount == 1) then
-- In single player mode the 3-wood action space gets only 2 wood.
woodScriptingZone = getObjectFromGUID("ac920e")
zoneResources = woodScriptingZone.getTable("resources")
zoneResources["Wood"] = 2
woodScriptingZone.setTable("resources", zoneResources)
end
initializeGameStageCards()
initializeActionCards(playerCount, isFamilyGame)
initializeOccupations(playerCount, deckTypes)
initializeMinorImprovements(deckTypes)
startLuaCoroutine(nil, 'initializeWorkPhase')
end
function initializeWorkPhase()
coroutine.yield(0)
startRound()
return 1
end
function setActionsRemaining(color, count)
actionsRemaining[color] = count
end
function isEndOfRound()
if (actionsRemaining == nil or next(actionsRemaining) == nil) then
return true
end
for color, actions in pairs(actionsRemaining) do
if (actions ~= nil and actions > 0) then
print("Atleast player " .. color .. " still has " .. actions .. " actions")
return false
end
end
print("No player has turns remaining")
return true
end
function returnWorker(object)
guid = object.getGUID()
for color, workerGUIDsForColor in pairs(workerGUIDs) do
for _, workerGUID in pairs(workerGUIDsForColor) do
if (guid == workerGUID) then
homeZone = getObjectFromGUID(homeZoneGUIDs[color])
object.setPositionSmooth(getObjectPositionTable(homeZone, nil))
return
end
end
end
end
function returnWorkersFromZone(zoneGUID)
zone = getObjectFromGUID(zoneGUID)
for _, object in pairs(zone.getObjects()) do
returnWorker(object)
end
end
function returnWorkers()
print("Returning workers")
for _, guid in pairs(actionCardScriptingZoneGUIDs) do
returnWorkersFromZone(guid)
end
for _, guid in pairs(actionBoardScriptingZoneGUIDs) do
returnWorkersFromZone(guid)
end
for _, guid in pairs(actionRoundScriptingZoneGUIDs) do
returnWorkersFromZone(guid)
end
end
function flipNewRoundCard()
print("Flipping new round card")
zone = getObjectFromGUID(actionRoundScriptingZoneGUIDs[currentRoundNumber])
for _, object in pairs(zone.getObjects()) do
if (object.name == "Card") then
object.setRotation({0.0, 180.0, 0.0})
end
end
end
function fillResourceToZone(zone, resources)
zonePosition = getObjectPositionTable(zone, {0.0, 2.0, 0.0})
for resource, amount in pairs(resources) do
print("Adding " .. amount .. " " .. resource .. " to " .. zone.getName())
resourceBag = getObjectFromGUID(resourceBagGUIDs[resource])
print("Taking resources from " .. resourceBag.getName())
local parameters = {}
parameters.position = zonePosition
parameters.rotation = {0.0, 0.0, 0.0}
parameters.callback = ""
parameters.params = {}
for i = 1, amount, 1 do
object = resourceBag.takeObject(parameters)
object.setPosition(zonePosition)
end
end
end
function fillResourcesToZone(zoneGUID)
zone = getObjectFromGUID(zoneGUID)
print("Filling resources to zone " .. zone.getName())
zoneResources = zone.getTable("resources")
if (not table.isEmpty(zoneResources)) then
fillResourceToZone(zone, zoneResources)
return
end
for _, object in pairs(zone.getObjects()) do
if (object.name == "Card") then
print("Getting resources for card " .. object.getName())
objectResources = object.getTable("resources")
if (not table.isEmpty(objectResources)) then
fillResourceToZone(zone, objectResources)
end
end
end
end
function fillResources()
print("Filling resources")
for _, guid in pairs(actionCardScriptingZoneGUIDs) do
fillResourcesToZone(guid)
end
for _, guid in pairs(actionBoardScriptingZoneGUIDs) do
fillResourcesToZone(guid)
end
for roundNumber, guid in pairs(actionRoundScriptingZoneGUIDs) do
if (roundNumber <= currentRoundNumber) then
fillResourcesToZone(guid)
end
end
end
function startRound()
currentRoundNumber = currentRoundNumber + 1
print("Starting round " .. currentRoundNumber)
flipNewRoundCard()
fillResources()
end
function endRound()
print("Ending round " .. currentRoundNumber)
returnWorkers()
end
function addAction(color)
actionsRemaining[color] = actionsRemaining[color] + 1
print("Adding action to player " .. color .. " player now has " .. actionsRemaining[color] .. " actions left")
end
function removeAction(color)
actionsRemaining[color] = actionsRemaining[color] - 1
print("Removing action from player " .. color .. " player now has " .. actionsRemaining[color] .. " actions left")
end
function getActions(color)
count = 0
farmGUID = playerFarmScriptingZoneGUIDs[color]
farmZone = getObjectFromGUID(farmGUID)
farmWorkerGUIDs = workerGUIDs[color]
for _, object in pairs(farmZone.getObjects()) do
if (table.contains(farmWorkerGUIDs, object.getGUID())) then
count = count + 1
end
end
return count
end
function updateActions()
actionsRemaining = {}
players = getSeatedPlayers()
print("Updating remaining actions for " .. #players .. " players")
for _, color in pairs(players) do
actionsRemaining[color] = getActions(color)
end
for color, actions in pairs(actionsRemaining) do
print("Player " .. color .. " has " .. actions .. " actions remaining")
end
end
--[[ Even hooks ]]
function onObjectEnterScriptingZone(zone, object)
for color, zoneGUID in pairs(playerFarmScriptingZoneGUIDs) do
if (zoneGUID == zone.getGUID()) then
for _, workerGUID in pairs(workerGUIDs[color]) do
if (workerGUID == object.getGUID()) then
addAction(color)
return
end
end
end
end
end
function onObjectLeaveScriptingZone(zone, object)
for color, zoneGUID in pairs(playerFarmScriptingZoneGUIDs) do
if (zoneGUID == zone.getGUID()) then
for _, workerGUID in pairs(workerGUIDs[color]) do
if (workerGUID == object.getGUID()) then
removeAction(color)
return
end
end
end
end
end
-- function update()
-- end
function onload()
updateActions()
end
function onPlayerTurnEnd(color)
if (isEndOfRound()) then
endRound()
if (currentRoundNumber < 14) then
startRound()
end
end
end
function onPlayerChangedColor(color)
updateActions()
end
| mit |
Sojerbot/new | plugins/btc.lua | 289 | 1375 | -- See https://bitcoinaverage.com/api
local function getBTCX(amount,currency)
local base_url = 'https://api.bitcoinaverage.com/ticker/global/'
-- Do request on bitcoinaverage, the final / is critical!
local res,code = https.request(base_url..currency.."/")
if code ~= 200 then return nil end
local data = json:decode(res)
-- Easy, it's right there
text = "BTC/"..currency..'\n'..'Buy: '..data.ask..'\n'..'Sell: '..data.bid
-- If we have a number as second parameter, calculate the bitcoin amount
if amount~=nil then
btc = tonumber(amount) / tonumber(data.ask)
text = text.."\n "..currency .." "..amount.." = BTC "..btc
end
return text
end
local function run(msg, matches)
local cur = 'EUR'
local amt = nil
-- Get the global match out of the way
if matches[1] == "!btc" then
return getBTCX(amt,cur)
end
if matches[2] ~= nil then
-- There is a second match
amt = matches[2]
cur = string.upper(matches[1])
else
-- Just a EUR or USD param
cur = string.upper(matches[1])
end
return getBTCX(amt,cur)
end
return {
description = "Bitcoin global average market value (in EUR or USD)",
usage = "!btc [EUR|USD] [amount]",
patterns = {
"^!btc$",
"^!btc ([Ee][Uu][Rr])$",
"^!btc ([Uu][Ss][Dd])$",
"^!btc (EUR) (%d+[%d%.]*)$",
"^!btc (USD) (%d+[%d%.]*)$"
},
run = run
}
| gpl-2.0 |
guangbin79/Lua_5.1.5-iOS | luasocket-3.0-rc1/test/mimetest.lua | 44 | 8413 | local socket = require("socket")
local ltn12 = require("ltn12")
local mime = require("mime")
local unpack = unpack or table.unpack
dofile("testsupport.lua")
local qptest = "qptest.bin"
local eqptest = "qptest.bin2"
local dqptest = "qptest.bin3"
local b64test = "b64test.bin"
local eb64test = "b64test.bin2"
local db64test = "b64test.bin3"
-- from Machado de Assis, "A Mão e a Rosa"
local mao = [[
Cursavam estes dois moços a academia de S. Paulo, estando
Luís Alves no quarto ano e Estêvão no terceiro.
Conheceram-se na academia, e ficaram amigos íntimos, tanto
quanto podiam sê-lo dois espíritos diferentes, ou talvez por
isso mesmo que o eram. Estêvão, dotado de extrema
sensibilidade, e não menor fraqueza de ânimo, afetuoso e
bom, não daquela bondade varonil, que é apanágio de uma alma
forte, mas dessa outra bondade mole e de cera, que vai à
mercê de todas as circunstâncias, tinha, além de tudo isso,
o infortúnio de trazer ainda sobre o nariz os óculos
cor-de-rosa de suas virginais ilusões. Luís Alves via bem
com os olhos da cara. Não era mau rapaz, mas tinha o seu
grão de egoísmo, e se não era incapaz de afeições, sabia
regê-las, moderá-las, e sobretudo guiá-las ao seu próprio
interesse. Entre estes dois homens travara-se amizade
íntima, nascida para um na simpatia, para outro no costume.
Eram eles os naturais confidentes um do outro, com a
diferença que Luís Alves dava menos do que recebia, e, ainda
assim, nem tudo o que dava exprimia grande confiança.
]]
local function random(handle, io_err)
if handle then
return function()
if not handle then error("source is empty!", 2) end
local len = math.random(0, 1024)
local chunk = handle:read(len)
if not chunk then
handle:close()
handle = nil
end
return chunk
end
else return ltn12.source.empty(io_err or "unable to open file") end
end
local function named(f)
return f
end
local what = nil
local function transform(input, output, filter)
local source = random(io.open(input, "rb"))
local sink = ltn12.sink.file(io.open(output, "wb"))
if what then
sink = ltn12.sink.chain(filter, sink)
else
source = ltn12.source.chain(source, filter)
end
--what = not what
ltn12.pump.all(source, sink)
end
local function encode_qptest(mode)
local encode = mime.encode("quoted-printable", mode)
local split = mime.wrap("quoted-printable")
local chain = ltn12.filter.chain(encode, split)
transform(qptest, eqptest, chain)
end
local function compare_qptest()
io.write("testing qp encoding and wrap: ")
compare(qptest, dqptest)
end
local function decode_qptest()
local decode = mime.decode("quoted-printable")
transform(eqptest, dqptest, decode)
end
local function create_qptest()
local f, err = io.open(qptest, "wb")
if not f then fail(err) end
-- try all characters
for i = 0, 255 do
f:write(string.char(i))
end
-- try all characters and different line sizes
for i = 0, 255 do
for j = 0, i do
f:write(string.char(i))
end
f:write("\r\n")
end
-- test latin text
f:write(mao)
-- force soft line breaks and treatment of space/tab in end of line
local tab
f:write(string.gsub(mao, "(%s)", function(c)
if tab then
tab = nil
return "\t"
else
tab = 1
return " "
end
end))
-- test crazy end of line conventions
local eol = { "\r\n", "\r", "\n", "\n\r" }
local which = 0
f:write(string.gsub(mao, "(\n)", function(c)
which = which + 1
if which > 4 then which = 1 end
return eol[which]
end))
for i = 1, 4 do
for j = 1, 4 do
f:write(eol[i])
f:write(eol[j])
end
end
-- try long spaced and tabbed lines
f:write("\r\n")
for i = 0, 255 do
f:write(string.char(9))
end
f:write("\r\n")
for i = 0, 255 do
f:write(' ')
end
f:write("\r\n")
for i = 0, 255 do
f:write(string.char(9),' ')
end
f:write("\r\n")
for i = 0, 255 do
f:write(' ',string.char(32))
end
f:write("\r\n")
f:close()
end
local function cleanup_qptest()
os.remove(qptest)
os.remove(eqptest)
os.remove(dqptest)
end
-- create test file
local function create_b64test()
local f = assert(io.open(b64test, "wb"))
local t = {}
for j = 1, 100 do
for i = 1, 100 do
t[i] = math.random(0, 255)
end
f:write(string.char(unpack(t)))
end
f:close()
end
local function encode_b64test()
local e1 = mime.encode("base64")
local e2 = mime.encode("base64")
local e3 = mime.encode("base64")
local e4 = mime.encode("base64")
local sp4 = mime.wrap()
local sp3 = mime.wrap(59)
local sp2 = mime.wrap("base64", 30)
local sp1 = mime.wrap(27)
local chain = ltn12.filter.chain(e1, sp1, e2, sp2, e3, sp3, e4, sp4)
transform(b64test, eb64test, chain)
end
local function decode_b64test()
local d1 = named(mime.decode("base64"), "d1")
local d2 = named(mime.decode("base64"), "d2")
local d3 = named(mime.decode("base64"), "d3")
local d4 = named(mime.decode("base64"), "d4")
local chain = named(ltn12.filter.chain(d1, d2, d3, d4), "chain")
transform(eb64test, db64test, chain)
end
local function cleanup_b64test()
os.remove(b64test)
os.remove(eb64test)
os.remove(db64test)
end
local function compare_b64test()
io.write("testing b64 chained encode: ")
compare(b64test, db64test)
end
local function identity_test()
io.write("testing identity: ")
local chain = named(ltn12.filter.chain(
named(mime.encode("quoted-printable"), "1 eq"),
named(mime.encode("base64"), "2 eb"),
named(mime.decode("base64"), "3 db"),
named(mime.decode("quoted-printable"), "4 dq")
), "chain")
transform(b64test, eb64test, chain)
compare(b64test, eb64test)
os.remove(eb64test)
end
local function padcheck(original, encoded)
local e = (mime.b64(original))
local d = (mime.unb64(encoded))
if e ~= encoded then fail("encoding failed") end
if d ~= original then fail("decoding failed") end
end
local function chunkcheck(original, encoded)
local len = string.len(original)
for i = 0, len do
local a = string.sub(original, 1, i)
local b = string.sub(original, i+1)
local e, r = mime.b64(a, b)
local f = (mime.b64(r))
if (e .. (f or "") ~= encoded) then fail(e .. (f or "")) end
end
end
local function padding_b64test()
io.write("testing b64 padding: ")
padcheck("a", "YQ==")
padcheck("ab", "YWI=")
padcheck("abc", "YWJj")
padcheck("abcd", "YWJjZA==")
padcheck("abcde", "YWJjZGU=")
padcheck("abcdef", "YWJjZGVm")
padcheck("abcdefg", "YWJjZGVmZw==")
padcheck("abcdefgh", "YWJjZGVmZ2g=")
padcheck("abcdefghi", "YWJjZGVmZ2hp")
padcheck("abcdefghij", "YWJjZGVmZ2hpag==")
chunkcheck("abcdefgh", "YWJjZGVmZ2g=")
chunkcheck("abcdefghi", "YWJjZGVmZ2hp")
chunkcheck("abcdefghij", "YWJjZGVmZ2hpag==")
print("ok")
end
local function test_b64lowlevel()
io.write("testing b64 low-level: ")
local a, b
a, b = mime.b64("", "")
assert(a == "" and b == "")
a, b = mime.b64(nil, "blablabla")
assert(a == nil and b == nil)
a, b = mime.b64("", nil)
assert(a == nil and b == nil)
a, b = mime.unb64("", "")
assert(a == "" and b == "")
a, b = mime.unb64(nil, "blablabla")
assert(a == nil and b == nil)
a, b = mime.unb64("", nil)
assert(a == nil and b == nil)
local binary=string.char(0x00,0x44,0x1D,0x14,0x0F,0xF4,0xDA,0x11,0xA9,0x78,0x00,0x14,0x38,0x50,0x60,0xCE)
local encoded = mime.b64(binary)
local decoded=mime.unb64(encoded)
assert(binary == decoded)
print("ok")
end
local t = socket.gettime()
create_b64test()
identity_test()
encode_b64test()
decode_b64test()
compare_b64test()
cleanup_b64test()
padding_b64test()
test_b64lowlevel()
create_qptest()
encode_qptest()
decode_qptest()
compare_qptest()
encode_qptest("binary")
decode_qptest()
compare_qptest()
cleanup_qptest()
print(string.format("done in %.2fs", socket.gettime() - t))
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.