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
lichtl/darkstar
scripts/zones/Abyssea-Attohwa/npcs/qm12.lua
9
1344
----------------------------------- -- Zone: Abyssea-Attohwa -- NPC: qm12 (???) -- Spawns Mielikki -- @pos ? ? ? 215 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(3084,1) and trade:getItemCount() == 1) then -- Player has all the required items. if (GetMobAction(17658273) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(17658273):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 3084); -- Inform player what items they need. 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
lichtl/darkstar
scripts/globals/spells/jubaku_san.lua
27
1700
----------------------------------------- -- Spell: Jubaku: San -- Spell accuracy is most highly affected by Enfeebling Magic Skill, Magic Accuracy, and INT. -- taken from paralyze ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local effect = EFFECT_PARALYSIS; -- Base Stats local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT)); --Duration Calculation local duration = 420 * applyResistance(caster,spell,target,dINT,NINJUTSU_SKILL,0); --Paralyze base power is 35 and is not affected by resistaces. local power = 35; --Calculates resist chanve from Reist Blind if (math.random(0,100) >= target:getMod(MOD_PARALYZERES)) then if (duration >= 210) then -- Erases a weaker blind and applies the stronger one local paralysis = target:getStatusEffect(effect); if (paralysis ~= nil) then if (paralysis:getPower() < power) then target:delStatusEffect(effect); target:addStatusEffect(effect,power,0,duration); spell:setMsg(237); else spell:setMsg(75); end else target:addStatusEffect(effect,power,0,duration); spell:setMsg(237); end else spell:setMsg(85); end else spell:setMsg(284); end return effect; end;
gpl-3.0
lichtl/darkstar
scripts/zones/Windurst_Woods/npcs/Samigo-Pormigo.lua
11
2592
----------------------------------- -- Area: Windurst Woods -- NPC: Samigo-Pormigo -- Type: Guildworker's Union Representative -- @zone 241 -- @pos -9.782 -5.249 -134.432 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; require("scripts/globals/keyitems"); require("scripts/globals/crafting"); require("scripts/zones/Windurst_Woods/TextIDs"); local keyitems = { [0] = { id = BONE_PURIFICATION, rank = 3, cost = 40000 }, [1] = { id = BONE_ENSORCELLMENT, rank = 3, cost = 40000 }, [2] = { id = FILING, rank = 3, cost = 10000 }, [3] = { id = WAY_OF_THE_BONEWORKER, rank = 9, cost = 20000 } }; local items = { [2] = { id = 15449, rank = 3, cost = 10000 }, [3] = { id = 13947, rank = 6, cost = 70000 }, [4] = { id = 14397, rank = 7, cost = 100000 }, [5] = { id = 142, -- Drogaroga's Fang rank = 9, cost = 150000 }, [6] = { id = 336, -- Boneworker's Signboard rank = 9, cost = 200000 }, [7] = { id = 15824, -- Bonecrafter's Ring rank = 6, cost = 80000 }, [8] = { id = 3663, -- Bonecraft Tools rank = 7, cost = 50000 }, [9] = { id = 3326, -- Boneworker's Emblem rank = 9, cost = 15000 } }; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) unionRepresentativeTrade(player, npc, trade, 0x2727, 6); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) unionRepresentativeTrigger(player, 6, 0x2726, "guild_bonecraft", keyitems); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,target) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x2726) then unionRepresentativeTriggerFinish(player, option, target, 6, "guild_bonecraft", keyitems, items); elseif (csid == 0x2727) then player:messageSpecial(GP_OBTAINED, option); end end;
gpl-3.0
lichtl/darkstar
scripts/zones/Bostaunieux_Oubliette/npcs/Chumia.lua
14
1059
----------------------------------- -- Area: Bostaunieux Oubliette -- NPC: Chumia -- Type: Standard NPC -- @pos 102.420 -25.001 70.457 167 ----------------------------------- package.loaded["scripts/zones/Bostaunieux_Oubliette/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Bostaunieux_Oubliette/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, CHUMIA_DIALOG); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Megaf/MegafXPlore2
mods/vessels/init.lua
3
6178
-- Minetest 0.4 mod: vessels -- See README.txt for licensing and other information. local vessels_shelf_formspec = "size[8,7;]" .. default.gui_bg .. default.gui_bg_img .. default.gui_slots .. "list[context;vessels;0,0.3;8,2;]" .. "list[current_player;main;0,2.85;8,1;]" .. "list[current_player;main;0,4.08;8,3;8]" .. "listring[context;vessels]" .. "listring[current_player;main]" .. default.get_hotbar_bg(0, 2.85) local function get_vessels_shelf_formspec(inv) local formspec = vessels_shelf_formspec local invlist = inv and inv:get_list("vessels") -- Inventory slots overlay local vx, vy = 0, 0.3 for i = 1, 16 do if i == 9 then vx = 0 vy = vy + 1 end if not invlist or invlist[i]:is_empty() then formspec = formspec .. "image[" .. vx .. "," .. vy .. ";1,1;vessels_shelf_slot.png]" end vx = vx + 1 end return formspec end minetest.register_node("vessels:shelf", { description = "Vessels Shelf", tiles = {"default_wood.png", "default_wood.png", "default_wood.png", "default_wood.png", "vessels_shelf.png", "vessels_shelf.png"}, paramtype2 = "facedir", is_ground_content = false, groups = {choppy = 3, oddly_breakable_by_hand = 2, flammable = 3}, sounds = default.node_sound_wood_defaults(), on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("formspec", get_vessels_shelf_formspec(nil)) local inv = meta:get_inventory() inv:set_size("vessels", 8 * 2) end, can_dig = function(pos,player) local inv = minetest.get_meta(pos):get_inventory() return inv:is_empty("vessels") end, allow_metadata_inventory_put = function(pos, listname, index, stack, player) if minetest.get_item_group(stack:get_name(), "vessel") ~= 0 then return stack:get_count() end return 0 end, on_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) minetest.log("action", player:get_player_name() .. " moves stuff in vessels shelf at ".. minetest.pos_to_string(pos)) local meta = minetest.get_meta(pos) meta:set_string("formspec", get_vessels_shelf_formspec(meta:get_inventory())) end, on_metadata_inventory_put = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name() .. " moves stuff to vessels shelf at ".. minetest.pos_to_string(pos)) local meta = minetest.get_meta(pos) meta:set_string("formspec", get_vessels_shelf_formspec(meta:get_inventory())) end, on_metadata_inventory_take = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name() .. " takes stuff from vessels shelf at ".. minetest.pos_to_string(pos)) local meta = minetest.get_meta(pos) meta:set_string("formspec", get_vessels_shelf_formspec(meta:get_inventory())) end, on_blast = function(pos) local drops = {} default.get_inventory_drops(pos, "vessels", drops) drops[#drops + 1] = "vessels:shelf" minetest.remove_node(pos) return drops end, }) minetest.register_craft({ output = "vessels:shelf", recipe = { {"group:wood", "group:wood", "group:wood"}, {"group:vessel", "group:vessel", "group:vessel"}, {"group:wood", "group:wood", "group:wood"}, } }) minetest.register_node("vessels:glass_bottle", { description = "Empty Glass Bottle", drawtype = "plantlike", tiles = {"vessels_glass_bottle.png"}, inventory_image = "vessels_glass_bottle.png", wield_image = "vessels_glass_bottle.png", paramtype = "light", is_ground_content = false, walkable = false, selection_box = { type = "fixed", fixed = {-0.25, -0.5, -0.25, 0.25, 0.3, 0.25} }, groups = {vessel = 1, dig_immediate = 3, attached_node = 1}, sounds = default.node_sound_glass_defaults(), }) minetest.register_craft( { output = "vessels:glass_bottle 10", recipe = { {"default:glass", "", "default:glass"}, {"default:glass", "", "default:glass"}, {"", "default:glass", ""} } }) minetest.register_node("vessels:drinking_glass", { description = "Empty Drinking Glass", drawtype = "plantlike", tiles = {"vessels_drinking_glass.png"}, inventory_image = "vessels_drinking_glass_inv.png", wield_image = "vessels_drinking_glass.png", paramtype = "light", is_ground_content = false, walkable = false, selection_box = { type = "fixed", fixed = {-0.25, -0.5, -0.25, 0.25, 0.3, 0.25} }, groups = {vessel = 1, dig_immediate = 3, attached_node = 1}, sounds = default.node_sound_glass_defaults(), }) minetest.register_craft( { output = "vessels:drinking_glass 14", recipe = { {"default:glass", "", "default:glass"}, {"default:glass", "", "default:glass"}, {"default:glass", "default:glass", "default:glass"} } }) minetest.register_node("vessels:steel_bottle", { description = "Empty Heavy Steel Bottle", drawtype = "plantlike", tiles = {"vessels_steel_bottle.png"}, inventory_image = "vessels_steel_bottle.png", wield_image = "vessels_steel_bottle.png", paramtype = "light", is_ground_content = false, walkable = false, selection_box = { type = "fixed", fixed = {-0.25, -0.5, -0.25, 0.25, 0.3, 0.25} }, groups = {vessel = 1, dig_immediate = 3, attached_node = 1}, sounds = default.node_sound_defaults(), }) minetest.register_craft( { output = "vessels:steel_bottle 5", recipe = { {"default:steel_ingot", "", "default:steel_ingot"}, {"default:steel_ingot", "", "default:steel_ingot"}, {"", "default:steel_ingot", ""} } }) -- Glass and steel recycling minetest.register_craftitem("vessels:glass_fragments", { description = "Glass Fragments", inventory_image = "vessels_glass_fragments.png", }) minetest.register_craft( { type = "shapeless", output = "vessels:glass_fragments", recipe = { "vessels:glass_bottle", "vessels:glass_bottle", }, }) minetest.register_craft( { type = "shapeless", output = "vessels:glass_fragments", recipe = { "vessels:drinking_glass", "vessels:drinking_glass", }, }) minetest.register_craft({ type = "cooking", output = "default:glass", recipe = "vessels:glass_fragments", }) minetest.register_craft( { type = "cooking", output = "default:steel_ingot", recipe = "vessels:steel_bottle", }) minetest.register_craft({ type = "fuel", recipe = "vessels:shelf", burntime = 30, })
gpl-3.0
RunAwayDSP/darkstar
scripts/globals/items/copper_frog.lua
11
1130
----------------------------------------- -- ID: 4515 -- Item: copper_frog -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 2 -- Agility 2 -- Mind -4 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if (target:getRace() ~= dsp.race.MITHRA) then result = dsp.msg.basic.CANNOT_EAT end if (target:getMod(dsp.mod.EAT_RAW_FISH) == 1) then result = 0 end if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,300,4515) end function onEffectGain(target,effect) target:addMod(dsp.mod.DEX, 2) target:addMod(dsp.mod.AGI, 2) target:addMod(dsp.mod.MND, -4) end function onEffectLose(target, effect) target:delMod(dsp.mod.DEX, 2) target:delMod(dsp.mod.AGI, 2) target:delMod(dsp.mod.MND, -4) end
gpl-3.0
lichtl/darkstar
scripts/zones/Port_Jeuno/npcs/Illauvolahaut.lua
14
1629
----------------------------------- -- Area: Port Jeuno -- NPC: Illauvolahaut -- @zone 246 -- @pos -12 8 54 ----------------------------------- package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Port_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) KazhPass = player:hasKeyItem(AIRSHIP_PASS_FOR_KAZHAM); Gil = player:getGil(); if (KazhPass == false) then player:startEvent(0x0023); -- without pass elseif (KazhPass == true and Gil < 200) then player:startEvent(0x002d); -- Pass without money elseif (KazhPass == true) then player:startEvent(0x0025); -- Pass with money end end; -- 0x0029 without addons (ZM) ? ----------------------------------- -- 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 == 0x0025) then Z = player:getZPos(); if (Z >= 58 and Z <= 61) then player:delGil(200); end end end;
gpl-3.0
lichtl/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/CeraneIVirgaut1.lua
14
1059
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Cerane I Virgaut -- @zone 80 -- @pos -268 -4 100 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, 13454); -- (Couldn't find default dialogue) How very good to see you again! end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
OctoEnigma/shiny-octo-system
gamemodes/darkrp/gamemode/modules/animations/sh_interface.lua
13
1214
DarkRP.addPlayerGesture = DarkRP.stub{ name = "addPlayerGesture", description = "Add a player gesture to the DarkRP animations menu (the one that opens with the keys weapon.). Note: This function must be called BOTH serverside AND clientside!", parameters = { { name = "anim", description = "The gesture enumeration.", type = "number", optional = false }, { name = "text", description = "The textual description of the animation. This is what players see on the button in the menu.", type = "string", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.removePlayerGesture = DarkRP.stub{ name = "removePlayerGesture", description = "Removes a player gesture from the DarkRP animations menu (the one that opens with the keys weapon.). Note: This function must be called BOTH serverside AND clientside!", parameters = { { name = "anim", description = "The gesture enumeration.", type = "number", optional = false } }, returns = { }, metatable = DarkRP }
mit
lightxue/dotfiles
nvim/lua/editor.lua
1
1228
-- insert = "ys", -- visual = "S", -- delete = "ds", -- change = "cs", require("nvim-surround").setup({}) -- require("indent_blankline").setup { -- -- for example, context is off by default, use this to turn it on -- show_current_context = true, -- show_current_context_start = true, -- } require("which-key").setup() require('neoscroll').setup() require('lualine').setup({ options = { component_separators = { left = '', right = '|' }, section_separators = { left = '', right = '' }, }, sections = { lualine_a = { 'mode' }, lualine_b = { 'branch', 'diagnostics' }, lualine_c = { { 'filename', path = 1 } }, lualine_x = { { 'filetype', icon = { align = 'right' } }, 'encoding', 'fileformat' }, lualine_y = { '%l/%L:%c' }, lualine_z = { '%b-0x%B' } }, inactive_sections = { lualine_a = {}, lualine_b = {}, lualine_c = { 'filename' }, lualine_x = { { 'filetype', icon = { align = 'right' } }, 'encoding', 'fileformat' }, lualine_y = { '%l/%L:%c' }, lualine_z = {} }, }) require'hop'.setup()
bsd-2-clause
RunAwayDSP/darkstar
scripts/globals/geomagnetic_fount.lua
9
1111
----------------------------------- -- SOA Geomagnetic Founts ----------------------------------- require("scripts/globals/keyitems") require("scripts/globals/missions") ----------------------------------- dsp = dsp or {} dsp.geomagneticFount = dsp.geomagneticFount or {} dsp.geomagneticFount.checkFount = function(player, npc) local theGeomagnetron = player:getCurrentMission(SOA) == dsp.mission.id.soa.THE_GEOMAGNETRON local charged = player:getCharVar("SOA") == 1 if theGeomagnetron and charged then player:messageSpecial(zones[player:getZoneID()].text.GEOMAGNETRON_ATTUNED + 2) -- Your device has already been attuned to a geomagnetic fount in the corresponding locale. elseif theGeomagnetron then player:messageSpecial(zones[player:getZoneID()].text.GEOMAGNETRON_ATTUNED, 0, dsp.ki.GEOMAGNETRON) -- Your <keyitem> has been attuned to a geomagnetic fount in the corresponding locale. player:setCharVar("SOA", 1) else player:messageSpecial(zones[player:getZoneID()].text.GEOMAGNETRON_ATTUNED + 1) -- A faint energy wafts up from the ground. end end
gpl-3.0
lichtl/darkstar
scripts/globals/weaponskills/shockwave.lua
18
1486
----------------------------------- -- Shockwave -- Great Sword weapon skill -- Skill level: 150 -- Delivers an area of effect attack. Sleeps enemies. Duration of effect varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Aqua Gorget. -- Aligned with the Aqua Belt. -- Element: None -- Modifiers: STR:30% ; MND:30% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.3; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); if (damage > 0 and target:hasStatusEffect(EFFECT_SLEEP_I) == false) then local duration = (tp/1000 * 60); target:addStatusEffect(EFFECT_SLEEP_I, 1, 0, duration); end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
RunAwayDSP/darkstar
scripts/globals/maws.lua
8
5885
----------------------------------- -- Cavernous Maw global functions ----------------------------------- require("scripts/globals/keyitems") require("scripts/globals/missions") require("scripts/globals/quests") require("scripts/globals/settings") require("scripts/globals/teleports") require("scripts/globals/titles") require("scripts/globals/zone") ----------------------------------- dsp.maws = dsp.maws or {} local ZN = dsp.zone local MAW = dsp.teleport.type.PAST_MAW local pastMaws = { --[ZONE ID] = {Bit Slot in Array, Cutscenes{new to WoTg or add new, mission, warp}, Destination {Coordinates}} [ZN.BATALLIA_DOWNS] = {bit = 0, cs = {new = 500, msn = 501, warp = 910}, dest = { -51.486, 0.371, 436.972, 128, 84}}, [ZN.ROLANBERRY_FIELDS] = {bit = 1, cs = {new = 500, msn = 501, warp = 904}, dest = {-196.500, 7.999, 361.192, 225, 91}}, [ZN.SAUROMUGUE_CHAMPAIGN] = {bit = 2, cs = {new = 500, msn = 501, warp = 904}, dest = { 366.858, 8.545, -228.861, 95, 98}}, [ZN.JUGNER_FOREST] = {bit = 3, cs = {add = nil, msn = nil, warp = 905}, dest = {-116.093, -8.005, -520.041, 0, 82}}, [ZN.PASHHOW_MARSHLANDS] = {bit = 4, cs = {add = nil, msn = nil, warp = 905}, dest = { 415.945, 24.659, 25.611, 101, 90}}, [ZN.MERIPHATAUD_MOUNTAINS] = {bit = 5, cs = {add = nil, msn = nil, warp = 905}, dest = { 595.000, -32.000, 279.300, 93, 97}}, [ZN.EAST_RONFAURE] = {bit = 6, cs = {add = nil, msn = nil, warp = 904}, dest = { 322.057, -60.059, 503.712, 64, 81}}, [ZN.NORTH_GUSTABERG] = {bit = 7, cs = {add = nil, msn = nil, warp = 903}, dest = { 469.697, -0.050, 478.949, 0, 88}}, [ZN.WEST_SARUTABARUTA] = {bit = 8, cs = {add = nil, msn = nil, warp = 904}, dest = { 2.628, -0.150, -166.562, 32, 95}}, [ZN.BATALLIA_DOWNS_S] = {bit = 0, cs = {add = 100, msn = 701, warp = 101}, dest = { -51.486, 0.371, 436.972, 128, 105}}, [ZN.ROLANBERRY_FIELDS_S] = {bit = 1, cs = {add = 101, msn = 701, warp = 102}, dest = {-196.500, 7.999, 361.192, 225, 110}}, [ZN.SAUROMUGUE_CHAMPAIGN_S] = {bit = 2, cs = {add = 101, msn = 701, warp = 102}, dest = { 366.858, 8.545, -228.861, 95, 120}}, [ZN.JUGNER_FOREST_S] = {bit = 3, cs = {add = 101, msn = nil, warp = 102}, dest = {-116.093, -8.005, -520.041, 0, 104}}, [ZN.PASHHOW_MARSHLANDS_S] = {bit = 4, cs = {add = 100, msn = nil, warp = 101}, dest = { 415.945, 24.659, 25.611, 101, 109}}, [ZN.MERIPHATAUD_MOUNTAINS_S] = {bit = 5, cs = {add = 102, msn = nil, warp = 103}, dest = { 595.000, -32.000, 279.300, 93, 119}}, [ZN.EAST_RONFAURE_S] = {bit = 6, cs = {add = 100, msn = nil, warp = 101}, dest = { 322.057, -60.059, 503.712, 64, 101}}, [ZN.NORTH_GUSTABERG_S] = {bit = 7, cs = {add = 100, msn = nil, warp = 101}, dest = { 469.697, -0.050, 478.949, 0, 106}}, [ZN.WEST_SARUTABARUTA_S] = {bit = 8, cs = {add = 100, msn = nil, warp = 101}, dest = { 2.628, -0.150, -166.562, 32, 115}}, } local function meetsMission2Reqs(player) if not player:getCurrentMission(WOTG) == dsp.mission.id.wotg.BACK_TO_THE_BEGINNING then return false end local Q = dsp.quest.id.crystalWar local Q1 = player:getQuestStatus(CRYSTAL_WAR, Q.CLAWS_OF_THE_GRIFFON) == QUEST_COMPLETED local Q2 = player:getQuestStatus(CRYSTAL_WAR, Q.THE_TIGRESS_STRIKES) == QUEST_COMPLETED local Q3 = player:getQuestStatus(CRYSTAL_WAR, Q.FIRES_OF_DISCONTENT) == QUEST_COMPLETED return Q1 or Q2 or Q3 end dsp.maws.onTrigger = function(player, npc) local ID = zones[player:getZoneID()] if not ENABLE_WOTG == 1 then player:messageSpecial(ID.text.NOTHING_HAPPENS) return end local maw = pastMaws[player:getZoneID()] local hasMaw = player:hasTeleport(MAW, maw.bit) local event = nil if maw.cs.msn and meetsMission2Reqs(player) then event = maw.cs.msn elseif hasMaw then event = maw.cs.warp else local hasFeather = player:hasKeyItem(dsp.ki.PURE_WHITE_FEATHER) if maw.cs.new and not hasFeather then event = maw.cs.new elseif maw.cs.add then event = maw.cs.add end end if event then player:startEvent(event) else player:messageSpecial(ID.text.NOTHING_HAPPENS) end end dsp.maws.onEventFinish = function(player, csid, option) local maw = pastMaws[player:getZoneID()] local goToMaw = function() player:setPos(unpack(maw.dest)) end local addMaw = function() if not player:hasTeleport(MAW, maw.bit) then player:addTeleport(MAW, maw.bit) end goToMaw() end if csid == maw.cs.warp and option == 1 then goToMaw() -- Known to have maw, no need to check elseif maw.cs.add and csid == maw.cs.add and option == 1 then addMaw() elseif maw.cs.msn and csid == maw.cs.msn then player:completeMission(WOTG, dsp.mission.id.wotg.BACK_TO_THE_BEGINNING) player:addMission(WOTG, dsp.mission.id.wotg.CAIT_SITH) player:addTitle(dsp.title.CAIT_SITHS_ASSISTANT) addMaw() -- May not have yet, check elseif maw.cs.new and csid == maw.cs.new then local ID = zones[player:getZoneID()] player:completeMission(WOTG,dsp.mission.id.wotg.CAVERNOUS_MAWS) player:addMission(WOTG,dsp.mission.id.wotg.BACK_TO_THE_BEGINNING) player:addKeyItem(dsp.ki.PURE_WHITE_FEATHER) player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.PURE_WHITE_FEATHER) local x = math.random(1, 3) if x == 1 then maw = pastMaws[ZN.BATALLIA_DOWNS] elseif x == 2 then maw = pastMaws[ZN.ROLANBERRY_FIELDS] else maw = pastMaws[ZN.SAUROMUGUE_CHAMPAIGN] end addMaw() end end
gpl-3.0
da03/OpenNMT
test/onmt/OptimTest.lua
8
5803
require('onmt.init') local tester = ... local optimTest = torch.TestSuite() local function getOptim(args) local cmd = onmt.utils.ExtendedCmdLine.new() onmt.train.Optim.declareOpts(cmd) local opt = cmd:parse('') for k, v in pairs(args) do opt[k] = v end return onmt.train.Optim.new(opt) end function optimTest.decay_default_noDecay() local args = { decay = 'default', learning_rate = 1, } local optim = getOptim(args) optim.valPerf[1] = 10.0 tester:eq(optim:updateLearningRate(5.0, 2), args.learning_rate) end function optimTest.decay_default_decayByEpoch() local args = { decay = 'default', learning_rate = 1, start_decay_at = 2 } local optim = getOptim(args) optim.valPerf[1] = 10.0 tester:eq(optim:updateLearningRate(5.0, 2), args.learning_rate * optim.args.learning_rate_decay) end function optimTest.decay_default_decayByScore() local args = { decay = 'default', learning_rate = 1 } local optim = getOptim(args) optim.valPerf[1] = 10.0 tester:eq(optim:updateLearningRate(11.0, 2), args.learning_rate * optim.args.learning_rate_decay) end function optimTest.decay_default_decayByScoreAgain() local args = { decay = 'default', learning_rate = 1 } local optim = getOptim(args) optim.valPerf[1] = 10.0 tester:eq(optim:updateLearningRate(11.0, 2), args.learning_rate * optim.args.learning_rate_decay) tester:eq(optim:updateLearningRate(9.0, 3), args.learning_rate * optim.args.learning_rate_decay * optim.args.learning_rate_decay) end function optimTest.decay_default_decayByScoreDelta() local args = { decay = 'default', learning_rate = 1, start_decay_score_delta = 0.5 } local optim = getOptim(args) optim.valPerf[1] = 10.0 tester:eq(optim:updateLearningRate(10.75, 2), args.learning_rate * optim.args.learning_rate_decay) end function optimTest.decay_scoreOnly_noDecay() local args = { decay = 'score_only', learning_rate = 1, start_decay_at = 2 } local optim = getOptim(args) optim.valPerf[1] = 10.0 tester:eq(optim:updateLearningRate(5.0, 2), args.learning_rate) end function optimTest.decay_scoreOnly_noDecayDeltaLowerIsBetter() local args = { decay = 'score_only', learning_rate = 1, start_decay_score_delta = 0.5 } local optim = getOptim(args) optim.valPerf[1] = 10.0 tester:eq(optim:updateLearningRate(9, 2), args.learning_rate) end function optimTest.decay_scoreOnly_noDecayDeltaHigherIsBetter() local args = { decay = 'score_only', learning_rate = 1, start_decay_score_delta = 0.5 } local optim = getOptim(args) optim.valPerf[1] = 10.0 tester:eq(optim:updateLearningRate(11, 2, onmt.evaluators.BLEUEvaluator.new()), args.learning_rate) end function optimTest.decay_scoreOnly_decayDeltaLowerIsBetter() local args = { decay = 'score_only', learning_rate = 1, start_decay_score_delta = 0.5 } local optim = getOptim(args) optim.valPerf[1] = 10.0 tester:eq(optim:updateLearningRate(9.75, 2), args.learning_rate * optim.args.learning_rate_decay) end function optimTest.decay_scoreOnly_decayDeltaHigherIsBetter() local args = { decay = 'score_only', learning_rate = 1, start_decay_score_delta = 1 } local optim = getOptim(args) optim.valPerf[1] = 10.0 tester:eq(optim:updateLearningRate(10.5, 2, onmt.evaluators.BLEUEvaluator.new()), args.learning_rate * optim.args.learning_rate_decay) end function optimTest.decay_epochOnly_noDecay() local args = { decay = 'epoch_only', learning_rate = 1, start_decay_at = 4 } local optim = getOptim(args) optim:updateLearningRate(10.0, 1) tester:eq(optim:updateLearningRate(11.0, 2), args.learning_rate) tester:eq(optim:updateLearningRate(9.0, 3), args.learning_rate) end function optimTest.decay_epochOnly_decay() local args = { decay = 'epoch_only', learning_rate = 1, start_decay_at = 2 } local optim = getOptim(args) optim.valPerf[1] = 10.0 tester:eq(optim:updateLearningRate(9.0, 2), args.learning_rate * optim.args.learning_rate_decay) end -- Test custom optimization methods against torch.optim. local ret, optim = pcall(require, 'optim') if ret then local function validateOptimMethod(refFunc, customFunc, learningRate) local params = torch.FloatTensor(30):uniform() local gradParams = torch.FloatTensor(30):uniform() local config = {} if learningRate then config.learningRate = learningRate end local opfunc = function(_) return 5.0, gradParams:clone() end local refState = {} local refParams = params:clone() refParams = refFunc(opfunc, refParams, config, refState) local customState = {} local customParams = params:clone() local customGradParams = gradParams:clone() if learningRate then customFunc(customGradParams, learningRate, customState) else customFunc(customGradParams, customState) end customParams:add(customGradParams) tester:eq(customParams, refParams, 1e-6) -- Second round with initialized states. refParams = refFunc(opfunc, refParams, config, refState) customGradParams:copy(gradParams) if learningRate then customFunc(customGradParams, learningRate, customState) else customFunc(customGradParams, customState) end customParams:add(customGradParams) tester:eq(customParams, refParams, 1e-6) end function optimTest.adam() validateOptimMethod(optim.adam, onmt.train.Optim.adamStep, 0.1) end function optimTest.adagrad() validateOptimMethod(optim.adagrad, onmt.train.Optim.adagradStep, 0.1) end function optimTest.adadelta() validateOptimMethod(optim.adadelta, onmt.train.Optim.adadeltaStep) end end return optimTest
mit
lichtl/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Pelsey-Holsey.lua
14
1065
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Pelsey-Holsey -- Type: Standard NPC -- @zone 94 -- @pos 119.755 -4.5 209.754 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01a3); 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
ForsakenX/6dof
level/d1rdl.lua
1
5184
-- vim:set sw=4 ts=4: -- -- This Lua script reads vertex/face from a Descent 1 .rdl level file. -- -- Copyright (C) 2010 Pim Goossens -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License along -- with this program; if not, see <http://www.gnu.org/licenses/>, or write -- to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -- Boston, MA 02110-1301 USA. local function DEBUG(level, str) DEBUGX(DBG_LEVEL, level, str) end local verts = {} local faces = {} -- Convert an 8-bit integer (0 <= n <= 255) to a list of bits local function bits(n) b = {} for i = 1, 8 do table.insert(b, test(n, i)) end return b end -- Compute a face normal given three of its vertices local function normal(v1,v2,v3) local n = (v2-v1):cross(v3-v2):norm() return n end local function face(v) return { { index = v[1], texcoords = {0,0}, material = nil }; { index = v[2], texcoords = {0,1}, material = nil }; { index = v[3], texcoords = {1,0}, material = nil }; { index = v[4], texcoords = {1,1}, material = nil }; normal = normal(verts[v[1]], verts[v[2]], verts[v[3]]); texture = nil; } end local f = binfile(io.open(config.lvlfile, 'rb')) local hdrID, ver, offset = f:binread('iii????????') if hdrID ~= 0x504c564c or ver ~= 1 then error('not an RDL file') end offset = offset + 1 DEBUG(2, 'Offset to mine geometry data is '..offset) if offset < 20 then error('invalid mine geometry data offset') end -- Skip to mine geometry data if offset > 20 then f:read(offset-20) end local nverts, ncubes = f:binread('hh') DEBUG(2, ('Header says %d verts, %d cubes'):format(nverts, ncubes)) -- Read vertices for i = 1, nverts do -- Coordinates in D1/D2's "fix" (fixed-point) format local vx, vy, vz = f:binread('iii') -- Convert to floating-point vector local v = vec(vx/0x10000, vy/0x10000, vz/0x10000) DEBUG(3, 'Adding vertex '..tostring(v)) table.insert(verts, v) end -- Now for the hardest part... read the cubes section which will -- provide us with the face (polygon) data for i = 1, ncubes do DEBUG(3, '--- Start of next cube, file position = '..f:seek()) local sidemask = bits(f:binread('B')) local n = 0 for i, s in ipairs(sidemask) do if i <= 6 and s then n = n + 2 end end -- Check the `attached cube ID' data for negative cube IDs DEBUG(3, ('Reading %d bytes of attached cube ID data'):format(n)) local neighbors = {f:binread(('h'):rep(n/2))} for i, n in ipairs(neighbors) do if n < 0 then sidemask[i] = false end end -- Now read the face data, processing only those that are not -- connected to other cubes local doface = true local vLFT, vLFB, vRFB, vRFT, vLBT, vLBB, vRBB, vRBT = f:binread('HHHHHHHH') -- Check vertex indices for validity for i, v in ipairs({vLFT, vLFB, vRFB, vRFT, vLBT, vLBB, vRBB, vRBT}) do if v > nverts then error('invalid vertex index '..v) end end DEBUG(3, ('Cube vertex indices: %d, %d, %d, %d, %d, %d, %d, %d'):format(vLFT, vLFB, vRFB, vRFT, vLBT, vLBB, vRBB, vRBT)) if not sidemask[3] then -- Left and right are swapped it seems... oh well. table.insert(faces, face({vLBT+1, vLFT+1, vLFB+1, vLBB+1})) end if not sidemask[2] then table.insert(faces, face({vLBT+1, vRBT+1, vRFT+1, vLFT+1})) end if not sidemask[1] then table.insert(faces, face({vRFT+1, vRBT+1, vRBB+1, vRFB+1})) end if not sidemask[4] then table.insert(faces, face({vRBB+1, vLBB+1, vLFB+1, vRFB+1})) end if not sidemask[5] then table.insert(faces, face({vRBT+1, vLBT+1, vLBB+1, vRBB+1})) end if not sidemask[6] then table.insert(faces, face({vLFT+1, vRFT+1, vRFB+1, vLFB+1})) end if sidemask[7] then -- Discard special data DEBUG(3, 'Discarding 4 bytes of special data') f:read(4) end -- Discard cube light value DEBUG(3, 'Discarding 2 bytes of cube light data') f:read(2) local wallmask = bits(f:binread('B')) for i = 1, 6 do if wallmask[i] then -- Wall ID, check for special value 255 DEBUG(3, 'Reading 1 byte of wall ID data') local wallnum = f:binread('B') if wallnum == 255 then wallmask[i] = false end end end -- For each closed side of the cube, and those with a wall... for i = 1, 6 do if wallmask[i] or not sidemask[i] then -- Primary texture data local primtex = f:binread('h') DEBUG(3, 'Discarding 2 bytes of primary texture data') if primtex < 0 then -- Discard secondary texture info DEBUG(3, 'Discarding 2 bytes of secondary texture data') f:read(2) end -- Discard UVL info DEBUG(3, 'Discarding 24 bytes of UVL data') f:read(24) end end end f:close() DEBUG(1, ("%s: %d vertices, %d faces"):format(config.lvlfile, #verts, #faces)) return { vertices = verts, faces = faces }
gpl-2.0
padrinoo/padrino15
plugins/bugzilla.lua
611
3983
do local BASE_URL = "https://bugzilla.mozilla.org/rest/" local function bugzilla_login() local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password print("accessing " .. url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_check(id) -- data = bugzilla_login() local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey -- print(url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_listopened(email) local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey local res,code = https.request( url ) print(res) local data = json:decode(res) return data end local function run(msg, matches) local response = "" if matches[1] == "status" then local data = bugzilla_check(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator response = response .. "\n Last update: "..data.bugs[1].last_change_time response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] print(response) end elseif matches[1] == "list" then local data = bugzilla_listopened(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else -- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator -- response = response .. "\n Last update: "..data.bugs[1].last_change_time -- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution -- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard -- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] local total = table.map_length(data.bugs) print("total bugs: " .. total) local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2] if total > 0 then response = response .. ": " for tableKey, bug in pairs(data.bugs) do response = response .. "\n #" .. bug.id response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution response = response .. "\n Whiteboard: " .. bug.whiteboard response = response .. "\n Summary: " .. bug.summary end end end end return response end -- (table) -- [bugs] = (table) -- [1] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 927704 -- [whiteboard] = (string) [approved][full processed] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/ -- [2] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 1049337 -- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/ -- total bugs: 2 return { description = "Lookup bugzilla status update", usage = "/bot bugzilla [bug number]", patterns = { "^/bugzilla (status) (.*)$", "^/bugzilla (list) (.*)$" }, run = run } end
gpl-2.0
lichtl/darkstar
scripts/globals/items/serving_of_karni_yarik_+1.lua
18
1379
----------------------------------------- -- ID: 5589 -- Item: serving_of_karni_yarik_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Agility 3 -- Vitality -1 -- Attack % 20 -- Attack Cap 65 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5589); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 3); target:addMod(MOD_VIT, -1); target:addMod(MOD_FOOD_ATTP, 20); target:addMod(MOD_FOOD_ATT_CAP, 65); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 3); target:delMod(MOD_VIT, -1); target:delMod(MOD_FOOD_ATTP, 20); target:delMod(MOD_FOOD_ATT_CAP, 65); end;
gpl-3.0
raingloom/yaoui
examples/anime/yaoui/dialogs/winapi/struct.lua
4
7372
--ffi/struct: struct ctype wrapper --Written by Cosmin Apreutesei. Public Domain. local yui_path = (...):match('(.-)[^%.]+$') setfenv(1, require(yui_path .. 'namespace')) require(yui_path .. 'util') local Struct = {} local Struct_meta = {__index = Struct} --struct virtual field setter and getter ------------------------------------- local setbit = setbit --cache function Struct:set(cdata, field, value) --hot code if type(field) ~= 'string' then error(string.format('struct "%s" has no field of type "%s"', self.ctype, type(field)), 5) end local def = self.fields[field] if def then local name, mask, setter = unpack(def, 1, 3) if mask then cdata[self.mask] = setbit(cdata[self.mask] or 0, mask, value ~= nil) end if name then if setter then value = setter(value, cdata) end if type(value) == 'cdata' then pin(value, cdata) end cdata[name] = value else setter(value, cdata) --custom setter end return end --masked bitfield support. def = self.bitfields and self.bitfields[field] if def then --support the syntax `struct.field = {BITNAME = true|false, ...}` for bitname, enabled in pairs(value) do cdata[field..'_'..bitname] = enabled end return else --support the syntax `struct.field_BITNAME = true|false`. local fieldname, bitname = field:match'^([^_]+)_(.*)' if fieldname then def = self.bitfields[fieldname] if def then local datafield, maskfield, prefix = unpack(def, 1, 3) local mask = _M[prefix..'_'..bitname] if mask then cdata[maskfield] = setbit(cdata[maskfield] or 0, mask, value ~= nil) cdata[datafield] = setbit(cdata[datafield] or 0, mask, value) return end end end end error(string.format('struct "%s" has no field "%s"', self.ctype, field), 5) end local getbit = getbit function Struct:get(cdata, field, value) --hot code if type(field) ~= 'string' then error(string.format('struct "%s" has no field of type "%s"', self.ctype, type(field)), 5) end local def = self.fields[field] if def then local name, mask, _, getter = unpack(def, 1, 4) if not mask or getbit(cdata[self.mask], mask) then if not name then if getter then return getter(cdata) else return true end elseif not getter then return cdata[name] else return getter(cdata[name], cdata) end else return nil end end --masked bitfield support local fieldname, bitname = field:match'^([^_]+)_(.*)' if fieldname then def = self.bitfields[fieldname] if def then local datafield, maskfield, prefix = unpack(def, 1, 3) local mask = _M[prefix..'_'..bitname] if mask then if getbit(cdata[maskfield] or 0, mask) then return getbit(cdata[datafield] or 0, mask) else return nil --masked off end end end end error(string.format('struct "%s" has no field "%s"', self.ctype, field), 5) end --struct instance constructor ------------------------------------------------ --set all fields with a table. function Struct:setall(cdata, t) if not t then return end for field, value in pairs(t) do cdata[field] = value end end --set all fields which have default values to their default values. function Struct:setdefaults(cdata) if not self.defaults then return end for field, value in pairs(self.defaults) do cdata[field] = value end end function Struct:init(cdata) end --stub --create a struct with a clear mask and default values. --cdata are passed through. function Struct:new(t) if type(t) == 'cdata' then return t end local cdata = self.ctype_cons() if self.size then cdata[self.size] = ffi.sizeof(cdata) end self:setdefaults(cdata) self:setall(cdata, t) --TODO: provide a way to make in/out buffer allocations declarative --instead of manually via init constructor (see winapi.filedialogs). self.init(cdata) return cdata end --clear all mask bits (prepare the struct for setting data). function Struct:clearmask(cdata) if self.mask then cdata[self.mask] = 0 end end --create or use existing struct and set all mask bits (prepare for receiving data). function Struct:setmask(cdata) if not cdata then cdata = self.ctype_cons() if self.size then cdata[self.size] = ffi.sizeof(cdata) end end if self.mask then cdata[self.mask] = self.full_mask end return cdata end Struct_meta.__call = Struct.new --collect the values of all virtual fields in a table. function Struct:collect(cdata) local t = {} for field in pairs(self.fields) do t[field] = cdata[field] end return t end --compute the struct's full mask (i.e. with all bitmasks set). function Struct:compute_mask() local mask = 0 for field, def in pairs(self.fields) do local bitmask = def[2] if bitmask then mask = bit.bor(mask, bitmask) end end return mask end --struct definition constructor ---------------------------------------------- local valid_struct_keys = index{'ctype', 'size', 'mask', 'fields', 'defaults', 'bitfields', 'init'} local function checkdefs(s) --typecheck a struct definition assert(s.ctype ~= nil, 'ctype missing') for k,v in pairs(s) do --check for typos in struct definition assert(valid_struct_keys[k], 'invalid struct key "%s"', k) end if s.fields then --check for accidentaly hidden fields for vname,def in pairs(s.fields) do local sname, mask, setter, getter = unpack(def, 1, 4) assert(vname ~= sname, 'virtual field "%s" not visible', vname) end end end function struct(s) checkdefs(s) setmetatable(s, Struct_meta) s.ctype_cons = ffi.typeof(s.ctype) if s.mask then s.full_mask = s:compute_mask() end ffi.metatype(s.ctype_cons, { --setup ctype for virtual fields __index = function(cdata,k) return s:get(cdata,k) end, __newindex = function(cdata,k,v) s:set(cdata,k,v) end, }) return s end --struct field definitions constructors -------------------------------------- --field definitions constructor for defining non-masked struct fields. --t is a table of form {virtfield1, cfield1, setter, getter, virtfield2, ...}. function sfields(t) local dt = {} for i=1,#t,4 do assert(type(t[i]) == 'string', 'invalid sfields spec') assert(type(t[i+1]) == 'string', 'invalid sfields spec') dt[t[i]] = { t[i+1] ~= '' and t[i+1] or nil, nil, (type(t[i+2]) ~= 'function' or t[i+2] ~= pass) and t[i+2] or nil, (type(t[i+3]) ~= 'function' or t[i+3] ~= pass) and t[i+3] or nil, } end return dt end --field definitions constructor for defining masked struct fields. --t is a table of form {virtfield1, cfield1, mask, setter, getter, virtfield2, ...}. function mfields(t) local dt = {} for i=1,#t,5 do assert(type(t[i]) == 'string', 'invalid mfields spec') assert(type(t[i+1]) == 'string', 'invalid mfields spec') assert(type(t[i+2]) == 'number', 'invalid mfields spec') dt[t[i]] = { t[i+1] ~= '' and t[i+1] or nil, t[i+2] ~= 0 and t[i+2] or nil, t[i+3] ~= pass and t[i+3] or nil, t[i+4] ~= pass and t[i+4] or nil, } end return dt end --struct field setters and getters ------------------------------------------- --create a struct setter for setting a fixed-size WCHAR[n] field with a Lua string. function wc_set(field) return function(s, cdata) wcs_to(s, cdata[field]) end end --create a struct getter for getting a fixed-size WCHAR[n] field as a Lua string. function wc_get(field) return function(cdata) return mbs(ffi.cast('WCHAR*', cdata[field])) end end
mit
RunAwayDSP/darkstar
scripts/zones/Mount_Zhayolm/npcs/Waudeen.lua
9
2359
----------------------------------- -- Area: Mount_Zhayolm -- NPC: Waudeen -- Type: Assault -- !pos 673.882 -23.995 367.604 61 ----------------------------------- local ID = require("scripts/zones/Mount_Zhayolm/IDs") require("scripts/globals/keyitems") require("scripts/globals/missions") require("scripts/globals/quests") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) local toauMission = player:getCurrentMission(TOAU) local beginnings = player:getQuestStatus(AHT_URHGAN, dsp.quest.id.ahtUrhgan.BEGINNINGS) -- IMMORTAL SENTRIES if toauMission == dsp.mission.id.toau.IMMORTAL_SENTRIES then if player:hasKeyItem(dsp.ki.SUPPLIES_PACKAGE) then player:startEvent(4) elseif player:getCharVar("AhtUrganStatus") == 1 then player:startEvent(5) end -- BEGINNINGS elseif beginnings == QUEST_ACCEPTED then if not player:hasKeyItem(dsp.ki.BRAND_OF_THE_FLAMESERPENT) then player:startEvent(10) -- brands you else player:startEvent(11) -- the way is neither smooth nor easy end -- ASSAULT elseif toauMission >= dsp.mission.id.toau.PRESIDENT_SALAHEEM then local IPpoint = player:getCurrency("imperial_standing") if player:hasKeyItem(dsp.ki.LEBROS_ASSAULT_ORDERS) and not player:hasKeyItem(dsp.ki.ASSAULT_ARMBAND) then player:startEvent(209, 50, IPpoint) else player:startEvent(6) -- player:delKeyItem(dsp.ki.ASSAULT_ARMBAND) end -- DEFAULT DIALOG else player:startEvent(3) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) -- IMMORTAL SENTRIES if csid == 4 and option == 1 then player:delKeyItem(dsp.ki.SUPPLIES_PACKAGE) player:setCharVar("AhtUrganStatus", 1) -- BEGINNINGS elseif csid == 10 then player:addKeyItem(dsp.ki.BRAND_OF_THE_FLAMESERPENT) player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.BRAND_OF_THE_FLAMESERPENT) -- ASSAULT elseif csid == 209 and option == 1 then player:delCurrency("imperial_standing", 50) player:addKeyItem(dsp.ki.ASSAULT_ARMBAND) player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.ASSAULT_ARMBAND) end end
gpl-3.0
PUMpITapp/getsmart
src/lora.lua
1
10998
--- Table containing metrics for font return { file="lora.PNG", height=148, description={ family="Lora", style="Bold", size=65 }, metrics={ ascender=117, descender=-32, height=148 }, texture={ file="lora.PNG", width=1024, height=1024 }, chars={ {char=" ",width=31,x=1,y=98,w=0,h=0,ox=0,oy=0}, {char="!",width=30,x=2,y=15,w=19,h=85,ox=6,oy=83}, {char='"',width=38,x=22,y=15,w=29,h=26,ox=5,oy=83}, {char="#",width=101,x=52,y=15,w=94,h=85,ox=4,oy=83}, {char="$",width=68,x=147,y=1,w=58,h=114,ox=6,oy=97}, {char="%",width=105,x=206,y=15,w=96,h=85,ox=5,oy=83}, {char="&",width=78,x=303,y=15,w=76,h=85,ox=3,oy=83}, {char="'",width=22,x=380,y=15,w=13,h=26,ox=5,oy=83}, {char="(",width=34,x=394,y=10,w=31,h=119,ox=3,oy=88}, {char=")",width=34,x=426,y=10,w=31,h=119,ox=1,oy=88}, {char="*",width=62,x=458,y=15,w=52,h=50,ox=5,oy=83}, {char="+",width=61,x=511,y=35,w=51,h=54,ox=5,oy=63}, {char=",",width=29,x=563,y=83,w=19,h=37,ox=5,oy=15}, {char="-",width=55,x=583,y=55,w=43,h=13,ox=6,oy=43}, {char=".",width=27,x=627,y=82,w=17,h=18,ox=5,oy=16}, {char="/",width=81,x=645,y=10,w=77,h=119,ox=2,oy=88}, {char="0",width=74,x=723,y=15,w=64,h=85,ox=5,oy=83}, {char="1",width=47,x=788,y=15,w=43,h=83,ox=1,oy=83}, {char="2",width=62,x=832,y=15,w=52,h=83,ox=4,oy=83}, {char="3",width=65,x=885,y=15,w=57,h=85,ox=4,oy=83}, {char="4",width=64,x=943,y=15,w=58,h=83,ox=2,oy=83}, {char="5",width=63,x=1,y=130,w=54,h=91,ox=5,oy=89}, {char="6",width=67,x=56,y=136,w=57,h=85,ox=5,oy=83}, {char="7",width=54,x=114,y=138,w=50,h=83,ox=2,oy=81}, {char="8",width=66,x=165,y=136,w=55,h=85,ox=7,oy=83}, {char="9",width=67,x=221,y=136,w=57,h=85,ox=5,oy=83}, {char=":",width=29,x=279,y=156,w=17,h=65,ox=6,oy=63}, {char=";",width=31,x=297,y=156,w=19,h=85,ox=6,oy=63}, {char="<",width=64,x=317,y=154,w=52,h=56,ox=4,oy=65}, {char="=",width=67,x=370,y=166,w=52,h=33,ox=7,oy=53}, {char=">",width=64,x=423,y=154,w=52,h=56,ox=7,oy=65}, {char="?",width=58,x=476,y=136,w=49,h=85,ox=4,oy=83}, {char="@",width=92,x=526,y=146,w=81,h=85,ox=6,oy=73}, {char="A",width=77,x=608,y=136,w=78,h=83,ox=0,oy=83}, {char="B",width=77,x=687,y=138,w=69,h=81,ox=5,oy=81}, {char="C",width=80,x=757,y=136,w=75,h=85,ox=4,oy=83}, {char="D",width=88,x=833,y=138,w=80,h=81,ox=5,oy=81}, {char="E",width=72,x=914,y=138,w=63,h=81,ox=5,oy=81}, {char="F",width=66,x=1,y=244,w=59,h=81,ox=5,oy=81}, {char="G",width=88,x=61,y=242,w=82,h=85,ox=4,oy=83}, {char="H",width=94,x=144,y=244,w=84,h=81,ox=5,oy=81}, {char="I",width=45,x=229,y=244,w=35,h=81,ox=5,oy=81}, {char="J",width=52,x=265,y=244,w=50,h=83,ox=0,oy=81}, {char="K",width=83,x=316,y=244,w=78,h=81,ox=5,oy=81}, {char="L",width=70,x=395,y=244,w=63,h=81,ox=5,oy=81}, {char="M",width=113,x=459,y=244,w=103,h=82,ox=5,oy=81}, {char="N",width=90,x=563,y=244,w=81,h=82,ox=5,oy=81}, {char="O",width=89,x=645,y=242,w=82,h=85,ox=4,oy=83}, {char="P",width=74,x=728,y=243,w=67,h=82,ox=5,oy=82}, {char="Q",width=89,x=796,y=242,w=89,h=108,ox=4,oy=83}, {char="R",width=80,x=886,y=243,w=73,h=82,ox=5,oy=82}, {char="S",width=69,x=960,y=242,w=61,h=85,ox=5,oy=83}, {char="T",width=75,x=1,y=361,w=71,h=81,ox=2,oy=81}, {char="U",width=88,x=73,y=361,w=84,h=83,ox=2,oy=81}, {char="V",width=82,x=158,y=361,w=82,h=82,ox=0,oy=81}, {char="W",width=118,x=241,y=361,w=117,h=82,ox=1,oy=81}, {char="X",width=81,x=359,y=361,w=80,h=81,ox=1,oy=81}, {char="Y",width=77,x=440,y=361,w=78,h=81,ox=0,oy=81}, {char="Z",width=70,x=519,y=361,w=60,h=81,ox=5,oy=81}, {char="[",width=45,x=580,y=354,w=38,h=118,ox=7,oy=88}, {char="\\",width=81,x=619,y=354,w=77,h=119,ox=2,oy=88}, {char="]",width=45,x=697,y=354,w=39,h=118,ox=0,oy=88}, {char="^",width=96,x=737,y=359,w=82,h=33,ox=7,oy=83}, {char="_",width=97,x=820,y=448,w=71,h=12,ox=13,oy=-6}, {char="`",width=33,x=892,y=351,w=22,h=25,ox=5,oy=91}, {char="a",width=61,x=915,y=382,w=56,h=62,ox=4,oy=60}, {char="b",width=66,x=1,y=474,w=63,h=90,ox=-1,oy=88}, {char="c",width=60,x=65,y=502,w=56,h=62,ox=3,oy=60}, {char="d",width=69,x=122,y=474,w=63,h=90,ox=4,oy=88}, {char="e",width=62,x=186,y=502,w=56,h=62,ox=4,oy=60}, {char="f",width=43,x=243,y=474,w=47,h=88,ox=3,oy=88}, {char="g",width=65,x=291,y=492,w=65,h=101,ox=3,oy=70}, {char="h",width=72,x=357,y=474,w=68,h=88,ox=2,oy=88}, {char="i",width=38,x=426,y=474,w=32,h=88,ox=4,oy=88}, {char="j",width=34,x=459,y=474,w=39,h=119,ox=-11,oy=88}, {char="k",width=69,x=499,y=474,w=65,h=88,ox=2,oy=88}, {char="l",width=36,x=565,y=474,w=32,h=88,ox=2,oy=88}, {char="m",width=107,x=598,y=502,w=102,h=60,ox=4,oy=60}, {char="n",width=74,x=701,y=502,w=68,h=60,ox=4,oy=60}, {char="o",width=66,x=770,y=502,w=59,h=62,ox=4,oy=60}, {char="p",width=70,x=830,y=502,w=63,h=90,ox=3,oy=60}, {char="q",width=67,x=894,y=502,w=63,h=90,ox=4,oy=60}, {char="r",width=56,x=958,y=502,w=51,h=60,ox=4,oy=60}, {char="s",width=56,x=1,y=622,w=48,h=62,ox=5,oy=60}, {char="t",width=48,x=50,y=609,w=48,h=75,ox=2,oy=73}, {char="u",width=72,x=99,y=623,w=68,h=61,ox=1,oy=59}, {char="v",width=62,x=168,y=624,w=63,h=58,ox=0,oy=58}, {char="w",width=94,x=232,y=624,w=94,h=58,ox=0,oy=58}, {char="x",width=64,x=327,y=624,w=60,h=58,ox=2,oy=58}, {char="y",width=64,x=388,y=624,w=63,h=89,ox=0,oy=58}, {char="z",width=60,x=452,y=624,w=52,h=58,ox=4,oy=58}, {char="{",width=43,x=505,y=594,w=43,h=119,ox=-1,oy=88}, {char="|",width=30,x=549,y=594,w=17,h=119,ox=6,oy=88}, {char="}",width=43,x=567,y=594,w=43,h=119,ox=0,oy=88}, {char="~",width=63,x=611,y=636,w=52,h=23,ox=6,oy=46}, }, kernings={ {from='"',to="&",offset=-2}, {from='"',to=",",offset=-14}, {from='"',to=".",offset=-14}, {from='"',to="/",offset=-12}, {from='"',to="4",offset=-5}, {from='"',to="@",offset=-2}, {from='"',to="A",offset=-8}, {from='"',to="J",offset=-4}, {from='"',to="a",offset=-2}, {from='"',to="b",offset=1}, {from='"',to="c",offset=-3}, {from='"',to="d",offset=-5}, {from='"',to="e",offset=-3}, {from='"',to="g",offset=-3}, {from='"',to="o",offset=-3}, {from='"',to="q",offset=-5}, {from='"',to="s",offset=-1}, {from="&",to='"',offset=-6}, {from="&",to="'",offset=-6}, {from="&",to="A",offset=6}, {from="&",to="J",offset=5}, {from="&",to="M",offset=1}, {from="&",to="T",offset=-4}, {from="&",to="U",offset=-2}, {from="&",to="V",offset=-6}, {from="&",to="W",offset=-5}, {from="&",to="X",offset=2}, {from="&",to="Y",offset=-5}, {from="&",to="Z",offset=2}, {from="&",to="a",offset=1}, {from="&",to="h",offset=3}, {from="&",to="i",offset=1}, {from="&",to="k",offset=3}, {from="&",to="l",offset=3}, {from="&",to="m",offset=1}, {from="&",to="n",offset=1}, {from="&",to="r",offset=1}, {from="&",to="v",offset=-2}, {from="&",to="w",offset=-2}, {from="&",to="x",offset=1}, {from="&",to="y",offset=-2}, {from="&",to="z",offset=1}, {from="'",to="&",offset=-2}, {from="'",to=",",offset=-11}, {from="'",to=".",offset=-11}, {from="'",to="/",offset=-11}, {from="'",to="4",offset=-5}, {from="'",to="@",offset=-2}, {from="'",to="A",offset=-8}, {from="'",to="J",offset=-4}, {from="'",to="a",offset=-2}, {from="'",to="b",offset=1}, {from="'",to="c",offset=-3}, {from="'",to="d",offset=-5}, {from="'",to="e",offset=-3}, {from="'",to="g",offset=-3}, {from="'",to="o",offset=-3}, {from="'",to="q",offset=-5}, {from="'",to="s",offset=-1}, {from="(",to="0",offset=-2}, {from="(",to="3",offset=-1}, {from="(",to="4",offset=-3}, {from="(",to="6",offset=-2}, {from="(",to="8",offset=-2}, {from="(",to="9",offset=-2}, {from="(",to="A",offset=-3}, {from="(",to="C",offset=-3}, {from="(",to="G",offset=-3}, {from="(",to="J",offset=-2}, {from="(",to="O",offset=-3}, {from="(",to="Q",offset=-3}, {from="(",to="S",offset=-1}, {from="(",to="V",offset=1}, {from="(",to="W",offset=1}, {from="(",to="X",offset=1}, {from="(",to="Y",offset=2}, {from="(",to="a",offset=-3}, {from="(",to="b",offset=4}, {from="(",to="c",offset=-4}, {from="(",to="d",offset=-4}, {from="(",to="e",offset=-4}, {from="(",to="f",offset=-2}, {from="(",to="h",offset=1}, {from="(",to="i",offset=-1}, {from="(",to="j",offset=12}, {from="(",to="k",offset=1}, {from="(",to="l",offset=1}, {from="(",to="m",offset=-3}, {from="(",to="n",offset=-3}, {from="(",to="o",offset=-4}, {from="(",to="q",offset=-4}, {from="(",to="r",offset=-3}, {from="(",to="s",offset=-3}, {from="(",to="t",offset=-2}, {from="(",to="u",offset=-3}, {from="(",to="v",offset=-3}, {from="(",to="w",offset=-3}, {from="(",to="x",offset=-2}, {from="(",to="z",offset=-3}, {from="(",to="{",offset=-2}, {from=")",to="]",offset=-4}, {from=")",to="}",offset=-2}, {from="*",to="A",offset=-6}, {from="*",to="B",offset=-1}, {from="*",to="D",offset=-1}, {from="*",to="E",offset=-1}, {from="*",to="F",offset=-1}, {from="*",to="H",offset=-1}, {from="*",to="I",offset=-1}, {from="*",to="J",offset=-5}, {from="*",to="K",offset=-1}, {from="*",to="L",offset=-1}, {from="*",to="M",offset=-1}, {from="*",to="N",offset=-1}, {from="*",to="P",offset=-1}, {from="*",to="R",offset=-1}, {from="*",to="T",offset=3}, {from="*",to="a",offset=-1}, {from="*",to="c",offset=-1}, {from="*",to="d",offset=-2}, {from="*",to="e",offset=-1}, {from="*",to="g",offset=-2}, {from="*",to="o",offset=-1}, {from="*",to="q",offset=-2}, {from="*",to="v",offset=1}, {from="*",to="w",offset=1}, {from="*",to="y",offset=1}, {from="+",to="1",offset=-2}, {from="+",to="2",offset=-2}, {from="+",to="3",offset=-1}, {from="+",to="7",offset=-4}, {from=",",to='"',offset=-14}, {from=",",to="'",offset=-11}, {from=",",to="0",offset=-2}, {from=",",to="7",offset=-3}, {from=",",to="C",offset=-2}, {from=",",to="G",offset=-2}, {from=",",to="O",offset=-2}, {from=",",to="Q",offset=-2}, {from=",",to="T",offset=-6}, {from=",",to="U",offset=-4}, {from=",",to="V",offset=-13}, {from=",",to="W",offset=-9}, {from=",",to="Y",offset=-8}, {from=",",to="j",offset=-1}, {from=",",to="p",offset=-1}, {from=",",to="t",offset=-2}, {from=",",to="u",offset=-1}, {from=",",to="v",offset=-5}, {from=",",to="w",offset=-4}, {from=",",to="y",offset=-5}, {from="-",to="1",offset=-3}, {from="-",to="2",offset=-3}, {from="-",to="3",offset=-2}, {from="-",to="7",offset=-7}, {from="-",to="8",offset=-1}, {from="-",to="A",offset=-5}, {from="-",to="B",offset=-3}, {from="-",to="D",offset=-3}, {from="-",to="E",offset=-3}, {from="-",to="F",offset=-3}, {from="-",to="H",offset=-3}, {from="-",to="I",offset=-3}, {from="-",to="J",offset=-7}, {from="-",to="K",offset=-3}, {from="-",to="L",offset=-3}, {from="-",to="M",offset=-3}, {from="-",to="N",offset=-3}, {from="-",to="P",offset=-3}, {from="-",to="R",offset=-3}, {from="-",to="S",offset=-1}, {from="-",to="T",offset=-7}, {from="-",to="U",offset=-2}, {from="-",to="V",offset=-6}, {from="-",to="W",offset=-5}, } }
gpl-3.0
lichtl/darkstar
scripts/globals/weaponskills/mystic_boon.lua
19
2075
----------------------------------- -- Mystic Boon -- Club weapon skill -- Skill level: N/A -- Converts damage dealt to own MP. Damage varies with TP. Yagrush: Aftermath effect varies with TP. -- Available only after completing the Unlocking a Myth (White Mage) quest. -- Damage is significantly affected by Attack. Verification Needed -- Not aligned with any "elemental gorgets" or elemental belts due to it's absence of Skillchain properties. -- Element: None -- Modifiers: STR:30% ; MND:70% -- 100%TP 200%TP 300%TP -- 2.5 4.0 7.0 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 2; 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 = 2.5; params.ftp200 = 4; params.ftp300 = 7; params.mnd_wsc = 0.7; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); -- Todo: MOD_AFTERMATH instead of Item ID checks in all these.. if ((player:getEquipID(SLOT_MAIN) == 18993) and (player:getMainJob() == JOBS.WHM)) then if (damage > 0) then local params = initAftermathParams() params.subpower.lv1 = 2 params.subpower.lv2 = 2 params.subpower.lv3 = 1 applyAftermathEffect(player, tp, params) end end player:addMP(damage); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
RunAwayDSP/darkstar
scripts/zones/Northern_San_dOria/npcs/Guilerme.lua
11
1569
----------------------------------- -- Area: Northern San d'Oria -- NPC: Guillerme -- Involved in Quest: Rosel the Armorer -- !pos -4.500 0.000 99.000 231 ----------------------------------- local ID = require("scripts/zones/Northern_San_dOria/IDs"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(ID.text.FLYER_REFUSED); end end end; function onTrigger(player,npc) -- "Rosel the Armorer" quest status var RoselTheArmorer = player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.ROSEL_THE_ARMORER); -- "Rosel the Armorer" - turn in reciept to prince if (RoselTheArmorer == QUEST_ACCEPTED and player:hasKeyItem(dsp.ki.RECEIPT_FOR_THE_PRINCE)) then player:startEvent(507); else player:showText(npc,ID.text.GUILERME_DIALOG); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) -- "Rosel the Armorer", give receipt to NPC:Guilerme if (csid == 507) then player:delKeyItem(dsp.ki.RECEIPT_FOR_THE_PRINCE); end; end;
gpl-3.0
lichtl/darkstar
scripts/globals/items/plate_of_tentacle_sushi_+1.lua
18
1750
----------------------------------------- -- ID: 5216 -- Item: plate_of_tentacle_sushi_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- HP 20 -- Dexterity 3 -- Agility 3 -- Mind -1 -- 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
ImpossibleBananaLabs/Factorio-Advanced-Electric
prototypes/technology/poles.lua
1
5039
local wooden_poles_2 = util.table.deepcopy(data.raw.technology["electric-energy-distribution-1"]) wooden_poles_2.name = "small-electric-pole-2" wooden_poles_2.effects = {{}} wooden_poles_2.effects[1].type = "unlock-recipe" wooden_poles_2.effects[1].recipe = "small-electric-pole-2" wooden_poles_2.prerequisites[1] = "electronics" wooden_poles_2.unit.count = 75 wooden_poles_2.unit.ingredients = {{}} wooden_poles_2.unit.ingredients[1] = {"automation-science-pack", 1} wooden_poles_2.unit.time = 30 wooden_poles_2.order = "c-e-b-2" wooden_poles_2.upgrade = true data:extend({wooden_poles_2}) local metal_poles_2 = util.table.deepcopy(data.raw.technology["electric-energy-distribution-1"]) metal_poles_2.name = "electric-pole-2" metal_poles_2.effects[1].type = "unlock-recipe" metal_poles_2.effects[1].recipe = "medium-electric-pole-2" metal_poles_2.effects[2].type = "unlock-recipe" metal_poles_2.effects[2].recipe = "big-electric-pole-2" metal_poles_2.prerequisites[1] = "electric-energy-distribution-1" metal_poles_2.prerequisites[2] = "small-electric-pole-2" metal_poles_2.unit.count = 75 metal_poles_2.unit.ingredients[1] = {"automation-science-pack", 1} metal_poles_2.unit.ingredients[2] = {"logistic-science-pack", 1} metal_poles_2.unit.time = 30 metal_poles_2.order = "c-e-b-3" metal_poles_2.upgrade = true data:extend({metal_poles_2}) local metal_poles_3 = util.table.deepcopy(data.raw.technology["electric-energy-distribution-1"]) metal_poles_3.name = "electric-pole-3" metal_poles_3.effects[1].type = "unlock-recipe" metal_poles_3.effects[1].recipe = "medium-electric-pole-3" metal_poles_3.effects[2].type = "unlock-recipe" metal_poles_3.effects[2].recipe = "big-electric-pole-3" metal_poles_3.prerequisites[1] = "electric-pole-2" metal_poles_3.unit.count = 100 metal_poles_3.unit.ingredients[1] = {"automation-science-pack", 1} metal_poles_3.unit.ingredients[2] = {"logistic-science-pack", 1} metal_poles_3.unit.ingredients[3] = {"chemical-science-pack", 1} metal_poles_3.unit.time = 30 metal_poles_3.order = "c-e-b-4" metal_poles_3.upgrade = true data:extend({metal_poles_3}) local metal_poles_4 = util.table.deepcopy(data.raw.technology["electric-energy-distribution-1"]) metal_poles_4.name = "electric-pole-4" metal_poles_4.effects[1].type = "unlock-recipe" metal_poles_4.effects[1].recipe = "medium-electric-pole-4" metal_poles_4.effects[2].type = "unlock-recipe" metal_poles_4.effects[2].recipe = "big-electric-pole-4" metal_poles_4.prerequisites[1] = "electric-pole-3" metal_poles_4.unit.count = 150 metal_poles_4.unit.ingredients[1] = {"automation-science-pack", 1} metal_poles_4.unit.ingredients[2] = {"logistic-science-pack", 1} metal_poles_4.unit.ingredients[3] = {"chemical-science-pack", 1} metal_poles_4.unit.ingredients[4] = {"production-science-pack", 1} metal_poles_4.unit.time = 30 metal_poles_4.order = "c-e-b-5" metal_poles_4.upgrade = true data:extend({metal_poles_4}) --substations-- local substations_2 = util.table.deepcopy(data.raw.technology["electric-energy-distribution-2"]) substations_2.name = "electric-substation-2" substations_2.effects[1].type = "unlock-recipe" substations_2.effects[1].recipe = "substation-2" substations_2.prerequisites[1] = "electric-energy-distribution-2" substations_2.prerequisites[2] = "advanced-electronics" substations_2.unit.count = 150 substations_2.unit.ingredients[1] = {"automation-science-pack", 1} substations_2.unit.ingredients[2] = {"logistic-science-pack", 1} substations_2.unit.ingredients[3] = {"chemical-science-pack", 1} substations_2.unit.time = 45 substations_2.order = "c-e-c-2" substations_2.upgrade = true data:extend({substations_2}) local substations_3 = util.table.deepcopy(data.raw.technology["electric-energy-distribution-2"]) substations_3.name = "electric-substation-3" substations_3.effects[1].type = "unlock-recipe" substations_3.effects[1].recipe = "substation-3" substations_3.prerequisites[1] = "electric-substation-2" substations_3.prerequisites[2] = "advanced-electronics-2" substations_3.unit.count = 200 substations_3.unit.ingredients[1] = {"automation-science-pack", 1} substations_3.unit.ingredients[2] = {"logistic-science-pack", 1} substations_3.unit.ingredients[3] = {"chemical-science-pack", 1} substations_3.unit.time = 45 substations_3.order = "c-e-c-3" substations_3.upgrade = true data:extend({substations_3}) local substations_4 = util.table.deepcopy(data.raw.technology["electric-energy-distribution-2"]) substations_4.name = "electric-substation-4" substations_4.effects[1].type = "unlock-recipe" substations_4.effects[1].recipe = "substation-4" substations_4.prerequisites[1] = "electric-substation-3" substations_4.unit.count = 200 substations_4.unit.ingredients[1] = {"automation-science-pack", 1} substations_4.unit.ingredients[2] = {"logistic-science-pack", 1} substations_4.unit.ingredients[3] = {"chemical-science-pack", 1} substations_4.unit.ingredients[4] = {"production-science-pack", 1} substations_4.unit.time = 45 substations_4.order = "c-e-c-4" substations_4.upgrade = true data:extend({substations_4})
gpl-3.0
RunAwayDSP/darkstar
scripts/zones/AlTaieu/npcs/qm3.lua
12
1362
----------------------------------- -- Area: Al'Taieu -- NPC: ??? (Jailer of Prudence Spawn) -- Allows players to spawn the Jailer of Prudence by trading the Third Virtue, Deed of Sensibility, and High-Quality Hpemde Organ to a ???. -- !pos , 706 -1 22 ----------------------------------- local ID = require("scripts/zones/AlTaieu/IDs"); ----------------------------------- function onTrade(player,npc,trade) -- JAILER OF PRUDENCE if ( not GetMobByID(ID.mob.JAILER_OF_PRUDENCE_1):isSpawned() and not GetMobByID(ID.mob.JAILER_OF_PRUDENCE_2):isSpawned() and trade:hasItemQty(1856,1) and -- third_virtue trade:hasItemQty(1870,1) and -- deed_of_sensibility trade:hasItemQty(1871,1) and -- high-quality_hpemde_organ trade:getItemCount() == 3 ) then player:tradeComplete(); SpawnMob(ID.mob.JAILER_OF_PRUDENCE_1):updateClaim(player); -- Spawn Jailer of Prudence 1 SpawnMob(ID.mob.JAILER_OF_PRUDENCE_2); -- Spawn Jailer of Prudence 2 unclaimed end end; function onTrigger(player,npc) end; function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("onFinish CSID: %u",csid); -- printf("onFinish RESULT: %u",option); end;
gpl-3.0
OctoEnigma/shiny-octo-system
lua/includes/modules/list.lua
2
1140
--=============================================================================-- -- -- A really simple module to allow easy additions to lists of items -- --=============================================================================-- local table = table local pairs = pairs module( "list" ) local g_Lists = {} -- -- Get a list -- function Get( list ) g_Lists[ list ] = g_Lists[ list ] or {} return table.Copy( g_Lists[ list ] ) end -- -- Get a list -- function GetForEdit( list ) g_Lists[ list ] = g_Lists[ list ] or {} return g_Lists[ list ] end -- -- Set a key value -- function Set( list, key, value ) local list = GetForEdit( list ) list[ key ] = value end -- -- Add a value to a list -- function Add( list, value ) local list = GetForEdit( list ) table.insert( list, value ) end -- -- Returns true if the list contains the value (as a value - not a key) -- function Contains( list, value ) if ( !g_Lists[ list ] ) then return false end for k, v in pairs( g_Lists[ list ] ) do -- If it contains this entry, bail early if ( v == value ) then return true end end return false end
mit
lichtl/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Porter_Moogle.lua
14
1549
----------------------------------- -- Area: Windurst Waters [S] -- NPC: Porter Moogle -- Type: Storage Moogle -- @zone 94 -- @pos TODO ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Waters_[S]/TextIDs"); require("scripts/globals/porter_moogle_util"); local e = { TALK_EVENT_ID = 523, STORE_EVENT_ID = 524, RETRIEVE_EVENT_ID = 525, ALREADY_STORED_ID = 526, MAGIAN_TRIAL_ID = 527 }; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) porterMoogleTrade(player, trade, e); end ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- No idea what the params are, other than event ID and gil. player:startEvent(e.TALK_EVENT_ID, 0x6FFFFF, 0x01, 0x06DD, 0x27, 0x7C7E, 0x15, player:getGil(), 0x03E8); end ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) porterEventUpdate(player, csid, option, e.RETRIEVE_EVENT_ID, RETRIEVE_DIALOG_ID, ITEM_CANNOT_BE_OBTAINED); end ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) porterEventFinish(player, csid, option, e.TALK_EVENT_ID, ITEM_CANNOT_BE_OBTAINED, ITEM_OBTAINED, NOT_HAVE_ENOUGH_GIL); end
gpl-3.0
RunAwayDSP/darkstar
scripts/globals/items/calico_comet.lua
11
1051
----------------------------------------- -- ID: 5715 -- Item: Calico Comet -- Food Effect: 5 Min, Mithra only ----------------------------------------- -- Dexterity 2 -- Mind -4 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if (target:getRace() ~= dsp.race.MITHRA) then result = dsp.msg.basic.CANNOT_EAT end if (target:getMod(dsp.mod.EAT_RAW_FISH) == 1) then result = 0 end if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,300,5715) end function onEffectGain(target,effect) target:addMod(dsp.mod.DEX, 2) target:addMod(dsp.mod.MND, -4) end function onEffectLose(target, effect) target:delMod(dsp.mod.DEX, 2) target:delMod(dsp.mod.MND, -4) end
gpl-3.0
lichtl/darkstar
scripts/zones/Castle_Oztroja/npcs/_47k.lua
14
1624
----------------------------------- -- Area: Castle Oztroja -- NPC: _47k (Torch Stand) -- Notes: Opens door _472 near password #1 -- @pos -57.412 -1.864 -30.627 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Castle_Oztroja/TextIDs"); require("scripts/globals/settings"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DoorID = npc:getID() - 3; local DoorA = GetNPCByID(DoorID):getAnimation(); local TorchStandA = npc:getAnimation(); local Torch1 = npc:getID(); local Torch2 = npc:getID() + 1; if (DoorA == 9 and TorchStandA == 9) then player:startEvent(0x000a); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) local Torch1 = GetNPCByID(17396168):getID(); local Torch2 = GetNPCByID(Torch1):getID() + 1; local DoorID = GetNPCByID(Torch1):getID() - 3; if (option == 1) then GetNPCByID(Torch1):openDoor(10); -- Torch Lighting GetNPCByID(Torch2):openDoor(10); -- Torch Lighting GetNPCByID(DoorID):openDoor(6); end end; -- printf("CSID: %u",csid); -- printf("RESULT: %u",option);
gpl-3.0
avilleret/openvibe
applications/demos/ssvep-demo/bci-examples/ssvep/scripts/classifier-training-target-separator.lua
5
1266
targets = {} non_targets = {} sent_stimulation = 0 function initialize(box) dofile(box:get_config("${Path_Data}") .. "/plugins/stimulation/lua-stimulator-stim-codes.lua") -- read the parameters of the box s_targets = box:get_setting(2) for t in s_targets:gmatch("%d+") do targets[t + 0] = true end s_non_targets = box:get_setting(3) for t in s_non_targets:gmatch("%d+") do non_targets[t + 0] = true end sent_stimulation = _G[box:get_setting(4)] end function uninitialize(box) end function process(box) finished = false while box:keep_processing() and not finished do time = box:get_current_time() while box:get_stimulation_count(1) > 0 do s_code, s_date, s_duration = box:get_stimulation(1, 1) box:remove_stimulation(1, 1) if s_code >= OVTK_StimulationId_Label_00 and s_code <= OVTK_StimulationId_Label_1F then received_stimulation = s_code - OVTK_StimulationId_Label_00 if targets[received_stimulation] ~= nil then box:send_stimulation(1, sent_stimulation, time) elseif non_targets[received_stimulation] ~= nil then box:send_stimulation(2, sent_stimulation, time) end elseif s_code == OVTK_StimulationId_ExperimentStop then finished = true end end box:sleep() end end
agpl-3.0
lichtl/darkstar
scripts/globals/items/tizona.lua
13
1377
----------------------------------------- -- ID: 19006 -- Item: Tizona -- Additional effect: MP Gain from damage dealt ----------------------------------------- require("scripts/globals/status"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 0; if ( player:getEquipID(SLOT_MAIN) == 18997 ) then -- Tizona 75 chance = 10; elseif ( player:getEquipID(SLOT_MAIN) == 19075 ) then -- Tizona 80 chance = 15; elseif ( player:getEquipID(SLOT_MAIN) == 19095 ) then -- Tizona 85 chance = 20; elseif ( ( player:getEquipID(SLOT_MAIN) == 19627 ) or ( player:getEquipID(SLOT_MAIN) == 19725 ) ) then -- Tizona 90 or Tizona 95 chance = 25; elseif ( ( player:getEquipID(SLOT_MAIN) == 19963 ) or ( player:getEquipID(SLOT_MAIN) == 20651 ) or ( player:getEquipID(SLOT_MAIN) == 20652 ) or ( player:getEquipID(SLOT_MAIN) == 20688 ) or ( player:getEquipID(SLOT_MAIN) == 19834 ) ) then -- Tizona 99 chance = 30; end if (math.random(0,99) >= chance) then return 0,0,0; else local drain = math.floor(damage * (math.random(100,200)/1000)); player:addMP(drain); return SUBEFFECT_MP_DRAIN, MSGBASIC_ADD_EFFECT_MP_DRAIN, drain; end end;
gpl-3.0
lichtl/darkstar
scripts/globals/weaponskills/viper_bite.lua
18
1699
----------------------------------- -- Viper Bite -- Dagger weapon skill -- Skill level: 100 -- Deals double damage and Poisons target. Duration of poison varies with TP. -- Doubles attack and not damage. -- Despite the animation showing two swings, this is a single-hit weapon skill. -- Will stack with Sneak Attack. -- Aligned with the Soil Gorget. -- Aligned with the Soil Belt. -- Element: None -- Modifiers: : -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.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 = 2; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.dex_wsc = 1.0; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); if (damage > 0) then local duration = (tp/1000 * 60) + 30; if (target:hasStatusEffect(EFFECT_POISON) == false) then target:addStatusEffect(EFFECT_POISON, 3, 0, duration); end end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
NiLuJe/koreader
frontend/version.lua
4
3187
--[[-- This module helps with retrieving version information. ]] local Version = {} --- Returns current KOReader git-rev. -- @treturn string full KOReader git-rev such as `v2015.11-982-g704d4238` function Version:getCurrentRevision() if not self.rev then local rev_file = io.open("git-rev", "r") if rev_file then self.rev = rev_file:read("*line") rev_file:close() end -- sanity check in case `git describe` failed if self.rev == "fatal: No names found, cannot describe anything." then self.rev = nil end end return self.rev end --- Returns normalized version of KOReader git-rev input string. -- @string rev full KOReader git-rev such as `v2015.11-982-g704d4238` -- @treturn int version in the form of a 10 digit number such as `2015110982` -- @treturn string short git commit version hash such as `704d4238` function Version:getNormalizedVersion(rev) if not rev then return end local year, month, point, revision = rev:match("v(%d%d%d%d)%.(%d%d)%.?(%d?%d?)-?(%d*)") year = tonumber(year) month = tonumber(month) point = tonumber(point) revision = tonumber(revision) local commit = rev:match("-%d*-g(%x*)[%d_%-]*") -- NOTE: * 10000 to handle at most 9999 commits since last tag ;). return ((year or 0) * 100 + (month or 0)) * 1000000 + (point or 0) * 10000 + (revision or 0), commit end --- Returns current version of KOReader. -- @treturn int version in the form of a 10 digit number such as `2015110982` -- @treturn string short git commit version hash such as `704d4238` -- @see getNormalizedVersion function Version:getNormalizedCurrentVersion() if not self.version or not self.commit then self.version, self.commit = self:getNormalizedVersion(self:getCurrentRevision()) end return self.version, self.commit end --- Returns current version of KOReader, in short form. -- @treturn string version, without the git details (i.e., at most YYYY.MM.P-R) function Version:getShortVersion() if not self.short then local rev = self:getCurrentRevision() if (not rev or rev == "") then return "unknown" end local year, month, point, revision = rev:match("v(%d%d%d%d)%.(%d%d)%.?(%d?%d?)-?(%d*)") self.short = year .. "." .. month if point and point ~= "" then self.short = self.short .. "." .. point end if revision and revision ~= "" then self.short = self.short .. "-" .. revision end end return self.short end --- Returns the release date of the current version of KOReader, YYYYmmdd, in UTC. --- Technically closer to the build date, but close enough where official builds are concerned ;). -- @treturn int date function Version:getBuildDate() if not self.date then local lfs = require("libs/libkoreader-lfs") local mtime = lfs.attributes("git-rev", "modification") if mtime then local ts = os.date("!%Y%m%d", mtime) self.date = tonumber(ts) or 0 else -- No git-rev file? self.date = 0 end end return self.date end return Version
agpl-3.0
CZ-NIC/turris-updater
src/lib/lua/postprocess.lua
1
14733
--[[ Copyright 2016, CZ.NIC z.s.p.o. (http://www.nic.cz/) This file is part of the turris updater. Updater 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. Updater 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 Updater. If not, see <http://www.gnu.org/licenses/>. ]]-- local pairs = pairs local ipairs = ipairs local tostring = tostring local error = error local pcall = pcall local next = next local type = type local table = table local string = string local DBG = DBG local WARN = WARN local ERROR = ERROR local archive = archive local utils = require "utils" local backend = require "backend" local requests = require "requests" module "postprocess" -- luacheck: globals get_repos deps_canon conflicts_canon available_packages pkg_aggregate run sort_candidates local function repo_parse(repo) repo.tp = 'parsed-repository' repo.content = {} local name = repo.name .. "/" .. repo.index_uri:uri() -- Get index local index = repo.index_uri:finish() -- TODO error? if index:sub(1, 2) == string.char(0x1F, 0x8B) then -- compressed index DBG("Decompressing index " .. name) index = archive.decompress(index) end -- Parse index DBG("Parsing index " .. name) local ok, list = pcall(backend.repo_parse, index) if not ok then local msg = "Couldn't parse the index of " .. name .. ": " .. tostring(list) if not repo.optional then error(utils.exception('syntax', msg)) end WARN(msg) -- TODO we might want to ignore this repository in its fulles instead of this end for _, pkg in pairs(list) do -- Compute the URI of each package (but don't download it yet, so don't create the uri object) pkg.uri_raw = repo.repo_uri .. '/' .. pkg.Filename pkg.repo = repo end repo.content = list end local function repos_failed_download(uri_fail) -- Locate failed repository and check if we can continue for _, repo in pairs(requests.known_repositories) do if uri_fail == repo.index_uri then local message = "Download failed for repository index " .. repo.name .. " (" .. repo.index_uri:uri() .. "): " .. tostring(repo.index_uri:download_error()) if not repo.optional then error(utils.exception('repo missing', message)) end WARN(message) repo.tp = 'failed-repository' break end end end function get_repos() DBG("Downloading repositories indexes") -- Run download while true do local uri_fail = requests.repositories_uri_master:download() if uri_fail then repos_failed_download(uri_fail) else break end end -- Collect indexes and parse them for _, repo in pairs(requests.known_repositories) do if repo.tp == 'repository' then -- ignore failed repositories local ok, err = pcall(repo_parse, repo) if not ok then -- TODO is this fatal? error(err) end end end end -- Helper function for deps_canon ‒ handles 0 and 1 item dependencies. local function dep_size_check(dep) if not next(dep.sub) then return nil elseif #dep.sub == 1 and dep.tp ~= 'dep-not' then return dep.sub[1] else return dep end end --[[ Canonicize the dependencies somewhat. This does several things: • Splits dependencies from strings (eg. "a, b, c" becomes a real dep-and object holding "a", "b", "c"). • Splits version limitations from dependency string (ex.: "a (>=1)" becomes { tp="dep-package", name="a", version=">=1" }). • Table dependencies are turned to real dep-and object. • Empty dependencies are turned to nil. • Single dependencies are turned to just the string (except with the not dependency) ]] function deps_canon(old_deps) if type(old_deps) == 'string' then if old_deps:match(',') then local sub = {} for dep in old_deps:gmatch('[^,]+') do table.insert(sub, deps_canon(dep)) end return deps_canon({ tp = 'dep-and', sub = sub }) elseif old_deps:match('%s') then local name, version = backend.parse_pkg_specifier(old_deps) if version then return { tp = "dep-package", name = name, version = version } else -- TODO possibly report error if name is nil? return name -- No version detected, use just name. end elseif old_deps == '' then return nil else return old_deps end elseif type(old_deps) == 'table' then local tp = old_deps.tp if tp == nil then -- It is an AND-type multi-dependency. Mark it as such. return deps_canon({ tp = 'dep-and', sub = old_deps }) elseif tp == 'dep-and' then -- Flatten any sub-and dependencies local sub = {} for _, val in ipairs(old_deps.sub) do local new_val = deps_canon(val) if new_val and new_val.tp == 'dep-and' then utils.arr_append(sub, new_val.sub) else table.insert(sub, new_val) end end return dep_size_check({ tp = 'dep-and', sub = sub }) elseif tp == 'dep-or' or tp == 'dep-not' then -- Run on sub-dependencies for i, val in ipairs(old_deps.sub) do old_deps.sub[i] = deps_canon(val) end return dep_size_check(old_deps) elseif tp == 'package' or tp == 'dep-package' then -- Single package dependency (an object instead of name) ‒ leave it as it is return old_deps else error(utils.exception('bad value', 'Object of type ' .. tp .. ' used as a dependency')); end elseif old_deps == nil then return nil else error(utils.exception('bad value', 'Bad deps type ' .. type(old_deps))) end end --[[ Create negative dependencies from Conflicts field. Argument conflicts is expected to contain string with names of packages. If generated dependencies don't have explicit version limitation than we use '~.*'. This should match every version. Specifying it that way we ignore candidates from other packages (added using Provides). This is required as 'Conflicts' shouldn't affect packages with different name. ]] function conflicts_canon(conflicts) if type(conflicts) ~= "string" and type(conflicts) ~= "nil" then error(utils.exception('bad value', 'Bad conflicts type ' .. type(conflicts))) end -- First canonize as dependency local dep = deps_canon(conflicts) if type(dep) == "string" then dep = { tp = "dep-not", sub = {{ tp = "dep-package", name = dep, version = "~.*" }} } elseif type(dep) == "table" and dep.tp then -- Note: The only acceptable input to this functions should be string and so the result should be a single package or conjunction of those packages. if dep.tp == "dep-package" then if not dep.version then dep.version = "~.*" end dep = { tp = "dep-not", sub = {dep} } elseif dep.tp == "dep-and" then for i, pkg in ipairs(dep.sub) do if type(pkg) ~= "string" and pkg.tp ~= "dep-package" then error(utils.exception('bad value', 'Bad conflict package deps type ' .. (pkg.tp or type(pkg)))) end if type(pkg) == "string" then pkg = { tp = "dep-package", name = pkg } dep.sub[i] = pkg end if not pkg.version then pkg.version = "~.*" end end dep.tp = "dep-or" dep = { tp = "dep-not", sub = {dep} } else error(utils.exception('bad value', 'Object of type ' .. dep.tp .. ' used as conflict deps')) end elseif type(dep) ~= "nil" then -- we pass if dep is nill but anything else is error at this point error(utils.exception('bad value', 'Bad conflict deps type ' .. type(dep))) end return dep end --[[ Sort all given candidates according to following criteria. * Source repository priority * For packages from same package group compare by version (preferring newer packages) * Prefer packages from package group we are working on (provided candidates are sorted to end) * Compare repository order of introduction * Sort alphabetically by name of package ]] function sort_candidates(pkgname, candidates) local function compare(a, b) -- The locally created packages (with content) have no repo, create a dummy one. Get its priority from the Package command, or the default 50 local a_repo = a.repo or {priority = utils.multi_index(a, "pkg", "priority") or 50, serial = -1, name = ""} local b_repo = b.repo or {priority = utils.multi_index(b, "pkg", "priority") or 50, serial = -1, name = ""} if a_repo.priority ~= b_repo.priority then -- Check repository priority return a_repo.priority > b_repo.priority end if a.Package == b.Package then -- Don't compare versions for different packages local vers_cmp = backend.version_cmp(a.Version, b.Version) if vers_cmp ~= 0 then -- Check version of package return vers_cmp == 1 -- a is newer version than b end elseif (a.Package ~= pkgname and b.Package == pkgname) or (a.Package == pkgname and b.Package ~= pkgname) then -- When only one of packages is provided by some other packages candidate return a.Package == pkgname -- Prioritize candidates of package it self, not provided ones. end if a_repo.serial ~= b_repo.serial then -- Check repo order of introduction return a_repo.serial < b_repo.serial end if a.Package ~= b.Package then -- As last resort when packages are not from same and not from provided package group return a.Package < b.Package -- Sort alphabetically by package name end -- As sorting algorithm is quicksort it sometimes compares object to it self. So we can't just strait print warning, but we have to check if it isn't same table. if a ~= b then WARN("Multiple candidates from same repository (" .. a_repo.name .. ") with same version (" .. a.Version .. ") for package " .. a.Package) end return false -- Because this is quicksort we have to as last resort return false end table.sort(candidates, compare) end available_packages = {} --[[ Compute the available_packages variable. It is a table indexed by the name of packages. Each package has candidates ‒ the sources that can be used to install the package. Also, it has modifiers ‒ list of amending 'package' objects. Afterwards the modifiers are put together to form single package object. ]] function pkg_aggregate() DBG("Aggregating packages together") for _, repo in pairs(requests.known_repositories) do if repo.tp == "parsed-repository" then -- TODO this content design is invalid as there can be multiple packages of same name in same repository with different versions for name, candidate in pairs(repo.content) do if not available_packages[name] then available_packages[name] = {candidates = {}, modifiers = {}} end table.insert(available_packages[name].candidates, candidate) if candidate.Provides then -- Add this candidate to package it provides for p in candidate.Provides:gmatch("[^, ]+") do if not available_packages[p] then available_packages[p] = {candidates = {}, modifiers = {}} end if p == name then WARN("Package provides itself, ignoring: " .. name) else table.insert(available_packages[p].candidates, candidate) end end end end end end for _, pkg in pairs(requests.known_packages) do if not available_packages[pkg.name] then available_packages[pkg.name] = {candidates = {}, modifiers = {}} end local pkg_group = available_packages[pkg.name] table.insert(pkg_group.modifiers, pkg) end for name, pkg_group in pairs(available_packages) do -- Merge the modifiers together to form single one. local modifier = { tp = 'package', name = name, deps = {}, order_after = {}, order_before = {}, pre_install = {}, pre_remove = {}, post_install = {}, post_remove = {}, reboot = false, replan = false, abi_change = {}, abi_change_deep = {} } for _, m in pairs(pkg_group.modifiers) do m.final = modifier --[[ Merge all the deps together. We use an empty table if there's nothing else, which is OK, since it'll get merged into the upper level and therefore won't have any effect during the subsequent dependency processing. Note that we don't merge the deps from the package sources, since there may be multiple candidates and the deps could differ. ]] table.insert(modifier.deps, m.deps or {}) -- Take a single value or a list from the source and merge it into a set in the destination local function set_merge(name) local src = m[name] if src == nil then return elseif type(src) == "table" then for _, v in pairs(src) do modifier[name][v] = true end else modifier[name][src] = true end end set_merge("order_after") set_merge("order_before") set_merge("pre_install") set_merge("pre_remove") set_merge("post_install") set_merge("post_remove") set_merge("abi_change") set_merge("abi_change_deep") local function flag_merge(name, vals) if m[name] and not vals[m[name]] then ERROR("Invalid " .. name .. " value " .. m[name] .. " on package " .. m.name) elseif (vals[m[name]] or 0) > vals[modifier[name]] then -- Pick the highest value (handle the case when there's no flag) modifier[name] = m[name] end end flag_merge("reboot", { [false] = 0, delayed = 1, finished = 2, immediate = 3 }) flag_merge("replan", { [false] = 0, finished = 1, [true] = 2, immediate = 2 }) if modifier.replan == true then -- true is the same as immediate so replace it modifier.replan = "immediate" end modifier.virtual = modifier.virtual or m.virtual end if modifier.virtual then -- virtual packages ignore all candidates pkg_group.candidates = {} end -- Canonize dependencies modifier.deps = deps_canon(modifier.deps) for _, candidate in ipairs(pkg_group.candidates or {}) do candidate.deps = deps_canon(utils.arr_prune({ candidate.deps, -- deps from updater configuration file candidate.Depends, -- Depends from repository conflicts_canon(candidate.Conflicts) -- Negative dependencies from repository })) end pkg_group.modifier = modifier -- We merged them together, they are no longer needed separately pkg_group.modifiers = nil -- Sort candidates sort_candidates(name, pkg_group.candidates or {}) end end --[[ Canonize request variables This is effectively here only to support if extra argument that should be canonized as dependency. ]] local function canon_requests(all_requests) for _, req in pairs(all_requests) do req.condition = deps_canon(req.condition) end end function run() get_repos() pkg_aggregate() canon_requests(requests.content_requests) end return _M
gpl-3.0
lichtl/darkstar
scripts/zones/Kazham/npcs/Eron-Tomaron.lua
27
3824
----------------------------------- -- Area: Kazham -- NPC: Eron-Tomaron -- Title Change NPC -- @pos -22 -4 -24 250 ----------------------------------- require("scripts/globals/titles"); local title2 = { DISCERNING_INDIVIDUAL , VERY_DISCERNING_INDIVIDUAL , EXTREMELY_DISCERNING_INDIVIDUAL , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title3 = { HEIR_OF_THE_GREAT_FIRE , YA_DONE_GOOD , GULLIBLES_TRAVELS , KAZHAM_CALLER , EXCOMMUNICATE_OF_KAZHAM , EVEN_MORE_GULLIBLES_TRAVELS , KING_OF_THE_OPOOPOS , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title4 = { FODDERCHIEF_FLAYER , WARCHIEF_WRECKER , DREAD_DRAGON_SLAYER , OVERLORD_EXECUTIONER , DARK_DRAGON_SLAYER , ADAMANTKING_KILLER , BLACK_DRAGON_SLAYER , MANIFEST_MAULER , BEHEMOTHS_BANE , ARCHMAGE_ASSASSIN , HELLSBANE , GIANT_KILLER , LICH_BANISHER , JELLYBANE , BOGEYDOWNER , BEAKBENDER , SKULLCRUSHER , MORBOLBANE , GOLIATH_KILLER , MARYS_GUIDE , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title5 = { SIMURGH_POACHER , ROC_STAR , SERKET_BREAKER , CASSIENOVA , THE_HORNSPLITTER , TORTOISE_TORTURER , MON_CHERRY , BEHEMOTH_DETHRONER , THE_VIVISECTOR , DRAGON_ASHER , EXPEDITIONARY_TROOPER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title6 = { ADAMANTKING_USURPER , OVERLORD_OVERTHROWER , DEITY_DEBUNKER , FAFNIR_SLAYER , ASPIDOCHELONE_SINKER , NIDHOGG_SLAYER , MAAT_MASHER , KIRIN_CAPTIVATOR , CACTROT_DESACELERADOR , LIFTER_OF_SHADOWS , TIAMAT_TROUNCER , VRTRA_VANQUISHER , WORLD_SERPENT_SLAYER , XOLOTL_XTRAPOLATOR , BOROKA_BELEAGUERER , OURYU_OVERWHELMER , VINEGAR_EVAPORATOR , VIRTUOUS_SAINT , BYEBYE_TAISAI , TEMENOS_LIBERATOR , APOLLYON_RAVAGER , WYRM_ASTONISHER , NIGHTMARE_AWAKENER , 0 , 0 , 0 , 0 , 0 } local title7 = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x271D,npcUtil.genTmask(player,title2),npcUtil.genTmask(player,title3),npcUtil.genTmask(player,title4),npcUtil.genTmask(player,title5),npcUtil.genTmask(player,title6),npcUtil.genTmask(player,title7),1 ,player:getGil()); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid==0x271D) then if (option > 0 and option <29) then if (player:delGil(200)) then player:setTitle( title2[option] ) end elseif (option > 256 and option <285) then if (player:delGil(300)) then player:setTitle( title3[option - 256] ) end elseif (option > 512 and option < 541) then if (player:delGil(400)) then player:setTitle( title4[option - 512] ) end elseif (option > 768 and option <797) then if (player:delGil(500)) then player:setTitle( title5[option - 768] ) end elseif (option > 1024 and option < 1053) then if (player:delGil(600)) then player:setTitle( title6[option - 1024] ) end end end end;
gpl-3.0
ali123345/ali-
plugin/muteall.lua
1
4809
do local function pre_process(msg) local hash = 'muteall:'..msg.to.id if redis:get(hash) and msg.to.type == 'channel' and not is_mod(msg) then tdcli.deleteMessages(msg.chat_id_, {[0] = msg.id_}) end return msg end local function run(msg, matches) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if matches[1] == 'mute' and matches[2] == 'all' and is_mod(msg) then local hash = 'muteall:'..msg.to.id if not matches[3] then redis:set(hash, true) return "mute all has been enabled" else local hour = string.gsub(matches[3], 'h', '') local num1 = tonumber(hour) * 3600 local minutes = string.gsub(matches[4], 'm', '') local num2 = tonumber(minutes) * 60 local second = string.gsub(matches[5], 's', '') local num3 = tonumber(second) local num4 = tonumber(num1 + num2 + num3) redis:setex(hash, num4, true) if not lang then return "Mute all has been enabled for \n⏺ hours : "..matches[3].."\n⏺ minutes : "..matches[4].."\n⏺ seconds : "..matches[5].."\n@BeyondTeam" elseif lang then return "بی صدا کردن فعال شد در \n⏺ ساعت : "..matches[3].."\n⏺ دقیقه : "..matches[4].."\n⏺ ثانیه : "..matches[5].."\n@BeyondTeam" end end end if matches[1] == 'mute' and matches[2] == 'hours' and is_mod(msg) then local hash = 'muteall:'..msg.to.id if not matches[3] then redis:set(hash, true) return "mute all has been enabled" else local hour = string.gsub(matches[3], 'h', '') local num1 = tonumber(hour) * 3600 local num4 = tonumber(num1) redis:setex(hash, num4, true) if not lang then return "Mute all has been enabled for \n⏺ hours : "..matches[3].."\n@BeyondTeam" elseif lang then return "بی صدا کردن فعال شد در \n⏺ ساعت : "..matches[3].."\n@BeyondTeam" end end end if matches[1] == 'mute' and matches[2] == 'minutes' and is_mod(msg) then local hash = 'muteall:'..msg.to.id if not matches[3] then redis:set(hash, true) return "mute all has been enabled" else local minutes = string.gsub(matches[3], 'm', '') local num2 = tonumber(minutes) * 60 local num4 = tonumber(num2) redis:setex(hash, num4, true) if not lang then return "Mute all has been enabled for \n⏺ minutes : "..matches[3].."\n@BeyondTeam" elseif lang then return "بی صدا کردن فعال شد در \n⏺ دقیقه : "..matches[3].."\n@BeyondTeam" end end end if matches[1] == 'mute' and matches[2] == 'seconds' and is_mod(msg) then local hash = 'muteall:'..msg.to.id if not matches[3] then redis:set(hash, true) return "mute all has been enabled" else local second = string.gsub(matches[3], 's', '') local num3 = tonumber(second) local num4 = tonumber(num3) redis:setex(hash, num3, true) if not lang then return "Mute all has been enabled for \n⏺ seconds : "..matches[3].."\n@BeyondTeam" elseif lang then return "بی صدا کردن فعال شد در \n⏺ ثانیه : "..matches[3].."\n@BeyondTeam" end end end if matches[1] == 'helpmute' then if not lang then text = [[ *Beyond Mute Commands:* *!mute all* `(hour) (minute) (seconds)` _Mute group at this time_ *!mute hours* `(number)` _Mute group at this time_ *!mute minute* `(number)` _Mute group at this time_ *!mute seconds* `(number)` _Mute group at this time_ *!unmute all* _Unmute group at this time_ _You can use_ *[!/#]* _at the beginning of commands._ ]] elseif lang then text = [[ *راهنمای بیصدا های ربات بیوند:* *!mute all* `(hour) (minute) (seconds)` _بیصدا کردن گروه با ساعت و دقیقه و ثانیه_ *!mute hours* `(number)` _بیصدا کردن گروه در ساعت_ *!mute minute* `(number)` _بیصدا کردن گروه در دقیقه_ *!mute seconds* `(number)` _بیصدا کردن گروه در ثانیه_ *!unmute all* _آزاد سازی بیصدایی گروه در آن زمان_ *شما میتوانید از [!/#] در اول دستورات برای اجرای آنها بهره بگیرید* ]] end return text end if matches[1] == 'unmute' and matches[2] == 'all' and is_mod(msg) then local hash = 'muteall:'..msg.to.id redis:del(hash) if not lang then return "mute all has been disabled" elseif lang then return "گروه ازاد شد و افراد می توانند دوباره پست بگذارند" end end end return { patterns = { _config.cmd .. '([Uu]nmute) (all)$', _config.cmd .. '([Hh]elpmute)$', _config.cmd .. '([Mm]ute) (all) (.*) (.*) (.*)$', _config.cmd .. '([Mm]ute) (hours) (.*)$', _config.cmd .. '([Mm]ute) (minutes) (.*)$', _config.cmd .. '([Mm]ute) (seconds) (.*)$', }, run = run, pre_process = pre_process } end --by @BeyondTeam
gpl-3.0
lichtl/darkstar
scripts/zones/Middle_Delkfutts_Tower/npcs/Treasure_Chest.lua
17
3792
----------------------------------- -- Area: Middle Delkfutt's Tower -- NPC: Treasure Chest -- Involved In Quest: Wings of Gold -- @zone 157 ----------------------------------- package.loaded["scripts/zones/Middle_Delkfutts_Tower/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/Middle_Delkfutts_Tower/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 43; local TreasureMinLvL = 33; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1036,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if ((trade:hasItemQty(1036,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); -- IMPORTANT ITEM: WINGS OF GOLD QUEST QUEST ----------- if (player:getQuestStatus(JEUNO,WINGS_OF_GOLD) == QUEST_ACCEPTED and player:hasKeyItem(GUIDING_BELL) == false) then questItemNeeded = 1; end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if (questItemNeeded == 1) then player:addKeyItem(GUIDING_BELL); player:messageSpecial(KEYITEM_OBTAINED,GUIDING_BELL); -- Guiding Bell (KI) else local zone = player:getZoneID(); player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]); player:messageSpecial(GIL_OBTAINED,loot[2]); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1036); 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
RunAwayDSP/darkstar
scripts/globals/spells/bluemagic/metallic_body.lua
12
1412
----------------------------------------- -- Spell: Metallic Body -- Absorbs an certain amount of damage from physical and magical attacks -- Spell cost: 19 MP -- Monster Type: Aquans -- Spell Type: Magical (Earth) -- Blue Magic Points: 1 -- Stat Bonus: None -- Level: 8 -- Casting Time: 7 seconds -- Recast Time: 60 seconds -- Duration: 5 minutes -- -- Combos: Max MP Boost ----------------------------------------- require("scripts/globals/bluemagic") require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0 end function onSpellCast(caster,target,spell) local typeEffect = dsp.effect.STONESKIN local blueskill = caster:getSkillLevel(dsp.skill.BLUE_MAGIC) local power = (blueskill/3) + (caster:getMainLvl()/3) + 10 local duration = 300 if (power > 150) then power = 150 end if (caster:hasStatusEffect(dsp.effect.DIFFUSION)) then local diffMerit = caster:getMerit(dsp.merit.DIFFUSION) if (diffMerit > 0) then duration = duration + (duration/100)* diffMerit end caster:delStatusEffect(dsp.effect.DIFFUSION) end if not target:addStatusEffect(typeEffect,power,0,duration,0,0,2) then spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) end return typeEffect end
gpl-3.0
lichtl/darkstar
scripts/zones/West_Sarutabaruta/npcs/Darumomo_WW.lua
14
3348
----------------------------------- -- Area: West Sarutabaruta -- NPC: Darumomo, W.W. -- Type: Border Conquest Guards -- @pos 399.450 -25.858 727.545 115 ----------------------------------- package.loaded["scripts/zones/West_Sarutabaruta/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/West_Sarutabaruta/TextIDs"); local guardnation = NATION_WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = SARUTABARUTA; local csid = 0x7ff6; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
RunAwayDSP/darkstar
scripts/zones/Apollyon/mobs/Light_Elemental.lua
9
2117
----------------------------------- -- Area: Apollyon SW -- Mob: Light Elemental ----------------------------------- require("scripts/globals/limbus"); ----------------------------------- function onMobDeath(mob, player, isKiller) end; function onMobDespawn(mob) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); local elementalday = GetServerVariable("[SW_Apollyon]ElementalTrigger") - 1; local correctelement=false; switch (elementalday): caseof { [0] = function (x) if (mobID==16932913 or mobID==16932921 or mobID==16932929) then correctelement=true; end end , [1] = function (x) if (mobID==16932912 or mobID==16932920 or mobID==16932928 ) then correctelement=true; end end , [2] = function (x) if (mobID==16932916 or mobID==16932924 or mobID==16932932 ) then correctelement=true; end end , [3] = function (x) if (mobID==16932910 or mobID==16932918 or mobID==16932926 ) then correctelement=true; end end , [4] = function (x) if (mobID==16932914 or mobID==16932922 or mobID==16932930 ) then correctelement=true; end end , [5] = function (x) if (mobID==16932917 or mobID==16932925 or mobID==16932933 ) then correctelement=true; end end , [6] = function (x) if (mobID==16932931 or mobID==16932915 or mobID==16932923 ) then correctelement=true; end end , [7] = function (x) if (mobID==16932911 or mobID==16932919 or mobID==16932927 ) then correctelement=true; end end , }; if (correctelement==true and IselementalDayAreDead() == true) then GetNPCByID(16932864+313):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+313):setStatus(dsp.status.NORMAL); end end;
gpl-3.0
kwketh/otclient
modules/corelib/ui/uiminiwindow.lua
1
10469
-- @docclass UIMiniWindow = extends(UIWindow) function UIMiniWindow.create() local miniwindow = UIMiniWindow.internalCreate() return miniwindow end function UIMiniWindow:getClassName() return 'UIMiniWindow' end function UIMiniWindow:open(dontSave) self:setVisible(true) if not dontSave then self:setSettings({closed = false}) end signalcall(self.onOpen, self) end function UIMiniWindow:close(dontSave) if not self:isExplicitlyVisible() then return end self:setVisible(false) if not dontSave then self:setSettings({closed = true}) end signalcall(self.onClose, self) end function UIMiniWindow:minimize(dontSave) self:setOn(true) self:getChildById('contentsPanel'):hide() self:getChildById('miniwindowScrollBar'):hide() self:getChildById('bottomResizeBorder'):hide() self:getChildById('minimizeButton'):setOn(true) self.maximizedHeight = self:getHeight() self:setHeight(self.minimizedHeight) if not dontSave then self:setSettings({minimized = true}) end signalcall(self.onMinimize, self) end function UIMiniWindow:maximize(dontSave) self:setOn(false) self:getChildById('contentsPanel'):show() self:getChildById('miniwindowScrollBar'):show() self:getChildById('bottomResizeBorder'):show() self:getChildById('minimizeButton'):setOn(false) self:setHeight(self:getSettings('height') or self.maximizedHeight) if not dontSave then self:setSettings({minimized = false}) end local parent = self:getParent() if parent and parent:getClassName() == 'UIMiniWindowContainer' then parent:fitAll(self) end signalcall(self.onMaximize, self) end function UIMiniWindow:setup() self:getChildById('closeButton').onClick = function() self:close() end self:getChildById('minimizeButton').onClick = function() if self:isOn() then self:maximize() else self:minimize() end end self:getChildById('miniwindowTopBar').onDoubleClick = function() if self:isOn() then self:maximize() else self:minimize() end end local oldParent = self:getParent() local settings = g_settings.getNode('MiniWindows') if settings then local selfSettings = settings[self:getId()] if selfSettings then if selfSettings.parentId then local parent = rootWidget:recursiveGetChildById(selfSettings.parentId) if parent then if parent:getClassName() == 'UIMiniWindowContainer' and selfSettings.index and parent:isOn() then self.miniIndex = selfSettings.index parent:scheduleInsert(self, selfSettings.index) elseif selfSettings.position then self:setParent(parent, true) self:setPosition(topoint(selfSettings.position)) end end end if selfSettings.minimized then self:minimize(true) else if selfSettings.height and self:isResizeable() then self:setHeight(selfSettings.height) elseif selfSettings.height and not self:isResizeable() then self:eraseSettings({height = true}) end end if selfSettings.closed then self:close(true) end end end local newParent = self:getParent() self.miniLoaded = true if self.save then if oldParent and oldParent:getClassName() == 'UIMiniWindowContainer' then addEvent(function() oldParent:order() end) end if newParent and newParent:getClassName() == 'UIMiniWindowContainer' and newParent ~= oldParent then addEvent(function() newParent:order() end) end end self:fitOnParent() end function UIMiniWindow:onVisibilityChange(visible) self:fitOnParent() end function UIMiniWindow:onDragEnter(mousePos) local parent = self:getParent() if not parent then return false end if parent:getClassName() == 'UIMiniWindowContainer' then local containerParent = parent:getParent() parent:removeChild(self) containerParent:addChild(self) parent:saveChildren() end local oldPos = self:getPosition() self.movingReference = { x = mousePos.x - oldPos.x, y = mousePos.y - oldPos.y } self:setPosition(oldPos) self.free = true return true end function UIMiniWindow:onDragLeave(droppedWidget, mousePos) if self.movedWidget then self.setMovedChildMargin(self.movedOldMargin or 0) self.movedWidget = nil self.setMovedChildMargin = nil self.movedOldMargin = nil self.movedIndex = nil end self:saveParent(self:getParent()) end function UIMiniWindow:onDragMove(mousePos, mouseMoved) local oldMousePosY = mousePos.y - mouseMoved.y local children = rootWidget:recursiveGetChildrenByMarginPos(mousePos) local overAnyWidget = false for i=1,#children do local child = children[i] if child:getParent():getClassName() == 'UIMiniWindowContainer' then overAnyWidget = true local childCenterY = child:getY() + child:getHeight() / 2 if child == self.movedWidget and mousePos.y < childCenterY and oldMousePosY < childCenterY then break end if self.movedWidget then self.setMovedChildMargin(self.movedOldMargin or 0) self.setMovedChildMargin = nil end if mousePos.y < childCenterY then self.movedOldMargin = child:getMarginTop() self.setMovedChildMargin = function(v) child:setMarginTop(v) end self.movedIndex = 0 else self.movedOldMargin = child:getMarginBottom() self.setMovedChildMargin = function(v) child:setMarginBottom(v) end self.movedIndex = 1 end self.movedWidget = child self.setMovedChildMargin(self:getHeight()) break end end if not overAnyWidget and self.movedWidget then self.setMovedChildMargin(self.movedOldMargin or 0) self.movedWidget = nil end return UIWindow.onDragMove(self, mousePos, mouseMoved) end function UIMiniWindow:onMousePress() local parent = self:getParent() if not parent then return false end if parent:getClassName() ~= 'UIMiniWindowContainer' then self:raise() return true end end function UIMiniWindow:onFocusChange(focused) if not focused then return end local parent = self:getParent() if parent and parent:getClassName() ~= 'UIMiniWindowContainer' then self:raise() end end function UIMiniWindow:onHeightChange(height) if not self:isOn() then self:setSettings({height = height}) end self:fitOnParent() end function UIMiniWindow:getSettings(name) if not self.save then return nil end local settings = g_settings.getNode('MiniWindows') if settings then local selfSettings = settings[self:getId()] if selfSettings then return selfSettings[name] end end return nil end function UIMiniWindow:setSettings(data) if not self.save then return end local settings = g_settings.getNode('MiniWindows') if not settings then settings = {} end local id = self:getId() if not settings[id] then settings[id] = {} end for key,value in pairs(data) do settings[id][key] = value end g_settings.setNode('MiniWindows', settings) end function UIMiniWindow:eraseSettings(data) if not self.save then return end local settings = g_settings.getNode('MiniWindows') if not settings then settings = {} end local id = self:getId() if not settings[id] then settings[id] = {} end for key,value in pairs(data) do settings[id][key] = nil end g_settings.setNode('MiniWindows', settings) end function UIMiniWindow:saveParent(parent) local parent = self:getParent() if parent then if parent:getClassName() == 'UIMiniWindowContainer' then parent:saveChildren() else self:saveParentPosition(parent:getId(), self:getPosition()) end end end function UIMiniWindow:saveParentPosition(parentId, position) local selfSettings = {} selfSettings.parentId = parentId selfSettings.position = pointtostring(position) self:setSettings(selfSettings) end function UIMiniWindow:saveParentIndex(parentId, index) local selfSettings = {} selfSettings.parentId = parentId selfSettings.index = index self:setSettings(selfSettings) self.miniIndex = index end function UIMiniWindow:disableResize() self:getChildById('bottomResizeBorder'):disable() end function UIMiniWindow:enableResize() self:getChildById('bottomResizeBorder'):enable() end function UIMiniWindow:fitOnParent() local parent = self:getParent() if self:isVisible() and parent and parent:getClassName() == 'UIMiniWindowContainer' then parent:fitAll(self) end end function UIMiniWindow:setParent(parent, dontsave) UIWidget.setParent(self, parent) if not dontsave then self:saveParent(parent) end self:fitOnParent() end function UIMiniWindow:setHeight(height) UIWidget.setHeight(self, height) signalcall(self.onHeightChange, self, height) end function UIMiniWindow:setContentHeight(height) local contentsPanel = self:getChildById('contentsPanel') local minHeight = contentsPanel:getMarginTop() + contentsPanel:getMarginBottom() + contentsPanel:getPaddingTop() + contentsPanel:getPaddingBottom() local resizeBorder = self:getChildById('bottomResizeBorder') resizeBorder:setParentSize(minHeight + height) end function UIMiniWindow:setContentMinimumHeight(height) local contentsPanel = self:getChildById('contentsPanel') local minHeight = contentsPanel:getMarginTop() + contentsPanel:getMarginBottom() + contentsPanel:getPaddingTop() + contentsPanel:getPaddingBottom() local resizeBorder = self:getChildById('bottomResizeBorder') resizeBorder:setMinimum(minHeight + height) end function UIMiniWindow:setContentMaximumHeight(height) local contentsPanel = self:getChildById('contentsPanel') local minHeight = contentsPanel:getMarginTop() + contentsPanel:getMarginBottom() + contentsPanel:getPaddingTop() + contentsPanel:getPaddingBottom() local resizeBorder = self:getChildById('bottomResizeBorder') resizeBorder:setMaximum(minHeight + height) end function UIMiniWindow:getMinimumHeight() local resizeBorder = self:getChildById('bottomResizeBorder') return resizeBorder:getMinimum() end function UIMiniWindow:getMaximumHeight() local resizeBorder = self:getChildById('bottomResizeBorder') return resizeBorder:getMaximum() end function UIMiniWindow:isResizeable() local resizeBorder = self:getChildById('bottomResizeBorder') return resizeBorder:isExplicitlyVisible() and resizeBorder:isEnabled() end
mit
lichtl/darkstar
scripts/zones/Port_Windurst/npcs/Sigismund.lua
13
2392
----------------------------------- -- Area: Windurst Waters -- NPC: Sigismund -- Starts and Finishes Quest: To Catch a Falling Star -- Working 100% -- @zone = 240 -- @pos = -110 -10 82 ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/status"); require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) starstatus = player:getQuestStatus(WINDURST,TO_CATCH_A_FALLIHG_STAR); if (starstatus == 1 and trade:hasItemQty(546,1) == true and trade:getItemCount() == 1 and trade:getGil() == 0) then player:startEvent(0x00c7); -- Quest Finish end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) starstatus = player:getQuestStatus(WINDURST,TO_CATCH_A_FALLIHG_STAR); if (starstatus == QUEST_AVAILABLE) then player:startEvent(0x00c4,0,546); -- Quest Start elseif (starstatus == QUEST_ACCEPTED) then player:startEvent(0x00c5,0,546); -- Quest Reminder elseif (starstatus == QUEST_COMPLETED and player:getVar("QuestCatchAFallingStar_prog") > 0) then player:startEvent(0x00c8); -- After Quest player:setVar("QuestCatchAFallingStar_prog",0) else player:startEvent(0x0165); 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 == 0x00c4) then player:addQuest(WINDURST,TO_CATCH_A_FALLIHG_STAR); elseif (csid == 0x00c7) then player:tradeComplete(trade); player:completeQuest(WINDURST,TO_CATCH_A_FALLIHG_STAR); player:addFame(WINDURST,75); player:addItem(12316); player:messageSpecial(ITEM_OBTAINED,12316); player:setVar("QuestCatchAFallingStar_prog",2); end end;
gpl-3.0
ArianWatch/VivaTeam
plugins/inrealm.lua
850
25085
-- 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 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 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' 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 "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) local data = load_data(_config.moderation.data, data) 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 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.."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 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.."memberlist.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
dalqak/slf
plugins/inrealm.lua
850
25085
-- 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 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 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' 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 "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) local data = load_data(_config.moderation.data, data) 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 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.."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 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.."memberlist.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
agpl-3.0
lichtl/darkstar
scripts/zones/Davoi/npcs/Storage_Hole.lua
14
1596
----------------------------------- -- Area: Davoi -- NPC: Storage Hole -- Involved in Quest: The Crimson Trial -- @pos -51 4 -217 149 ----------------------------------- package.loaded["scripts/zones/Davoi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Davoi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,THE_CRIMSON_TRIAL) == QUEST_ACCEPTED) then if (trade:hasItemQty(1103,1) and trade:getItemCount() == 1) then player:tradeComplete(); player:addKeyItem(ORCISH_DRIED_FOOD); player:messageSpecial(KEYITEM_OBTAINED,ORCISH_DRIED_FOOD); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(SANDORIA,THE_CRIMSON_TRIAL) == QUEST_ACCEPTED) then player:messageSpecial(AN_ORCISH_STORAGE_HOLE); else player:messageSpecial(YOU_SEE_NOTHING); 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
lichtl/darkstar
scripts/zones/Northern_San_dOria/npcs/Attarena.lua
17
1958
----------------------------------- -- Area: Northern San d'Oria -- NPC: Attarena -- Only sells when San d'Oria controlls Li'Telor Region ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/events/harvest_festivals"); require("scripts/globals/settings"); require("scripts/globals/conquest"); require("scripts/globals/quests"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == 1) then if (trade:hasItemQty(532,1) == true and trade:getItemCount() == 1) then player:messageSpecial(FLYER_REFUSED); end else onHalloweenTrade(player,trade,npc); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(LITELOR); if (RegionOwner ~= NATION_SANDORIA) then player:showText(npc,ATTARENA_CLOSED_DIALOG); else player:showText(npc,ATTARENA_OPEN_DIALOG); local stock = {0x026f,119, -- Bay Leaves 0x103a,6440} -- Holy Water showShop(player,SANDORIA,stock); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
RunAwayDSP/darkstar
scripts/zones/Northern_San_dOria/npcs/Attarena.lua
11
1244
----------------------------------- -- Area: Northern San d'Oria -- NPC: Attarena -- Only sells when San d'Oria controlls Li'Telor Region ----------------------------------- local ID = require("scripts/zones/Northern_San_dOria/IDs") require("scripts/globals/events/harvest_festivals") require("scripts/globals/npc_util") require("scripts/globals/conquest") require("scripts/globals/quests") require("scripts/globals/shop") function onTrade(player,npc,trade) if player:getQuestStatus(SANDORIA, dsp.quest.id.sandoria.FLYERS_FOR_REGINE) == QUEST_ACCEPTED and npcUtil.tradeHas(trade, 532) then player:messageSpecial(ID.text.FLYER_REFUSED) else onHalloweenTrade(player,trade,npc); end end; function onTrigger(player,npc) if GetRegionOwner(dsp.region.LITELOR) ~= dsp.nation.SANDORIA then player:showText(npc, ID.text.ATTARENA_CLOSED_DIALOG) else local stock = { 623, 119, -- Bay Leaves 4154, 6440, -- Holy Water } player:showText(npc, ID.text.ATTARENA_OPEN_DIALOG) dsp.shop.general(player, stock, SANDORIA) end end; function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) end
gpl-3.0
lichtl/darkstar
scripts/zones/Norg/npcs/Fouvia.lua
14
1622
----------------------------------- -- Area: Norg -- NPC: Fouvia -- Type: Wyvern Name Changer -- @zone 252 -- @pos -84.066 -6.414 47.826 ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/pets"); require("scripts/zones/Norg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getMainJob() ~= JOBS.DRG) then player:showText(npc,FOUIVA_DIALOG); -- Oi 'av naw business wi' de likes av you. elseif (player:getGil() < 9800) then player:showText(npc,FOUIVA_DIALOG + 9); -- You don't 'av enough gil. Come back when you do. else player:startEvent(0x0082,0,0,0,0,0,0,player:getVar("ChangedWyvernName")); 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 == 0x82 and option ~= 1073741824) then -- Player didn't cancel out player:delGil(9800); player:setVar("ChangedWyvernName",1); player:setPetName(PETTYPE_WYVERN,option+1); end end;
gpl-3.0
RunAwayDSP/darkstar
scripts/zones/FeiYin/npcs/Rukususu.lua
9
1210
----------------------------------- -- Area: Fei'Yin -- NPC: Rukususu (talk to Cermet Door _no5 to trigger) -- Type: Quest NPC -- !pos -194.133 -0.986 191.077 204 -- Involved in quests: Curses, Foiled A-Golem!?,SMN AF2: Class Reunion, SMN AF3: Carbuncle Debacle -- Involved in Missions: Windurst 5-1/7-2/8-2 ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) -- Curses, Foiled A_Golem!? if (player:hasKeyItem(dsp.ki.SHANTOTTOS_NEW_SPELL)) then player:startEvent(14); -- deliver spell elseif (player:hasKeyItem(dsp.ki.SHANTOTTOS_EXSPELL)) then player:startEvent(13); -- spell erased, try again! -- standard dialog else player:startEvent(15); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) -- Curses, Foiled A_Golem!? if (csid == 14) then player:setCharVar("foiledagolemdeliverycomplete",1); player:delKeyItem(dsp.ki.SHANTOTTOS_NEW_SPELL); -- remove key item end end;
gpl-3.0
OctoEnigma/shiny-octo-system
gamemodes/terrortown/entities/entities/ttt_radio.lua
3
6887
---- Radio equipment playing distraction sounds AddCSLuaFile() if CLIENT then -- this entity can be DNA-sampled so we need some display info ENT.Icon = "vgui/ttt/icon_radio" ENT.PrintName = "radio_name" end ENT.Type = "anim" ENT.Model = Model("models/props/cs_office/radio.mdl") ENT.CanUseKey = true ENT.CanHavePrints = false ENT.SoundLimit = 5 ENT.SoundDelay = 0.5 function ENT:Initialize() self:SetModel(self.Model) self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self:SetCollisionGroup(COLLISION_GROUP_NONE) if SERVER then self:SetMaxHealth(40) end self:SetHealth(40) if SERVER then self:SetUseType(SIMPLE_USE) end -- Register with owner if CLIENT then if LocalPlayer() == self:GetOwner() then LocalPlayer().radio = self end end self.SoundQueue = {} self.Playing = false self.fingerprints = {} end function ENT:UseOverride(activator) if IsValid(activator) and activator:IsPlayer() and activator:IsActiveTraitor() then local prints = self.fingerprints or {} self:Remove() local wep = activator:Give("weapon_ttt_radio") if IsValid(wep) then wep.fingerprints = wep.fingerprints or {} table.Add(wep.fingerprints, prints) end end end local zapsound = Sound("npc/assassin/ball_zap1.wav") function ENT:OnTakeDamage(dmginfo) self:TakePhysicsDamage(dmginfo) self:SetHealth(self:Health() - dmginfo:GetDamage()) if self:Health() < 0 then self:Remove() local effect = EffectData() effect:SetOrigin(self:GetPos()) util.Effect("cball_explode", effect) sound.Play(zapsound, self:GetPos()) if IsValid(self:GetOwner()) then LANG.Msg(self:GetOwner(), "radio_broken") end end end function ENT:OnRemove() if CLIENT then if LocalPlayer() == self:GetOwner() then LocalPlayer().radio = nil end end end function ENT:AddSound(snd) if #self.SoundQueue < self.SoundLimit then table.insert(self.SoundQueue, snd) end end local simplesounds = { scream = { Sound("vo/npc/male01/pain07.wav"), Sound("vo/npc/male01/pain08.wav"), Sound("vo/npc/male01/pain09.wav"), Sound("vo/npc/male01/no02.wav") }, explosion = { Sound("BaseExplosionEffect.Sound") } }; local serialsounds = { footsteps = { sound = { {Sound("player/footsteps/concrete1.wav"), Sound("player/footsteps/concrete2.wav")}, {Sound("player/footsteps/concrete3.wav"), Sound("player/footsteps/concrete4.wav")} }, times = {8, 16}, delay = 0.35, ampl = 80 }, burning = { sound = { Sound("General.BurningObject"), Sound("General.StopBurning") }, times = {2, 2}, delay = 4, }, beeps = { sound = { Sound("weapons/c4/c4_beep1.wav") }, delay = 0.75, times = {8, 12}, ampl = 70 } }; local gunsounds = { shotgun = { sound = Sound( "Weapon_XM1014.Single" ), delay = 0.8, times = {1, 3}, burst = false }, pistol = { sound = Sound( "Weapon_FiveSeven.Single" ), delay = 0.4, times = {2, 4}, burst = false }, mac10 = { sound = Sound( "Weapon_mac10.Single" ), delay = 0.065, times = {5, 10}, burst = true }, deagle = { sound = Sound( "Weapon_Deagle.Single" ), delay = 0.6, times = {1, 3}, burst = false }, m16 = { sound = Sound( "Weapon_M4A1.Single" ), delay = 0.2, times = {1, 5}, burst = true }, rifle = { sound = Sound( "weapons/scout/scout_fire-1.wav" ), delay = 1.5, times = {1, 1}, burst = false, ampl = 80 }, huge = { sound = Sound( "Weapon_m249.Single" ), delay = 0.055, times = {6, 12}, burst = true } }; function ENT:PlayDelayedSound(snd, ampl, last) -- maybe we can get destroyed while a timer is still up if IsValid(self) then if type(snd) == "table" then snd = table.Random(snd) end sound.Play(snd, self:GetPos(), ampl) self.Playing = not last --print("Playing", snd, last) end end function ENT:PlaySound(snd) local pos = self:GetPos() local this = self if simplesounds[snd] then sound.Play(table.Random(simplesounds[snd]), pos) elseif gunsounds[snd] then local gunsound = gunsounds[snd] local times = math.random(gunsound.times[1], gunsound.times[2]) local t = 0 for i=1, times do timer.Simple(t, function() if IsValid(this) then this:PlayDelayedSound(gunsound.sound, gunsound.ampl or 90, (i == times)) end end) if gunsound.burst then t = t + gunsound.delay else t = t + math.Rand(gunsound.delay, gunsound.delay * 2) end end elseif serialsounds[snd] then local serialsound = serialsounds[snd] local num = #serialsound.sound local times = math.random(serialsound.times[1], serialsound.times[2]) local t = 0 local idx = 1 for i=1, times do local sound = serialsound.sound[idx] timer.Simple(t, function() if IsValid(this) then this:PlayDelayedSound(sound, serialsound.ampl or 75, (i == times)) end end) t = t + serialsound.delay idx = idx + 1 if idx > num then idx = 1 end end end end local nextplay = 0 function ENT:Think() if CurTime() > nextplay and #self.SoundQueue > 0 then if not self.Playing then local snd = table.remove(self.SoundQueue, 1) self:PlaySound(snd) end -- always do this, makes timing work out a little better nextplay = CurTime() + self.SoundDelay end end if SERVER then local soundtypes = { "scream", "shotgun", "explosion", "pistol", "mac10", "deagle", "m16", "rifle", "huge", "burning", "beeps", "footsteps" }; local function RadioCmd(ply, cmd, args) if not IsValid(ply) or not ply:IsActiveTraitor() then return end if not #args == 2 then return end local eidx = tonumber(args[1]) local snd = tostring(args[2]) if not eidx or not snd then return end local radio = Entity(eidx) if not IsValid(radio) then return end if not radio:GetOwner() == ply then return end if not table.HasValue(soundtypes, snd) then print("Received radio sound not in table from", ply) return end radio:AddSound(snd) end concommand.Add("ttt_radio_play", RadioCmd) end
mit
RunAwayDSP/darkstar
scripts/globals/items/piece_of_kusamochi_+1.lua
11
1875
----------------------------------------- -- ID: 6263 -- Item: kusamochi+1 -- Food Effect: 60 Min, All Races ----------------------------------------- -- HP + 30 (Pet & Master) -- Vitality + 4 (Pet & Master) -- Attack + 21% Cap: 77 (Pet & Master) Pet Cap: 120 -- Ranged Attack + 21% Cap: 77 (Pet & Master) Pet Cap: 120 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if (target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD)) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,3600,6263) end function onEffectGain(target, effect) target:addMod(dsp.mod.HP, 30) target:addMod(dsp.mod.VIT, 4) target:addMod(dsp.mod.FOOD_ATTP, 21) target:addMod(dsp.mod.FOOD_ATT_CAP, 77) target:addMod(dsp.mod.FOOD_RATTP, 21) target:addMod(dsp.mod.FOOD_RATT_CAP, 77) target:addPetMod(dsp.mod.HP, 30) target:addPetMod(dsp.mod.VIT, 4) target:addPetMod(dsp.mod.FOOD_ATTP, 21) target:addPetMod(dsp.mod.FOOD_ATT_CAP, 120) target:addPetMod(dsp.mod.FOOD_RATTP, 21) target:addPetMod(dsp.mod.FOOD_RATT_CAP, 120) end function onEffectLose(target, effect) target:delMod(dsp.mod.HP, 30) target:delMod(dsp.mod.VIT, 4) target:delMod(dsp.mod.FOOD_ATTP, 21) target:delMod(dsp.mod.FOOD_ATT_CAP, 77) target:delMod(dsp.mod.FOOD_RATTP, 21) target:delMod(dsp.mod.FOOD_RATT_CAP, 77) target:delPetMod(dsp.mod.HP, 30) target:delPetMod(dsp.mod.VIT, 4) target:delPetMod(dsp.mod.FOOD_ATTP, 21) target:delPetMod(dsp.mod.FOOD_ATT_CAP, 120) target:delPetMod(dsp.mod.FOOD_RATTP, 21) target:delPetMod(dsp.mod.FOOD_RATT_CAP, 120) end
gpl-3.0
Joemag/Egg-Battle
lua/ErrorManager/init.lua
1
11454
--[[ Copyright 2014 Sergej Nisin Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]] local ERRORMANAGER_PATH = ERRORMANAGER_PATH or ({...})[1]:gsub("[%.\\/]init$", ""):gsub("%.", "/") local ErrorManager = {} local oldprint = print local printtable = {} function print(...) local stringtable = {} for i,v in ipairs({...}) do stringtable[i] = tostring(v) end table.insert(printtable, table.concat(stringtable, "\t")) oldprint(...) end local function error_printer(msg, layer) print((debug.traceback("Error: " .. tostring(msg), 1+(layer or 1)):gsub("\n[^\n]+$", ""))) end local function getTraceback(msg) msg = tostring(msg) error_printer(msg, 2) local trace = debug.traceback() local err = {} table.insert(err, "Error\n") table.insert(err, msg.."\n\n") local numl = 0 for l in string.gmatch(trace, "(.-)\n") do numl = numl + 1 if not string.match(l, "ErrorManager") and not string.match(l, "boot.lua") then l = string.gsub(l, "stack traceback:", "Traceback\n") table.insert(err, l) end end local p = table.concat(err, "\n") p = string.gsub(p, "\t", "") p = string.gsub(p, "%[string \"(.-)\"%]", "%1") return p end ErrorManager.trace = "" local this = {} function ErrorManager.load() this.scale = love.window.getPixelScale and love.window.getPixelScale() or 1 this.font = love.graphics.setNewFont(math.floor(14*this.scale)) this.bigfont = love.graphics.setNewFont(math.floor(30*this.scale)) this.hugefont = love.graphics.setNewFont(math.floor(40*this.scale)) this.eggimg = love.graphics.newImage("gfx/error.png") this.reportclicked = false this.sended = false this.senderror = false this.reportThread = nil this.reportChannel = nil end function ErrorManager.update() if this.reportThread and this.reportThread:getError( ) then print(this.reportThread:getError()) this.senderror = this.reportThread:getError() end if this.reportChannel then local value = this.reportChannel:pop() while value do if type(value) == "table" then if value.id == "content" then --self.content = value.value elseif value.id == "success" then this.sended = true elseif value.id == "error" then this.senderror = value.desc print("Error: ".. value.desc) end end value = this.reportChannel:pop() end end end function ErrorManager.draw() love.graphics.setColor(200, 0, 0) love.graphics.setFont(this.bigfont) local imgwidth = this.eggimg:getWidth() * this.scale love.graphics.printf("Oops, an error occurred", 30*this.scale, 40*this.scale, love.graphics.getWidth() - 20*this.scale - imgwidth) love.graphics.setColor(255, 255, 255) love.graphics.draw(this.eggimg, love.graphics.getWidth() - imgwidth, 10, 0, this.scale, this.scale) love.graphics.setFont(this.font) love.graphics.printf(ErrorManager.trace, 30, this.eggimg:getHeight() * this.scale + 30* this.scale, love.graphics.getWidth() - 60) --width, lines = Font:getWrap(text, width) local buttheight = 40*this.scale + this.hugefont:getHeight() -- Report button local butty = love.graphics.getHeight() - buttheight - 1 love.graphics.setColor(0, 200, 0) love.graphics.rectangle("fill", 1, butty, love.graphics.getWidth()-2, buttheight) love.graphics.setColor(255, 255, 255) love.graphics.rectangle("line", 1, butty, love.graphics.getWidth()-2, buttheight) if not this.reportclicked then love.graphics.setFont(this.hugefont) love.graphics.printf("Send report", 0, butty+20*this.scale, love.graphics.getWidth(), "center") else if this.senderror then love.graphics.setFont(this.bigfont) love.graphics.printf("Sending failed", 0, butty+20*this.scale, love.graphics.getWidth(), "center") elseif this.sended then love.graphics.setFont(this.hugefont) love.graphics.printf("Thank you", 0, butty+20*this.scale, love.graphics.getWidth(), "center") else love.graphics.setFont(this.hugefont) love.graphics.printf("Sending...", 0, butty+20*this.scale, love.graphics.getWidth(), "center") end end -- local butty = love.graphics.getHeight() - buttheight*2 - 1 -- Report button -- love.graphics.setColor(255, 255, 255) -- love.graphics.rectangle("fill", 1, butty, love.graphics.getWidth()-2, buttheight) -- love.graphics.setColor(0, 0, 0) -- love.graphics.rectangle("line", 1, butty, love.graphics.getWidth()-2, buttheight) -- love.graphics.printf("Send report", 0, butty+10*this.scale, love.graphics.getWidth(), "center") --love.graphics.printf(ErrorManager.trace, 30, 30, love.graphics.getWidth() - 60) end function ErrorManager.mousepressed(x, y, button) if not this.reportclicked then local buttheight = 40*this.scale + this.hugefont:getHeight() -- Report button local butty = love.graphics.getHeight() - buttheight - 1 if y > butty then this.reportclicked = true this.reportThread = love.thread.newThread( ERRORMANAGER_PATH.."/reportthread.lua" ) this.reportChannel = love.thread.getChannel( "sendreport" ) local reporttext = tostring(GAMEVERSION).."\n"..ErrorManager.trace.."\n\n---rendererinfo---\n" local rname, rversion, gvendor, gdevice = love.graphics.getRendererInfo( ) local os_string = love.system.getOS( ) local cores = love.system.getProcessorCount( ) local width,height,flags = love.window.getMode() local pixelscale = tostring(love.window.getPixelScale and love.window.getPixelScale()) local loveversion = "" if love.getVersion then local vmajor, vminor, revision, codename = love.getVersion( ) loveversion = string.format("Version %d.%d.%d: %s", vmajor, vminor, revision, codename) else loveversion = tostring(love._version) end reporttext = reporttext.."LOVE Version: ".. loveversion .."\n" reporttext = reporttext.."Renderer Name: ".. rname .."\n" reporttext = reporttext.."Renderer Version: ".. rversion .."\n" reporttext = reporttext.."Graphics Card Vendor: ".. gvendor .."\n" reporttext = reporttext.."Graphics Card: ".. gdevice .."\n" reporttext = reporttext.."OS: ".. os_string .."\n" reporttext = reporttext.."CPU Cores: ".. cores .."\n" reporttext = reporttext.."Width: ".. width .."\n" reporttext = reporttext.."Height: ".. height .."\n" reporttext = reporttext.."fullscreen: ".. tostring(flags["fullscreen"]) .."\n" reporttext = reporttext.."fullscreentype: ".. tostring(flags["fullscreentype"]) .."\n" reporttext = reporttext.."vsync: ".. tostring(flags["vsync"]) .."\n" reporttext = reporttext.."fsaa: ".. tostring(flags["fsaa"]) .."\n" reporttext = reporttext.."resizable: ".. tostring(flags["resizable"]) .."\n" reporttext = reporttext.."borderless: ".. tostring(flags["borderless"]) .."\n" reporttext = reporttext.."centered: ".. tostring(flags["centered"]) .."\n" reporttext = reporttext.."display: ".. tostring(flags["display"]) .."\n" reporttext = reporttext.."minwidth: ".. tostring(flags["minwidth"]) .."\n" reporttext = reporttext.."minheight: ".. tostring(flags["minheight"]) .."\n" reporttext = reporttext.."highdpi: ".. tostring(flags["highdpi"]) .."\n" reporttext = reporttext.."srgb: ".. tostring(flags["srgb"]) .."\n" reporttext = reporttext.."RAM used: ".. tostring(collectgarbage("count")) .."kb\n" reporttext = reporttext.."Pixelscale: ".. pixelscale .."\n" if love.graphics.isSupported then reporttext = reporttext.."\n--isSupported--\n" reporttext = reporttext.."canvas: ".. tostring(love.graphics.isSupported("canvas")) .."\n" reporttext = reporttext.."npot: ".. tostring(love.graphics.isSupported("npot")) .."\n" reporttext = reporttext.."subtractive: ".. tostring(love.graphics.isSupported("subtractive")) .."\n" reporttext = reporttext.."shader: ".. tostring(love.graphics.isSupported("shader")) .."\n" reporttext = reporttext.."hdrcanvas: ".. tostring(love.graphics.isSupported("hdrcanvas")) .."\n" reporttext = reporttext.."multicanvas: ".. tostring(love.graphics.isSupported("multicanvas")) .."\n" reporttext = reporttext.."mipmap: ".. tostring(love.graphics.isSupported("mipmap")) .."\n" reporttext = reporttext.."dxt: ".. tostring(love.graphics.isSupported("dxt")) .."\n" reporttext = reporttext.."bc5: ".. tostring(love.graphics.isSupported("bc5")) .."\n" reporttext = reporttext.."srgb: ".. tostring(love.graphics.isSupported("srgb")) .."\n" end if love.graphics.getSystemLimit then reporttext = reporttext.."\n--SystemLimit--\n" reporttext = reporttext.."pointsize: ".. love.graphics.getSystemLimit("pointsize") .."\n" reporttext = reporttext.."texturesize: ".. love.graphics.getSystemLimit("texturesize") .."\n" reporttext = reporttext.."multicanvas: ".. love.graphics.getSystemLimit("multicanvas") .."\n" reporttext = reporttext.."canvasfsaa: ".. love.graphics.getSystemLimit("canvasfsaa") .."\n" end reporttext = reporttext.."\n---printlog---\n" reporttext = reporttext.. table.concat(printtable, "\n") .."\n" this.reportThread:start(reporttext, "sendreport") end end end function ErrorManager.mousereleased(x, y, button) end function ErrorManager.run() if not love.window or not love.graphics or not love.event then return end if not love.graphics.isCreated() or not love.window.isCreated() then if not pcall(love.window.setMode, 800, 600) then return end end -- Reset state. if love.mouse then love.mouse.setVisible(true) love.mouse.setGrabbed(false) end if love.joystick then for i,v in ipairs(love.joystick.getJoysticks()) do v:setVibration() -- Stop all joystick vibrations. end end if love.audio then love.audio.stop() end love.graphics.reset() love.graphics.setBackgroundColor(89, 157, 220) love.graphics.setColor(255, 255, 255, 255) love.graphics.clear() love.graphics.origin() ErrorManager.load() while true do love.event.pump() for e, a, b, c in love.event.poll() do if e == "quit" then return end if e == "keypressed" and a == "escape" then return end if e == "mousepressed" then ErrorManager.mousepressed(a, b, c) end if e == "mousereleased" then ErrorManager.mousereleased(a, b, c) end end ErrorManager.update() love.graphics.clear() ErrorManager.draw() love.graphics.present() if love.timer then love.timer.sleep(0.1) end end end function love.errhand(msg) -- function love.window.getPixelScale(...) -- return 1 -- end if type(ErrorManager) == "table" then ErrorManager.msg = msg end local status, err = pcall(function() ErrorManager.trace = getTraceback(msg) end) ErrorManager.trace = ErrorManager.trace or "" if not status then ErrorManager.trace = ErrorManager.trace .. "\nError getting traceback:\n"..tostring(err).."\n" end local status, err = pcall(ErrorManager.run) if not status then ErrorManager.trace = ErrorManager.trace .. "\nError in ErrorManager.run:\n"..tostring(err).."\n" print(ErrorManager.trace) io.read() end end
apache-2.0
lichtl/darkstar
scripts/zones/Misareaux_Coast/npcs/_0p0.lua
14
2580
----------------------------------- -- Area: Misareaux Coast -- NPC: Dilapidated Gate -- @pos 260 9 -435 25 ----------------------------------- package.loaded["scripts/zones/Misareaux_Coast/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Misareaux_Coast/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) == AN_ETERNAL_MELODY and player:getVar("PromathiaStatus") == 1) then player:startEvent(0x0005); elseif (player:getCurrentMission(COP) == SHELTERING_DOUBT and player:getVar("PromathiaStatus") == 3) then player:startEvent(0x0007); elseif (player:getCurrentMission(COP) == A_PLACE_TO_RETURN and player:getVar("PromathiaStatus") == 1) then if (player:getVar("Warder_Aglaia_KILL") == 1 and player:getVar("Warder_Euphrosyne_KILL") == 1 and player:getVar("Warder_Thalia_KILL") == 1) then player:startEvent(0x000A); elseif (GetMobAction(16879893) == 0 and GetMobAction(16879894) == 0 and GetMobAction(16879895) == 0) then SpawnMob(16879893):updateClaim(player); SpawnMob(16879894):updateClaim(player); SpawnMob(16879895):updateClaim(player); else player:messageSpecial(DOOR_CLOSED); end else player:messageSpecial(DOOR_CLOSED); 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("PromathiaStatus",2); elseif (csid == 0x0007) then player:setVar("PromathiaStatus",0); player:completeMission(COP,SHELTERING_DOUBT); player:addMission(COP,THE_SAVAGE); elseif (csid == 0x000A) then player:setVar("PromathiaStatus",0); player:setVar("Warder_Aglaia_KILL",0); player:setVar("Warder_Euphrosyne_KILL",0); player:setVar("Warder_Thalia_KILL",0); player:completeMission(COP,A_PLACE_TO_RETURN); player:addMission(COP,MORE_QUESTIONS_THAN_ANSWERS); end end;
gpl-3.0
lichtl/darkstar
scripts/globals/spells/valor_minuet_ii.lua
27
1565
----------------------------------------- -- Spell: Valor Minuet II -- Grants Attack bonus to all allies. ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 10; if (sLvl+iLvl > 85) then power = power + math.floor((sLvl+iLvl-85) / 6); end if (power >= 32) then power = 32; end local iBoost = caster:getMod(MOD_MINUET_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); if (iBoost > 0) then power = power + 1 + (iBoost-1)*4; end power = power + caster:getMerit(MERIT_MINUET_EFFECT); if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_MINUET,power,0,duration,caster:getID(), 0, 2)) then spell:setMsg(75); end return EFFECT_MINUET; end;
gpl-3.0
lichtl/darkstar
scripts/zones/Abyssea-Konschtat/npcs/qm6.lua
10
1347
----------------------------------- -- Zone: Abyssea-Konschtat -- NPC: qm6 (???) -- Spawns Bloodguzzler -- @pos ? ? ? 15 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(2903,1) and trade:getItemCount() == 1) then -- Player has all the required items. if (GetMobAction(16838899) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(16838899):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 2903); -- Inform payer what items they need. 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
RunAwayDSP/darkstar
scripts/globals/spells/bluemagic/sub-zero_smash.lua
4
1822
----------------------------------------- -- Spell: Sub-zero Smash -- Additional Effect: Paralysis. Damage varies with TP -- Spell cost: 44 MP -- Monster Type: Aquans -- Spell Type: Physical (Blunt) -- Blue Magic Points: 4 -- Stat Bonus: HP+10 VIT+3 -- Level: 72 -- Casting Time: 1 second -- Recast Time: 30 seconds -- Skillchain Element(s): Fragmentation-IconFragmentation (can open/close Light-Icon Light with Fusion WSs and spells) -- Combos: Fast Cast ----------------------------------------- require("scripts/globals/bluemagic") require("scripts/globals/status") require("scripts/globals/magic") ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0 end function onSpellCast(caster,target,spell) local params = {} -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_CRITICAL params.dmgtype = dsp.damageType.BLUNT params.scattr = SC_FRAGMENTATION params.numhits = 1 params.multiplier = 1.95 params.tp150 = 1.25 params.tp300 = 1.25 params.azuretp = 1.25 params.duppercap = 72 params.str_wsc = 0.0 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.20 params.mnd_wsc = 0.3 params.chr_wsc = 0.0 damage = BluePhysicalSpell(caster, target, spell, params) damage = BlueFinalAdjustments(caster, target, spell, damage, params) local chance = math.random(1,20) if (damage > 0 and chance > 5) then local typeEffect = dsp.effect.PARALYSIS target:delStatusEffect(typeEffect) target:addStatusEffect(typeEffect,1,0,getBlueEffectDuration(caster,resist,typeEffect)) end return damage end
gpl-3.0
lichtl/darkstar
scripts/globals/spells/thunderstorm.lua
32
1193
-------------------------------------- -- Spell: Thunderstorm -- Changes the weather around target party member to "thundery." -------------------------------------- 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) target:delStatusEffectSilent(EFFECT_FIRESTORM); target:delStatusEffectSilent(EFFECT_SANDSTORM); target:delStatusEffectSilent(EFFECT_RAINSTORM); target:delStatusEffectSilent(EFFECT_WINDSTORM); target:delStatusEffectSilent(EFFECT_HAILSTORM); target:delStatusEffectSilent(EFFECT_THUNDERSTORM); target:delStatusEffectSilent(EFFECT_AURORASTORM); target:delStatusEffectSilent(EFFECT_VOIDSTORM); local merit = caster:getMerit(MERIT_STORMSURGE); local power = 0; if merit > 0 then power = merit + caster:getMod(MOD_STORMSURGE_EFFECT) + 2; end target:addStatusEffect(EFFECT_THUNDERSTORM,power,0,180); return EFFECT_THUNDERSTORM; end;
gpl-3.0
lichtl/darkstar
scripts/zones/Uleguerand_Range/npcs/HomePoint#3.lua
27
1258
----------------------------------- -- Area: Uleguerand_Range -- NPC: HomePoint#3 -- @pos ----------------------------------- package.loaded["scripts/zones/Uleguerand_Range/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Uleguerand_Range/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fe, 78); 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 == 0x21fe) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
scscgit/scsc_wildstar_addons
MarketplaceAuctionEnhanced/MarketplaceAuctionEnhanced.lua
1
9543
----------------------------------------------------------------------------------------------- -- Client Lua Script for MarketplaceAuctionEnhanced -- Copyright (c) NCsoft. All rights reserved ----------------------------------------------------------------------------------------------- require "Window" require "GameLib" require "Money" require "Item" require "Unit" require "MarketplaceLib" require "ItemAuction" local lastBuyVScrollPos = 0 local customPageCounter = 0 local categoryPressed = false ----------------------------------------------------------------------------------------------- -- MarketplaceAuctionEnhanced Module Definition ----------------------------------------------------------------------------------------------- local MarketplaceAuctionEnhanced = {} ----------------------------------------------------------------------------------------------- -- Initialization ----------------------------------------------------------------------------------------------- function MarketplaceAuctionEnhanced:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end function MarketplaceAuctionEnhanced:Init() local bHasConfigureFunction = false local strConfigureButtonText = "" local tDependencies = {"MarketplaceAuction"} Apollo.RegisterAddon(self, bHasConfigureFunction, strConfigureButtonText, tDependencies) end ----------------------------------------------------------------------------------------------- -- MarketplaceAuctionEnhanced OnLoad ----------------------------------------------------------------------------------------------- function MarketplaceAuctionEnhanced:OnLoad() -- load our form file self.xmlDoc = XmlDoc.CreateFromFile("MarketplaceAuctionEnhanced.xml") -- Get MarketplaceAuction addon self.MarketplaceAuction = Apollo.GetAddon("MarketplaceAuction") self:InitializeTimer() self:InitializeHooks() Print("onload ") end -- Timers function MarketplaceAuctionEnhanced:InitializeTimer() Apollo.RegisterTimerHandler("VScrollTimer", "OnVScrollTimer", self) end ----------------------------------------------------------------------------------------------- -- MarketplaceAuctionEnhanced Override Functions ----------------------------------------------------------------------------------------------- function MarketplaceAuctionEnhanced:InitializeHooks() local MarketplaceAuction = Apollo.GetAddon("MarketplaceAuction") -- Called when user clicks on an item (row) inside the AH local fnOldOnRowSelectBtnCheck = MarketplaceAuction.OnRowSelectBtnCheck MarketplaceAuction.OnRowSelectBtnCheck = function(wndHandler, wndControl) fnOldOnRowSelectBtnCheck(wndHandler, wndControl) lastBuyVScrollPos = MarketplaceAuction.wndMain:FindChild("BuyContainer"):FindChild("SearchResultList"):GetVScrollPos() end -- Function called when sort options combo (ending soon, newly listed...) is changed local fnOldOnSortOptionsUseableToggle = MarketplaceAuction.OnSortOptionsUseableToggle MarketplaceAuction.OnSortOptionsUseableToggle = function(wndHandler, wndControl) fnOldOnSortOptionsUseableToggle(wndHandler, wndControl) -- SortFlyoutStat and SortOptionsTimeLH and etc -- Reset scrollpos and page when changing search filter lastBuyVScrollPos = 0 customPageCounter = 0 MarketplaceAuction:OnRefreshBtn() end -- Function to init buy window with proper scroll positions local fnOldInitializeBuy = MarketplaceAuction.InitializeBuy MarketplaceAuction.InitializeBuy = function() fnOldInitializeBuy(MarketplaceAuction) local strSearchQuery = tostring(MarketplaceAuction.wndMain:FindChild("SearchEditBox"):GetText()) -- if curpage isnt valid (happens at startup) then always go to page 0 if MarketplaceAuction.nCurPage == nil or MarketplaceAuction.nCurPage < 0 then MarketplaceAuction.fnLastSearch(0) -- if user has written a search string then always go to page 0 or it will fail to list the results elseif strSearchQuery and string.len(strSearchQuery) > 0 then MarketplaceAuction.fnLastSearch(0) MarketplaceAuction:RequestUpdates() -- got here after user clicked on any category, reset paging elseif categoryPressed == true then categoryPressed = false customPageCounter = 0 lastBuyVScrollPos = 0 MarketplaceAuction.fnLastSearch(0) -- else, go back to the page we were on earlier (before searching, buying, bidding, selling) else MarketplaceAuction.fnLastSearch(customPageCounter) -- Create new timer to restore the previous vertical scroll position after changing page Apollo.StopTimer("VScrollTimer") Apollo.CreateTimer("VScrollTimer", 1, false) end end -- Function called when "go to first buy page" button is pressed local fnOldOnBuySearchFirstBtn = MarketplaceAuction.OnBuySearchFirstBtn MarketplaceAuction.OnBuySearchFirstBtn = function(wndHandler, wndControl) fnOldOnBuySearchFirstBtn(wndHandler, wndControl) customPageCounter = 0 end -- Function called when "go to previous buy page" button is pressed local fnOldOnOnBuySearchPrevBtn = MarketplaceAuction.OnBuySearchPrevBtn MarketplaceAuction.OnBuySearchPrevBtn = function(wndHandler, wndControl) fnOldOnOnBuySearchPrevBtn(wndHandler, wndControl) customPageCounter = MarketplaceAuction.nCurPage - 1 end -- Function called when "go to next buy page" button is pressed local fnOldOnBuySearchNextBtn = MarketplaceAuction.OnBuySearchNextBtn MarketplaceAuction.OnBuySearchNextBtn = function(wndHandler, wndControl) fnOldOnBuySearchNextBtn(wndHandler, wndControl) customPageCounter = MarketplaceAuction.nCurPage + 1 end -- Function called when "go to last buy page" button is pressed local fnOldOnBuySearchLastBtn = MarketplaceAuction.OnBuySearchLastBtn MarketplaceAuction.OnBuySearchLastBtn = function(wndHandler, wndControl) fnOldOnBuySearchLastBtn(wndHandler, wndControl) customPageCounter = math.floor(MarketplaceAuction.nTotalResults / MarketplaceLib.kAuctionSearchPageSize) end local fnOldInitialize = MarketplaceAuction.Initialize MarketplaceAuction.Initialize= function() fnOldInitialize(MarketplaceAuction) -- Force window to open buy decor category as the default self:SetDecorAsDefaultCategory() end --------------------------------------------------------------------------------------------------- -- We would like to know when a user buy/bid items to stay on that AH page, problem is that code is hidden for us :( -- The workaround is to check for when user clicks any category/subcategory and in that case reset current page to 0 -- Ugly hack: InitializeBuy is being called beefore OnCategoryTopBtnCheck & OnCategoryMidBtnCheck, meaning it won't -- see the changed bool value, ttherefore we call InitializeBuy a second time. --------------------------------------------------------------------------------------------------- local fnOldOnCategoryTopBtnCheck = MarketplaceAuction.OnCategoryTopBtnCheck MarketplaceAuction.OnCategoryTopBtnCheck = function(wndHandler, wndControl) fnOldOnCategoryTopBtnCheck(wndHandler, wndControl) categoryPressed = true self.MarketplaceAuction:InitializeBuy() end local fnOldOnCategoryMidBtnCheck = MarketplaceAuction.OnCategoryMidBtnCheck MarketplaceAuction.OnCategoryMidBtnCheck= function(wndHandler, wndControl) fnOldOnCategoryMidBtnCheck(wndHandler, wndControl) categoryPressed = true self.MarketplaceAuction:InitializeBuy() end end --------------------------------------------------------------------------------------------------- -- MarketplaceAuctionEnhanced Internal Functions --------------------------------------------------------------------------------------------------- function MarketplaceAuctionEnhanced:SetDecorAsDefaultCategory() for idx, wndTopItem in pairs(self.MarketplaceAuction.wndMain:FindChild("MainCategoryContainer"):GetChildren()) do if idx == 1 then -- Uncheck the "Heavy armor -> All" category wndTopItem:FindChild("CategoryTopBtn"):SetCheck(false) end if idx == 8 then -- Check the "Housing -> decor" category wndTopItem:FindChild("CategoryTopBtn"):SetCheck(true) local categoryTopItem = wndTopItem:FindChild("CategoryTopBtn"):GetData() local categoryTopList = categoryTopItem:FindChild("CategoryTopList") for idG, wndMidItem in pairs(categoryTopList:GetChildren()) do if idG == 2 then --"All" button is first in list of miditems, we want second button for "Decor" local midButton = wndMidItem:FindChild("CategoryMidBtn") midButton:SetCheck(true) -- Set internal values so RefreshBtn() can do its magic self.MarketplaceAuction.nSearchId = midButton:GetData()[1] self.MarketplaceAuction.strSearchEnum = midButton:GetData()[2] end end end end self.MarketplaceAuction:OnRefreshBtn(self.MarketplaceAuction) self.MarketplaceAuction:OnResizeCategories(self.MarketplaceAuction) end function MarketplaceAuctionEnhanced:OnVScrollTimer() if self.MarketplaceAuction.wndMain and self.MarketplaceAuction.wndMain:IsValid() then Apollo.StopTimer("VScrollTimer") self.MarketplaceAuction.wndMain:FindChild("SearchResultList"):SetVScrollPos(lastBuyVScrollPos) end end ----------------------------------------------------------------------------------------------- -- MarketplaceAuctionEnhanced Instance ----------------------------------------------------------------------------------------------- local MarketplaceAuctionEnhancedInst = MarketplaceAuctionEnhanced:new() MarketplaceAuctionEnhancedInst:Init()
mit
RunAwayDSP/darkstar
scripts/zones/Norg/npcs/Parlemaille.lua
14
1495
----------------------------------- -- Area: Norg -- NPC: Parlemaille -- Standard Info NPC ----------------------------------- require("scripts/globals/pathfind"); ----------------------------------- local path = { -20.369047, 1.097733, -24.847025, -20.327482, 1.097733, -25.914215, -20.272402, 1.097733, -27.108938, -20.094927, 1.097733, -26.024536, -19.804167, 1.097733, -13.467897, -20.166626, 1.097733, -29.047626, -20.415781, 1.097733, -30.099203, -20.956963, 1.097733, -31.050713, -21.629911, 1.097733, -31.904819, -22.395691, 1.097733, -32.705379, -23.187502, 1.097733, -33.450657, -24.126440, 1.097733, -33.993565, -25.146549, 1.097733, -34.370991, -24.118807, 1.097733, -34.021263, -23.177444, 1.097733, -33.390072, -22.360268, 1.097733, -32.672077, -21.594837, 1.097733, -31.877075, -20.870659, 1.097733, -30.991661, -20.384108, 1.097733, -29.968874, -20.212332, 1.097733, -28.944513, -20.144073, 1.097733, -27.822714, -20.110937, 1.097733, -26.779232, -19.802849, 1.097733, -13.406805 }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(dsp.path.first(path)); -- onPath(npc); end; function onPath(npc) dsp.path.patrol(npc, path); end; function onTrade(player,npc,trade) end; function onTrigger(player,npc) player:startEvent(88); npc:wait(); end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option,npc) npc:wait(0); end;
gpl-3.0
lichtl/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
lichtl/darkstar
scripts/zones/Ship_bound_for_Selbina/npcs/Maera.lua
14
1361
----------------------------------- -- Area: Ship bound for Selbina -- NPC: Maera -- Type: Standard Merchant NPC -- @pos -1.139 -2.101 -9.000 220 ----------------------------------- package.loaded["scripts/zones/Ship_bound_for_Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Ship_bound_for_Selbina/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,MAERA_SHOP_DIALOG); stock = {0x1010,910, -- Potion 0x1020,4832, -- Ether 0x1034,316, -- Antidote 0x1036,2595, -- Eye Drops 0x1037,800} -- Echo Drops 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
DaCyclops/robotic-combinators
prototypes/signals-robotic.lua
1
2682
data:extend( { { type = "virtual-signal", name = "signal-robot-log-idle", icon = "__robotic-combinators__/graphics/signal-robot-log-idle.png", subgroup = "virtual-signal-number", order = "r[robots]-[01]" }, { type = "virtual-signal", name = "signal-robot-log-total", icon = "__robotic-combinators__/graphics/signal-robot-log-total.png", subgroup = "virtual-signal-number", order = "r[robots]-[02]" }, { type = "virtual-signal", name = "signal-robot-con-idle", icon = "__robotic-combinators__/graphics/signal-robot-con-idle.png", subgroup = "virtual-signal-number", order = "r[robots]-[03]" }, { type = "virtual-signal", name = "signal-robot-con-total", icon = "__robotic-combinators__/graphics/signal-robot-con-total.png", subgroup = "virtual-signal-number", order = "r[robots]-[04]" }, { type = "virtual-signal", name = "signal-robot-construction-radius", icon = "__robotic-combinators__/graphics/signal-robot-con-radius.png", subgroup = "virtual-signal-number", order = "r[robots]-[05]" }, { type = "virtual-signal", name = "signal-robot-roboports", icon = "__robotic-combinators__/graphics/signal-robot-roboports.png", subgroup = "virtual-signal-number", order = "r[robots]-[06]" }, { type = "virtual-signal", name = "signal-robot-storage-count", icon = "__robotic-combinators__/graphics/signal-robot-storage.png", subgroup = "virtual-signal-number", order = "r[robots]-[07]" }, { type = "virtual-signal", name = "signal-robot-storage-empty", icon = "__robotic-combinators__/graphics/signal-robot-storage-empty.png", subgroup = "virtual-signal-number", order = "r[robots]-[08]" }, { type = "virtual-signal", name = "signal-robot-pending-requesters", icon = "__robotic-combinators__/graphics/signal-robot-pending-requester.png", subgroup = "virtual-signal-number", order = "r[robots]-[09]" }, { type = "virtual-signal", name = "signal-robot-charging-count", icon = "__robotic-combinators__/graphics/signal-robot-now-charging.png", subgroup = "virtual-signal-number", order = "r[robots]-[10]" }, { type = "virtual-signal", name = "signal-robot-to-charge-count", icon = "__robotic-combinators__/graphics/signal-robot-to-charge.png", subgroup = "virtual-signal-number", order = "r[robots]-[11]" }, { type = "virtual-signal", name = "signal-robot-sad-robots", icon = "__robotic-combinators__/graphics/signal-robot-sad.png", subgroup = "virtual-signal-number", order = "r[robots]-[12]" }, })
mit
lichtl/darkstar
scripts/zones/RuLude_Gardens/npcs/Pherimociel.lua
5
2703
----------------------------------- -- Area: Ru'Lude Gardens -- NPC: Pherimociel -- Involved in mission: COP 1-2 -- @pos -31.627 1.002 67.956 243 ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/RuLude_Gardens/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local Hrandom =math.random(); if (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") == 0) then player:startEvent(0x0018); elseif (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") == 1) then player:startEvent(0x0019); elseif (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Tenzen_s_Path") == 3) then player:startEvent(0x003A); elseif (player:getCurrentMission(COP) == FOR_WHOM_THE_VERSE_IS_SUNG and player:getVar("PromathiaStatus") == 0) then player:startEvent(0x273E); elseif (player:getCurrentMission(COP) == A_PLACE_TO_RETURN and player:getVar("PromathiaStatus") == 1) then if (Hrandom<0.2) then player:startEvent(0x001B); elseif (Hrandom<0.6) then player:startEvent(0x001C); else player:startEvent(0x001D); end elseif (player:getCurrentMission(COP) == MORE_QUESTIONS_THAN_ANSWERS and player:getVar("PromathiaStatus") == 0) then player:startEvent(0x2741); else player:startEvent(0x009b); 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 == 0x0018) then player:setVar("PromathiaStatus",1); -- first cs mission 1.2 has been seen YOU CAN NOW ENTER TO PROMYVION player:setVar("FirstPromyvionHolla",1); player:setVar("FirstPromyvionMea",1); player:setVar("FirstPromyvionDem",1); elseif (csid == 0x003A) then player:setVar("COP_Tenzen_s_Path",4); elseif (csid == 0x273E or 0x2741) then player:setVar("PromathiaStatus",1); end end;
gpl-3.0
zegotinha/LiveShift
vlclib/windows/lua/intf/telnet.lua
2
8395
--[==========================================================================[ telnet.lua: VLM interface plugin --[==========================================================================[ Copyright (C) 2007 the VideoLAN team $Id$ Authors: Antoine Cellerier <dionoea at videolan dot 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. --]==========================================================================] description= [============================================================================[ VLM Interface plugin Copy (features wise) of the original VLC modules/control/telnet.c module. Differences are: * it's in Lua * 'lock' command to lock the telnet promt * possibility to listen on different hosts including stdin for example: listen on stdin: vlc -I lua --lua-intf telnet --lua-config "telnet={host='*console'}" listen on stdin + 2 ports on localhost: vlc -I lua --lua-intf telnet --lua-config "telnet={hosts={'localhost:4212','localhost:5678','*console'}}" Configuration options setable throught the --lua-config option are: * hosts: A list of hosts to listen on (see examples above). * host: A host to listen on. (won't be used if `hosts' is set) * password: The password used for remote clients. * prompt: The prompt. ]============================================================================] require "host" --[[ Some telnet command special characters ]] WILL = "\251" -- Indicates the desire to begin performing, or confirmation that you are now performing, the indicated option. WONT = "\252" -- Indicates the refusal to perform, or continue performing, the indicated option. DO = "\253" -- Indicates the request that the other party perform, or confirmation that you are expecting the other party to perform, the indicated option. DONT = "\254" -- Indicates the demand that the other party stop performing, or confirmation that you are no longer expecting the other party to perform, the indicated option. IAC = "\255" -- Interpret as command ECHO = "\001" --[[ Client status change callbacks ]] function on_password( client ) if client.type == host.client_type.net then client:send( "Password: " ..IAC..WILL..ECHO ) else -- no authentication needed on stdin client:switch_status( host.status.read ) end end function on_read( client ) client:send( config.prompt and tostring(config.prompt) or "> " ) end function on_write( client ) end --[[ Misc functions ]] function telnet_commands( client ) -- remove telnet command replies from the client's data client.buffer = string.gsub( client.buffer, IAC.."["..DO..DONT..WILL..WONT.."].", "" ) end function vlm_message_to_string(client,message,prefix) local prefix = prefix or "" if message.value then client:append(prefix .. message.name .. " : " .. message.value) else client:append(prefix .. message.name) end if message.children then for i,c in ipairs(message.children) do vlm_message_to_string(client,c,prefix.." ") end end end --[[ Configure the host ]] h = host.host() h.status_callbacks[host.status.password] = on_password h.status_callbacks[host.status.read] = on_read h.status_callbacks[host.status.write] = on_write h:listen( config.hosts or config.host or "localhost:4212" ) password = config.password or "admin" --[[ Launch vlm ]] vlm = vlc.vlm() --[[ Commands ]] function shutdown(client) h:broadcast("Shutting down.\r\n") vlc.msg.err("shutdown requested") vlc.misc.quit() return true end function logout(client) client:del() return true end function quit(client) if client.type == host.client_type.net then return logout(client) else return shutdown(client) end end function lock(client) client:send("\r\n") client:switch_status( host.status.password ) client.buffer = "" return false end function print_text(text) return function(client) client:append(string.gsub(text,"\r?\n","\r\n")) return true end end function help(client) client:append(" Telnet Specific Commands:") for c,t in pairs(commands) do client:append(" "..c.." : "..t.help) end return true end commands = { ["shutdown"] = { func = shutdown, help = "shutdown VLC" }, ["quit"] = { func = quit, help = "logout from telnet/shutdown VLC from local shell" }, ["logout"] = { func = logout, help = "logout" }, ["lock"] = { func = lock, help = "lock the telnet prompt" }, ["description"] = { func = print_text(description), help = "describe this module" }, ["license"] = { func = print_text(vlc.misc.license()), help = "print VLC's license message" }, ["help"] = { func = help, help = "show this help", dovlm = true }, } function client_command( client ) local cmd = client.buffer client.buffer = "" if not commands[cmd] or not commands[cmd].func or commands[cmd].dovlm then -- if it's not an interface specific command, it has to be a VLM command local message, vlc_err = vlm:execute_command( cmd ) vlm_message_to_string( client, message ) if not commands[cmd] or not commands[cmd].func and not commands[cmd].dovlm then if vlc_err ~= 0 then client:append( "Type `help' for help." ) end return true end end ok, msg = pcall( commands[cmd].func, client ) if not ok then client:append( "Error in `"..cmd.."' "..msg ) return true end return msg end --[[ The main loop ]] while not vlc.misc.should_die() do local w, r = h:accept_and_select() -- Handle writes for _, client in pairs(w) do local len = client:send() client.buffer = string.sub(client.buffer,len+1) if client.buffer == "" then client:switch_status( host.status.read ) end end -- Handle reads for _, client in pairs(r) do local str = client:recv(1000) if not str or str == "" -- the telnet client program has left or (client.type == host.client_type.net and str == "\004") then -- Caught a ^D client.cmds = "quit\n" else client.cmds = client.cmds .. str end client.buffer = "" -- split the command at the first '\n' while string.find(client.cmds, "\n") do -- save the buffer to send to the client local saved_buffer = client.buffer -- get the next command local index = string.find(client.cmds, "\n") client.buffer = string.gsub(string.sub(client.cmds, 0, index - 1), "^%s*(.-)%s*$", "%1") client.cmds = string.sub(client.cmds, index + 1) -- Remove telnet commands from the command line if client.type == host.client_type.net then telnet_commands( client ) end -- Run the command if client.status == host.status.password then if client.buffer == password then client:send( IAC..WONT..ECHO.."\r\nWelcome, Master\r\n" ) client.buffer = "" client:switch_status( host.status.write ) elseif client.buffer == "quit" then client_command( client ) else client:send( "\r\nWrong password\r\nPassword: " ) client.buffer = "" end elseif client_command( client ) then client:switch_status( host.status.write ) end client.buffer = saved_buffer .. client.buffer end end end --[[ Clean up ]] vlm = nil
gpl-3.0
RunAwayDSP/darkstar
scripts/globals/items/bowl_of_soy_ramen_+1.lua
11
1526
----------------------------------------- -- ID: 6459 -- Item: bowl_of_soy_ramen_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- HP +55 -- STR +6 -- VIT +6 -- AGI +4 -- Attack +11% (cap 175) -- Ranged Attack +11% (cap 175) -- Resist Slow +15 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,3600,6459) end function onEffectGain(target,effect) target:addMod(dsp.mod.HP, 55) target:addMod(dsp.mod.STR, 6) target:addMod(dsp.mod.VIT, 6) target:addMod(dsp.mod.AGI, 4) target:addMod(dsp.mod.FOOD_ATTP, 11) target:addMod(dsp.mod.FOOD_ATT_CAP, 175) target:addMod(dsp.mod.FOOD_RATTP, 11) target:addMod(dsp.mod.FOOD_RATT_CAP, 175) target:addMod(dsp.mod.SLOWRES, 15) end function onEffectLose(target, effect) target:delMod(dsp.mod.HP, 55) target:delMod(dsp.mod.STR, 6) target:delMod(dsp.mod.VIT, 6) target:delMod(dsp.mod.AGI, 4) target:delMod(dsp.mod.FOOD_ATTP, 11) target:delMod(dsp.mod.FOOD_ATT_CAP, 175) target:delMod(dsp.mod.FOOD_RATTP, 11) target:delMod(dsp.mod.FOOD_RATT_CAP, 175) target:delMod(dsp.mod.SLOWRES, 15) end
gpl-3.0
lichtl/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/HomePoint#3.lua
27
1287
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: HomePoint#3 -- @pos -108 -6 -108 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fe, 107); 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 == 0x21fe) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
lichtl/darkstar
scripts/zones/Jugner_Forest/Zone.lua
4
4186
----------------------------------- -- -- Zone: Jugner_Forest (104) -- ----------------------------------- package.loaded[ "scripts/zones/Jugner_Forest/TextIDs"] = nil; package.loaded["scripts/globals/chocobo_digging"] = nil; ----------------------------------- require("scripts/zones/Jugner_Forest/TextIDs"); require("scripts/globals/zone"); require("scripts/globals/icanheararainbow"); require("scripts/globals/conquest"); require("scripts/globals/chocobo_digging"); ----------------------------------- -- Chocobo Digging vars ----------------------------------- local itemMap = { -- itemid, abundance, requirement { 4504, 152, DIGREQ_NONE }, { 688, 182, DIGREQ_NONE }, { 697, 83, DIGREQ_NONE }, { 4386, 3, DIGREQ_NONE }, { 17396, 129, DIGREQ_NONE }, { 691, 144, DIGREQ_NONE }, { 918, 8, DIGREQ_NONE }, { 699, 76, DIGREQ_NONE }, { 4447, 38, DIGREQ_NONE }, { 695, 45, DIGREQ_NONE }, { 4096, 100, DIGREQ_NONE }, -- all crystals { 690, 15, DIGREQ_BORE }, { 1446, 8, DIGREQ_BORE }, { 702, 23, DIGREQ_BORE }, { 701, 8, DIGREQ_BORE }, { 696, 30, DIGREQ_BORE }, { 4570, 10, DIGREQ_MODIFIER }, { 4487, 11, DIGREQ_MODIFIER }, { 4409, 12, DIGREQ_MODIFIER }, { 1188, 10, DIGREQ_MODIFIER }, { 4532, 12, DIGREQ_MODIFIER }, }; local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED }; ----------------------------------- -- onChocoboDig ----------------------------------- function onChocoboDig(player, precheck) return chocoboDig(player, itemMap, precheck, messageArray); end; ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local manuals = {17203883,17203884}; SetFieldManual(manuals); local vwnpc = {17203933,17203934,17203935}; SetVoidwatchNPC(vwnpc); zone:registerRegion(1, -484, 10, 292, 0, 0, 0); -- Sets Mark for "Under Oath" Quest cutscene. -- Fraelissa SetRespawnTime(17203447, 900, 10800); SetRegionalConquestOverseers(zone:getRegionID()); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn( player, prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos( 342, -5, 15.117, 169); end if (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow cs = 0x000f; 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) if (region:GetRegionID() == 1) then if (player:getVar("UnderOathCS") == 7) then -- Quest: Under Oath - PLD AF3 player:startEvent(0x000E); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x000f) then lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x000f) then lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow elseif (csid == 0x000E) then player:setVar("UnderOathCS",8); -- Quest: Under Oath - PLD AF3 end end;
gpl-3.0
sjznxd/lc-20130222
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
RunAwayDSP/darkstar
scripts/globals/spells/diaga_iii.lua
11
2314
----------------------------------------- -- Spell: Diaga III -- Lowers an enemy's defense and gradually deals light elemental damage. ----------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/magic") require("scripts/globals/utils") require("scripts/globals/msg") ----------------------------------------- function onMagicCastingCheck(caster, target, spell) return 0 end function onSpellCast(caster, target, spell) local basedmg = caster:getSkillLevel(dsp.skill.ENFEEBLING_MAGIC) / 3 local params = {} params.dmg = basedmg params.multiplier = 5 params.skillType = dsp.skill.ENFEEBLING_MAGIC params.attribute = dsp.mod.INT params.hasMultipleTargetReduction = false params.diff = caster:getStat(dsp.mod.INT) - target:getStat(dsp.mod.INT) params.attribute = dsp.mod.INT params.skillType = dsp.skill.ENFEEBLING_MAGIC params.bonus = 1.0 -- Calculate raw damage local dmg = calculateMagicDamage(caster, target, spell, params) -- Softcaps at 60, should always do at least 1 dmg = utils.clamp(dmg, 1, 60) -- Get resist multiplier (1x if no resist) local resist = applyResistance(caster, target, spell, params) -- Get the resisted damage dmg = dmg * resist -- Add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = addBonuses(caster, spell, target, dmg) -- Add in target adjustment dmg = adjustForTarget(target, dmg, spell:getElement()) -- Add in final adjustments including the actual damage dealt local final = finalMagicAdjustments(caster, target, spell, dmg) -- Calculate duration and bonus local duration = calculateDuration(120, spell:getSkillType(), spell:getSpellGroup(), caster, target) local dotBonus = caster:getMod(dsp.mod.DIA_DOT) -- Dia Wand -- Check for Bio local bio = target:getStatusEffect(dsp.effect.BIO) -- Do it! target:addStatusEffect(dsp.effect.DIA, 3 + dotBonus, 3, duration, 0, 20, 3) spell:setMsg(dsp.msg.basic.MAGIC_DMG) -- Try to kill same tier Bio (non-default behavior) if BIO_OVERWRITE == 1 and bio ~= nil then if bio:getPower() <= 3 then target:delStatusEffect(dsp.effect.BIO) end end return final end
gpl-3.0
lichtl/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
RunAwayDSP/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/Animated_Claymore.lua
9
1185
----------------------------------- -- Area: Dynamis - Xarcabard -- Mob: Animated Claymore ----------------------------------- require("scripts/globals/status"); local ID = require("scripts/zones/Dynamis-Xarcabard/IDs"); ----------------------------------- function onMobEngaged(mob,target) if (mob:AnimationSub() == 3) then SetDropRate(102,1574,1000); else SetDropRate(102,1574,0); end target:showText(mob,ID.text.ANIMATED_CLAYMORE_DIALOG); SpawnMob(17330365):updateEnmity(target); SpawnMob(17330366):updateEnmity(target); SpawnMob(17330367):updateEnmity(target); SpawnMob(17330372):updateEnmity(target); SpawnMob(17330373):updateEnmity(target); SpawnMob(17330374):updateEnmity(target); end; function onMobFight(mob,target) -- TODO: add battle dialog end; function onMobDisengage(mob) mob:showText(mob,ID.text.ANIMATED_CLAYMORE_DIALOG+2); end; function onMobDeath(mob, player, isKiller) player:showText(mob,ID.text.ANIMATED_CLAYMORE_DIALOG+1); DespawnMob(17330365); DespawnMob(17330366); DespawnMob(17330367); DespawnMob(17330372); DespawnMob(17330373); DespawnMob(17330374); end;
gpl-3.0
NiLuJe/koreader
plugins/vocabbuilder.koplugin/db.lua
3
18425
local DataStorage = require("datastorage") local Device = require("device") local SQ3 = require("lua-ljsqlite3/init") local LuaData = require("luadata") local logger = require("logger") local db_location = DataStorage:getSettingsDir() .. "/vocabulary_builder.sqlite3" local DB_SCHEMA_VERSION = 20221002 local VOCABULARY_DB_SCHEMA = [[ -- To store looked up words CREATE TABLE IF NOT EXISTS "vocabulary" ( "word" TEXT NOT NULL UNIQUE, "title_id" INTEGER, "create_time" INTEGER NOT NULL, "review_time" INTEGER, "due_time" INTEGER NOT NULL, "review_count" INTEGER NOT NULL DEFAULT 0, "prev_context" TEXT, "next_context" TEXT, "streak_count" INTEGER NOT NULL DEFAULT 0, PRIMARY KEY("word") ); CREATE TABLE IF NOT EXISTS "title" ( "id" INTEGER NOT NULL UNIQUE, "name" TEXT UNIQUE, "filter" INTEGER NOT NULL DEFAULT 1, PRIMARY KEY("id") ); CREATE INDEX IF NOT EXISTS due_time_index ON vocabulary(due_time); CREATE INDEX IF NOT EXISTS title_name_index ON title(name); ]] local VocabularyBuilder = { path = db_location } function VocabularyBuilder:init() VocabularyBuilder:createDB() end function VocabularyBuilder:selectCount(vocab_widget) local db_conn = SQ3.open(db_location) local where_clause = vocab_widget:check_reverse() and " WHERE due_time <= " .. vocab_widget.reload_time or "" local sql = "SELECT count(0) FROM vocabulary INNER JOIN title ON filter=true AND title_id=id" .. where_clause .. ";" local count = tonumber(db_conn:rowexec(sql)) db_conn:close() return count end function VocabularyBuilder:createDB() local db_conn = SQ3.open(db_location) -- Make it WAL, if possible if Device:canUseWAL() then db_conn:exec("PRAGMA journal_mode=WAL;") else db_conn:exec("PRAGMA journal_mode=TRUNCATE;") end -- Create db db_conn:exec(VOCABULARY_DB_SCHEMA) -- Check version local db_version = tonumber(db_conn:rowexec("PRAGMA user_version;")) if db_version == 0 then self:insertLookupData(db_conn) -- Update version db_conn:exec(string.format("PRAGMA user_version=%d;", DB_SCHEMA_VERSION)) elseif db_version < DB_SCHEMA_VERSION then local ok, re local log = function(msg) logger.warn("[vocab builder db migration]", msg) end if db_version < 20220608 then ok, re = pcall(db_conn.exec, db_conn, "ALTER TABLE vocabulary ADD prev_context TEXT;") if not ok then log(re) end ok, re = pcall(db_conn.exec, db_conn, "ALTER TABLE vocabulary ADD next_context TEXT;") if not ok then log(re) end ok, re = pcall(db_conn.exec, db_conn, "ALTER TABLE vocabulary ADD title_id INTEGER;") if not ok then log(re) end ok, re = pcall(db_conn.exec, db_conn, "INSERT OR IGNORE INTO title (name) SELECT DISTINCT book_title FROM vocabulary;") if not ok then log(re) end ok, re = pcall(db_conn.exec, db_conn, "UPDATE vocabulary SET title_id = (SELECT id FROM title WHERE name = book_title);") if not ok then log(re) end ok, re = pcall(db_conn.exec, db_conn, "ALTER TABLE vocabulary DROP book_title;") if not ok then log(re) end end if db_version < 20220730 then ok, re = pcall(db_conn.exec, db_conn, "ALTER TABLE title ADD filter INTEGER NOT NULL DEFAULT 1;") if not ok then log(re) end end if db_version < 20221002 then ok, re = pcall(db_conn.exec, db_conn, [[ ALTER TABLE vocabulary ADD streak_count INTEGER NULL DEFAULT 0; UPDATE vocabulary SET streak_count = review_count; ]]) if not ok then log(re) end end db_conn:exec("CREATE INDEX IF NOT EXISTS title_id_index ON vocabulary(title_id);") -- Update version db_conn:exec(string.format("PRAGMA user_version=%d;", DB_SCHEMA_VERSION)) end db_conn:close() end function VocabularyBuilder:insertLookupData(db_conn) local file_path = DataStorage:getSettingsDir() .. "/lookup_history.lua" local lookup_history = LuaData:open(file_path, "LookupHistory") if lookup_history:has("lookup_history") then local lookup_history_table = lookup_history:readSetting("lookup_history") local book_titles = {} local stmt = db_conn:prepare("INSERT INTO title (name) values (?);") for i = #lookup_history_table, 1, -1 do local book_title = lookup_history_table[i].book_title or "" if not book_titles[book_title] then stmt:bind(book_title) stmt:step() stmt:clearbind():reset() book_titles[book_title] = true end end local words = {} local insert_sql = [[INSERT OR REPLACE INTO vocabulary (word, title_id, create_time, due_time, review_time) values (?, (SELECT id FROM title WHERE name = ?), ?, ?, ?);]] stmt = db_conn:prepare(insert_sql) for i = #lookup_history_table, 1, -1 do local value = lookup_history_table[i] if not words[value.word] then stmt:bind(value.word, value.book_title or "", value.time, value.time + 5*60, value.time) stmt:step() stmt:clearbind():reset() words[value.word] = true end end end end function VocabularyBuilder:_select_items(items, start_idx, reload_time) local conn = SQ3.open(db_location) local sql if not reload_time then sql = string.format("SELECT * FROM vocabulary INNER JOIN title ON title_id = title.id AND filter = true ORDER BY due_time limit %d OFFSET %d;", 32, start_idx-1) else sql = string.format([[SELECT * FROM vocabulary INNER JOIN title ON title_id = title.id AND filter = true WHERE due_time <= ]] .. reload_time .. " ORDER BY due_time desc limit %d OFFSET %d;", 32, start_idx-1) end local results = conn:exec(sql) conn:close() if not results then return end local current_time = os.time() for i = 1, #results.word do local item = items[start_idx+i-1] if item and not item.word then item.word = results.word[i] item.review_count = math.max(0, tonumber(results.review_count[i])) item.streak_count = math.max(0, tonumber(results.streak_count[i])) item.book_title = results.name[i] or "" item.create_time = tonumber( results.create_time[i]) item.review_time = nil --use this field to flag change item.due_time = tonumber(results.due_time[i]) item.is_dim = tonumber(results.due_time[i]) > current_time item.prev_context = results.prev_context[i] item.next_context = results.next_context[i] item.got_it_callback = function(item_input) VocabularyBuilder:gotOrForgot(item_input, true) end item.forgot_callback = function(item_input) VocabularyBuilder:gotOrForgot(item_input, false) end item.remove_callback = function(item_input) VocabularyBuilder:remove(item_input) end end end end function VocabularyBuilder:select_items(vocab_widget, start_idx, end_idx) local items = vocab_widget.item_table local start_cursor if #items == 0 then start_cursor = 0 else for i = start_idx+1, end_idx do if not items[i].word then start_cursor = i break end end end if not start_cursor then return end self:_select_items(items, start_cursor, vocab_widget:check_reverse() and vocab_widget.reload_time) end function VocabularyBuilder:gotOrForgot(item, isGot) local current_time = os.time() local due_time local target_review_count = math.max(item.review_count + (isGot and 1 or -1), 0) local target_count = isGot and item.streak_count + 1 or 0 if target_count == 0 then due_time = current_time + 5 * 60 elseif target_count == 1 then due_time = current_time + 30 * 60 elseif target_count == 2 then due_time = current_time + 12 * 3600 elseif target_count == 3 then due_time = current_time + 24 * 3600 elseif target_count == 4 then due_time = current_time + 48 * 3600 elseif target_count == 5 then due_time = current_time + 96 * 3600 elseif target_count == 6 then due_time = current_time + 24 * 7 * 3600 elseif target_count == 7 then due_time = current_time + 24 * 15 * 3600 else due_time = current_time + 24 * 3600 * 30 * 2 ^ (math.min(target_count - 8, 6)) end item.last_streak_count = item.streak_count item.last_review_count = item.review_count item.last_review_time = item.review_time item.last_due_time = item.due_time item.streak_count = target_count item.review_count = target_review_count item.review_time = current_time item.due_time = due_time end function VocabularyBuilder:batchUpdateItems(items) local sql = [[UPDATE vocabulary SET review_count = ?, streak_count = ?, review_time = ?, due_time = ? WHERE word = ?;]] local conn = SQ3.open(db_location) local stmt = conn:prepare(sql) for _, item in ipairs(items) do if item.review_time then stmt:bind(item.review_count, item.streak_count, item.review_time, item.due_time, item.word) stmt:step() stmt:clearbind():reset() item.review_time = nil end end conn:exec("DELETE FROM title WHERE NOT EXISTS( SELECT title_id FROM vocabulary WHERE id = title_id );") conn:close() end function VocabularyBuilder:insertOrUpdate(entry) local conn = SQ3.open(db_location) local stmt = conn:prepare("INSERT OR IGNORE INTO title (name) VALUES (?);") stmt:bind(entry.book_title) stmt:step() stmt:clearbind():reset() stmt = conn:prepare([[INSERT INTO vocabulary (word, title_id, create_time, due_time, review_time, prev_context, next_context) VALUES (?, (SELECT id FROM title WHERE name = ?), ?, ?, ?, ?, ?) ON CONFLICT(word) DO UPDATE SET title_id = excluded.title_id, create_time = excluded.create_time, review_count = MAX(review_count-1, 0), streak_count = 0, due_time = ?, prev_context = ifnull(excluded.prev_context, prev_context), next_context = ifnull(excluded.next_context, next_context);]]); stmt:bind(entry.word, entry.book_title, entry.time, entry.time+300, entry.time, entry.prev_context, entry.next_context, entry.time+300) stmt:step() stmt:clearbind():reset() conn:close() end function VocabularyBuilder:toggleBookFilter(ids) local id_string = "" for key, _ in pairs(ids) do id_string = id_string .. (id_string == "" and "" or ",") .. key end local conn = SQ3.open(db_location) conn:exec("UPDATE title SET filter = (filter | 1) - (filter & 1) WHERE id in ("..id_string..");") conn:close() end function VocabularyBuilder:updateBookIdOfWord(word, id) if not word or type(id) ~= "number" then return end local conn = SQ3.open(db_location) local stmt = conn:prepare("UPDATE vocabulary SET title_id = ? WHERE word = ?;") stmt:bind(id, word) stmt:step() stmt:clearbind():reset() conn:close() end function VocabularyBuilder:insertNewBook(title) local conn = SQ3.open(db_location) local stmt = conn:prepare("INSERT INTO title (name) VALUES (?);") stmt:bind(title):step() stmt:clearbind():reset() stmt = conn:prepare("SELECT id FROM title WHERE name = ?") local result = stmt:bind(title):step() stmt:clearbind():reset() conn:close() return tonumber(result[1]) end function VocabularyBuilder:changeBookTitle(old_title, title) local conn = SQ3.open(db_location) local stmt = conn:prepare("UPDATE title SET name = ? WHERE name = ?;") stmt:bind(title, old_title):step() stmt:clearbind():reset() conn:close() end function VocabularyBuilder:selectBooks() local conn = SQ3.open(db_location) local sql = string.format("SELECT * FROM title") local results = conn:exec(sql) conn:close() local items = {} if not results then return items end for i = 1, #results.id do table.insert(items, { id = tonumber(results.id[i]), name = results.name[i], filter = tonumber(results.filter[i]) ~= 0 }) end return items end function VocabularyBuilder:hasFilteredBook() local conn = SQ3.open(db_location) local has_filter = tonumber(conn:rowexec("SELECT count(0) FROM title WHERE filter = false limit 1;")) conn:close() return has_filter ~= 0 end function VocabularyBuilder:remove(item) local conn = SQ3.open(db_location) local stmt = conn:prepare("DELETE FROM vocabulary WHERE word = ? ;") stmt:bind(item.word) stmt:step() stmt:clearbind():reset() conn:close() end function VocabularyBuilder:resetProgress() local conn = SQ3.open(db_location) local due_time = os.time() conn:exec(string.format("UPDATE vocabulary SET review_count = 0, streak_count = 0, due_time = %d;", due_time)) conn:close() end function VocabularyBuilder:purge() local conn = SQ3.open(db_location) conn:exec("DELETE FROM vocabulary; DELETE FROM title;") conn:close() end -- Synchronization function VocabularyBuilder.onSync(local_path, cached_path, income_path) -- we try to open income db local conn_income = SQ3.open(income_path) local ok1, v1 = pcall(conn_income.rowexec, conn_income, "PRAGMA schema_version") if not ok1 or tonumber(v1) == 0 then -- no income db or wrong db, first time sync logger.dbg("vocabbuilder open income DB failed", v1) return true end local sql = "attach '" .. income_path:gsub("'", "''") .."' as income_db;" -- then we try to open cached db local conn_cached = SQ3.open(cached_path) local ok2, v2 = pcall(conn_cached.rowexec, conn_cached, "PRAGMA schema_version") local attached_cache if not ok2 or tonumber(v2) == 0 then -- no cached or error, no item to delete logger.dbg("vocabbuilder open cached DB failed", v2) else attached_cache = true sql = sql .. "attach '" .. cached_path:gsub("'", "''") ..[[' as cached_db; -- first we delete from income_db words that exist in cached_db but not in local_db, -- namely the ones that were deleted since last sync DELETE FROM income_db.vocabulary WHERE word IN ( SELECT word FROM cached_db.vocabulary WHERE word NOT IN ( SELECT word FROM vocabulary ) ); -- We need to delete words that were delete in income_db since last sync DELETE FROM vocabulary WHERE word IN ( SELECT word FROM cached_db.vocabulary WHERE word NOT IN ( SELECT word FROM income_db.vocabulary ) ); ]] end conn_cached:close() conn_income:close() local conn = SQ3.open(local_path) local ok3, v3 = pcall(conn.exec, conn, "PRAGMA schema_version") if not ok3 or tonumber(v3) == 0 then -- no local db, this is an error logger.err("vocabbuilder open local DB", v3) return false end sql = sql .. [[ -- We merge the local db with income db to form the synced db. -- First we do the books INSERT OR IGNORE INTO title (name) SELECT name FROM income_db.title; -- Then update income db's book title id references UPDATE income_db.vocabulary SET title_id = ifnull( (SELECT mid FROM ( SELECT m.id as mid, title_id as i_tid FROM title as m -- main db INNER JOIN income_db.title as i -- income db ON m.name = i.name LEFT JOIN income_db.vocabulary on title_id = i.id ) WHERE income_db.vocabulary.title_id = i_tid ) , title_id); -- Then we merge the income_db's contents into the local db INSERT INTO vocabulary (word, create_time, review_time, due_time, review_count, prev_context, next_context, title_id, streak_count) SELECT word, create_time, review_time, due_time, review_count, prev_context, next_context, title_id, streak_count FROM income_db.vocabulary WHERE true ON CONFLICT(word) DO UPDATE SET due_time = MAX(due_time, excluded.due_time), review_count = CASE WHEN create_time = excluded.create_time THEN MAX(review_count, excluded.review_count) ELSE review_count + excluded.review_count END, prev_context = ifnull(excluded.prev_context, prev_context), next_context = ifnull(excluded.next_context, next_context), streak_count = CASE WHEN review_time > excluded.review_time THEN streak_count ELSE excluded.streak_count END, review_time = MAX(review_time, excluded.review_time), create_time = excluded.create_time, -- we always use the remote value to eliminate duplicate review_count sum title_id = excluded.title_id -- use remote in case re-assignable book id be supported ]] conn:exec(sql) pcall(conn.exec, conn, "COMMIT;") conn:exec("DETACH income_db;"..(attached_cache and "DETACH cached_db;" or "")) conn:exec("PRAGMA temp_store = 2;") -- use memory for temp files local ok, errmsg = pcall(conn.exec, conn, "VACUUM;") -- we upload a compact file if not ok then logger.warn("Failed compacting vocab database:", errmsg) end conn:close() return true end VocabularyBuilder:init() return VocabularyBuilder
agpl-3.0
lichtl/darkstar
scripts/zones/Selbina/npcs/Romeo.lua
14
2522
----------------------------------- -- Area: Selbina -- NPC: Romeo -- Starts and Finishes Quest: Donate to Recycling -- @zone 248 -- @pos -11 -11 -6 ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(OTHER_AREAS,DONATE_TO_RECYCLING) == QUEST_ACCEPTED) then if ((trade:hasItemQty(16482,5) == true or trade:hasItemQty(16483,5) == true or trade:hasItemQty(16534,5) == true or trade:hasItemQty(17068,5) == true or trade:hasItemQty(17104,5) == true) and trade:getGil() == 0 and trade:getItemCount() == 5) then player:startEvent(0x0015); -- Finish quest "Donate to Recycling" end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) DonateToRecycling = player:getQuestStatus(OTHER_AREAS,DONATE_TO_RECYCLING); if (DonateToRecycling == QUEST_AVAILABLE) then player:startEvent(0x0014); -- Start quest "Donate to Recycling" elseif (DonateToRecycling == QUEST_ACCEPTED) then player:startEvent(0x0016); -- During quest "Donate to Recycling" else player:startEvent(0x0017); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0014) then player:addQuest(OTHER_AREAS,DONATE_TO_RECYCLING); elseif (csid == 0x0015) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,89); else player:completeQuest(OTHER_AREAS,DONATE_TO_RECYCLING); player:addTitle(ECOLOGIST); player:addItem(89); player:messageSpecial(ITEM_OBTAINED,89); -- Wastebasket player:addFame(OTHER_AREAS,30); player:tradeComplete(); end end end;
gpl-3.0
raingloom/yaoui
yaoui/View.lua
4
7035
local yui_path = (...):match('(.-)[^%.]+$') .. '.' local Object = require(yui_path .. 'UI.classic.classic') local View = Object:extend('View') function View:new(yui, x, y, w, h, layout) if not layout then error('No layout specified') end self.yui = yui self.x, self.y = x, y self.w, self.h = w, h self.layout = layout self.name = self.layout.name if not self.layout[1] or (self.layout[1] and self.layout[1].class_name ~= 'Stack' and self.layout[1].class_name ~= 'Flow') then error('View must have a Stack or Flow as its first element') end self[1] = self.layout[1] -- Set parents and names self.layout[1].parent = self if self.layout[1].name then self[self.layout[1].name] = self.layout[1] end -- Default settings self.margin_left = layout.margin_left or 0 self.margin_top = layout.margin_top or 0 self.margin_right = layout.margin_right or 0 self.margin_bottom = layout.margin_bottom or 0 -- Set child position and size self.layout[1].x, self.layout[1].y = self.x + self.margin_left, self.y + self.margin_top self.layout[1].w = self.w - self.margin_left - self.margin_right self.layout[1].h = self.h - self.margin_top - self.margin_bottom self:setElementSize(self.layout[1]) self:setElementPosition(self.layout[1], self.x + self.margin_left, self.y + self.margin_top) self:reSetElementSize(self.layout[1], self) end function View:update(dt) self.layout[1]:update(dt) if self.layout.overlay then for _, element in ipairs(self.layout.overlay) do element:update(dt) end end end function View:draw() self.layout[1]:draw() if self.layout.overlay then for _, element in ipairs(self.layout.overlay) do element:draw() end end if self.layout[1].postDraw then self.layout[1]:postDraw() end if self.yui.debug_draw then love.graphics.rectangle('line', self.x, self.y, self.w, self.h) end end function View:getAllElements() return self.layout[1]:getAllElements() end function View:setElementPosition(element, x, y) element.x, element.y = x, y if element.class_name == 'Stack' then local h = 0 for i, e in ipairs(element.layout) do self:setElementPosition(e, element.x + element.margin_left, element.y + element.margin_top + h + (i-1)*element.spacing) h = h + e.h end if element.layout.bottom then h = 0 for i = #element.layout.bottom, 1, -1 do local e = element.layout.bottom[i] self:setElementPosition(e, element.x + element.margin_left, element.y + element.h - element.parent.margin_top - element.margin_bottom - e.h - (#element.layout.bottom - i)*element.spacing - h) h = h + e.h end end elseif element.class_name == 'Flow' then local w = 0 for i, e in ipairs(element.layout) do self:setElementPosition(e, element.x + element.margin_left + w + (i-1)*element.spacing, element.y + element.margin_top) w = w + e.w end if element.layout.right then w = 0 for i = #element.layout.right, 1, -1 do local e = element.layout.right[i] self:setElementPosition(e, element.x + element.w - element.parent.margin_left - element.margin_right - e.w - (#element.layout.right - i)*element.spacing - w, element.y + element.margin_top) w = w + e.w end end end end function View:reSetElementSize(element, parent) if element.class_name == 'Stack' then element.h = parent.y + parent.h - parent.margin_bottom - element.y if element.x + element.w > parent.x + parent.w - parent.margin_right then element.w = parent.x + parent.w - parent.margin_right - element.x end for _, e in ipairs(element.layout) do if e.class_name == 'Stack' or e.class_name == 'Flow' then self:reSetElementSize(e, element) end end if element.layout.bottom then for _, e in ipairs(element.layout.bottom) do if e.class_name == 'Stack' or e.class_name == 'Flow' then self:reSetElementSize(e, element) end end end elseif element.class_name == 'Flow' then element.w = parent.x + parent.w - parent.margin_right - element.x if element.y + element.h > parent.y + parent.h - parent.margin_bottom then element.h = parent.y + parent.h - parent.margin_bottom - element.y end for _, e in ipairs(element.layout) do if e.class_name == 'Stack' or e.class_name == 'Flow' then self:reSetElementSize(e, element) end end if element.layout.right then for _, e in ipairs(element.layout.right) do if e.class_name == 'Stack' or e.class_name == 'Flow' then self:reSetElementSize(e, element) end end end end end function View:setElementSize(element) if element.class_name == 'Stack' then for _, e in ipairs(element.layout) do if not e.w or not e.h then self:setElementSize(e) end end if element.layout.bottom then for _, e in ipairs(element.layout.bottom) do if not e.w or not e.h then self:setElementSize(e) end end end -- Set sizes local min = 0 for _, e in ipairs(element.layout) do if e.w > min then min = e.w end end if element.layout.bottom then for _, element in ipairs(element.layout.bottom) do if element.w > min then min = element.w end end end element.w = element.layout.w or (min + element.margin_left + element.margin_right) element.h = element.layout.h or self.h -- dummy elseif element.class_name == 'Flow' then for _, e in ipairs(element.layout) do if not e.w or not e.h then self:setElementSize(e) end end if element.layout.right then for _, e in ipairs(element.layout.right) do if not e.w or not e.h then self:setElementSize(e) end end end -- Set sizes local min = 0 for _, e in ipairs(element.layout) do if e.h > min then min = e.h end end if element.layout.right then for _, e in ipairs(element.layout.right) do if e.h > min then min = e.h end end end element.h = element.layout.h or (min + element.margin_top + element.margin_bottom) element.w = element.layout.w or self.w -- dummy end end return View
mit
lichtl/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/_5fe.lua
12
1096
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Odin's Gate -- @pos 100 -34 -49 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (npc:getAnimation() == 9) then player:messageSpecial(SOLID_STONE); end return 0; 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
lichtl/darkstar
scripts/zones/Sealions_Den/bcnms/warriors_path.lua
26
2441
----------------------------------- -- Area: Sealion's Den -- Name: warriors_path -- bcnmID : 993 ----------------------------------- package.loaded["scripts/zones/Sealions_Den/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Sealions_Den/TextIDs"); ----------------------------------- --Tarutaru --Tenzen group 860 3875 --Makki-Chebukki (RNG) , 16908311 16908315 16908319 group 853 2492 --Kukki-Chebukki (BLM) 16908312 16908316 16908320 group 852 2293 --Cherukiki (WHM). 16908313 16908317 16908321 group 851 710 --instance 1 @pos -780 -103 -90 --instance 2 @pos -140 -23 -450 --instance 3 @pos 500 56 -810 -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage player:addExp(1000); if (player:getCurrentMission(COP) == THE_WARRIOR_S_PATH) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); player:setVar("PromathiaStatus",0); player:completeMission(COP,THE_WARRIOR_S_PATH); player:addMission(COP,GARDEN_OF_ANTIQUITY); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,1); end elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7d01) then player:setPos(-25,-1 ,-620 ,208 ,33);-- al'taieu player:addTitle(THE_CHEBUKKIS_WORST_NIGHTMARE); end end;
gpl-3.0
lichtl/darkstar
scripts/zones/Upper_Delkfutts_Tower/npcs/_4e2.lua
14
1347
----------------------------------- -- Area: Upper Delkfutt's Tower -- NPC: Elevator -- @pos -294 -143 27 158 ----------------------------------- package.loaded["scripts/zones/Upper_Delkfutts_Tower/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Upper_Delkfutts_Tower/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(549,1) and trade:getItemCount() == 1) then -- Trade Delkfutt Key player:startEvent(0x0006); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(DELKFUTT_KEY)) then player:startEvent(0x0006); else player:messageSpecial(THIS_ELEVATOR_GOES_DOWN); 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); end;
gpl-3.0
lichtl/darkstar
scripts/globals/mobskills/Pyric_Bulwark.lua
27
1086
--------------------------------------------- -- Pyric Bulwark -- -- Description: Grants a Physical Shield effect for a time. -- Type: Enhancing -- -- Range: Self --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if(mob:getFamily() == 316) then local mobSkin = mob:getModelId(); if (mobSkin == 1796) then return 0; else return 1; end end -- TODO: Used only when second/left head is alive (animationsub 0 or 1) if (mob:AnimationSub() <= 1) then return 0; else return 1; end end; function onMobWeaponSkill(target, mob, skill) -- addEx to pervent dispel mob:addStatusEffectEx(EFFECT_PHYSICAL_SHIELD,0,1,0,45) skill:setMsg(MSG_BUFF) if (mob:getFamily() == 313) then -- Tinnin follows this up immediately with Nerve Gas mob:useMobAbility(1580); end return EFFECT_PHYSICAL_SHIELD; end;
gpl-3.0
RunAwayDSP/darkstar
scripts/globals/abilities/pets/thunderstorm.lua
11
1428
--------------------------------------------------- -- Geocrush --------------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") require("scripts/globals/magic") --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0,0 end function onPetAbility(target, pet, skill) local dINT = math.floor(pet:getStat(dsp.mod.INT) - target:getStat(dsp.mod.INT)) local tp = skill:getTP() / 10 local master = pet:getMaster() local merits = 0 if (master ~= nil and master:isPC()) then merits = master:getMerit(dsp.merit.THUNDERSTORM) end tp = tp + (merits - 40) if (tp > 300) then tp = 300 end --note: this formula is only accurate for level 75 - 76+ may have a different intercept and/or slope local damage = math.floor(512 + 1.72*(tp+1)) damage = damage + (dINT * 1.5) damage = MobMagicalMove(pet,target,skill,damage,dsp.magic.ele.LIGHTNING,1,TP_NO_EFFECT,0) damage = mobAddBonuses(pet, nil, target, damage.dmg, dsp.magic.ele.LIGHTNING) damage = AvatarFinalAdjustments(damage,pet,skill,target,dsp.attackType.MAGICAL,dsp.damageType.LIGHTNING,1) target:takeDamage(damage, pet, dsp.attackType.MAGICAL, dsp.damageType.LIGHTNING) target:updateEnmityFromDamage(pet,damage) return damage end
gpl-3.0
lichtl/darkstar
scripts/globals/items/serving_of_monastic_sautee.lua
18
1312
----------------------------------------- -- ID: 4293 -- Item: serving_of_monastic_sautee -- Food Effect: 240Min, All Races ----------------------------------------- -- Agility 1 -- Ranged ACC % 7 -- Ranged ACC Cap 20 ----------------------------------------- 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,4293); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 1); target:addMod(MOD_FOOD_RACCP, 7); target:addMod(MOD_FOOD_RACC_CAP, 20); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 1); target:delMod(MOD_FOOD_RACCP, 7); target:delMod(MOD_FOOD_RACC_CAP, 20); end;
gpl-3.0
lichtl/darkstar
scripts/globals/items/ilm-long_salmon_sub.lua
18
1492
----------------------------------------- -- ID: 4266 -- Item: ilm-long_salmon_sub -- Food Effect: 60Min, All Races ----------------------------------------- -- Dexterity 2 -- Agility 1 -- Vitality 1 -- Intelligence 2 -- Mind -2 -- Ranged ACC 3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,4266); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_AGI, 1); target:addMod(MOD_VIT, 1); target:addMod(MOD_INT, 2); target:addMod(MOD_MND, -2); target:addMod(MOD_RACC, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_AGI, 1); target:delMod(MOD_VIT, 1); target:delMod(MOD_INT, 2); target:delMod(MOD_MND, -2); target:delMod(MOD_RACC, 3); end;
gpl-3.0
RunAwayDSP/darkstar
scripts/zones/Windurst_Waters/npcs/Hakeem.lua
12
1287
----------------------------------- -- Area: Windurst Waters -- NPC: Hakeem -- Type: Cooking Image Support -- !pos -123.120 -2.999 65.472 238 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); local ID = require("scripts/zones/Windurst_Waters/IDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local guildMember = isGuildMember(player,4); local SkillCap = getCraftSkillCap(player,dsp.skill.COOKING); local SkillLevel = player:getSkillLevel(dsp.skill.COOKING); if (guildMember == 1) then if (player:hasStatusEffect(dsp.effect.COOKING_IMAGERY) == false) then player:startEvent(10017,SkillCap,SkillLevel,2,495,player:getGil(),0,4095,0); -- p1 = skill level else player:startEvent(10017,SkillCap,SkillLevel,2,495,player:getGil(),7094,4095,0); end else player:startEvent(10017); -- Standard Dialogue end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 10017 and option == 1) then player:messageSpecial(ID.text.COOKING_SUPPORT,0,8,2); player:addStatusEffect(dsp.effect.COOKING_IMAGERY,1,0,120); end end;
gpl-3.0
lichtl/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
lichtl/darkstar
scripts/globals/spells/phalanx.lua
27
1151
----------------------------------------- -- Spell: PHALANX ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local enhskill = caster:getSkillLevel(ENHANCING_MAGIC_SKILL); local final = 0; local duration = 180; if (caster:hasStatusEffect(EFFECT_COMPOSURE) == true and caster:getID() == target:getID()) then duration = duration * 3; end if (enhskill<=300) then final = (enhskill/10) -2; if (final<0) then final = 0; end elseif (enhskill>300) then final = ((enhskill-300)/29) + 28; else print("Warning: Unknown enhancing magic skill for phalanx."); end if (final>35) then final = 35; end if (target:addStatusEffect(EFFECT_PHALANX,final,0,duration)) then spell:setMsg(230); else spell:setMsg(75); end return EFFECT_PHALANX; end;
gpl-3.0
lichtl/darkstar
scripts/globals/items/fish_chiefkabob.lua
18
1530
----------------------------------------- -- ID: 4575 -- Item: fish_chiefkabob -- Food Effect: 60Min, All Races ----------------------------------------- -- Dexterity 1 -- Vitality 2 -- Mind 1 -- Charisma 1 -- defense % 26 -- defense Cap 95 ----------------------------------------- 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,4575); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 1); target:addMod(MOD_VIT, 2); target:addMod(MOD_MND, 1); target:addMod(MOD_CHR, 1); target:addMod(MOD_FOOD_DEFP, 26); target:addMod(MOD_FOOD_DEF_CAP, 95); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 1); target:delMod(MOD_VIT, 2); target:delMod(MOD_MND, 1); target:delMod(MOD_CHR, 1); target:delMod(MOD_FOOD_DEFP, 26); target:delMod(MOD_FOOD_DEF_CAP, 95); end;
gpl-3.0
kwketh/otclient
modules/client_stats/stats.lua
2
3776
UUID = nil HOST = 'otclient.herokuapp.com' PORT = 80 FIRST_REPORT_DELAY = 15 REPORT_DELAY = 60 sendReportEvent = nil firstReportEvent = nil function initUUID() UUID = g_settings.getString('report-uuid') if not UUID or #UUID ~= 36 then UUID = g_crypt.genUUID() g_settings.set('report-uuid', UUID) end end function init() connect(g_game, { onGameStart = onGameStart, onGameEnd = onGameEnd }) initUUID() end function terminate() disconnect(g_game, { onGameStart = onGameStart, onGameEnd = onGameEnd }) removeEvent(firstReportEvent) removeEvent(sendReportEvent) end function configure(host, port, delay) if not host then return end HOST = host PORT = port or PORT REPORT_DELAY = delay or REPORT_DELAY end function sendReport() if not HOST then return end local protocolHttp = ProtocolHttp.create() protocolHttp.onConnect = onConnect protocolHttp.onRecv = onRecv protocolHttp.onError = onError protocolHttp:connect(HOST, PORT) end function onGameStart() if not HOST then return end removeEvent(firstReportEvent) removeEvent(sendReportEvent) firstReportEvent = addEvent(sendReport, FIRST_REPORT_DELAY*1000) sendReportEvent = cycleEvent(sendReport, REPORT_DELAY*1000) end function onGameEnd() removeEvent(firstReportEvent) removeEvent(sendReportEvent) end function onConnect(protocol) if not g_game.isOnline() then protocol:disconnect() return end local post = '' post = post .. 'uid=' .. UUID post = post .. '&report_delay=' .. REPORT_DELAY post = post .. '&os=' .. g_app.getOs() post = post .. '&graphics_vendor=' .. g_graphics.getVendor() post = post .. '&graphics_renderer=' .. g_graphics.getRenderer() post = post .. '&graphics_version=' .. g_graphics.getVersion() post = post .. '&painter_engine=' .. g_graphics.getPainterEngine() post = post .. '&fps=' .. g_app.getBackgroundPaneFps() post = post .. '&max_fps=' .. g_app.getBackgroundPaneMaxFps() post = post .. '&fullscreen=' .. tostring(g_window.isFullscreen()) post = post .. '&window_width=' .. g_window.getWidth() post = post .. '&window_height=' .. g_window.getHeight() post = post .. '&player_name=' .. g_game.getCharacterName() post = post .. '&world_name=' .. g_game.getWorldName() post = post .. '&build_version=' .. g_app.getVersion() post = post .. '&build_revision=' .. g_app.getBuildRevision() post = post .. '&build_commit=' .. g_app.getBuildCommit() post = post .. '&build_date=' .. g_app.getBuildDate() post = post .. '&display_width=' .. g_window.getDisplayWidth() post = post .. '&display_height=' .. g_window.getDisplayHeight() post = post .. '&cpu=' .. g_platform.getCPUName() post = post .. '&mem=' .. g_platform.getTotalSystemMemory() post = post .. '&os_name=' .. g_platform.getOSName() post = post .. getAdditionalData() local message = '' message = message .. "POST /report HTTP/1.1\r\n" message = message .. "Host: " .. HOST .. "\r\n" message = message .. "Accept: */*\r\n" message = message .. "Connection: close\r\n" message = message .. "Content-Type: application/x-www-form-urlencoded\r\n" message = message .. "Content-Length: " .. post:len() .. "\r\n\r\n" message = message .. post protocol:send(message) protocol:recv() end function getAdditionalData() return '' end function onRecv(protocol, message) if string.find(message, 'HTTP/1.1 200 OK') then --pinfo('Stats sent to server successfully!') end protocol:disconnect() end function onError(protocol, message, code) pdebug('Could not send statistics: ' .. message) end
mit
RunAwayDSP/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/Hume_Bones.lua
9
1258
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Hume Bones -- Involved in Quests: Blue Ribbon Blues -- !pos 299 0.1 19 195 ----------------------------------- local ID = require("scripts/zones/The_Eldieme_Necropolis/IDs") require("scripts/globals/npc_util") require("scripts/globals/quests") ----------------------------------- function onTrade(player,npc,trade) if player:getQuestStatus(WINDURST,dsp.quest.id.windurst.BLUE_RIBBON_BLUES) == QUEST_ACCEPTED and player:getCharVar("BlueRibbonBluesProg") >= 3 and player:getCharVar("Lich_C_Magnus_Died") == 0 and npcUtil.tradeHas(trade, 13569) and npcUtil.popFromQM(player, npc, ID.mob.LICH_C_MAGNUS, {hide = 0}) then player:messageSpecial(ID.text.RETURN_RIBBON_TO_HER) player:confirmTrade() end end function onTrigger(player,npc) if player:getCharVar("Lich_C_Magnus_Died") == 1 and not player:hasItem(12521) then if npcUtil.giveItem(player, 12521) then player:setCharVar("Lich_C_Magnus_Died", 0) end else player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY) end end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) end
gpl-3.0
RunAwayDSP/darkstar
scripts/zones/Western_Adoulin/npcs/Defliaa.lua
9
1591
----------------------------------- -- Area: Western Adoulin -- NPC: Defliaa -- Type: Quest NPC and Shop NPC -- Involved with Quest: 'All the Way to the Bank' -- !pos 43 2 -113 256 ----------------------------------- local ID = require("scripts/zones/Western_Adoulin/IDs"); require("scripts/globals/keyitems"); require("scripts/globals/npc_util"); require("scripts/globals/shop"); function onTrade(player,npc,trade) -- ALL THE WAY TO THE BANK if (player:hasKeyItem(dsp.ki.TARUTARU_SAUCE_INVOICE)) then local ATWTTB_Paid_Defliaa = player:getMaskBit(player:getCharVar("ATWTTB_Payments"), 0); if (not ATWTTB_Paid_Defliaa and npcUtil.tradeHas( trade, {{"gil",19440}} )) then player:startEvent(5069); end end end; function onTrigger(player,npc) player:showText(npc, ID.text.DEFLIAA_SHOP_TEXT); local stock = { 5166, 3400, -- Coeurl Sub 4421, 1560, -- Melon Pie 5889, 19440, -- Stuffed Pitaru 5885, 18900, -- Saltena 4396, 280, -- Sausage Roll 4356, 200, -- White Bread 5686, 800, -- Cheese Sandwich } dsp.shop.general(player, stock); end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) -- ALL THE WAY TO THE BANK if (csid == 5069) then player:confirmTrade(); player:setMaskBit("ATWTTB_Payments", 0, true); if (player:isMaskFull(player:getCharVar("ATWTTB_Payments"), 5)) then npcUtil.giveKeyItem(player, dsp.ki.TARUTARU_SAUCE_RECEIPT); end end end;
gpl-3.0
ld-test/loop
lua/loop/thread/SocketScheduler.lua
12
3473
-------------------------------------------------------------------------------- ---------------------- ## ##### ##### ###### ----------------------- ---------------------- ## ## ## ## ## ## ## ----------------------- ---------------------- ## ## ## ## ## ###### ----------------------- ---------------------- ## ## ## ## ## ## ----------------------- ---------------------- ###### ##### ##### ## ----------------------- ---------------------- ----------------------- ----------------------- Lua Object-Oriented Programming ------------------------ -------------------------------------------------------------------------------- -- Project: LOOP Class Library -- -- Release: 2.3 beta -- -- Title : Cooperative Threads Scheduler with Integrated Socket API -- -- Author : Renato Maia <maia@inf.puc-rio.br> -- -------------------------------------------------------------------------------- local getmetatable = getmetatable local luasocket = require "socket.core" local oo = require "loop.simple" local IOScheduler = require "loop.thread.IOScheduler" local CoSocket = require "loop.thread.CoSocket" module "loop.thread.SocketScheduler" oo.class(_M, IOScheduler) -------------------------------------------------------------------------------- -- Initialization Code --------------------------------------------------------- -------------------------------------------------------------------------------- function __init(class, self) self = IOScheduler.__init(class, self) self.sockets = CoSocket({ socketapi = luasocket }, self) return self end __init(getmetatable(_M), _M) -------------------------------------------------------------------------------- -- Customizable Behavior ------------------------------------------------------- -------------------------------------------------------------------------------- time = luasocket.gettime select = luasocket.select sleep = luasocket.sleep -------------------------------------------------------------------------------- -- Component Version ----------------------------------------------------------- --[[---------------------------------------------------------------------------- SchedulerType = component.Type{ control = component.Facet, threads = component.Facet, } SocketSchedulerType = component.Type{ SchedulerType, sockets = component.Facet, } SocketScheduler = SchedulerType{ IOScheduler, socket = CoSocket, } scheduler = SocketScheduler{ time = luasocket.gettime, select = luasocket.select, sleep = luasocket.sleep, socket = { socketapi = luasocket } } subscheduler = SocketScheduler{ time = function(...) return scheduler.threads:time(...) end, select = function(...) return scheduler.sockets:select(...) end, sleep = function(...) return scheduler.threads:sleep(...) end, socket = { socketapi = scheduler.sockets } } subscheduler.threads:register(coroutine.create(function() local s = assert(scheduler.sockets:bind("localhost", 8080)) local c = assert(s:accept()) print("Got:", c:receive("*a")) end)) scheduler.threads:register(coroutine.create(function() return subscheduler.control:run() end)) scheduler.control:run() ----------------------------------------------------------------------------]]--
mit
Megaf/MegafXPlore2
mods/areas/internal.lua
5
7252
function areas:player_exists(name) return minetest.get_auth_handler().get_auth(name) ~= nil end -- Save the areas table to a file function areas:save() local datastr = minetest.serialize(self.areas) if not datastr then minetest.log("error", "[areas] Failed to serialize area data!") return end local file, err = io.open(self.config.filename, "w") if err then return err end file:write(datastr) file:close() end -- Load the areas table from the save file function areas:load() local file, err = io.open(self.config.filename, "r") if err then self.areas = self.areas or {} return err end self.areas = minetest.deserialize(file:read("*a")) if type(self.areas) ~= "table" then self.areas = {} end file:close() self:populateStore() end --- Checks an AreaStore ID. -- Deletes the AreaStore (falling back to the iterative method) -- and prints an error message if the ID is invalid. -- @return Whether the ID was valid. function areas:checkAreaStoreId(sid) if not sid then minetest.log("error", "AreaStore failed to find an ID for an " .."area! Falling back to iterative area checking.") self.store = nil self.store_ids = nil end return sid and true or false end -- Populates the AreaStore after loading, if needed. function areas:populateStore() if not rawget(_G, "AreaStore") then return end local store = AreaStore() local store_ids = {} for id, area in pairs(areas.areas) do local sid = store:insert_area(area.pos1, area.pos2, tostring(id)) if not self:checkAreaStoreId(sid) then return end store_ids[id] = sid end self.store = store self.store_ids = store_ids end -- Finds the first usable index in a table -- Eg: {[1]=false,[4]=true} -> 2 local function findFirstUnusedIndex(t) local i = 0 repeat i = i + 1 until t[i] == nil return i end --- Add a area. -- @return The new area's ID. function areas:add(owner, name, pos1, pos2, parent) local id = findFirstUnusedIndex(self.areas) self.areas[id] = { name = name, pos1 = pos1, pos2 = pos2, owner = owner, parent = parent } -- Add to AreaStore if self.store then local sid = self.store:insert_area(pos1, pos2, tostring(id)) if self:checkAreaStoreId(sid) then self.store_ids[id] = sid end end return id end --- Remove a area, and optionally it's children recursively. -- If a area is deleted non-recursively the children will -- have the removed area's parent as their new parent. function areas:remove(id, recurse) if recurse then -- Recursively find child entries and remove them local cids = self:getChildren(id) for _, cid in pairs(cids) do self:remove(cid, true) end else -- Update parents local parent = self.areas[id].parent local children = self:getChildren(id) for _, cid in pairs(children) do -- The subarea parent will be niled out if the -- removed area does not have a parent self.areas[cid].parent = parent end end -- Remove main entry self.areas[id] = nil -- Remove from AreaStore if self.store then self.store:remove_area(self.store_ids[id]) self.store_ids[id] = nil end end --- Move an area. function areas:move(id, area, pos1, pos2) area.pos1 = pos1 area.pos2 = pos2 if self.store then self.store:remove_area(areas.store_ids[id]) local sid = self.store:insert_area(pos1, pos2, tostring(id)) if self:checkAreaStoreId(sid) then self.store_ids[id] = sid end end end -- Checks if a area between two points is entirely contained by another area. -- Positions must be sorted. function areas:isSubarea(pos1, pos2, id) local area = self.areas[id] if not area then return false end local ap1, ap2 = area.pos1, area.pos2 local ap1x, ap1y, ap1z = ap1.x, ap1.y, ap1.z local ap2x, ap2y, ap2z = ap2.x, ap2.y, ap2.z local p1x, p1y, p1z = pos1.x, pos1.y, pos1.z local p2x, p2y, p2z = pos2.x, pos2.y, pos2.z if (p1x >= ap1x and p1x <= ap2x) and (p2x >= ap1x and p2x <= ap2x) and (p1y >= ap1y and p1y <= ap2y) and (p2y >= ap1y and p2y <= ap2y) and (p1z >= ap1z and p1z <= ap2z) and (p2z >= ap1z and p2z <= ap2z) then return true end end -- Returns a table (list) of children of an area given it's identifier function areas:getChildren(id) local children = {} for cid, area in pairs(self.areas) do if area.parent and area.parent == id then table.insert(children, cid) end end return children end -- Checks if the user has sufficient privileges. -- If the player is not a administrator it also checks -- if the area intersects other areas that they do not own. -- Also checks the size of the area and if the user already -- has more than max_areas. function areas:canPlayerAddArea(pos1, pos2, name) local privs = minetest.get_player_privs(name) if privs.areas then return true end -- Check self protection privilege, if it is enabled, -- and if the area is too big. if not self.config.self_protection or not privs[areas.config.self_protection_privilege] then return false, "Self protection is disabled or you do not have" .." the necessary privilege." end local max_size = privs.areas_high_limit and self.config.self_protection_max_size_high or self.config.self_protection_max_size if (pos2.x - pos1.x) > max_size.x or (pos2.y - pos1.y) > max_size.y or (pos2.z - pos1.z) > max_size.z then return false, "Area is too big." end -- Check number of areas the user has and make sure it not above the max local count = 0 for _, area in pairs(self.areas) do if area.owner == name then count = count + 1 end end local max_areas = privs.areas_high_limit and self.config.self_protection_max_areas_high or self.config.self_protection_max_areas if count >= max_areas then return false, "You have reached the maximum amount of" .." areas that you are allowed to protect." end -- Check intersecting areas local can, id = self:canInteractInArea(pos1, pos2, name) if not can then local area = self.areas[id] return false, ("The area intersects with %s [%u] (%s).") :format(area.name, id, area.owner) end return true end -- Given a id returns a string in the format: -- "name [id]: owner (x1, y1, z1) (x2, y2, z2) -> children" function areas:toString(id) local area = self.areas[id] local message = ("%s [%d]: %s %s %s"):format( area.name, id, area.owner, minetest.pos_to_string(area.pos1), minetest.pos_to_string(area.pos2)) local children = areas:getChildren(id) if #children > 0 then message = message.." -> "..table.concat(children, ", ") end return message end -- Re-order areas in table by their identifiers function areas:sort() local sa = {} for k, area in pairs(self.areas) do if not area.parent then table.insert(sa, area) local newid = #sa for _, subarea in pairs(self.areas) do if subarea.parent == k then subarea.parent = newid table.insert(sa, subarea) end end end end self.areas = sa end -- Checks if a player owns an area or a parent of it function areas:isAreaOwner(id, name) local cur = self.areas[id] if cur and minetest.check_player_privs(name, self.adminPrivs) then return true end while cur do if cur.owner == name then return true elseif cur.parent then cur = self.areas[cur.parent] else return false end end return false end
gpl-3.0
lichtl/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Caiphimonride.lua
17
1310
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Caiphimonride -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; require("scripts/zones/Tavnazian_Safehold/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,CAIPHIMONRIDE_SHOP_DIALOG); stock = {0x4042,1867, --Dagger 0x40b6,8478, --Longsword 0x43B7,8, --Rusty Bolt 0x47C7,93240, --Falx (COP Chapter 4 Needed; not implemented yet) 0x4726,51905} --Voulge (COP Chapter 4 Needed; not implemented yet) 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
NiLuJe/koreader
spec/unit/widget_inputcontainer_spec.lua
8
5927
describe("InputContainer widget", function() local InputContainer, Screen setup(function() require("commonrequire") InputContainer = require("ui/widget/container/inputcontainer") Screen = require("device").screen end) it("should register touch zones", function() local ic = InputContainer:new{} assert.is.same(#ic._ordered_touch_zones, 0) ic:registerTouchZones({ { id = "foo", ges = "swipe", screen_zone = { ratio_x = 0, ratio_y = 0, ratio_w = 1, ratio_h = 1, }, handler = function() end, }, { id = "bar", ges = "tap", screen_zone = { ratio_x = 0, ratio_y = 0.1, ratio_w = 0.5, ratio_h = 1, }, handler = function() end, }, }) local screen_width, screen_height = Screen:getWidth(), Screen:getHeight() assert.is.same(#ic._ordered_touch_zones, 2) assert.is.same("foo", ic._ordered_touch_zones[1].def.id) assert.is.same(ic._ordered_touch_zones[1].def.handler, ic._ordered_touch_zones[1].handler) assert.is.same("bar", ic._ordered_touch_zones[2].def.id) assert.is.same("tap", ic._ordered_touch_zones[2].gs_range.ges) assert.is.same(0, ic._ordered_touch_zones[2].gs_range.range.x) assert.is.same(math.floor(screen_height * 0.1), ic._ordered_touch_zones[2].gs_range.range.y) assert.is.same(screen_width / 2, ic._ordered_touch_zones[2].gs_range.range.w) assert.is.same(screen_height, ic._ordered_touch_zones[2].gs_range.range.h) end) it("should support overrides for touch zones", function() local ic = InputContainer:new{} ic:registerTouchZones({ { id = "foo", ges = "tap", screen_zone = { ratio_x = 0, ratio_y = 0, ratio_w = 1, ratio_h = 1, }, handler = function() end, }, { id = "bar", ges = "tap", screen_zone = { ratio_x = 0, ratio_y = 0, ratio_w = 0.5, ratio_h = 1, }, handler = function() end, }, { id = "baz", ges = "tap", screen_zone = { ratio_x = 0, ratio_y = 0, ratio_w = 0.5, ratio_h = 1, }, overrides = { 'foo' }, handler = function() end, }, }) assert.is.same(ic._ordered_touch_zones[1].def.id, 'baz') assert.is.same(ic._ordered_touch_zones[2].def.id, 'foo') assert.is.same(ic._ordered_touch_zones[3].def.id, 'bar') end) it("should support indirect overrides for touch zones", function() local ic = InputContainer:new{} local dummy_screen_size = {ratio_x = 0, ratio_y = 0, ratio_w = 1, ratio_h = 1,} ic:registerTouchZones({ { id = "readerfooter_tap", ges = "tap", screen_zone = dummy_screen_size, overrides = { 'tap_forward', 'tap_backward', 'readermenu_tap', }, handler = function() end, }, { id = "readerfooter_hold", ges = "hold", screen_zone = dummy_screen_size, overrides = {'readerhighlight_hold'}, handler = function() end, }, { id = "readerhighlight_tap", ges = "tap", screen_zone = dummy_screen_size, overrides = { 'tap_forward', 'tap_backward', }, handler = function() end, }, { id = "readerhighlight_hold", ges = "hold", screen_zone = dummy_screen_size, handler = function() end, }, { id = "readerhighlight_hold_release", ges = "hold_release", screen_zone = dummy_screen_size, handler = function() end, }, { id = "readerhighlight_hold_pan", ges = "hold_pan", rate = 2.0, screen_zone = dummy_screen_size, handler = function() end, }, { id = "tap_forward", ges = "tap", screen_zone = dummy_screen_size, handler = function() end, }, { id = "tap_backward", ges = "tap", screen_zone = dummy_screen_size, handler = function() end, }, { id = "readermenu_tap", ges = "tap", overrides = { "tap_forward", "tap_backward", }, screen_zone = dummy_screen_size, handler = function() end, }, }) assert.is.same('readerfooter_tap', ic._ordered_touch_zones[1].def.id) assert.is.same('readerhighlight_tap', ic._ordered_touch_zones[2].def.id) assert.is.same('readermenu_tap', ic._ordered_touch_zones[3].def.id) assert.is.same('tap_forward', ic._ordered_touch_zones[4].def.id) assert.is.same('tap_backward', ic._ordered_touch_zones[5].def.id) assert.is.same('readerfooter_hold', ic._ordered_touch_zones[6].def.id) assert.is.same('readerhighlight_hold', ic._ordered_touch_zones[7].def.id) assert.is.same('readerhighlight_hold_release', ic._ordered_touch_zones[8].def.id) assert.is.same('readerhighlight_hold_pan', ic._ordered_touch_zones[9].def.id) end) end)
agpl-3.0
NiLuJe/koreader
frontend/apps/cloudstorage/ftp.lua
4
6011
local BD = require("ui/bidi") local ConfirmBox = require("ui/widget/confirmbox") local DocumentRegistry = require("document/documentregistry") local FtpApi = require("apps/cloudstorage/ftpapi") local InfoMessage = require("ui/widget/infomessage") local MultiInputDialog = require("ui/widget/multiinputdialog") local ReaderUI = require("apps/reader/readerui") local UIManager = require("ui/uimanager") local ltn12 = require("ltn12") local logger = require("logger") local util = require("util") local _ = require("gettext") local T = require("ffi/util").template local Ftp = {} function Ftp:run(address, user, pass, path) local url = FtpApi:generateUrl(address, util.urlEncode(user), util.urlEncode(pass)) .. path return FtpApi:listFolder(url, path) end function Ftp:downloadFile(item, address, user, pass, path, callback_close) local url = FtpApi:generateUrl(address, util.urlEncode(user), util.urlEncode(pass)) .. item.url logger.dbg("downloadFile url", url) path = util.fixUtf8(path, "_") local file, err = io.open(path, "w") if not file then UIManager:show(InfoMessage:new{ text = T(_("Could not save file to %1:\n%2"), BD.filepath(path), err), }) return end local response = FtpApi:ftpGet(url, "retr", ltn12.sink.file(file)) if response ~= nil then local __, filename = util.splitFilePathName(path) if G_reader_settings:isTrue("show_unsupported") and not DocumentRegistry:hasProvider(filename) then UIManager:show(InfoMessage:new{ text = T(_("File saved to:\n%1"), BD.filepath(path)), }) else UIManager:show(ConfirmBox:new{ text = T(_("File saved to:\n%1\nWould you like to read the downloaded book now?"), BD.filepath(path)), ok_callback = function() local Event = require("ui/event") UIManager:broadcastEvent(Event:new("SetupShowReader")) if callback_close then callback_close() end ReaderUI:showReader(path) end }) end else UIManager:show(InfoMessage:new{ text = T(_("Could not save file to:\n%1"), BD.filepath(path)), timeout = 3, }) end end function Ftp:config(item, callback) local text_info = _([[ The FTP address must be in the following format: ftp://example.domain.com An IP address is also supported, for example: ftp://10.10.10.1 Username and password are optional.]]) local hint_name = _("Your FTP name") local text_name = "" local hint_address = _("FTP address eg ftp://example.com") local text_address = "" local hint_username = _("FTP username") local text_username = "" local hint_password = _("FTP password") local text_password = "" local hint_folder = _("FTP folder") local text_folder = "/" local title local text_button_right = _("Add") if item then title = _("Edit FTP account") text_button_right = _("Apply") text_name = item.text text_address = item.address text_username = item.username text_password = item.password text_folder = item.url else title = _("Add FTP account") end self.settings_dialog = MultiInputDialog:new { title = title, fields = { { text = text_name, input_type = "string", hint = hint_name , }, { text = text_address, input_type = "string", hint = hint_address , }, { text = text_username, input_type = "string", hint = hint_username, }, { text = text_password, input_type = "string", text_type = "password", hint = hint_password, }, { text = text_folder, input_type = "string", hint = hint_folder, }, }, buttons = { { { text = _("Cancel"), id = "close", callback = function() self.settings_dialog:onClose() UIManager:close(self.settings_dialog) end }, { text = _("Info"), callback = function() UIManager:show(InfoMessage:new{ text = text_info }) end }, { text = text_button_right, callback = function() local fields = self.settings_dialog:getFields() if fields[1] ~= "" and fields[2] ~= "" then if item then -- edit callback(item, fields) else -- add new callback(fields) end self.settings_dialog:onClose() UIManager:close(self.settings_dialog) else UIManager:show(InfoMessage:new{ text = _("Please fill in all fields.") }) end end }, }, }, input_type = "text", } UIManager:show(self.settings_dialog) self.settings_dialog:onShowKeyboard() end function Ftp:info(item) local info_text = T(_"Type: %1\nName: %2\nAddress: %3", "FTP", item.text, item.address) UIManager:show(InfoMessage:new{text = info_text}) end return Ftp
agpl-3.0
scscgit/scsc_wildstar_addons
WSRPHousing/Lists/EntityDominionPlayer.lua
1
10146
ChatSystemLib.PostOnChannel(ChatSystemLib.ChatChannel_System, "[WSRP Housing Directory] Entity: Dominion Directory Loaded.") return { { title = "Valiantheart Coliseum", owner = "Erallia Valiantheart", hours = "Refer to Owner for hours", staff = "Erallia Valiantheart", description = "The Valiantheart Coliseum and Tavern owned by Erallia Valiantheart, a place labeled as 'Spar-and-Bar', you can come to spectate or even be a part of the many fights that take place here. We hold various different fights and we're always looking for new ways to make sparring here, a memory that'll last a lifetime. We also host an event every so often called the \"Dominion's Finest Fighter\" tournament up in the main Coliseum. We're open to requests by RPers or the Valiantheart crew on opening at any time.", }, { title = "Noriack's Cafe", owner = "Chef Noriack", hours = "Friday 10pm est - Whenever ", staff = "Chef Noriack, Lala Sasazy, Prietess Helmina, Neffelo Clamp", description = "Noriack's cafe serves a wide variety of tea, coffee, lattes, cassianos, and a small beer and wine selection. The popular Necrohive Mead is a regular here to many guests. The food selection can be just as varied with dishes like the ultra cheesy Artemis Pizza, the sweet and spicy Honey glazed Ravenok, or get your desert on with some delicious Caramel and Chocolate topped Cheesecake. Many other items are available and the menu changes from week to week. \nNoriack's cafe is a whirlwind of activity on Friday evenings from 10pm est until it quiets down (Well after midnight.) Though everyone is always welcome to come use the Lopp staff that exist to get meals and drinks in the off hours. \nThe grounds of the cafe are always open to the public and are composed of lovely gardens and a glass skyway that puts you above the troubles of the world. There is a sky garden, lounge, and even a dance floor to get ones groove on. \nWe are happy to cater events and provide off hour services, or even home delivery, just please contact Chef Noriack with any requests you might have. Wedding coming up? Rent out the cafe, or let us come to you! Wedding booth construction available upon request.", }, { title = "The Shock Collar Bar & Casino", owner = "Neffelo Clamp", hours = "Wednesdays 10pm est - 1am", staff = "Neffelo Clamp, Chef Noriack, Vannyx Xanniton, Priestess Helmina", description = "The premier Club Casino and Bar! It hosts beverages from Bezgelore and a wide assortment of safe for all to consume beverages as well. Come try your hand at the slot machines or some cards or roulette while you're there. Meet some new friends and get immersed in chua culture! \n\nCome and marvel at the technology displayed! Admired the scientific beauty! Make new contacts for business! All at the Shock Collar Bar and Casino! \n\nThis club is run by the Red Tail Collective headed by Neffelo Clamp and is open to all. A small section that is a chua only private bar inside the main building exists for those chua needing to get to a place that feels more like home.\n\n\n\n", }, { title = "The Eldan Fried Cubig Protobar", owner = "Grumlen Dangerpants", hours = "24/7", staff = "Grumlen Dangerpants", description = "The Eldan-Fried Cubig (EFC) protobar was originally conceived by the Protostar Corporation as a means of assuring fast food services to almost anywhere in the known galaxy, utilizing a delivery system of advanced teleportation-based transit and housed in small, communal sit-in \“dining ships\”. The only constructed prototype was scrapped and left for ruin atop an asteroid in the Halon Ring of Nexus, where chua scrapper Grumlen \"Dangerpants\" stumbled upon it years later and took it upon himself to refurbish the small business to that of his own design. \n\nClaiming to definitely still be a licensed Protostar franchise, and boasting a menu of only 2 different questionably-specific fried meals... it’s safe to say EFC's food probably tastes as good as the place in which it’s presented is maintained.", }, { title = "Our Lady Eldan", owner = "Opeth Mistreaver", hours = "24/7", staff = "Priestess Helmina, Opeth Mistreaver, Furgun Darkstorm", description = "This plot is a Vigilant Church, fully dedicated to the religious beliefs of the Dominion religion. There is a shrine to the Six Scions, a full church with pipe organ, confessional and prayer candles, a church rectory, mausoleum w/cemetery, a conference/meeting hall, cleansing water spring and expansive garden. \n\nIt is open to all religious events. Please contact our staff to set up events or for use of the plot, it is open for viewing, but would like to keep the peace so to speak. Regular Vigils (sermons) are held on Sundays at 7:00 PM EST.", }, { title = "Evindra Imeperial Park", owner = "Xerune Novimae", hours = "24/7", staff = "Xerune Novimae, Isabella Sinclair, Perseus Ford, Vyzura Razorcloak, Atun Nol (xerune is IC, all others can change things)", description = "The Imperial Park is a place for all Dominion citizens to enjoy the flora wonders of Nexus at any time and within the safety of the Empire. Several exhibits exist to show off certain areas such as Ellevar, Deardune, and Wilderrun. The Emperor Myrcalus Botany Conservatory holds some exhibits in contested territories such as Farside, Celestion, Algoroc, Galeras, and another unknown. There's also picnic area with food vendors and a ferris wheel. It is truly a park for anyone.\n\nThere is also a game! A scavenger hunt for 8 carrots and a vind all hidden throughout the park. Can you find them all? \n\nHowever there is also a secret, underground the ICI conducts meetings and other details. To the general public no one knows of it's location. But for those of the ICI know it is a place for their needs be it from holding suspicious people, interrogations, medical needs to even socializing among themselves and a place to rest. ", }, { title = "The Jabbit Hole", owner = "Jabbit Tooth", hours = "24/7", staff = "Jabbit Tooth", description = "Though not an advertised or even desirable locale, the mysterious city—nicknamed by the knowing few as the \"Jabbit Hole\"—has become home to a handful of lost vagrants and those of ill repute. Its origins are unknown, as is its location. The only method of travel seems to be through a bypassed teleportation pad nestled within the corner of the city's only currently accessible alleyway.\nThe city itself had gradually fallen further into a state of disrepair following whatever cataclysm flung it into its present realm of existence. A smoggy, starless sky envelops the urban landscape with a framework of decayed architecture keeping the area contained.\nMost visitors of the Jabbit Hole gain access through the numerous faulty teleportation pads courtesy of Protostar's Nexus colonization project. Regardless of the amount of work it takes to get in, travelers will find the real challenge is their inevitable escape. Unless they were never meant to leave at all.", }, { title = "Curiosity", owner = "Vagabond Croix", hours = "Every other Saturday 10 PM-?", staff = "Vagabond Croix", description = "Curiosity is the Dominion's premiere night club, offering the finest in finger foods, such as the now famous pulled cupork sliders, along with a massive assortment of liquors, spirits, and exciting cocktails to keep you curious for more.\n\nCuriosity hosts a variety of events, including trivia night, murder mysteries, truth or dare, scavenger hunts, and a banquet of other delightful challenges to keep the brain guessing and the mind wanting more.", }, { title = "The Beacon of the Scions", owner = "Inquisitor Garack", hours = "Unscheduled", staff = "Inquisitor Garack, Daisy Xay", description = "The Beacon of the Scions is a Dominion space station near Nexus. It has a market, lodging, and a bar/restaurant, with more features on the way. It's also connected to the Protostar Housing Network.", }, { title = "ICI Operative Retreat", owner = "Desai Septaphex", hours = "24/7", staff = "Desai Septaphex", description = "The retreat offers a calm environs for agents off duty and any of their friends to unwind, enjoy a drink, conversation, pray, spar, or enjoy a sauna or acid bath (mechari only) Just please.. do avoid the basement....", }, { title = "Horizon", owner = "Victoria Hemming", hours = "Sunday 8:30 - 11:30 PM (EST)", staff = "Victoria Hemming", description = "Horizon is an open-air dance club that is in low orbit around Nexus. Yes, you read correctly! Equipped with the latest Protostar™ Skyplot mobility technologies, Horizon is always moving towards the horizon, countering the motion of Nexus’ rotation. The end result is a perpetual sunset for our patrons to enjoy.\n\nThe warm sunlight is not all that Horizon has to offer. Far from Cassus, Horizon aims to bring the long absent summer Cassian club culture to Nexus. Gone are the days of being crammed in a dimly lit underground bunker with a jukebox violating your ear drums (or audio receptors). Horizon sports a specially made sound system, named \“The Endless Summer Sound System™\”, which incorporates one of Nexus’ most powerful setup of speakers working in tandem with the latest in acoustic design to bring loud, thumping dance music to you without the fear of going deaf. Coupled with the sunny, laid-back atmosphere and tailored selection of music, Horizon brings a clubbing experience like none other.\n\nRead more at: http://www.tinyurl.com/horizonadvert", }, { title = "The Vigilant Sanctuary", owner = "Dajia Nano", hours = "24/7", staff = "Dajia Nano, Afterburn Unicron", description = "A haven for those seeking refuge, or quiet meditation away from the bustle of Illium. The Sanctuary is a place for those devout to the Scions to come and pray within the sanctuary itself or wander the gardens while basking in the glory of the Scions. The Vigilant Sanctuary is open to host sermons for the Vigilant Church along with offering a place to stay for those loyal to the Dominion. Deeper within the Sanctuary, there is a rehabilitation facility for those of the Dominion in need of some..re-education.", }, }
mit
RunAwayDSP/darkstar
scripts/globals/items/yogurt_cake.lua
11
1025
----------------------------------------- -- ID: 5627 -- Item: Yogurt Cake -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- Intelligence 1 -- HP Recovered while healing 3 -- MP Recovered while healing 6 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,10800,5627) end function onEffectGain(target, effect) target:addMod(dsp.mod.INT, 1) target:addMod(dsp.mod.HPHEAL, 3) target:addMod(dsp.mod.MPHEAL, 6) end function onEffectLose(target, effect) target:delMod(dsp.mod.INT, 1) target:delMod(dsp.mod.HPHEAL, 3) target:delMod(dsp.mod.MPHEAL, 6) end
gpl-3.0
lichtl/darkstar
scripts/zones/Port_Bastok/npcs/Styi_Palneh.lua
27
4322
----------------------------------- -- Area: Port Bastok -- NPC: Styi Palneh -- Title Change NPC -- @pos 28 4 -15 236 ----------------------------------- require("scripts/globals/titles"); local title2 = { NEW_ADVENTURER , BASTOK_WELCOMING_COMMITTEE , BUCKET_FISHER , PURSUER_OF_THE_PAST , MOMMYS_HELPER , HOT_DOG , STAMPEDER , RINGBEARER , ZERUHN_SWEEPER , TEARJERKER , CRAB_CRUSHER , BRYGIDAPPROVED , GUSTABERG_TOURIST , MOGS_MASTER , CERULEAN_SOLDIER , DISCERNING_INDIVIDUAL , VERY_DISCERNING_INDIVIDUAL , EXTREMELY_DISCERNING_INDIVIDUAL , APOSTATE_FOR_HIRE , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title3 = { SHELL_OUTER , PURSUER_OF_THE_TRUTH , QIJIS_FRIEND , TREASURE_SCAVENGER , SAND_BLASTER , DRACHENFALL_ASCETIC , ASSASSIN_REJECT , CERTIFIED_ADVENTURER , QIJIS_RIVAL , CONTEST_RIGGER , KULATZ_BRIDGE_COMPANION , AVENGER , AIRSHIP_DENOUNCER , STAR_OF_IFRIT , PURPLE_BELT , MOGS_KIND_MASTER , TRASH_COLLECTOR , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title4 = { BEADEAUX_SURVEYOR , PILGRIM_TO_DEM , BLACK_DEATH , DARK_SIDER , SHADOW_WALKER , SORROW_DROWNER , STEAMING_SHEEP_REGULAR , SHADOW_BANISHER , MOGS_EXCEPTIONALLY_KIND_MASTER , HYPER_ULTRA_SONIC_ADVENTURER , GOBLIN_IN_DISGUISE , BASTOKS_SECOND_BEST_DRESSED , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title5 = { PARAGON_OF_WARRIOR_EXCELLENCE , PARAGON_OF_MONK_EXCELLENCE , PARAGON_OF_DARK_KNIGHT_EXCELLENCE , HEIR_OF_THE_GREAT_EARTH , MOGS_LOVING_MASTER , HERO_AMONG_HEROES , DYNAMISBASTOK_INTERLOPER , MASTER_OF_MANIPULATION , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title6 = { LEGIONNAIRE , DECURION , CENTURION , JUNIOR_MUSKETEER , SENIOR_MUSKETEER , MUSKETEER_COMMANDER , GOLD_MUSKETEER , PRAEFECTUS , SENIOR_GOLD_MUSKETEER , PRAEFECTUS_CASTRORUM , ANVIL_ADVOCATE , FORGE_FANATIC , ACCOMPLISHED_BLACKSMITH , ARMORY_OWNER , TRINKET_TURNER , SILVER_SMELTER , ACCOMPLISHED_GOLDSMITH , JEWELRY_STORE_OWNER , FORMULA_FIDDLER , POTION_POTENTATE , ACCOMPLISHED_ALCHEMIST , APOTHECARY_OWNER , 0 , 0 , 0 , 0 , 0 , 0 } local title7 = { MOG_HOUSE_HANDYPERSON , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00C8,npcUtil.genTmask(player,title2),npcUtil.genTmask(player,title3),npcUtil.genTmask(player,title4),npcUtil.genTmask(player,title5),npcUtil.genTmask(player,title6),npcUtil.genTmask(player,title7),1 ,player:getGil()); 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==0x00C8) then if (option > 0 and option <29) then if (player:delGil(200)) then player:setTitle( title2[option] ) end elseif (option > 256 and option <285) then if (player:delGil(300)) then player:setTitle( title3[option - 256] ) end elseif (option > 512 and option < 541) then if (player:delGil(400)) then player:setTitle( title5[option - 512] ) end elseif (option > 768 and option <797) then if (player:delGil(500)) then player:setTitle( title5[option - 768] ) end elseif (option > 1024 and option < 1053) then if (player:delGil(600)) then player:setTitle( title6[option - 1024] ) end elseif (option > 1280 and option < 1309) then if (player:delGil(700)) then player:setTitle( title7[option - 1280]) end end end end;
gpl-3.0
lichtl/darkstar
scripts/zones/Dragons_Aery/mobs/Nidhogg.lua
12
2334
----------------------------------- -- Area: Dragons Aery -- HNM: Nidhogg ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/status"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobSpawn ----------------------------------- function onMobSpawn(mob) if (LandKingSystem_NQ > 0 or LandKingSystem_HQ > 0) then GetNPCByID(17408033):setStatus(STATUS_DISAPPEAR); end end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) local battletime = mob:getBattleTime(); local twohourTime = mob:getLocalVar("twohourTime"); if (twohourTime == 0) then mob:setLocalVar("twohourTime",math.random(30,90)); end if (battletime >= twohourTime) then mob:useMobAbility(956); -- technically aerial hurricane wing, but I'm using 700 for his two hour --(since I have no inclination to spend millions on a PI to cap one name you never see) mob:setLocalVar("twohourTime",battletime + math.random(60,120)); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) player:addTitle(NIDHOGG_SLAYER); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) -- Set Nidhogg's Window Open Time if (LandKingSystem_HQ ~= 1) then local wait = 72 * 3600; SetServerVariable("[POP]Nidhogg", os.time(t) + wait); -- 3 days if (LandKingSystem_HQ == 0) then -- Is time spawn only DeterMob(mob:getID(), true); end end -- Set Fafnir's spawnpoint and respawn time (21-24 hours) if (LandKingSystem_NQ ~= 1) then local Fafnir = mob:getID()-1; SetServerVariable("[PH]Nidhogg", 0); DeterMob(Fafnir, false); UpdateNMSpawnPoint(Fafnir); GetMobByID(Fafnir):setRespawnTime(math.random(75600,86400)); end if (LandKingSystem_NQ > 0 or LandKingSystem_HQ > 0) then GetNPCByID(17408033):updateNPCHideTime(FORCE_SPAWN_QM_RESET_TIME); end end;
gpl-3.0
Megaf/MegafXPlore2
mods/player_api/api.lua
1
4031
-- Minetest 0.4 mod: player -- See README.txt for licensing and other information. player_api = {} -- Player animation blending -- Note: This is currently broken due to a bug in Irrlicht, leave at 0 local animation_blend = 0 player_api.registered_models = { } -- Local for speed. local models = player_api.registered_models function player_api.register_model(name, def) models[name] = def end -- Player stats and animations local player_model = {} local player_textures = {} local player_anim = {} local player_sneak = {} player_api.player_attached = {} function player_api.get_animation(player) local name = player:get_player_name() return { model = player_model[name], textures = player_textures[name], animation = player_anim[name], } end -- Called when a player's appearance needs to be updated function player_api.set_model(player, model_name) local name = player:get_player_name() local model = models[model_name] if model then if player_model[name] == model_name then return end player:set_properties({ mesh = model_name, textures = player_textures[name] or model.textures, visual = "mesh", visual_size = model.visual_size or {x = 1, y = 1}, collisionbox = model.collisionbox or {-0.3, 0.0, -0.3, 0.3, 1.77, 0.3}, stepheight = model.stepheight or 0.6, }) player_api.set_animation(player, "stand") else player:set_properties({ textures = {"player.png", "player_back.png"}, visual = "upright_sprite", collisionbox = {-0.3, 0.0, -0.3, 0.3, 1.75, 0.3}, stepheight = 0.6, }) end player_model[name] = model_name end function player_api.set_textures(player, textures) local name = player:get_player_name() local model = models[player_model[name]] local model_textures = model and model.textures or nil player_textures[name] = textures or model_textures player:set_properties({textures = textures or model_textures,}) end function player_api.set_animation(player, anim_name, speed) local name = player:get_player_name() if player_anim[name] == anim_name then return end local model = player_model[name] and models[player_model[name]] if not (model and model.animations[anim_name]) then return end local anim = model.animations[anim_name] player_anim[name] = anim_name player:set_animation(anim, speed or model.animation_speed, animation_blend) end minetest.register_on_leaveplayer(function(player) local name = player:get_player_name() player_model[name] = nil player_anim[name] = nil player_textures[name] = nil end) -- Localize for better performance. local player_set_animation = player_api.set_animation local player_attached = player_api.player_attached -- Check each player and apply animations minetest.register_globalstep(function(dtime) for _, player in pairs(minetest.get_connected_players()) do local name = player:get_player_name() local model_name = player_model[name] local model = model_name and models[model_name] if model and not player_attached[name] then local controls = player:get_player_control() local walking = false local animation_speed_mod = model.animation_speed or 30 -- Determine if the player is walking if controls.up or controls.down or controls.left or controls.right then walking = true end -- Determine if the player is sneaking, and reduce animation speed if so if controls.sneak then animation_speed_mod = animation_speed_mod / 2 end -- Apply animations based on what the player is doing if player:get_hp() == 0 then player_set_animation(player, "lay") elseif walking then if player_sneak[name] ~= controls.sneak then player_anim[name] = nil player_sneak[name] = controls.sneak end if controls.LMB then player_set_animation(player, "walk_mine", animation_speed_mod) else player_set_animation(player, "walk", animation_speed_mod) end elseif controls.LMB then player_set_animation(player, "mine") else player_set_animation(player, "stand", animation_speed_mod) end end end end)
gpl-3.0