repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278 values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15 values |
|---|---|---|---|---|---|
mehrpouya81/persianseed | plugins/banhammer.lua | 214 | 11956 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
local bots_protection = "Yes"
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function username_id(cb_extra, success, result)
local get_cmd = cb_extra.get_cmd
local receiver = cb_extra.receiver
local chat_id = cb_extra.chat_id
local member = cb_extra.member
local text = ''
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if member_id == our_id then return false end
if get_cmd == 'kick' then
if is_momod2(member_id, chat_id) then
return send_large_msg(receiver, "you can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) then
return send_large_msg(receiver, "you can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
return unbanall_user(member_id, chat_id)
end
end
end
return send_large_msg(receiver, text)
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
local receiver = get_receiver(msg)
if matches[1]:lower() == 'kickme' then-- /kickme
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return nil
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
if msg.to.type == 'chat' then
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(tonumber(matches[2]), msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'ban'
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
return
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
if msg.to.type == 'chat' then
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'unban'
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if msg.to.type == 'chat' then
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'kick'
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
else
return 'This isn\'t a chat group'
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
if msg.to.type == 'chat' then
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'banall'
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if msg.to.type == 'chat' then
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] removed from global ban list'
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'unbanall'
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Bb]anall) (.*)$",
"^[!/]([Bb]anall)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]banlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Uu]nbanall) (.*)$",
"^[!/]([Uu]nbanall)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
jbeich/Aquaria | files/scripts/maps/map_suntemple.lua | 6 | 1623 | -- 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()
if isFlag(FLAG_SUNTEMPLE_WATERLEVEL, 0) then
setWaterLevel(node_y(getNode("SUNTEMPLE_GEAR1")))
elseif isFlag(FLAG_SUNTEMPLE_WATERLEVEL, 1) then
setWaterLevel(node_y(getNode("SUNTEMPLE_GEAR2")))
else
setWaterLevel(node_y(getNode("SUNTEMPLE_GEAR3")))
end
debugLog(string.format("SunTemple: FLAG_SUNTEMPLE_WATERLEVEL was %d", getFlag(FLAG_SUNTEMPLE_WATERLEVEL)))
if isFlag(FLAG_SUNTEMPLE_LIGHTCRYSTAL, 1) then
local node = entity_getNearestNode(getNaija(), "LIGHTCRYSTAL_SPAWN")
if node ~= 0 then
createEntity("LightCrystalCharged", "", node_x(node), node_y(node))
end
local crystalHolder = getEntity("CrystalHolder")
if crystalHolder ~=0 then
entity_delete(crystalHolder)
end
end
end
| gpl-2.0 |
AquariaOSE/Aquaria | files/scripts/maps/map_suntemple.lua | 6 | 1623 | -- 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()
if isFlag(FLAG_SUNTEMPLE_WATERLEVEL, 0) then
setWaterLevel(node_y(getNode("SUNTEMPLE_GEAR1")))
elseif isFlag(FLAG_SUNTEMPLE_WATERLEVEL, 1) then
setWaterLevel(node_y(getNode("SUNTEMPLE_GEAR2")))
else
setWaterLevel(node_y(getNode("SUNTEMPLE_GEAR3")))
end
debugLog(string.format("SunTemple: FLAG_SUNTEMPLE_WATERLEVEL was %d", getFlag(FLAG_SUNTEMPLE_WATERLEVEL)))
if isFlag(FLAG_SUNTEMPLE_LIGHTCRYSTAL, 1) then
local node = entity_getNearestNode(getNaija(), "LIGHTCRYSTAL_SPAWN")
if node ~= 0 then
createEntity("LightCrystalCharged", "", node_x(node), node_y(node))
end
local crystalHolder = getEntity("CrystalHolder")
if crystalHolder ~=0 then
entity_delete(crystalHolder)
end
end
end
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Metalworks/npcs/Cid.lua | 14 | 11944 | -----------------------------------
-- Area: Metalworks
-- NPC: Cid
-- Starts & Finishes Quest: Cid's Secret, The Usual, Dark Puppet (start)
-- Involved in Mission: Bastok 7-1
-- @pos -12 -12 1 237
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/globals/quests");
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getCurrentMission(BASTOK) == THE_CRYSTAL_LINE and player:getVar("MissionStatus") == 1) then
if (trade:getItemQty(613,1) and trade:getItemCount() == 1) then
player:startEvent(0x01fa);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local currentday = tonumber(os.date("%j"));
local CidsSecret = player:getQuestStatus(BASTOK,CID_S_SECRET);
local LetterKeyItem = player:hasKeyItem(UNFINISHED_LETTER);
local currentMission = player:getCurrentMission(BASTOK);
local currentCOPMission = player:getCurrentMission(COP);
local UlmiaPath = player:getVar("COP_Ulmia_s_Path");
local TenzenPath = player:getVar("COP_Tenzen_s_Path");
local LouverancePath = player:getVar("COP_Louverance_s_Path");
local TreePathAv=0;
if (currentCOPMission == DAWN and player:getVar("PromathiaStatus")==3 and player:getVar("Promathia_kill_day")~=currentday and player:getVar("COP_tenzen_story")== 0 ) then
player:startEvent(0x0381); -- COP event
elseif (currentCOPMission == CALM_BEFORE_THE_STORM and player:hasKeyItem(LETTERS_FROM_ULMIA_AND_PRISHE) == false and player:getVar("COP_Dalham_KILL") == 2 and player:getVar("COP_Boggelmann_KILL") == 2 and player:getVar("Cryptonberry_Executor_KILL")==2) then
player:startEvent(0x037C); -- COP event
elseif (currentCOPMission == FIRE_IN_THE_EYES_OF_MEN and player:getVar("PromathiaStatus")==2 and player:getVar("Promathia_CID_timer")~=VanadielDayOfTheYear()) then
player:startEvent(0x037A); -- COP event
elseif (currentCOPMission == FIRE_IN_THE_EYES_OF_MEN and player:getVar("PromathiaStatus")==1) then
player:startEvent(0x0359); -- COP event
elseif (currentCOPMission == ONE_TO_BE_FEARED and player:getVar("PromathiaStatus")==0) then
player:startEvent(0x0358); -- COP event
elseif (currentCOPMission == THREE_PATHS and LouverancePath == 6 ) then
player:startEvent(0x0354); -- COP event
elseif (currentCOPMission == THREE_PATHS and LouverancePath == 9 ) then
if (TenzenPath==11 and UlmiaPath==8) then
TreePathAv=6;
elseif (TenzenPath==11) then
TreePathAv=2;
elseif (UlmiaPath==8) then
TreePathAv=4;
else
TreePathAv=1;
end
player:startEvent(0x0355,TreePathAv); -- COP event
elseif (currentCOPMission == THREE_PATHS and TenzenPath == 10 ) then
if (UlmiaPath==8 and LouverancePath==10) then
TreePathAv=5;
elseif (LouverancePath==10) then
TreePathAv=3;
elseif (UlmiaPath==8) then
TreePathAv=4;
else
TreePathAv=1;
end
player:startEvent(0x0356,TreePathAv); -- COP event
elseif (currentCOPMission == THREE_PATHS and UlmiaPath == 7 ) then
if (TenzenPath==11 and LouverancePath==10) then
TreePathAv=3;
elseif (LouverancePath==10) then
TreePathAv=1;
elseif (TenzenPath==11) then
TreePathAv=2;
else
TreePathAv=0;
end
player:startEvent(0x0357,TreePathAv); -- COP event
elseif (currentCOPMission == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus") > 8) then
player:startEvent(0x0352); -- COP event
elseif (currentCOPMission == THE_ENDURING_TUMULT_OF_WAR and player:getVar("PromathiaStatus")==1) then
player:startEvent(0x0351); -- COP event
elseif (currentCOPMission == THE_CALL_OF_THE_WYRMKING and player:getVar("PromathiaStatus")==1) then
player:startEvent(0x034D); -- COP event
elseif (currentCOPMission == THE_ROAD_FORKS and player:getVar("EMERALD_WATERS_Status")== 7 and player:getVar("MEMORIES_OF_A_MAIDEN_Status")== 12) then --two paths are finished ?
player:startEvent(0x034F); -- COP event 3.3
elseif (player:getMainJob() == JOBS.DRK and player:getMainLvl() >= AF2_QUEST_LEVEL and
player:getQuestStatus(BASTOK,DARK_LEGACY) == QUEST_COMPLETED and player:getQuestStatus(BASTOK,DARK_PUPPET) == QUEST_AVAILABLE) then
player:startEvent(0x02f8); -- Start Quest "Dark Puppet"
elseif (currentMission == GEOLOGICAL_SURVEY) then
if (player:hasKeyItem(RED_ACIDITY_TESTER)) then
player:startEvent(0x01f8);
elseif (player:hasKeyItem(BLUE_ACIDITY_TESTER) == false) then
player:startEvent(0x01f7);
end
elseif (currentMission == THE_CRYSTAL_LINE) then
if (player:hasKeyItem(C_L_REPORTS)) then
player:showText(npc,MISSION_DIALOG_CID_TO_AYAME);
else
player:startEvent(0x01f9);
end
elseif (currentMission == THE_FINAL_IMAGE and player:getVar("MissionStatus") == 0) then
player:startEvent(0x02fb); -- Bastok Mission 7-1
elseif (currentMission == THE_FINAL_IMAGE and player:getVar("MissionStatus") == 2) then
player:startEvent(0x02fc); -- Bastok Mission 7-1 (with Ki)
--Begin Cid's Secret
elseif (player:getFameLevel(BASTOK) >= 4 and CidsSecret == QUEST_AVAILABLE) then
player:startEvent(0x01fb);
elseif (CidsSecret == QUEST_ACCEPTED and LetterKeyItem == false and player:getVar("CidsSecret_Event") == 1) then
player:startEvent(0x01fc); --After talking to Hilda, Cid gives information on the item she needs
elseif (CidsSecret == QUEST_ACCEPTED and LetterKeyItem == false) then
player:startEvent(0x01f6); --Reminder dialogue from Cid if you have not spoken to Hilda
elseif (CidsSecret == QUEST_ACCEPTED and LetterKeyItem) then
player:startEvent(0x01fd);
--End Cid's Secret
else
player:startEvent(0x01f4); -- Standard Dialogue
end
end;
-- 0x01f7 0x01f8 0x01f9 0x01fa 0x01f4 0x01f6 0x02d0 0x01fb 0x01fc 0x01fd 0x025b 0x02f3 0x02f8 0x03f2 0x02fb 0x02fc
-- 0x030c 0x030e 0x031b 0x031c 0x031d 0x031e 0x031f 0x035d 0x034e 0x0350 0x035e 0x035f 0x0353 0x035a 0x034d 0x034f
-- 0x0351 0x0352 0x0354 0x0355 0x0356 0x0357 0x0358 0x0359 0x0364 0x0365 0x0373 0x0374 0x037a 0x037b 0x037c 0x037d
-- 0x037e 0x037f 0x0381 0x0382
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- local currentday = tonumber(os.date("%j"));
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0381) then
player:setVar("COP_tenzen_story",1);
elseif (csid == 0x037C) then
player:addKeyItem(LETTERS_FROM_ULMIA_AND_PRISHE);
player:messageSpecial(KEYITEM_OBTAINED,LETTERS_FROM_ULMIA_AND_PRISHE);
elseif (csid == 0x037A) then
player:setVar("PromathiaStatus",0);
player:setVar("Promathia_CID_timer",0);
player:completeMission(COP,FIRE_IN_THE_EYES_OF_MEN);
player:addMission(COP,CALM_BEFORE_THE_STORM);
elseif (csid == 0x0359) then
player:setVar("PromathiaStatus",2);
player:setVar("Promathia_CID_timer",VanadielDayOfTheYear());
elseif (csid == 0x0357) then
player:setVar("COP_Ulmia_s_Path",8);
elseif (csid == 0x0356) then
player:setVar("COP_Tenzen_s_Path",11);
elseif (csid == 0x0355) then
player:setVar("COP_Louverance_s_Path",10);
elseif (csid == 0x0354) then
player:setVar("COP_Louverance_s_Path",7);
elseif (csid == 0x0352) then
player:setVar("PromathiaStatus",0);
player:completeMission(COP,DESIRES_OF_EMPTINESS);
player:addMission(COP,THREE_PATHS);
elseif (csid == 0x0351) then
player:setVar("PromathiaStatus",2);
elseif (csid == 0x0358) then
player:setVar("PromathiaStatus",1);
elseif (csid == 0x034D) then
player:setVar("PromathiaStatus",0);
player:completeMission(COP,THE_CALL_OF_THE_WYRMKING);
player:addMission(COP,A_VESSEL_WITHOUT_A_CAPTAIN);
elseif (csid == 0x034F) then
-- finishing mission 3.3 and all sub missions
player:setVar("EMERALD_WATERS_Status",0);
player:setVar("MEMORIES_OF_A_MAIDEN_Status",0);
player:completeMission(COP,THE_ROAD_FORKS);
player:addMission(COP,DESCENDANTS_OF_A_LINE_LOST);
player:completeMission(COP,DESCENDANTS_OF_A_LINE_LOST);
player:addMission(COP,COMEDY_OF_ERRORS_ACT_I);
player:completeMission(COP,COMEDY_OF_ERRORS_ACT_I);
player:addMission(COP,TENDING_AGED_WOUNDS ); --starting 3.4 COP mission
elseif (csid == 0x02f8) then
player:addQuest(BASTOK,DARK_PUPPET);
player:setVar("darkPuppetCS",1);
elseif (csid == 0x01f7) then
player:addKeyItem(BLUE_ACIDITY_TESTER);
player:messageSpecial(KEYITEM_OBTAINED, BLUE_ACIDITY_TESTER);
elseif (csid == 0x01f8 or csid == 0x02fc) then
finishMissionTimeline(player,1,csid,option);
elseif (csid == 0x01f9 and option == 0) then
if (player:getVar("MissionStatus") == 0) then
if (player:getFreeSlotsCount(0) >= 1) then
crystal = math.random(4096,4103);
player:addItem(crystal);
player:messageSpecial(ITEM_OBTAINED, crystal);
player:setVar("MissionStatus",1);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,crystal);
end
end
elseif (csid == 0x01fa and option == 0) then
player:tradeComplete();
player:addKeyItem(C_L_REPORTS);
player:messageSpecial(KEYITEM_OBTAINED, C_L_REPORTS);
elseif (csid == 0x02fb) then
player:setVar("MissionStatus",1);
elseif (csid == 0x01fb) then
player:addQuest(BASTOK,CID_S_SECRET);
elseif (csid == 0x01fd) then
if (player:getFreeSlotsCount(0) >= 1) then
player:delKeyItem(UNFINISHED_LETTER);
player:setVar("CidsSecret_Event",0);
player:addItem(13570);
player:messageSpecial(ITEM_OBTAINED,13570); -- Ram Mantle
player:addFame(BASTOK,30);
player:completeQuest(BASTOK,CID_S_SECRET);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13570);
end
end
-- complete chapter "tree path"
if (csid == 0x0355 or csid == 0x0356 or csid == 0x0357) then
if (player:getVar("COP_Tenzen_s_Path")==11 and player:getVar("COP_Ulmia_s_Path")==8 and player:getVar("COP_Louverance_s_Path")==10) then
player:completeMission(COP,THREE_PATHS);
player:addMission(COP,FOR_WHOM_THE_VERSE_IS_SUNG);
player:setVar("PromathiaStatus",0);
end
end
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Quicksand_Caves/npcs/_5sa.lua | 14 | 1273 | -----------------------------------
-- Area: Quicksand Caves
-- NPC: Ornate Door
-- Door blocked by Weight system
-- @pos -418 0 790 208
-----------------------------------
package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Quicksand_Caves/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local difX = player:getXPos()-(-425);
local difZ = player:getZPos()-(790);
local Distance = math.sqrt( math.pow(difX,2) + math.pow(difZ,2) );
if (Distance < 3) then
return -1;
end
player:messageSpecial(DOOR_FIRMLY_SHUT);
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
nyczducky/darkstar | scripts/globals/zone.lua | 11 | 3195 | ------------------------------------
--
-- Contains global functions and variables
-- related to area specific things
--
------------------------------------
------------------------------------
-- zone related IDs
------------------------------------
-- Zone Types
ZONETYPE_NONE = 0
ZONETYPE_CITY = 1
ZONETYPE_OUTDOORS = 2
ZONETYPE_DUNGEON = 3
ZONETYPE_BATTLEFIELD = 4
ZONETYPE_DYNAMIS = 5
ZONETYPE_INSTANCED = 6
-- Continent Type
THE_MIDDLE_LANDS = 1
THE_ARADJIAH_CONTINENT = 2
THE_SHADOWREIGN_ERA = 3
OTHER_AREAS = 4
-- Region Types
REGION_RONFAURE = 0
REGION_ZULKHEIM = 1
REGION_NORVALLEN = 2
REGION_GUSTABERG = 3
REGION_DERFLAND = 4
REGION_SARUTABARUTA = 5
REGION_KOLSHUSHU = 6
REGION_ARAGONEU = 7
REGION_FAUREGANDI = 8
REGION_VALDEAUNIA = 9
REGION_QUFIMISLAND = 10
REGION_LITELOR = 11
REGION_KUZOTZ = 12
REGION_VOLLBOW = 13
REGION_ELSHIMOLOWLANDS = 14
REGION_ELSHIMOUPLANDS = 15
REGION_TULIA = 16
REGION_MOVALPOLOS = 17
REGION_TAVNAZIA = 18
REGION_SANDORIA = 19
REGION_BASTOK = 20
REGION_WINDURST = 21
REGION_JEUNO = 22
REGION_DYNAMIS = 23
REGION_TAVNAZIAN_MARQ = 24
REGION_PROMYVION = 25
REGION_LUMORIA = 26
REGION_LIMBUS = 27
REGION_WEST_AHT_URHGAN = 28
REGION_MAMOOL_JA_SAVAGE = 29
REGION_HALVUNG = 30
REGION_ARRAPAGO = 31
REGION_ALZADAAL = 32
REGION_RONFAURE_FRONT = 33
REGION_NORVALLEN_FRONT = 34
REGION_GUSTABERG_FRONT = 35
REGION_DERFLAND_FRONT = 36
REGION_SARUTA_FRONT = 37
REGION_ARAGONEAU_FRONT = 38
REGION_FAUREGANDI_FRONT = 39
REGION_VALDEAUNIA_FRONT = 40
REGION_ABYSSEA = 41
REGION_THE_THRESHOLD = 42
REGION_ABDHALJS = 43
REGION_ADOULIN_ISLANDS = 44
REGION_EAST_ULBUKA = 45
REGION_UNKNOWN = 255
-----------------------------------
-- SetExplorerMoogles
----------------------------------
function SetExplorerMoogles(moogle)
if (EXPLORER_MOOGLE == 1) then
local npc = GetNPCByID(moogle);
if (npc == nil) then
printf("'SetExplorerMoogles' Error trying to load undefined npc (%d)", moogle);
else
npc:setStatus(0);
end
end
end;
-----------------------------------
-- SetRespawnTime
----------------------------------
function SetRespawnTime(id, minTime, maxTime)
-- This function is redundant should place the mob:setRespawnTime() and UpdateNMSpawnPoint back in the individual zones.
-- Having this global just uses 3 functions where only 2 were needed.
local mob = GetMobByID(id);
if (mob == nil) then
printf("'SetTimedSpawns' Error trying to load undefined mob (%d)", id);
else
UpdateNMSpawnPoint(id);
mob:setRespawnTime(math.random((minTime),(maxTime)));
end
end
| gpl-3.0 |
dtrip/awesome | lib/wibox/widget/slider.lua | 2 | 14647 | ---------------------------------------------------------------------------
-- An interactive mouse based slider widget.
--
--@DOC_wibox_widget_defaults_slider_EXAMPLE@
--
-- @author Grigory Mishchenko <grishkokot@gmail.com>
-- @author Emmanuel Lepage Vallee <elv1313@gmail.com>
-- @copyright 2015 Grigory Mishchenko, 2016 Emmanuel Lepage Vallee
-- @widgetmod wibox.widget.slider
---------------------------------------------------------------------------
local setmetatable = setmetatable
local type = type
local color = require("gears.color")
local gtable = require("gears.table")
local beautiful = require("beautiful")
local base = require("wibox.widget.base")
local shape = require("gears.shape")
local capi = {
mouse = mouse,
mousegrabber = mousegrabber,
root = root,
}
local slider = {mt={}}
--- The slider handle shape.
--
--@DOC_wibox_widget_slider_handle_shape_EXAMPLE@
--
-- @property handle_shape
-- @tparam[opt=gears shape rectangle] gears.shape shape
-- @propemits true false
-- @propbeautiful
-- @see gears.shape
--- The slider handle color.
--
--@DOC_wibox_widget_slider_handle_color_EXAMPLE@
--
-- @property handle_color
-- @propbeautiful
-- @tparam color handle_color
-- @propemits true false
--- The slider handle margins.
--
--@DOC_wibox_widget_slider_handle_margins_EXAMPLE@
--
-- @property handle_margins
-- @tparam[opt={}] table margins
-- @tparam[opt=0] number margins.left
-- @tparam[opt=0] number margins.right
-- @tparam[opt=0] number margins.top
-- @tparam[opt=0] number margins.bottom
-- @propemits true false
-- @propbeautiful
--- The slider handle width.
--
--@DOC_wibox_widget_slider_handle_width_EXAMPLE@
--
-- @property handle_width
-- @tparam number handle_width
-- @propemits true false
-- @propbeautiful
--- The handle border_color.
--
--@DOC_wibox_widget_slider_handle_border_EXAMPLE@
--
-- @property handle_border_color
-- @tparam color handle_border_color
-- @propemits true false
-- @propbeautiful
--- The handle border width.
-- @property handle_border_width
-- @tparam[opt=0] number handle_border_width
-- @propemits true false
-- @propbeautiful
--- The bar (background) shape.
--
--@DOC_wibox_widget_slider_bar_shape_EXAMPLE@
--
-- @property bar_shape
-- @tparam[opt=gears shape rectangle] gears.shape shape
-- @propemits true false
-- @propbeautiful
-- @see gears.shape
--- The bar (background) height.
--
--@DOC_wibox_widget_slider_bar_height_EXAMPLE@
--
-- @property bar_height
-- @tparam number bar_height
-- @propbeautiful
-- @propemits true false
--- The bar (background) color.
--
--@DOC_wibox_widget_slider_bar_color_EXAMPLE@
--
-- @property bar_color
-- @tparam color bar_color
-- @propbeautiful
-- @propemits true false
--- The bar (active) color.
--
--@DOC_wibox_widget_slider_bar_active_color_EXAMPLE@
--
-- Only works when both `bar_active_color` and `bar_color` are passed as hex color string
-- @property bar_active_color
-- @tparam color bar_active_color
-- @propbeautiful
-- @propemits true false
--- The bar (background) margins.
--
--@DOC_wibox_widget_slider_bar_margins_EXAMPLE@
--
-- @property bar_margins
-- @tparam[opt={}] table margins
-- @tparam[opt=0] number margins.left
-- @tparam[opt=0] number margins.right
-- @tparam[opt=0] number margins.top
-- @tparam[opt=0] number margins.bottom
-- @propbeautiful
-- @propemits true false
--- The bar (background) border width.
-- @property bar_border_width
-- @tparam[opt=0] number bar_border_width
-- @propemits true false
--- The bar (background) border_color.
--
--@DOC_wibox_widget_slider_bar_border_EXAMPLE@
--
-- @property bar_border_color
-- @tparam color bar_border_color
-- @propbeautiful
-- @propemits true false
--- The slider value.
--
-- **Signal:** *property::value* notify the value is changed.
--
--@DOC_wibox_widget_slider_value_EXAMPLE@
--
-- @property value
-- @tparam[opt=0] number value
-- @propemits true false
--- The slider minimum value.
--
-- @property minimum
-- @tparam[opt=0] number minimum
-- @propemits true false
--- The slider maximum value.
--
-- @property maximum
-- @tparam[opt=100] number maximum
-- @propemits true false
--- The bar (background) border width.
--
-- @beautiful beautiful.slider_bar_border_width
-- @param number
--- The bar (background) border color.
--
-- @beautiful beautiful.slider_bar_border_color
-- @param color
--- The handle border_color.
--
-- @beautiful beautiful.slider_handle_border_color
-- @param color
--- The handle border width.
--
-- @beautiful beautiful.slider_handle_border_width
-- @param number
--- The handle width.
--
-- @beautiful beautiful.slider_handle_width
-- @param number
--- The handle color.
--
-- @beautiful beautiful.slider_handle_color
-- @param color
--- The handle shape.
--
-- @beautiful beautiful.slider_handle_shape
-- @tparam[opt=gears shape rectangle] gears.shape shape
-- @see gears.shape
--- The bar (background) shape.
--
-- @beautiful beautiful.slider_bar_shape
-- @tparam[opt=gears shape rectangle] gears.shape shape
-- @see gears.shape
--- The bar (background) height.
--
-- @beautiful beautiful.slider_bar_height
-- @param number
--- The bar (background) margins.
--
-- @beautiful beautiful.slider_bar_margins
-- @tparam[opt={}] table margins
-- @tparam[opt=0] number margins.left
-- @tparam[opt=0] number margins.right
-- @tparam[opt=0] number margins.top
-- @tparam[opt=0] number margins.bottom
--- The slider handle margins.
--
-- @beautiful beautiful.slider_handle_margins
-- @tparam[opt={}] table margins
-- @tparam[opt=0] number margins.left
-- @tparam[opt=0] number margins.right
-- @tparam[opt=0] number margins.top
-- @tparam[opt=0] number margins.bottom
--- The bar (background) color.
--
-- @beautiful beautiful.slider_bar_color
-- @param color
--- The bar (active) color.
--
-- Only works when both `beautiful.slider_bar_color` and `beautiful.slider_bar_active_color` are hex color strings
-- @beautiful beautiful.slider_bar_active_color
-- @param color
local properties = {
-- Handle
handle_shape = shape.rectangle,
handle_color = false,
handle_margins = {},
handle_width = false,
handle_border_width = 0,
handle_border_color = false,
-- Bar
bar_shape = shape.rectangle,
bar_height = false,
bar_color = false,
bar_active_color = false,
bar_margins = {},
bar_border_width = 0,
bar_border_color = false,
-- Content
value = 0,
minimum = 0,
maximum = 100,
}
-- Create the accessors
for prop in pairs(properties) do
slider["set_"..prop] = function(self, value)
local changed = self._private[prop] ~= value
self._private[prop] = value
if changed then
self:emit_signal("property::"..prop, value)
self:emit_signal("widget::redraw_needed")
end
end
slider["get_"..prop] = function(self)
-- Ignoring the false's is on purpose
return self._private[prop] == nil
and properties[prop]
or self._private[prop]
end
end
-- Add some validation to set_value
function slider:set_value(value)
value = math.min(value, self:get_maximum())
value = math.max(value, self:get_minimum())
local changed = self._private.value ~= value
self._private.value = value
if changed then
self:emit_signal( "property::value", value)
self:emit_signal( "widget::redraw_needed" )
end
end
local function get_extremums(self)
local min = self._private.minimum or properties.minimum
local max = self._private.maximum or properties.maximum
local interval = max - min
return min, max, interval
end
function slider:draw(_, cr, width, height)
local value = self._private.value or self._private.min or 0
local maximum = self._private.maximum
or properties.maximum
local minimum = self._private.minimum
or properties.minimum
local range = maximum - minimum
local active_rate = (value - minimum) / range
local handle_height, handle_width = height, self._private.handle_width
or beautiful.slider_handle_width
or height/2
local handle_border_width = self._private.handle_border_width
or beautiful.slider_handle_border_width
or properties.handle_border_width or 0
local bar_height = self._private.bar_height
-- If there is no background, then skip this
local bar_color = self._private.bar_color
or beautiful.slider_bar_color
local bar_active_color = self._private.bar_active_color
or beautiful.slider_bar_active_color
if bar_color then
cr:set_source(color(bar_color))
end
local margins = self._private.bar_margins
or beautiful.slider_bar_margins
local x_offset, right_margin, y_offset = 0, 0
if margins then
if type(margins) == "number" then
bar_height = bar_height or (height - 2*margins)
x_offset, y_offset = margins, margins
right_margin = margins
else
bar_height = bar_height or (
height - (margins.top or 0) - (margins.bottom or 0)
)
x_offset, y_offset = margins.left or 0, margins.top or 0
right_margin = margins.right or 0
end
else
bar_height = bar_height or beautiful.slider_bar_height or height
y_offset = (height - bar_height)/2
end
cr:translate(x_offset, y_offset)
local bar_shape = self._private.bar_shape
or beautiful.slider_bar_shape
or properties.bar_shape
local bar_border_width = self._private.bar_border_width
or beautiful.slider_bar_border_width
or properties.bar_border_width
bar_shape(cr, width - x_offset - right_margin, bar_height or height)
if bar_active_color and type(bar_color) == "string" and type(bar_active_color) == "string" then
local bar_active_width = active_rate * (width - x_offset - right_margin)
- (handle_width - handle_border_width/2) * (active_rate - 0.5)
cr:set_source(color.create_pattern{
type = "linear",
from = {0,0},
to = {bar_active_width, 0},
stops = {{0.99, bar_active_color}, {0.99, bar_color}}
})
end
if bar_color then
if bar_border_width == 0 then
cr:fill()
else
cr:fill_preserve()
end
end
-- Draw the bar border
if bar_border_width > 0 then
local bar_border_color = self._private.bar_border_color
or beautiful.slider_bar_border_color
or properties.bar_border_color
cr:set_line_width(bar_border_width)
if bar_border_color then
cr:save()
cr:set_source(color(bar_border_color))
cr:stroke()
cr:restore()
else
cr:stroke()
end
end
cr:translate(-x_offset, -y_offset)
-- Paint the handle
local handle_color = self._private.handle_color
or beautiful.slider_handle_color
-- It is ok if there is no color, it will be inherited
if handle_color then
cr:set_source(color(handle_color))
end
local handle_shape = self._private.handle_shape
or beautiful.slider_handle_shape
or properties.handle_shape
-- Lets get the margins for the handle
margins = self._private.handle_margins
or beautiful.slider_handle_margins
x_offset, y_offset = 0, 0
if margins then
if type(margins) == "number" then
x_offset, y_offset = margins, margins
handle_width = handle_width - 2*margins
handle_height = handle_height - 2*margins
else
x_offset, y_offset = margins.left or 0, margins.top or 0
handle_width = handle_width -
(margins.left or 0) - (margins.right or 0)
handle_height = handle_height -
(margins.top or 0) - (margins.bottom or 0)
end
end
-- Get the widget size back to it's non-transfored value
local min, _, interval = get_extremums(self)
local rel_value = ((value-min)/interval) * (width-handle_width)
cr:translate(x_offset + rel_value, y_offset)
handle_shape(cr, handle_width, handle_height)
if handle_border_width > 0 then
cr:fill_preserve()
else
cr:fill()
end
-- Draw the handle border
if handle_border_width > 0 then
local handle_border_color = self._private.handle_border_color
or beautiful.slider_handle_border_color
or properties.handle_border_color
if handle_border_color then
cr:set_source(color(handle_border_color))
end
cr:set_line_width(handle_border_width)
cr:stroke()
end
end
function slider:fit(_, width, height)
-- Use all the space, this should be used with a constraint widget
return width, height
end
-- Move the handle to the correct location
local function move_handle(self, width, x, _)
local _, _, interval = get_extremums(self)
self:set_value(math.floor((x*interval)/width))
end
local function mouse_press(self, x, y, button_id, _, geo)
if button_id ~= 1 then return end
local matrix_from_device = geo.hierarchy:get_matrix_from_device()
-- Sigh. geo.width/geo.height is in device space. We need it in our own
-- coordinate system
local width = geo.widget_width
move_handle(self, width, x, y)
-- Calculate a matrix transforming from screen coordinates into widget coordinates
local wgeo = geo.drawable.drawable:geometry()
local matrix = matrix_from_device:translate(-wgeo.x, -wgeo.y)
capi.mousegrabber.run(function(mouse)
if not mouse.buttons[1] then
return false
end
-- Calculate the point relative to the widget
move_handle(self, width, matrix:transform_point(mouse.x, mouse.y))
return true
end,"fleur")
end
--- Create a slider widget.
-- @tparam[opt={}] table args
-- @constructorfct wibox.widget.slider
local function new(args)
local ret = base.make_widget(nil, nil, {
enable_properties = true,
})
gtable.crush(ret._private, args or {})
gtable.crush(ret, slider, true)
ret:connect_signal("button::press", mouse_press)
return ret
end
function slider.mt:__call(_, ...)
return new(...)
end
--@DOC_widget_COMMON@
--@DOC_object_COMMON@
return setmetatable(slider, slider.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Garlaige_Citadel/Zone.lua | 9 | 3832 | -----------------------------------
--
-- Zone: Garlaige_Citadel (200)
--
-----------------------------------
package.loaded["scripts/zones/Garlaige_Citadel/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/zone");
require("scripts/zones/Garlaige_Citadel/TextIDs");
banishing_gates_base = 17596761; -- _5k0 (First banishing gate)
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
-- Banishing Gate #1...
zone:registerRegion(1,-208,-1,224,-206,1,227);
zone:registerRegion(2,-208,-1,212,-206,1,215);
zone:registerRegion(3,-213,-1,224,-211,1,227);
zone:registerRegion(4,-213,-1,212,-211,1,215);
-- Banishing Gate #2
zone:registerRegion(10,-51,-1,82,-49,1,84);
zone:registerRegion(11,-151,-1,82,-149,1,84);
zone:registerRegion(12,-51,-1,115,-49,1,117);
zone:registerRegion(13,-151,-1,115,-149,1,117);
-- Banishing Gate #3
zone:registerRegion(19,-190,-1,355,-188,1,357);
zone:registerRegion(20,-130,-1,355,-128,1,357);
zone:registerRegion(21,-190,-1,322,-188,1,324);
zone:registerRegion(22,-130,-1,322,-128,1,324);
-- Old Two-Wings
SetRespawnTime(17596506, 900, 10800);
-- Skewer Sam
SetRespawnTime(17596507, 900, 10800);
-- Serket
SetRespawnTime(17596720, 900, 10800);
UpdateTreasureSpawnPoint(17596812);
UpdateTreasureSpawnPoint(17596813);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-380.035,-13.548,398.032,64);
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
local regionID = region:GetRegionID();
local mylever = banishing_gates_base + regionID;
GetNPCByID(mylever):setAnimation(8);
if (regionID >= 1 and regionID <= 4) then
gateid = banishing_gates_base;
msg_offset = 0;
elseif (regionID >= 10 and regionID <= 13) then
gateid = banishing_gates_base + 9;
msg_offset = 1;
elseif (regionID >= 19 and regionID <= 22) then
gateid = banishing_gates_base + 18;
msg_offset = 2;
end;
-- Open Gate
gate1 = GetNPCByID(gateid + 1);
gate2 = GetNPCByID(gateid + 2);
gate3 = GetNPCByID(gateid + 3);
gate4 = GetNPCByID(gateid + 4);
if (gate1:getAnimation() == 8 and gate2:getAnimation() == 8 and gate3:getAnimation() == 8 and gate4:getAnimation() == 8) then
player:messageSpecial(BANISHING_GATES + msg_offset); -- Banishing gate opening
GetNPCByID(gateid):openDoor(30);
end
end;
-----------------------------------
-- onRegionLeave
-----------------------------------
function onRegionLeave(player,region)
local regionID = region:GetRegionID();
local mylever = banishing_gates_base + regionID;
GetNPCByID(mylever):setAnimation(9);
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 |
dtrip/awesome | tests/examples/wibox/nwidget/default.lua | 4 | 3116 | --DOC_GEN_IMAGE --DOC_HIDE_ALL
local parent = ...
local naughty = require("naughty")
local wibox = require("wibox")
local beautiful = require("beautiful")
local def = require("naughty.widget._default")
local acommon = require("awful.widget.common")
local aplace = require("awful.placement")
local gears = require("gears")
beautiful.notification_bg = beautiful.bg_normal
local notif = naughty.notification {
title = "A notification",
message = "This notification has actions!",
icon = beautiful.awesome_icon,
actions = {
naughty.action {
name = "Accept",
icon = beautiful.awesome_icon,
},
naughty.action {
name = "Refuse",
icon = beautiful.awesome_icon,
},
naughty.action {
name = "Ignore",
icon = beautiful.awesome_icon,
},
}
}
local default = wibox.widget(def)
acommon._set_common_property(default, "notification", notif)
local w, h = default:fit({dpi=96}, 9999, 9999)
default.forced_width = w + 25
default.forced_height = h
local canvas = wibox.layout.manual()
canvas.forced_width = w + 150
canvas.forced_height = h + 100
canvas:add_at(default, aplace.centered)
local function create_info(text, x, y, width, height)
canvas:add_at(wibox.widget {
{
{
text = text,
align = "center",
ellipsize = "none",
wrap = "word",
widget = wibox.widget.textbox
},
top = 2,
bottom = 2,
left = 10,
right = 10,
widget = wibox.container.margin
},
forced_width = width,
forced_height = height,
shape = gears.shape.rectangle,
shape_border_width = 1,
shape_border_color = beautiful.border_color,
bg = "#ffff0055",
widget = wibox.container.background
}, {x = x, y = y})
end
local function create_line(x1, y1, x2, y2)
return canvas:add_at(wibox.widget {
fit = function()
return x2-x1+6, y2-y1+6
end,
draw = function(_, _, cr)
cr:set_source_rgb(0,0,0)
cr:set_line_width(1)
cr:arc(1.5, 1.5, 1.5, 0, math.pi*2)
cr:arc(x2-x1+1.5, y2-y1+1.5, 1.5, 0, math.pi*2)
cr:fill()
cr:move_to(1.5,1.5)
cr:line_to(x2-x1+1.5, y2-y1+1.5)
cr:stroke()
end,
layout = wibox.widget.base.make_widget,
}, {x=x1, y=y1})
end
create_info("naughty.widget.background", 10, canvas.forced_height - 30, nil, nil)
create_line(80, canvas.forced_height-55, 80, canvas.forced_height - 30)
create_info("naughty.list.actions", 170, canvas.forced_height - 30, nil, nil)
create_line(200, canvas.forced_height-105, 200, canvas.forced_height - 30)
create_info("naughty.widget.icon", 20, 25, nil, nil)
create_line(80, 40, 80, 60)
create_info("naughty.widget.title", 90, 4, nil, nil)
create_line(140, 20, 140, 60)
create_info("naughty.widget.message", 150, 25, nil, nil)
create_line(210, 40, 210, 75)
parent:add(canvas)
| gpl-2.0 |
nyczducky/darkstar | scripts/globals/weaponskills/arching_arrow.lua | 12 | 1388 | -----------------------------------
-- Arching Arrow
-- Archery weapon skill
-- Skill level: 225
-- Delivers a single-hit attack. Chance of params.critical varies with TP.
-- Aligned with the Flame Gorget & Light Gorget.
-- Aligned with the Flame Belt & Light Belt.
-- Element: None
-- Modifiers: STR:16% ; AGI:25%
-- 100%TP 200%TP 300%TP
-- 3.50 3.50 3.50
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 1;
params.ftp100 = 3.5; params.ftp200 = 3.5; params.ftp300 = 3.5;
params.str_wsc = 0.16; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.25; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.1; params.crit200 = 0.3; params.crit300 = 0.5;
params.canCrit = true;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.20; params.agi_wsc = 0.50;
end
local damage, criticalHit, tpHits, extraHits = doRangedWeaponskill(player, target, wsID, params, tp, primary);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
ld-test/luarepl | repl/plugins/pretty_print.lua | 4 | 6617 | -- Copyright (c) 2011-2015 Rob Hoelz <rob@hoelz.ro>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy of
-- this software and associated documentation files (the "Software"), to deal in
-- the Software without restriction, including without limitation the rights to
-- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
-- the Software, and to permit persons to whom the Software is furnished to do so,
-- subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
-- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
-- COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
-- IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-- CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-- Pretty prints expression results (console only)
local format = string.format
local tconcat = table.concat
local tsort = table.sort
local tostring = tostring
local type = type
local floor = math.floor
local pairs = pairs
local ipairs = ipairs
local error = error
local stderr = io.stderr
pcall(require, 'luarocks.require')
local ok, term = pcall(require, 'term')
if not ok then
term = nil
end
local keywords = {
['and'] = true,
['break'] = true,
['do'] = true,
['else'] = true,
['elseif'] = true,
['end'] = true,
['false'] = true,
['for'] = true,
['function'] = true,
['if'] = true,
['in'] = true,
['local'] = true,
['nil'] = true,
['not'] = true,
['or'] = true,
['repeat'] = true,
['return'] = true,
['then'] = true,
['true'] = true,
['until'] = true,
['while'] = true,
}
local function compose(f, g)
return function(...)
return f(g(...))
end
end
local emptycolormap = setmetatable({}, { __index = function()
return function(s)
return s
end
end})
local colormap = emptycolormap
if term then
colormap = {
['nil'] = term.colors.blue,
string = term.colors.yellow,
punctuation = compose(term.colors.green, term.colors.bright),
ident = term.colors.red,
boolean = term.colors.green,
number = term.colors.cyan,
path = term.colors.white,
misc = term.colors.magenta,
}
end
local function isinteger(n)
return type(n) == 'number' and floor(n) == n
end
local function isident(s)
return type(s) == 'string' and not keywords[s] and s:match('^[a-zA-Z_][a-zA-Z0-9_]*$')
end
-- most of these are arbitrary, I *do* want numbers first, though
local type_order = {
number = 0,
string = 1,
userdata = 2,
table = 3,
thread = 4,
boolean = 5,
['function'] = 6,
cdata = 7,
}
local function cross_type_order(a, b)
local pos_a = type_order[ type(a) ]
local pos_b = type_order[ type(b) ]
if pos_a == pos_b then
return a < b
else
return pos_a < pos_b
end
end
local function sortedpairs(t)
local keys = {}
local seen_non_string
for k in pairs(t) do
keys[#keys + 1] = k
if not seen_non_string and type(k) ~= 'string' then
seen_non_string = true
end
end
local sort_func = seen_non_string and cross_type_order or nil
tsort(keys, sort_func)
local index = 1
return function()
if keys[index] == nil then
return nil
else
local key = keys[index]
local value = t[key]
index = index + 1
return key, value
end
end, keys
end
local function find_longstring_nest_level(s)
local level = 0
while s:find(']' .. string.rep('=', level) .. ']', 1, true) do
level = level + 1
end
return level
end
local function dump(params)
local pieces = params.pieces
local seen = params.seen
local path = params.path
local v = params.value
local indent = params.indent
local t = type(v)
if t == 'nil' or t == 'boolean' or t == 'number' then
pieces[#pieces + 1] = colormap[t](tostring(v))
elseif t == 'string' then
if v:match '\n' then
local level = find_longstring_nest_level(v)
pieces[#pieces + 1] = colormap.string('[' .. string.rep('=', level) .. '[' .. v .. ']' .. string.rep('=', level) .. ']')
else
pieces[#pieces + 1] = colormap.string(format('%q', v))
end
elseif t == 'table' then
if seen[v] then
pieces[#pieces + 1] = colormap.path(seen[v])
return
end
seen[v] = path
local lastintkey = 0
pieces[#pieces + 1] = colormap.punctuation '{\n'
for i, v in ipairs(v) do
for j = 1, indent do
pieces[#pieces + 1] = ' '
end
dump {
pieces = pieces,
seen = seen,
path = path .. '[' .. tostring(i) .. ']',
value = v,
indent = indent + 1,
}
pieces[#pieces + 1] = colormap.punctuation ',\n'
lastintkey = i
end
for k, v in sortedpairs(v) do
if not (isinteger(k) and k <= lastintkey and k > 0) then
for j = 1, indent do
pieces[#pieces + 1] = ' '
end
if isident(k) then
pieces[#pieces + 1] = colormap.ident(k)
else
pieces[#pieces + 1] = colormap.punctuation '['
dump {
pieces = pieces,
seen = seen,
path = path .. '.' .. tostring(k),
value = k,
indent = indent + 1,
}
pieces[#pieces + 1] = colormap.punctuation ']'
end
pieces[#pieces + 1] = colormap.punctuation ' = '
dump {
pieces = pieces,
seen = seen,
path = path .. '.' .. tostring(k),
value = v,
indent = indent + 1,
}
pieces[#pieces + 1] = colormap.punctuation ',\n'
end
end
for j = 1, indent - 1 do
pieces[#pieces + 1] = ' '
end
pieces[#pieces + 1] = colormap.punctuation '}'
else
pieces[#pieces + 1] = colormap.misc(tostring(v))
end
end
repl:requirefeature 'console'
function override:displayresults(results)
local pieces = {}
for i = 1, results.n do
dump {
pieces = pieces,
seen = {},
path = '<topvalue>',
value = results[i],
indent = 1,
}
pieces[#pieces + 1] = '\n'
end
stderr:write(tconcat(pieces, ''))
end
| mit |
alirezafodaji/tele-IR | plugins/plugins.lua | 88 | 6304 | do
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'. '..v..' '..status..'\n'
end
end
local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled'
return text
end
local function list_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..v..' '..status..'\n'
end
end
local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.'
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return 'Plugin '..plugin_name..' is enabled'
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return 'Plugin '..plugin_name..' does not exists'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return 'Plugin '..name..' does not exists'
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return 'Plugin '..name..' not enabled'
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return "Plugin doesn't exists"
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return 'Plugin '..plugin..' disabled on this chat'
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return 'This plugin is not disabled'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return 'Plugin '..plugin..' is enabled again'
end
local function run(msg, matches)
-- Show the available plugins
if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return list_all_plugins()
end
-- Re-enable a plugin for this chat
if matches[1] == 'enable' and matches[3] == 'chat' then
local receiver = get_receiver(msg)
local plugin = matches[2]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
-- Enable a plugin
if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
-- Disable a plugin on a chat
if matches[1] == 'disable' and matches[3] == 'chat' then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
end
-- Disable a plugin
if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[2] == 'plugins' then
return 'This plugin can\'t be disabled'
end
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
end
return {
description = "Plugin to manage other plugins. Enable, disable or reload.",
usage = {
moderator = {
"!plugins disable [plugin] chat : disable plugin only this chat.",
"!plugins enable [plugin] chat : enable plugin only this chat.",
},
sudo = {
"!plugins : list all plugins.",
"!plugins enable [plugin] : enable plugin.",
"!plugins disable [plugin] : disable plugin.",
"!plugins reload : reloads all plugins." },
},
patterns = {
"^!plugins$",
"^!plugins? (enable) ([%w_%.%-]+)$",
"^!plugins? (disable) ([%w_%.%-]+)$",
"^!plugins? (enable) ([%w_%.%-]+) (chat)",
"^!plugins? (disable) ([%w_%.%-]+) (chat)",
"^!plugins? (reload)$" },
run = run,
moderated = true, -- set to moderator mode
--privileged = true
}
end
--Copyright and edit; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
trelemar/Dither | lib/hump/gamestate.lua | 14 | 3533 | --[[
Copyright (c) 2010-2013 Matthias Richter
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]--
local function __NULL__() end
-- default gamestate produces error on every callback
local state_init = setmetatable({leave = __NULL__},
{__index = function() error("Gamestate not initialized. Use Gamestate.switch()") end})
local stack = {state_init}
local initialized_states = setmetatable({}, {__mode = "k"})
local state_is_dirty = true
local GS = {}
function GS.new(t) return t or {} end -- constructor - deprecated!
local function change_state(stack_offset, to, ...)
local pre = stack[#stack]
-- initialize only on first call
;(initialized_states[to] or to.init or __NULL__)(to)
initialized_states[to] = __NULL__
stack[#stack+stack_offset] = to
state_is_dirty = true
return (to.enter or __NULL__)(to, pre, ...)
end
function GS.switch(to, ...)
assert(to, "Missing argument: Gamestate to switch to")
assert(to ~= GS, "Can't call switch with colon operator")
;(stack[#stack].leave or __NULL__)(stack[#stack])
return change_state(0, to, ...)
end
function GS.push(to, ...)
assert(to, "Missing argument: Gamestate to switch to")
assert(to ~= GS, "Can't call push with colon operator")
return change_state(1, to, ...)
end
function GS.pop(...)
assert(#stack > 1, "No more states to pop!")
local pre, to = stack[#stack], stack[#stack-1]
stack[#stack] = nil
;(pre.leave or __NULL__)(pre)
state_is_dirty = true
return (to.resume or __NULL__)(to, pre, ...)
end
function GS.current()
return stack[#stack]
end
-- fetch event callbacks from love.handlers
local all_callbacks = { 'draw', 'errhand', 'update' }
for k in pairs(love.handlers) do
all_callbacks[#all_callbacks+1] = k
end
function GS.registerEvents(callbacks)
local registry = {}
callbacks = callbacks or all_callbacks
for _, f in ipairs(callbacks) do
registry[f] = love[f] or __NULL__
love[f] = function(...)
registry[f](...)
return GS[f](...)
end
end
end
-- forward any undefined functions
setmetatable(GS, {__index = function(_, func)
-- call function only if at least one 'update' was called beforehand
-- (see issue #46)
if not state_is_dirty or func == 'update' then
state_is_dirty = false
return function(...)
return (stack[#stack][func] or __NULL__)(stack[#stack], ...)
end
end
return __NULL__
end})
return GS
| mit |
benloz10/FinalFrontier | gamemodes/finalfrontier/gamemode/systems/medical.lua | 1 | 2730 | -- Copyright (c) 2014 Danni Lock [codednil@yahoo.co.uk]
--
-- 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/>.
SYS.FullName = "Medical Bay"
SYS.SGUIName = "medical"
SYS.Powered = true
function SYS:GetMaximumCharge()
return self._nwdata.maxcharge or 0
end
function SYS:GetCurrentCharge()
return math.min(self._nwdata.charge or 0, self._nwdata.maxcharge or 0)
end
if SERVER then
resource.AddFile("materials/systems/medical.png")
SYS._oldScore = 0
function SYS:Initialize()
self._nwdata.maxcharge = 1
self._nwdata.charge = 0
self._nwdata:Update()
end
function SYS:CalculatePowerNeeded()
local needed = 0
if self._nwdata.charge < self._nwdata.maxcharge then
needed = 6
end
return needed
end
function SYS:Think()
local needsUpdate = false
local score = self:GetRoom():GetModuleScore(moduletype.SYSTEM_POWER)
if score ~= self._oldScore then
self._oldScore = score
self._nwdata.maxcharge = score * 500
needsUpdate = true
end
if self._nwdata.charge < self._nwdata.maxcharge then
self._nwdata.charge = math.min(self._nwdata.maxcharge, self._nwdata.charge + self:GetPower() / 4)
needsUpdate = true
elseif self._nwdata.charge > self._nwdata.maxcharge then
self._nwdata.charge = self._nwdata.maxcharge
needsUpdate = true
end
if self._nwdata.charge >= 5 then
for _, ply in ipairs(player.GetAll()) do
if ply:GetRoom() == self:GetRoom() then
if (ply:Health() < ply:GetMaxHealth()) then
ply:SetHealth(math.min(ply:Health() + 1, ply:GetMaxHealth()))
self._nwdata.charge = self._nwdata.charge - 2
needsUpdate = true
end
if ply:GetPlyOxygen() < ply:GetPlyMaxOxygen() then
ply:SetPlyOxygen(ply:GetPlyOxygen() + 1)
self._nwdata.charge = self._nwdata.charge - 2
needsUpdate = true
end end
end
end
if needsUpdate then
self._nwdata:Update()
end
end
elseif CLIENT then
SYS.Icon = Material("systems/medical.png", "smooth")
end | lgpl-3.0 |
sjznxd/lc-20121231 | modules/admin-full/luasrc/model/cbi/admin_network/vlan.lua | 21 | 8152 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2010-2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
m = Map("network", translate("Switch"), translate("The network ports on this device can be combined to several <abbr title=\"Virtual Local Area Network\">VLAN</abbr>s in which computers can communicate directly with each other. <abbr title=\"Virtual Local Area Network\">VLAN</abbr>s are often used to separate different network segments. Often there is by default one Uplink port for a connection to the next greater network like the internet and other ports for a local network."))
local switches = { }
m.uci:foreach("network", "switch",
function(x)
local sid = x['.name']
local switch_name = x.name or sid
local has_vlan = nil
local has_learn = nil
local has_vlan4k = nil
local has_jumbo3 = nil
local min_vid = 0
local max_vid = 16
local num_vlans = 16
local num_ports = 6
local cpu_port = 5
local switch_title
local enable_vlan4k = false
-- Parse some common switch properties from swconfig help output.
local swc = io.popen("swconfig dev %q help 2>/dev/null" % switch_name)
if swc then
local is_port_attr = false
local is_vlan_attr = false
while true do
local line = swc:read("*l")
if not line then break end
if line:match("^%s+%-%-vlan") then
is_vlan_attr = true
elseif line:match("^%s+%-%-port") then
is_vlan_attr = false
is_port_attr = true
elseif line:match("cpu @") then
switch_title = line:match("^switch%d: %w+%((.-)%)")
num_ports, cpu_port, num_vlans =
line:match("ports: (%d+) %(cpu @ (%d+)%), vlans: (%d+)")
num_ports = tonumber(num_ports) or 6
num_vlans = tonumber(num_vlans) or 16
cpu_port = tonumber(cpu_port) or 5
min_vid = 1
elseif line:match(": pvid") or line:match(": tag") or line:match(": vid") then
if is_vlan_attr then has_vlan4k = line:match(": (%w+)") end
elseif line:match(": enable_vlan4k") then
enable_vlan4k = true
elseif line:match(": enable_vlan") then
has_vlan = "enable_vlan"
elseif line:match(": enable_learning") then
has_learn = "enable_learning"
elseif line:match(": max_length") then
has_jumbo3 = "max_length"
end
end
swc:close()
end
-- Switch properties
s = m:section(NamedSection, x['.name'], "switch",
switch_title and translatef("Switch %q (%s)", switch_name, switch_title)
or translatef("Switch %q", switch_name))
s.addremove = false
if has_vlan then
s:option(Flag, has_vlan, translate("Enable VLAN functionality"))
end
if has_learn then
x = s:option(Flag, has_learn, translate("Enable learning and aging"))
x.default = x.enabled
end
if has_jumbo3 then
x = s:option(Flag, has_jumbo3, translate("Enable Jumbo Frame passthrough"))
x.enabled = "3"
x.rmempty = true
end
-- VLAN table
s = m:section(TypedSection, "switch_vlan",
switch_title and translatef("VLANs on %q (%s)", switch_name, switch_title)
or translatef("VLANs on %q", switch_name))
s.template = "cbi/tblsection"
s.addremove = true
s.anonymous = true
-- Filter by switch
s.filter = function(self, section)
local device = m:get(section, "device")
return (device and device == switch_name)
end
-- Override cfgsections callback to enforce row ordering by vlan id.
s.cfgsections = function(self)
local osections = TypedSection.cfgsections(self)
local sections = { }
local section
for _, section in luci.util.spairs(
osections,
function(a, b)
return (tonumber(m:get(osections[a], has_vlan4k or "vlan")) or 9999)
< (tonumber(m:get(osections[b], has_vlan4k or "vlan")) or 9999)
end
) do
sections[#sections+1] = section
end
return sections
end
-- When creating a new vlan, preset it with the highest found vid + 1.
s.create = function(self, section, origin)
-- Filter by switch
if m:get(origin, "device") ~= switch_name then
return
end
local sid = TypedSection.create(self, section)
local max_nr = 0
local max_id = 0
m.uci:foreach("network", "switch_vlan",
function(s)
if s.device == switch_name then
local nr = tonumber(s.vlan)
local id = has_vlan4k and tonumber(s[has_vlan4k])
if nr ~= nil and nr > max_nr then max_nr = nr end
if id ~= nil and id > max_id then max_id = id end
end
end)
m:set(sid, "device", switch_name)
m:set(sid, "vlan", max_nr + 1)
if has_vlan4k then
m:set(sid, has_vlan4k, max_id + 1)
end
return sid
end
local port_opts = { }
local untagged = { }
-- Parse current tagging state from the "ports" option.
local portvalue = function(self, section)
local pt
for pt in (m:get(section, "ports") or ""):gmatch("%w+") do
local pc, tu = pt:match("^(%d+)([tu]*)")
if pc == self.option then return (#tu > 0) and tu or "u" end
end
return ""
end
-- Validate port tagging. Ensure that a port is only untagged once,
-- bail out if not.
local portvalidate = function(self, value, section)
-- ensure that the ports appears untagged only once
if value == "u" then
if not untagged[self.option] then
untagged[self.option] = true
elseif min_vid > 0 or tonumber(self.option) ~= cpu_port then -- enable multiple untagged cpu ports due to weird broadcom default setup
return nil,
translatef("Port %d is untagged in multiple VLANs!", tonumber(self.option) + 1)
end
end
return value
end
local vid = s:option(Value, has_vlan4k or "vlan", "VLAN ID", "<div id='portstatus-%s'></div>" % switch_name)
local mx_vid = has_vlan4k and 4094 or (num_vlans - 1)
vid.rmempty = false
vid.forcewrite = true
vid.vlan_used = { }
vid.datatype = "and(uinteger,range("..min_vid..","..mx_vid.."))"
-- Validate user provided VLAN ID, make sure its within the bounds
-- allowed by the switch.
vid.validate = function(self, value, section)
local v = tonumber(value)
local m = has_vlan4k and 4094 or (num_vlans - 1)
if v ~= nil and v >= min_vid and v <= m then
if not self.vlan_used[v] then
self.vlan_used[v] = true
return value
else
return nil,
translatef("Invalid VLAN ID given! Only unique IDs are allowed")
end
else
return nil,
translatef("Invalid VLAN ID given! Only IDs between %d and %d are allowed.", min_vid, m)
end
end
-- When writing the "vid" or "vlan" option, serialize the port states
-- as well and write them as "ports" option to uci.
vid.write = function(self, section, value)
local o
local p = { }
for _, o in ipairs(port_opts) do
local v = o:formvalue(section)
if v == "t" then
p[#p+1] = o.option .. v
elseif v == "u" then
p[#p+1] = o.option
end
end
if enable_vlan4k then
m:set(sid, "enable_vlan4k", "1")
end
m:set(section, "ports", table.concat(p, " "))
return Value.write(self, section, value)
end
-- Fallback to "vlan" option if "vid" option is supported but unset.
vid.cfgvalue = function(self, section)
return m:get(section, has_vlan4k or "vlan")
or m:get(section, "vlan")
end
-- Build per-port off/untagged/tagged choice lists.
local pt
for pt = 0, num_ports - 1 do
local title
if pt == cpu_port then
title = translate("CPU")
else
title = translatef("Port %d", pt)
end
local po = s:option(ListValue, tostring(pt), title)
po:value("", translate("off"))
po:value("u", translate("untagged"))
po:value("t", translate("tagged"))
po.cfgvalue = portvalue
po.validate = portvalidate
po.write = function() end
port_opts[#port_opts+1] = po
end
switches[#switches+1] = switch_name
end
)
-- Switch status template
s = m:section(SimpleSection)
s.template = "admin_network/switch_status"
s.switches = switches
return m
| apache-2.0 |
AquariaOSE/Aquaria | files/scripts/entities/_unused/queenhydra.lua | 6 | 3636 | -- 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
-- ================================================================================================
-- Q U E E N H Y D R A
-- ================================================================================================
-- ================================================================================================
-- L O C A L V A R I A B L E S
-- ================================================================================================
chaseDelay = 0
-- ================================================================================================
-- FUNCTIONS
-- ================================================================================================
function init()
setupBasicEntity(
"wurm-head", -- texture
15, -- health
1, -- manaballamount
2, -- exp
1, -- money
32, -- collideRadius (only used if hit entities is on)
STATE_IDLE, -- initState
256, -- sprite width
256, -- 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() -- fix the head orientation
if getFlag("Q1")==1 then
entity_delete()
else
entity_initSegments(
8, -- num segments
2, -- minDist
26, -- maxDist
"wurm-body", -- body tex
"wurm-tail", -- tail tex
256, -- width
256, -- height
0.05, -- taper
0 -- reverse segment direction
)
end
end
function update(dt)
if entity_hasTarget() then
if entity_isTargetInRange(64) then
entity_hurtTarget(1);
entity_pushTarget(400);
end
end
if chaseDelay > 0 then
chaseDelay = chaseDelay - dt
if chaseDelay < 0 then
chaseDelay = 0
end
end
if entity_getState()==STATE_IDLE then
if not entity_hasTarget() then
entity_findTarget(800)
else
if chaseDelay==0 then
if entity_isTargetInRange(1000) then
if entity_getHealth() < 4 then
entity_setMaxSpeed(600)
entity_moveTowardsTarget(dt, 1500)
else
entity_setMaxSpeed(400)
entity_moveTowardsTarget(dt, 1000)
end
else
entity_setMaxSpeed(100)
end
end
end
end
entity_doEntityAvoidance(dt, 200, 0.1)
if entity_getHealth() < 4 then
entity_doSpellAvoidance(dt, 64, 0.5);
end
entity_doCollisionAvoidance(dt, 5, 1)
entity_updateMovement(dt)
entity_rotateToVel(0.1)
end
function enterState()
if entity_getState()==STATE_IDLE then
elseif entity_getState()==STATE_DEAD then
conversation("Q1-BossDead")
setFlag("TransitActive", 1)
setFlag("Q1", 1)
end
end
function exitState()
end
function hitSurface()
end
| gpl-2.0 |
AquariaOSE/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 |
nyczducky/darkstar | scripts/zones/Southern_San_dOria/npcs/Rouva.lua | 14 | 1754 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Rouva
-- Involved in Quest: Lure of the Wildcat (San d'Oria)
-- @pos -17 2 10 230
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatSandy = player:getVar("WildcatSandy");
if (player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,2) == false) then
player:startEvent(0x0328);
else
player:startEvent(0x0298);
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 == 0x0328) then
player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",2,true);
end
end; | gpl-3.0 |
nyczducky/darkstar | scripts/globals/items/plate_of_boiled_barnacles_+1.lua | 12 | 1323 | -----------------------------------------
-- ID: 5981
-- Item: Plate of Boiled Barnacles +1
-- Food Effect: 60 Mins, All Races
-----------------------------------------
-- Charisma -2
-- Defense % 26 Cap 135
-----------------------------------------
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,5981);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_CHR, -2);
target:addMod(MOD_FOOD_DEFP, 26);
target:addMod(MOD_FOOD_DEF_CAP, 135);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_CHR, -2);
target:delMod(MOD_FOOD_DEFP, 26);
target:delMod(MOD_FOOD_DEF_CAP, 135);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Caedarva_Mire/npcs/Nareema.lua | 18 | 2118 | -----------------------------------
-- Area: Caedarva Mire
-- NPC: Nareema
-- Type: Assault
-- @pos 518.387 -24.707 -467.297 79
-----------------------------------
package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Caedarva_Mire/TextIDs");
require("scripts/globals/missions");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local IPpoint = player:getCurrency("imperial_standing");
if (player:getCurrentMission(TOAU) == IMMORTAL_SENTRIES) then
if (player:hasKeyItem(SUPPLIES_PACKAGE)) then
player:startEvent(5,1);
elseif (player:getVar("AhtUrganStatus") == 1) then
player:startEvent(6,1);
end
elseif (player:getCurrentMission(TOAU) >= PRESIDENT_SALAHEEM) then
if (player:hasKeyItem(LEUJAOAM_ASSAULT_ORDERS) and player:hasKeyItem(ASSAULT_ARMBAND) == false) then
player:startEvent(149,50,IPpoint);
else
player:startEvent(7,1);
-- player:delKeyItem(ASSAULT_ARMBAND);
end
else
player:startEvent(4);
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 == 5 and option == 1) then
player:delKeyItem(SUPPLIES_PACKAGE);
player:setVar("AhtUrganStatus",1);
elseif (csid == 149 and option == 1) then
player:delCurrency("imperial_standing", 50);
player:addKeyItem(ASSAULT_ARMBAND);
player:messageSpecial(KEYITEM_OBTAINED,ASSAULT_ARMBAND);
end
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Port_Bastok/Zone.lua | 26 | 3589 | -----------------------------------
--
-- Zone: Port_Bastok (236)
--
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/zone");
require("scripts/globals/settings");
require("scripts/globals/missions");
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
zone:registerRegion(1,-112,-3,-17,-96,3,-3);--event COP
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
-- FIRST LOGIN (START CS)
if (player:getPlaytime(false) == 0) then
if (OPENING_CUTSCENE_ENABLE == 1) then
cs = 0x0001;
end
player:setPos(132,-8.5,-13,179);
player:setHomePoint();
end
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
if (prevZone == 224) then
cs = 0x0049;
player:setPos(-36.000, 7.000, -58.000, 194);
else
position = math.random(1,5) + 57;
player:setPos(position,8.5,-239,192);
if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then
cs = 0x7534;
end
player:setVar("PlayerMainJob",0);
end
end
if (player:getCurrentMission(COP) == THE_ENDURING_TUMULT_OF_WAR and player:getVar("PromathiaStatus") == 0) then
cs = 0x0132;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
local regionID =region:GetRegionID();
-- printf("regionID: %u",regionID);
if (regionID == 1 and player:getCurrentMission(COP) == THE_CALL_OF_THE_WYRMKING and player:getVar("PromathiaStatus") == 0) then
player:startEvent(0x0131);
end
end;
-----------------------------------
-- onRegionLeave
-----------------------------------
function onRegionLeave(player,region)
end;
-----------------------------------
-- onTransportEvent
-----------------------------------
function onTransportEvent(player,transport)
player:startEvent(0x0047);
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 == 0x0001) then
player:messageSpecial(ITEM_OBTAINED,536);
elseif (csid == 0x0047) then
player:setPos(0,0,0,0,224);
elseif (csid == 0x7534 and option == 0) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
elseif (csid == 0x0131) then
player:setVar("PromathiaStatus",1);
elseif (csid == 0x0132) then
player:setVar("COP_optional_CS_chasalvigne",0);
player:setVar("COP_optional_CS_Anoki",0);
player:setVar("COP_optional_CS_Despachaire",0);
player:setVar("PromathiaStatus",1);
end
end; | gpl-3.0 |
moltafet35/senatorv2 | 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 |
Arashbrsh/lifeeee | 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 |
starius/lpjit | benchmark/test_parenthesis.lua | 1 | 1139 | local lpeg = require 'lpeg'
local lpjit = require 'lpjit'
local function genParenthesis()
local abc = 'qwertyuiop[sdfghjklvbnmxcv56789\n'
local t = {}
math.randomseed(0)
for i = 1, 50 do
table.insert(t, '(')
end
for i = 1, 10000 do
if math.random(1, 2) == 1 then
table.insert(t, '(')
else
table.insert(t, ')')
end
if math.random(1, 2) == 1 then
local c = math.random(1, #abc)
table.insert(t, abc:sub(c, c))
end
end
return table.concat(t)
end
local text = genParenthesis()
local report = '%s %d %.10f'
local pattern = lpeg.P {
"(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")"
}
local t1 = os.clock()
local res = pattern:match(text)
local t2 = os.clock()
print(report:format('lpeg', res, t2 - t1))
local pattern2 = lpjit.compile(pattern)
local t1 = os.clock()
local res = pattern2:match(text)
local t2 = os.clock()
print(report:format('asm ', res, t2 - t1))
local t1 = os.clock()
local check = text:match('%b()')
local t2 = os.clock()
print(report:format('lua ', #check, t2 - t1))
assert(res == #check + 1)
| mit |
SamOatesPlugins/cuberite | Server/Plugins/NetworkTest/NetworkTest.lua | 7 | 17057 |
-- NetworkTest.lua
-- Implements a few tests for the cNetwork API
--- Map of all servers currently open
-- g_Servers[PortNum] = cServerHandle
local g_Servers = {}
--- Map of all UDP endpoints currently open
-- g_UDPEndpoints[PortNum] = cUDPEndpoint
local g_UDPEndpoints = {}
--- List of fortune messages for the fortune server
-- A random message is chosen for each incoming connection
-- The contents are loaded from the splashes.txt file on plugin startup
local g_Fortunes =
{
"Empty splashes.txt",
}
-- HTTPS certificate to be used for the SSL server:
local g_HTTPSCert = [[
-----BEGIN CERTIFICATE-----
MIIDfzCCAmegAwIBAgIJAOBHN+qOWodcMA0GCSqGSIb3DQEBBQUAMFYxCzAJBgNV
BAYTAmN6MQswCQYDVQQIDAJjejEMMAoGA1UEBwwDbG9jMQswCQYDVQQKDAJfWDEL
MAkGA1UECwwCT1UxEjAQBgNVBAMMCWxvY2FsaG9zdDAeFw0xNTAxMjQwODQ2MzFa
Fw0yNTAxMjEwODQ2MzFaMFYxCzAJBgNVBAYTAmN6MQswCQYDVQQIDAJjejEMMAoG
A1UEBwwDbG9jMQswCQYDVQQKDAJfWDELMAkGA1UECwwCT1UxEjAQBgNVBAMMCWxv
Y2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJkFYSElu/jw
nxqjimmj246DejKJK8uy/l9QQibb/Z4kO/3s0gVPOYo0mKv32xUFP7wYIE3XWT61
zyfvK+1jpnlQTCtM8T5xw/7CULKgLmuIzlQx5Dhy7d+tW46kOjFKwQajS9YzwqWu
KBOPnFamQWz6vIzuM05+7aIMXbzamInvW/1x3klIrpGQgALwSB1N+oUzTInTBRKK
21pecUE9t3qrU40Cs5bN0fQBnBjLwbgmnTh6LEplfQZHG5wLvj0IeERVU9vH7luM
e9/IxuEZluCiu5ViF3jqLPpjYOrkX7JDSKme64CCmNIf0KkrwtFjF104Qylike60
YD3+kw8Q+DECAwEAAaNQME4wHQYDVR0OBBYEFHHIDTc7mrLDXftjQ5ejU9Udfdyo
MB8GA1UdIwQYMBaAFHHIDTc7mrLDXftjQ5ejU9UdfdyoMAwGA1UdEwQFMAMBAf8w
DQYJKoZIhvcNAQEFBQADggEBAHxCJxZPmH9tvx8GKiDV3rgGY++sMItzrW5Uhf0/
bl3DPbVz51CYF8nXiWvSJJzxhH61hKpZiqvRlpyMuovV415dYQ+Xc2d2IrTX6e+d
Z4Pmwfb4yaX+kYqIygjXMoyNxOJyhTnCbJzycV3v5tvncBWN9Wqez6ZonWDdFdAm
J+Moty+atc4afT02sUg1xz+CDr1uMbt62tHwKYCdxXCwT//bOs6W21+mQJ5bEAyA
YrHQPgX76uo8ed8rPf6y8Qj//lzq/+33EIWqf9pnbklQgIPXJU07h+5L+Y63RF4A
ComLkzas+qnQLcEN28Dg8QElXop6hfiD0xq3K0ac2bDnjoU=
-----END CERTIFICATE-----
]]
local g_HTTPSPrivKey = [[
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCZBWEhJbv48J8a
o4ppo9uOg3oyiSvLsv5fUEIm2/2eJDv97NIFTzmKNJir99sVBT+8GCBN11k+tc8n
7yvtY6Z5UEwrTPE+ccP+wlCyoC5riM5UMeQ4cu3frVuOpDoxSsEGo0vWM8KlrigT
j5xWpkFs+ryM7jNOfu2iDF282piJ71v9cd5JSK6RkIAC8EgdTfqFM0yJ0wUSitta
XnFBPbd6q1ONArOWzdH0AZwYy8G4Jp04eixKZX0GRxucC749CHhEVVPbx+5bjHvf
yMbhGZbgoruVYhd46iz6Y2Dq5F+yQ0ipnuuAgpjSH9CpK8LRYxddOEMpYpHutGA9
/pMPEPgxAgMBAAECggEAWxQ4m+I54BJYoSJ2YCqHpGvdb/b1emkvvsumlDqc2mP2
0U0ENOTS+tATj0gXvotBRFOX5r0nAYx1oO9a1hFaJRsGOz+w19ofLqO6JJfzCU6E
gNixXmgJ7fjhZiWZ/XzhJ3JK0VQ9px/h+sKf63NJvfQABmJBZ5dlGe8CXEZARNin
03TnE3RUIEK+jEgwShN2OrGjwK9fjcnXMHwEnKZtCBiYEfD2N+pQmS20gIm13L1t
+ZmObIC24NqllXxl4I821qzBdhmcT7+rGmKR0OT5YKbt6wFA5FPKD9dqlzXzlKck
r2VAh+JlCtFKxcScmWtQOnVDtf5+mcKFbP4ck724AQKBgQDLk+RDhvE5ykin5R+B
dehUQZgHb2pPL7N1DAZShfzwSmyZSOPQDFr7c0CMijn6G0Pw9VX6Vrln0crfTQYz
Hli+zxlmcMAD/WC6VImM1LCUzouNRy37rSCnuPtngZyHdsyzfheGnjORH7HlPjtY
JCTLaekg0ckQvt//HpRV3DCdaQKBgQDAbLmIOTyGfne74HLswWnY/kCOfFt6eO+E
lZ724MWmVPWkxq+9rltC2CDx2i8jjdkm90dsgR5OG2EaLnUWldUpkE0zH0ATrZSV
ezJWD9SsxTm8ksbThD+pJKAVPxDAboejF7kPvpaO2wY+bf0AbO3M24rJ2tccpMv8
AcfXBICDiQKBgQCSxp81/I3hf7HgszaC7ZLDZMOK4M6CJz847aGFUCtsyAwCfGYb
8zyJvK/WZDam14+lpA0IQAzPCJg/ZVZJ9uA/OivzCum2NrHNxfOiQRrLPxuokaBa
q5k2tA02tGE53fJ6mze1DEzbnkFxqeu5gd2xdzvpOLfBxgzT8KU8PlQiuQKBgGn5
NvCj/QZhDhYFVaW4G1ArLmiKamL3yYluUV7LiW7CaYp29gBzzsTwfKxVqhJdo5NH
KinCrmr7vy2JGmj22a+LTkjyU/rCZQsyDxXAoDMKZ3LILwH8WocPqa4pzlL8TGzw
urXGE+rXCwhE0Mp0Mz7YRgZHJKMcy06duG5dh11pAoGBALHbsBIDihgHPyp2eKMP
K1f42MdKrTBiIXV80hv2OnvWVRCYvnhrqpeRMzCR1pmVbh+QhnwIMAdWq9PAVTTn
ypusoEsG8Y5fx8xhgjs0D2yMcrmi0L0kCgHIFNoym+4pI+sv6GgxpemfrmaPNcMx
DXi9JpaquFRJLGJ7jMCDgotL
-----END PRIVATE KEY-----
]]
--- Map of all services that can be run as servers
-- g_Services[ServiceName] = function() -> accept-callbacks
local g_Services =
{
-- Echo service: each connection echoes back what has been sent to it
echo = function (a_Port)
return
{
-- A new connection has come, give it new link-callbacks:
OnIncomingConnection = function (a_RemoteIP, a_RemotePort)
return
{
OnError = function (a_Link, a_ErrorCode, a_ErrorMsg)
LOG("EchoServer(" .. a_Port .. ": Connection to " .. a_Link:GetRemoteIP() .. ":" .. a_Link:GetRemotePort() .. " failed: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")")
end,
OnReceivedData = function (a_Link, a_Data)
-- Echo the received data back to the link:
a_Link:Send(a_Data)
end,
OnRemoteClosed = function (a_Link)
end
} -- Link callbacks
end, -- OnIncomingConnection()
-- Send a welcome message to newly accepted connections:
OnAccepted = function (a_Link)
a_Link:Send("Hello, " .. a_Link:GetRemoteIP() .. ", welcome to the echo server @ MCServer-Lua\r\n")
end, -- OnAccepted()
-- There was an error listening on the port:
OnError = function (a_ErrorCode, a_ErrorMsg)
LOGINFO("EchoServer(" .. a_Port .. ": Cannot listen: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")")
end, -- OnError()
} -- Listen callbacks
end, -- echo
-- Fortune service: each incoming connection gets a welcome message plus a random fortune text; all communication is ignored afterwards
fortune = function (a_Port)
return
{
-- A new connection has come, give it new link-callbacks:
OnIncomingConnection = function (a_RemoteIP, a_RemotePort)
return
{
OnError = function (a_Link, a_ErrorCode, a_ErrorMsg)
LOG("FortuneServer(" .. a_Port .. "): Connection to " .. a_Link:GetRemoteIP() .. ":" .. a_Link:GetRemotePort() .. " failed: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")")
end,
OnReceivedData = function (a_Link, a_Data)
-- Ignore any received data
end,
OnRemoteClosed = function (a_Link)
end
} -- Link callbacks
end, -- OnIncomingConnection()
-- Send a welcome message and the fortune to newly accepted connections:
OnAccepted = function (a_Link)
a_Link:Send("Hello, " .. a_Link:GetRemoteIP() .. ", welcome to the fortune server @ MCServer-Lua\r\n\r\nYour fortune:\r\n")
a_Link:Send(g_Fortunes[math.random(#g_Fortunes)] .. "\r\n")
end, -- OnAccepted()
-- There was an error listening on the port:
OnError = function (a_ErrorCode, a_ErrorMsg)
LOGINFO("FortuneServer(" .. a_Port .. "): Cannot listen: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")")
end, -- OnError()
} -- Listen callbacks
end, -- fortune
-- HTTPS time - serves current time for each https request received
httpstime = function (a_Port)
return
{
-- A new connection has come, give it new link-callbacks:
OnIncomingConnection = function (a_RemoteIP, a_RemotePort)
local IncomingData = "" -- accumulator for the incoming data, until processed by the http
return
{
OnError = function (a_Link, a_ErrorCode, a_ErrorMsg)
LOG("https-time server(" .. a_Port .. "): Connection to " .. a_Link:GetRemoteIP() .. ":" .. a_Link:GetRemotePort() .. " failed: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")")
end,
OnReceivedData = function (a_Link, a_Data)
IncomingData = IncomingData .. a_Data
if (IncomingData:find("\r\n\r\n")) then
-- We have received the entire request headers, just send the response and shutdown the link:
local Content = os.date()
a_Link:Send("HTTP/1.0 200 OK\r\nContent-type: text/plain\r\nContent-length: " .. #Content .. "\r\n\r\n" .. Content)
a_Link:Shutdown()
end
end,
OnRemoteClosed = function (a_Link)
LOG("httpstime: link closed by remote")
end
} -- Link callbacks
end, -- OnIncomingConnection()
-- Start TLS on the new link:
OnAccepted = function (a_Link)
local res, msg = a_Link:StartTLSServer(g_HTTPSCert, g_HTTPSPrivKey, "")
if not(res) then
LOG("https-time server(" .. a_Port .. "): Cannot start TLS server: " .. msg)
a_Link:Close()
end
end, -- OnAccepted()
-- There was an error listening on the port:
OnError = function (a_ErrorCode, a_ErrorMsg)
LOGINFO("https-time server(" .. a_Port .. "): Cannot listen: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")")
end, -- OnError()
} -- Listen callbacks
end, -- httpstime
-- TODO: Other services (daytime, ...)
}
function Initialize(a_Plugin)
-- Load the splashes.txt file into g_Fortunes, overwriting current content:
local idx = 1
for line in io.lines(a_Plugin:GetLocalFolder() .. "/splashes.txt") do
g_Fortunes[idx] = line
idx = idx + 1
end
-- Use the InfoReg shared library to process the Info.lua file:
dofile(cPluginManager:GetPluginsPath() .. "/InfoReg.lua")
RegisterPluginInfoCommands()
RegisterPluginInfoConsoleCommands()
-- Seed the random generator:
math.randomseed(os.time())
return true
end
function HandleConsoleNetClient(a_Split)
-- Get the address to connect to:
local Host = a_Split[3] or "google.com"
local Port = a_Split[4] or 80
-- Create the callbacks "personalised" for the address:
local Callbacks =
{
OnConnected = function (a_Link)
LOG("Connected to " .. Host .. ":" .. Port .. ".")
LOG("Connection stats: Remote address: " .. a_Link:GetRemoteIP() .. ":" .. a_Link:GetRemotePort() .. ", Local address: " .. a_Link:GetLocalIP() .. ":" .. a_Link:GetLocalPort())
LOG("Sending HTTP request for front page.")
a_Link:Send("GET / HTTP/1.0\r\nHost: " .. Host .. "\r\n\r\n")
end,
OnError = function (a_Link, a_ErrorCode, a_ErrorMsg)
LOG("Connection to " .. Host .. ":" .. Port .. " failed: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")")
end,
OnReceivedData = function (a_Link, a_Data)
LOG("Received data from " .. Host .. ":" .. Port .. ":\r\n" .. a_Data)
end,
OnRemoteClosed = function (a_Link)
LOG("Connection to " .. Host .. ":" .. Port .. " was closed by the remote peer.")
end
}
-- Queue a connect request:
local res = cNetwork:Connect(Host, Port, Callbacks)
if not(res) then
LOGWARNING("cNetwork:Connect call failed immediately")
return true
end
return true, "Client connection request queued."
end
function HandleConsoleNetClose(a_Split)
-- Get the port to close:
local Port = tonumber(a_Split[3] or 1024)
if not(Port) then
return true, "Bad port number: \"" .. a_Split[3] .. "\"."
end
-- Close the server, if there is one:
if not(g_Servers[Port]) then
return true, "There is no server currently listening on port " .. Port .. "."
end
g_Servers[Port]:Close()
g_Servers[Port] = nil
return true, "Port " .. Port .. " closed."
end
function HandleConsoleNetIps(a_Split)
local Addresses = cNetwork:EnumLocalIPAddresses()
LOG("IP addresses enumerated, " .. #Addresses .. " found")
for idx, addr in ipairs(Addresses) do
LOG(" IP #" .. idx .. ": " .. addr)
end
return true
end
function HandleConsoleNetLookup(a_Split)
-- Get the name to look up:
local Addr = a_Split[3] or "google.com"
-- Create the callbacks "personalised" for the host:
local Callbacks =
{
OnNameResolved = function (a_Hostname, a_IP)
LOG(a_Hostname .. " resolves to " .. a_IP)
end,
OnError = function (a_Query, a_ErrorCode, a_ErrorMsg)
LOG("Failed to retrieve information for " .. a_Query .. ": " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")")
assert(a_Query == Addr)
end,
OnFinished = function (a_Query)
LOG("Resolving " .. a_Query .. " has finished.")
assert(a_Query == Addr)
end,
}
-- Queue both name and IP DNS queries;
-- we don't distinguish between an IP and a hostname in this command so we don't know which one to use:
local res = cNetwork:HostnameToIP(Addr, Callbacks)
if not(res) then
LOGWARNING("cNetwork:HostnameToIP call failed immediately")
return true
end
res = cNetwork:IPToHostname(Addr, Callbacks)
if not(res) then
LOGWARNING("cNetwork:IPToHostname call failed immediately")
return true
end
return true, "DNS query has been queued."
end
function HandleConsoleNetListen(a_Split)
-- Get the params:
local Port = tonumber(a_Split[3] or 1024)
if not(Port) then
return true, "Invalid port: \"" .. a_Split[3] .. "\"."
end
local Service = string.lower(a_Split[4] or "echo")
-- Create the callbacks specific for the service:
if (g_Services[Service] == nil) then
return true, "No such service: " .. Service
end
local Callbacks = g_Services[Service](Port)
-- Start the server:
local srv = cNetwork:Listen(Port, Callbacks)
if not(srv:IsListening()) then
-- The error message has already been printed in the Callbacks.OnError()
return true
end
g_Servers[Port] = srv
return true, Service .. " server started on port " .. Port
end
function HandleConsoleNetSClient(a_Split)
-- Get the address to connect to:
local Host = a_Split[3] or "github.com"
local Port = a_Split[4] or 443
-- Create the callbacks "personalised" for the address:
local Callbacks =
{
OnConnected = function (a_Link)
LOG("Connected to " .. Host .. ":" .. Port .. ".")
LOG("Connection stats: Remote address: " .. a_Link:GetRemoteIP() .. ":" .. a_Link:GetRemotePort() .. ", Local address: " .. a_Link:GetLocalIP() .. ":" .. a_Link:GetLocalPort())
LOG("Sending HTTP request for front page.")
a_Link:StartTLSClient()
a_Link:Send("GET / HTTP/1.0\r\nHost: " .. Host .. "\r\n\r\n")
end,
OnError = function (a_Link, a_ErrorCode, a_ErrorMsg)
LOG("Connection to " .. Host .. ":" .. Port .. " failed: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")")
end,
OnReceivedData = function (a_Link, a_Data)
LOG("Received data from " .. Host .. ":" .. Port .. ":\r\n" .. a_Data)
end,
OnRemoteClosed = function (a_Link)
LOG("Connection to " .. Host .. ":" .. Port .. " was closed by the remote peer.")
end
}
-- Queue a connect request:
local res = cNetwork:Connect(Host, Port, Callbacks)
if not(res) then
LOGWARNING("cNetwork:Connect call failed immediately")
return true
end
return true, "SSL Client connection request queued."
end
function HandleConsoleNetUdpClose(a_Split)
-- Get the port to close:
local Port = tonumber(a_Split[4] or 1024)
if not(Port) then
return true, "Bad port number: \"" .. a_Split[4] .. "\"."
end
-- Close the server, if there is one:
if not(g_UDPEndpoints[Port]) then
return true, "There is no UDP endpoint currently listening on port " .. Port .. "."
end
g_UDPEndpoints[Port]:Close()
g_UDPEndpoints[Port] = nil
return true, "UDP Port " .. Port .. " closed."
end
function HandleConsoleNetUdpListen(a_Split)
-- Get the params:
local Port = tonumber(a_Split[4] or 1024)
if not(Port) then
return true, "Invalid port: \"" .. a_Split[4] .. "\"."
end
local Callbacks =
{
OnReceivedData = function (a_Endpoint, a_Data, a_RemotePeer, a_RemotePort)
LOG("Incoming UDP datagram from " .. a_RemotePeer .. " port " .. a_RemotePort .. ":\r\n" .. a_Data)
end,
OnError = function (a_Endpoint, a_ErrorCode, a_ErrorMsg)
LOG("Error in UDP endpoint: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")")
end,
}
g_UDPEndpoints[Port] = cNetwork:CreateUDPEndpoint(Port, Callbacks)
return true, "UDP listener on port " .. Port .. " started."
end
function HandleConsoleNetUdpSend(a_Split)
-- Get the params:
local Host = a_Split[4] or "localhost"
local Port = tonumber(a_Split[5] or 1024)
if not(Port) then
return true, "Invalid port: \"" .. a_Split[5] .. "\"."
end
local Message
if (a_Split[6]) then
Message = table.concat(a_Split, " ", 6)
else
Message = "hello"
end
-- Define minimum callbacks for the UDP endpoint:
local Callbacks =
{
OnError = function (a_Endpoint, a_ErrorCode, a_ErrorMsg)
LOG("Error in UDP datagram sending: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")")
end,
OnReceivedData = function ()
-- ignore
end,
}
-- Send the data:
local Endpoint = cNetwork:CreateUDPEndpoint(0, Callbacks)
Endpoint:EnableBroadcasts()
if not(Endpoint:Send(Message, Host, Port)) then
Endpoint:Close()
return true, "Sending UDP datagram failed"
end
Endpoint:Close()
return true, "UDP datagram sent"
end
function HandleConsoleNetWasc(a_Split)
local Callbacks =
{
OnConnected = function (a_Link)
LOG("Connected to webadmin, starting TLS...")
local res, msg = a_Link:StartTLSClient("", "", "")
if not(res) then
LOG("Failed to start TLS client: " .. msg)
return
end
-- We need to send a keep-alive due to #1737
a_Link:Send("GET / HTTP/1.0\r\nHost: localhost\r\nConnection: keep-alive\r\n\r\n")
end,
OnError = function (a_Link, a_ErrorCode, a_ErrorMsg)
LOG("Connection to webadmin failed: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")")
end,
OnReceivedData = function (a_Link, a_Data)
LOG("Received data from webadmin:\r\n" .. a_Data)
-- Close the link once all the data is received:
if (a_Data == "0\r\n\r\n") then -- Poor man's end-of-data detection; works on localhost
-- TODO: The Close() method is not yet exported to Lua
-- a_Link:Close()
end
end,
OnRemoteClosed = function (a_Link)
LOG("Connection to webadmin was closed")
end,
}
if not(cNetwork:Connect("localhost", "8080", Callbacks)) then
LOG("Canot connect to webadmin")
end
return true
end
| apache-2.0 |
nyczducky/darkstar | scripts/globals/items/dish_of_spaghetti_ortolana.lua | 12 | 1559 | -----------------------------------------
-- ID: 5658
-- Item: Dish of Spafhetti Ortolana
-- Food Effect: 30 Mins, All Races
-----------------------------------------
-- Agility 2
-- Vitality 2
-- HP +30% Cap 70
-- StoreTP +6
-- Resist Blind +10
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5658);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_VIT, 2);
target:addMod(MOD_AGI, 2);
target:addMod(MOD_FOOD_HPP, 30);
target:addMod(MOD_FOOD_HP_CAP, 70);
target:addMod(MOD_STORETP, 6);
target:addMod(MOD_BLINDRES, 10);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_VIT, 2);
target:delMod(MOD_AGI, 2);
target:delMod(MOD_FOOD_HPP, 30);
target:delMod(MOD_FOOD_HP_CAP, 70);
target:delMod(MOD_STORETP, 6);
target:delMod(MOD_BLINDRES, 10);
end;
| gpl-3.0 |
jbeich/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 |
sjznxd/lc-20121231 | applications/luci-olsr/luasrc/model/cbi/olsr/olsrdhna.lua | 78 | 1844 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2011 Manuel Munz <freifunk at somakoma dot de>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local uci = require "luci.model.uci".cursor()
local ipv = uci:get_first("olsrd", "olsrd", "IpVersion", "4")
mh = Map("olsrd", translate("OLSR - HNA-Announcements"), translate("Hosts in a OLSR routed network can announce connecitivity " ..
"to external networks using HNA messages."))
if ipv == "6and4" or ipv == "4" then
hna4 = mh:section(TypedSection, "Hna4", translate("Hna4"), translate("Both values must use the dotted decimal notation."))
hna4.addremove = true
hna4.anonymous = true
hna4.template = "cbi/tblsection"
net4 = hna4:option(Value, "netaddr", translate("Network address"))
net4.datatype = "ip4addr"
net4.placeholder = "10.11.12.13"
net4.default = "10.11.12.13"
msk4 = hna4:option(Value, "netmask", translate("Netmask"))
msk4.datatype = "ip4addr"
msk4.placeholder = "255.255.255.255"
msk4.default = "255.255.255.255"
end
if ipv == "6and4" or ipv == "6" then
hna6 = mh:section(TypedSection, "Hna6", translate("Hna6"), translate("IPv6 network must be given in full notation, " ..
"prefix must be in CIDR notation."))
hna6.addremove = true
hna6.anonymous = true
hna6.template = "cbi/tblsection"
net6 = hna6:option(Value, "netaddr", translate("Network address"))
net6.datatype = "ip6addr"
net6.placeholder = "fec0:2200:106:0:0:0:0:0"
net6.default = "fec0:2200:106:0:0:0:0:0"
msk6 = hna6:option(Value, "prefix", translate("Prefix"))
msk6.datatype = "range(0,128)"
msk6.placeholder = "128"
msk6.default = "128"
end
return mh
| apache-2.0 |
rovemonteux/score_framework | src/instruments/guitar.lua | 1 | 17712 | -------------------------------------------------------------------------------
---- Score Framework - A Lua-based framework for creating multi-track MIDI files.
---- Copyright (c) 2017 Rove Monteux
----
---- This program is free software; you can redistribute it and/or modify it
---- under the terms of the GNU General Public License as published by the Free
---- Software Foundation; either version 3 of the License, or (at your option)
---- any later version.
----
---- This program is distributed in the hope that it will be useful, but WITHOUT
---- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
---- FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
---- more details.
----
---- You should have received a copy of the GNU General Public License along
---- with this program; if not, see <http://www.gnu.org/licenses/>.
---------------------------------------------------------------------------------
package.path = package.path .. ";../?.lua"
require 'data/notes'
function guitar_0_0 (timeline, noteduration, notevelocity, position, channel)
note_e2 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_0_1 (timeline, noteduration, notevelocity, position, channel)
note_f2 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_0_2 (timeline, noteduration, notevelocity, position, channel)
note_fs2 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_0_3 (timeline, noteduration, notevelocity, position, channel)
note_g2 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_0_4 (timeline, noteduration, notevelocity, position, channel)
note_gs2 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_0_5 (timeline, noteduration, notevelocity, position, channel)
note_a2 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_0_6 (timeline, noteduration, notevelocity, position, channel)
note_as2 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_0_7 (timeline, noteduration, notevelocity, position, channel)
note_b2 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_0_8 (timeline, noteduration, notevelocity, position, channel)
note_c3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_0_9 (timeline, noteduration, notevelocity, position, channel)
note_cs3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_0_10 (timeline, noteduration, notevelocity, position, channel)
note_d3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_0_11 (timeline, noteduration, notevelocity, position, channel)
note_ds3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_0_12 (timeline, noteduration, notevelocity, position, channel)
note_e3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_0_13 (timeline, noteduration, notevelocity, position, channel)
note_f3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_0_14 (timeline, noteduration, notevelocity, position, channel)
note_fs3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_0_15 (timeline, noteduration, notevelocity, position, channel)
note_g3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_1_0 (timeline, noteduration, notevelocity, position, channel)
note_a2 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_1_1 (timeline, noteduration, notevelocity, position, channel)
note_as2 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_1_2 (timeline, noteduration, notevelocity, position, channel)
note_b2 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_1_3 (timeline, noteduration, notevelocity, position, channel)
note_c3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_1_4 (timeline, noteduration, notevelocity, position, channel)
note_cs3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_1_5 (timeline, noteduration, notevelocity, position, channel)
note_d3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_1_6 (timeline, noteduration, notevelocity, position, channel)
note_ds3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_1_7 (timeline, noteduration, notevelocity, position, channel)
note_e3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_1_8 (timeline, noteduration, notevelocity, position, channel)
note_f3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_1_9 (timeline, noteduration, notevelocity, position, channel)
note_fs3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_1_10 (timeline, noteduration, notevelocity, position, channel)
note_g3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_1_11 (timeline, noteduration, notevelocity, position, channel)
note_gs3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_1_12 (timeline, noteduration, notevelocity, position, channel)
note_a3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_1_13 (timeline, noteduration, notevelocity, position, channel)
note_as3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_1_14 (timeline, noteduration, notevelocity, position, channel)
note_b3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_1_15 (timeline, noteduration, notevelocity, position, channel)
note_c4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_2_0 (timeline, noteduration, notevelocity, position, channel)
note_d3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_2_1 (timeline, noteduration, notevelocity, position, channel)
note_ds3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_2_2 (timeline, noteduration, notevelocity, position, channel)
note_e3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_2_3 (timeline, noteduration, notevelocity, position, channel)
note_f3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_2_4 (timeline, noteduration, notevelocity, position, channel)
note_fs3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_2_5 (timeline, noteduration, notevelocity, position, channel)
note_g3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_2_6 (timeline, noteduration, notevelocity, position, channel)
note_gs3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_2_7 (timeline, noteduration, notevelocity, position, channel)
note_a3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_2_8 (timeline, noteduration, notevelocity, position, channel)
note_as3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_2_9 (timeline, noteduration, notevelocity, position, channel)
note_b3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_2_10 (timeline, noteduration, notevelocity, position, channel)
note_c4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_2_11 (timeline, noteduration, notevelocity, position, channel)
note_cs4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_2_12 (timeline, noteduration, notevelocity, position, channel)
note_d4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_2_13 (timeline, noteduration, notevelocity, position, channel)
note_ds4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_2_14 (timeline, noteduration, notevelocity, position, channel)
note_e4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_2_15 (timeline, noteduration, notevelocity, position, channel)
note_f4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_3_0 (timeline, noteduration, notevelocity, position, channel)
note_g3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_3_1 (timeline, noteduration, notevelocity, position, channel)
note_gs3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_3_2 (timeline, noteduration, notevelocity, position, channel)
note_a3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_3_3 (timeline, noteduration, notevelocity, position, channel)
note_as3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_3_4 (timeline, noteduration, notevelocity, position, channel)
note_b3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_3_5 (timeline, noteduration, notevelocity, position, channel)
note_c4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_3_6 (timeline, noteduration, notevelocity, position, channel)
note_cs4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_3_7 (timeline, noteduration, notevelocity, position, channel)
note_d4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_3_8 (timeline, noteduration, notevelocity, position, channel)
note_ds4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_3_9 (timeline, noteduration, notevelocity, position, channel)
note_e4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_3_10 (timeline, noteduration, notevelocity, position, channel)
note_f4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_3_11 (timeline, noteduration, notevelocity, position, channel)
note_fs4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_3_12 (timeline, noteduration, notevelocity, position, channel)
note_g4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_3_13 (timeline, noteduration, notevelocity, position, channel)
note_gs4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_3_14 (timeline, noteduration, notevelocity, position, channel)
note_a4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_3_15 (timeline, noteduration, notevelocity, position, channel)
note_as4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_0_0 (timeline, noteduration, notevelocity, position, channel)
guitar_0_0 (timeline, noteduration, notevelocity, position, channel)
guitar_1_2 (timeline, noteduration, notevelocity, position, channel)
guitar_2_2 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_0_1 (timeline, noteduration, notevelocity, position, channel)
guitar_0_1 (timeline, noteduration, notevelocity, position, channel)
guitar_1_3 (timeline, noteduration, notevelocity, position, channel)
guitar_2_3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_0_2 (timeline, noteduration, notevelocity, position, channel)
guitar_0_2 (timeline, noteduration, notevelocity, position, channel)
guitar_1_4 (timeline, noteduration, notevelocity, position, channel)
guitar_2_4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_0_3 (timeline, noteduration, notevelocity, position, channel)
guitar_0_3 (timeline, noteduration, notevelocity, position, channel)
guitar_1_5 (timeline, noteduration, notevelocity, position, channel)
guitar_2_5 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_0_4 (timeline, noteduration, notevelocity, position, channel)
guitar_0_4 (timeline, noteduration, notevelocity, position, channel)
guitar_1_6 (timeline, noteduration, notevelocity, position, channel)
guitar_2_6 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_0_5 (timeline, noteduration, notevelocity, position, channel)
guitar_0_5 (timeline, noteduration, notevelocity, position, channel)
guitar_1_7 (timeline, noteduration, notevelocity, position, channel)
guitar_2_7 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_0_6 (timeline, noteduration, notevelocity, position, channel)
guitar_0_6 (timeline, noteduration, notevelocity, position, channel)
guitar_1_8 (timeline, noteduration, notevelocity, position, channel)
guitar_2_8 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_0_7 (timeline, noteduration, notevelocity, position, channel)
guitar_0_7 (timeline, noteduration, notevelocity, position, channel)
guitar_1_9 (timeline, noteduration, notevelocity, position, channel)
guitar_2_9 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_0_8 (timeline, noteduration, notevelocity, position, channel)
guitar_0_8 (timeline, noteduration, notevelocity, position, channel)
guitar_1_10 (timeline, noteduration, notevelocity, position, channel)
guitar_2_10 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_0_9 (timeline, noteduration, notevelocity, position, channel)
guitar_0_9 (timeline, noteduration, notevelocity, position, channel)
guitar_1_11 (timeline, noteduration, notevelocity, position, channel)
guitar_2_11 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_0_10 (timeline, noteduration, notevelocity, position, channel)
guitar_0_10 (timeline, noteduration, notevelocity, position, channel)
guitar_1_12 (timeline, noteduration, notevelocity, position, channel)
guitar_2_12 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_1_0 (timeline, noteduration, notevelocity, position, channel)
guitar_1_0 (timeline, noteduration, notevelocity, position, channel)
guitar_2_2 (timeline, noteduration, notevelocity, position, channel)
guitar_3_2 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_1_1 (timeline, noteduration, notevelocity, position, channel)
guitar_1_1 (timeline, noteduration, notevelocity, position, channel)
guitar_2_3 (timeline, noteduration, notevelocity, position, channel)
guitar_3_3 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_1_2 (timeline, noteduration, notevelocity, position, channel)
guitar_1_2 (timeline, noteduration, notevelocity, position, channel)
guitar_2_4 (timeline, noteduration, notevelocity, position, channel)
guitar_3_4 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_1_3 (timeline, noteduration, notevelocity, position, channel)
guitar_1_3 (timeline, noteduration, notevelocity, position, channel)
guitar_2_5 (timeline, noteduration, notevelocity, position, channel)
guitar_3_5 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_1_4 (timeline, noteduration, notevelocity, position, channel)
guitar_1_4 (timeline, noteduration, notevelocity, position, channel)
guitar_2_6 (timeline, noteduration, notevelocity, position, channel)
guitar_3_6 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_1_5 (timeline, noteduration, notevelocity, position, channel)
guitar_1_5 (timeline, noteduration, notevelocity, position, channel)
guitar_2_7 (timeline, noteduration, notevelocity, position, channel)
guitar_3_7 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_1_6 (timeline, noteduration, notevelocity, position, channel)
guitar_1_6 (timeline, noteduration, notevelocity, position, channel)
guitar_2_8 (timeline, noteduration, notevelocity, position, channel)
guitar_3_8 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_1_7 (timeline, noteduration, notevelocity, position, channel)
guitar_1_7 (timeline, noteduration, notevelocity, position, channel)
guitar_2_9 (timeline, noteduration, notevelocity, position, channel)
guitar_3_9 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_1_8 (timeline, noteduration, notevelocity, position, channel)
guitar_1_8 (timeline, noteduration, notevelocity, position, channel)
guitar_2_10 (timeline, noteduration, notevelocity, position, channel)
guitar_3_10 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_1_9 (timeline, noteduration, notevelocity, position, channel)
guitar_1_9 (timeline, noteduration, notevelocity, position, channel)
guitar_2_11 (timeline, noteduration, notevelocity, position, channel)
guitar_3_11 (timeline, noteduration, notevelocity, position, channel)
end
function guitar_chord_1_10 (timeline, noteduration, notevelocity, position, channel)
guitar_1_10 (timeline, noteduration, notevelocity, position, channel)
guitar_2_12 (timeline, noteduration, notevelocity, position, channel)
guitar_3_12 (timeline, noteduration, notevelocity, position, channel)
end | gpl-3.0 |
francot514/CardGamePRO-Simulator | data/cards/c1184.lua | 1 | 1268 | --Awanw sword
function c1184.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c1184.cost)
e1:SetTarget(c1184.target)
e1:SetOperation(c1184.activate)
c:RegisterEffect(e1)
end
function c1184.cfilter(c)
return c:IsFaceup() and c:IsAttribute(CIV_BABYLONIAN)
end
function c1184.sfilter(c,e,tp)
return c:IsCode(1504) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c1184.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckReleaseGroup(tp,nil,2,nil) end
local rg=Duel.SelectReleaseGroup(tp,c1184.cfilter,2,2,nil)
Duel.Release(rg,REASON_COST)
end
function c1184.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c1184.sfilter,tp,LOCATION_EXTRA,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA)
end
function c1184.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.SelectMatchingCard(tp,c1184.sfilter,tp,LOCATION_EXTRA,0,1,1,nil,e,tp)
local tc=g:GetFirst()
if tc and Duel.GetLocationCount(tp,LOCATION_MZONE)>-1 then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP_ATTACK)
end
end | gpl-2.0 |
lgeek/koreader | frontend/optmath.lua | 5 | 1502 | --[[--
Simple math helper functions
]]
local Math = {}
function Math.roundAwayFromZero(num)
if num > 0 then
return math.ceil(num)
else
return math.floor(num)
end
end
function Math.round(num)
return math.floor(num + 0.5)
end
function Math.oddEven(number)
if number % 2 == 1 then
return "odd"
else
return "even"
end
end
local function tmin_max(tab, func, op)
if #tab == 0 then return nil, nil end
local index, value = 1, tab[1]
for i = 2, #tab do
if func then
if func(value, tab[i]) then
index, value = i, tab[i]
end
elseif op == "min" then
if value > tab[i] then
index, value = i, tab[i]
end
elseif op == "max" then
if value < tab[i] then
index, value = i, tab[i]
end
end
end
return index, value
end
--[[--
Returns the minimum element of a table.
The optional argument func specifies a one-argument ordering function.
@tparam table tab
@tparam func func
@treturn dynamic minimum element of a table
]]
function Math.tmin(tab, func)
return tmin_max(tab, func, "min")
end
--[[--
Returns the maximum element of a table.
The optional argument func specifies a one-argument ordering function.
@tparam table tab
@tparam func func
@treturn dynamic maximum element of a table
]]
function Math.tmax(tab, func)
return tmin_max(tab, func, "max")
end
return Math
| agpl-3.0 |
ld-test/vararg | vararg.lua | 6 | 3305 | local math = require "math"
local table = require "table"
local error, assert, select = error, assert, select
local max, unpack = math.max, table.unpack or unpack
local setmetatable = setmetatable
local tinsert2 = function(t, n, i, v)
-- lua 5.2 rise error if index out of range
-- assert(type(t) =='table')
-- assert(type(n) =='number')
-- assert(type(i) =='number')
if i > n then
t[i] = v
return i
end
for j = n, i, -1 do
t[j + 1] = t[j]
end
t[i] = v
return n+1
end
local tremove2 = function(t, n, i)
-- lua 5.2 rise error if index out of range
-- assert(type(t) =='table')
-- assert(type(n) =='number')
-- assert(type(i) =='number')
if i > n then
for j = n+1, i do
t[j] = nil
end
return n
end
for j = i, n do
t[j] = t[j+1]
end
return n-1
end
local function idx(i, n, d)
if i == nil then
if not d then
return error("number expected, got nil", 2)
end
return d
end
if i < 0 then
i = n+i+1
end
if i <= 0 then
return error("index out of bounds", 2)
end
return i
end
local function pack(...)
local n = select("#", ...)
local v = {...}
return function(...)
if (...) == "#" then
return n
else
local argc = select("#", ...)
if argc == 0 then
return unpack(v, 1, n)
else
local i, j = ...
if i == nil then
if j == nil then j = 0 end
i = j+1
if i > 0 and i <= n then
return i, v[i]
end
else
i = idx(i, n, 1)
j = idx(j, n, i)
return unpack(v, i, j)
end
end
end
end
end
local function range(i, j, ...)
local n = select("#", ...)
i, j = idx(i,n), idx(j,n)
if i > j then return end
return unpack({...}, i, j)
end
local function remove(i, ...)
local n = select("#", ...)
local t = {...}
i = idx(i, n)
assert(i>0, "index out of bounds")
if i<=n then
n = tremove2(t, n, i)
end
return unpack(t, 1, n)
end
local function insert(v, i, ...)
local n = select("#", ...)
local t = {...}
i = idx(i, n)
assert(i > 0, "index out of bounds")
n = tinsert2(t, n, i, v)
return unpack(t, 1, n)
end
local function replace(v, i, ...)
local n = select("#", ...)
local t = {...}
i = idx(i, n)
assert(i > 0, "index out of bounds")
t[i] = v
n = max(n, i)
return unpack(t, 1, n)
end
local function append(...)
local n = select("#",...)
if n <= 1 then return ... end
local t = {select(2, ...)}
t[n] = (...)
return unpack(t, 1, n)
end
local function map(...)
local n = select("#", ...)
assert(n > 0)
local f = ...
local t = {}
for i = 2, n do
t[i-1] = f((select(i, ...)))
end
return unpack(t, 1, n-1)
end
local function packinto(n, t, ...)
local c = select("#", ...)
for i = 1, c do
t[n+i] = select(i, ...)
end
return n+c
end
local function concat(...)
local n = 0
local t = {}
for i = 1, select("#", ...) do
local f = select(i, ...)
n = packinto(n, t, f())
end
return unpack(t, 1, n)
end
local function count(...)
return select("#", ...)
end
local function at(i, ...)
local n = select("#", ...)
i = idx(i,n)
if i > n then return end
return (select(i, ...))
end
return setmetatable({
pack = pack,
range = range,
insert = insert,
remove = remove,
replace = replace,
append = append,
map = map,
concat = concat,
count = count,
at = at,
},{
__call = function(_, ...)
return pack(...)
end
})
| mit |
nyczducky/darkstar | scripts/globals/mobskills/Absolute_Terror.lua | 28 | 1378 | ---------------------------------------------------
-- Absolute Terror
-- Causes Terror, which causes the victim to be stunned for the duration of the effect, this can not be removed.
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:hasStatusEffect(EFFECT_MIGHTY_STRIKES)) then
return 1;
elseif (mob:hasStatusEffect(EFFECT_SUPER_BUFF)) then
return 1;
elseif (mob:hasStatusEffect(EFFECT_INVINCIBLE)) then
return 1;
elseif (mob:hasStatusEffect(EFFECT_BLOOD_WEAPON)) then
return 1;
elseif (target:isBehind(mob, 48) == true) then
return 1;
elseif (mob:AnimationSub() == 1) then
return 1;
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_TERROR;
local power = 30;
-- Three minutes is WAY too long, especially on Wyrms. Reduced to Wiki's definition of 'long time'. Reference: http://wiki.ffxiclopedia.org/wiki/Absolute_Terror
local duration = 30;
if (skill:isAoE()) then
duration = 10;
end;
skill:setMsg(MobStatusEffectMove(mob, target, typeEffect, power, 0, duration));
return typeEffect;
end
| gpl-3.0 |
guangbin79/Lua_5.1.5-iOS | copas-2_0_1/tests/largetransfer.lua | 1 | 3189 | -- tests large transmissions, sending and receiving
-- uses `receive` and `receivePartial`
-- Does send the same string twice simultaneously
--
-- Test should;
-- * show timer output, once per minute, and actual time should be 60 second increments
-- * both transmissions should take appr. equal time, then they we're nicely cooperative
--
-- Requires;
-- * test certificates, generated using LuaSec scripts in ./samples/certs
-- generate them and put all the 'A' certificates next to this testscript
local copas = require 'copas'
local socket = require 'socket'
local body = ("A"):rep(1024*1024*10) -- 10 mb string
local start = socket.gettime()
local done = 0
local sparams, cparams
local function runtest()
local s1 = socket.bind('*', 49500)
copas.addserver(s1, copas.handler(function(skt)
--skt:settimeout(0) -- don't set, uses `receive` method
local res, err, part = skt:receive('*a')
res = res or part
if res ~= body then print("Received doesn't match send") end
print("Reading... 49500... Done!", socket.gettime()-start, err, #res)
if copas.removeserver then copas.removeserver(s1) end
end, sparams))
local s2 = socket.bind('*', 49501)
copas.addserver(s2, copas.handler(function(skt)
skt:settimeout(0) -- set, uses the `receivePartial` method
local res, err, part = skt:receive('*a')
res = res or part
if res ~= body then print("Received doesn't match send") end
print("Reading... 49501... Done!", socket.gettime()-start, err, #res)
if copas.removeserver then copas.removeserver(s2) end
end, sparams))
copas.addthread(function()
copas.sleep(0)
local skt = socket.tcp()
skt = copas.wrap(skt, cparams)
skt:connect("localhost", 49500)
skt:send(body)
print("Writing... 49500... Done!", socket.gettime()-start, err, #body)
skt = nil
collectgarbage()
collectgarbage()
done = done + 1
end)
copas.addthread(function()
copas.sleep(0)
local skt = socket.tcp()
skt = copas.wrap(skt, cparams)
skt:connect("localhost", 49501)
skt:send(body)
print("Writing... 49501... Done!", socket.gettime()-start, err, #body)
skt = nil
collectgarbage()
collectgarbage()
done = done + 1
end)
copas.addthread(function()
copas.sleep(0)
local i = 1
while done ~= 2 do
copas.sleep(60)
print(i, "minutes:", socket.gettime()-start)
i = i + 1
end
end)
print("starting loop")
copas.loop()
print("Loop done")
end
runtest() -- run test using regular connection (s/cparams == nil)
-- set ssl parameters and do it again
sparams = {
mode = "server",
protocol = "tlsv1",
key = "./serverAkey.pem",
certificate = "./serverA.pem",
cafile = "./rootA.pem",
verify = {"peer", "fail_if_no_peer_cert"},
options = {"all", "no_sslv2"},
}
cparams = {
mode = "client",
protocol = "tlsv1",
key = "./clientAkey.pem",
certificate = "./clientA.pem",
cafile = "./rootA.pem",
verify = {"peer", "fail_if_no_peer_cert"},
options = {"all", "no_sslv2"},
}
done = 0
start = socket.gettime()
runtest()
| mit |
jbeich/Aquaria | files/scripts/entities/leopardshark.lua | 6 | 2873 | -- 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.attackDelay = 0
v.dir = 1
function init(me)
setupBasicEntity(
me,
"", -- texture
10, -- health
2, -- manaballamount
2, -- exp
10, -- money
64, -- collideRadius (for hitting entities + spells)
STATE_IDLE, -- initState
128, -- sprite width
128, -- sprite height
1, -- particle "explosion" type, 0 = none
0, -- 0/1 hit other entities off/on (uses collideRadius)
4000 -- updateCull -1: disabled, default: 4000
)
entity_initSkeletal(me, "leopardshark")
entity_generateCollisionMask(me)
entity_setDeathParticleEffect(me, "Explode")
entity_offset(me, -0, -10)
entity_offset(me, 0, 10, 0.5, -1, 1, 1)
entity_setState(me, STATE_IDLE)
--entity_setCullRadius(me, 1024)
v.n = getNaija()
end
function update(me, dt)
if not entity_hasTarget(me) then
entity_findTarget(me, 300)
if entity_hasTarget(me) then
entity_moveTowardsTarget(me, 1, 400)
else
entity_addVel(me, 500*v.dir, 0)
entity_updateMovement(me, dt)
entity_flipToVel(me)
end
else
entity_moveTowardsTarget(me, dt, 400)
entity_flipToEntity(me, entity_getTarget(me))
entity_findTarget(me, 340)
end
entity_doEntityAvoidance(me, dt, 32, 0.5)
entity_doCollisionAvoidance(me, dt, 5, 0.8)
entity_updateCurrents(me, dt)
entity_updateMovement(me, dt)
--entity_rotateToVel(me, 0, 90)
entity_handleShotCollisions(me)
entity_touchAvatarDamage(me, entity_getCollideRadius(me), 0.75, 400)
--if entity_touchAvatarDamage(me, entity_getCollideRadius(me), 0.75, 400) then
-- entity_moveTowardsTarget(me, 1, -500)
--end
end
function hitSurface(me)
v.dir = -v.dir
end
function enterState(me)
if entity_isState(me, STATE_IDLE) then
entity_animate(me, "idle", LOOP_INF)
end
end
function exitState(me)
end
function dieNormal(me)
if chance(40) then
spawnIngredient("SharkFin", entity_x(me), entity_y(me))
end
end
function damage(me)
return true
end
function animationKey(me, key)
end
| gpl-2.0 |
rotmanmi/torch7 | torchcwrap.lua | 54 | 15111 | local wrap = require 'cwrap'
local types = wrap.types
types.Tensor = {
helpname = function(arg)
if arg.dim then
return string.format("Tensor~%dD", arg.dim)
else
return "Tensor"
end
end,
declare = function(arg)
local txt = {}
table.insert(txt, string.format("THTensor *arg%d = NULL;", arg.i))
if arg.returned then
table.insert(txt, string.format("int arg%d_idx = 0;", arg.i));
end
return table.concat(txt, '\n')
end,
check = function(arg, idx)
if arg.dim then
return string.format("(arg%d = luaT_toudata(L, %d, torch_Tensor)) && (arg%d->nDimension == %d)", arg.i, idx, arg.i, arg.dim)
else
return string.format("(arg%d = luaT_toudata(L, %d, torch_Tensor))", arg.i, idx)
end
end,
read = function(arg, idx)
if arg.returned then
return string.format("arg%d_idx = %d;", arg.i, idx)
end
end,
init = function(arg)
if type(arg.default) == 'boolean' then
return string.format('arg%d = THTensor_(new)();', arg.i)
elseif type(arg.default) == 'number' then
return string.format('arg%d = %s;', arg.i, arg.args[arg.default]:carg())
else
error('unknown default tensor type value')
end
end,
carg = function(arg)
return string.format('arg%d', arg.i)
end,
creturn = function(arg)
return string.format('arg%d', arg.i)
end,
precall = function(arg)
local txt = {}
if arg.default and arg.returned then
table.insert(txt, string.format('if(arg%d_idx)', arg.i)) -- means it was passed as arg
table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i))
table.insert(txt, string.format('else'))
if type(arg.default) == 'boolean' then -- boolean: we did a new()
table.insert(txt, string.format('luaT_pushudata(L, arg%d, torch_Tensor);', arg.i))
else -- otherwise: point on default tensor --> retain
table.insert(txt, string.format('{'))
table.insert(txt, string.format('THTensor_(retain)(arg%d);', arg.i)) -- so we need a retain
table.insert(txt, string.format('luaT_pushudata(L, arg%d, torch_Tensor);', arg.i))
table.insert(txt, string.format('}'))
end
elseif arg.default then
-- we would have to deallocate the beast later if we did a new
-- unlikely anyways, so i do not support it for now
if type(arg.default) == 'boolean' then
error('a tensor cannot be optional if not returned')
end
elseif arg.returned then
table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i))
end
return table.concat(txt, '\n')
end,
postcall = function(arg)
local txt = {}
if arg.creturned then
-- this next line is actually debatable
table.insert(txt, string.format('THTensor_(retain)(arg%d);', arg.i))
table.insert(txt, string.format('luaT_pushudata(L, arg%d, torch_Tensor);', arg.i))
end
return table.concat(txt, '\n')
end
}
types.Generator = {
helpname = function(arg)
return "Generator"
end,
declare = function(arg)
return string.format("THGenerator *arg%d = NULL;", arg.i)
end,
check = function(arg, idx)
return string.format("(arg%d = luaT_toudata(L, %d, torch_Generator))", arg.i, idx)
end,
read = function(arg, idx)
end,
init = function(arg)
local text = {}
-- If no generator is supplied, pull the default out of the torch namespace.
table.insert(text, 'lua_getglobal(L,"torch");')
table.insert(text, string.format('arg%d = luaT_getfieldcheckudata(L, -1, "_gen", torch_Generator);', arg.i))
table.insert(text, 'lua_pop(L, 2);')
return table.concat(text, '\n')
end,
carg = function(arg)
return string.format('arg%d', arg.i)
end,
creturn = function(arg)
return string.format('arg%d', arg.i)
end,
precall = function(arg)
end,
postcall = function(arg)
end
}
types.IndexTensor = {
helpname = function(arg)
return "LongTensor"
end,
declare = function(arg)
local txt = {}
table.insert(txt, string.format("THLongTensor *arg%d = NULL;", arg.i))
if arg.returned then
table.insert(txt, string.format("int arg%d_idx = 0;", arg.i));
end
return table.concat(txt, '\n')
end,
check = function(arg, idx)
return string.format('(arg%d = luaT_toudata(L, %d, "torch.LongTensor"))', arg.i, idx)
end,
read = function(arg, idx)
local txt = {}
if not arg.noreadadd then
table.insert(txt, string.format("THLongTensor_add(arg%d, arg%d, -1);", arg.i, arg.i));
end
if arg.returned then
table.insert(txt, string.format("arg%d_idx = %d;", arg.i, idx))
end
return table.concat(txt, '\n')
end,
init = function(arg)
return string.format('arg%d = THLongTensor_new();', arg.i)
end,
carg = function(arg)
return string.format('arg%d', arg.i)
end,
creturn = function(arg)
return string.format('arg%d', arg.i)
end,
precall = function(arg)
local txt = {}
if arg.default and arg.returned then
table.insert(txt, string.format('if(arg%d_idx)', arg.i)) -- means it was passed as arg
table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i))
table.insert(txt, string.format('else')) -- means we did a new()
table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.LongTensor");', arg.i))
elseif arg.default then
error('a tensor cannot be optional if not returned')
elseif arg.returned then
table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i))
end
return table.concat(txt, '\n')
end,
postcall = function(arg)
local txt = {}
if arg.creturned or arg.returned then
table.insert(txt, string.format("THLongTensor_add(arg%d, arg%d, 1);", arg.i, arg.i));
end
if arg.creturned then
-- this next line is actually debatable
table.insert(txt, string.format('THLongTensor_retain(arg%d);', arg.i))
table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.LongTensor");', arg.i))
end
return table.concat(txt, '\n')
end
}
for _,typename in ipairs({"ByteTensor", "CharTensor", "ShortTensor", "IntTensor", "LongTensor",
"FloatTensor", "DoubleTensor"}) do
types[typename] = {
helpname = function(arg)
if arg.dim then
return string.format('%s~%dD', typename, arg.dim)
else
return typename
end
end,
declare = function(arg)
local txt = {}
table.insert(txt, string.format("TH%s *arg%d = NULL;", typename, arg.i))
if arg.returned then
table.insert(txt, string.format("int arg%d_idx = 0;", arg.i));
end
return table.concat(txt, '\n')
end,
check = function(arg, idx)
if arg.dim then
return string.format('(arg%d = luaT_toudata(L, %d, "torch.%s")) && (arg%d->nDimension == %d)', arg.i, idx, typename, arg.i, arg.dim)
else
return string.format('(arg%d = luaT_toudata(L, %d, "torch.%s"))', arg.i, idx, typename)
end
end,
read = function(arg, idx)
if arg.returned then
return string.format("arg%d_idx = %d;", arg.i, idx)
end
end,
init = function(arg)
if type(arg.default) == 'boolean' then
return string.format('arg%d = TH%s_new();', arg.i, typename)
elseif type(arg.default) == 'number' then
return string.format('arg%d = %s;', arg.i, arg.args[arg.default]:carg())
else
error('unknown default tensor type value')
end
end,
carg = function(arg)
return string.format('arg%d', arg.i)
end,
creturn = function(arg)
return string.format('arg%d', arg.i)
end,
precall = function(arg)
local txt = {}
if arg.default and arg.returned then
table.insert(txt, string.format('if(arg%d_idx)', arg.i)) -- means it was passed as arg
table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i))
table.insert(txt, string.format('else'))
if type(arg.default) == 'boolean' then -- boolean: we did a new()
table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.%s");', arg.i, typename))
else -- otherwise: point on default tensor --> retain
table.insert(txt, string.format('{'))
table.insert(txt, string.format('TH%s_retain(arg%d);', typename, arg.i)) -- so we need a retain
table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.%s");', arg.i, typename))
table.insert(txt, string.format('}'))
end
elseif arg.default then
-- we would have to deallocate the beast later if we did a new
-- unlikely anyways, so i do not support it for now
if type(arg.default) == 'boolean' then
error('a tensor cannot be optional if not returned')
end
elseif arg.returned then
table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i))
end
return table.concat(txt, '\n')
end,
postcall = function(arg)
local txt = {}
if arg.creturned then
-- this next line is actually debatable
table.insert(txt, string.format('TH%s_retain(arg%d);', typename, arg.i))
table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.%s");', arg.i, typename))
end
return table.concat(txt, '\n')
end
}
end
types.LongArg = {
vararg = true,
helpname = function(arg)
return "(LongStorage | dim1 [dim2...])"
end,
declare = function(arg)
return string.format("THLongStorage *arg%d = NULL;", arg.i)
end,
init = function(arg)
if arg.default then
error('LongArg cannot have a default value')
end
end,
check = function(arg, idx)
return string.format("torch_islongargs(L, %d)", idx)
end,
read = function(arg, idx)
return string.format("arg%d = torch_checklongargs(L, %d);", arg.i, idx)
end,
carg = function(arg, idx)
return string.format('arg%d', arg.i)
end,
creturn = function(arg, idx)
return string.format('arg%d', arg.i)
end,
precall = function(arg)
local txt = {}
if arg.returned then
table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.LongStorage");', arg.i))
end
return table.concat(txt, '\n')
end,
postcall = function(arg)
local txt = {}
if arg.creturned then
-- this next line is actually debatable
table.insert(txt, string.format('THLongStorage_retain(arg%d);', arg.i))
table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.LongStorage");', arg.i))
end
if not arg.returned and not arg.creturned then
table.insert(txt, string.format('THLongStorage_free(arg%d);', arg.i))
end
return table.concat(txt, '\n')
end
}
types.charoption = {
helpname = function(arg)
if arg.values then
return "(" .. table.concat(arg.values, '|') .. ")"
end
end,
declare = function(arg)
local txt = {}
table.insert(txt, string.format("const char *arg%d = NULL;", arg.i))
if arg.default then
table.insert(txt, string.format("char arg%d_default = '%s';", arg.i, arg.default))
end
return table.concat(txt, '\n')
end,
init = function(arg)
return string.format("arg%d = &arg%d_default;", arg.i, arg.i)
end,
check = function(arg, idx)
local txt = {}
local txtv = {}
table.insert(txt, string.format('(arg%d = lua_tostring(L, %d)) && (', arg.i, idx))
for _,value in ipairs(arg.values) do
table.insert(txtv, string.format("*arg%d == '%s'", arg.i, value))
end
table.insert(txt, table.concat(txtv, ' || '))
table.insert(txt, ')')
return table.concat(txt, '')
end,
read = function(arg, idx)
end,
carg = function(arg, idx)
return string.format('arg%d', arg.i)
end,
creturn = function(arg, idx)
end,
precall = function(arg)
end,
postcall = function(arg)
end
}
| bsd-3-clause |
nyczducky/darkstar | scripts/globals/abilities/pets/hydro_breath.lua | 29 | 1337 | ---------------------------------------------------
-- Hydro Breath
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
require("scripts/globals/ability");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onUseAbility(pet, target, skill, action)
local master = pet:getMaster()
---------- Deep Breathing ----------
-- 0 for none
-- 1 for first merit
-- 0.25 for each merit after the first
-- TODO: 0.1 per merit for augmented AF2 (10663 *w/ augment*)
local deep = 1;
if (pet:hasStatusEffect(EFFECT_MAGIC_ATK_BOOST) == true) then
deep = deep + 1 + (master:getMerit(MERIT_DEEP_BREATHING)-1)*0.25;
pet:delStatusEffect(EFFECT_MAGIC_ATK_BOOST);
end
local gear = master:getMod(MOD_WYVERN_BREATH)/256; -- Master gear that enhances breath
local dmgmod = MobBreathMove(pet, target, 0.185, pet:getMainLvl()*15, ELE_WATER); -- Works out to (hp/6) + 15, as desired
dmgmod = (dmgmod * (1+gear))*deep;
pet:setTP(0)
local dmg = AbilityFinalAdjustments(dmgmod,pet,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WATER,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
return dmg;
end
| gpl-3.0 |
wenhulove333/ScutServer | SDK/template/multi-platform-quick/Resources/scripts/testScene.lua | 4 | 43283 | module("testScene", package.seeall)
function P(fileName)
if fileName then
return ScutDataLogic.CFileHelper:getPath(fileName)
else
return nil
end
end
------文字资源-------------------------
IDS_JINDOU = "金豆"
IDS_JIFEN = "积分"
IDS_JINGYAN = "经验"
IDS_SORCE = "分数:"
IDS_NICKNAME = "昵称:"
IDS_SORCE1 = "分数"
IDS_NICKNAME1 = "昵称"
IDS_OK="确认"
IDS_SUBMIT = "提交成绩"
IDS_CANCLE="取消"
IDS_EMPTY_TIP = "输入不能为空"
IDS_ORDER = "名次"
IDS_TEST = "请按右下角排行按钮进行TCP连接"
IDS_TCP_CONNECTING = "TCP连接建立中"
IDS_TCP_CONNECTED = "TCP连接已建立,接受数据中"
IDS_CONNECT_COUNT = "收到服务器推送数据%d次"
-----图片资源路径-------------------------
image_background_sm="common/list_1002_1.9.png"--背景图
image_list_txt="common/panle_1009_1.9.png"--文本输入框底图
image_list_txt_2="common/list_1004.9.png"--文本输入框底图
image_logo="Image/logo.png"--logo
image_logoSmall="Image/logo2.png" --小Logo
image_button_red_c_0="button/button_1012.png"--红色长按钮
image_button_red_c_1="button/button_1011.png"--红色长按钮
image_mainscene = "common/panel_1003_1.png" --背景
image_exit = "button/icon_1027.png" --返回按钮
image_roomBg="common/panel_1002_3.png" --房间背景
image_menuBg="common/panel_1006.png"--菜单背景
image_nameBg="common/panel_1002_1.9.png" --名字背景
image_shop_1="common/panel_1003_4.png" --头像商店
image_shop="common/panel_1003_5.png" --头像商店
---聊天
icon_1024="chat/icon_1024.png"--聊天按钮
tou_ming="common/tou_ming.9.png"--透明按钮
panle_1016_1="common/panle_1016_1.png"--下划线
button_1022="tabNameImg/button_1022.png"--即时聊天
button_1023="tabNameImg/button_1023.png"--聊天记录
--排行榜
button_1028="tabNameImg/button_1028.png"--金豆排行
button_1029="tabNameImg/button_1029.png"--胜率排行
button_1006="title/button_1006.png";--说明
panle_1019_1_9="button/panle_1019_1.9.png"--list中单个对应的背景框
panle_1014_1="common/panle_1014_1.png"--说明框背景框先用这张
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
mConnectNum = 0;
pWinSize=CCDirector:sharedDirector():getWinSize()
function PT(x,y)
return CCPoint(x,y)
end
function Half_Float(x)
return x*0.5
end
function SZ(width, height)
return CCSize(width, height)
end
function SCALEX(x)
return CCDirector:sharedDirector():getWinSize().width/480*x
end
function SCALEY(y)
return CCDirector:sharedDirector():getWinSize().height /320*y
end
FONT_NAME = "黑体"
FONT_DEF_SIZE = SCALEX(18)
FONT_SM_SIZE = SCALEX(15)
FONT_BIG_SIZE = SCALEX(23)
FONT_M_BIG_SIZE = SCALEX(63)
FONT_SMM_SIZE = SCALEX(13)
FONT_FM_SIZE=SCALEX(11)
FONT_FMM_SIZE=SCALEX(12)
FONT_FMMM_SIZE=SCALEX(9)
ccBLACK = ccc3(0,0,0)
ccWHITE = ccc3(255,255,255)
ccYELLOW = ccc3(255,255,0)
ccBLUE = ccc3(0,0,255)
ccGREEN = ccc3(0,255,0)
ccRED = ccc3(255,0,0)
ccMAGENTA = ccc3(255,0,255)
ccPINK = ccc3(228,56,214) -- 粉色
ccORANGE = ccc3(206, 79, 2) -- 橘红色
ccGRAY = ccc3(166,166,166)
ccC1=ccc3(45,245,250)
---通用颜色
ccRED1= ccc3(86,26,0)
ccYELLOW2=ccc3(241,176,63)
------获取资源的路径---------------------
function P(fileName)
if fileName then
return ScutDataLogic.CFileHelper:getPath(fileName)
else
return nil
end
end
function SX(x)
return SCALEX(x)
end
function SY(y)
return SCALEY(y)
end
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)
----------------------- ui control ----------------------------------------------
ZyButton = {
_menuItem = nil,
_label = nil,
_menu = nil,
_colorNormal = nil,
_colorSelected = nil,
_isSelected = nil,
}
ZyImage = {
_image = nil,
_scaleX = 1,
_scaleY = 1,
}
function ZyImage:new(param)
local instance = {}
if type(param) == "string" then
instance._image = self:imageWithFile(param)
elseif type(param) == "userdata" then
instance._image = param
end
instance._image:setAnchorPoint(CCPoint(0, 0))
setmetatable(instance, self)
self.__index = self
return instance
end
function ZyImage:imageWithFile(fileName)
local image =CCSprite:create(P(fileName))
image:setAnchorPoint(CCPoint(0, 0))
return image
end
function ZyImage:imageSize(fileName)
local sprite = CCSprite:create(P(fileName))
local size = sprite:getContentSize()
return size
end
function ZyImage:resize(size)
local oldSize = self._image:getContentSize()
self._scaleX = (size.width / oldSize.width)
self._scaleY = (size.height / oldSize.height)
self._image:setScaleX(self._scaleX)
self._image:setScaleY(self._scaleY)
self._image:setContentSize(size)
end
function ZyImage:image()
return self._image
end
function ZyImage:getContentSize()
return self._image:getContentSize()
end
function ZyButton:new(picNor, picDown, picDis, title, fontName, fontSize)
local instance = {}
setmetatable(instance, self)
self.__index = self
local addLabel = true
local label
local label1
local label2
local menuItem
local menu
if fontName == nil then
fontName = FONT_NAME
end
if fontSize == nil then
fontSize = FONT_SM_SIZE
end
if picNor and picDown and picDis then
menuItem = CCMenuItemImage:create(P(picNor), P(picDown), P(picDis))
elseif picNor and picDown then
menuItem = CCMenuItemImage:create(P(picNor), P(picDown))
elseif picNor then
local spriteNor = CCSprite:create(P(picNor))
local spriteDown = CCSprite:create(P(picNor))
if title then
local size = ZyFont.stringSize(title, spriteNor:getContentSize().width, fontName, fontSize)
label1 = CCLabelTTF:create(title,fontName, fontSize, size, kCCTextAlignmentCenter )
label1:setPosition(CCPoint(spriteNor:getContentSize().width / 2, spriteNor:getContentSize().height / 2))
spriteNor:addChild(label1, 0)
label2 = CCLabelTTF:create(title, fontName, fontSize, size, kCCTextAlignmentCenter)
label2:setPosition(CCPoint(spriteDown:getContentSize().width / 2, spriteDown:getContentSize().height / 2))
spriteDown:addChild(label2, 0)
spriteDown:setPosition(CCPoint(0, SY(-1)))
else
spriteDown:setScale(0.94)
spriteDown:setPosition(CCPoint(spriteNor:getContentSize().width * 0.03, spriteNor:getContentSize().height * 0.03))
end
menuItem = CCMenuItemSprite:create(spriteNor, spriteDown)
addLabel = true
else
menuItem = CCMenuItemLabel:itemWithLabel(instance._label)
addLabel = true
end
if addLabel and title then
if title then
label = CCLabelTTF:create(title, fontName, fontSize)
end
label:setPosition(CCPoint(menuItem:getContentSize().width / 2, menuItem:getContentSize().height / 2))
menuItem:addChild(label, 0)
end
menuItem:setAnchorPoint(CCPoint(0, 0))
menu = CCMenu:createWithItem(menuItem)
menu:setContentSize(menuItem:getContentSize())
menu:setAnchorPoint(CCPoint(0, 0))
instance._menuItem = menuItem
instance._menu = menu
instance._label = label
instance._label1 = label1
instance._label2 = label2
instance._isSelected = false
return instance
end
function setScaleXY(frame,scaleX,scaleY)
if scaleX~=nil then
frame:setScaleX(scaleX/frame:getContentSize().width)
end
if scaleY~=nil then
frame:setScaleX(scaleY/frame:getContentSize().height)
end
end
function ZyButton:addto(parent, param1, param2)
if type(param1) == "userdata" then
parent:addChildItem(self._menu, param1)
else
if param2 then
parent:addChild(self._menu, param1, param2)
elseif param1 then
parent:addChild(self._menu, param1)
else
parent:addChild(self._menu, 0)
end
end
end
function ZyButton:addChild(item,tag)
self._menuItem:addChild(item,tag)
end
function ZyButton:menuItem()
return self._menuItem
end
function ZyButton:menu()
return self._menu
end
function ZyButton:registerScriptTapHandler(handler)
self._menuItem:registerScriptTapHandler(handler)
end
function ZyButton:setIsEnabled(enabled)
self._menuItem:setEnabled(enabled)
end
function ZyButton:getIsEnabled()
return self._menuItem:getIsEnabled()
end
function ZyButton:setIsVisible(enabled)
self._menuItem:setVisible(enabled)
end
function ZyButton:setString(label)
if self._label1 then
self._label1:setString(label)
end
if self._label2 then
self._label2:setString(label)
end
if self._label then
self._label:setString(label)
end
end
function ZyButton:getString()
return self._label:getString()
end
--
function ZyButton:setColor(color)
if self._label then
self._label:setColor(color)
end
if self._label1 then
self._label1:setColor(color)
end
if self._label2 then
self._label2:setColor(color)
end
end
function ZyButton:setColorNormal(color)
self._colorNormal = color
if not self._isSelected then
self._label:setColor(color)
end
end
function ZyButton:setColorSelected(color)
self._colorSelected = color
if self._isSelected then
self._label:setColor(color)
end
end
function ZyButton:setTag(tag)
self._menuItem:setTag(tag)
end
function ZyButton:getTag(tag)
return self._menuItem:getTag()
end
function ZyButton:setPosition(position)
self._menu:setPosition(position)
end
function ZyButton:getPosition()
return self._menu:getPosition()
end
function ZyButton:setAnchorPoint(point)
self._menu:setAnchorPoint(point)
self._menuItem:setAnchorPoint(point)
end
function ZyButton:getAnchorPoint(ponint)
return self._menu:getAnchorPoint(point)
end
function ZyButton:setContentSize(size)
self._menu:setContentSize(size)
end
function ZyButton:getContentSize()
return self._menu:getContentSize()
end
function ZyButton:setScale(scale)
return self._menu:setScale(scale)
end
function ZyButton:setScaleX(scale)
return self._menu:setScaleX(scale)
end
function ZyButton:setScaleY(scale)
return self._menu:setScaleY(scale)
end
function ZyButton:getScale()
return self._menu:getScale()
end
function ZyButton:selected()
self._isSelected = true
self._menuItem:selected()
if self._colorSelected then
self._label:setColor(self._colorSelected)
elseif self._colorNormal then
self._label:setColor(self._colorNormal)
end
end
function ZyButton:unselected()
self._isSelected = false
self._menuItem:unselected()
if self._colorNormal then
self._label:setColor(self._colorNormal)
end
end
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
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 MenuItem(normalPic, downPic, listtener, strText, TextAlign, fontSize, color, bCheck, disablePic)
local strNor = nil
local strDown = nil
local strDisable = nil
if normalPic ~= nil then
strNor = (normalPic)
end
if downPic ~= nil then
strDown = (downPic)
end
if disablePic ~= nil then
strDisable = (disablePic)
end
local menuItem
if disablePic == nil then
menuItem = CCMenuItemImage:create(strNor, strDown)
else
menuItem = CCMenuItemImage:create(strNor, strDown, strDisable)
end
if bCheck then
menuItem:selected()
else
menuItem:unselected()
end
local pLable = nil
if strText ~= nil then
pLable = CCLabelTTF:create(strText, FONT_NAME, (fontSize))
end
local szMenu = menuItem:getContentSize()
if listtener ~= nil then
menuItem:registerScriptTapHandler(function () listtener(menuItem) end )
end
menuItem:setAnchorPoint(CCPoint(0, 0))
--TextAlign--
if pLable ~= nil then
if TextAlign == 0 then --AlignLeft
pLable:setAnchorPoint(CCPoint(0, 0.5))
pLable:setPosition(CCPoint(0, szMenu.height/2))
elseif TextAlign == 1 then --AlignCenter
pLable:setPosition(CCPoint(szMenu.width/2, szMenu.height/2))
else --ALignRight
pLable:setAnchorPoint(CCPoint(1, 0.5))
pLable:setPosition(CCPoint(szMenu.width/2, szMenu.height/2))
end
if color ~= nil then
pLable:setColor(color)
end
menuItem:addChild(pLable, 0, 0)
end
return menuItem, pLable
end
function Button(normalPic, downPic, listtener, strText, TextAlign, fontSize, color, tag, bCheck, disablePic)
menuItem = MenuItem(normalPic, downPic, listtener, strText, TextAlign, fontSize, color, bCheck, disablePic)
if tag ~= nil then
menuItem:setTag(tag)
end
local Btn = CCMenu:createWithItem(menuItem)
Btn:setContentSize(menuItem:getContentSize())
return Btn, menuItem
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: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((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 = 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 = 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:setCallbackFun(fun)
self._funCallback = fun
end
local mRankLayer
local mLayer
local tip1
local tip2
local tip3
local bgLayer
local submitLayer
local allTable={};
local mList;
local mNameEdit;
local mScoreEdit;
local isCanSubmit = true
local isCanGetRank = true
local mNameStr;
local mScoreStr;
-- close the ranking layer
function closeBtnActon()
if bgLayer then
mScene:removeChild(bgLayer,true);
bgLayer = nil
end
end
function showRank()
if isCanGetRank == false then
return
end
-- if addressPath is not nil use socket connect
local addressPath="ph.scutgame.com:9001"
ScutDataLogic.CNetWriter:getInstance():writeString("ActionId",1001)
ScutDataLogic.CNetWriter:getInstance():writeString("PageIndex",1 )
ScutDataLogic.CNetWriter:getInstance():writeString("PageSize",30)
ZyExecRequest(mScene, nil,false,addressPath )
if labelIds1 then
labelIds1:setVisible(false)
end
labelIds2 = CCLabelTTF:create(IDS_TCP_CONNECTING, "fsfe", FONT_SM_SIZE);
labelIds2:setPosition(labelIds1:getPosition());
mScene:addChild(labelIds2, 99);
end
function submitOK()
local name= mNameEdit:getText()
local sorce= mScoreEdit:getText()
if name=="" or sorce == "" then
local box = ZyMessageBoxEx:new()
box:doPrompt(mScene, nil,IDS_EMPTY_TIP,IDS_OK,messageCallback)
mNameEdit:setVisible(false);
mScoreEdit:setVisible(false);
else
local addressPath="ph.scutgame.com:9001"
ScutDataLogic.CNetWriter:getInstance():writeString("ActionId",1000)
ScutDataLogic.CNetWriter:getInstance():writeString("UserName",name )
ScutDataLogic.CNetWriter:getInstance():writeString("Score",sorce)
ZyExecRequest(mScene, nil,false,addressPath)
end
end
function createUIBg(titleImagePath,titleStr,textColor,closeBtnActionPath, touming)
local layer = CCLayer:create()
layer:setAnchorPoint(CCPoint(0,0))
layer:setPosition(CCPoint(0,0))
local bgPic = CCSprite:create(P(image_mainscene))
bgPic:setAnchorPoint(CCPoint(0,0))
bgPic:setScaleX(pWinSize.width/bgPic:getContentSize().width)
bgPic:setScaleY(pWinSize.height/bgPic:getContentSize().height)
bgPic:setPosition(CCPoint(0,0))
layer:addChild(bgPic, 0, 0)
layer:setContentSize(pWinSize)
if touming then
local toumingBg = CCSprite:create(P("common/panel_1002_12.png"))
toumingBg:setScaleX(pWinSize.width*0.92/toumingBg:getContentSize().width)
toumingBg:setScaleY(pWinSize.height*0.8/toumingBg:getContentSize().height)
toumingBg:setAnchorPoint(CCPoint(0,0))
toumingBg:setPosition(CCPoint(pWinSize.width*0.04, pWinSize.height*0.06))
layer:addChild(toumingBg, 0)
end
local closeBtn = nil
if closeBtnActionPath ~= nil then
local norClose = CCSprite:create(P(Image.image_close))
local norDown = CCSprite :create(P(Image.image_close))
norDown:setScale(0.9)
local menuItem = CCMenuItemSprite:itemFromNormalSprite(norClose, norDown)
norClose:setAnchorPoint(CCPoint(0.5,0.5))
norDown:setAnchorPoint(CCPoint(0.5, 0.5))
norClose:setPosition(CCPoint(menuItem:getContentSize().width/2, menuItem:getContentSize().height/2))
norDown:setPosition(CCPoint(menuItem:getContentSize().width/2, menuItem:getContentSize().height/2))
closeBtn = CCMenu:menuWithItem(menuItem)
menuItem:setAnchorPoint(CCPoint(0, 0))
menuItem:setPosition(CCPoint(0, 0))
menuItem:registerScriptHandler(closeBtnActionPath)
closeBtn:setContentSize(menuItem:getContentSize())
layer:addChild(closeBtn, 0, 0)
closeBtn:setPosition(CCPoint(layer:getContentSize().width - closeBtn:getContentSize().width,layer:getContentSize().height - closeBtn:getContentSize().height-SY(3)))
end
local titleImageLabel = nil
local titleStrLabel = nil
if titleImagePath then
titleImageLabel = CCSprite:create(P(titleImagePath))
titleImageLabel:setAnchorPoint(CCPoint(0,0))
titleImageLabel:setPosition(CCPoint(pWinSize.width*0.5-titleImageLabel:getContentSize().width*0.5,pWinSize.height*0.95-titleImageLabel:getContentSize().height))
layer:addChild(titleImageLabel,0)
end
if titleStr then
titleStrLabel = CCLabelTTF:create(titleStr, FONT_NAME, FONT_BIG_SIZE)
titleStrLabel:setAnchorPoint(CCPoint(0.5,0))
titleStrLabel:setPosition(CCPoint(pWinSize.width*0.5,pWinSize.height-titleStrLabel:getContentSize().height-SY(15)))
layer:addChild(titleStrLabel,0)
if textColor ~= nil then
titleStrLabel:setColor(textColor)
end
end
return layer
end
function messageCallback()
mNameEdit:setVisible(true);
mScoreEdit:setVisible(true);
end
function submitCancle()
closeSubmitLaye()
end
function submit()
if isCanSubmit == false then
return
end
isCanSubmit = false
isCanGetRank = false
local aa=nil
local ww=288
local hh=0
local xx=(pWinSize.width-ww)/2
local imgSprite=CCSprite:create(P(image_list_txt));
local txt_h= imgSprite:getContentSize().height
submitLayer = CCLayer:create();
submitLayer:setContentSize(CCSize(SX(240),SY(160)));
mScene:addChild(submitLayer);
submitLayer:setAnchorPoint(PT(0.5,0.5));
submitLayer:setPosition(PT(mScene:getContentSize().width/2, mScene:getContentSize().height/2));
local sprite = CCSprite:create(P("common/panel_1002_12.png"))
sprite:setScaleX(SX(240)/sprite:getContentSize().width);
sprite:setScaleY(SY(160)/sprite:getContentSize().height);
submitLayer:addChild(sprite,0);
local startY = 0
local titleName1=CCLabelTTF:create(IDS_NICKNAME,FONT_NAME, FONT_DEF_SIZE);
titleName1:setAnchorPoint(CCPoint(0,0))
titleName1:setPosition(CCPoint(SX(-100),
startY+titleName1:getContentSize().height - SY(30)))
submitLayer:addChild(titleName1)
titleName1:setColor(ccc3(0,0,0))
local txt_x=titleName1:getPositionX()+SX(8)+titleName1:getContentSize().width
local txt_ww=xx+ww-txt_x-SX(44)
local bgEmCCPointy1= CCSprite:create(P(image_list_txt))
mNameEdit = CCEditBox:create(CCSize(SX(120),bgEmCCPointy1:getContentSize().height), CCScale9Sprite:create(P(image_list_txt)))
mNameEdit:setPosition(CCPoint(titleName1:getPositionX()+ titleName1:getContentSize().width + SX(60) ,titleName1:getPositionY()+SY(5)))
mNameEdit:setFontColor(ccc3(0,0,0))
submitLayer:addChild(mNameEdit)
local titleName=CCLabelTTF:create(IDS_SORCE, "sfeew", FONT_DEF_SIZE);
titleName:setColor(ccc3(0,0,0))
titleName:setAnchorPoint(CCPoint(0,0))
aa=(hh/2-titleName:getContentSize().height)/2
titleName:setPosition(CCPoint(titleName1:getPositionX(),titleName1:getPositionY()+txt_h+SY(10)))
submitLayer:addChild(titleName)
mScoreEdit = CCEditBox:create(CCSize(SX(120),bgEmCCPointy1:getContentSize().height), CCScale9Sprite:create(P(image_list_txt)))
mScoreEdit:setFontColor(ccc3(0,0,0))
mScoreEdit:setPosition(CCPoint(titleName:getPositionX() + titleName:getContentSize().width + SX(60) ,titleName:getPositionY()+SY(5)))
submitLayer:addChild(mScoreEdit)
mScoreEdit:setVisible(true)
local button2 = ZyButton:new("button/button_1011.png", "button/button_1012.png",nil,IDS_OK)
button2:setPosition(PT(SX(-30) -button2:getContentSize().width,SY(-50)));
button2:addto(submitLayer,0)
button2:registerScriptTapHandler(submitOK);
local button3 = ZyButton:new("button/button_1011.png", "button/button_1012.png",nil,IDS_CANCLE)
button3:setPosition(PT(SX(30) ,SY(-50)));
button3:addto(submitLayer,0)
button3:registerScriptTapHandler(submitCancle);
end
function closeSubmitLaye()
mScene:removeChild(submitLayer,true)
isCanSubmit = true
isCanGetRank = true
end
function init()
if mScene then
return
end
local scene = ScutScene:new()
mScene = scene.root
scene:registerCallback(netCallback)
CCDirector:sharedDirector():pushScene(mScene)
pWinSize = mScene:getContentSize()
mLayer = CCLayer:create()
mLayer:setAnchorPoint(CCPoint(0,0))
mLayer:setPosition(CCPoint(0,0))
mScene:addChild(mLayer, 0)
mRankLayer = CCLayer:create();
mRankLayer:setAnchorPoint(PT(0.5, 0.5));
mRankLayer:setPosition(PT(pWinSize.width/2, pWinSize.height/2));
CCDirector:sharedDirector():pushScene(mScene)
local bgSprite=CCSprite:create(P("beijing.jpg"))
bgSprite:setScaleX(pWinSize.width/bgSprite:getContentSize().width)
bgSprite:setScaleY(pWinSize.height/bgSprite:getContentSize().height)
bgSprite:setAnchorPoint(CCPoint(0.5,0.5))
bgSprite:setPosition(CCPoint(pWinSize.width/2,pWinSize.height/2));
mScene:addChild(bgSprite);
--ScutDataLogic.CNetWriter:setUrl("http://ph.scutgame.com/service.aspx")
local button = ZyButton:new("icon_1011.png");
button:addto(mScene,0);
button:setPosition(PT(pWinSize.width - button:getContentSize().width - SX(10), SY(10)));
button:registerScriptTapHandler(showRank)
local button2 = ZyButton:new("button/button_1011.png", "button/button_1012.png",nil,IDS_SUBMIT)
button2:setPosition(PT(pWinSize.width/2 - button2:getContentSize().width/2 ,SY(10)));
button2:addto(mScene,0)
button2:registerScriptTapHandler(submit);
-- 请按右下角排行按钮进行TCP连接
labelIds1 = CCLabelTTF:create(IDS_TEST,"sfeew", FONT_SM_SIZE);
labelIds1:setPosition(PT(SX(20) + labelIds1:getContentSize().width/2 , pWinSize.height - SY(18)));
labelIds1:setAnchorPoint(PT(0.5,0.5));
mScene:addChild(labelIds1,99);
end
function netCallback(pZyScene, lpExternalData, isTcp)
local actionID = ZyReader:getActionID()
local lpExternalData = lpExternalData or 0
local userData = ZyRequestParam:getParamData(lpExternalData)
if actionID==1001 then
local table = _1001Callback(pZyScene, lpExternalData);
if labelIds2 then
labelIds2:setVisible(false)
end
labelIds3 = CCLabelTTF:create(IDS_TCP_CONNECTED, "xxxx", FONT_SM_SIZE);
labelIds3:setPosition(labelIds2:getPosition());
mScene:addChild(labelIds3);
if isTcp == true then
mConnectNum = mConnectNum + 1 ;
end
if labelIds4 == nil then
labelIds4 = CCLabelTTF:create(string.format(IDS_CONNECT_COUNT,mConnectNum), "xxxx", FONT_SM_SIZE);
labelIds4:setPosition(PT(labelIds3:getPositionX() , labelIds3:getPositionY() - SY(15)));
mScene:addChild(labelIds4, 99);
else
labelIds4:setString(string.format(IDS_CONNECT_COUNT,mConnectNum));
end
if table then
if bgLayer == nil then
bgLayer= createUIBg(nil,nil,ccc3(255,255,255),nil,true)
mScene:addChild(bgLayer)
local closeBtn=ZyButton:new(image_exit, image_exit);
closeBtn:setPosition(PT(bgLayer:getContentSize().width-closeBtn:getContentSize().width - SX(15),bgLayer:getContentSize().height-closeBtn:getContentSize().height - SY(5)));
closeBtn:registerScriptTapHandler(closeBtnActon);
closeBtn:addto(bgLayer,99);
showLayout(table.RecordTabel)
end
end
elseif actionID == 1000 then
_1000Callback(pZyScene, lpExternalData);
end
end
function showLayout(data)
--[[
if layoutLayer then
mLayer:removeChild(layoutLayer,true)
layoutLayer=nil;
return
end
]]
layoutLayer=CCLayer:create()
bgLayer:addChild(layoutLayer,1)
local simpleW=(pWinSize.width*0.8)/3
local Bg=CCSprite:create(P(panle_1019_1_9))
local scalex=simpleW/Bg:getContentSize().width
local scaleList={0.7,1.1,1.2}
local cursor=pWinSize.width*0.1
local listBgStartY=pWinSize.height*0.75
allTable.ranKingTitlePos={}
allTable.biliSize={}
local table=nil
table={IDS_ORDER,IDS_NICKNAME1,IDS_SORCE1}
allTable.title={}
for i,v in ipairs(table) do
local temp=scaleList[i]
local textlabel=CCLabelTTF:create(v,FONT_NAME,FONT_SM_SIZE)
textlabel:setAnchorPoint(PT(0.5,0))
textlabel:setColor(ccRED1)
textlabel:setPosition(PT(cursor+simpleW*temp/2,listBgStartY+SY(2)))
allTable.ranKingTitlePos[i]=(textlabel:getPositionX())
allTable.biliSize[i]=simpleW*scaleList[i]
cursor=cursor+(simpleW*scaleList[i])
layoutLayer:addChild(textlabel,1)
allTable.title[i]=textlabel
end
mScrollView = CCScrollView:create()
mScrollSize = SZ(pWinSize.width*0.8 , pWinSize.height*0.63)
if nil ~= mScrollView then
mScrollView:setViewSize(mScrollSize)
mScrollView:setPosition(PT(pWinSize.width*0.1,listBgStartY - pWinSize.height*0.63))
mScrollView:setScale(1.0)
mScrollView:ignoreAnchorPointForPosition(true)
mScrollView:setDirection(kCCScrollViewDirectionVertical)
end
layoutLayer:addChild(mScrollView)
update(data)
end
function update(mtable)
if bgLayer == nil then
return
end
local bgEmpty = CCSprite:create(P(panle_1019_1_9))
local layer = CCLayer:create()
layer:setContentSize(CCSize(mScrollSize.width, bgEmpty:getContentSize().height*#mtable))
layer:setPosition(PT(0, -bgEmpty:getContentSize().height*#mtable + mScrollSize.height))
if layer and mScrollView then
mScrollView:setContainer(layer)
mScrollView:updateInset()
end
for i, v in ipairs(mtable) do
local bgEmpty = CCSprite:create(P(panle_1019_1_9))
local bgLayer = CCLayer:create()
bgLayer:setContentSize(CCSize(mScrollSize.width, bgEmpty:getContentSize().height))
layer:addChild(bgLayer,0)
bgLayer:setPosition(PT(-SX(50),layer:getContentSize().height-i*bgEmpty:getContentSize().height))
local table={i,v.UserName,v.Score }
for k, v in ipairs(table) do
local bgEmpty= CCScale9Sprite:create(P(panle_1019_1_9));
bgEmpty:setContentSize(CCSize(allTable.biliSize[k]*0.95,bgEmpty:getContentSize().height));
bgEmpty:setAnchorPoint(PT(0.5,0.5))
bgEmpty:setPosition(PT(allTable.ranKingTitlePos[k]-layer:getPositionX(),pWinSize.height*0.63/4/2))
bgLayer:addChild(bgEmpty,0)
local value=CCLabelTTF:create(v,FONT_NAME,FONT_SM_SIZE)
value:setAnchorPoint(PT(0.5,0.5))
value:setPosition(PT(allTable.ranKingTitlePos[k]-layer:getPositionX(),pWinSize.height*0.63/4/2))
bgLayer:addChild(value,0)
end
end
end
function _1001Callback(pZyScene, lpExternalData)
local DataTabel=nil
if ZyReader:getResult() == 0 then
DataTabel={}
DataTabel.PageCount= ZyReader:getInt()
local RecordNums_1=ZyReader:getInt()
local RecordTabel_1={}
if RecordNums_1~=0 then
for k=1,RecordNums_1 do
local mRecordTabel_1={}
ZyReader:recordBegin()
mRecordTabel_1.UserName= ZyReader:readString()
mRecordTabel_1.Score= ZyReader:getInt()
ZyReader:recordEnd()
table.insert(RecordTabel_1,mRecordTabel_1)
end
end
DataTabel.RecordTabel = RecordTabel_1;
else
local box = ZyMessageBoxEx:new()
box:doPrompt(pZyScene, nil, ZyReader:readErrorMsg(),IDS_OK)
end
return DataTabel
end
function _1000Callback(pZyScene, lpExternalData)
local DataTabel=nil
if ZyReader:getResult() == 0 then
DataTabel={}
closeSubmitLaye()
else
local box = ZyMessageBoxEx:new()
box:doPrompt(pZyScene, nil, ZyReader:readErrorMsg(), IDS_OK)
end
return DataTabel
end
| mit |
wenhulove333/ScutServer | Sample/GameRanking/Client/release_socket/lua/testScene.lua | 4 | 43283 | module("testScene", package.seeall)
function P(fileName)
if fileName then
return ScutDataLogic.CFileHelper:getPath(fileName)
else
return nil
end
end
------文字资源-------------------------
IDS_JINDOU = "金豆"
IDS_JIFEN = "积分"
IDS_JINGYAN = "经验"
IDS_SORCE = "分数:"
IDS_NICKNAME = "昵称:"
IDS_SORCE1 = "分数"
IDS_NICKNAME1 = "昵称"
IDS_OK="确认"
IDS_SUBMIT = "提交成绩"
IDS_CANCLE="取消"
IDS_EMPTY_TIP = "输入不能为空"
IDS_ORDER = "名次"
IDS_TEST = "请按右下角排行按钮进行TCP连接"
IDS_TCP_CONNECTING = "TCP连接建立中"
IDS_TCP_CONNECTED = "TCP连接已建立,接受数据中"
IDS_CONNECT_COUNT = "收到服务器推送数据%d次"
-----图片资源路径-------------------------
image_background_sm="common/list_1002_1.9.png"--背景图
image_list_txt="common/panle_1009_1.9.png"--文本输入框底图
image_list_txt_2="common/list_1004.9.png"--文本输入框底图
image_logo="Image/logo.png"--logo
image_logoSmall="Image/logo2.png" --小Logo
image_button_red_c_0="button/button_1012.png"--红色长按钮
image_button_red_c_1="button/button_1011.png"--红色长按钮
image_mainscene = "common/panel_1003_1.png" --背景
image_exit = "button/icon_1027.png" --返回按钮
image_roomBg="common/panel_1002_3.png" --房间背景
image_menuBg="common/panel_1006.png"--菜单背景
image_nameBg="common/panel_1002_1.9.png" --名字背景
image_shop_1="common/panel_1003_4.png" --头像商店
image_shop="common/panel_1003_5.png" --头像商店
---聊天
icon_1024="chat/icon_1024.png"--聊天按钮
tou_ming="common/tou_ming.9.png"--透明按钮
panle_1016_1="common/panle_1016_1.png"--下划线
button_1022="tabNameImg/button_1022.png"--即时聊天
button_1023="tabNameImg/button_1023.png"--聊天记录
--排行榜
button_1028="tabNameImg/button_1028.png"--金豆排行
button_1029="tabNameImg/button_1029.png"--胜率排行
button_1006="title/button_1006.png";--说明
panle_1019_1_9="button/panle_1019_1.9.png"--list中单个对应的背景框
panle_1014_1="common/panle_1014_1.png"--说明框背景框先用这张
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
mConnectNum = 0;
pWinSize=CCDirector:sharedDirector():getWinSize()
function PT(x,y)
return CCPoint(x,y)
end
function Half_Float(x)
return x*0.5
end
function SZ(width, height)
return CCSize(width, height)
end
function SCALEX(x)
return CCDirector:sharedDirector():getWinSize().width/480*x
end
function SCALEY(y)
return CCDirector:sharedDirector():getWinSize().height /320*y
end
FONT_NAME = "黑体"
FONT_DEF_SIZE = SCALEX(18)
FONT_SM_SIZE = SCALEX(15)
FONT_BIG_SIZE = SCALEX(23)
FONT_M_BIG_SIZE = SCALEX(63)
FONT_SMM_SIZE = SCALEX(13)
FONT_FM_SIZE=SCALEX(11)
FONT_FMM_SIZE=SCALEX(12)
FONT_FMMM_SIZE=SCALEX(9)
ccBLACK = ccc3(0,0,0)
ccWHITE = ccc3(255,255,255)
ccYELLOW = ccc3(255,255,0)
ccBLUE = ccc3(0,0,255)
ccGREEN = ccc3(0,255,0)
ccRED = ccc3(255,0,0)
ccMAGENTA = ccc3(255,0,255)
ccPINK = ccc3(228,56,214) -- 粉色
ccORANGE = ccc3(206, 79, 2) -- 橘红色
ccGRAY = ccc3(166,166,166)
ccC1=ccc3(45,245,250)
---通用颜色
ccRED1= ccc3(86,26,0)
ccYELLOW2=ccc3(241,176,63)
------获取资源的路径---------------------
function P(fileName)
if fileName then
return ScutDataLogic.CFileHelper:getPath(fileName)
else
return nil
end
end
function SX(x)
return SCALEX(x)
end
function SY(y)
return SCALEY(y)
end
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)
----------------------- ui control ----------------------------------------------
ZyButton = {
_menuItem = nil,
_label = nil,
_menu = nil,
_colorNormal = nil,
_colorSelected = nil,
_isSelected = nil,
}
ZyImage = {
_image = nil,
_scaleX = 1,
_scaleY = 1,
}
function ZyImage:new(param)
local instance = {}
if type(param) == "string" then
instance._image = self:imageWithFile(param)
elseif type(param) == "userdata" then
instance._image = param
end
instance._image:setAnchorPoint(CCPoint(0, 0))
setmetatable(instance, self)
self.__index = self
return instance
end
function ZyImage:imageWithFile(fileName)
local image =CCSprite:create(P(fileName))
image:setAnchorPoint(CCPoint(0, 0))
return image
end
function ZyImage:imageSize(fileName)
local sprite = CCSprite:create(P(fileName))
local size = sprite:getContentSize()
return size
end
function ZyImage:resize(size)
local oldSize = self._image:getContentSize()
self._scaleX = (size.width / oldSize.width)
self._scaleY = (size.height / oldSize.height)
self._image:setScaleX(self._scaleX)
self._image:setScaleY(self._scaleY)
self._image:setContentSize(size)
end
function ZyImage:image()
return self._image
end
function ZyImage:getContentSize()
return self._image:getContentSize()
end
function ZyButton:new(picNor, picDown, picDis, title, fontName, fontSize)
local instance = {}
setmetatable(instance, self)
self.__index = self
local addLabel = true
local label
local label1
local label2
local menuItem
local menu
if fontName == nil then
fontName = FONT_NAME
end
if fontSize == nil then
fontSize = FONT_SM_SIZE
end
if picNor and picDown and picDis then
menuItem = CCMenuItemImage:create(P(picNor), P(picDown), P(picDis))
elseif picNor and picDown then
menuItem = CCMenuItemImage:create(P(picNor), P(picDown))
elseif picNor then
local spriteNor = CCSprite:create(P(picNor))
local spriteDown = CCSprite:create(P(picNor))
if title then
local size = ZyFont.stringSize(title, spriteNor:getContentSize().width, fontName, fontSize)
label1 = CCLabelTTF:create(title,fontName, fontSize, size, kCCTextAlignmentCenter )
label1:setPosition(CCPoint(spriteNor:getContentSize().width / 2, spriteNor:getContentSize().height / 2))
spriteNor:addChild(label1, 0)
label2 = CCLabelTTF:create(title, fontName, fontSize, size, kCCTextAlignmentCenter)
label2:setPosition(CCPoint(spriteDown:getContentSize().width / 2, spriteDown:getContentSize().height / 2))
spriteDown:addChild(label2, 0)
spriteDown:setPosition(CCPoint(0, SY(-1)))
else
spriteDown:setScale(0.94)
spriteDown:setPosition(CCPoint(spriteNor:getContentSize().width * 0.03, spriteNor:getContentSize().height * 0.03))
end
menuItem = CCMenuItemSprite:create(spriteNor, spriteDown)
addLabel = true
else
menuItem = CCMenuItemLabel:itemWithLabel(instance._label)
addLabel = true
end
if addLabel and title then
if title then
label = CCLabelTTF:create(title, fontName, fontSize)
end
label:setPosition(CCPoint(menuItem:getContentSize().width / 2, menuItem:getContentSize().height / 2))
menuItem:addChild(label, 0)
end
menuItem:setAnchorPoint(CCPoint(0, 0))
menu = CCMenu:createWithItem(menuItem)
menu:setContentSize(menuItem:getContentSize())
menu:setAnchorPoint(CCPoint(0, 0))
instance._menuItem = menuItem
instance._menu = menu
instance._label = label
instance._label1 = label1
instance._label2 = label2
instance._isSelected = false
return instance
end
function setScaleXY(frame,scaleX,scaleY)
if scaleX~=nil then
frame:setScaleX(scaleX/frame:getContentSize().width)
end
if scaleY~=nil then
frame:setScaleX(scaleY/frame:getContentSize().height)
end
end
function ZyButton:addto(parent, param1, param2)
if type(param1) == "userdata" then
parent:addChildItem(self._menu, param1)
else
if param2 then
parent:addChild(self._menu, param1, param2)
elseif param1 then
parent:addChild(self._menu, param1)
else
parent:addChild(self._menu, 0)
end
end
end
function ZyButton:addChild(item,tag)
self._menuItem:addChild(item,tag)
end
function ZyButton:menuItem()
return self._menuItem
end
function ZyButton:menu()
return self._menu
end
function ZyButton:registerScriptTapHandler(handler)
self._menuItem:registerScriptTapHandler(handler)
end
function ZyButton:setIsEnabled(enabled)
self._menuItem:setEnabled(enabled)
end
function ZyButton:getIsEnabled()
return self._menuItem:getIsEnabled()
end
function ZyButton:setIsVisible(enabled)
self._menuItem:setVisible(enabled)
end
function ZyButton:setString(label)
if self._label1 then
self._label1:setString(label)
end
if self._label2 then
self._label2:setString(label)
end
if self._label then
self._label:setString(label)
end
end
function ZyButton:getString()
return self._label:getString()
end
--
function ZyButton:setColor(color)
if self._label then
self._label:setColor(color)
end
if self._label1 then
self._label1:setColor(color)
end
if self._label2 then
self._label2:setColor(color)
end
end
function ZyButton:setColorNormal(color)
self._colorNormal = color
if not self._isSelected then
self._label:setColor(color)
end
end
function ZyButton:setColorSelected(color)
self._colorSelected = color
if self._isSelected then
self._label:setColor(color)
end
end
function ZyButton:setTag(tag)
self._menuItem:setTag(tag)
end
function ZyButton:getTag(tag)
return self._menuItem:getTag()
end
function ZyButton:setPosition(position)
self._menu:setPosition(position)
end
function ZyButton:getPosition()
return self._menu:getPosition()
end
function ZyButton:setAnchorPoint(point)
self._menu:setAnchorPoint(point)
self._menuItem:setAnchorPoint(point)
end
function ZyButton:getAnchorPoint(ponint)
return self._menu:getAnchorPoint(point)
end
function ZyButton:setContentSize(size)
self._menu:setContentSize(size)
end
function ZyButton:getContentSize()
return self._menu:getContentSize()
end
function ZyButton:setScale(scale)
return self._menu:setScale(scale)
end
function ZyButton:setScaleX(scale)
return self._menu:setScaleX(scale)
end
function ZyButton:setScaleY(scale)
return self._menu:setScaleY(scale)
end
function ZyButton:getScale()
return self._menu:getScale()
end
function ZyButton:selected()
self._isSelected = true
self._menuItem:selected()
if self._colorSelected then
self._label:setColor(self._colorSelected)
elseif self._colorNormal then
self._label:setColor(self._colorNormal)
end
end
function ZyButton:unselected()
self._isSelected = false
self._menuItem:unselected()
if self._colorNormal then
self._label:setColor(self._colorNormal)
end
end
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
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 MenuItem(normalPic, downPic, listtener, strText, TextAlign, fontSize, color, bCheck, disablePic)
local strNor = nil
local strDown = nil
local strDisable = nil
if normalPic ~= nil then
strNor = (normalPic)
end
if downPic ~= nil then
strDown = (downPic)
end
if disablePic ~= nil then
strDisable = (disablePic)
end
local menuItem
if disablePic == nil then
menuItem = CCMenuItemImage:create(strNor, strDown)
else
menuItem = CCMenuItemImage:create(strNor, strDown, strDisable)
end
if bCheck then
menuItem:selected()
else
menuItem:unselected()
end
local pLable = nil
if strText ~= nil then
pLable = CCLabelTTF:create(strText, FONT_NAME, (fontSize))
end
local szMenu = menuItem:getContentSize()
if listtener ~= nil then
menuItem:registerScriptTapHandler(function () listtener(menuItem) end )
end
menuItem:setAnchorPoint(CCPoint(0, 0))
--TextAlign--
if pLable ~= nil then
if TextAlign == 0 then --AlignLeft
pLable:setAnchorPoint(CCPoint(0, 0.5))
pLable:setPosition(CCPoint(0, szMenu.height/2))
elseif TextAlign == 1 then --AlignCenter
pLable:setPosition(CCPoint(szMenu.width/2, szMenu.height/2))
else --ALignRight
pLable:setAnchorPoint(CCPoint(1, 0.5))
pLable:setPosition(CCPoint(szMenu.width/2, szMenu.height/2))
end
if color ~= nil then
pLable:setColor(color)
end
menuItem:addChild(pLable, 0, 0)
end
return menuItem, pLable
end
function Button(normalPic, downPic, listtener, strText, TextAlign, fontSize, color, tag, bCheck, disablePic)
menuItem = MenuItem(normalPic, downPic, listtener, strText, TextAlign, fontSize, color, bCheck, disablePic)
if tag ~= nil then
menuItem:setTag(tag)
end
local Btn = CCMenu:createWithItem(menuItem)
Btn:setContentSize(menuItem:getContentSize())
return Btn, menuItem
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: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((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 = 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 = 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:setCallbackFun(fun)
self._funCallback = fun
end
local mRankLayer
local mLayer
local tip1
local tip2
local tip3
local bgLayer
local submitLayer
local allTable={};
local mList;
local mNameEdit;
local mScoreEdit;
local isCanSubmit = true
local isCanGetRank = true
local mNameStr;
local mScoreStr;
-- close the ranking layer
function closeBtnActon()
if bgLayer then
mScene:removeChild(bgLayer,true);
bgLayer = nil
end
end
function showRank()
if isCanGetRank == false then
return
end
-- if addressPath is not nil use socket connect
local addressPath="ph.scutgame.com:9001"
ScutDataLogic.CNetWriter:getInstance():writeString("ActionId",1001)
ScutDataLogic.CNetWriter:getInstance():writeString("PageIndex",1 )
ScutDataLogic.CNetWriter:getInstance():writeString("PageSize",30)
ZyExecRequest(mScene, nil,false,addressPath )
if labelIds1 then
labelIds1:setVisible(false)
end
labelIds2 = CCLabelTTF:create(IDS_TCP_CONNECTING, "fsfe", FONT_SM_SIZE);
labelIds2:setPosition(labelIds1:getPosition());
mScene:addChild(labelIds2, 99);
end
function submitOK()
local name= mNameEdit:getText()
local sorce= mScoreEdit:getText()
if name=="" or sorce == "" then
local box = ZyMessageBoxEx:new()
box:doPrompt(mScene, nil,IDS_EMPTY_TIP,IDS_OK,messageCallback)
mNameEdit:setVisible(false);
mScoreEdit:setVisible(false);
else
local addressPath="ph.scutgame.com:9001"
ScutDataLogic.CNetWriter:getInstance():writeString("ActionId",1000)
ScutDataLogic.CNetWriter:getInstance():writeString("UserName",name )
ScutDataLogic.CNetWriter:getInstance():writeString("Score",sorce)
ZyExecRequest(mScene, nil,false,addressPath)
end
end
function createUIBg(titleImagePath,titleStr,textColor,closeBtnActionPath, touming)
local layer = CCLayer:create()
layer:setAnchorPoint(CCPoint(0,0))
layer:setPosition(CCPoint(0,0))
local bgPic = CCSprite:create(P(image_mainscene))
bgPic:setAnchorPoint(CCPoint(0,0))
bgPic:setScaleX(pWinSize.width/bgPic:getContentSize().width)
bgPic:setScaleY(pWinSize.height/bgPic:getContentSize().height)
bgPic:setPosition(CCPoint(0,0))
layer:addChild(bgPic, 0, 0)
layer:setContentSize(pWinSize)
if touming then
local toumingBg = CCSprite:create(P("common/panel_1002_12.png"))
toumingBg:setScaleX(pWinSize.width*0.92/toumingBg:getContentSize().width)
toumingBg:setScaleY(pWinSize.height*0.8/toumingBg:getContentSize().height)
toumingBg:setAnchorPoint(CCPoint(0,0))
toumingBg:setPosition(CCPoint(pWinSize.width*0.04, pWinSize.height*0.06))
layer:addChild(toumingBg, 0)
end
local closeBtn = nil
if closeBtnActionPath ~= nil then
local norClose = CCSprite:create(P(Image.image_close))
local norDown = CCSprite :create(P(Image.image_close))
norDown:setScale(0.9)
local menuItem = CCMenuItemSprite:itemFromNormalSprite(norClose, norDown)
norClose:setAnchorPoint(CCPoint(0.5,0.5))
norDown:setAnchorPoint(CCPoint(0.5, 0.5))
norClose:setPosition(CCPoint(menuItem:getContentSize().width/2, menuItem:getContentSize().height/2))
norDown:setPosition(CCPoint(menuItem:getContentSize().width/2, menuItem:getContentSize().height/2))
closeBtn = CCMenu:menuWithItem(menuItem)
menuItem:setAnchorPoint(CCPoint(0, 0))
menuItem:setPosition(CCPoint(0, 0))
menuItem:registerScriptHandler(closeBtnActionPath)
closeBtn:setContentSize(menuItem:getContentSize())
layer:addChild(closeBtn, 0, 0)
closeBtn:setPosition(CCPoint(layer:getContentSize().width - closeBtn:getContentSize().width,layer:getContentSize().height - closeBtn:getContentSize().height-SY(3)))
end
local titleImageLabel = nil
local titleStrLabel = nil
if titleImagePath then
titleImageLabel = CCSprite:create(P(titleImagePath))
titleImageLabel:setAnchorPoint(CCPoint(0,0))
titleImageLabel:setPosition(CCPoint(pWinSize.width*0.5-titleImageLabel:getContentSize().width*0.5,pWinSize.height*0.95-titleImageLabel:getContentSize().height))
layer:addChild(titleImageLabel,0)
end
if titleStr then
titleStrLabel = CCLabelTTF:create(titleStr, FONT_NAME, FONT_BIG_SIZE)
titleStrLabel:setAnchorPoint(CCPoint(0.5,0))
titleStrLabel:setPosition(CCPoint(pWinSize.width*0.5,pWinSize.height-titleStrLabel:getContentSize().height-SY(15)))
layer:addChild(titleStrLabel,0)
if textColor ~= nil then
titleStrLabel:setColor(textColor)
end
end
return layer
end
function messageCallback()
mNameEdit:setVisible(true);
mScoreEdit:setVisible(true);
end
function submitCancle()
closeSubmitLaye()
end
function submit()
if isCanSubmit == false then
return
end
isCanSubmit = false
isCanGetRank = false
local aa=nil
local ww=288
local hh=0
local xx=(pWinSize.width-ww)/2
local imgSprite=CCSprite:create(P(image_list_txt));
local txt_h= imgSprite:getContentSize().height
submitLayer = CCLayer:create();
submitLayer:setContentSize(CCSize(SX(240),SY(160)));
mScene:addChild(submitLayer);
submitLayer:setAnchorPoint(PT(0.5,0.5));
submitLayer:setPosition(PT(mScene:getContentSize().width/2, mScene:getContentSize().height/2));
local sprite = CCSprite:create(P("common/panel_1002_12.png"))
sprite:setScaleX(SX(240)/sprite:getContentSize().width);
sprite:setScaleY(SY(160)/sprite:getContentSize().height);
submitLayer:addChild(sprite,0);
local startY = 0
local titleName1=CCLabelTTF:create(IDS_NICKNAME,FONT_NAME, FONT_DEF_SIZE);
titleName1:setAnchorPoint(CCPoint(0,0))
titleName1:setPosition(CCPoint(SX(-100),
startY+titleName1:getContentSize().height - SY(30)))
submitLayer:addChild(titleName1)
titleName1:setColor(ccc3(0,0,0))
local txt_x=titleName1:getPositionX()+SX(8)+titleName1:getContentSize().width
local txt_ww=xx+ww-txt_x-SX(44)
local bgEmCCPointy1= CCSprite:create(P(image_list_txt))
mNameEdit = CCEditBox:create(CCSize(SX(120),bgEmCCPointy1:getContentSize().height), CCScale9Sprite:create(P(image_list_txt)))
mNameEdit:setPosition(CCPoint(titleName1:getPositionX()+ titleName1:getContentSize().width + SX(60) ,titleName1:getPositionY()+SY(5)))
mNameEdit:setFontColor(ccc3(0,0,0))
submitLayer:addChild(mNameEdit)
local titleName=CCLabelTTF:create(IDS_SORCE, "sfeew", FONT_DEF_SIZE);
titleName:setColor(ccc3(0,0,0))
titleName:setAnchorPoint(CCPoint(0,0))
aa=(hh/2-titleName:getContentSize().height)/2
titleName:setPosition(CCPoint(titleName1:getPositionX(),titleName1:getPositionY()+txt_h+SY(10)))
submitLayer:addChild(titleName)
mScoreEdit = CCEditBox:create(CCSize(SX(120),bgEmCCPointy1:getContentSize().height), CCScale9Sprite:create(P(image_list_txt)))
mScoreEdit:setFontColor(ccc3(0,0,0))
mScoreEdit:setPosition(CCPoint(titleName:getPositionX() + titleName:getContentSize().width + SX(60) ,titleName:getPositionY()+SY(5)))
submitLayer:addChild(mScoreEdit)
mScoreEdit:setVisible(true)
local button2 = ZyButton:new("button/button_1011.png", "button/button_1012.png",nil,IDS_OK)
button2:setPosition(PT(SX(-30) -button2:getContentSize().width,SY(-50)));
button2:addto(submitLayer,0)
button2:registerScriptTapHandler(submitOK);
local button3 = ZyButton:new("button/button_1011.png", "button/button_1012.png",nil,IDS_CANCLE)
button3:setPosition(PT(SX(30) ,SY(-50)));
button3:addto(submitLayer,0)
button3:registerScriptTapHandler(submitCancle);
end
function closeSubmitLaye()
mScene:removeChild(submitLayer,true)
isCanSubmit = true
isCanGetRank = true
end
function init()
if mScene then
return
end
local scene = ScutScene:new()
mScene = scene.root
scene:registerCallback(netCallback)
CCDirector:sharedDirector():pushScene(mScene)
pWinSize = mScene:getContentSize()
mLayer = CCLayer:create()
mLayer:setAnchorPoint(CCPoint(0,0))
mLayer:setPosition(CCPoint(0,0))
mScene:addChild(mLayer, 0)
mRankLayer = CCLayer:create();
mRankLayer:setAnchorPoint(PT(0.5, 0.5));
mRankLayer:setPosition(PT(pWinSize.width/2, pWinSize.height/2));
CCDirector:sharedDirector():pushScene(mScene)
local bgSprite=CCSprite:create(P("beijing.jpg"))
bgSprite:setScaleX(pWinSize.width/bgSprite:getContentSize().width)
bgSprite:setScaleY(pWinSize.height/bgSprite:getContentSize().height)
bgSprite:setAnchorPoint(CCPoint(0.5,0.5))
bgSprite:setPosition(CCPoint(pWinSize.width/2,pWinSize.height/2));
mScene:addChild(bgSprite);
--ScutDataLogic.CNetWriter:setUrl("http://ph.scutgame.com/service.aspx")
local button = ZyButton:new("icon_1011.png");
button:addto(mScene,0);
button:setPosition(PT(pWinSize.width - button:getContentSize().width - SX(10), SY(10)));
button:registerScriptTapHandler(showRank)
local button2 = ZyButton:new("button/button_1011.png", "button/button_1012.png",nil,IDS_SUBMIT)
button2:setPosition(PT(pWinSize.width/2 - button2:getContentSize().width/2 ,SY(10)));
button2:addto(mScene,0)
button2:registerScriptTapHandler(submit);
-- 请按右下角排行按钮进行TCP连接
labelIds1 = CCLabelTTF:create(IDS_TEST,"sfeew", FONT_SM_SIZE);
labelIds1:setPosition(PT(SX(20) + labelIds1:getContentSize().width/2 , pWinSize.height - SY(18)));
labelIds1:setAnchorPoint(PT(0.5,0.5));
mScene:addChild(labelIds1,99);
end
function netCallback(pZyScene, lpExternalData, isTcp)
local actionID = ZyReader:getActionID()
local lpExternalData = lpExternalData or 0
local userData = ZyRequestParam:getParamData(lpExternalData)
if actionID==1001 then
local table = _1001Callback(pZyScene, lpExternalData);
if labelIds2 then
labelIds2:setVisible(false)
end
labelIds3 = CCLabelTTF:create(IDS_TCP_CONNECTED, "xxxx", FONT_SM_SIZE);
labelIds3:setPosition(labelIds2:getPosition());
mScene:addChild(labelIds3);
if isTcp == true then
mConnectNum = mConnectNum + 1 ;
end
if labelIds4 == nil then
labelIds4 = CCLabelTTF:create(string.format(IDS_CONNECT_COUNT,mConnectNum), "xxxx", FONT_SM_SIZE);
labelIds4:setPosition(PT(labelIds3:getPositionX() , labelIds3:getPositionY() - SY(15)));
mScene:addChild(labelIds4, 99);
else
labelIds4:setString(string.format(IDS_CONNECT_COUNT,mConnectNum));
end
if table then
if bgLayer == nil then
bgLayer= createUIBg(nil,nil,ccc3(255,255,255),nil,true)
mScene:addChild(bgLayer)
local closeBtn=ZyButton:new(image_exit, image_exit);
closeBtn:setPosition(PT(bgLayer:getContentSize().width-closeBtn:getContentSize().width - SX(15),bgLayer:getContentSize().height-closeBtn:getContentSize().height - SY(5)));
closeBtn:registerScriptTapHandler(closeBtnActon);
closeBtn:addto(bgLayer,99);
showLayout(table.RecordTabel)
end
end
elseif actionID == 1000 then
_1000Callback(pZyScene, lpExternalData);
end
end
function showLayout(data)
--[[
if layoutLayer then
mLayer:removeChild(layoutLayer,true)
layoutLayer=nil;
return
end
]]
layoutLayer=CCLayer:create()
bgLayer:addChild(layoutLayer,1)
local simpleW=(pWinSize.width*0.8)/3
local Bg=CCSprite:create(P(panle_1019_1_9))
local scalex=simpleW/Bg:getContentSize().width
local scaleList={0.7,1.1,1.2}
local cursor=pWinSize.width*0.1
local listBgStartY=pWinSize.height*0.75
allTable.ranKingTitlePos={}
allTable.biliSize={}
local table=nil
table={IDS_ORDER,IDS_NICKNAME1,IDS_SORCE1}
allTable.title={}
for i,v in ipairs(table) do
local temp=scaleList[i]
local textlabel=CCLabelTTF:create(v,FONT_NAME,FONT_SM_SIZE)
textlabel:setAnchorPoint(PT(0.5,0))
textlabel:setColor(ccRED1)
textlabel:setPosition(PT(cursor+simpleW*temp/2,listBgStartY+SY(2)))
allTable.ranKingTitlePos[i]=(textlabel:getPositionX())
allTable.biliSize[i]=simpleW*scaleList[i]
cursor=cursor+(simpleW*scaleList[i])
layoutLayer:addChild(textlabel,1)
allTable.title[i]=textlabel
end
mScrollView = CCScrollView:create()
mScrollSize = SZ(pWinSize.width*0.8 , pWinSize.height*0.63)
if nil ~= mScrollView then
mScrollView:setViewSize(mScrollSize)
mScrollView:setPosition(PT(pWinSize.width*0.1,listBgStartY - pWinSize.height*0.63))
mScrollView:setScale(1.0)
mScrollView:ignoreAnchorPointForPosition(true)
mScrollView:setDirection(kCCScrollViewDirectionVertical)
end
layoutLayer:addChild(mScrollView)
update(data)
end
function update(mtable)
if bgLayer == nil then
return
end
local bgEmpty = CCSprite:create(P(panle_1019_1_9))
local layer = CCLayer:create()
layer:setContentSize(CCSize(mScrollSize.width, bgEmpty:getContentSize().height*#mtable))
layer:setPosition(PT(0, -bgEmpty:getContentSize().height*#mtable + mScrollSize.height))
if layer and mScrollView then
mScrollView:setContainer(layer)
mScrollView:updateInset()
end
for i, v in ipairs(mtable) do
local bgEmpty = CCSprite:create(P(panle_1019_1_9))
local bgLayer = CCLayer:create()
bgLayer:setContentSize(CCSize(mScrollSize.width, bgEmpty:getContentSize().height))
layer:addChild(bgLayer,0)
bgLayer:setPosition(PT(-SX(50),layer:getContentSize().height-i*bgEmpty:getContentSize().height))
local table={i,v.UserName,v.Score }
for k, v in ipairs(table) do
local bgEmpty= CCScale9Sprite:create(P(panle_1019_1_9));
bgEmpty:setContentSize(CCSize(allTable.biliSize[k]*0.95,bgEmpty:getContentSize().height));
bgEmpty:setAnchorPoint(PT(0.5,0.5))
bgEmpty:setPosition(PT(allTable.ranKingTitlePos[k]-layer:getPositionX(),pWinSize.height*0.63/4/2))
bgLayer:addChild(bgEmpty,0)
local value=CCLabelTTF:create(v,FONT_NAME,FONT_SM_SIZE)
value:setAnchorPoint(PT(0.5,0.5))
value:setPosition(PT(allTable.ranKingTitlePos[k]-layer:getPositionX(),pWinSize.height*0.63/4/2))
bgLayer:addChild(value,0)
end
end
end
function _1001Callback(pZyScene, lpExternalData)
local DataTabel=nil
if ZyReader:getResult() == 0 then
DataTabel={}
DataTabel.PageCount= ZyReader:getInt()
local RecordNums_1=ZyReader:getInt()
local RecordTabel_1={}
if RecordNums_1~=0 then
for k=1,RecordNums_1 do
local mRecordTabel_1={}
ZyReader:recordBegin()
mRecordTabel_1.UserName= ZyReader:readString()
mRecordTabel_1.Score= ZyReader:getInt()
ZyReader:recordEnd()
table.insert(RecordTabel_1,mRecordTabel_1)
end
end
DataTabel.RecordTabel = RecordTabel_1;
else
local box = ZyMessageBoxEx:new()
box:doPrompt(pZyScene, nil, ZyReader:readErrorMsg(),IDS_OK)
end
return DataTabel
end
function _1000Callback(pZyScene, lpExternalData)
local DataTabel=nil
if ZyReader:getResult() == 0 then
DataTabel={}
closeSubmitLaye()
else
local box = ZyMessageBoxEx:new()
box:doPrompt(pZyScene, nil, ZyReader:readErrorMsg(), IDS_OK)
end
return DataTabel
end
| mit |
nyczducky/darkstar | scripts/globals/weaponskills/steel_cyclone.lua | 26 | 1617 | -----------------------------------
-- Steel Cyclone
-- Great Axe weapon skill
-- Skill level: 240
-- Delivers a single-hit attack. Damage varies with TP.
-- In order to obtain Steel Cyclone, the quest The Weight of Your Limits must be completed.
-- Will stack with Sneak Attack.
-- Aligned with the Breeze Gorget, Aqua Gorget & Snow Gorget.
-- Aligned with the Breeze Belt, Aqua Belt & Snow Belt.
-- Element: None
-- Modifiers: STR:60% ; VIT:60%
-- 100%TP 200%TP 300%TP
-- 1.50 2.5 4.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.5; params.ftp200 = 1.75; params.ftp300 = 3;
params.str_wsc = 0.5; params.dex_wsc = 0.0; params.vit_wsc = 0.5; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
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.66;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp200 = 2.5; params.ftp300 = 4;
params.str_wsc = 0.6; params.vit_wsc = 0.6;
params.atkmulti = 1.5;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
AquariaOSE/Aquaria | files/scripts/entities/formupgradeenergy2.lua | 6 | 2754 | -- 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.charge = 0
v.delay = 1
function init(me)
setupEntity(me, "FormUpgrades/EnergyIdol")
entity_setDamageTarget(me, DT_AVATAR_ENERGYBLAST, false)
entity_setCollideRadius(me, 50)
entity_setMaxSpeed(me, 450)
entity_setEntityType(me, ET_ENEMY)
entity_setAllDamageTargets(me, false)
entity_setDamageTarget(me, DT_AVATAR_SHOCK, true)
entity_setDamageTarget(me, DT_AVATAR_ENERGYBLAST, true)
if hasFormUpgrade(FORMUPGRADE_ENERGY2) then
entity_setState(me, STATE_CHARGED)
end
end
function hitSurface(me)
entity_setWeight(me, 0)
entity_clearVel(me)
end
function update(me, dt)
entity_handleShotCollisions(me)
entity_updateMovement(me, dt)
entity_updateCurrents(me)
if not entity_isState(me, STATE_CHARGED) then
v.delay = v.delay - dt
if v.delay < 0 then
v.delay = 0.5
v.charge = v.charge - 1
if v.charge < 0 then
v.charge = 0
end
end
end
end
function enterState(me)
if entity_isState(me, STATE_CHARGED) then
entity_setAllDamageTargets(me, false)
entity_setTexture(me, "FormUpgrades/EnergyIdol-Charged")
--debugLog(msg("GET ENERGY FORM UPGRADE!"))
learnFormUpgrade(FORMUPGRADE_ENERGY2)
elseif entity_isState(me, STATE_INHOLDER) then
entity_setWeight(me, 0)
entity_clearVel(me)
end
end
function exitState(me)
end
function damage(me, attacker, bone, damageType, dmg)
if not entity_isState(me, STATE_CHARGED) then
if damageType == DT_AVATAR_ENERGYBLAST then
--v.charge = v.charge + dmg
elseif damageType == DT_AVATAR_SHOCK then
v.charge = v.charge + 10
end
if v.charge >= 10 then
playSfx("EnergyOrbCharge")
spawnParticleEffect("EnergyOrbCharge", entity_x(me), entity_y(me))
setControlHint("Naija's Energy Form has been upgraded. Energy Blasts will deal more damage.", 0, 0, 0, 8)
entity_setState(me, STATE_CHARGED)
end
end
return false
end
function activate(me)
end
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/King_Ranperres_Tomb/npcs/_5a0.lua | 14 | 2515 | -----------------------------------
-- Area: King Ranperre's Tomb
-- DOOR: _5a0 (Heavy Stone Door)
-- @pos -39.000 4.823 20.000 190
-----------------------------------
package.loaded["scripts/zones/King_Ranperres_Tomb/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/King_Ranperres_Tomb/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local currentMission = player:getCurrentMission(SANDORIA);
local MissionStatus = player:getVar("MissionStatus");
if (currentMission == RANPERRE_S_FINAL_REST and MissionStatus == 1) then
if (GetMobAction(17555898) == 0 and GetMobAction(17555899) == 0 and GetMobAction(17555900) == 0) then
if (player:getVar("Mission6-2MobKilled") == 1) then
player:setVar("Mission6-2MobKilled",0);
player:setVar("MissionStatus",2);
else
SpawnMob(17555898):updateClaim(player);
SpawnMob(17555899):updateClaim(player);
SpawnMob(17555900):updateClaim(player);
end
end
elseif (currentMission == RANPERRE_S_FINAL_REST and MissionStatus == 2) then
player:startEvent(0x0006);
elseif (currentMission == RANPERRE_S_FINAL_REST and MissionStatus == 3) then
player:startEvent(0x0007);
elseif (currentMission == RANPERRE_S_FINAL_REST and MissionStatus == 8) then
player:startEvent(0x0005);
elseif (currentMission == THE_HEIR_TO_THE_LIGHT and MissionStatus == 6) then
player:startEvent(0x000e);
else
player:messageSpecial(HEAVY_DOOR);
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 == 0x0005) then
player:setVar("MissionStatus",9);
elseif (csid == 0x000e) then
player:setVar("MissionStatus",7);
-- at this point 3 optional cs are available and open until watched (add 3 var to char?)
end
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/globals/items/plate_of_tentacle_sushi_+1.lua | 12 | 1747 | -----------------------------------------
-- ID: 5216
-- Item: plate_of_tentacle_sushi_+1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- HP 20
-- Dexterity 3
-- Agility 3
-- Accuracy % 20 (cap 20)
-- Ranged Accuracy % 20 (cap 20)
-- Double Attack 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,3600,5216);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 20);
target:addMod(MOD_DEX, 3);
target:addMod(MOD_AGI, 3);
target:addMod(MOD_FOOD_ACCP, 20);
target:addMod(MOD_FOOD_ACC_CAP, 20);
target:addMod(MOD_FOOD_RACCP, 20);
target:addMod(MOD_FOOD_RACC_CAP, 20);
target:addMod(MOD_DOUBLE_ATTACK, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 20);
target:delMod(MOD_DEX, 3);
target:delMod(MOD_AGI, 3);
target:delMod(MOD_FOOD_ACCP, 20);
target:delMod(MOD_FOOD_ACC_CAP, 20);
target:delMod(MOD_FOOD_RACCP, 20);
target:delMod(MOD_FOOD_RACC_CAP, 20);
target:delMod(MOD_DOUBLE_ATTACK, 1);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/globals/spells/shellra_v.lua | 26 | 1101 | -----------------------------------------
-- Spell: Shellra
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local meritBonus = caster:getMerit(MERIT_SHELLRA_V);
local duration = 1800;
local power = 62;
if (meritBonus > 0) then -- certain mobs can cast this spell, so don't apply the -2 for having 0 merits.
power = power + meritBonus - 2;
end
power = power * 100/256; -- doing it this way because otherwise the merit power would have to be 0.78125.
--printf("Shellra V Power: %d", power);
duration = calculateDurationForLvl(duration, 75, target:getMainLvl());
local typeEffect = EFFECT_SHELL;
if (target:addStatusEffect(typeEffect, power, 0, duration)) then
spell:setMsg(230);
else
spell:setMsg(75); -- no effect
end
return typeEffect;
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/globals/items/sausage_roll.lua | 12 | 1759 | -----------------------------------------
-- ID: 4396
-- Item: sausage_roll
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Health % 6 (cap 160)
-- Vitality 3
-- Intelligence -1
-- Attack % 27
-- Attack Cap 30
-- Ranged ATT % 27
-- Ranged ATT Cap 30
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,4396);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 6);
target:addMod(MOD_FOOD_HP_CAP, 160);
target:addMod(MOD_VIT, 3);
target:addMod(MOD_INT, -1);
target:addMod(MOD_FOOD_ATTP, 27);
target:addMod(MOD_FOOD_ATT_CAP, 30);
target:addMod(MOD_FOOD_RATTP, 27);
target:addMod(MOD_FOOD_RATT_CAP, 30);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 6);
target:delMod(MOD_FOOD_HP_CAP, 160);
target:delMod(MOD_VIT, 3);
target:delMod(MOD_INT, -1);
target:delMod(MOD_FOOD_ATTP, 27);
target:delMod(MOD_FOOD_ATT_CAP, 30);
target:delMod(MOD_FOOD_RATTP, 27);
target:delMod(MOD_FOOD_RATT_CAP, 30);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/globals/items/cup_of_caravan_tea.lua | 12 | 1329 | -----------------------------------------
-- ID: 5927
-- Item: Cup of Caravan Tea
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- HP 22
-- MP 32
-- Charisma 6
-- Intelligence 4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5927);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 22);
target:addMod(MOD_MP, 32);
target:addMod(MOD_CHR, 6);
target:addMod(MOD_INT, 4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 22);
target:delMod(MOD_MP, 32);
target:delMod(MOD_CHR, 6);
target:delMod(MOD_INT, 4);
end;
| gpl-3.0 |
sjznxd/lc-20121231 | applications/luci-radvd/luasrc/model/cbi/radvd/rdnss.lua | 74 | 2324 | --[[
LuCI - Lua Configuration Interface
Copyright 2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local sid = arg[1]
local utl = require "luci.util"
m = Map("radvd", translatef("Radvd - RDNSS"),
translate("Radvd is a router advertisement daemon for IPv6. " ..
"It listens to router solicitations and sends router advertisements " ..
"as described in RFC 4861."))
m.redirect = luci.dispatcher.build_url("admin/network/radvd")
if m.uci:get("radvd", sid) ~= "rdnss" then
luci.http.redirect(m.redirect)
return
end
s = m:section(NamedSection, sid, "interface", translate("RDNSS Configuration"))
s.addremove = false
--
-- General
--
o = s:option(Flag, "ignore", translate("Enable"))
o.rmempty = false
function o.cfgvalue(...)
local v = Flag.cfgvalue(...)
return v == "1" and "0" or "1"
end
function o.write(self, section, value)
Flag.write(self, section, value == "1" and "0" or "1")
end
o = s:option(Value, "interface", translate("Interface"),
translate("Specifies the logical interface name this section belongs to"))
o.template = "cbi/network_netlist"
o.nocreate = true
o.optional = false
function o.formvalue(...)
return Value.formvalue(...) or "-"
end
function o.validate(self, value)
if value == "-" then
return nil, translate("Interface required")
end
return value
end
function o.write(self, section, value)
m.uci:set("radvd", section, "ignore", 0)
m.uci:set("radvd", section, "interface", value)
end
o = s:option(DynamicList, "addr", translate("Addresses"),
translate("Advertised IPv6 RDNSS. If empty, the current IPv6 address of the interface is used"))
o.optional = false
o.rmempty = true
o.datatype = "ip6addr"
o.placeholder = translate("default")
function o.cfgvalue(self, section)
local l = { }
local v = m.uci:get_list("radvd", section, "addr")
for v in utl.imatch(v) do
l[#l+1] = v
end
return l
end
o = s:option(Value, "AdvRDNSSLifetime", translate("Lifetime"),
translate("Specifies the maximum duration how long the RDNSS entries are used for name resolution."))
o.datatype = 'or(uinteger,"infinity")'
o.placeholder = 1200
return m
| apache-2.0 |
nyczducky/darkstar | scripts/globals/weaponskills/tachi_kasha.lua | 18 | 1884 | -----------------------------------
-- Tachi Kasha
-- Great Katana weapon skill
-- Skill Level: 250
-- Paralyzes target. Damage varies with TP.
-- Paralyze effect duration is 60 seconds when unresisted.
-- In order to obtain Tachi: Kasha, the quest The Potential Within must be completed.
-- Will stack with Sneak Attack.
-- Tachi: Kasha appears to have a moderate attack bonus of +50%. [1]
-- Aligned with the Flame Gorget, Light Gorget & Shadow Gorget.
-- Aligned with the Flame Belt, Light Belt & Shadow Belt.
-- Element: None
-- Modifiers: STR:75%
-- 100%TP 200%TP 300%TP
-- 1.5625 2.6875 4.125
-----------------------------------
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.56; params.ftp200 = 1.88; params.ftp300 = 2.5;
params.str_wsc = 0.75; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1.5;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 1.5625; params.ftp200 = 2.6875; params.ftp300 = 4.125;
params.str_wsc = 0.75;
params.atkmulti = 1.65
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
if (damage > 0 and target:hasStatusEffect(EFFECT_PARALYSIS) == false) then
target:addStatusEffect(EFFECT_PARALYSIS, 25, 0, 60);
end
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Phomiuna_Aqueducts/npcs/_0rt.lua | 14 | 1640 | -----------------------------------
-- Area: Phomiuna_Aqueducts
-- NPC: Oil lamp
-- @pos -60 -23 60 27
-----------------------------------
package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Phomiuna_Aqueducts/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local DoorOffset = npc:getID();
player:messageSpecial(LAMP_OFFSET+3); -- wind lamp
npc:openDoor(7); -- lamp animation
local element = VanadielDayElement();
--printf("element: %u",element);
if (element == 3) then -- winday
if (GetNPCByID(DoorOffset-1):getAnimation() == 8) then -- lamp earth open?
GetNPCByID(DoorOffset-8):openDoor(15); -- Open Door _0rk
end
elseif (element == 4) then -- iceday
if (GetNPCByID(DoorOffset-5):getAnimation() == 8) then -- lamp ice open?
GetNPCByID(DoorOffset-8):openDoor(15); -- Open Door _0rk
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
nyczducky/darkstar | scripts/zones/Port_Windurst/npcs/_6o6.lua | 14 | 1442 | -----------------------------------
-- Area: Port Windurst
-- NPC: Door: Departures Exit
-- @zone 240
-- @pos 218 -5 114
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(AIRSHIP_PASS) == true and player:getGil() >= 200) then
player:startEvent(0x00b5,0,8,0,0,0,0,0,200);
else
player:startEvent(0x00b7,0,8);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x00b5) then
X = player:getXPos();
if (X >= 221 and X <= 225) then
player:delGil(200);
end
end
end;
| gpl-3.0 |
Sojerbot/new | plugins/inrealm.lua | 13 | 25404 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'گروهی بانام [ '..string.gsub(group_name, '_', ' ')..' ] ساخته شد.'
end
end
local function create_realm(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'گپ مادر بانام [ '..string.gsub(group_name, '_', ' ')..' ] ساخته شد.'
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function get_group_type(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not data[tostring(msg.to.id)]['group_type'] then
return 'No group type available.'
end
local group_type = data[tostring(msg.to.id)]['group_type']
return group_type
else
return 'Chat type not found.'
end
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function set_description(msg, data, target, about)
if not is_admin(msg) then
return "فقط ادمین رباتا"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'قوانین گروه:\n'..about
end
local function set_rules(msg, data, target)
if not is_admin(msg) then
return "فقط ادمین"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'قوانین گروه:\n'..rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin(msg) then
return "فقط ادمین!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'غیرفعال' then
return 'اسم گروه قفل است.'
else
data[tostring(target)]['settings']['lock_name'] = 'فعال'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'اسم گروه قفل است.'
end
end
local function unlock_group_name(msg, data, target)
if not is_admin(msg) then
return "فقط ادمین"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'غیرفعال' then
return 'اسم گروه آزاد شد.'
else
data[tostring(target)]['settings']['lock_name'] = 'غیر فعال'
save_data(_config.moderation.data, data)
return 'اسم گروه آزاد شد.'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin(msg) then
return "فقط ادمین"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'فعال' then
return 'قفل ادد ممبر فعال'
else
data[tostring(target)]['settings']['lock_member'] = 'فعال'
save_data(_config.moderation.data, data)
end
return 'قفل اددممبر فعال'
end
local function unlock_group_member(msg, data, target)
if not is_admin(msg) then
return "فقط ادمین"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'غیرفعال' then
return 'اددممبر قفل نیست'
else
data[tostring(target)]['settings']['lock_member'] = 'غیر فعال'
save_data(_config.moderation.data, data)
return 'قفل ادد ممبر فعال نیست'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin(msg) then
return "فقط ادمین"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'فعال' then
return 'قفل عکس فعال'
else
data[tostring(target)]['settings']['set_photo'] = 'صبرکنید'
save_data(_config.moderation.data, data)
end
return 'هرعکسی که بفرستی میزارم روی پروفایل گروه'
end
local function unlock_group_photo(msg, data, target)
if not is_admin(msg) then
return "فقط ادمین"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'غیرفعال' then
return 'عکس گروه قفل نیست'
else
data[tostring(target)]['settings']['lock_photo'] = 'غیرفعال'
save_data(_config.moderation.data, data)
return 'قفل عکس گروه غیرفعال شد'
end
end
local function lock_group_flood(msg, data, target)
if not is_admin(msg) then
return "فقط ادمین"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'فعال' then
return 'اسپم قفل شد'
else
data[tostring(target)]['settings']['flood'] = 'فعال'
save_data(_config.moderation.data, data)
return 'اسپم فعال'
end
end
local function unlock_group_flood(msg, data, target)
if not is_admin(msg) then
return "فقط ادمین"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'فعال' then
return 'قفل اسپم غیرفعال'
else
data[tostring(target)]['settings']['flood'] = 'غیرفعال'
save_data(_config.moderation.data, data)
return 'قفل اسپم غیرفعال'
end
end
-- show group settings
local function show_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin(msg) then
return "فقط ادمین"
end
local settings = data[tostring(target)]['settings']
local text = "تنظیمات گروه:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
send_large_msg(receiver, text)
local file = io.open("./groups/lists/"..result.id.."لیست افراداینگروه.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function returnidsfile(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
local file = io.open("./groups/lists/"..result.id.."لیست افزاد این گروه.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_name..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List for Realm admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function groups_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'
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function realms_list(msg)
local data = load_data(_config.moderation.data)
local realms = 'realms'
if not data[tostring(realms)] then
return 'No Realms at the moment'
end
local message = 'List of Realms:\n'
for k,v in pairs(data[tostring(realms)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['admins_in'] then
group_owner = tostring(data[tostring(v)]['admins_in'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/realms.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function set_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'yes' then
return 'Log group is already set'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes'
save_data(_config.moderation.data, data)
return 'Log group has been set'
end
end
local function unset_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'no' then
return 'Log group is already disabled'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no'
save_data(_config.moderation.data, data)
return 'log group has been disabled'
end
end
local function help()
local help_text = tostring(_config.help_text_realm)
return help_text
end
function run(msg, matches)
--vardump(msg)
local name_log = user_print_name(msg.from)
if matches[1] == 'log' and is_owner(msg) then
savelog(msg.to.id, "log file created by owner")
send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnidsfile, {receiver=receiver})
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
end
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
group_type = 'group'
return create_group(msg)
end
if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then
return --Do nothing
end
if matches[1] == 'createrealm' and matches[2] then
group_name = matches[2]
group_type = 'realm'
return create_realm(msg)
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[2] then if data[tostring(matches[2])] then
local settings = data[tostring(matches[2])]['settings']
if matches[1] == 'setabout' and matches[2] then
local target = matches[2]
local about = matches[3]
return set_description(msg, data, target, about)
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then --group lock *
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
end
if matches[1] == 'unlock' then --group unlock *
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
end
if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then
local target = matches[2]
return show_group_settings(msg, data, target)
end
if matches[1] == 'setname' and is_realm(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setgpname' and is_admin(msg) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
end
end
if matches[1] == 'help' and is_realm(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'set' then
if matches[2] == 'loggroup' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group")
return set_log_group(msg)
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return modrem(msg),
print("Closing Group: "..receiver),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'Error: Group '..matches[3]..' not found'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return realmrem(msg),
print("Closing realm: "..receiver),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'Error: Realm '..matches[3]..' not found'
end
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if not is_admin(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been demoted")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'type'then
local group_type = get_group_type(msg)
return group_type
end
if matches[1] == 'list' and matches[2] == 'admins' then
return admin_list(msg)
end
if matches[1] == 'list' and matches[2] == 'groups' then
if msg.to.type == 'chat' then
groups_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
elseif msg.to.type == 'user' then
groups_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
end
end
if matches[1] == 'list' and matches[2] == 'realms' then
if msg.to.type == 'chat' then
realms_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
elseif msg.to.type == 'user' then
realms_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
end
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
return {
patterns = {
"^[!/](creategroup) (.*)$",
"^[!/](createrealm) (.*)$",
"^[!/](setabout) (%d+) (.*)$",
"^[!/](setrules) (%d+) (.*)$",
"^[!/](setname) (.*)$",
"^[!/](setgpname) (%d+) (.*)$",
"^[!/](setname) (%d+) (.*)$",
"^[!/](lock) (%d+) (.*)$",
"^[!/](unlock) (%d+) (.*)$",
"^[!/](setting) (%d+)$",
"^[!/](wholist)$",
"^[!/](who)$",
"^[!/](type)$",
"^[!/](kill) (chat) (%d+)$",
"^[!/](kill) (realm) (%d+)$",
"^[!/](addadmin) (.*)$", -- sudoers only
"^[!/](removeadmin) (.*)$", -- sudoers only
"^[!/](list) (.*)$",
"^[!/](log)$",
"^[!/](help)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
dtrip/awesome | tests/examples/text/gears/object/properties.lua | 6 | 1286 | --DOC_GEN_OUTPUT --DOC_HIDE
local gears = require("gears") --DOC_HIDE
-- Create a class for this object. It will be used as a backup source for
-- methods and accessors. It is also possible to set them directly on the
-- object.
local class = {}
function class:get_foo()
print("In get foo", self._foo or "bar")
return self._foo or "bar"
end
function class:set_foo(value)
print("In set foo", value)
-- In case it is necessary to bypass the object property system, use
-- `rawset`
rawset(self, "_foo", value)
-- When using custom accessors, the signals need to be handled manually
self:emit_signal("property::foo", value)
end
function class:method(a, b, c)
print("In a method", a, b, c)
end
local o = gears.object {
class = class,
enable_properties = true,
enable_auto_signals = true,
}
print(o.foo)
o.foo = 42
print(o.foo)
o:method(1, 2, 3)
-- Random properties can also be added, the signal will be emitted automatically.
o:connect_signal("property::something", function(obj, value)
assert(obj == o)
print("In the connection handler!", value)
end)
print(o.something)
o.something = "a cow"
print(o.something)
--DOC_HIDE vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Boneyard_Gully/npcs/_081.lua | 22 | 1453 | -----------------------------------
-- Area: Boneyard_Gully
-- NPC: _081 (Dark Miasma)
-----------------------------------
package.loaded["scripts/zones/Boneyard_Gully/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/bcnm");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/zones/Boneyard_Gully/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (TradeBCNM(player,player:getZoneID(),trade,npc)) then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (EventTriggerBCNM(player,npc)) then
return 1;
else
return 1;
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdate CSID: %u",csid);
-- printf("onUpdate RESULT: %u",option);
if (EventUpdateBCNM(player,csid,option)) then
return;
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinish CSID: %u",csid);
-- printf("onFinish RESULT: %u",option);
if (EventFinishBCNM(player,csid,option)) then
return;
end
end; | gpl-3.0 |
nyczducky/darkstar | scripts/globals/items/cutlet_sandwich.lua | 12 | 1739 | -----------------------------------------
-- ID: 6396
-- Item: cutlet_sandwich
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP +40
-- STR +7
-- INT -7
-- Fire resistance +20
-- Attack +20% (cap 120)
-- Ranged Attack +20% (cap 120)
-----------------------------------------
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,6396);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 40);
target:addMod(MOD_STR, 7);
target:addMod(MOD_INT, -7);
target:addMod(MOD_FIRERES, 20);
target:addMod(MOD_FOOD_ATTP, 20);
target:addMod(MOD_FOOD_ATT_CAP, 120);
target:addMod(MOD_FOOD_RATTP, 20);
target:addMod(MOD_FOOD_RATT_CAP, 120);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 40);
target:delMod(MOD_STR, 7);
target:delMod(MOD_INT, -7);
target:delMod(MOD_FIRERES, 20);
target:delMod(MOD_FOOD_ATTP, 20);
target:delMod(MOD_FOOD_ATT_CAP, 120);
target:delMod(MOD_FOOD_RATTP, 20);
target:delMod(MOD_FOOD_RATT_CAP, 120);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Bastok_Markets_[S]/npcs/Silke.lua | 17 | 1235 | -----------------------------------
-- Area: Bastok Markets (S)
-- NPC: Silke
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Bastok_Markets_[S]/TextIDs");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,SILKE_SHOP_DIALOG);
stock = {0x17ab,29925, -- Animus Augeo Schema
0x17ac,29925, -- Animus Minuo Schema
0x17ad,36300} -- Adloquim Schema
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
jbeich/Aquaria | files/scripts/entities/groundshockershell.lua | 6 | 2443 | -- 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.myWeight = 432
v.onSurface = 0
function init(me)
setupBasicEntity(
me,
"GroundShocker/Shell", -- texture
3, -- health
0, -- manaballamount
0, -- exp
0, -- money
21, -- collideRadius (for hitting entities + spells)
STATE_IDLE, -- initState
128, -- sprite width
128, -- sprite height
1, -- particle "explosion" type, maps to particleEffects.txt -1 = none
1, -- 0/1 hit other entities off/on (uses collideRadius)
2000 -- updateCull -1: disabled, default: 4000
)
entity_setBounce(me, 0.2)
entity_setCanLeaveWater(me, true)
entity_setAllDamageTargets(me, false)
entity_setMaxSpeed(me, 640)
end
function update(me, dt)
entity_handleShotCollisions(me)
entity_updateMovement(me, dt)
if entity_checkSplash(me) then
end
if not entity_isUnderWater(me) then
if not entity_isBeingPulled(me) then
entity_setWeight(me, v.myWeight*2)
entity_setMaxSpeedLerp(me, 5, 0.1)
end
else
entity_setMaxSpeedLerp(me, 1, 0.1)
entity_setWeight(me, v.myWeight)
end
if entity_getVelLen(me) > 76 then
entity_rotateToVel(me, 0.34)
end
-- DESTROY IF ON SURFACE TOO LONG
if v.onSurface > 3 then
entity_alpha(me, 0, 0.12)
entity_scale(me, 0, 0, 0.12)
entity_delete(me, 0.12)
spawnParticleEffect("GroundShockerShellDestroy", entity_x(me), entity_y(me))
end
entity_touchAvatarDamage(me, 32, 0.13, 321)
end
function damage(me, attacker, bone, damageType, dmg)
return false
end
function hitSurface(me)
v.onSurface = v.onSurface + 1
end
| gpl-2.0 |
MOSAVI17/Generalbot | plugins/commit.lua | 15 | 13045 | -- Commits from https://github.com/ngerakines/commitment.
local command = 'commit'
local doc = '`Returns a commit message from whatthecommit.com.`'
local triggers = {
'^/commit[@'..bot.username..']*'
}
local commits = {
"One does not simply merge into master",
"Merging the merge",
"Another bug bites the dust",
"de-misunderestimating",
"Some shit.",
"add actual words",
"I CAN HAZ COMMENTZ.",
"giggle.",
"Whatever.",
"Finished fondling.",
"FONDLED THE CODE",
"this is how we generate our shit.",
"unh",
"It works!",
"unionfind is no longer being molested.",
"Well, it's doing something.",
"I'M PUSHING.",
"Whee.",
"Whee, good night.",
"It'd be nice if type errors caused the compiler to issue a type error",
"Fucking templates.",
"I hate this fucking language.",
"marks",
"that coulda been bad",
"hoo boy",
"It was the best of times, it was the worst of times",
"Fucking egotistical bastard. adds expandtab to vimrc",
"if you're not using et, fuck off",
"WHO THE FUCK CAME UP WITH MAKE?",
"This is a basic implementation that works.",
"By works, I meant 'doesnt work'. Works now..",
"Last time I said it works? I was kidding. Try this.",
"Just stop reading these for a while, ok..",
"Give me a break, it's 2am. But it works now.",
"Make that it works in 90% of the cases. 3:30.",
"Ok, 5am, it works. For real.",
"FOR REAL.",
"I don't know what these changes are supposed to accomplish but somebody told me to make them.",
"I don't get paid enough for this shit.",
"fix some fucking errors",
"first blush",
"So my boss wanted this button ...",
"uhhhhhh",
"forgot we're not using a smart language",
"include shit",
"To those I leave behind, good luck!",
"things occurred",
"i dunno, maybe this works",
"8==========D",
"No changes made",
"whooooooooooooooooooooooooooo",
"clarify further the brokenness of C++. why the fuck are we using C++?",
".",
"Friday 5pm",
"changes",
"A fix I believe, not like I tested or anything",
"Useful text",
"pgsql is being a pain",
"pgsql is more strict, increase the hackiness up to 11",
"c&p fail",
"syntax",
"fix",
"just shoot me",
"arrrggghhhhh fixed!",
"someone fails and it isn't me",
"totally more readable",
"better grepping",
"fix",
"fix bug, for realz",
"fix /sigh",
"Does this work",
"MOAR BIFURCATION",
"bifurcation",
"REALLY FUCKING FIXED",
"FIX",
"better ignores",
"More ignore",
"more ignores",
"more ignores",
"more ignores",
"more ignores",
"more ignores",
"more ignored words",
"more fixes",
"really ignore ignored worsd",
"fixes",
"/sigh",
"fix",
"fail",
"pointless limitation",
"omg what have I done?",
"added super-widget 2.0.",
"tagging release w.t.f.",
"I can't believe it took so long to fix this.",
"I must have been drunk.",
"This is why the cat shouldn't sit on my keyboard.",
"This is why git rebase is a horrible horrible thing.",
"ajax-loader hotness, oh yeah",
"small is a real HTML tag, who knew.",
"WTF is this.",
"Do things better, faster, stronger",
"Use a real JS construct, WTF knows why this works in chromium.",
"Added a banner to the default admin page. Please have mercy on me =(",
"needs more cow bell",
"Switched off unit test X because the build had to go out now and there was no time to fix it properly.",
"Updated",
"I must sleep... it's working... in just three hours...",
"I was wrong...",
"Completed with no bugs...",
"Fixed a little bug...",
"Fixed a bug in NoteLineCount... not seriously...",
"woa!! this one was really HARD!",
"Made it to compile...",
"changed things...",
"touched...",
"i think i fixed a bug...",
"perfect...",
"Moved something to somewhere... goodnight...",
"oops, forgot to add the file",
"Corrected mistakes",
"oops",
"oops!",
"put code that worked where the code that didn't used to be",
"Nothing to see here, move along",
"I am even stupider than I thought",
"I don't know what the hell I was thinking.",
"fixed errors in the previous commit",
"Committed some changes",
"Some bugs fixed",
"Minor updates",
"Added missing file in previous commit",
"bug fix",
"typo",
"bara bra grejjor",
"Continued development...",
"Does anyone read this? I'll be at the coffee shop accross the street.",
"That's just how I roll",
"work in progress",
"minor changes",
"some brief changes",
"assorted changes",
"lots and lots of changes",
"another big bag of changes",
"lots of changes after a lot of time",
"LOTS of changes. period",
"Test commit. Please ignore",
"I'm just a grunt. Don't blame me for this awful PoS.",
"I did it for the lulz!",
"I'll explain this when I'm sober .. or revert it",
"Obligatory placeholder commit message",
"A long time ago, in a galaxy far far away...",
"Fixed the build.",
"various changes",
"One more time, but with feeling.",
"Handled a particular error.",
"Fixed unnecessary bug.",
"Removed code.",
"Added translation.",
"Updated build targets.",
"Refactored configuration.",
"Locating the required gigapixels to render...",
"Spinning up the hamster...",
"Shovelling coal into the server...",
"Programming the flux capacitor",
"The last time I tried this the monkey didn't survive. Let's hope it works better this time.",
"I should have had a V8 this morning.",
"640K ought to be enough for anybody",
"pay no attention to the man behind the curtain",
"a few bits tried to escape, but we caught them",
"Who has two thumbs and remembers the rudiments of his linear algebra courses? Apparently, this guy.",
"workaround for ant being a pile of fail",
"Don't push this commit",
"rats",
"squash me",
"fixed mistaken bug",
"Final commit, ready for tagging",
"-m \'So I hear you like commits ...\'",
"epic",
"need another beer",
"Well the book was obviously wrong.",
"lolwhat?",
"Another commit to keep my CAN streak going.",
"I cannot believe that it took this long to write a test for this.",
"TDD: 1, Me: 0",
"Yes, I was being sarcastic.",
"Apparently works-for-me is a crappy excuse.",
"tl;dr",
"I would rather be playing SC2.",
"Crap. Tonight is raid night and I am already late.",
"I know what I am doing. Trust me.",
"You should have trusted me.",
"Is there an award for this?",
"Is there an achievement for this?",
"I'm totally adding this to epic win. +300",
"This really should not take 19 minutes to build.",
"fixed the israeli-palestinian conflict",
"SHIT ===> GOLD",
"Committing in accordance with the prophecy.",
"It compiles! Ship it!",
"LOL!",
"Reticulating splines...",
"SEXY RUSSIAN CODES WAITING FOR YOU TO CALL",
"s/import/include/",
"extra debug for stuff module",
"debug line test",
"debugo",
"remove debug<br/>all good",
"debug suff",
"more debug... who overwrote!",
"these confounded tests drive me nuts",
"For great justice.",
"QuickFix.",
"oops - thought I got that one.",
"removed echo and die statements, lolz.",
"somebody keeps erasing my changes.",
"doh.",
"pam anderson is going to love me.",
"added security.",
"arrgghh... damn this thing for not working.",
"jobs... steve jobs",
"and a comma",
"this is my quickfix branch and i will use to do my quickfixes",
"Fix my stupidness",
"and so the crazy refactoring process sees the sunlight after some months in the dark!",
"gave up and used tables.",
"[Insert your commit message here. Be sure to make it descriptive.]",
"Removed test case since code didn't pass QA",
"removed tests since i can't make them green",
"stuff",
"more stuff",
"Become a programmer, they said. It'll be fun, they said.",
"Same as last commit with changes",
"foo",
"just checking if git is working properly...",
"fixed some minor stuff, might need some additional work.",
"just trolling the repo",
"All your codebase are belong to us.",
"Somebody set up us the bomb.",
"should work I guess...",
"To be honest, I do not quite remember everything I changed here today. But it is all good, I tell ya.",
"well crap.",
"herpderp (redux)",
"herpderp",
"Derp",
"derpherp",
"Herping the derp",
"sometimes you just herp the derp so hard it herpderps",
"Derp. Fix missing constant post rename",
"Herping the fucking derp right here and now.",
"Derp, asset redirection in dev mode",
"mergederp",
"Derp search/replace fuckup",
"Herpy dooves.",
"Derpy hooves",
"derp, helper method rename",
"Herping the derp derp (silly scoping error)",
"Herp derp I left the debug in there and forgot to reset errors.",
"Reset error count between rows. herpderp",
"hey, what's that over there?!",
"hey, look over there!",
"It worked for me...",
"Does not work.",
"Either Hot Shit or Total Bollocks",
"Arrrrgggg",
"Don’t mess with Voodoo",
"I expected something different.",
"Todo!!!",
"This is supposed to crash",
"No changes after this point.",
"I know, I know, this is not how I’m supposed to do it, but I can't think of something better.",
"Don’t even try to refactor it.",
"(c) Microsoft 1988",
"Please no changes this time.",
"Why The Fuck?",
"We should delete this crap before shipping.",
"Shit code!",
"ALL SORTS OF THINGS",
"Herpderp, shoulda check if it does really compile.",
"I CAN HAZ PYTHON, I CAN HAZ INDENTS",
"Major fixup.",
"less french words",
"breathe, =, breathe",
"IEize",
"this doesn't really make things faster, but I tried",
"this should fix it",
"forgot to save that file",
"Glue. Match sticks. Paper. Build script!",
"Argh! About to give up :(",
"Blaming regex.",
"oops",
"it's friday",
"yo recipes",
"Not sure why",
"lol digg",
"grrrr",
"For real, this time.",
"Feed. You. Stuff. No time.",
"I don't give a damn 'bout my reputation",
"DEAL WITH IT",
"commit",
"tunning",
"I really should've committed this when I finished it...",
"It's getting hard to keep up with the crap I've trashed",
"I honestly wish I could remember what was going on here...",
"I must enjoy torturing myself",
"For the sake of my sanity, just ignore this...",
"That last commit message about silly mistakes pales in comparision to this one",
"My bad",
"Still can't get this right...",
"Nitpicking about alphabetizing methods, minor OCD thing",
"Committing fixes in the dark, seriously, who killed my power!?",
"You can't see it, but I'm making a very angry face right now",
"Fix the fixes",
"It's secret!",
"Commit committed....",
"No time to commit.. My people need me!",
"Something fixed",
"I'm hungry",
"asdfasdfasdfasdfasdfasdfadsf",
"hmmm",
"formatted all",
"Replace all whitespaces with tabs.",
"s/ / /g",
"I'm too foo for this bar",
"Things went wrong...",
"??! what the ...",
"This solves it.",
"Working on tests (haha)",
"fixed conflicts (LOL merge -s ours; push -f)",
"last minute fixes.",
"fuckup.",
"Revert \"fuckup\".",
"should work now.",
"final commit.",
"done. going to bed now.",
"buenas those-things.",
"Your commit is writing checks your merge can't cash.",
"This branch is so dirty, even your mom can't clean it.",
"wip",
"Revert \"just testing, remember to revert\"",
"bla",
"harharhar",
"restored deleted entities just to be sure",
"added some filthy stuff",
"bugger",
"lol",
"oopsie B|",
"Copy pasta fail. still had a instead of a",
"Now added delete for real",
"grmbl",
"move your body every every body",
"Trying to fake a conflict",
"And a commit that I don't know the reason of...",
"ffs",
"that's all folks",
"Fucking submodule bull shit",
"apparently i did something…",
"bump to 0.0.3-dev:wq",
"pep8 - cause I fell like doing a barrel roll",
"pep8 fixer",
"it is hump day _^_",
"happy monday _ bleh _",
"after of this commit remember do a git reset hard",
"someday I gonna kill someone for this shit...",
"magic, have no clue but it works",
"I am sorry",
"dirty hack, have a better idea ?",
"Code was clean until manager requested to fuck it up",
" - Temporary commit.",
":(:(",
"...",
"GIT :/",
"stopped caring 10 commits ago",
"Testing in progress ;)",
"Fixed Bug",
"Fixed errors",
"Push poorly written test can down the road another ten years",
"commented out failing tests",
"I'm human",
"TODO: write meaningful commit message",
"Pig",
"SOAP is a piece of shit",
"did everything",
"project lead is allergic to changes...",
"making this thing actually usable.",
"I was told to leave it alone, but I have this thing called OCD, you see",
"Whatever will be, will be 8{",
"It's 2015; why are we using ColdFusion?!",
"#GrammarNazi",
"Future self, please forgive me and don't hit me with the baseball bat again!",
"Hide those navs, boi!",
"Who knows...",
"Who knows WTF?!",
"I should get a raise for this.",
"Done, to whoever merges this, good luck.",
"Not one conflict, today was a good day.",
"First Blood",
"Fixed the fuck out of #526!",
"I'm too old for this shit!",
"One little whitespace gets its very own commit! Oh, life is so erratic!"
}
local action = function(msg)
sendMessage(msg.chat.id, '`'..commits[math.random(#commits)]..'`', true, nil, true)
end
return {
action = action,
triggers = triggers,
doc = doc,
command = command
}
| gpl-2.0 |
AquariaOSE/Aquaria | files/scripts/entities/_unused/mengil.lua | 6 | 2149 | -- 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
-- ================================================================================================
-- MENGRIL
-- ================================================================================================
running = false
function init(me)
setupConversationEntity(me, "Mengil")
entity_initSkeletal(me, "merman", "mengil")
entity_animate(me, "idle", LOOP_INF)
entity_scale(me, 0.6, 0.6)
entity_setActivation(me, AT_CLICK, 80, 256)
if isMapName("TransitPort") then
entity_animate(me, "sitting", LOOP_INF)
end
end
function update(me, dt)
if getStory() < 15 and not running then
running = true
naija = getEntity("Naija")
mengrilNode = getNode("GATE")
if entity_x(naija) > node_x(mengrilNode) then
-- the line must be drawn HERE!
wnd(1)
txt("Mengril: THOUH SHALT NOT PASS!")
wnd(0)
entity_swimToNode(naija, getNode("NAIJABACKOFF"))
entity_watchForPath(naija)
end
running = false
end
end
function enterState(me)
end
function exitState(me)
end
function activate(me)
if getStory() <15 then
wnd(1)
txt("Mengril: What? You expect me to have dialogue for the section of the game wherein you're not allowed to leave MainArea?")
txt("Mengril: Puppy Cocks!")
wnd(0)
end
end
function hitSurface(me)
end
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Dynamis-Xarcabard/mobs/Animated_Longsword.lua | 17 | 1502 | -----------------------------------
-- Area: Dynamis Xarcabard
-- MOB: Animated Longsword
-----------------------------------
require("scripts/globals/status");
require("scripts/zones/Dynamis-Xarcabard/TextIDs");
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
if (mob:AnimationSub() == 3) then
SetDropRate(111,1573,1000);
else
SetDropRate(111,1573,0);
end
target:showText(mob,ANIMATED_LONGSWORD_DIALOG);
SpawnMob(17330355):updateEnmity(target);
SpawnMob(17330356):updateEnmity(target);
SpawnMob(17330357):updateEnmity(target);
SpawnMob(17330362):updateEnmity(target);
SpawnMob(17330363):updateEnmity(target);
SpawnMob(17330364):updateEnmity(target);
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
-- TODO: add battle dialog
end;
-----------------------------------
-- onMobDisengage
-----------------------------------
function onMobDisengage(mob)
mob:showText(mob,ANIMATED_LONGSWORD_DIALOG+2);
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
player:showText(mob,ANIMATED_LONGSWORD_DIALOG+1);
DespawnMob(17330355);
DespawnMob(17330356);
DespawnMob(17330357);
DespawnMob(17330362);
DespawnMob(17330363);
DespawnMob(17330364);
end; | gpl-3.0 |
nyczducky/darkstar | scripts/zones/Sealions_Den/npcs/_0w0.lua | 14 | 1998 | -----------------------------------
-- Area: Sealion's Den
-- NPC: Iron Gate
-- @pos 612 132 774 32
-----------------------------------
package.loaded["scripts/zones/Sealions_Den/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/bcnm");
require("scripts/globals/missions");
require("scripts/globals/titles");
require("scripts/globals/teleports");
require("scripts/zones/Sealions_Den/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (TradeBCNM(player,player:getZoneID(),trade,npc)) then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == SLANDEROUS_UTTERINGS and player:getVar("PromathiaStatus") == 1) then
player:startEvent(0x000D);
elseif (EventTriggerBCNM(player,npc)) then
return;
elseif (player:getCurrentMission(COP) > THE_WARRIOR_S_PATH) then
player:startEvent(0x000C);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdate CSID: %u",csid);
-- printf("onUpdate RESULT: %u",option);
EventUpdateBCNM(player,csid,option)
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinish CSID: %u",csid);
-- printf("onFinish RESULT: %u",option);
if (EventFinishBCNM(player,csid,option)) then
return;
end
if (csid == 0x000c and option == 1) then
toPalaceEntrance(player);
elseif (csid == 0x000D) then
player:setVar("PromathiaStatus",0);
player:completeMission(COP,SLANDEROUS_UTTERINGS);
player:addMission(COP,THE_ENDURING_TUMULT_OF_WAR);
player:addTitle(THE_LOST_ONE);
end
end; | gpl-3.0 |
AquariaOSE/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 |
nyczducky/darkstar | scripts/globals/items/pork_cutlet_+1.lua | 12 | 1740 | -----------------------------------------
-- ID: 6395
-- Item: pork_cutlet_+1
-- Food Effect: 240Min, All Races
-----------------------------------------
-- HP +45
-- STR +8
-- INT -8
-- Fire resistance +21
-- Attack +21% (cap 125)
-- Ranged Attack +21% (cap 125)
-----------------------------------------
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,6395);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 45);
target:addMod(MOD_STR, 8);
target:addMod(MOD_INT, -8);
target:addMod(MOD_FIRERES, 21);
target:addMod(MOD_FOOD_ATTP, 21);
target:addMod(MOD_FOOD_ATT_CAP, 125);
target:addMod(MOD_FOOD_RATTP, 21);
target:addMod(MOD_FOOD_RATT_CAP, 125);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 45);
target:delMod(MOD_STR, 8);
target:delMod(MOD_INT, -8);
target:delMod(MOD_FIRERES, 21);
target:delMod(MOD_FOOD_ATTP, 21);
target:delMod(MOD_FOOD_ATT_CAP, 125);
target:delMod(MOD_FOOD_RATTP, 21);
target:delMod(MOD_FOOD_RATT_CAP, 125);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Port_Jeuno/npcs/Veujaie.lua | 14 | 1041 | ----------------------------------
-- Area: Port Jeuno
-- NPC: Veujaie
-- Type: Item Deliverer
-- @zone 246
-- @pos -20.349 7.999 -2.888
--
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
require("scripts/zones/Port_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, 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/globals/weaponskills/black_halo.lua | 25 | 1568 | -----------------------------------
-- Black Halo
-- Club weapon skill
-- Skill level: 230
-- In order to obtain Black Halo, the quest Orastery Woes must be completed.
-- Delivers a two-hit attack. Damage varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Shadow Gorget, Thunder Gorget & Breeze Gorget.
-- Aligned with the Shadow Belt, Thunder Belt & Breeze Belt.
-- Element: None
-- Modifiers: STR:30% ; MND:50%
-- 100%TP 200%TP 300%TP
-- 1.50 2.50 3.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 2;
params.ftp100 = 1.5; params.ftp200 = 2.5; params.ftp300 = 3;
params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.5; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 3.0; params.ftp200 = 7.25; params.ftp300 = 9.75;
params.mnd_wsc = 0.7;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
GSRMOHAMMAD/fortg | plugins/filtering.lua | 11 | 2563 | --[[
#
# @GPMOD
# @Dragon_Born
#
]]
local function addword(msg, name)
local hash = 'chat:'..msg.to.id..':badword'
redis:hset(hash, name, 'newword')
return "کلمه جدید به فیلتر کلمات اضافه شد\n>"..name
end
local function get_variables_hash(msg)
return 'chat:'..msg.to.id..':badword'
end
local function list_variablesbad(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = 'لیست کلمات غیرمجاز :\n\n'
for i=1, #names do
text = text..'> '..names[i]..'\n'
end
return text
else
return
end
end
function clear_commandbad(msg, var_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:del(hash, var_name)
return 'تمامی کلمات فیلتر شده حذف شدند'
end
local function list_variables2(msg, value)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i=1, #names do
if string.match(value, names[i]) and not is_momod(msg) then
if msg.to.type == 'channel' then
delete_msg(msg.id,ok_cb,false)
else
kick_user(msg.from.id, msg.to.id)
end
return
end
--text = text..names[i]..'\n'
end
end
end
local function get_valuebad(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return
else
return value
end
end
end
function clear_commandsbad(msg, cmd_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:hdel(hash, cmd_name)
return ''..cmd_name..' پاک شد'
end
local function run(msg, matches)
if matches[2] == 'addword' then
if not is_momod(msg) then
return 'only for moderators'
end
local name = string.sub(matches[3], 1, 50)
local text = addword(msg, name)
return text
end
if matches[2] == 'badwords' then
return list_variablesbad(msg)
elseif matches[2] == 'clearbadwords' then
if not is_momod(msg) then return '_|_' end
local asd = '1'
return clear_commandbad(msg, asd)
elseif matches[2] == 'remword' or matches[2] == 'rw' then
if not is_momod(msg) then return '_|_' end
return clear_commandsbad(msg, matches[3])
else
local name = user_print_name(msg.from)
return list_variables2(msg, matches[1])
end
end
return {
patterns = {
"^([#/])(rw) (.*)$",
"^([#/])(addword) (.*)$",
"^([#/])(remword) (.*)$",
"^([#/])(badwords)$",
"^([#/])(clearbadwords)$",
"^(.+)$",
},
run = run
}
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Behemoths_Dominion/TextIDs.lua | 7 | 1076 | -- 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>.
SENSE_OF_FOREBODING = 6400; -- You are suddenly overcome with a sense of foreboding...
NOTHING_OUT_OF_ORDINARY = 6399; -- There is nothing out of the ordinary here.
IRREPRESSIBLE_MIGHT = 6403; -- An aura of irrepressible might threatens to overwhelm you...
-- ZM4 Dialog
ZILART_MONUMENT = 7319; -- It is an ancient Zilart monument.?Prompt?
ALREADY_OBTAINED_FRAG = 7316; -- You have already obtained this monument's
FOUND_ALL_FRAGS = 7318; -- You have obtained ! You now have all 8 fragments of light!
CANNOT_REMOVE_FRAG = 7315; -- It is an oddly shaped stone monument. A shining stone is embedded in it, but cannot be removed...?Prompt?
-- conquest Base
CONQUEST_BASE = 7046; -- Tallying conquest results...
| gpl-3.0 |
oldstylejoe/vlc-timed | share/lua/playlist/zapiks.lua | 17 | 2964 | --[[
$Id$
Copyright © 2011 the VideoLAN team
Authors: Konstantin Pavlov (thresh@videolan.org)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "zapiks.fr/(.*).html" )
or string.match( vlc.path, "zapiks.fr/view/." )
or string.match( vlc.path, "26in.fr/videos/." )
end
-- Parse function.
function parse()
if string.match ( vlc.path, "zapiks.fr/(.+).html" ) or string.match( vlc.path, "26in.fr/videos/" ) then
while true do
line = vlc.readline()
if not line then break end
-- Try to find video id number
if string.match( line, "video_src(.+)file=(%d+)\"" ) then
_,_,id = string.find( line, "file=(%d+)")
end
-- Try to find title
if string.match( line, "(.*)</title>" ) then
_,_,name = string.find( line, "(.*)</title>" )
end
end
return { { path = "http://www.zapiks.fr/view/index.php?file=" .. id, name = name } }
end
if string.match ( vlc.path, "zapiks.fr/view/." ) then
prefres = vlc.var.inherit(nil, "preferred-resolution")
while true do
line = vlc.readline()
if not line then break end
-- Try to find URL of video
if string.match( line, "<file>(.*)</file>" ) then
_,_,path = string.find ( line, "<file>(.*)</file>" )
end
-- Try to find image for arturl
if string.match( line, "<image>(.*)</image>" ) then
_,_,arturl = string.find( line, "<image>(.*)</image>" )
end
if string.match( line, "title=\"(.*)\"" ) then
_,_,name = string.find( line, "title=\"(.*)\"" )
end
-- Try to find whether video is HD actually
if( prefres <0 or prefres >= 720 ) then
if string.match( line, "<hd.file>(.*)</hd.file>" ) then
_,_,path = string.find( line, "<hd.file>(.*)</hd.file>" )
end
end
end
return { { path = path; name = name; arturl = arturl } }
end
vlc.msg.err( "Could not extract the video URL from zapiks.fr" )
return {}
end
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Western_Altepa_Desert/mobs/Desert_Dhalmel.lua | 14 | 1048 | -----------------------------------
-- Area: Western Altepa Desert
-- MOB: Desert Dhalmel
-- Note: Place holder for Celphie
-----------------------------------
require("scripts/globals/fieldsofvalor");
require("scripts/zones/Western_Altepa_Desert/MobIDs");
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
checkRegime(player,mob,135,1);
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
local mobID = mob:getID();
if (Celphie_PH[mobID] ~= nil) then
local ToD = GetServerVariable("[POP]Celphie");
if (ToD <= os.time(t) and GetMobAction(Celphie) == 0) then
if (math.random(1,20) == 5) then
UpdateNMSpawnPoint(Celphie);
GetMobByID(Celphie):setRespawnTime(GetMobRespawnTime(mobID));
SetServerVariable("[PH]Celphie", mobID);
DeterMob(mobID, true);
end
end
end
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Temenos/mobs/Kindred_Dark_Knight.lua | 28 | 1108 | -----------------------------------
-- Area: Temenos N T
-- NPC: Kindred_Dark_Knight
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Temenos/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
if (IsMobDead(16928797)==true and IsMobDead(16928798)==true and IsMobDead(16928799)==true ) then
GetNPCByID(16928768+27):setPos(-120,-80,429);
GetNPCByID(16928768+27):setStatus(STATUS_NORMAL);
GetNPCByID(16928768+161):setPos(-123,-80,429);
GetNPCByID(16928768+161):setStatus(STATUS_NORMAL);
GetNPCByID(16928768+212):setPos(-117,-80,429);
GetNPCByID(16928768+212):setStatus(STATUS_NORMAL);
end
end; | gpl-3.0 |
jasujm/bridge | sample/config.lua | 1 | 3465 | -- Sample configuration file for the bridge application
-- The bind interface and port. Control socket binds to bind_base_port. Event
-- socket binds to bind_base_port + 1.
bind_address = os.getenv("BRIDGE_BIND_ADDRESS") or "*"
bind_base_port = os.getenv("BRIDGE_BIND_BASE_PORT") or 5555
-- Set curve_secret_key and curve_public_key to enable encrypting traffic with
-- CurveZMQ. The keys here are the test keys test keys
-- (http://api.zeromq.org/4-2:zmq-curve) and should be substituted for a keypair
-- you generated.
if os.getenv("BRIDGE_USE_CURVE") then
curve_secret_key = "JTKVSB%%)wK0E.X)V>+}o?pNmC{O&4W4b!Ni{Lh6"
curve_public_key = "rq:rM>}U?@Lns47E1%kR.o@n%FcmmsL/@{H8]yf7"
-- The known_nodes table can be used to assign identities to known public
-- keys.
known_nodes = {
{ public_key = "rq:rM>}U?@Lns47E1%kR.o@n%FcmmsL/@{H8]yf7", user_id = "the node" },
}
end
-- Data directory will be used to record games so that they can be continued
-- when the application is restarted. If omitted, games will be lost on exit.
if os.getenv("BRIDGE_USE_RECORDER") then
data_dir = os.getenv("BRIDGE_DATA_DIR")
if not data_dir then
home = os.getenv("HOME")
if home then
data_dir = home .. "/.bridge"
end
end
end
-- Set up game(s) using the game function. To setup a game with peers, you
-- additionally need to specify positions_controlled, peers and, optionally,
-- card_server.
-- Note that peerless games can also be created by the frontend application
-- after startup.
-- The following sets up a default game if the BRIDGE_DEFAULT_GAME environment
-- variable is set. This is intended of spinning up a server hosting a single
-- ad hoc game.
if os.getenv("BRIDGE_DEFAULT_GAME") then
game {
uuid = "bed30528-2cfe-44ee-9db7-79ec19fdd715",
default = true,
}
end
-- game {
-- UUID is a mandatory argument to the game command
-- uuid = "61b431d1-386b-4b16-a99d-d48dd35f1a4e",
-- For a game with peers you need to configure which positions this
-- peer controls. The positions need to be agreed in advance, and
-- together the peers need to control all positions. That is: each
-- player needs to uncomment exactly one of the lines below.
-- positions_controlled = { "north" },
-- positions_controlled = { "east" },
-- positions_controlled = { "west" },
-- positions_controlled = { "south" },
-- Tell the backend where it can finds its peers. Assuming all the
-- other peers have the same CURVE keypair as yourself (needs not
-- be the case), you can just assign server_key from the
-- curve_public_key you defined above.
-- peers = {
-- { endpoint="tcp://peer1.example.com:5555", server_key = curve_public_key },
-- { endpoint="tcp://peer2.example.com:5555", server_key = curve_public_key },
-- { endpoint="tcp://peer3.example.com:5555", server_key = curve_public_key },
-- },
-- To configure card exchange using card server, uncomment the
-- following section. control_endpoint and base_peer_endpoint are
-- what you use as command line arguments when running the bridgecs
-- command. Peer endpoints need to be accessible by the card server
-- peers. control_endpoint should only be accessible by the bridge
-- backend.
-- card_server = os.getenv("BRIDGE_USE_CS") and {
-- control_endpoint = "tcp://127.0.0.1:5560",
-- base_peer_endpoint = "tcp://*:5565",
-- },
-- }
| gpl-3.0 |
sevu/wesnoth | data/ai/micro_ais/cas/ca_messenger_escort_move.lua | 6 | 3712 | local AH = wesnoth.require "ai/lua/ai_helper.lua"
local LS = wesnoth.require "location_set"
local MAIUV = wesnoth.require "ai/micro_ais/micro_ai_unit_variables.lua"
local M = wesnoth.map
local messenger_next_waypoint = wesnoth.require "ai/micro_ais/cas/ca_messenger_f_next_waypoint.lua"
local function get_escorts(cfg)
local escorts = AH.get_units_with_moves {
side = wesnoth.current.side,
{ "and", wml.get_child(cfg, "filter_second") }
}
return escorts
end
local ca_messenger_escort_move = {}
function ca_messenger_escort_move:evaluation(cfg)
-- Move escort units close to messengers, and in between messengers and enemies
-- The messengers have moved at this time, so we don't need to exclude them,
-- but we check that there are messengers left
if (not get_escorts(cfg)[1]) then return 0 end
local _, _, _, messengers = messenger_next_waypoint(cfg)
if (not messengers) or (not messengers[1]) then return 0 end
return cfg.ca_score
end
function ca_messenger_escort_move:execution(cfg)
local escorts = get_escorts(cfg)
local _, _, _, messengers = messenger_next_waypoint(cfg)
local avoid_map = AH.get_avoid_map(ai, wml.get_child(cfg, "avoid"), true)
local enemies = AH.get_attackable_enemies()
local base_rating_map = LS.create()
local max_rating, best_unit, best_hex = - math.huge, nil, nil
for _,unit in ipairs(escorts) do
-- Only considering hexes unoccupied by other units is good enough for this
local reach_map = AH.get_reachable_unocc(unit)
-- Minor rating for the fastest and strongest unit to go first
local unit_rating = unit.max_moves / 100. + unit.hitpoints / 1000.
reach_map:iter( function(x, y, v)
if (not avoid_map:get(x, y)) or ((x == unit.x) and (y == unit.y)) then
local base_rating = base_rating_map:get(x, y)
if (not base_rating) then
base_rating = 0
-- Distance from messenger is most important; only closest messenger counts for this
-- Give somewhat of a bonus for the messenger that has moved the farthest through the waypoints
local max_messenger_rating = - math.huge
for _,m in ipairs(messengers) do
local messenger_rating = 1. / (M.distance_between(x, y, m.x, m.y) + 2.)
local wp_rating = MAIUV.get_mai_unit_variables(m, cfg.ai_id, "wp_rating")
messenger_rating = messenger_rating * 10. * (1. + wp_rating * 2.)
if (messenger_rating > max_messenger_rating) then
max_messenger_rating = messenger_rating
end
end
base_rating = base_rating + max_messenger_rating
-- Distance from (sum of) enemies is important too
-- This favors placing escort units between the messenger and close enemies
for _,e in ipairs(enemies) do
base_rating = base_rating + 1. / (M.distance_between(x, y, e.x, e.y) + 2.)
end
base_rating_map:insert(x, y, base_rating)
end
local rating = base_rating + unit_rating
if (rating > max_rating) then
max_rating = rating
best_unit, best_hex = unit, { x, y }
end
end
end)
end
-- This will always find at least the hex the unit is on -> no check necessary
AH.movefull_stopunit(ai, best_unit, best_hex)
end
return ca_messenger_escort_move
| gpl-2.0 |
nyczducky/darkstar | scripts/globals/abilities/fight.lua | 26 | 1130 | -----------------------------------
-- Ability: Fight
-- Commands your pet to attack the target.
-- Obtained: Beastmaster Level 1
-- Recast Time: 10 seconds
-- Duration: N/A
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:getPet() == nil) then
return MSGBASIC_REQUIRES_A_PET,0;
else
if (target:getID() == player:getPet():getID() or (target:getMaster() ~= nil and target:getMaster():isPC())) then
return MSGBASIC_CANNOT_ATTACK_TARGET,0;
else
return 0,0;
end
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
local pet = player:getPet();
if (player:checkDistance(pet) <= 25) then
if (pet:hasStatusEffect(EFFECT_HEALING)) then
pet:delStatusEffect(EFFECT_HEALING)
end
player:petAttack(target);
end
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/globals/items/pogaca_+1.lua | 12 | 1445 | -----------------------------------------
-- ID: 5638
-- Item: pogaca_+1
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Lizard Killer +12
-- Resist Paralyze +12
-- HP Recovered While Healing 6
-- MP Recovered While Healing 6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,360,5638);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_LIZARD_KILLER, 12);
target:addMod(MOD_PARALYZERES, 12);
target:addMod(MOD_HPHEAL, 6);
target:addMod(MOD_MPHEAL, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_LIZARD_KILLER, 12);
target:delMod(MOD_PARALYZERES, 12);
target:delMod(MOD_HPHEAL, 6);
target:delMod(MOD_MPHEAL, 6);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/globals/spells/choke.lua | 9 | 1851 | -----------------------------------------
-- Spell: Choke
-- Deals wind damage that lowers an enemy's vitality 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_FROST) ~= 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_RASP) ~= nil) then
target:delStatusEffect(EFFECT_RASP);
end;
local sINT = caster:getStat(MOD_INT);
local DOT = getElementalDebuffDOT(sINT);
local effect = target:getStatusEffect(EFFECT_CHOKE);
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_CHOKE);
end;
spell:setMsg(237);
local duration = math.floor(ELEMENTAL_DEBUFF_DURATION * resist);
target:addStatusEffect(EFFECT_CHOKE,DOT, 3, ELEMENTAL_DEBUFF_DURATION,FLAG_ERASABLE);
end;
end;
end;
return EFFECT_CHOKE;
end; | gpl-3.0 |
naxiwer/Atlas | lib/active-queries.lua | 40 | 3780 | --[[ $%BEGINLICENSE%$
Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; version 2 of the
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
-- proxy.auto-config will pick them up
local commands = require("proxy.commands")
local auto_config = require("proxy.auto-config")
--- init the global scope
if not proxy.global.active_queries then
proxy.global.active_queries = {}
end
if not proxy.global.max_active_trx then
proxy.global.max_active_trx = 0
end
-- default config for this script
if not proxy.global.config.active_queries then
proxy.global.config.active_queries = {
show_idle_connections = false
}
end
---
-- track the active queries and dump all queries at each state-change
--
function collect_stats()
local num_conns = 0
local active_conns = 0
for k, v in pairs(proxy.global.active_queries) do
num_conns = num_conns + 1
if v.state ~= "idle" then
active_conns = active_conns + 1
end
end
if active_conns > proxy.global.max_active_trx then
proxy.global.max_active_trx = active_conns
end
return {
active_conns = active_conns,
num_conns = num_conns,
max_active_trx = proxy.global.max_active_trx
}
end
---
-- dump the state of the current queries
--
function print_stats(stats)
local o = ""
for k, v in pairs(proxy.global.active_queries) do
if v.state ~= "idle" or proxy.global.config.active_queries.show_idle_connections then
local cmd_query = ""
if v.cmd then
cmd_query = string.format("(%s) %q", v.cmd.type_name, v.cmd.query or "")
end
o = o .." ["..k.."] (".. v.username .."@".. v.db ..") " .. cmd_query .." (state=" .. v.state .. ")\n"
end
end
-- prepend the data and the stats about the number of connections and trx
o = os.date("%Y-%m-%d %H:%M:%S") .. "\n" ..
" #connections: " .. stats.num_conns ..
", #active trx: " .. stats.active_conns ..
", max(active trx): ".. stats.max_active_trx ..
"\n" .. o
print(o)
end
---
-- enable tracking the packets
function read_query(packet)
local cmd = commands.parse(packet)
local r = auto_config.handle(cmd)
if r then return r end
proxy.queries:append(1, packet)
-- add the query to the global scope
local connection_id = proxy.connection.server.thread_id
proxy.global.active_queries[connection_id] = {
state = "started",
cmd = cmd,
db = proxy.connection.client.default_db or "",
username = proxy.connection.client.username or ""
}
print_stats(collect_stats())
return proxy.PROXY_SEND_QUERY
end
---
-- statement is done, track the change
function read_query_result(inj)
local connection_id = proxy.connection.server.thread_id
proxy.global.active_queries[connection_id].state = "idle"
proxy.global.active_queries[connection_id].cmd = nil
if inj.resultset then
local res = inj.resultset
if res.flags.in_trans then
proxy.global.active_queries[connection_id].state = "in_trans"
end
end
print_stats(collect_stats())
end
---
-- remove the information about the connection
--
function disconnect_client()
local connection_id = proxy.connection.server.thread_id
if connection_id then
proxy.global.active_queries[connection_id] = nil
print_stats(collect_stats())
end
end
| gpl-2.0 |
aqasaeed/ali | plugins/GroupManager.lua | 39 | 11325 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "This service is private for SUDO (@shayansoft)"
end
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group '..string.gsub(group_name, '_', ' ')..' created, check messages list...'
end
local function set_description(msg, data)
if not is_momod(msg) then
return "You are NOT moderator"
end
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = deskripsi
save_data(_config.moderation.data, data)
return 'Set this message for about=>\n\n'..deskripsi
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'Group have not about'
end
local about = data[tostring(msg.to.id)][data_cat]
return about
end
local function set_rules(msg, data)
if not is_momod(msg) then
return "You are NOT moderator"
end
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set this message for rules=>\n\n'..rules
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'Group have not rules'
end
local rules = data[tostring(msg.to.id)][data_cat]
return rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data)
if not is_momod(msg) then
return "You are NOT moderator"
end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Name is already locked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['set_name'] = string.gsub(msg.to.print_name, '_', ' ')
save_data(_config.moderation.data, data)
return 'Group name locked'
end
end
local function unlock_group_name(msg, data)
if not is_momod(msg) then
return "You are NOT moderator"
end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Name is already unlocked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data)
if not is_momod(msg) then
return "You are NOT moderator"
end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Members are already locked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members locked'
end
local function unlock_group_member(msg, data)
if not is_momod(msg) then
return "You are NOT moderator"
end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Members are already unlocked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data)
if not is_momod(msg) then
return "You are NOT moderator"
end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Photo is already locked'
else
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Send group photo now'
end
local function unlock_group_photo(msg, data)
if not is_momod(msg) then
return "You are NOT moderator"
end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Photo is already unlocked'
else
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo unlocked'
end
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Group photo save and set', ok_cb, false)
else
print('Error: '..msg.id)
send_large_msg(receiver, 'Failed, try again', ok_cb, false)
end
end
-- show group settings
local function show_group_settings(msg, data)
if not is_momod(msg) then
return "You are NOT moderator"
end
local settings = data[tostring(msg.to.id)]['settings']
local text = "Group Settings:\n_________________________\n> Lock Group Name : "..settings.lock_name.."\n> Lock Group Photo : "..settings.lock_photo.."\n> Lock Group Member : "..settings.lock_member.."\n> Anti Spam System : on\n> Anti Spam Mod : kick\n> Anti Spam Action : 10\n> Group Status : active\n> Group Model : free\n> Group Mod : 2\n> Supportion : yes\n> Bot Version : 1.6"
return text
end
function run(msg, matches)
--vardump(msg)
if matches[1] == 'makegroup' and matches[2] then
group_name = matches[2]
return create_group(msg)
end
if not is_chat_msg(msg) then
return "This is not group"
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if msg.media and is_chat_msg(msg) and is_momod(msg) then
if msg.media.type == 'photo' and data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then
load_photo(msg.id, set_group_photo, msg)
end
end
end
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'setabout' and matches[2] then
deskripsi = matches[2]
return set_description(msg, data)
end
if matches[1] == 'about' then
return get_description(msg, data)
end
if matches[1] == 'setrules' then
rules = matches[2]
return set_rules(msg, data)
end
if matches[1] == 'rules' then
return get_rules(msg, data)
end
if matches[1] == 'group' and matches[2] == '+' then --group lock *
if matches[3] == 'name' then
return lock_group_name(msg, data)
end
if matches[3] == 'member' then
return lock_group_member(msg, data)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data)
end
end
if matches[1] == 'group' and matches[2] == '-' then --group unlock *
if matches[3] == 'name' then
return unlock_group_name(msg, data)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data)
end
end
if matches[1] == 'group' and matches[2] == '?' then
return show_group_settings(msg, data)
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Send new photo now'
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo (receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo (receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
end
end
return {
description = "Group Manager System",
usage = {
"/makegroup (name) : create new group",
"/about : view group about",
"/rules : view group rules",
"/setname (name) : set group name",
"/setphoto : set group photo",
"/setabout (message) : set group about",
"/setrules (message) : set group rules",
"/group + name : lock group name",
"/group + photo : lock group photo",
"/group + member : lock group member",
"/group - name : unlock group name",
"/group - photo : unlock group photo",
"/group - member : unlock group member",
"/group ? : view group settings"
},
patterns = {
"^[!/](makegroup) (.*)$",
"^[!/](setabout) (.*)$",
"^[!/](about)$",
"^[!/](setrules) (.*)$",
"^[!/](rules)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](group) (+) (.*)$",
"^[!/](group) (-) (.*)$",
"^[!/](group) (?)$",
"^!!tgservice (.+)$",
"%[(photo)%]",
},
run = run,
}
end
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/RuLude_Gardens/npcs/HomePoint#2.lua | 27 | 1264 | -----------------------------------
-- Area: RuLude_Gardens
-- NPC: HomePoint#2
-- @pos 53 9 -57 243
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/RuLude_Gardens/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fd, 30);
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 == 0x21fd) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
rpav-eso/ThiefsKnapsack | libs/LibAddonMenu-2.0/controls/editbox.lua | 6 | 5492 | --[[editboxData = {
type = "editbox",
name = "My Editbox",
tooltip = "Editbox's tooltip text.",
getFunc = function() return db.text end,
setFunc = function(text) db.text = text doStuff() end,
isMultiline = true, --boolean
width = "full", --or "half" (optional)
disabled = function() return db.someBooleanSetting end, --or boolean (optional)
warning = "Will need to reload the UI.", --(optional)
default = defaults.text, --(optional)
reference = "MyAddonEditbox" --(optional) unique global reference to control
} ]]
local widgetVersion = 7
local LAM = LibStub("LibAddonMenu-2.0")
if not LAM:RegisterWidget("editbox", widgetVersion) then return end
local wm = WINDOW_MANAGER
local cm = CALLBACK_MANAGER
local tinsert = table.insert
local function UpdateDisabled(control)
local disable
if type(control.data.disabled) == "function" then
disable = control.data.disabled()
else
disable = control.data.disabled
end
if disable then
control.label:SetColor(ZO_DEFAULT_DISABLED_COLOR:UnpackRGBA())
control.editbox:SetColor(ZO_DEFAULT_DISABLED_MOUSEOVER_COLOR:UnpackRGBA())
else
control.label:SetColor(ZO_DEFAULT_ENABLED_COLOR:UnpackRGBA())
control.editbox:SetColor(ZO_DEFAULT_ENABLED_COLOR:UnpackRGBA())
end
--control.editbox:SetEditEnabled(not disable)
control.editbox:SetMouseEnabled(not disable)
end
local function UpdateValue(control, forceDefault, value)
if forceDefault then --if we are forcing defaults
value = control.data.default
control.data.setFunc(value)
control.editbox:SetText(value)
elseif value then
control.data.setFunc(value)
--after setting this value, let's refresh the others to see if any should be disabled or have their settings changed
if control.panel.data.registerForRefresh then
cm:FireCallbacks("LAM-RefreshPanel", control)
end
else
value = control.data.getFunc()
control.editbox:SetText(value)
end
end
function LAMCreateControl.editbox(parent, editboxData, controlName)
local control = wm:CreateControl(controlName or editboxData.reference, parent.scroll or parent, CT_CONTROL)
control:SetMouseEnabled(true)
control:SetResizeToFitDescendents(true)
control:SetHandler("OnMouseEnter", ZO_Options_OnMouseEnter)
control:SetHandler("OnMouseExit", ZO_Options_OnMouseExit)
control.label = wm:CreateControl(nil, control, CT_LABEL)
local label = control.label
label:SetAnchor(TOPLEFT)
label:SetFont("ZoFontWinH4")
label:SetWrapMode(TEXT_WRAP_MODE_ELLIPSIS)
label:SetText(editboxData.name)
control.bg = wm:CreateControlFromVirtual(nil, control, "ZO_EditBackdrop")
local bg = control.bg
if editboxData.isMultiline then
control.editbox = wm:CreateControlFromVirtual(nil, bg, "ZO_DefaultEditMultiLineForBackdrop")
control.editbox:SetHandler("OnMouseWheel", function(self, delta)
if self:HasFocus() then --only set focus to new spots if the editbox is currently in use
local cursorPos = self:GetCursorPosition()
local text = self:GetText()
local textLen = text:len()
local newPos
if delta > 0 then --scrolling up
local reverseText = text:reverse()
local revCursorPos = textLen - cursorPos
local revPos = reverseText:find("\n", revCursorPos+1)
newPos = revPos and textLen - revPos
else --scrolling down
newPos = text:find("\n", cursorPos+1)
end
if newPos then --if we found a new line, then scroll, otherwise don't
self:SetCursorPosition(newPos)
end
end
end)
else
control.editbox = wm:CreateControlFromVirtual(nil, bg, "ZO_DefaultEditForBackdrop")
end
local editbox = control.editbox
editbox:SetText(editboxData.getFunc())
editbox:SetMaxInputChars(3000)
editbox:SetHandler("OnFocusLost", function(self) control:UpdateValue(false, self:GetText()) end)
editbox:SetHandler("OnEscape", function(self) self:LoseFocus() control:UpdateValue(false, self:GetText()) end)
editbox:SetHandler("OnMouseEnter", function() ZO_Options_OnMouseEnter(control) end)
editbox:SetHandler("OnMouseExit", function() ZO_Options_OnMouseExit(control) end)
local isHalfWidth = editboxData.width == "half"
if isHalfWidth then
control:SetDimensions(250, 55)
label:SetDimensions(250, 26)
bg:SetDimensions(225, editboxData.isMultiline and 74 or 24)
bg:SetAnchor(TOPRIGHT, label, BOTTOMRIGHT)
if editboxData.isMultiline then
editbox:SetDimensionConstraints(210, 74, 210, 500)
end
else
control:SetDimensions(510, 30)
label:SetDimensions(300, 26)
bg:SetDimensions(200, editboxData.isMultiline and 100 or 24)
bg:SetAnchor(TOPRIGHT)
if editboxData.isMultiline then
editbox:SetDimensionConstraints(185, 100, 185, 500)
end
end
if editboxData.warning then
control.warning = wm:CreateControlFromVirtual(nil, control, "ZO_Options_WarningIcon")
control.warning:SetAnchor(TOPRIGHT, control.bg, TOPLEFT, -5, 0)
--control.warning.tooltipText = editboxData.warning
control.warning.data = {tooltipText = editboxData.warning}
end
control.panel = parent.panel or parent --if this is in a submenu, panel is its parent
control.data = editboxData
control.data.tooltipText = editboxData.tooltip
if editboxData.disabled then
control.UpdateDisabled = UpdateDisabled
control:UpdateDisabled()
end
control.UpdateValue = UpdateValue
control: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 |
Sojerbot/new | 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 |
mehrpouya81/giantbot | 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 |
mynameiscraziu/mycaty | 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 |
alinoroz/pop_tm | 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 |
aktel/vice-players | Vendor/CEGUI/cegui/src/ScriptingModules/LuaScriptModule/support/tolua++bin/lua/verbatim.lua | 7 | 1667 | -- tolua: verbatim class
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- $Id: verbatim.lua 1004 2006-02-27 13:03:20Z lindquist $
-- This code is free software; you can redistribute it and/or modify it.
-- The software provided hereunder is on an "as is" basis, and
-- the author has no obligation to provide maintenance, support, updates,
-- enhancements, or modifications.
-- Verbatim class
-- Represents a line translated directed to the binding file.
-- The following filds are stored:
-- line = line text
classVerbatim = {
line = '',
cond = nil, -- condition: where to generate the code (s=suport, r=register)
}
classVerbatim.__index = classVerbatim
setmetatable(classVerbatim,classFeature)
-- preamble verbatim
function classVerbatim:preamble ()
if self.cond == '' then
write(self.line)
end
end
-- support code
function classVerbatim:supcode ()
if strfind(self.cond,'s') then
write(self.line)
write('\n')
end
end
-- register code
function classVerbatim:register (pre)
if strfind(self.cond,'r') then
write(self.line)
end
end
-- Print method
function classVerbatim:print (ident,close)
print(ident.."Verbatim{")
print(ident.." line = '"..self.line.."',")
print(ident.."}"..close)
end
-- Internal constructor
function _Verbatim (t)
setmetatable(t,classVerbatim)
append(t)
return t
end
-- Constructor
-- Expects a string representing the text line
function Verbatim (l,cond)
if strsub(l,1,1) == "'" then
l = strsub(l,2)
elseif strsub(l,1,1) == '$' then
cond = 'sr' -- generates in both suport and register fragments
l = strsub(l,2)
end
return _Verbatim {
line = l,
cond = cond or '',
}
end
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Jugner_Forest/npcs/Cavernous_Maw_2.lua | 29 | 1894 | -----------------------------------
-- Area: Jugner Forest
-- NPC: Cavernous Maw
-- @pos 246.318, -0.709, 5.706 104
-- Teleports Players to Abyssea - Vunkerl
-----------------------------------
package.loaded["scripts/zones/Jugner_Forest/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/abyssea");
require("scripts/zones/Jugner_Forest/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, THE_BEAST_OF_BASTORE) == QUEST_AVAILABLE) then
player:startEvent(48);
else
player:startEvent(47,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 Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 48) then
player:addQuest(ABYSSEA, THE_BEAST_OF_BASTORE);
elseif (csid == 49) then
-- Killed Sedna
elseif (csid == 47 and option == 1) then
player:setPos(-351,-46.750,699.5,10,217);
end
end; | gpl-3.0 |
devadvisor/Advisor | 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 |
aliarshad2000/telehunter | plugins/inrealm.lua | 22 | 16813 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group '..string.gsub(group_name, '_', ' ')..' has been created.'
end
end
local function set_description(msg, data, target, about)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function set_rules(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(target)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
-- show group settings
local function show_group_settings(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
send_large_msg(receiver, text)
local file = io.open("./groups/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function returnidsfile(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
local file = io.open("./groups/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..result.id,"./groups/"..result.id.."memberlist.txt", ok_cb, false)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_name..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List for Realm admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function group_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'
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "no owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
print(group_owner)
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n'
end
local file = io.open("groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
function run(msg, matches)
--vardump(msg)
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
return create_group(msg)
end
if matches[1] == 'log' and is_owner(msg) then
savelog(msg.to.id, "log file created by owner")
send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnidsfile, {receiver=receiver})
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
end
if not is_realm(msg) then
return
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[2] then if data[tostring(matches[2])] then
local settings = data[tostring(matches[2])]['settings']
if matches[1] == 'setabout' and matches[2] then
local target = matches[2]
local about = matches[3]
return set_description(msg, data, target, about)
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then --group lock *
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
end
if matches[1] == 'unlock' then --group unlock *
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
end
if matches[1] == 'setting' and data[tostring(matches[2])]['settings'] then
local target = matches[2]
return show_group_settings(msg, data, target)
end
if matches[1] == 'setname' and is_admin(msg) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
rename_chat(to_rename, group_name_set, ok_cb, false)
end
end end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if not is_admin(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been demoted")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'list' and matches[2] == 'admins' then
return admin_list(msg)
end
if matches[1] == 'list' and matches[2] == 'groups' then
group_list(msg)
send_document("chat#id"..msg.to.id, "groups.txt", ok_cb, false)
return " Group list created" --group_list(msg)
end
end
return {
patterns = {
"^[!/](creategroup) (.*)$",
"^[!/](setabout) (%d+) (.*)$",
"^[!/](setrules) (%d+) (.*)$",
"^[!/](setname) (%d+) (.*)$",
"^[!/](lock) (%d+) (.*)$",
"^[!/](unlock) (%d+) (.*)$",
"^[!/](setting) (%d+)$",
"^[!/](wholist)$",
"^[!/](who)$",
"^[!/](addadmin) (.*)$", -- sudoers only
"^[!/](removeadmin) (.*)$", -- sudoers only
"^[!/](list) (.*)$",
"^[!/](log)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
mynameiscraziu/mycaty | plugins/plugins.lua | 325 | 6164 | do
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'. '..v..' '..status..'\n'
end
end
local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled'
return text
end
local function list_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..v..' '..status..'\n'
end
end
local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.'
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return 'Plugin '..plugin_name..' is enabled'
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return 'Plugin '..plugin_name..' does not exists'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return 'Plugin '..name..' does not exists'
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return 'Plugin '..name..' not enabled'
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return "Plugin doesn't exists"
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return 'Plugin '..plugin..' disabled on this chat'
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return 'This plugin is not disabled'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return 'Plugin '..plugin..' is enabled again'
end
local function run(msg, matches)
-- Show the available plugins
if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return list_all_plugins()
end
-- Re-enable a plugin for this chat
if matches[1] == 'enable' and matches[3] == 'chat' then
local receiver = get_receiver(msg)
local plugin = matches[2]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
-- Enable a plugin
if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
-- Disable a plugin on a chat
if matches[1] == 'disable' and matches[3] == 'chat' then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
end
-- Disable a plugin
if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[2] == 'plugins' then
return 'This plugin can\'t be disabled'
end
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
end
return {
description = "Plugin to manage other plugins. Enable, disable or reload.",
usage = {
moderator = {
"!plugins disable [plugin] chat : disable plugin only this chat.",
"!plugins enable [plugin] chat : enable plugin only this chat.",
},
sudo = {
"!plugins : list all plugins.",
"!plugins enable [plugin] : enable plugin.",
"!plugins disable [plugin] : disable plugin.",
"!plugins reload : reloads all plugins." },
},
patterns = {
"^!plugins$",
"^!plugins? (enable) ([%w_%.%-]+)$",
"^!plugins? (disable) ([%w_%.%-]+)$",
"^!plugins? (enable) ([%w_%.%-]+) (chat)",
"^!plugins? (disable) ([%w_%.%-]+) (chat)",
"^!plugins? (reload)$" },
run = run,
moderated = true, -- set to moderator mode
--privileged = true
}
end | gpl-2.0 |
nyczducky/darkstar | scripts/zones/Al_Zahbi/npcs/Bornahn.lua | 14 | 1170 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Bornahn
-- Guild Merchant NPC: Goldsmithing Guild
-- @pos 46.011 0.000 -42.713 48
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Al_Zahbi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(60429,8,23,4)) then
player:showText(npc,BORNAHN_SHOP_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Misareaux_Coast/Zone.lua | 12 | 1571 | -----------------------------------
--
-- Zone: Misareaux_Coast (25)
--
-----------------------------------
package.loaded["scripts/zones/Misareaux_Coast/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Misareaux_Coast/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(567.624,-20,280.775,120);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
sudheesh001/RFID-DBSync | cardpeek-0.8.3/dot_cardpeek_dir/scripts/belgian eID.lua | 17 | 6000 | --
-- This file is part of Cardpeek, the smartcard reader utility.
--
-- Copyright 2009-2013 by 'L1L1'
--
-- Cardpeek is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Cardpeek 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 Cardpeek. If not, see <http://www.gnu.org/licenses/>.
--
-- @name Belgian eID
-- @description Belgian electronic ID card.
-- @targets 0.8
require('lib.apdu')
require('lib.tlv')
require('lib.strict')
function tlv_parse_utf8(node,data)
node:set_attribute("val",data)
node:set_attribute("alt",data:format("%C"))
end
EID_IDO = {
['0'] = { "File structure version" },
['1'] = { "Card number", ui_parse_printable },
['2'] = { "Chip number" },
['3'] = { "Card validity start date", ui_parse_printable },
['4'] = { "Card validity end date", ui_parse_printable },
['5'] = { "Card delivery municipality", ui_parse_printable },
['6'] = { "National number", ui_parse_printable },
['7'] = { "Name", ui_parse_printable },
['8'] = { "2 first given names", ui_parse_printable },
['9'] = { "First letter of third given name", ui_parse_printable },
['A'] = { "Nationality", ui_parse_printable },
['B'] = { "Birth location", ui_parse_printable },
['C'] = { "Birth date", ui_parse_printable },
['D'] = { "Sex", ui_parse_printable },
['E'] = { "Noble condition", ui_parse_printable },
['F'] = { "Document type", ui_parse_printable },
['10'] = { "Special status", ui_parse_printable },
['11'] = { "Hash of photo" }
}
ADDRESS_IDO = {
['0'] = { "File structure version" },
['1'] = { "Street and number", ui_parse_printable },
['2'] = { "ZIP code", ui_parse_printable },
['3'] = { "municipality", ui_parse_printable }
}
--[[
-- If we follow the specs, this is the type of TLV parsing we need to do.
-- in practice tlv_parse() in lib.tlv seems to work just as well
function simpletlv_parse(node,data,ido)
local tag
local len = 0
local head
local tail
local pos = 1
local child
if data==nil or #data==0 then
return
end
tag = string.format("%X",data:get(0))
while data:get(pos)==0xFF do
len = len + 255
pos = pos + 1
end
len = len + data:get(pos)
pos = pos + 1
head = data:sub(pos,pos+len-1)
tail = data:sub(pos+len)
if ido[tag] then
child = node:append({ classname="item", label=ido[tag][1], id=tag, size=#head })
if ido[tag][2] then
ido[tag][2](child,head)
else
child:set_attribute("val",head)
end
else
node:append({ classname="file", label="(unknown)", id=tag, size=#head, val=head })
end
return simpletlv_parse(node,tail,ido)
end
--]]
-- weird parameters for belgian EID card select
local BEID_SELECT = card.SELECT_RETURN_FMD + card.SELECT_RETURN_FCP
function eid_process_photo(node)
node:set_attribute("mime-type","image/jpeg")
end
function eid_process_tlv(node)
local data = node:get_attribute("val")
tlv_parse(node,data)
end
function eid_process_tlv_id(node)
local data = node:get_attribute("val")
tlv_parse(node,data,EID_IDO)
end
function eid_process_tlv_address(node)
local data = node:get_attribute("val")
tlv_parse(node,data,ADDRESS_IDO)
end
local eid_structure =
{
{ "folder", "MF", ".3F00", {
{ "file", "EF_DIR", ".2F00", eid_process_tlv },
{ "folder", "DF_BELPIC", ".DF00", {
{ "file", "EF_ODF", ".5031", eid_process_tlv },
{ "file", "EF_TokenInfo", ".5032", eid_process_tlv },
{ "file", "EF_AODF", ".5034", eid_process_tlv },
{ "file", "EF_PrKDF", ".5035", eid_process_tlv },
{ "file", "EF_CDF", ".5037", eid_process_tlv },
{ "file", "EF_Cert#2", ".5038", eid_process_tlv },
{ "file", "EF_Cert#3", ".5039", eid_process_tlv },
{ "file", "EF_Cert#4", ".503A", eid_process_tlv },
{ "file", "EF_Cert#6", ".503B", eid_process_tlv },
{ "file", "EF_Cert#8", ".503C", eid_process_tlv },
}},
{ "folder", "DF_ID", ".DF01", {
{ "file", "EF_ID#RN", ".4031", eid_process_tlv_id },
{ "file", "EF_SGN#RN", ".4032", nil },
{ "file", "EF_ID#Address",".4033", eid_process_tlv_address },
{ "file", "EF_SGN#Address",".4034", nil },
{ "file", "EF_ID#Photo", ".4035", eid_process_photo },
{ "file", "EF_PuK#7", ".4038", nil },
{ "file", "EF_Preferences",".4039", nil },
}}
}
}
}
function eid_load_files(parent, struct, path)
local k,v
local sw, resp
local node
if struct==nil then
log.print(log.ERROR,"missing parameter #2 in eid_load_files()")
return
end
if path==nil then
path = {}
end
for k,v in ipairs(struct) do
sw, resp = card.select(v[3],BEID_SELECT)
if sw == 0x9000 then
node = parent:append({ classname=v[1], label=v[2], id=v[3] })
if type(v[4])=="table" then
table.insert(path,v[3])
eid_load_files(node,v[4],path)
table.remove(path)
local k2,v2
-- this is done to move up to parent dir
-- We start again from the MF and go down
for k2,v2 in ipairs(path) do
card.select(v2,BEID_SELECT)
end
else
local pos = 0
local data = bytes.new(8)
repeat
sw, resp = card.read_binary('.',pos)
if resp then
pos = pos + #resp
data = data .. resp
end
until sw~=0x9000 or resp==nil or #resp<256
if #data then
node:set_attribute("val",data)
node:set_attribute("size",#data)
if type(v[4])=="function" then
v[4](node)
end
else
node:set_attribute("alt",string.format("No content (code %04x)",sw))
end
end
end
end
end
if card.connect() then
local CARD
CARD = card.tree_startup("Belgian eID")
eid_load_files(CARD,eid_structure)
card.disconnect()
end
| gpl-2.0 |
nyczducky/darkstar | scripts/globals/weaponskills/empyreal_arrow.lua | 15 | 1552 | -----------------------------------
-- Empyreal Arrow
-- Archery weapon skill
-- Skill level: 250
-- In order to obtain Empyreal Arrow, the quest From Saplings Grow must be completed.
-- Delivers a single-hit attack. Damage varies with TP.
-- Aligned with the Flame Gorget & Light Gorget.
-- Aligned with the Flame Belt & Light Belt.
-- Element: None
-- Modifiers: STR:16% ; AGI:25%
-- 100%TP 200%TP 300%TP
-- 2.00 2.75 3.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 1;
params.ftp100 = 2; params.ftp200 = 2.75; params.ftp300 = 3;
params.str_wsc = 0.16; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.25; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 1.5; params.ftp200 = 2.5; params.ftp300 = 5;
params.str_wsc = 0.20; params.agi_wsc = 0.50;
params.atkmulti = 2;
end
local damage, criticalHit, tpHits, extraHits = doRangedWeaponskill(player, target, wsID, params, tp, primary);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
wenhulove333/ScutServer | Sample/Doudizhu/Client/lua/lib/ZyMessageBoxEx.lua | 1 | 13975 |
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:registerScriptTapHandler(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] )
contentLabel= ZyMultiLabel:new(contentStr,labelWidth,FONT_NAME,FONT_SMM_SIZE)
contentLabel:addto(messageBox,0)
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 |
blackman1380/selfbot | plugins/password.lua | 4 | 2252 | do
local function set_pass(msg, pass, id)
local hash = nil
if msg.to.type == "channel" then
hash = 'setpass:'
end
local name = string.gsub(msg.to.print_name, '_', '')
if hash then
redis:hset(hash, pass, id)
return send_large_msg("channel#id"..msg.to.id, "Password Of SuperGroup/Group : ["..name.."] Has Been Set To:\n> "..pass.."\n\nNow User Can Join in pm (Send Msg To @BlackPlus In PV) By\n\n#join "..pass.." ", ok_cb, true)
end
end
local function is_used(pass)
local hash = 'setpass:'
local used = redis:hget(hash, pass)
return used or false
end
local function show_add(cb_extra, success, result)
vardump(result)
local receiver = cb_extra.receiver
local text = "I Added You To > "..result.title
send_large_msg(receiver, text)
end
local function added(msg, target)
local receiver = get_receiver(msg)
channel_info("channel#id"..target, show_add, {receiver=receiver})
end
local function run(msg, matches)
if matches[1] == "setpass" and msg.to.type == "channel" and matches[2] then
local pass = matches[2]
local id = msg.to.id
if is_used(pass) then
return "Sorry, This pass is already taken."
end
redis:del("setpass:", id)
return set_pass(msg, pass, id)
end
if matches[1] == "join" and matches[2] then
local hash = 'setpass:'
local pass = matches[2]
local id = redis:hget(hash, pass)
local receiver = get_receiver(msg)
if not id then
return "*Error 404\n\n> Could not find a group with this pass\n> Maby the pass has been changed"
end
channel_invite("channel#id"..id, "user#id"..msg.from.id, ok_cb, false)
return added(msg, id)
else
return "I could not added you to"..string.gsub(msg.to.id.print_name, '_', ' ')
end
if matches[1] == "pass" then
local hash = 'setpass:'
local chat_id = msg.to.id
local pass = redis:hget(hash, channel_id)
local receiver = get_receiver(msg)
send_large_msg(receiver, "Password for SuperGroup/Group : ["..msg.to.print_name.."]\n\nPass > "..pass)
end
end
return {
patterns = {
"^[/!#](setpass) (.*)$",
"^[/!#](pass)$",
"^[/!#]([Jj]oin) (.*)$",
"^!!tgservice (chat_add_user)$",
"^!!tgservice (.+)$",
"^!!tgservice (chat_del_user)$"
},
run = run
}
end | gpl-2.0 |
nyczducky/darkstar | scripts/globals/mobskills/Everyones_Grudge.lua | 36 | 1591 | ---------------------------------------------
-- Everyones Grudge
--
-- Notes: Invokes collective hatred to spite a single target.
-- Damage done is 5x the amount of tonberries you have killed! For NM's using this it is 50 x damage.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:isMobType(MOBTYPE_NOTORIOUS)) then
return 1;
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local realDmg = 0;
local mobID = mob:getID();
local power = 5;
if (target:getID() > 100000) then
realDmg = power * math.random(30,100);
else
realDmg = power * target:getVar("EVERYONES_GRUDGE_KILLS"); -- Damage is 5 times the amount you have killed
if (mobID == 17428677 or mobID == 17433008 or mobID == 17433006 or mobID == 17433009 or mobID == 17432994 or mobID == 17433007 or mobID == 17428813 or mobID == 17432659 or mobID == 17432846 or mobID == 17428809) then
realDmg = realDmg * 10; -- Sets the Multiplyer to 50 for NM's
elseif (mobID == 17432799 or mobID == 17428611 or MobID == 17428554 or mobID == 17428751 or mobID == 17432609 or mobID == 16814432 or mobID == 17432624 or mobID == 17285526 or mobID == 17285460) then
realDmg = realDmg * 10; -- Sets the Multiplyer to 50 for NM's , staggered list
end
end
target:delHP(realDmg);
return realDmg;
end; | gpl-3.0 |
dddaaaddd/teleiran_new | plugins/banhammer.lua | 1 | 12493 |
local function pre_process(msg)
local data = load_data(_config.moderation.data)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] Is Banned & Kicked ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned and not is_momod2(msg.from.id, msg.to.id) or is_gbanned(user_id) and not is_admin2(msg.from.id) then -- Check it with redis
print('User is banned!')
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) >= 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) >= 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' or msg.to.type == 'channel' then
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
local chat_id = extra.chat_id
local chat_type = extra.chat_type
if chat_type == "chat" then
receiver = 'chat#id'..chat_id
else
receiver = 'channel#id'..chat_id
end
if success == 0 then
return send_large_msg(receiver, "Cannot find username")
end
local member_id = result.peer_id
local user_id = member_id
local member = result.username
local from_id = extra.from_id
local get_cmd = extra.get_cmd
if get_cmd == "kick" then
if member_id == from_id then
send_large_msg(receiver, "You can't kick yourself")
return
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
send_large_msg(receiver, "You can't kick mods/owner/admins")
return
end
kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
send_large_msg(receiver, "You can't ban mods/owner/admins")
return
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] Banned')
ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] UnBanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] Public Banned')
banall_user(member_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] Public UnBanned')
unbanall_user(member_id)
end
end
local function run(msg, matches)
local support_id = msg.from.id
if matches[1]:lower() == 'id' and msg.to.type == "chat" or msg.to.type == "user" then
if msg.to.type == "user" then
return "User ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID: "..msg.to.id.."\nUser ID: "..msg.from.id
end
end
if matches[1]:lower() == 'kickme' and msg.to.type == "chat" then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin1(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin1(msg) then
msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
elseif string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
local receiver = get_receiver(msg)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(matches[2], msg.to.id)
send_large_msg(receiver, 'User ['..matches[2]..'] banned')
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin1(msg) then
msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
elseif string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self"
end
local user_id = matches[2]
local chat_id = msg.to.id
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if not is_admin1(msg) and not is_support(support_id) then
return
end
if matches[1]:lower() == 'banall' and is_admin1(msg) then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin1(msg) then
banall = get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] Public Banned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] Public UnBanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[#!/]([Bb]anall) (.*)$",
"^[#!/]([Bb]anall)$",
"^[#!/]([Bb]anlist) (.*)$",
"^[#!/]([Bb]anlist)$",
"^[#!/]([Gg]banlist)$",
"^[#!/]([Kk]ickme)",
"^[#!/]([Kk]ick)$",
"^[#!/]([Bb]an)$",
"^[#!/]([Bb]an) (.*)$",
"^[#!/]([Uu]nban) (.*)$",
"^[#!/]([Uu]nbanall) (.*)$",
"^[#!/]([Uu]nbanall)$",
"^[#!/]([Kk]ick) (.*)$",
"^[#!/]([Uu]nban)$",
"^[#!/]([Ii][Dd])$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
AquariaOSE/Aquaria | files/scripts/maps/node_pushleft.lua | 6 | 1045 | -- 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)
v.n = getNaija()
end
function update(me, dt)
if node_isEntityIn(me, v.n) then
entity_addVel(v.n, -8000*dt, 0)
end
end
| gpl-2.0 |
abosalah22/memo | plugins/aboshoshoo1.lua | 1 | 4351 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY SAJJAD NOORI ▀▄ ▄▀
▀▄ ▄▀ BY SAJAD NOORI (@SAJJADNOORI) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY SAJJAD NOORI ▀▄ ▄▀
▀▄ ▄▀ help1 : مساعدة ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
do
local function run(msg, matches)
if is_momod(msg) and matches[1]== "help1" then
return [[ ❣ setadmin : لرفع اداري للمجموعه
❣ demoteadmin : لتنزيل اداري من المجموعه
❣ promote : لرفع او تصعيد ادمن
❣ demote : لتنزيل او حذف الادمن
❣ owner : لعرض المدير
❣ modlist : لاظهار ادمنية المجموعة
❣ admins : اضهار اداريين المجموعه
🔸➖🔹➖🔸➖🔹➖🔸
✔️ Commands for control membee
❣ kick : لطرد العضو
❣ ban : لحظر العظر
❣ unban : فتح الخظر عن العضو
❣ kickme : للخروج من المجموعة
❣ silent : لتفعيل الصمت على احد الاعضاء
❣ clean mutelist: الغاء الصمت على العضو
❣ block : لحضر الكلمة
❣ words : لعرض الكلمات المحظورة
❣ unblock : لفتح حضر الكلمة
❣ me : لمعرفه موقعك في المجموعة
🔸➖🔹➖🔸➖🔹➖🔸
✔️ Commands for control
❣ rules : لاضهار القوانين
❣ setrules : لاظافة القوانين
❣ setphoto : لوضع صورة
❣ setname : لوضع اسم
❣ setusername : لوضع معرف للكروب
❣ setabout : لاظافة الوصف
❣ id : لاظهار الايدي
❣ settings : اضهار اعدادات المجموعة
❣ info : اضهار المعلومات الخاصه بك
❣ info group : اضهار معلومات المجموعة
❣ settings modes : اضهار اعادادات الوسائط
❣ newlink : لصنع الرابط او تغيرة
❣ link : لضهور رابط المجموعه
❣ setlink : لوضع رابط للمجموعه
❣ linksl : للحصول على الرابط في الخاص
🔸➖🔹➖🔸➖🔹➖🔸
✔️ Commands for Security
❣ lock all : لقفل المجموعه باكملها
❣ unlock all : لفتح المجموعه باكملها
❣ lock member : لقفل اضافة المجموعة
❣ unlock member : للفتح اضافة المجموعة
❣ lock text : لقفل دردشة المجموعة
❣ unlock text : فتح الدردشه
❣ lock photo : لمنع إرسال الصور
❣ unlock photo : للسماح بإرسال الصور
❣ lock audio : لمنع البصمات
❣ unlock audio : للسماح بإرسال البصمات
❣ lock video : لمنع ارسال فديو
❣ unlock video : للسماح بإرسال فديو
❣ lock links : لمنع الروابط
❣ unlock links : للسماح بإرسال روابط
❣ lock flood : لمنع التكرار
❣ unlock flood : للسماح بلتكرار
❣ lock sticker : لمنع الملصقات
❣ unlock sticker : للسماح بلملصقات
❣ lock gifs : لمنع الصور المتحركة
❣ unlock gifs : للسماح بالصور المتحركة
❣ lock documents : لمنع ارسال الملفات
❣ unlock documents : للسماح بإرسال الملفات
❣ lock spam : لمنع الكلايش الطويلة
❣ unlock spam : للسماح بلكلايش الطويلة
❣ lock rtl : لمنع اطافة جماعة
❣ unlock rtl : للسماح بإضافة جماعة
❣ lock arabic : لمنع اللغة ألعربيه
❣ unlock arabic : للسماح بلغه ألعربيه
❣ lock fwd : لمنع اعاديت توجيه
❣ unlock fwd : للسماح باعادت توجيه
🔸➖🔹➖🔸➖🔹➖🔸
Version :1.0
#Dev : @abo_shosho98
#Dev_bot : @aboaloshbot
]]
end
if not is_momod(msg) then
return "Only admins 😎🖕🏿"
end
end
return {
description = "Help list",
usage = "Help list",
patterns = {
"(help1)"
},
run = run
}
end
| gpl-2.0 |
nyczducky/darkstar | scripts/globals/items/dish_of_spaghetti_carbonara.lua | 12 | 1829 | -----------------------------------------
-- ID: 5190
-- Item: dish_of_spaghetti_carbonara
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Health % 14
-- Health Cap 175
-- Magic 10
-- Strength 4
-- Vitality 2
-- Intelligence -3
-- Attack % 17
-- Attack Cap 65
-- Store TP 6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5190);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 14);
target:addMod(MOD_FOOD_HP_CAP, 175);
target:addMod(MOD_MP, 10);
target:addMod(MOD_STR, 4);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_INT, -3);
target:addMod(MOD_FOOD_ATTP, 17);
target:addMod(MOD_FOOD_ATT_CAP, 65);
target:addMod(MOD_STORETP, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 14);
target:delMod(MOD_FOOD_HP_CAP, 175);
target:delMod(MOD_MP, 10);
target:delMod(MOD_STR, 4);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_INT, -3);
target:delMod(MOD_FOOD_ATTP, 17);
target:delMod(MOD_FOOD_ATT_CAP, 65);
target:delMod(MOD_STORETP, 6);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Caedarva_Mire/npcs/Nuimahn.lua | 14 | 1402 | -----------------------------------
-- Area: Caedarva Mire
-- NPC: Nuimahn
-- Type: Alzadaal Undersea Ruins
-- @pos -380 0 -381 79
-----------------------------------
package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Caedarva_Mire/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1 and trade:hasItemQty(2185,1)) then
player:tradeComplete();
player:startEvent(0x00cb);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getZPos() < -281) then
player:startEvent(0x00cc); -- leaving
else
player:startEvent(0x00ca); -- entering
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 == 0x00cb) then
player:setPos(-515,-6.5,740,0,72);
end
end; | gpl-3.0 |
nyczducky/darkstar | scripts/zones/Temenos/npcs/Armoury_Crate.lua | 21 | 8373 | -----------------------------------
-- Area: Temenos
-- NPC: Armoury Crate
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/zones/Temenos/TextIDs");
require("scripts/globals/limbus");
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local CofferID = npc:getID();
local CofferType=0;
local lootID=0;
local InstanceRegion=0;
local addtime=0;
local DespawnOtherCoffer=false;
local MimicID=0;
local X = npc:getXPos();
local Y = npc:getYPos();
local Z = npc:getZPos();
for coffer = 1,#ARMOURY_CRATES_LIST_TEMENOS,2 do
if (ARMOURY_CRATES_LIST_TEMENOS[coffer] == CofferID-16928768) then
CofferType=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][1];
InstanceRegion=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][2];
addtime=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][3];
DespawnOtherCoffer=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][4];
MimicID=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][5];
lootID=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][6];
end
end
printf("CofferID : %u",CofferID-16928768);
printf("Coffertype %u",CofferType);
printf("InstanceRegion: %u",InstanceRegion);
printf("addtime: %u",addtime);
printf("MimicID: %u",MimicID);
printf("lootID: %u",lootID);
local coffer = CofferID-16928768;
if (CofferType == cTIME) then
player:addTimeToSpecialBattlefield(InstanceRegion,addtime);
elseif (CofferType == cITEM) then
if (InstanceRegion == Central_Temenos_4th_Floor and coffer~=79) then
local randmimic = math.random(1,24)
print("randmimic" ..randmimic);
if ( randmimic < 19) then
local MimicList={16928986,16928987,16928988,16928989,16928990,16928991,16928992,16928993,16928994,16928995,16928996,16928997,16928998,16928999,16929000,16929001,16929002,16929003};
GetMobByID(MimicList[randmimic]):setSpawn(X,Y,Z);
SpawnMob(MimicList[randmimic]):setPos(X,Y,Z);
GetMobByID(MimicList[randmimic]):updateClaim(player);
else
player:BCNMSetLoot(lootID,InstanceRegion,CofferID);
player:getBCNMloot();
end
-- despawn les coffer du meme groupe
for coffer = 1, #ARMOURY_CRATES_LIST_TEMENOS, 2 do
if (ARMOURY_CRATES_LIST_TEMENOS[coffer+1][5] == MimicID) then
GetNPCByID(16928768+ARMOURY_CRATES_LIST_TEMENOS[coffer]):setStatus(STATUS_DISAPPEAR);
end
end
else
player:BCNMSetLoot(lootID, InstanceRegion, CofferID);
player:getBCNMloot();
end
elseif (CofferType == cRESTORE) then
player:RestoreAndHealOnBattlefield(InstanceRegion);
elseif (CofferType == cMIMIC) then
if (coffer == 284) then
GetMobByID(16928844):setSpawn(X,Y,Z);
SpawnMob(16928844):setPos(X,Y,Z)
GetMobByID(16928844):updateClaim(player);
elseif (coffer == 321) then
GetMobByID(16928853):setSpawn(X,Y,Z);
SpawnMob(16928853):setPos(X,Y,Z);
GetMobByID(16928853):updateClaim(player);
elseif (coffer == 348) then
GetMobByID(16928862):setSpawn(X,Y,Z);
SpawnMob(16928862):setPos(X,Y,Z);
GetMobByID(16928862):updateClaim(player);
elseif (coffer == 360) then
GetMobByID(16928871):setSpawn(X,Y,Z);
SpawnMob(16928871):setPos(X,Y,Z);
GetMobByID(16928871):updateClaim(player);
elseif (coffer == 393) then
GetMobByID(16928880):setSpawn(X,Y,Z);
SpawnMob(16928880):setPos(X,Y,Z);
GetMobByID(16928880):updateClaim(player);
elseif (coffer == 127) then
GetMobByID(16928889):setSpawn(X,Y,Z);
SpawnMob(16928889):setPos(X,Y,Z);
GetMobByID(16928889):updateClaim(player);
elseif (coffer == 123) then
GetMobByID(16928894):setSpawn(X,Y,Z);
SpawnMob(16928894):setPos(X,Y,Z);
GetMobByID(16928894):updateClaim(player);
end
end
if (DespawnOtherCoffer == true) then
HideArmouryCrates(InstanceRegion,TEMENOS);
if (InstanceRegion==Temenos_Eastern_Tower) then --despawn mob of the current floor
if (coffer == 173 or coffer == 215 or coffer == 284 or coffer == 40) then
--floor 1
if (GetMobAction(16928840) > 0) then DespawnMob(16928840); end
if (GetMobAction(16928841) > 0) then DespawnMob(16928841); end
if (GetMobAction(16928842) > 0) then DespawnMob(16928842); end
if (GetMobAction(16928843) > 0) then DespawnMob(16928843); end
GetNPCByID(16929228):setStatus(STATUS_NORMAL);
elseif (coffer == 174 or coffer == 216 or coffer == 321 or coffer == 45) then
--floor 2
if (GetMobAction(16928849) > 0) then DespawnMob(16928849); end
if (GetMobAction(16928850) > 0) then DespawnMob(16928850); end
if (GetMobAction(16928851) > 0) then DespawnMob(16928851); end
if (GetMobAction(16928852) > 0) then DespawnMob(16928852); end
GetNPCByID(16929229):setStatus(STATUS_NORMAL);
elseif (coffer == 181 or coffer == 217 or coffer == 348 or coffer == 46) then
--floor 3
if (GetMobAction(16928858) > 0) then DespawnMob(16928858); end
if (GetMobAction(16928859) > 0) then DespawnMob(16928859); end
if (GetMobAction(16928860) > 0) then DespawnMob(16928860); end
if (GetMobAction(16928861) > 0) then DespawnMob(16928861); end
GetNPCByID(16929230):setStatus(STATUS_NORMAL);
elseif (coffer == 182 or coffer == 236 or coffer == 360 or coffer == 47) then
--floor 4
if (GetMobAction(16928867) > 0) then DespawnMob(16928867); end
if (GetMobAction(16928868) > 0) then DespawnMob(16928868); end
if (GetMobAction(16928869) > 0) then DespawnMob(16928869); end
if (GetMobAction(16928870) > 0) then DespawnMob(16928870); end
GetNPCByID(16929231):setStatus(STATUS_NORMAL);
elseif (coffer == 183 or coffer == 261 or coffer == 393 or coffer == 68) then
--floor 5
if (GetMobAction(16928876) > 0) then DespawnMob(16928876); end
if (GetMobAction(16928877) > 0) then DespawnMob(16928877); end
if (GetMobAction(16928878) > 0) then DespawnMob(16928878); end
if (GetMobAction(16928879) > 0) then DespawnMob(16928879); end
GetNPCByID(16929232):setStatus(STATUS_NORMAL);
elseif (coffer == 277 or coffer == 190 or coffer == 127 or coffer == 69) then
--floor 6
if (GetMobAction(16928885) > 0) then DespawnMob(16928885); end
if (GetMobAction(16928886) > 0) then DespawnMob(16928886); end
if (GetMobAction(16928887) > 0) then DespawnMob(16928887); end
if (GetMobAction(16928888) > 0) then DespawnMob(16928888); end
GetNPCByID(16929233):setStatus(STATUS_NORMAL);
elseif (coffer == 70 or coffer == 123) then
--floor 7
if (GetMobAction(16928892) > 0) then DespawnMob(16928892); end
if (GetMobAction(16928893) > 0) then DespawnMob(16928893); end
GetNPCByID(16929234):setStatus(STATUS_NORMAL);
end
end
end
npc:setStatus(STATUS_DISAPPEAR);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.