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 |
|---|---|---|---|---|---|
Servius/tfa-sw-weapons-repository | Backups_Reworks/tfa_swrp_shared_old/lua/entities/vox_e60r_rocket/cl_init.lua | 11 | 1374 | include('shared.lua')
//[[---------------------------------------------------------
//Name: Draw Purpose: Draw the model in-game.
//Remember, the things you render first will be underneath!
//-------------------------------------------------------]]
function ENT:Draw()
// self.BaseClass.Draw(self)
-- We want to override rendering, so don't call baseclass.
// Use this when you need to add to the rendering.
self.Entity:DrawModel() // Draw the model.
end
function ENT:Initialize()
pos = self:GetPos()
self.emitter = ParticleEmitter( pos )
end
function ENT:Think()
pos = self:GetPos()
for i=0, (10) do
local particle = self.emitter:Add( "particle/smokesprites_000"..math.random(1,9), pos + (self:GetForward() * -100 * i))
if (particle) then
particle:SetVelocity((self:GetForward() * -2000) )
particle:SetDieTime( math.Rand( 1.5, 3 ) )
particle:SetStartAlpha( math.Rand( 5, 8 ) )
particle:SetEndAlpha( 0 )
particle:SetStartSize( math.Rand( 40, 50 ) )
particle:SetEndSize( math.Rand( 130, 150 ) )
particle:SetRoll( math.Rand(0, 360) )
particle:SetRollDelta( math.Rand(-1, 1) )
particle:SetColor( 200 , 200 , 200 )
particle:SetAirResistance( 200 )
particle:SetGravity( Vector( 100, 0, 0 ) )
end
end
end
| apache-2.0 |
Servius/tfa-sw-weapons-repository | Backups_Reworks/tfa_swrp_shared_old/lua/entities/dc17m_at_rocket2/cl_init.lua | 11 | 1374 | include('shared.lua')
//[[---------------------------------------------------------
//Name: Draw Purpose: Draw the model in-game.
//Remember, the things you render first will be underneath!
//-------------------------------------------------------]]
function ENT:Draw()
// self.BaseClass.Draw(self)
-- We want to override rendering, so don't call baseclass.
// Use this when you need to add to the rendering.
self.Entity:DrawModel() // Draw the model.
end
function ENT:Initialize()
pos = self:GetPos()
self.emitter = ParticleEmitter( pos )
end
function ENT:Think()
pos = self:GetPos()
for i=0, (10) do
local particle = self.emitter:Add( "particle/smokesprites_000"..math.random(1,9), pos + (self:GetForward() * -100 * i))
if (particle) then
particle:SetVelocity((self:GetForward() * -2000) )
particle:SetDieTime( math.Rand( 1.5, 3 ) )
particle:SetStartAlpha( math.Rand( 5, 8 ) )
particle:SetEndAlpha( 0 )
particle:SetStartSize( math.Rand( 40, 50 ) )
particle:SetEndSize( math.Rand( 130, 150 ) )
particle:SetRoll( math.Rand(0, 360) )
particle:SetRollDelta( math.Rand(-1, 1) )
particle:SetColor( 200 , 200 , 200 )
particle:SetAirResistance( 200 )
particle:SetGravity( Vector( 100, 0, 0 ) )
end
end
end
| apache-2.0 |
Dual-Boxing/Jamba | Modules/Jamba-Trade/JambaTrade.lua | 1 | 36470 | --[[
Jamba - Jafula's Awesome Multi-Boxer Assistant
Copyright 2008 - 2015 Michael "Jafula" Miller
License: The MIT License
]]--
-- Create the addon using AceAddon-3.0 and embed some libraries.
local AJM = LibStub( "AceAddon-3.0" ):NewAddon(
"JambaTrade",
"JambaModule-1.0",
"AceConsole-3.0",
"AceEvent-3.0",
"AceHook-3.0",
"AceTimer-3.0"
)
-- Get the Jamba Utilities Library.
local JambaUtilities = LibStub:GetLibrary( "JambaUtilities-1.0" )
local JambaHelperSettings = LibStub:GetLibrary( "JambaHelperSettings-1.0" )
local LibBagUtils = LibStub:GetLibrary( "LibBagUtils-1.0" )
local LibGratuity = LibStub( "LibGratuity-3.0" )
local AceGUI = LibStub( "AceGUI-3.0" )
-- Constants and Locale for this module.
AJM.moduleName = "Jamba-Trade"
AJM.settingsDatabaseName = "JambaTradeProfileDB"
AJM.chatCommand = "jamba-trade"
local L = LibStub( "AceLocale-3.0" ):GetLocale( AJM.moduleName )
AJM.parentDisplayName = L["Interaction"]
AJM.moduleDisplayName = L["Trade"]
AJM.inventorySeperator = "\008"
AJM.inventoryPartSeperator = "\009"
-- Settings - the values to store and their defaults for the settings database.
AJM.settings = {
profile = {
messageArea = JambaApi.DefaultMessageArea(),
framePoint = "CENTER",
frameRelativePoint = "CENTER",
frameXOffset = 0,
frameYOffset = 0,
showJambaTradeWindow = true,
adjustMoneyWithGuildBank = false,
goldAmountToKeepOnToon = 200,
adjustMoneyWithMasterOnTrade = false,
goldAmountToKeepOnToonTrade = 200,
ignoreSoulBound = false
},
}
-- Configuration.
function AJM:GetConfiguration()
local configuration = {
name = AJM.moduleDisplayName,
handler = AJM,
type = 'group',
childGroups = "tab",
get = "JambaConfigurationGetSetting",
set = "JambaConfigurationSetSetting",
args = {
loadname = {
type = "input",
name = L["Load Item By Name"],
desc = L["Load a certain amount of an item by name into the trade window."],
usage = "/jamba-trade loadname <item-name>,<amount>",
get = false,
set = "JambaTradeLoadNameCommand",
guiHidden = true,
},
loadtype = {
type = "input",
name = L["Load Items By Type"],
desc = L["Load items by type into the trade window."],
usage = "/jamba-trade loadtype <class>,<subclass>",
get = false,
set = "JambaTradeLoadTypeCommand",
guiHidden = true,
},
push = {
type = "input",
name = L["Push Settings"],
desc = L["Push the trade settings to all characters in the team."],
usage = "/jamba-trade push",
get = false,
set = "JambaSendSettings",
guiHidden = true,
},
},
}
return configuration
end
-------------------------------------------------------------------------------------------------------------
-- Command this module sends.
-------------------------------------------------------------------------------------------------------------
AJM.COMMAND_SHOW_INVENTORY = "ShowInventory"
AJM.COMMAND_HERE_IS_MY_INVENTORY = "HereIsMyInventory"
AJM.COMMAND_LOAD_ITEM_INTO_TRADE = "LoadItemIntoTrade"
AJM.COMMAND_LOAD_ITEM_CLASS_INTO_TRADE = "LoadItemClassIntoTrade"
AJM.COMMAND_GET_SLOT_COUNT = "GetSlotCount"
AJM.COMMAND_HERE_IS_MY_SLOT_COUNT = "HereIsMySlotCount"
-------------------------------------------------------------------------------------------------------------
-- Messages module sends.
-------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------
-- Addon initialization, enabling and disabling.
-------------------------------------------------------------------------------------------------------------
-- Initialise the module.
function AJM:OnInitialize()
AJM.inventory = ""
AJM.inventoryInDisplayTable = {}
AJM.inventorySortedTable = {}
AJM.itemClassList = {}
AJM.itemClassSubList = {}
AJM.itemClassSubListLastSelection = {}
AJM.itemClassCurrentSelection = ""
AJM.itemSubClassCurrentSelection = ""
-- Create the settings control.
AJM:SettingsCreate()
-- Initialse the JambaModule part of this module.
AJM:JambaModuleInitialize( AJM.settingsControl.widgetSettings.frame )
AJM:CreateInventoryFrame()
-- Populate the settings.
AJM:SettingsRefresh()
end
-- Called when the addon is enabled.
function AJM:OnEnable()
AJM:RegisterEvent( "TRADE_SHOW" )
AJM:RegisterEvent( "TRADE_CLOSED" )
AJM:RegisterEvent( "GUILDBANKFRAME_OPENED" )
AJM:RegisterMessage( JambaApi.MESSAGE_MESSAGE_AREAS_CHANGED, "OnMessageAreasChanged" )
end
-- Called when the addon is disabled.
function AJM:OnDisable()
-- AceHook-3.0 will tidy up the hooks for us.
end
function AJM:SettingsCreate()
AJM.settingsControl = {}
-- Create the settings panel.
JambaHelperSettings:CreateSettings(
AJM.settingsControl,
AJM.moduleDisplayName,
AJM.parentDisplayName,
AJM.SettingsPushSettingsClick
)
local bottomOfInfo = AJM:SettingsCreateTrade( JambaHelperSettings:TopOfSettings() )
AJM.settingsControl.widgetSettings.content:SetHeight( -bottomOfInfo )
-- Help
local helpTable = {}
JambaHelperSettings:CreateHelp( AJM.settingsControl, helpTable, AJM:GetConfiguration() )
end
function AJM:SettingsPushSettingsClick( event )
AJM:JambaSendSettings()
end
function AJM:SettingsCreateTrade( top )
local checkBoxHeight = JambaHelperSettings:GetCheckBoxHeight()
local editBoxHeight = JambaHelperSettings:GetEditBoxHeight()
local left = JambaHelperSettings:LeftOfSettings()
local headingHeight = JambaHelperSettings:HeadingHeight()
local headingWidth = JambaHelperSettings:HeadingWidth( false )
local dropdownHeight = JambaHelperSettings:GetDropdownHeight()
local verticalSpacing = JambaHelperSettings:GetVerticalSpacing()
local movingTop = top
JambaHelperSettings:CreateHeading( AJM.settingsControl, L["Trade Options"], movingTop, false )
movingTop = movingTop - headingHeight
AJM.settingsControl.checkBoxShowJambaTradeWindow = JambaHelperSettings:CreateCheckBox(
AJM.settingsControl,
headingWidth,
left,
movingTop,
L["Show Jamba Trade Window On Trade"],
AJM.SettingsToggleShowJambaTradeWindow
)
movingTop = movingTop - checkBoxHeight
AJM.settingsControl.checkBoxAdjustMoneyOnToonViaGuildBank = JambaHelperSettings:CreateCheckBox(
AJM.settingsControl,
headingWidth,
left,
movingTop,
L["Adjust Toon Money While Visiting The Guild Bank"],
AJM.SettingsToggleAdjustMoneyOnToonViaGuildBank
)
movingTop = movingTop - checkBoxHeight
AJM.settingsControl.editBoxGoldAmountToLeaveOnToon = JambaHelperSettings:CreateEditBox( AJM.settingsControl,
headingWidth,
left,
movingTop,
L["Amount of Gold"]
)
AJM.settingsControl.editBoxGoldAmountToLeaveOnToon:SetCallback( "OnEnterPressed", AJM.EditBoxChangedGoldAmountToLeaveOnToon )
movingTop = movingTop - editBoxHeight
AJM.settingsControl.checkBoxAdjustMoneyWithMasterOnTrade = JambaHelperSettings:CreateCheckBox(
AJM.settingsControl,
headingWidth,
left,
movingTop,
L["Trade Excess Gold To Master From Slave"],
AJM.SettingsToggleAdjustMoneyWithMasterOnTrade
)
movingTop = movingTop - checkBoxHeight
AJM.settingsControl.editBoxGoldAmountToLeaveOnToonTrade = JambaHelperSettings:CreateEditBox( AJM.settingsControl,
headingWidth,
left,
movingTop,
L["Amount Of Gold To Keep"]
)
AJM.settingsControl.editBoxGoldAmountToLeaveOnToonTrade:SetCallback( "OnEnterPressed", AJM.EditBoxChangedGoldAmountToLeaveOnToonTrade )
movingTop = movingTop - editBoxHeight
AJM.settingsControl.dropdownMessageArea = JambaHelperSettings:CreateDropdown(
AJM.settingsControl,
headingWidth,
left,
movingTop,
L["Message Area"]
)
AJM.settingsControl.dropdownMessageArea:SetList( JambaApi.MessageAreaList() )
AJM.settingsControl.dropdownMessageArea:SetCallback( "OnValueChanged", AJM.SettingsSetMessageArea )
movingTop = movingTop - dropdownHeight - verticalSpacing
return movingTop
end
function AJM:OnMessageAreasChanged( message )
AJM.settingsControl.dropdownMessageArea:SetList( JambaApi.MessageAreaList() )
end
function AJM:SettingsSetMessageArea( event, value )
AJM.db.messageArea = value
AJM:SettingsRefresh()
end
function AJM:SettingsToggleShowJambaTradeWindow( event, checked )
AJM.db.showJambaTradeWindow = checked
AJM:SettingsRefresh()
end
function AJM:SettingsToggleAdjustMoneyOnToonViaGuildBank( event, checked )
AJM.db.adjustMoneyWithGuildBank = checked
AJM:SettingsRefresh()
end
function AJM:SettingsToggleAdjustMoneyWithMasterOnTrade( event, checked )
AJM.db.adjustMoneyWithMasterOnTrade = checked
AJM:SettingsRefresh()
end
function AJM:EditBoxChangedGoldAmountToLeaveOnToon( event, text )
AJM.db.goldAmountToKeepOnToon = tonumber( text )
if AJM.db.goldAmountToKeepOnToon == nil then
AJM.db.goldAmountToKeepOnToon = 0
end
AJM:SettingsRefresh()
end
function AJM:EditBoxChangedGoldAmountToLeaveOnToonTrade( event, text )
AJM.db.goldAmountToKeepOnToonTrade = tonumber( text )
if AJM.db.goldAmountToKeepOnToonTrade == nil then
AJM.db.goldAmountToKeepOnToonTrade = 0
end
AJM:SettingsRefresh()
end
-- Settings received.
function AJM:JambaOnSettingsReceived( characterName, settings )
if characterName ~= AJM.characterName then
-- Update the settings.
AJM.db.messageArea = settings.messageArea
AJM.db.framePoint = settings.framePoint
AJM.db.frameRelativePoint = settings.frameRelativePoint
AJM.db.frameXOffset = settings.frameXOffset
AJM.db.frameYOffset = settings.frameYOffset
AJM.db.showJambaTradeWindow = settings.showJambaTradeWindow
AJM.db.adjustMoneyWithGuildBank = settings.adjustMoneyWithGuildBank
AJM.db.goldAmountToKeepOnToon = settings.goldAmountToKeepOnToon
AJM.db.adjustMoneyWithMasterOnTrade = settings.adjustMoneyWithMasterOnTrade
AJM.db.goldAmountToKeepOnToonTrade = settings.goldAmountToKeepOnToonTrade
-- Refresh the settings.
AJM:SettingsRefresh()
-- Tell the player.
AJM:Print( L["Settings received from A."]( characterName ) )
end
end
function AJM:BeforeJambaProfileChanged()
end
function AJM:OnJambaProfileChanged()
AJM:SettingsRefresh()
end
function AJM:SettingsRefresh()
AJM.settingsControl.checkBoxShowJambaTradeWindow:SetValue( AJM.db.showJambaTradeWindow )
AJM.settingsControl.dropdownMessageArea:SetValue( AJM.db.messageArea )
AJM.settingsControl.checkBoxAdjustMoneyOnToonViaGuildBank:SetValue( AJM.db.adjustMoneyWithGuildBank )
AJM.settingsControl.editBoxGoldAmountToLeaveOnToon:SetText( tostring( AJM.db.goldAmountToKeepOnToon ) )
AJM.settingsControl.editBoxGoldAmountToLeaveOnToon:SetDisabled( not AJM.db.adjustMoneyWithGuildBank )
AJM.settingsControl.checkBoxAdjustMoneyWithMasterOnTrade:SetValue( AJM.db.adjustMoneyWithMasterOnTrade )
AJM.settingsControl.editBoxGoldAmountToLeaveOnToonTrade:SetText( tostring( AJM.db.goldAmountToKeepOnToonTrade ) )
AJM.settingsControl.editBoxGoldAmountToLeaveOnToonTrade:SetDisabled( not AJM.db.adjustMoneyWithMasterOnTrade )
end
-- A Jamba command has been received.
function AJM:JambaOnCommandReceived( characterName, commandName, ... )
if characterName == self.characterName then
return
end
if commandName == AJM.COMMAND_SHOW_INVENTORY then
AJM:SendInventory( characterName )
end
if commandName == AJM.COMMAND_HERE_IS_MY_INVENTORY then
AJM:ShowOtherToonsInventory( characterName, ... )
end
if commandName == AJM.COMMAND_LOAD_ITEM_INTO_TRADE then
AJM:LoadItemIntoTrade( ... )
end
if commandName == AJM.COMMAND_LOAD_ITEM_CLASS_INTO_TRADE then
AJM:LoadItemClassIntoTradeWindow( ... )
end
if commandName == AJM.COMMAND_GET_SLOT_COUNT then
AJM:GetSlotCountAndSendToToon( characterName )
end
if commandName == AJM.COMMAND_HERE_IS_MY_SLOT_COUNT then
AJM:SetOtherToonsSlotCount( characterName, ... )
end
end
-------------------------------------------------------------------------------------------------------------
-- Trade functionality.
-------------------------------------------------------------------------------------------------------------
function AJM:CreateInventoryFrame()
local frame = CreateFrame( "Frame", "JambaTradeInventoryWindowFrame", UIParent )
frame.parentObject = AJM
frame:SetFrameStrata( "LOW" )
frame:SetToplevel( true )
frame:SetClampedToScreen( true )
frame:EnableMouse( true )
frame:SetMovable( true )
frame:RegisterForDrag( "LeftButton" )
frame:SetScript( "OnDragStart",
function( this )
this:StartMoving()
end )
frame:SetScript( "OnDragStop",
function( this )
this:StopMovingOrSizing()
local point, relativeTo, relativePoint, xOffset, yOffset = this:GetPoint()
AJM.db.framePoint = point
AJM.db.frameRelativePoint = relativePoint
AJM.db.frameXOffset = xOffset
AJM.db.frameYOffset = yOffset
end )
frame:ClearAllPoints()
frame:SetPoint( AJM.db.framePoint, UIParent, AJM.db.frameRelativePoint, AJM.db.frameXOffset, AJM.db.frameYOffset )
frame:SetBackdrop( {
bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true, tileSize = 10, edgeSize = 20,
insets = { left = 3, right = 3, top = 3, bottom = 3 }
} )
frame:SetWidth( 323 )
frame:SetHeight( 452 )
frame.title = frame:CreateFontString( nil, "OVERLAY", "GameFontNormal" )
frame.title:SetText( "Jamba-Trade" )
frame.title:SetPoint( "TOPLEFT", frame, "TOPLEFT", 10, -7 )
frame.title:SetJustifyH( "LEFT" )
frame.title:SetJustifyV( "TOP" )
local left, right, top, bottom, width, height
left = 86
right = 400
top = 10
bottom = 35
width = right - left
height = bottom - top
local header = frame:CreateTexture( nil, "ARTWORK" )
header:SetTexture( "Interface\\BankFrame\\UI-BankFrame" )
header:ClearAllPoints()
header:SetPoint( "TOPLEFT", frame, "TOPLEFT", 7, 0 )
header:SetWidth( width )
header:SetHeight( height )
header:SetTexCoord( left/512, right/512, top/512, bottom/512 )
frame.header = header
local closeButton = CreateFrame( "Button", "JambaTradeInventoryWindowFrameButtonClose", frame, "UIPanelCloseButton" )
closeButton:SetScript( "OnClick", AJM.JambaTradeWindowCloseButtonClicked )
closeButton:SetPoint( "TOPRIGHT", frame, "TOPRIGHT", 1, 2 )
local dropDownClass = AceGUI:Create( "Dropdown" )
dropDownClass.frame:SetParent( frame )
dropDownClass:SetLabel( "" )
dropDownClass:SetPoint( "TOPLEFT", frame, "TOPLEFT", 8, -28 )
dropDownClass:SetWidth( 130 )
dropDownClass:SetList( AJM.itemClassList )
dropDownClass:SetCallback( "OnValueChanged", AJM.JambaTradeClassDropDownChanged )
frame.dropDownClass = dropDownClass
local dropDownSubClass = AceGUI:Create( "Dropdown" )
dropDownSubClass.frame:SetParent( frame )
dropDownSubClass:SetLabel( "" )
dropDownSubClass:SetPoint( "TOPLEFT", frame, "TOPLEFT", 142, -28 )
dropDownSubClass:SetWidth( 170 )
dropDownSubClass:SetCallback( "OnValueChanged", AJM.JambaTradeSubClassDropDownChanged )
frame.dropDownSubClass = dropDownSubClass
local checkBoxIgnoreSoulBound = CreateFrame( "CheckButton", "JambaTradeInventoryWindowFrameCheckButtonIgnoreSoulbound", frame, "ChatConfigCheckButtonTemplate" )
checkBoxIgnoreSoulBound:SetPoint( "TOPLEFT", frame, "TOPLEFT", 142, -95 )
checkBoxIgnoreSoulBound:SetHeight( 24 )
checkBoxIgnoreSoulBound:SetWidth( 24 )
checkBoxIgnoreSoulBound:SetScript( "OnClick", AJM.JambaTradeIgnoreSoulBoundCheckboxChanged )
frame.checkBoxIgnoreSoulBound = checkBoxIgnoreSoulBound
local labelIgnoreSoulBound = frame:CreateFontString( nil, "BACKGROUND", "GameFontHighlight" )
labelIgnoreSoulBound:SetText( L["Ignore Soulbound"] )
labelIgnoreSoulBound:SetPoint( "TOPLEFT", frame, "TOPLEFT", 167, -100 )
labelIgnoreSoulBound:SetJustifyH( "LEFT" )
labelIgnoreSoulBound:SetJustifyV( "TOP" )
labelIgnoreSoulBound:SetWidth( 150 )
frame.labelIgnoreSoulBound = labelIgnoreSoulBound
local labelMineBags = frame:CreateFontString( nil, "BACKGROUND", "GameFontHighlight" )
labelMineBags:SetText( "" )
labelMineBags:SetPoint( "TOPLEFT", frame, "TOPLEFT", 145, -63 )
labelMineBags:SetJustifyH( "LEFT" )
labelMineBags:SetJustifyV( "TOP" )
labelMineBags:SetWidth( 370 )
frame.labelMineBags = labelMineBags
local labelTheirsBags = frame:CreateFontString( nil, "BACKGROUND", "GameFontHighlight" )
labelTheirsBags:SetText( "")
labelTheirsBags:SetPoint( "TOPLEFT", frame, "TOPLEFT", 145, -80 )
labelTheirsBags:SetJustifyH( "LEFT" )
labelTheirsBags:SetJustifyV( "TOP" )
labelTheirsBags:SetWidth( 370 )
frame.labelTheirsBags = labelTheirsBags
local loadMineButton = CreateFrame( "Button", "JambaTradeInventoryWindowFrameButtonLoadMine", frame, "UIPanelButtonTemplate" )
loadMineButton:SetScript( "OnClick", AJM.JambaTradeLoadMineButtonClicked )
loadMineButton:SetPoint( "TOPLEFT", frame, "TOPLEFT", 10, -60 )
loadMineButton:SetHeight( 24 )
loadMineButton:SetWidth( 100 )
loadMineButton:SetText( L["Load Mine"] )
frame.loadMineButton = loadMineButton
local loadTheirsButton = CreateFrame( "Button", "JambaTradeInventoryWindowFrameButtonLoadTheirs", frame, "UIPanelButtonTemplate" )
loadTheirsButton:SetScript( "OnClick", AJM.JambaTradeLoadTheirsButtonClicked )
loadTheirsButton:SetPoint( "TOPLEFT", frame, "TOPLEFT", 10, -87 )
loadTheirsButton:SetHeight( 24 )
loadTheirsButton:SetWidth( 100 )
loadTheirsButton:SetText( L["Load Theirs"] )
frame.loadTheirsButton = loadTheirsButton
local blockNumber = 0
local cellCounter = 0
local blockRowSize = 7
local blockColumnSize = 8
local cellXOffset = 4
local cellYOffset = -4
local cellXSpacing = 4
local cellYSpacing = 4
local xOffset = 6
local yOffset = header:GetHeight() + 93
local blockXLocation, blockYLocation
local cellHeight, cellWidth
local tempButton = CreateFrame( "Button", "JambaTradeInventoryWindowFrameButtonTemp", frame, "ItemButtonTemplate" )
cellWidth = tempButton:GetWidth()
cellHeight = tempButton:GetHeight()
tempButton:Hide()
AJM.tradeScrollRowHeight = cellHeight + cellYSpacing
AJM.tradeScrollRowsToDisplay = 1 * blockColumnSize
AJM.tradeScrollMaximumRows = AJM.tradeScrollRowsToDisplay
AJM.tradeScrollOffset = 0
AJM.tradeScrollItemsPerRow = 1 * blockRowSize
frame.tradeScrollFrame = CreateFrame( "ScrollFrame", frame:GetName().."ScrollFrame", frame, "FauxScrollFrameTemplate" )
frame.tradeScrollFrame:SetPoint( "TOPLEFT", frame, "TOPLEFT", -27, -yOffset )
frame.tradeScrollFrame:SetPoint( "BOTTOMRIGHT", frame, "BOTTOMRIGHT", -27, 5 )
frame.tradeScrollFrame:SetScript( "OnVerticalScroll",
function( self, offset )
FauxScrollFrame_OnVerticalScroll(
self,
offset,
AJM.tradeScrollRowHeight,
AJM.TradeScrollRefreshCallback )
end
)
frame.slotBackgrounds = {}
frame.slots = {}
left = 79
right = 121
top = 255
bottom = 296
width = right - left
height = bottom - top
for blockY = 0, (blockColumnSize - 1) do
for blockX = 0, (blockRowSize - 1) do
blockNumber = blockX + (blockY * blockColumnSize)
local slotTexture = frame:CreateTexture( nil, "ARTWORK" )
slotTexture:SetTexture( "Interface\\ContainerFrame\\UI-Bag-Components-Bank" )
slotTexture:ClearAllPoints()
blockXLocation = xOffset + (1 * (blockX * width))
blockYLocation = -yOffset + (-1 * (blockY * height))
slotTexture:SetPoint( "TOPLEFT", frame, "TOPLEFT", blockXLocation, blockYLocation )
slotTexture:SetWidth( width )
slotTexture:SetHeight( height )
slotTexture:SetTexCoord( left/256, right/256, top/512, bottom/512 )
frame.slotBackgrounds[blockNumber] = slotTexture
frame.slots[cellCounter] = CreateFrame( "Button", "JambaTradeInventoryWindowFrameButton"..cellCounter, frame, "ItemButtonTemplate" )
frame.slots[cellCounter]:SetPoint( "TOPLEFT", frame, "TOPLEFT", cellXOffset + blockXLocation, cellYOffset + blockYLocation )
frame.slots[cellCounter]:SetScript( "OnClick", function( self ) AJM:OtherToonInventoryButtonClick( self ) end)
frame.slots[cellCounter]:SetScript( "OnEnter", function( self ) AJM:OtherToonInventoryButtonEnter( self ) end )
frame.slots[cellCounter]:SetScript( "OnLeave", function( self ) AJM:OtherToonInventoryButtonLeave( self ) end)
frame.slots[cellCounter]:Hide()
cellCounter = cellCounter + 1
end
end
JambaTradeInventoryFrame = frame
table.insert( UISpecialFrames, "JambaTradeInventoryWindowFrame" )
JambaTradeInventoryFrame:Hide()
end
function AJM:JambaTradeWindowCloseButtonClicked()
JambaTradeInventoryFrame:Hide()
end
function AJM:JambaTradeClassDropDownChanged( event, value )
AJM.itemClassCurrentSelection = value
JambaTradeInventoryFrame.dropDownSubClass:SetList( AJM.itemClassSubList[value] )
JambaTradeInventoryFrame.dropDownSubClass:SetValue( AJM.itemClassSubListLastSelection[value] )
AJM:TradeScrollRefreshCallback()
end
function AJM:JambaTradeSubClassDropDownChanged( event, value )
AJM.itemSubClassCurrentSelection = value
AJM.itemClassSubListLastSelection[AJM.itemClassCurrentSelection] = AJM.itemSubClassCurrentSelection
AJM:TradeScrollRefreshCallback()
end
function AJM:JambaTradeIgnoreSoulBoundCheckboxChanged()
if JambaTradeInventoryFrame.checkBoxIgnoreSoulBound:GetChecked() then
AJM.db.ignoreSoulBound = true
else
AJM.db.ignoreSoulBound = false
end
end
function AJM.JambaTradeLoadMineButtonClicked()
AJM:LoadItemClassIntoTradeWindow( AJM.itemClassCurrentSelection, AJM.itemSubClassCurrentSelection, AJM.db.ignoreSoulBound )
end
function AJM.JambaTradeLoadTheirsButtonClicked()
AJM:JambaSendCommandToToon( UnitName( "npc" ), AJM.COMMAND_LOAD_ITEM_CLASS_INTO_TRADE, AJM.itemClassCurrentSelection, AJM.itemSubClassCurrentSelection, AJM.db.ignoreSoulBound )
end
function AJM:OtherToonInventoryButtonEnter( self )
if self.link ~= nil then
GameTooltip_SetDefaultAnchor( GameTooltip, self )
GameTooltip:SetOwner( self, "ANCHOR_LEFT" )
GameTooltip:ClearLines()
GameTooltip:SetHyperlink( self.link )
CursorUpdate()
end
end
function AJM:OtherToonInventoryButtonLeave( self )
if self.link ~= nil then
GameTooltip:Hide()
ResetCursor()
end
end
function AJM:OtherToonInventoryButtonClick( self )
AJM:JambaSendCommandToToon( UnitName( "npc" ), AJM.COMMAND_LOAD_ITEM_INTO_TRADE, self.bag, self.slot, false )
SetItemButtonDesaturated( self, 1, 0.5, 0.5, 0.5 )
end
function AJM:GetInventory()
local itemId
AJM.inventory = ""
for bag, slot, link in LibBagUtils:Iterate( "BAGS" ) do
-- Don't send slots that have no items and don't send anything in the keyring bag (-2)
if link ~= nil and bag ~= -2 then
local texture, itemCount, locked, quality, readable = GetContainerItemInfo( bag, slot )
itemId = JambaUtilities:GetItemIdFromItemLink( link )
AJM.inventory = AJM.inventory..bag..AJM.inventoryPartSeperator..slot..AJM.inventoryPartSeperator..itemId..AJM.inventoryPartSeperator..itemCount..AJM.inventorySeperator
end
end
end
function AJM:JambaTradeLoadTypeCommand( info, parameters )
local class, subclass = strsplit( ",", parameters )
if class ~= nil and class:trim() ~= "" and subclass ~= nil and subclass:trim() ~= "" then
AJM:LoadItemClassIntoTradeWindow( class:trim(), subclass:trim(), false )
else
AJM:JambaSendMessageToTeam( AJM.db.messageArea, L["Jamba-Trade: Please provide a class and a subclass seperated by a comma for the loadtype command."], false )
end
end
function AJM:JambaTradeLoadNameCommand( info, parameters )
local itemName, amount = strsplit( ",", parameters )
if itemName ~= nil and itemName:trim() ~= "" and amount ~= nil and amount:trim() ~= "" then
AJM:SplitStackItemByNameLimitAmount( itemName:trim(), amount:trim() )
else
AJM:JambaSendMessageToTeam( AJM.db.messageArea, L["Jamba-Trade: Please provide a name and an amount seperated by a comma for the loadname command."], false )
end
end
function AJM:TRADE_SHOW( event, ... )
if AJM.db.showJambaTradeWindow == true then
AJM:TradeShowDisplayJambaTrade()
end
if AJM.db.adjustMoneyWithMasterOnTrade == true then
AJM:ScheduleTimer( "TradeShowAdjustMoneyWithMaster", 1 )
end
end
function AJM:TradeShowAdjustMoneyWithMaster()
if JambaApi.IsCharacterTheMaster( AJM.characterName ) == true then
return
end
local moneyToKeepOnToon = tonumber( AJM.db.goldAmountToKeepOnToonTrade ) * 10000
local moneyOnToon = GetMoney()
local moneyToDepositOrWithdraw = moneyOnToon - moneyToKeepOnToon
if moneyToDepositOrWithdraw == 0 then
return
end
if moneyToDepositOrWithdraw > 0 then
PickupPlayerMoney( moneyToDepositOrWithdraw )
AddTradeMoney()
end
end
function AJM:TradeShowDisplayJambaTrade()
local slotsFree, totalSlots = LibBagUtils:CountSlots( "BAGS", 0 )
JambaTradeInventoryFrame.labelMineBags:SetText( self.characterName..": "..(totalSlots - slotsFree).."/"..totalSlots )
if slotsFree < 6 then
JambaTradeInventoryFrame.labelMineBags:SetTextColor( 0.9, 0.0, 0.0 )
end
JambaTradeInventoryFrame.checkBoxIgnoreSoulBound:SetChecked( AJM.db.ignoreSoulBound )
AJM:JambaTradeIgnoreSoulBoundCheckboxChanged()
AJM:JambaSendCommandToToon( UnitName( "npc" ), AJM.COMMAND_GET_SLOT_COUNT )
AJM:LoadThisToonsClasses()
AJM:JambaSendCommandToToon( UnitName( "npc" ), AJM.COMMAND_SHOW_INVENTORY )
end
function AJM:TRADE_CLOSED()
if AJM.db.showJambaTradeWindow == false then
return
end
JambaTradeInventoryFrame:Hide()
end
function AJM:GUILDBANKFRAME_OPENED()
if AJM.db.adjustMoneyWithGuildBank == false then
return
end
if not CanWithdrawGuildBankMoney() then
return
end
local moneyToKeepOnToon = tonumber( AJM.db.goldAmountToKeepOnToon ) * 10000
local moneyOnToon = GetMoney()
local moneyToDepositOrWithdraw = moneyOnToon - moneyToKeepOnToon
if moneyToDepositOrWithdraw == 0 then
return
end
if moneyToDepositOrWithdraw > 0 then
DepositGuildBankMoney( moneyToDepositOrWithdraw )
else
WithdrawGuildBankMoney( -1 * moneyToDepositOrWithdraw )
end
end
function AJM:SendInventory( characterName )
AJM:GetInventory()
AJM:JambaSendCommandToToon( characterName, AJM.COMMAND_HERE_IS_MY_INVENTORY, AJM.inventory )
end
function AJM:GetSlotCountAndSendToToon( characterName )
local slotsFree, totalSlots = LibBagUtils:CountSlots( "BAGS", 0 )
AJM:JambaSendCommandToToon( characterName, AJM.COMMAND_HERE_IS_MY_SLOT_COUNT, slotsFree, totalSlots )
end
function AJM:SetOtherToonsSlotCount( characterName, slotsFree, totalSlots )
JambaTradeInventoryFrame.labelTheirsBags:SetText( characterName..": "..(totalSlots - slotsFree).."/"..totalSlots )
if slotsFree < 6 then
JambaTradeInventoryFrame.labelTheirsBags:SetTextColor( 0.9, 0.0, 0.0 )
end
end
function AJM:LoadItemIntoTrade( bag, slot, ignoreSoulBound )
ClearCursor()
LibGratuity:SetBagItem( bag, slot )
if LibGratuity:Find( ITEM_SOULBOUND, 1, 3 ) then
-- SOULBOUND
if ignoreSoulBound == true then
return true
end
if GetTradePlayerItemLink( MAX_TRADE_ITEMS ) == nil then
PickupContainerItem( bag, slot )
ClickTradeButton( MAX_TRADE_ITEMS )
return true
end
else
for iterateTradeSlots = 1, (MAX_TRADE_ITEMS - 1) do
if GetTradePlayerItemLink( iterateTradeSlots ) == nil then
PickupContainerItem( bag, slot )
ClickTradeButton( iterateTradeSlots )
return true
end
end
end
ClearCursor()
return false
end
function AJM:LoadItemClassIntoTradeWindow( requiredClass, requiredSubClass, ignoreSoulBound )
for bag, slot, link in LibBagUtils:Iterate( "BAGS" ) do
-- Ignore slots that have no items and ignore anything in the keyring bag (-2)
if link ~= nil and bag ~= -2 then
local itemId = JambaUtilities:GetItemIdFromItemLink( link )
local name, link, quality, iLevel, reqLevel, class, subClass, maxStack, equipSlot, texture, vendorPrice = GetItemInfo( itemId )
if requiredClass == L["!Single Item"] then
if requiredSubClass == name then
if AJM:LoadItemIntoTrade( bag, slot, ignoreSoulBound ) == false then
return
end
end
end
if requiredClass == L["!Quality"] then
if requiredSubClass == AJM:GetQualityName( quality ) then
if AJM:LoadItemIntoTrade( bag, slot, ignoreSoulBound ) == false then
return
end
end
end
if requiredClass == class and requiredSubClass == subClass then
if AJM:LoadItemIntoTrade( bag, slot, ignoreSoulBound ) == false then
return
end
end
end
end
end
function AJM:SplitStackItemByNameLimitAmount( name, amount )
amount = tonumber( amount )
local foundAndSplit = false
for bag, slot, link in LibBagUtils:Iterate( "BAGS", name ) do
-- If the item has been found and split, then finish up this section.
if foundAndSplit == true then
break
end
-- Attempt to split the item to the request amount.
SplitContainerItem( bag, slot, amount )
-- If successful, cursor will have item, stick it into an empty spot in the bags.
if CursorHasItem() then
LibBagUtils:PutItem( "BAGS" )
foundAndSplit = true
end
end
-- If item was found and split successfully then look for item stack of the request size and attempt to put it in the trade window.
if foundAndSplit == true then
AJM:ScheduleTimer( "LoadItemByNameLimitAmountIntoTradeWindow", 5, name..","..tostring( amount ) )
end
end
function AJM:LoadItemByNameLimitAmountIntoTradeWindow( nameAndAmount )
local name, amount = strsplit( ",", nameAndAmount )
amount = tonumber( amount )
for bag, slot, link in LibBagUtils:Iterate( "BAGS", name ) do
local texture, count, locked, quality, readable, lootable, link = GetContainerItemInfo( bag, slot )
if count == amount then
-- This stack is the required size.
AJM:LoadItemIntoTrade( bag, slot, false )
break
end
end
end
local function JambaInventoryClassSort( a, b )
local aClass = ""
local bClass = ""
local aSubClass = ""
local bSubClass = ""
local aName = ""
local bName = ""
if a ~= nil then
aClass = a.class
aSubClass = a.subClass
aName = a.name
end
if b ~= nil then
bClass = b.class
bSubClass = b.subClass
bName = b.name
end
if aClass == bClass then
if aSubClass == bSubClass then
return aName > bName
end
return aSubClass > bSubClass
end
return aClass > bClass
end
function AJM:AddToClassAndSubClassLists( class, subClass )
if class ~= nil then
if AJM.itemClassList[class] == nil then
AJM.itemClassList[class] = class
AJM.itemClassSubList[class] = {}
AJM.itemClassSubListLastSelection[class] = ""
end
if class ~= nil and subClass ~= nil then
AJM.itemClassSubList[class][subClass] = subClass
end
end
end
function AJM:GetQualityName( quality )
if quality == LE_ITEM_QUALITY_POOR then
return L["0. Poor (gray)"]
end
if quality == LE_ITEM_QUALITY_COMMON then
return L["1. Common (white)"]
end
if quality == LE_ITEM_QUALITY_UNCOMMON then
return L["2. Uncommon (green)"]
end
if quality == LE_ITEM_QUALITY_RARE then
return L["3. Rare / Superior (blue)"]
end
if quality == LE_ITEM_QUALITY_EPIC then
return L["4. Epic (purple)"]
end
if quality == LE_ITEM_QUALITY_LEGENDARY then
return L["5. Legendary (orange)"]
end
if quality == 6 then
return L["6. Artifact (golden yellow)"]
end
if quality == LE_ITEM_QUALITY_HEIRLOOM then
return L["7. Heirloom (light yellow)"]
end
return L["Unknown"]
end
function AJM:LoadThisToonsClasses()
local itemId
for bag, slot, link in LibBagUtils:Iterate( "BAGS" ) do
-- Don't send slots that have no items and don't send anything in the keyring bag (-2)
if link ~= nil and bag ~= -2 then
itemId = JambaUtilities:GetItemIdFromItemLink( link )
local name, link, quality, iLevel, reqLevel, class, subClass, maxStack, equipSlot, texture, vendorPrice = GetItemInfo( itemId )
if name ~= nil then
AJM:AddToClassAndSubClassLists( L["!Single Item"], name )
end
if quality ~= nil then
AJM:AddToClassAndSubClassLists( L["!Quality"], AJM:GetQualityName( quality ) )
end
AJM:AddToClassAndSubClassLists( class, subClass )
end
end
end
function AJM:ShowOtherToonsInventory( characterName, inventory )
table.wipe( AJM.inventorySortedTable )
local inventoryLines = { strsplit( AJM.inventorySeperator, inventory ) }
local inventoryInfo
for index, line in ipairs( inventoryLines ) do
local bag, slot, inventoryItemID, itemCount = strsplit( AJM.inventoryPartSeperator, line )
if inventoryItemID ~= nil and inventoryItemID ~= "" then
local name, link, quality, iLevel, reqLevel, class, subClass, maxStack, equipSlot, texture, vendorPrice = GetItemInfo( inventoryItemID )
AJM:AddToClassAndSubClassLists( class, subClass )
if name ~= nil then
AJM:AddToClassAndSubClassLists( L["!Single Item"], name )
end
if quality ~= nil then
AJM:AddToClassAndSubClassLists( L["!Quality"], AJM:GetQualityName( quality ) )
end
if texture == nil then
class = "?"
name = "?"
end
inventoryInfo = {}
inventoryInfo.bag = bag
inventoryInfo.slot = slot
inventoryInfo.inventoryItemID = inventoryItemID
inventoryInfo.itemCount = itemCount
inventoryInfo.class = class
inventoryInfo.subClass = subClass
inventoryInfo.name = name
table.insert( AJM.inventorySortedTable, inventoryInfo )
end
end
table.sort( AJM.inventorySortedTable, JambaInventoryClassSort )
-- Start the row at 1, and the column at 0.
local rowCounter = 0
local columnCounter = AJM.tradeScrollItemsPerRow - 1
table.wipe( AJM.inventoryInDisplayTable )
for index, line in ipairs( AJM.inventorySortedTable ) do
columnCounter = columnCounter + 1
if columnCounter == AJM.tradeScrollItemsPerRow then
rowCounter = rowCounter + 1
columnCounter = 0
end
if AJM.inventoryInDisplayTable[rowCounter] == nil then
AJM.inventoryInDisplayTable[rowCounter] = {}
end
AJM.inventoryInDisplayTable[rowCounter][columnCounter] = {}
AJM.inventoryInDisplayTable[rowCounter][columnCounter]["bag"] = line.bag
AJM.inventoryInDisplayTable[rowCounter][columnCounter]["slot"] = line.slot
AJM.inventoryInDisplayTable[rowCounter][columnCounter]["inventoryItemID"] = line.inventoryItemID
AJM.inventoryInDisplayTable[rowCounter][columnCounter]["itemCount"] = line.itemCount
end
AJM.tradeScrollMaximumRows = rowCounter
AJM:TradeScrollRefreshCallback()
JambaTradeInventoryFrame.dropDownClass:SetList( AJM.itemClassList )
JambaTradeInventoryFrame:Show()
end
function AJM:TradeScrollRefreshCallback()
FauxScrollFrame_Update(
JambaTradeInventoryFrame.tradeScrollFrame,
AJM.tradeScrollMaximumRows,
AJM.tradeScrollRowsToDisplay,
AJM.tradeScrollRowHeight
)
AJM.tradeScrollOffset = FauxScrollFrame_GetOffset( JambaTradeInventoryFrame.tradeScrollFrame )
local slotNumber, columnNumber, slot
local r, g, b
for iterateDisplayRows = 1, AJM.tradeScrollRowsToDisplay do
-- Reset cells.
for columnNumber = 0, (AJM.tradeScrollItemsPerRow - 1) do
slotNumber = columnNumber + ((iterateDisplayRows - 1) * AJM.tradeScrollItemsPerRow)
slot = JambaTradeInventoryFrame.slots[slotNumber]
SetItemButtonTexture( slot, "" )
slot:Hide()
end
-- Get data.
local dataRowNumber = iterateDisplayRows + AJM.tradeScrollOffset
if dataRowNumber <= AJM.tradeScrollMaximumRows then
-- Put items in cells.
for columnNumber, inventoryInfoTable in pairs( AJM.inventoryInDisplayTable[dataRowNumber] ) do
slotNumber = columnNumber + ((iterateDisplayRows - 1) * AJM.tradeScrollItemsPerRow)
slot = JambaTradeInventoryFrame.slots[slotNumber]
local name, link, quality, iLevel, reqLevel, class, subClass, maxStack, equipSlot, texture, vendorPrice = GetItemInfo( inventoryInfoTable["inventoryItemID"] )
if texture == nil then
texture = "Interface\\Icons\\Temp"
r = 0.9
g = 0.0
b = 0.0
else
r, g, b = GetItemQualityColor( quality )
end
SetItemButtonTexture( slot, texture )
SetItemButtonCount( slot, tonumber( inventoryInfoTable["itemCount"] ) )
if AJM.itemClassCurrentSelection == class and AJM.itemSubClassCurrentSelection == subClass then
SetItemButtonTextureVertexColor( slot, 0.4, 0.9, 0.0 )
SetItemButtonNormalTextureVertexColor( slot, 0.9, 0.9, 0.0 )
elseif AJM.itemClassCurrentSelection == L["!Single Item"] and AJM.itemSubClassCurrentSelection == name then
SetItemButtonTextureVertexColor( slot, 0.4, 0.9, 0.0 )
SetItemButtonNormalTextureVertexColor( slot, 0.9, 0.9, 0.0 )
elseif AJM.itemClassCurrentSelection == L["!Quality"] and AJM.itemSubClassCurrentSelection == AJM:GetQualityName( quality ) then
SetItemButtonTextureVertexColor( slot, 0.4, 0.9, 0.0 )
SetItemButtonNormalTextureVertexColor( slot, 0.9, 0.9, 0.0 )
else
SetItemButtonTextureVertexColor( slot, 1.0, 1.0, 1.0 )
SetItemButtonNormalTextureVertexColor( slot, r, g, b )
end
slot.link = link
slot.bag = inventoryInfoTable["bag"]
slot.slot = inventoryInfoTable["slot"]
slot:Show()
end
end
end
end
| mit |
Sonicrich05/FFXI-Server | scripts/zones/West_Sarutabaruta/npcs/Banege_RK.lua | 30 | 3066 | -----------------------------------
-- Area: West Sarutabaruta
-- NPC: Banege, R.K.
-- 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 = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = SARUTABARUTA;
local csid = 0x7ffa;
-----------------------------------
-- 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 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/spells/blizzaga.lua | 2 | 1025 | -----------------------------------------
-- Spell: Blizzaga
-- Deals ice damage to an enemy.
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function OnMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
--calculate raw damage
dmg = calculateMagicDamage(145,1,caster,spell,target,ELEMENTAL_MAGIC_SKILL,MOD_INT,false);
--get resist multiplier (1x if no resist)
resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL,1.0);
--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);
--add in final adjustments
dmg = finalMagicAdjustments(caster,target,spell,dmg);
return dmg;
end; | gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Chateau_dOraguille/npcs/Chaloutte.lua | 4 | 1054 | -----------------------------------
-- Area: Chateau d'Oraguille
-- NPC: Chaloutte
-- Type: Event Scene Replayer
-- @zone: 233
-- @pos: 10.450 -1 -11.985
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x022d);
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 |
ArtixBot/tome4-minstrel | tome-minstrel/overload/data/gfx/particles/revivification.lua | 1 | 1564 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2017 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
can_shift = true
base_size = 32
return { blend_mode=core.particles.BLEND_SHINY, generator = function()
local ad = rng.range(0, 360)
local a = math.rad(ad)
local dir = math.rad(ad + 90)
local r = rng.range(12, 20)
local dirv = math.rad(1)
return {
trail = 0,
life = rng.range(10, 20),
size = rng.range(2, 6), sizev = -0.1, sizea = 0,
x = r * math.cos(a), xv = 0, xa = 0,
y = r * math.sin(a), yv = 0, ya = 0,
dir = dir, dirv = -dirv, dira = 0,
vel = rng.percent(50) and -1 or 1, velv = 0, vela = 0,
r = rng.range(133, 153)/255, rv = 0, ra = 0,
g = rng.range(233, 253)/255, gv = 0, ga = 0,
b = rng.range(157, 177)/255, bv = 0, ba = 0,
a = rng.range(25, 220)/255, av = -0.03, aa = 0,
}
end, },
function(self)
self.ps:emit(10)
end,
200, "particle_torus"
| gpl-3.0 |
DiNaSoR/Angel_Arena | game/angel_arena/scripts/vscripts/items/rubick_dagon/rubick_dagon.lua | 1 | 1466 | if item_rubick_dagon == nil then
item_rubick_dagon = class({})
end
LinkLuaModifier( "modifier_rubick_dagon_passive", 'items/rubick_dagon/modifier_rubick_dagon_passive', LUA_MODIFIER_MOTION_NONE )
function item_rubick_dagon:GetIntrinsicModifierName()
return "modifier_rubick_dagon_passive"
end
function item_rubick_dagon:OnSpellStart()
local caster = self:GetCaster()
local target = self:GetCursorTarget()
if not caster or not target then return end
if target:TriggerSpellAbsorb(self) then return end
local int_pct = self:GetSpecialValueFor("int_damage_pct") / 100
local dagon_level = 6
local dagon_particle = ParticleManager:CreateParticle("particles/items_fx/dagon.vpcf", PATTACH_ABSORIGIN_FOLLOW, caster)
local particle_effect_intensity = 300 + (100 * dagon_level)
ParticleManager:SetParticleControlEnt(dagon_particle, 1, target, PATTACH_POINT_FOLLOW, "attach_hitloc", target:GetAbsOrigin(), false)
ParticleManager:SetParticleControl(dagon_particle, 2, Vector(particle_effect_intensity))
caster:EmitSound("DOTA_Item.Dagon.Activate")
target:EmitSound("DOTA_Item.Dagon5.Target")
if IsServer() then
if not caster:IsRealHero() then
local player = caster:GetPlayerOwner()
caster = player:GetAssignedHero()
end
local damage = caster:GetIntellect()*int_pct + self:GetSpecialValueFor("damage");
ApplyDamage({ victim = target, attacker = caster, damage = damage, damage_type = DAMAGE_TYPE_MAGICAL })
end
end | mit |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Northern_San_dOria/npcs/Daveille.lua | 6 | 1369 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Daveille
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0248);
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 |
Sonicrich05/FFXI-Server | scripts/globals/effects/accuracy_down.lua | 18 | 1045 | -----------------------------------
--
-- EFFECT_ACCURACY_DOWN
--
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
if (effect:getPower()>100) then
effect:setPower(50);
end
target:addMod(MOD_ACCP,-effect:getPower());
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
-- the effect restore accuracy of 1 every 3 ticks.
local downACC_effect_size = effect:getPower()
if (downACC_effect_size > 0) then
effect:setPower(downACC_effect_size - 1)
target:delMod(MOD_ACC,-1);
end
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
local downACC_effect_size = effect:getPower()
if (downACC_effect_size > 0) then
target:delMod(MOD_ACCP,-effect:getPower());
end
end; | gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Bibiki_Bay/npcs/Tswe_Panipahr.lua | 4 | 1935 | -----------------------------------
-- Area: Bibiki Bay
-- NPC: Tswe Panipahr
-- Type: Manaclipper
-- @zone: 4
-- @pos: 484.604 -4.035 729.671
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Bibiki_Bay/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Bibiki_Bay/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local curentticket=0;
if (player:hasKeyItem(MANACLIPPER_TICKET))then
curentticket=MANACLIPPER_TICKET;
elseif(player:hasKeyItem(MANACLIPPER_MULTITICKET))then
curentticket=MANACLIPPER_MULTITICKET;
end
if ( curentticket ~= 0 )then
player:messageSpecial(HAVE_BILLET,curentticket);
else
local gils=player:getGil();
player:startEvent(0x0023,MANACLIPPER_TICKET,MANACLIPPER_MULTITICKET ,80,gils,0,500);
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 == 0x0023)then
if (option==1)then
player:delGil(80);
player:addKeyItem(MANACLIPPER_TICKET);
player:messageSpecial(KEYITEM_OBTAINED,MANACLIPPER_TICKET);
elseif(option==2)then
player:delGil(500);
player:addKeyItem(MANACLIPPER_MULTITICKET);
player:messageSpecial(KEYITEM_OBTAINED,MANACLIPPER_MULTITICKET);
player:setVar("Manaclipper_Ticket",10);
end
end
end;
| gpl-3.0 |
paulosalvatore/forgottenserver | data/spells/scripts/attack/inflict_wound.lua | 5 | 1059 | local combat = Combat()
combat:setParameter(COMBAT_PARAM_TYPE, COMBAT_PHYSICALDAMAGE)
combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_DRAWBLOOD)
combat:setParameter(COMBAT_PARAM_DISTANCEEFFECT, CONST_ANI_WEAPONTYPE)
local function getHighestSkillLevel(creature)
local skillLevel = -1
for skillType = SKILL_CLUB, SKILL_AXE do
if skillLevel < creature:getEffectiveSkillLevel(skillType) then
skillLevel = creature:getEffectiveSkillLevel(skillType)
end
end
return skillLevel
end
function onTargetCreature(creature, target)
local skill = getHighestSkillLevel(creature)
local min = (creature:getLevel() / 80) + (skill * 0.2) + 2
local max = (creature:getLevel() / 80) + (skill * 0.4) + 2
local damage = math.random(math.floor(min), math.floor(max))
creature:addDamageCondition(target, CONDITION_BLEEDING, 1, target:isPlayer() and math.floor(damage / 4 + 0.5) or damage)
return true
end
combat:setCallback(CALLBACK_PARAM_TARGETCREATURE, "onTargetCreature")
function onCastSpell(creature, variant)
return combat:execute(creature, variant)
end
| gpl-2.0 |
Sonicrich05/FFXI-Server | scripts/zones/Windurst_Woods/npcs/Peshi_Yohnts.lua | 44 | 2158 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Peshi Yohnts
-- Type: Bonecraft Guild Master
-- @pos -6.175 -6.249 -144.667 241
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local newRank = tradeTestItem(player,npc,trade,SKILL_BONECRAFT);
if (newRank ~= 0) then
player:setSkillRank(SKILL_BONECRAFT,newRank);
player:startEvent(0x2721,0,0,0,0,newRank);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local getNewRank = 0;
local craftSkill = player:getSkillLevel(SKILL_BONECRAFT);
local testItem = getTestItem(player,npc,SKILL_BONECRAFT);
local guildMember = isGuildMember(player,2);
if (guildMember == 1) then guildMember = 64; end
if (canGetNewRank(player,craftSkill,SKILL_BONECRAFT) == 1) then getNewRank = 100; end
player:startEvent(0x2720,testItem,getNewRank,30,guildMember,44,0,0,0);
end;
-- 0x2720 0x2721 0x02c6 0x02c7 0x02c8 0x02c9 0x02ca 0x02cb 0x02fc
-----------------------------------
-- 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 == 0x2720 and option == 1) then
local crystal = math.random(4096,4101);
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,crystal);
else
player:addItem(crystal);
player:messageSpecial(ITEM_OBTAINED,crystal);
signupGuild(player,4);
end
end
end; | gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/meat_mithkabob.lua | 3 | 1342 | -----------------------------------------
-- ID: 4381
-- Item: meat_mithkabob
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Strength 5
-- Agility 1
-- Intelligence -2
-- Attack % 22
-- Attack Cap 60
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,4381);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 5);
target:addMod(MOD_AGI, 1);
target:addMod(MOD_INT, -2);
target:addMod(MOD_FOOD_ATTP, 22);
target:addMod(MOD_FOOD_ATT_CAP, 60);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 5);
target:delMod(MOD_AGI, 1);
target:delMod(MOD_INT, -2);
target:delMod(MOD_FOOD_ATTP, 22);
target:delMod(MOD_FOOD_ATT_CAP, 60);
end;
| gpl-3.0 |
JesterXL/Corona-SDK---Adobe-AIR-Workshop-and-Refactoring-Presentation | Gaming/code-gaming/Corona/Lesson-5/5-c/main.lua | 1 | 2027 | require "physics"
physics.start()
physics.setDrawMode( "hybrid" )
physics.setGravity( 0, 0 )
stage = display.getCurrentStage()
player = display.newImage("player.png")
player.x = 40
player.y = 40
physics.addBody( player, { density = 1.0, friction = 0.3, bounce = 0.2,
bodyType = "kinematic",
isBullet = true, isSensor = true, isFixedRotation = true
})
function newEnemy()
local enemy = display.newImage("enemy.png")
enemy.y = 40
enemy.x = math.random() * stage.width
function enemy:enterFrame(event)
self.y = self.y + 3
if self.y > stage.height then
Runtime:removeEventListener("enterFrame", self)
self:removeSelf()
end
end
Runtime:addEventListener("enterFrame", enemy)
physics.addBody( enemy, { density = 1.0, friction = 0.3, bounce = 0.2,
bodyType = "kinematic",
isBullet = true, isSensor = true, isFixedRotation = true
})
return enemy
end
function newBullet()
print("newBullet")
local bullet = display.newImage("player_bullet.png")
bullet.x = player.x
bullet.y = player.y
function bullet:enterFrame(event)
self.y = self.y - 6
if self.y < 0 then
Runtime:removeEventListener("enterFrame", self)
self:removeSelf()
end
end
Runtime:addEventListener("enterFrame", bullet)
physics.addBody( bullet, { density = 1.0, friction = 0.3, bounce = 0.2,
bodyType = "kinematic",
isBullet = true, isSensor = true, isFixedRotation = true
})
return bullet
end
function startBulletTimer()
stopBulletTimer()
bulletTimer = timer.performWithDelay(500, newBullet, 0)
end
function stopBulletTimer()
if bulletTimer ~= nil then
timer.cancel(bulletTimer)
bulletTimer = nil
end
end
function onTouch(event)
player.x = event.x
player.y = event.y - 60
if event.phase == "began" then
startBulletTimer()
elseif event.phase == "ended" or event.phase == "cancelled" then
stopBulletTimer()
end
end
function onTimer(event)
newEnemy()
end
Runtime:addEventListener("touch", onTouch)
timer.performWithDelay(1000, onTimer, 0)
| mit |
Sonicrich05/FFXI-Server | scripts/globals/abilities/pets/ecliptic_howl.lua | 20 | 1294 | ---------------------------------------------------
-- Aerial Armor
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
require("scripts/globals/utils");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onPetAbility(target, pet, skill, summoner)
local bonusTime = utils.clamp(summoner:getSkillLevel(SKILL_SUM) - 300, 0, 200);
local duration = 180 + bonusTime;
local moon = VanadielMoonPhase();
local buffvalue = 0;
if moon > 90 then
buffvalue = 25;
elseif moon > 75 then
buffvalue = 21;
elseif moon > 60 then
buffvalue = 17;
elseif moon > 40 then
buffvalue = 13;
elseif moon > 25 then
buffvalue = 9;
elseif moon > 10 then
buffvalue = 5;
else
buffvalue = 1;
end
target:delStatusEffect(EFFECT_ACCURACY_BOOST);
target:delStatusEffect(EFFECT_EVASION_BOOST);
target:addStatusEffect(EFFECT_ACCURACY_BOOST,buffvalue,0,duration);
target:addStatusEffect(EFFECT_EVASION_BOOST,25-buffvalue,0,duration);
skill:setMsg(0);
return 0;
end | gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/globals/mobskills/Dispelling_Wind.lua | 18 | 1037 | ---------------------------------------------
-- Dispelling Wind
--
-- Description: Dispels two effects from targets in an area of effect.
-- Type: Enfeebling
-- Utsusemi/Blink absorb: Ignores shadows
-- Range: 10' radial
-- Notes:
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local dis1 = target:dispelStatusEffect();
local dis2 = target:dispelStatusEffect();
if (dis1 ~= EFFECT_NONE and dis2 ~= EFFECT_NONE) then
skill:setMsg(MSG_DISAPPEAR_NUM);
return 2;
elseif (dis1 ~= EFFECT_NONE or dis2 ~= EFFECT_NONE) then
-- dispeled only one
skill:setMsg(MSG_DISAPPEAR_NUM);
return 1;
else
skill:setMsg(MSG_NO_EFFECT); -- no effect
end
return 0;
end; | gpl-3.0 |
arabi373/nod32bot | plugins/location.lua | 93 | 1704 | -- Implement a command !loc [area] which uses
-- the static map API to get a location image
-- Not sure if this is the proper way
-- Intent: get_latlong is in time.lua, we need it here
-- loadfile "time.lua"
-- Globals
-- If you have a google api key for the geocoding/timezone api
do
local api_key = nil
local base_api = "https://maps.googleapis.com/maps/api"
function get_staticmap(area)
local api = base_api .. "/staticmap?"
-- Get a sense of scale
local lat,lng,acc,types = get_latlong(area)
local scale = types[1]
if scale=="locality" then zoom=8
elseif scale=="country" then zoom=4
else zoom = 13 end
local parameters =
"size=600x300" ..
"&zoom=" .. zoom ..
"¢er=" .. URL.escape(area) ..
"&markers=color:red"..URL.escape("|"..area)
if api_key ~=nil and api_key ~= "" then
parameters = parameters .. "&key="..api_key
end
return lat, lng, api..parameters
end
function run(msg, matches)
local receiver = get_receiver(msg)
local lat,lng,url = get_staticmap(matches[1])
-- Send the actual location, is a google maps link
send_location(receiver, lat, lng, ok_cb, false)
-- Send a picture of the map, which takes scale into account
send_photo_from_url(receiver, url)
-- Return a link to the google maps stuff is now not needed anymore
return nil
end
return {
description = "Gets information about a location, maplink and overview",
usage = "!loc (location): Gets information about a location, maplink and overview",
patterns = {"^!loc (.*)$"},
run = run
}
end
--Copyright and edit; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
DiNaSoR/Angel_Arena | game/angel_arena/scripts/vscripts/items/magician_ring/modifiers/modifier_item_magician_ring_buff.lua | 1 | 1619 | modifier_item_magician_ring_buff = class({})
--------------------------------------------------------------------------------
function modifier_item_magician_ring_buff:IsHidden()
return false
end
--------------------------------------------------------------------------------
function modifier_item_magician_ring_buff:IsDebuff()
return false
end
--------------------------------------------------------------------------------
function modifier_item_magician_ring_buff:IsPurgable()
return false
end
--------------------------------------------------------------------------------
function modifier_item_magician_ring_buff:DestroyOnExpire()
return true
end
--------------------------------------------------------------------------------
function modifier_item_magician_ring_buff:GetTexture()
return "custom/magician_ring"
end
--------------------------------------------------------------------------------
function modifier_item_magician_ring_buff:OnCreated( kv )
end
--------------------------------------------------------------------------------
function modifier_item_magician_ring_buff:OnDestroy( kv )
end
--------------------------------------------------------------------------------
function modifier_item_magician_ring_buff:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_COOLDOWN_PERCENTAGE,
}
return funcs
end
--------------------------------------------------------------------------------
function modifier_item_magician_ring_buff:GetModifierPercentageCooldown( params )
return (self:GetAbility():GetSpecialValueFor("cooldown_reduce") or 0) * self:GetStackCount()
end
| mit |
Sonicrich05/FFXI-Server | scripts/zones/The_Eldieme_Necropolis/npcs/_5ff.lua | 34 | 1109 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: Leviathan's Gate
-- @pos 88 -34 -60 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 |
Servius/tfa-sw-weapons-repository | Live Addons/servius_uploader_legacy/rako_hardeen_rifle/lua/weapons/tfa_rakohardeen_rifle/shared.lua | 1 | 6554 | if ( SERVER ) then
AddCSLuaFile( "shared.lua" )
end
if ( CLIENT ) then
SWEP.PrintName = "Rako Hardeens Rifle"
SWEP.Author = "TFA, Servius"
SWEP.ViewModelFOV = 70
SWEP.Slot = 2
SWEP.SlotPos = 3
end
SWEP.Base = "tfa_3dscoped_base"
SWEP.Category = "TFA Star Wars"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.HoldType = "rpg"
SWEP.ViewModelFOV = 70
SWEP.ViewModelFlip = false
SWEP.ViewModel = "models/weapons/cstrike/c_snip_awp.mdl"
SWEP.WorldModel = "models/weapons/synbf3/w_a280.mdl"
SWEP.ShowViewModel = true
SWEP.ShowWorldModel = false
SWEP.UseHands = true
SWEP.Primary.Sound = Sound ("weapons/1misc_guns/wpn_balnab_rifle_shoot_01.ogg");
SWEP.Primary.ReloadSound = Sound ("weapons/shared/standard_reload.ogg");
SWEP.Primary.KickUp = 2
SWEP.Weight = 15
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
SWEP.Primary.Recoil = 0.7
SWEP.Primary.Damage = 85
SWEP.Primary.NumShots = 1
SWEP.Primary.Spread = 0.0125
SWEP.Primary.IronAccuracy = .001 -- Ironsight accuracy, should be the same for shotguns
SWEP.Primary.ClipSize = 10
SWEP.Primary.RPM = 100
SWEP.Primary.DefaultClip = 50
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "ar2"
SWEP.SelectiveFire = true --Allow selecting your firemode?
SWEP.DisableBurstFire = false --Only auto/single?
SWEP.OnlyBurstFire = false --No auto, only burst/single?
SWEP.DefaultFireMode = "" --Default to auto or whatev
SWEP.FireModes = {
--"Auto",
"2Burst",
"Single"
}
SWEP.FireModeName = nil --Change to a text value to override it
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.Secondary.IronFOV = 70
SWEP.ViewModelBoneMods = {
["ValveBiped.Bip01_L_UpperArm"] = { scale = Vector(1, 1, 1), pos = Vector(0.555, -1.668, -0.556), angle = Angle(0, 0, 0) },
["v_weapon.awm_parent"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["ValveBiped.Bip01_R_UpperArm"] = { scale = Vector(1, 1, 1), pos = Vector(0.185, -0.926, -0.186), angle = Angle(0, 0, 0) }
}
SWEP.IronSightsPos = Vector(-6.881, -3.201, 2.16)
SWEP.IronSightsAng = Vector(0, 0, 0)
SWEP.VElements = {
["element_scope"] = { type = "Model", model = "models/rtcircle.mdl", bone = "v_weapon.awm_parent", rel = "element_name", pos = Vector(3.67, -0.02, 5.67), angle = Angle(-90, -90, -90), size = Vector(0.28, 0.28, 0.28), color = Color(255, 255, 255, 255), surpresslightning = false, material = "!tfa_rtmaterial", skin = 0, bodygroup = {} },
["element_name"] = { type = "Model", model = "models/servius/starwars/cwa/rakohardeen_rifle.mdl", bone = "v_weapon.awm_parent", rel = "", pos = Vector(-0.601, -3, 10), angle = Angle(180, -90, 0), size = Vector(0.95, 0.95, 0.95), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}
SWEP.WElements = {
["element_name"] = { type = "Model", model = "models/servius/starwars/cwa/rakohardeen_rifle.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(-4.401, 1.19, -2), angle = Angle(-100, 1, 0), size = Vector(0.79, 0.79, 0.79), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}
SWEP.BlowbackVector = Vector(0,-3,0.025)
SWEP.Blowback_Only_Iron = false
SWEP.DoProceduralReload = true
SWEP.ProceduralReloadTime = 2.5
----Swft Base Code
SWEP.TracerCount = 1
SWEP.MuzzleFlashEffect = ""
SWEP.TracerName = "effect_sw_laser_red"
SWEP.Secondary.IronFOV = 70
SWEP.Primary.KickUp = 0.2
SWEP.Primary.KickDown = 0.1
SWEP.Primary.KickHorizontal = 0.1
SWEP.Primary.KickRight = 0.1
SWEP.DisableChambering = true
SWEP.ImpactDecal = "FadingScorch"
SWEP.ImpactEffect = "effect_sw_impact" --Impact Effect
SWEP.RunSightsPos = Vector(2.127, 0, 1.355)
SWEP.RunSightsAng = Vector(-15.775, 10.023, -5.664)
SWEP.BlowbackEnabled = true
SWEP.BlowbackVector = Vector(0,-3,0.1)
SWEP.Blowback_Shell_Enabled = false
SWEP.Blowback_Shell_Effect = ""
SWEP.ThirdPersonReloadDisable=false
SWEP.Primary.DamageType = DMG_SHOCK
SWEP.DamageType = DMG_SHOCK
--3dScopedBase stuff
SWEP.RTMaterialOverride = 0
SWEP.RTScopeAttachment = -1
SWEP.Scoped_3D = true
SWEP.ScopeReticule = "scope/gdcw_red_nobar"
SWEP.Secondary.ScopeZoom = 8
SWEP.ScopeReticule_Scale = {2.5,2.5}
SWEP.Secondary.UseACOG = false --Overlay option
SWEP.Secondary.UseMilDot = false --Overlay option
SWEP.Secondary.UseSVD = false --Overlay option
SWEP.Secondary.UseParabolic = false --Overlay option
SWEP.Secondary.UseElcan = false --Overlay option
SWEP.Secondary.UseGreenDuplex = false --Overlay option
if surface then
SWEP.Secondary.ScopeTable = nil --[[
{
scopetex = surface.GetTextureID("scope/gdcw_closedsight"),
reticletex = surface.GetTextureID("scope/gdcw_acogchevron"),
dottex = surface.GetTextureID("scope/gdcw_acogcross")
}
]]--
end
DEFINE_BASECLASS( SWEP.Base )
--[[
SWEP.HoldType = "rpg"
SWEP.ViewModelFOV = 70
SWEP.ViewModelFlip = false
SWEP.UseHands = true
SWEP.ViewModel = "models/weapons/cstrike/c_snip_awp.mdl"
SWEP.WorldModel = "models/weapons/synbf3/w_a280.mdl"
SWEP.ShowViewModel = true
SWEP.ShowWorldModel = false
SWEP.ViewModelBoneMods = {
["ValveBiped.Bip01_L_UpperArm"] = { scale = Vector(1, 1, 1), pos = Vector(0.555, -1.668, -0.556), angle = Angle(0, 0, 0) },
["v_weapon.awm_parent"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) },
["ValveBiped.Bip01_R_UpperArm"] = { scale = Vector(1, 1, 1), pos = Vector(0.185, -0.926, -0.186), angle = Angle(0, 0, 0) }
}
SWEP.IronSightsPos = Vector(-6.881, -3.201, 2.16)
SWEP.IronSightsAng = Vector(0, 0, 0)
SWEP.VElements = {
["element_scope"] = { type = "Model", model = "models/rtcircle.mdl", bone = "v_weapon.awm_parent", rel = "element_name", pos = Vector(3.67, -0.02, 5.67), angle = Angle(-90, -90, 0), size = Vector(0.28, 0.28, 0.28), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} },
["element_name"] = { type = "Model", model = "models/servius/starwars/cwa/rakohardeen_rifle.mdl", bone = "v_weapon.awm_parent", rel = "", pos = Vector(-0.601, -3, 10), angle = Angle(180, -90, 0), size = Vector(0.95, 0.95, 0.95), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}
SWEP.WElements = {
["element_name"] = { type = "Model", model = "models/servius/starwars/cwa/rakohardeen_rifle.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(-4.401, 1.19, -2), angle = Angle(-100, 1, 0), size = Vector(0.79, 0.79, 0.79), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}
]] | apache-2.0 |
zillemarco/CppSharp | build/premake5.lua | 2 | 1252 | -- This is the starting point of the build scripts for the project.
-- It defines the common build settings that all the projects share
-- and calls the build scripts of all the sub-projects.
config = {}
include "Helpers.lua"
include "LLVM.lua"
workspace "CppSharp"
configurations { "Debug", "Release" }
platforms { target_architecture() }
characterset "Unicode"
symbols "On"
location (builddir)
objdir (objsdir)
targetdir (libdir)
debugdir (bindir)
filter "system:windows"
defines { "WINDOWS" }
filter {}
group "Libraries"
include (srcdir .. "/Core")
include (srcdir .. "/AST")
--include (srcdir .. "/ASTViewer")
include (srcdir .. "/CppParser")
include (srcdir .. "/CppParser/Bindings")
include (srcdir .. "/CppParser/Bootstrap")
include (srcdir .. "/CppParser/ParserGen")
include (srcdir .. "/Parser")
include (srcdir .. "/CLI")
include (srcdir .. "/Generator")
include (srcdir .. "/Generator.Tests")
include (srcdir .. "/Runtime")
if not _OPTIONS["disable-tests"] then
dofile "Tests.lua"
group "Tests"
IncludeTests()
end
if not _OPTIONS["disable-tests"] then
if string.starts(action, "vs") then
group "Examples"
IncludeExamples()
end
end
| mit |
rlowrance/re | lua/abandoned/WeightedLinearRegression.lua | 1 | 5238 | -- WeightedLinearRegression.lua
-- define class WeightedLinearRegression
-- torch libraries
require 'nn'
require 'optim'
-- local libraries
require 'Trainer'
require 'Validations'
require 'WeightedMSECriterion'
local WeightedLinearRegression = torch.class('WeightedLinearRegression')
function WeightedLinearRegression:__init(inputs, targets, numDimensions)
-- validate parameters
Validations.isTable(self, 'self')
Validations.isNotNil(inputs, 'inputs')
Validations.isNotNil(targets, 'targets')
Validations.isIntegerGt0(numDimensions, 'numDimensions')
-- save data for type validations
self.inputs = inputs
self.targets = targets
self.numDimensions = numDimensions
end
function WeightedLinearRegression:estimate(query, weights, opt)
-- validate parameters
Validations.isTable(self, 'self')
Validations.isTensor(query, 'query')
Validations.isNotNil(weights, 'weights')
Validations.isTable(opt, 'opt')
-- define model
self.model = nn.Sequential()
local numOutputs = 1
self.model:add(nn.Linear(self.numDimensions, numOutputs))
-- define loss function
self.criterion = nn.MSECriterion()
-- iterate to a solution
-- first with SGD then with L-BFGS
if false then
print('\nestimate self', self)
print('estimate opt', opt)
print('estimate opt.sgd', opt.sgd)
end
self:_iterate(optim.sgd,
opt.sgd.epochs,
opt.sgd.batchSize,
opt.sgd.params,
weights)
self:_iterate(optim.lbfgs,
opt.lbfgs.epochs,
opt.lbfgs.batchSize,
opt.lbfgs.params,
weights)
return self.model:forward(query)
end
function WeightedLinearRegression:_iterate(optimize,
numEpochs,
batchSize,
optimParms,
weights)
-- validate parameters
Validations.isFunction(optimize, 'optimize')
Validations.isNumber(numEpochs, 'numEpochs')
Validations.isNumberGt0(batchSize, 'batchSize')
Validations.isNilOrTable(optimParams, 'optimParams')
Validations.isTable(weights, 'weights')
if false then
print('_iterate self', self)
print('_iterate numEpochs', numEpochs)
print('_iterate batchSize', batchSize)
print('_iterate num weights', #weights)
print('_iterate optimParams', optimParms)
end
x, dl_dx = self.model:getParameters() -- create view of parameters
for epochNumber =1,numEpochs do
currentLoss = 0
local highestIndex = 0
local numBatches = 0
for batchNumber = 1,#self.inputs do
if highestIndex >= #self.inputs then break end
numBatches = numBatches + 1
local batchIndices = {}
for b=1,batchSize do
local nextIndex = (batchNumber - 1) * batchSize + b
--print('_iterate nextIndex', nextIndex)
if nextIndex <= #self.inputs then
batchIndices[#batchIndices + 1] = nextIndex
highestIndex = nextIndex
end
end
if false then
print('_iterate batchNumber', batchNumber)
print('_iterate batchSize', batchSize)
print('_iterate batchIndices', batchIndices)
end
function feval(x_new)
if x ~= x_new then x:copy(x_new) end
dl_dx:zero() -- reset gradient in model
local cumLoss = 0
local numInBatch = 0
-- iterate over the indices in the batch
for _,nextIndex in pairs(batchIndices) do
numInBatch = numInBatch + 1
local input = self.inputs[nextIndex]
local target = self.targets[nextIndex]
Validations.isTensor(input, 'inputs[nextIndex]')
Validations.isTensor(target, 'targets[nextIndex]')
local modelOutput = self.model:forward(input)
--print('feval input', input)
--print('feval target', target)
local lossUnweighted =
self.criterion:forward(self.model:forward(input), target)
local lossWeighted = weights[nextIndex] * lossUnweighted
cumLoss = cumLoss + lossWeighted
self.model:backward(input,
self.criterion:backward(input, target))
end
return cumLoss / numInBatch, dl_dx / numInBatch
end -- function feval
_, fs = optimize(feval, x, optimParams)
if opt.verboseBatch then
print('loss values during optimization procedure', fs)
end
-- the last value in fs is the value at the optimimum x*
currentLoss = currentLoss + fs[#fs]
end -- loop over batches
-- finished with all the batches
currentLoss = currentLoss / numBatches
if opt.verboseEpoch then
print(string.format('epoch %d of %d; current loss = %.15f',
epochNumber, numEpochs,
currentLoss))
end
end -- loop over epochs
end -- method _iterate
| gpl-3.0 |
fruitwasp/DarkRP | gamemode/modules/fadmin/fadmin/playeractions/changeteam/cl_init.lua | 3 | 1379 | FAdmin.StartHooks["zzSetTeam"] = function()
FAdmin.Messages.RegisterNotification{
name = "setteam",
hasTarget = true,
message = {"instigator", " set the team of ", "targets", " to ", "extraInfo.1"},
readExtraInfo = function()
return {team.GetName(net.ReadUInt(16))}
end,
extraInfoColors = {Color(255, 102, 0)}
}
FAdmin.Access.AddPrivilege("SetTeam", 2)
FAdmin.Commands.AddCommand("SetTeam", nil, "<Player>", "<Team>")
FAdmin.ScoreBoard.Player:AddActionButton("Set team", "fadmin/icons/changeteam", Color(0, 200, 0, 255),
function(ply) return FAdmin.Access.PlayerHasPrivilege(LocalPlayer(), "SetTeam", ply) end, function(ply, button)
local menu = DermaMenu()
local Padding = vgui.Create("DPanel")
Padding:SetPaintBackgroundEnabled(false)
Padding:SetSize(1,5)
menu:AddPanel(Padding)
local Title = vgui.Create("DLabel")
Title:SetText(" Teams:\n")
Title:SetFont("UiBold")
Title:SizeToContents()
Title:SetTextColor(color_black)
menu:AddPanel(Title)
for k, v in SortedPairsByMemberValue(team.GetAllTeams(), "Name") do
local uid = ply:UserID()
menu:AddOption(v.Name, function() RunConsoleCommand("_FAdmin", "setteam", uid, k) end)
end
menu:Open()
end)
end
| mit |
Sonicrich05/FFXI-Server | scripts/zones/Castle_Oztroja/TextIDs.lua | 4 | 2162 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6564; -- You cannot obtain the item <item>. Come back after sorting your inventory.
FULL_INVENTORY_AFTER_TRADE = 6567; -- You cannot obtain the #. Try trading again after sorting your inventory.
ITEM_OBTAINED = 6568; -- Obtained: <item>.
GIL_OBTAINED = 6569; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6571; -- Obtained key item: <keyitem>.
ITEMS_OBTAINED = 6574; -- You obtain
FISHING_MESSAGE_OFFSET = 7242; -- You can't fish here.
-- Other dialog
SENSE_OF_FOREBODING = 6583; -- You are suddenly overcome with a sense of foreboding...
NOTHING_OUT_OF_ORDINARY = 7750; -- There is nothing out of the ordinary here.
ITS_LOCKED = 1; -- It's locked.
PROBABLY_WORKS_WITH_SOMETHING_ELSE = 3; -- It probably works with something else.
TORCH_LIT = 5; -- The torch is lit.
-- Treasure Coffer/Chest Dialog
CHEST_UNLOCKED = 7407; -- You unlock the chest!
CHEST_FAIL = 7408; -- Fails to open the chest.
CHEST_TRAP = 7409; -- The chest was trapped!
CHEST_WEAK = 7410; -- You cannot open the chest when you are in a weakened state.
CHEST_MIMIC = 7411; -- The chest was a mimic!
CHEST_MOOGLE = 7412; -- You cannot open the chest while participating in the moogle event.
CHEST_ILLUSION = 7413; -- The chest was but an illusion...
CHEST_LOCKED = 7414; -- The chest appears to be locked.
YAGUDO_AVATAR_ENGAGE = 7428; -- Kahk-ka-ka... You filthy, dim-witted heretics! You have damned yourselves by coming here.
YAGUDO_AVATAR_DEATH = 7429; -- Our lord, Tzee Xicu the Manifest!Even should our bodies be crushed and broken, may our souls endure into eternity...
YAGUDO_KING_ENGAGE = 7430; -- You are not here as sacrifices, are you? Could you possibly be committing this affront in the face of a deity?Very well, I will personally mete out your divine punishment, kyah!
YAGUDO_KING_DEATH = 7431; -- You have...bested me... However, I...am...a god... I will never die...never rot...never fade...never...
-- conquest Base
CONQUEST_BASE = 26;
| gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/zones/Talacca_Cove/Zone.lua | 28 | 1314 | -----------------------------------
--
-- Zone: Talacca_Cove (57)
--
-----------------------------------
package.loaded["scripts/zones/Talacca_Cove/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Talacca_Cove/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(64.007,-9.281,-99.988,88);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Buburimu_Peninsula/npcs/Stone_Monument.lua | 3 | 1214 | -----------------------------------
-- Area: Buburimu Peninsula
-- NPC: Stone Monument
-- Involved in quest "An Explorer's Footsteps"
-----------------------------------
package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Buburimu_Peninsula/TextIDs");
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0384);
end;
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then
player:tradeComplete();
player:addItem(570);
player:specialMessage(ITEM_OBTAINED,570);
player:setVar("anExplorer-CurrentTablet",0x02000);
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 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Heavens_Tower/npcs/Heruru.lua | 4 | 1032 | -----------------------------------
-- Area: Heavens Tower
-- NPC: Heruru
-- Type: Standard NPC
-- @zone: 242
-- @pos: 2.321 -26.5 4.641
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Heavens_Tower/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x003e);
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 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/serving_of_snowy_rolanberry.lua | 3 | 1287 | -----------------------------------------
-- ID: 4594
-- Item: serving_of_snowy_rolanberry
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Magic % 18
-- Magic Cap 60
-- Intelligence 2
-- Wind Res 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,4594);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_MPP, 18);
target:addMod(MOD_FOOD_MP_CAP, 60);
target:addMod(MOD_INT, 2);
target:addMod(MOD_WINDRES, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_MPP, 18);
target:delMod(MOD_FOOD_MP_CAP, 60);
target:delMod(MOD_INT, 2);
target:delMod(MOD_WINDRES, 5);
end;
| gpl-3.0 |
mandrav/moai_pex_editor | src/hp/event/EventDispatcher.lua | 1 | 4133 | --------------------------------------------------------------------------------
-- This class is has a function of event notification.
--
--------------------------------------------------------------------------------
local class = require("hp/lang/class")
local Event = require("hp/event/Event")
local EventListener = require("hp/event/EventListener")
local M = class()
local EVENT_CACHE = {}
--------------------------------------------------------------------------------
-- The constructor.
-- @param eventType (option)The type of event.
--------------------------------------------------------------------------------
function M:init()
self.eventlisteners = {}
end
--------------------------------------------------------------------------------
-- Adds an event listener. <br>
-- will now catch the events that are sent in the dispatchEvent. <br>
-- @param eventType Target event type.
-- @param callback The callback function.
-- @param source (option)The first argument passed to the callback function.
-- @param priority (option)Notification order.
--------------------------------------------------------------------------------
function M:addEventListener(eventType, callback, source, priority)
assert(eventType)
assert(callback)
if self:hasEventListener(eventType, callback, source) then
return false
end
local listener = EventListener(eventType, callback, source, priority)
for i, v in ipairs(self.eventlisteners) do
if listener.priority < v.priority then
table.insert(self.eventlisteners, i, listener)
return true
end
end
table.insert(self.eventlisteners, listener)
return true
end
--------------------------------------------------------------------------------
-- Removes an event listener.
--------------------------------------------------------------------------------
function M:removeEventListener(eventType, callback, source)
assert(eventType)
assert(callback)
for key, obj in ipairs(self.eventlisteners) do
if obj.type == eventType and obj.callback == callback and obj.source == source then
table.remove(self.eventlisteners, key)
return true
end
end
return false
end
--------------------------------------------------------------------------------
-- Returns true if you have an event listener. <br>
-- @return Returns true if you have an event listener.
--------------------------------------------------------------------------------
function M:hasEventListener(eventType, callback, source)
assert(eventType)
for key, obj in ipairs(self.eventlisteners) do
if obj.type == eventType then
if callback or source then
if obj.callback == callback and obj.source == source then
return true
end
else
return true
end
end
end
return false
end
--------------------------------------------------------------------------------
-- Dispatches the event.
--------------------------------------------------------------------------------
function M:dispatchEvent(event, data)
local eventName = type(event) == "string" and event
if eventName then
event = EVENT_CACHE[eventName] or Event(eventName)
EVENT_CACHE[eventName] = nil
end
assert(event.type)
event.data = data or event.data
event.stoped = false
event.target = self.eventTarget or self
for key, obj in ipairs(self.eventlisteners) do
if obj.type == event.type then
event:setListener(obj.callback, obj.source)
obj:call(event)
if event.stoped == true then
break
end
end
end
if eventName then
EVENT_CACHE[eventName] = event
end
end
--------------------------------------------------------------------------------
-- Remove all event listeners.
--------------------------------------------------------------------------------
function M:clearEventListeners()
self.eventlisteners = {}
end
return M | mit |
Siliconsoul/mirror-askozia-svn | scripts/config-functions.lua | 3 | 6796 | #!/usr/bin/lua
-- --- T2-COPYRIGHT-NOTE-BEGIN ---
-- This copyright note is auto-generated by ./scripts/Create-CopyPatch.
--
-- T2 SDE: scripts/config-functions.lua
-- Copyright (C) 2006 - 2007 The T2 SDE Project
-- Copyright (C) 2006 - 2007 Rene Rebe <rene@exactcode.de>
--
-- More information can be found in the files COPYING and README.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; version 2 of the License. A copy of the
-- GNU General Public License can be found in the file COPYING.
-- --- T2-COPYRIGHT-NOTE-END ---
packages = {} -- our internal package array of tables
function pkglistread (filename)
local f = io.open (filename, "r")
packages = {}
for line in f:lines() do
-- use captures to yank out the various parts:
-- X -----5---9 149.800 develop lua 5.1.1 / extra/development DIETLIBC 0
-- X -----5---- 112.400 xorg bigreqsproto 1.0.2 / base/x11 0
-- hm - maybe strtok as one would do in C?
pkg = {}
pkg.status, pkg.stages, pkg.priority, pkg.repository,
pkg.name, pkg.ver, pkg.extraver, pkg.categories, pkg.flags =
string.match (line, "([XO]) *([0123456789-]+) *([0123456789.]+) *(%S+) *(%S+) *(%S+) *(%S*) */ ([abcdefghijklmnopqrstuvwxyz0123456789/ ]+) *([ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 _-]*) 0")
-- shortcomming of above regex
if pkg.categories then
pkg.categories = string.match (pkg.categories, "(.*%S) *");
else
print ("error no Cateory tag - parsing: ", line)
end
pkg.alias = pkg.name
pkg.default_status = pkg.status
--[[
print (line);
if pkg.categories == nil then
pkg.categories = "nil" end
if pkg.flags == nil then
pkg.flags = "nil" end
io.write ("'",pkg.categories,"'",pkg.flags,"'\n")
]]--
if pkg.alias == nil then
print ("error parsing: ", line)
else
packages[#packages+1] = pkg
end
end
f:close()
end
function pkglistwrite (filename)
local f = io.open (filename, "w")
for i,pkg in ipairs(packages) do
-- only write not fully disabled packages
if pkg.status ~= "-" then
f:write (pkg.status, " ", pkg.stages, " ", pkg.priority, " ",
pkg.repository, " ", pkg.alias, " ", pkg.ver)
if string.len(pkg.extraver) > 0 then
f:write (" ", pkg.extraver)
end
f:write (" / ", pkg.categories)
if string.len(pkg.flags) > 0 then
f:write (" ", pkg.flags)
end
f:write (" 0\n")
end
end
f:close()
end
-- tracks the state and also expands patterns
-- either called with just packages or repository/package
-- allowing wildcards such as perl/*
local function pkgswitch (mode, ...)
--local matched = false
local tr = { ["+"] = "%+",
["-"] = "%-",
["*"] = ".*" }
for i,arg in ipairs {...} do
-- split repo from the package and expand wildcard to regex
local rep, pkg = string.match (arg, "(.*)/(.*)");
if rep == nil then
rep = "*"
pkg = arg
end
rep = "^" .. string.gsub (rep, "([+*-])", tr) .. "$"
pkg = "^" .. string.gsub (pkg, "([+*-])", tr) .. "$"
--optimization, to skip the package traversal early
local pkg_match = false
if string.find (pkg, "*") == nil then
pkg_match = true
end
--print ("regex> rep: " .. rep .. ", pkg: '" .. pkg .. "'")
for j,p in ipairs(packages) do
-- match
--[[
if (pkg == "linux-header") then
print ("pkg> p.rep: " .. p.repository ..
", p.alias: '" .. p.alias .. "'")
local s1 = string.match(p.alias, pkg)
local s2 = string.match(p.repository, rep)
if s1 == nil then s1 = "nil" end
if s2 == nil then s2 = "nil" end
print ("match pkg: " .. s1)
print ("match rep: " .. s2)
end
]]--
if (string.match(p.alias, pkg) and
string.match(p.repository, rep)) then
--matched = true
-- if not already disabled completely
--print ("matched rep: " .. rep .. ", pkg: " .. pkg)
--print ("with rep: " .. p.repository ..", pkg: " .. p.alias)
if p.status ~= "-" then
--print ("set to: " .. mode)
if mode == "=" then
p.status = p.default_status
else
p.status = mode
end
end
-- just optimization
if pkg_match then
break
end
end
end
end
--if matched == false then
-- print ("Warning: pkgsel - no match for: " .. mode .. " " .. ...)
--end
end
function pkgenable (pkg)
pkgswitch ("X", pkg)
end
function pkgdisable (pkg)
pkgswitch ("O", pkg)
end
function pkgremove (pkg)
pkgswitch ("-", pkg)
end
function pkgcheck (pattern, mode)
-- split the pattern seperated by "|"
p = {}
for x in string.gmatch(pattern, "[^|]+") do
p[#p+1] = x
end
for i,pkg in ipairs(packages) do
for j,x in ipairs (p) do
if pkg.alias == x then
if mode == "X" then
if pkg.status == "X" then return true end
elseif mode == "O" then
if pkg.status == "O" then return true end
elseif mode == "." then
return 0
else
print ("Syntax error near pkgcheck: "..pattern.." "..mode)
end
end
end
end
return false
end
--
-- Parse pkg selection rules
--
-- Example:
-- X python - selects just the python package
-- O perl/* - deselects all perl repository packages
-- = glibc - sets package glibc to it's default state
-- include file - recursively parse file specified
--
function pkgsel_parse (filename)
local f = io.open (filename, "r")
if f == nil then
print ("Error opening file: '" .. filename .."'")
return
end
for line in f:lines() do
line = string.gsub (line, "#.*","")
local action
local pattern
action, pattern = string.match (line, "(%S+) +(%S+)")
if action == "x" or action == "X" then
pkgswitch ("X", pattern)
elseif action == "o" or action == "O" then
pkgswitch ("O", pattern)
elseif action == "-" then
pkgswitch ("-", pattern)
elseif action == "=" then
pkgswitch ("=", pattern)
elseif action == "include" then
pkgsel_parse (pattern)
else
if not line == "" then
print ("Syntax error in: "..line)
end
end
end
f:close()
end
--
print "LUA accelerator (C) 2006 by Valentin Ziegler & Rene Rebe, ExactCODE"
-- register shortcuts for the functions above
bash.register("pkglistread")
bash.register("pkglistwrite")
bash.register("pkgcheck")
bash.register("pkgremove")
bash.register("pkgenable")
bash.register("pkgdisable")
bash.register("pkgsel_parse")
| gpl-2.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/loach_slop.lua | 2 | 1410 | -----------------------------------------
-- ID: 5669
-- Item: loach_slop
-- Food Effect: 3Hour,Group Food, All Races
-----------------------------------------
-- Accuracy % 7
-- Accuracy Cap 15
-- HP % 7
-- HP Cap 15
-- Evasion 3
-- (Did Not Add Group Food Effect)
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5669);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_ACCP, 7);
target:addMod(MOD_FOOD_ACC_CAP, 15);
target:addMod(MOD_FOOD_HPP, 7);
target:addMod(MOD_FOOD_HP_CAP, 15);
target:addMod(MOD_EVA, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_ACCP, 7);
target:delMod(MOD_FOOD_ACC_CAP, 15);
target:delMod(MOD_FOOD_HPP, 7);
target:delMod(MOD_FOOD_HP_CAP, 15);
target:delMod(MOD_EVA, 3);
end;
| gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/globals/weaponskills/spinning_slash.lua | 30 | 1563 | -----------------------------------
-- Spinning Slash
-- Great Sword weapon skill
-- Skill level: 225
-- Delivers a single-hit attack. Damage varies with TP.
-- Modifiers: STR:30% ; INT:30%
-- 100%TP 200%TP 300%TP
-- 2.5 3 3.5
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
--ftp damage mods (for Damage Varies with TP; lines are calculated in the function
params.ftp100 = 2.5; params.ftp200 = 3; params.ftp300 = 3.5;
--wscs are in % so 0.2=20%
params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.3; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
--critical mods, again in % (ONLY USE FOR critICAL HIT VARIES WITH TP)
params.crit100 = 0.0; params.crit200=0.0; params.crit300=0.0;
params.canCrit = false;
--params.accuracy mods (ONLY USE FOR accURACY VARIES WITH TP) , should be the acc at those %s NOT the penalty values. Leave 0 if acc doesnt vary with tp.
params.acc100 = 0; params.acc200=0; params.acc300=0;
--attack multiplier (only some WSes use this, this varies the actual ratio value, see Tachi: Kasha) 1 is default.
params.atkmulti = 1.5;
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Windurst_Waters_[S]/npcs/Pahpe_Rauulih.lua | 4 | 1054 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Pahpe Rauulih
-- Type: Standard NPC
-- @zone: 94
-- @pos: -39.740 -4.499 53.223
--
-- 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(0x01ab);
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 |
Sonicrich05/FFXI-Server | scripts/globals/items/plate_of_tentacle_sushi.lua | 21 | 1809 | -----------------------------------------
-- ID: 5215
-- Item: plate_of_tentacle_sushi
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP 20
-- Dexterity 3
-- Agility 3
-- Mind -1
-- Accuracy % 19 (cap 18)
-- Ranged Accuracy % 19 (cap 18)
-- 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,1800,5215);
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_MND, -1);
target:addMod(MOD_FOOD_ACCP, 19);
target:addMod(MOD_FOOD_ACC_CAP, 18);
target:addMod(MOD_FOOD_RACCP, 19);
target:addMod(MOD_FOOD_RACC_CAP, 18);
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_MND, -1);
target:delMod(MOD_FOOD_ACCP, 19);
target:delMod(MOD_FOOD_ACC_CAP, 18);
target:delMod(MOD_FOOD_RACCP, 19);
target:delMod(MOD_FOOD_RACC_CAP, 18);
target:delMod(MOD_DOUBLE_ATTACK, 1);
end;
| gpl-3.0 |
bright-things/ionic-luci | applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/sensors.lua | 30 | 2974 | -- Copyright 2015 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
require "luci.sys"
local m, s, o
local sensor_types = {
["12v"] = "voltage",
["2.0v"] = "voltage",
["2.5v"] = "voltage",
["3.3v"] = "voltage",
["5.0v"] = "voltage",
["5v"] = "voltage",
["ain1"] = "voltage",
["ain2"] = "voltage",
["cpu_temp"] = "temperature",
["fan1"] = "fanspeed",
["fan2"] = "fanspeed",
["fan3"] = "fanspeed",
["fan4"] = "fanspeed",
["fan5"] = "fanspeed",
["fan6"] = "fanspeed",
["fan7"] = "fanspeed",
["in0"] = "voltage",
["in10"] = "voltage",
["in2"] = "voltage",
["in3"] = "voltage",
["in4"] = "voltage",
["in5"] = "voltage",
["in6"] = "voltage",
["in7"] = "voltage",
["in8"] = "voltage",
["in9"] = "voltage",
["power1"] = "power",
["remote_temp"] = "temperature",
["temp1"] = "temperature",
["temp2"] = "temperature",
["temp3"] = "temperature",
["temp4"] = "temperature",
["temp5"] = "temperature",
["temp6"] = "temperature",
["temp7"] = "temperature",
["temp"] = "temperature",
["vccp1"] = "voltage",
["vccp2"] = "voltage",
["vdd"] = "voltage",
["vid1"] = "voltage",
["vid2"] = "voltage",
["vid3"] = "voltage",
["vid4"] = "voltage",
["vid5"] = "voltage",
["vid"] = "voltage",
["vin1"] = "voltage",
["vin2"] = "voltage",
["vin3"] = "voltage",
["vin4"] = "voltage",
["volt12"] = "voltage",
["volt5"] = "voltage",
["voltbatt"] = "voltage",
["vrm"] = "voltage"
}
m = Map("luci_statistics",
translate("Sensors Plugin Configuration"),
translate("The sensors plugin uses the Linux Sensors framework to gather environmental statistics."))
s = m:section( NamedSection, "collectd_sensors", "luci_statistics" )
o = s:option( Flag, "enable", translate("Enable this plugin") )
o.default = 0
o = s:option(Flag, "__all", translate("Monitor all sensors"))
o:depends("enable", 1)
o.default = 1
o.write = function() end
o.cfgvalue = function(self, sid)
local v = self.map:get(sid, "Sensor")
if v == nil or (type(v) == "table" and #v == 0) or (type(v) == "string" and #v == 0) then
return "1"
end
end
o = s:option(MultiValue, "Sensor", translate("Sensor list"), translate("Hold Ctrl to select multiple items or to deselect entries."))
o:depends({enable = 1, __all = "" })
o.widget = "select"
o.rmempty = true
o.size = 0
local sensorcli = io.popen("/usr/sbin/sensors -u -A")
if sensorcli then
local bus, sensor
while true do
local ln = sensorcli:read("*ln")
if not ln then
break
elseif ln:match("^[%w-]+$") then
bus = ln
elseif ln:match("^[%w-]+:$") then
sensor = ln:sub(0, -2):lower()
if bus and sensor_types[sensor] then
o:value("%s/%s-%s" %{ bus, sensor_types[sensor], sensor })
o.size = o.size + 1
end
elseif ln == "" then
bus = nil
sensor = nil
end
end
sensorcli:close()
end
o = s:option( Flag, "IgnoreSelected", translate("Monitor all except specified") )
o.default = 0
o.rmempty = true
o:depends({ enable = 1, __all = "" })
return m
| apache-2.0 |
AdUki/Grapedit | scripts/libs/pl/utils.lua | 9 | 14915 | --- Generally useful routines.
-- See @{01-introduction.md.Generally_useful_functions|the Guide}.
-- @module pl.utils
local format,gsub,byte = string.format,string.gsub,string.byte
local compat = require 'pl.compat'
local clock = os.clock
local stdout = io.stdout
local append = table.insert
local unpack = rawget(_G,'unpack') or rawget(table,'unpack')
local collisions = {}
local utils = {
_VERSION = "1.2.1",
lua51 = compat.lua51,
setfenv = compat.setfenv,
getfenv = compat.getfenv,
load = compat.load,
execute = compat.execute,
dir_separator = _G.package.config:sub(1,1),
unpack = unpack
}
--- end this program gracefully.
-- @param code The exit code or a message to be printed
-- @param ... extra arguments for message's format'
-- @see utils.fprintf
function utils.quit(code,...)
if type(code) == 'string' then
utils.fprintf(io.stderr,code,...)
code = -1
else
utils.fprintf(io.stderr,...)
end
io.stderr:write('\n')
os.exit(code)
end
--- print an arbitrary number of arguments using a format.
-- @param fmt The format (see string.format)
-- @param ... Extra arguments for format
function utils.printf(fmt,...)
utils.assert_string(1,fmt)
utils.fprintf(stdout,fmt,...)
end
--- write an arbitrary number of arguments to a file using a format.
-- @param f File handle to write to.
-- @param fmt The format (see string.format).
-- @param ... Extra arguments for format
function utils.fprintf(f,fmt,...)
utils.assert_string(2,fmt)
f:write(format(fmt,...))
end
local function import_symbol(T,k,v,libname)
local key = rawget(T,k)
-- warn about collisions!
if key and k ~= '_M' and k ~= '_NAME' and k ~= '_PACKAGE' and k ~= '_VERSION' then
utils.printf("warning: '%s.%s' overrides existing symbol\n",libname,k)
end
rawset(T,k,v)
end
local function lookup_lib(T,t)
for k,v in pairs(T) do
if v == t then return k end
end
return '?'
end
local already_imported = {}
--- take a table and 'inject' it into the local namespace.
-- @param t The Table
-- @param T An optional destination table (defaults to callers environment)
function utils.import(t,T)
T = T or _G
t = t or utils
if type(t) == 'string' then
t = require (t)
end
local libname = lookup_lib(T,t)
if already_imported[t] then return end
already_imported[t] = libname
for k,v in pairs(t) do
import_symbol(T,k,v,libname)
end
end
utils.patterns = {
FLOAT = '[%+%-%d]%d*%.?%d*[eE]?[%+%-]?%d*',
INTEGER = '[+%-%d]%d*',
IDEN = '[%a_][%w_]*',
FILE = '[%a%.\\][:%][%w%._%-\\]*'
}
--- escape any 'magic' characters in a string
-- @param s The input string
function utils.escape(s)
utils.assert_string(1,s)
return (s:gsub('[%-%.%+%[%]%(%)%$%^%%%?%*]','%%%1'))
end
--- return either of two values, depending on a condition.
-- @param cond A condition
-- @param value1 Value returned if cond is true
-- @param value2 Value returned if cond is false (can be optional)
function utils.choose(cond,value1,value2)
if cond then return value1
else return value2
end
end
local raise
--- return the contents of a file as a string
-- @param filename The file path
-- @param is_bin open in binary mode
-- @return file contents
function utils.readfile(filename,is_bin)
local mode = is_bin and 'b' or ''
utils.assert_string(1,filename)
local f,err = io.open(filename,'r'..mode)
if not f then return utils.raise (err) end
local res,err = f:read('*a')
f:close()
if not res then return raise (err) end
return res
end
--- write a string to a file
-- @param filename The file path
-- @param str The string
-- @return true or nil
-- @return error message
-- @raise error if filename or str aren't strings
function utils.writefile(filename,str)
utils.assert_string(1,filename)
utils.assert_string(2,str)
local f,err = io.open(filename,'w')
if not f then return raise(err) end
f:write(str)
f:close()
return true
end
--- return the contents of a file as a list of lines
-- @param filename The file path
-- @return file contents as a table
-- @raise errror if filename is not a string
function utils.readlines(filename)
utils.assert_string(1,filename)
local f,err = io.open(filename,'r')
if not f then return raise(err) end
local res = {}
for line in f:lines() do
append(res,line)
end
f:close()
return res
end
--- split a string into a list of strings separated by a delimiter.
-- @param s The input string
-- @param re A Lua string pattern; defaults to '%s+'
-- @param plain don't use Lua patterns
-- @param n optional maximum number of splits
-- @return a list-like table
-- @raise error if s is not a string
function utils.split(s,re,plain,n)
utils.assert_string(1,s)
local find,sub,append = string.find, string.sub, table.insert
local i1,ls = 1,{}
if not re then re = '%s+' end
if re == '' then return {s} end
while true do
local i2,i3 = find(s,re,i1,plain)
if not i2 then
local last = sub(s,i1)
if last ~= '' then append(ls,last) end
if #ls == 1 and ls[1] == '' then
return {}
else
return ls
end
end
append(ls,sub(s,i1,i2-1))
if n and #ls == n then
ls[#ls] = sub(s,i1)
return ls
end
i1 = i3+1
end
end
--- split a string into a number of values.
-- @param s the string
-- @param re the delimiter, default space
-- @return n values
-- @usage first,next = splitv('jane:doe',':')
-- @see split
function utils.splitv (s,re)
return unpack(utils.split(s,re))
end
--- convert an array of values to strings.
-- @param t a list-like table
-- @param temp buffer to use, otherwise allocate
-- @param tostr custom tostring function, called with (value,index).
-- Otherwise use `tostring`
-- @return the converted buffer
function utils.array_tostring (t,temp,tostr)
temp, tostr = temp or {}, tostr or tostring
for i = 1,#t do
temp[i] = tostr(t[i],i)
end
return temp
end
--- execute a shell command and return the output.
-- This function redirects the output to tempfiles and returns the content of those files.
-- @param cmd a shell command
-- @param bin boolean, if true, read output as binary file
-- @return true if successful
-- @return actual return code
-- @return stdout output (string)
-- @return errout output (string)
function utils.executeex(cmd, bin)
local mode
local outfile = os.tmpname()
local errfile = os.tmpname()
if utils.dir_separator == '\\' then
outfile = os.getenv('TEMP')..outfile
errfile = os.getenv('TEMP')..errfile
end
cmd = cmd .. [[ >"]]..outfile..[[" 2>"]]..errfile..[["]]
local success, retcode = utils.execute(cmd)
local outcontent = utils.readfile(outfile, bin)
local errcontent = utils.readfile(errfile, bin)
os.remove(outfile)
os.remove(errfile)
return success, retcode, (outcontent or ""), (errcontent or "")
end
--- 'memoize' a function (cache returned value for next call).
-- This is useful if you have a function which is relatively expensive,
-- but you don't know in advance what values will be required, so
-- building a table upfront is wasteful/impossible.
-- @param func a function of at least one argument
-- @return a function with at least one argument, which is used as the key.
function utils.memoize(func)
return setmetatable({}, {
__index = function(self, k, ...)
local v = func(k,...)
self[k] = v
return v
end,
__call = function(self, k) return self[k] end
})
end
utils.stdmt = {
List = {_name='List'}, Map = {_name='Map'},
Set = {_name='Set'}, MultiMap = {_name='MultiMap'}
}
local _function_factories = {}
--- associate a function factory with a type.
-- A function factory takes an object of the given type and
-- returns a function for evaluating it
-- @param mt metatable
-- @param fun a callable that returns a function
function utils.add_function_factory (mt,fun)
_function_factories[mt] = fun
end
local function _string_lambda(f)
local raise = utils.raise
if f:find '^|' or f:find '_' then
local args,body = f:match '|([^|]*)|(.+)'
if f:find '_' then
args = '_'
body = f
else
if not args then return raise 'bad string lambda' end
end
local fstr = 'return function('..args..') return '..body..' end'
local fn,err = utils.load(fstr)
if not fn then return raise(err) end
fn = fn()
return fn
else return raise 'not a string lambda'
end
end
--- an anonymous function as a string. This string is either of the form
-- '|args| expression' or is a function of one argument, '_'
-- @param lf function as a string
-- @return a function
-- @usage string_lambda '|x|x+1' (2) == 3
-- @usage string_lambda '_+1 (2) == 3
-- @function utils.string_lambda
utils.string_lambda = utils.memoize(_string_lambda)
local ops
--- process a function argument.
-- This is used throughout Penlight and defines what is meant by a function:
-- Something that is callable, or an operator string as defined by <code>pl.operator</code>,
-- such as '>' or '#'. If a function factory has been registered for the type, it will
-- be called to get the function.
-- @param idx argument index
-- @param f a function, operator string, or callable object
-- @param msg optional error message
-- @return a callable
-- @raise if idx is not a number or if f is not callable
function utils.function_arg (idx,f,msg)
utils.assert_arg(1,idx,'number')
local tp = type(f)
if tp == 'function' then return f end -- no worries!
-- ok, a string can correspond to an operator (like '==')
if tp == 'string' then
if not ops then ops = require 'pl.operator'.optable end
local fn = ops[f]
if fn then return fn end
local fn, err = utils.string_lambda(f)
if not fn then error(err..': '..f) end
return fn
elseif tp == 'table' or tp == 'userdata' then
local mt = getmetatable(f)
if not mt then error('not a callable object',2) end
local ff = _function_factories[mt]
if not ff then
if not mt.__call then error('not a callable object',2) end
return f
else
return ff(f) -- we have a function factory for this type!
end
end
if not msg then msg = " must be callable" end
if idx > 0 then
error("argument "..idx..": "..msg,2)
else
error(msg,2)
end
end
--- bind the first argument of the function to a value.
-- @param fn a function of at least two values (may be an operator string)
-- @param p a value
-- @return a function such that f(x) is fn(p,x)
-- @raise same as @{function_arg}
-- @see func.bind1
function utils.bind1 (fn,p)
fn = utils.function_arg(1,fn)
return function(...) return fn(p,...) end
end
--- bind the second argument of the function to a value.
-- @param fn a function of at least two values (may be an operator string)
-- @param p a value
-- @return a function such that f(x) is fn(x,p)
-- @raise same as @{function_arg}
function utils.bind2 (fn,p)
fn = utils.function_arg(1,fn)
return function(x,...) return fn(x,p,...) end
end
--- assert that the given argument is in fact of the correct type.
-- @param n argument index
-- @param val the value
-- @param tp the type
-- @param verify an optional verfication function
-- @param msg an optional custom message
-- @param lev optional stack position for trace, default 2
-- @raise if the argument n is not the correct type
-- @usage assert_arg(1,t,'table')
-- @usage assert_arg(n,val,'string',path.isdir,'not a directory')
function utils.assert_arg (n,val,tp,verify,msg,lev)
if type(val) ~= tp then
error(("argument %d expected a '%s', got a '%s'"):format(n,tp,type(val)),lev or 2)
end
if verify and not verify(val) then
error(("argument %d: '%s' %s"):format(n,val,msg),lev or 2)
end
end
--- assert the common case that the argument is a string.
-- @param n argument index
-- @param val a value that must be a string
-- @raise val must be a string
function utils.assert_string (n,val)
utils.assert_arg(n,val,'string',nil,nil,3)
end
local err_mode = 'default'
--- control the error strategy used by Penlight.
-- Controls how <code>utils.raise</code> works; the default is for it
-- to return nil and the error string, but if the mode is 'error' then
-- it will throw an error. If mode is 'quit' it will immediately terminate
-- the program.
-- @param mode - either 'default', 'quit' or 'error'
-- @see utils.raise
function utils.on_error (mode)
if ({['default'] = 1, ['quit'] = 2, ['error'] = 3})[mode] then
err_mode = mode
else
-- fail loudly
if err_mode == 'default' then err_mode = 'error' end
utils.raise("Bad argument expected string; 'default', 'quit', or 'error'. Got '"..tostring(mode).."'")
end
end
--- used by Penlight functions to return errors. Its global behaviour is controlled
-- by <code>utils.on_error</code>
-- @param err the error string.
-- @see utils.on_error
function utils.raise (err)
if err_mode == 'default' then return nil,err
elseif err_mode == 'quit' then utils.quit(err)
else error(err,2)
end
end
--- is the object of the specified type?.
-- If the type is a string, then use type, otherwise compare with metatable
-- @param obj An object to check
-- @param tp String of what type it should be
function utils.is_type (obj,tp)
if type(tp) == 'string' then return type(obj) == tp end
local mt = getmetatable(obj)
return tp == mt
end
raise = utils.raise
--- load a code string or bytecode chunk.
-- @param code Lua code as a string or bytecode
-- @param name for source errors
-- @param mode kind of chunk, 't' for text, 'b' for bytecode, 'bt' for all (default)
-- @param env the environment for the new chunk (default nil)
-- @return compiled chunk
-- @return error message (chunk is nil)
-- @function utils.load
---------------
-- Get environment of a function.
-- With Lua 5.2, may return nil for a function with no global references!
-- Based on code by [Sergey Rozhenko](http://lua-users.org/lists/lua-l/2010-06/msg00313.html)
-- @param f a function or a call stack reference
-- @function utils.setfenv
---------------
-- Set environment of a function
-- @param f a function or a call stack reference
-- @param env a table that becomes the new environment of `f`
-- @function utils.setfenv
--- execute a shell command.
-- This is a compatibility function that returns the same for Lua 5.1 and Lua 5.2
-- @param cmd a shell command
-- @return true if successful
-- @return actual return code
-- @function utils.execute
return utils
| mit |
Moosader/Intro-to-Mobile-Game-Development-2015 | Projects/Grab the Treasure I/main.lua | 1 | 1682 | -- Load our images
treasure_texture = Texture.new( "content/treasure.png" )
background = Bitmap.new( Texture.new( "content/background.png" ) )
treasure = Bitmap.new( treasure_texture )
-- Load sounds
pickupSound = Sound.new( "content/Pickup_Coin3.wav" )
music = Sound.new( "content/DancingBunnies_Moosader.mp3" )
-- Load text
font = TTFont.new( "content/Amburegul.ttf", 20 )
scoreText = TextField.new( font, "Score: 0" )
scoreText:setPosition( 40, 30 )
scoreText:setTextColor( 0x8d8d8d )
-- Draw images
stage:addChild( background )
stage:addChild( treasure )
-- Draw text
stage:addChild( scoreText )
-- Play music
musicChannel = music:play()
musicChannel:setLooping( true )
score = 0
moveTreasureCounter = 100
-- Functions
function RandomlyPlaceTreasure()
local randomX = math.random( 0, 320 - 64 )
local randomY = math.random( 0, 480 - 64 )
print( "Treasure location: ", randomX, randomY )
treasure:setPosition( randomX, randomY )
-- Countdown Timer
moveTreasureCounter = math.random( 50, 200 )
end
function HandleClick( event )
if ( treasure:hitTestPoint( event.x, event.y ) ) then
score = score + 1
print( "Grab treasure, score = ", score )
RandomlyPlaceTreasure()
pickupSound:play()
scoreText:setText( "Score: " .. score )
end
end
function Update( event )
moveTreasureCounter = moveTreasureCounter - 1
if ( moveTreasureCounter == 0 ) then
print( "Timer is 0, move the treasure" )
RandomlyPlaceTreasure()
end
end
stage:addEventListener( Event.MOUSE_DOWN, HandleClick, self )
stage:addEventListener( Event.ENTER_FRAME, Update, self )
-- Game Start
RandomlyPlaceTreasure() | mit |
Sonicrich05/FFXI-Server | scripts/zones/Mhaura/npcs/Rycharde.lua | 17 | 16001 | -----------------------------------
-- Area: Mhaura
-- NPC: Rycharde
-- Standard Info NPC
-- Starts & Finishes non Repeatable Quest: Rycharde the Chef,
-- WAY_OF_THE_COOK, UNENDING_CHASE
-- his name is Valgeir (not completed correctly, ferry not implemented)
-- the clue (100%)
-- the basics (not completed correctly, ferry not implemented)
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Mhaura/TextIDs");
-- player:startEvent(0x4a); -- first quest completed ok
-- player:startEvent(0x4b); -- nothing to do
-- player:startEvent(0x4c); -- second quest start --WAY_OF_THE_COOK
-- player:startEvent(0x4e); -- you have x hours left
-- player:startEvent(0x4f); -- not yet done
-- player:startEvent(0x50); -- second quest completed
-- player:startEvent(0x51); -- too late second quest
-- player:startEvent(0x52);-- third quest
-- player:startEvent(0x53);-- third quest completed
-- player:startEvent(0x54);-- third quest said no, ask again
-- player:startEvent(0x55);-- third quest comment no hurry
-- player:startEvent(0x56);-- forth quest His Name is Valgeir
-- player:startEvent(0x57);-- forth quest not done yet
-- player:startEvent(0x58);-- forth quest done!
-- player:startEvent(0x59);-- nothing to do
-- player:startEvent(0x5a);-- fifth quest The Clue
-- player:startEvent(0x5b);-- fifth quest The Clue asked again
-- player:startEvent(0x5c);-- fifth quest completed
-- player:startEvent(0x5d);-- fifth quest not enogh
-- player:startEvent(0x5e);-- sixth quest The Basics
-- player:startEvent(0x5f);-- sixth quest not done yet
-- player:startEvent(0x60);-- sixth quest completed
-- player:startEvent(0x61);-- sixth quest completed commentary
-- player:startEvent(0x62);-- sixth quest completed commentary 2
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(OTHER_AREAS,RYCHARDE_THE_CHEF)== QUEST_ACCEPTED) then
local count = trade:getItemCount();
local DhalmelMeat = trade:hasItemQty(4359,trade:getItemCount()); --4359 - slice_of_dhalmel_meat
if (DhalmelMeat == true and count == 2) then
player:startEvent(0x4a); -- completed ok
elseif (DhalmelMeat == true and count == 1) then
player:startEvent(0x49); -- that's not enogh!
end
elseif (player:getQuestStatus(OTHER_AREAS,WAY_OF_THE_COOK) == QUEST_ACCEPTED) then
local count = trade:getItemCount();
local DhalmelMeat = trade:hasItemQty(4359,1); --4359 - slice_of_dhalmel_meat
local BeehiveChip = trade:hasItemQty(912,1); --4359 - slice_of_dhalmel_meat
if (DhalmelMeat == true and BeehiveChip == true and count == 2) then
local Dayspassed=VanadielDayOfTheYear()-player:getVar("QuestRychardeTCDayStarted_var");
local TotalHourLeft=72-(VanadielHour()+Dayspassed*24)+player:getVar("QuestWayotcHourStarted_var");
if (TotalHourLeft>0) then
player:startEvent(0x50); -- second quest completed
else
player:startEvent(0x51); -- too late second quest
end
end
elseif (player:getQuestStatus(OTHER_AREAS,UNENDING_CHASE) == QUEST_ACCEPTED) then
local puffball = trade:hasItemQty(4448,1); --4448 - puffball
if (puffball == true) then
player:startEvent(0x53); -- completed quest 3 UNENDING_CHASE
end
elseif (player:getQuestStatus(OTHER_AREAS,THE_CLUE) == QUEST_ACCEPTED) then
local count = trade:getItemCount();
local DhalmelMeat = trade:hasItemQty(4357,trade:getItemCount()); --4357 - crawler egg
if (DhalmelMeat == true and count > 3) then
player:startEvent(0x5c);
elseif (DhalmelMeat == true) then
player:startEvent(0x5d); -- that's not enogh!
end
elseif (player:getQuestStatus(OTHER_AREAS,THE_BASICS) == QUEST_ACCEPTED) then
local BackedPototo = trade:hasItemQty(4436,1); --4436 - baked_popoto
if (BackedPototo == true) then
player:startEvent(0x60);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
------------------------------------ QUEST RYCHARDE_THE_CHEF-----------------------------------------
if (player:getQuestStatus(OTHER_AREAS,RYCHARDE_THE_CHEF)==QUEST_AVAILABLE) then
QuestStatus = player:getVar("QuestRychardetheChef_var");
if (QuestStatus == 2 ) then -- seconnd stage one quest
player:startEvent(0x46,4359); -- ask if player would do quest
elseif (QuestStatus == 3 ) then
player:startEvent(0x47,4359); -- said no, ask again if player would do quest
else
player:startEvent(0x45); -- talk about something else
end
elseif (player:getQuestStatus(OTHER_AREAS,RYCHARDE_THE_CHEF)==QUEST_ACCEPTED) then
player:startEvent(0x48); -- not done yet huh?
--------------------------------------------- quest WAY_OF_THE_COOK
elseif (player:getQuestStatus(OTHER_AREAS,WAY_OF_THE_COOK)==QUEST_AVAILABLE and player:getFameLevel(WINDURST)>2) then -- quest WAY_OF_THE_COOK
if (player:getVar("QuestRychardeTCCompDay_var")+ 7 < VanadielDayOfTheYear() or player:getVar("QuestRychardeTCCompYear_var") < VanadielYear()) then --8 days or so after the completition of the last quest ... and required fame
player:startEvent(0x4c,4359,912);-- second quest WAY_OF_THE_COOK
else
player:startEvent(0x4b); -- nothing to do
end
elseif (player:getQuestStatus(OTHER_AREAS,WAY_OF_THE_COOK)==QUEST_ACCEPTED) then
Dayspassed=VanadielDayOfTheYear()-player:getVar("QuestRychardeTCDayStarted_var");
TotalHourLeft=72-(VanadielHour()+Dayspassed*24)+player:getVar("QuestWayotcHourStarted_var");
if (TotalHourLeft>0) then
player:startEvent(0x4e,TotalHourLeft); -- you have x hours left
else
player:startEvent(0x4f); -- not yet done
end
---------------------------QUEST UNENDING_CHASE--------------------------------------------------
elseif (player:getQuestStatus(OTHER_AREAS,UNENDING_CHASE)==QUEST_AVAILABLE and player:getFameLevel(WINDURST) > 2) then
if (player:getVar("QuestWayofTCCompDay_var")+7 < VanadielDayOfTheYear() or player:getVar("QuestWayofTCCompYear_var") < VanadielYear()) then -- days between quest
if (player:getVar("QuestUnendingCAskedAlready_var")==2) then
player:startEvent(0x54,4448);-- third quest said no, ask again
else
player:startEvent(0x52,4448);-- third quest UNENDING_CHASE 4448 - puffball
end
else
player:startEvent(0x4b); -- nothing to do
end
elseif (player:getQuestStatus(OTHER_AREAS,UNENDING_CHASE)==QUEST_ACCEPTED) then
player:startEvent(0x55);-- third quest comment no hurry
-------------------------QUEST HIS_NAME_IS_VALGEIR--------------------------------------------------
elseif (player:getQuestStatus(OTHER_AREAS,HIS_NAME_IS_VALGEIR)==QUEST_AVAILABLE and player:getFameLevel(WINDURST)>2) then
if (player:getVar("QuestUnendingCCompDay_var")+2< VanadielDayOfTheYear() or player:getVar("QuestUnendingCCompYear_var")< VanadielYear()) then
player:startEvent(0x56);-- forth quest His Name is Valgeir
else
player:startEvent(0x4b); -- nothing to do
end
elseif (player:getQuestStatus(OTHER_AREAS,HIS_NAME_IS_VALGEIR)==QUEST_ACCEPTED) then
if (player:hasKeyItem(90)) then
player:startEvent(0x57);-- forth quest not done yet
else
player:startEvent(0x58);-- forth quest done!
end
---------------------------QUEST THE CLUE--------------------------------------------------------
elseif (player:getQuestStatus(OTHER_AREAS,THE_CLUE)==QUEST_AVAILABLE and player:getFameLevel(WINDURST)>4) then
if (player:getQuestStatus(OTHER_AREAS,EXPERTISE)==QUEST_COMPLETED) then
if (player:getVar("QuestExpertiseCompDay_var")+7 < VanadielDayOfTheYear() or player:getVar("QuestExpertiseCompYear_var") < VanadielYear()) then
if (player:getVar("QuestTheClueStatus_var")==1) then
player:startEvent(0x5b,4357);-- fifth quest The Clue asked again 4357 - crawler_egg
else
player:startEvent(0x5a,4357);-- fifth quest The Clue 4357 - crawler_egg
end;
else
player:startEvent(0x4b); -- nothing to do
end
else
player:startEvent(0x4b); -- nothing to do
end
elseif (player:getQuestStatus(OTHER_AREAS,THE_CLUE)==QUEST_ACCEPTED) then
player:startEvent(0x55);-- third quest comment no hurry
---------------------------QUEST THE Basics--------------------------------------------------------
elseif (player:getQuestStatus(OTHER_AREAS,THE_BASICS)==QUEST_AVAILABLE and player:getFameLevel(WINDURST) > 4) then
if (player:getVar("QuestTheClueCompDay_var")+7 < VanadielDayOfTheYear() or player:getVar("QuestTheClueCompYear_var") < VanadielYear()) then
player:startEvent(0x5e);-- sixth quest The Basics
else
player:startEvent(0x4b); -- nothing to do standar dialog
end
elseif (player:getQuestStatus(OTHER_AREAS,THE_BASICS)==QUEST_ACCEPTED) then
player:startEvent(0x5f);-- sixth quest not done yet
else
if (player:getVar("QuestTheBasicsComentary_var")==1) then
player:startEvent(0x61);-- sixth quest completed commentary
else
player:startEvent(0x62);-- sixth quest completed commentary 2
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x46 or csid == 0x47) then --accept quest 1
player:setVar("QuestRychardetheChef_var",3); --
if (option == 71 or option == 72) then --70 = answer no 71 answer yes!
player:addQuest(OTHER_AREAS,RYCHARDE_THE_CHEF);
end
elseif (csid == 0x4a) then -- end quest 1 RYCHARDE_THE_CHEF
player:tradeComplete();
player:addFame(WINDURST,WIN_FAME*120);
player:addTitle(PURVEYOR_IN_TRAINING);
player:addGil(GIL_RATE*1500);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*1500);
player:setVar("QuestRychardetheChef_var",0);
player:setVar("QuestRychardeTCCompDay_var",VanadielDayOfTheYear());
player:setVar("QuestRychardeTCCompYear_var",VanadielYear());
player:completeQuest(OTHER_AREAS,RYCHARDE_THE_CHEF);
elseif (csid == 0x4c) then -- accept quest 2
if (option == 74 ) then -- answer yes!
player:setVar("QuestWayotcHourStarted_var",VanadielHour());
player:setVar("QuestRychardeTCDayStarted_var",VanadielDayOfTheYear());
player:addQuest(OTHER_AREAS,WAY_OF_THE_COOK);
end
elseif (csid == 0x50) then --end quest 2 WAY_OF_THE_COOK
player:tradeComplete();
player:addFame(WINDURST,WIN_FAME*120);
player:addTitle(ONESTAR_PURVEYOR);
player:addGil(GIL_RATE*1500);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*1500);
player:setVar("QuestWayotcHourStarted_var",0);
player:setVar("QuestRychardeTCDayStarted_var",0);
player:setVar("QuestRychardeTCCompDay_var",0);
player:setVar("QuestRychardeTCCompYear_var",0);
player:setVar("QuestWayofTCCompDay_var",VanadielDayOfTheYear()); -- completition day of WAY_OF_THE_COOK
player:setVar("QuestWayofTCCompYear_var",VanadielYear());
player:completeQuest(OTHER_AREAS,WAY_OF_THE_COOK);
elseif (csid == 0x51) then --end quest 2 WAY_OF_THE_COOK
player:tradeComplete();
player:addFame(WINDURST,WIN_FAME*120);
player:addTitle(PURVEYOR_IN_TRAINING);
player:addGil(GIL_RATE*1000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*1000);
player:setVar("QuestWayotcHourStarted_var",0);
player:setVar("QuestRychardeTCDayStarted_var",0);
player:setVar("QuestRychardeTCCompDay_var",0);
player:setVar("QuestRychardeTCCompYear_var",0);
player:setVar("QuestWayofTCCompDay_var",VanadielDayOfTheYear()); -- completition day of WAY_OF_THE_COOK
player:setVar("QuestWayofTCCompYear_var",VanadielYear());
player:completeQuest(OTHER_AREAS,WAY_OF_THE_COOK);
elseif (csid == 0x52) then -- accept quest 3 UNENDING_CHASE
player:setVar("QuestUnendingCAskedAlready_var",2);
if (option == 77 ) then -- answer yes!
player:addQuest(OTHER_AREAS,UNENDING_CHASE);
end
elseif (csid == 0x54) then -- accept quest 3 UNENDING_CHASE
if (option == 78 ) then -- answer yes!
player:addQuest(OTHER_AREAS,UNENDING_CHASE);
end
elseif (csid == 0x53) then -- end quest 3 UNENDING_CHASE
player:tradeComplete();
player:addFame(WINDURST,WIN_FAME*120);
player:addTitle(TWOSTAR_PURVEYOR);
player:addGil(GIL_RATE*2100);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*2100);
player:setVar("QuestUnendingCAskedAlready_var",0);
player:setVar("QuestWayofTCCompDay_var",0); -- completition day of WAY_OF_THE_COOK delete variable
player:setVar("QuestWayofTCCompYear_var",0);
player:setVar("QuestUnendingCCompDay_var",VanadielDayOfTheYear()); -- completition day of unending chase
player:setVar("QuestUnendingCCompYear_var",VanadielYear());
player:completeQuest(OTHER_AREAS,UNENDING_CHASE);
elseif (csid == 0x56) then -- accept quest 4 HIS_NAME_IS_VALGEIR
if (option == 80 ) then -- answer yes!
player:addKeyItem(ARAGONEU_PIZZA); --give pizza to player
player:messageSpecial(KEYITEM_OBTAINED,ARAGONEU_PIZZA);
player:addQuest(OTHER_AREAS,HIS_NAME_IS_VALGEIR);
end
elseif (csid == 0x58) then -- end quest 4 his name is Valgeir
player:addFame(WINDURST,WIN_FAME*120);
player:addKeyItem(MAP_OF_THE_TORAIMARAI_CANAL); --reward Map of the Toraimarai Canal
player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_TORAIMARAI_CANAL);
player:setVar("QuestUnendingCCompDay_var",0); -- completition day of unending chase delete
player:setVar("QuestUnendingCCompYear_var",0);
player:setVar("QuestHNIVCCompDay_var",VanadielDayOfTheYear()); -- completition day of unending chase
player:setVar("QuestHNIVCCompYear_var",VanadielYear());
player:completeQuest(OTHER_AREAS,HIS_NAME_IS_VALGEIR);
elseif (csid == 0x5a or csid == 0x5b) then --accept quest the clue
player:setVar("QuestTheClueStatus_var",1);
if (option == 83 ) then
player:addQuest(OTHER_AREAS,THE_CLUE);
end
elseif (csid == 0x5c) then -- end quest THE CLUE
player:tradeComplete();
player:addFame(WINDURST,WIN_FAME*120);
player:addTitle(FOURSTAR_PURVEYOR);
player:addGil(GIL_RATE*3000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*3000);
player:setVar("QuestTheClueStatus_var",0);
player:setVar("QuestExpertiseCompDay_var",0); -- completition day of expertice quest
player:setVar("QuestExpertiseCompYear_var",0);
player:setVar("QuestTheClueCompDay_var",VanadielDayOfTheYear()); -- completition day of THE CLUE
player:setVar("QuestTheClueCompYear_var",VanadielYear());
player:completeQuest(OTHER_AREAS,THE_CLUE);
elseif (csid == 0x5e) then --accept quest the basics
if (option == 85 ) then
--TODO pay for ferry
player:addKeyItem(MHAURAN_COUSCOUS); --MHAURAN_COUSCOUS = 92;
player:messageSpecial(KEYITEM_OBTAINED,MHAURAN_COUSCOUS);
player:addQuest(OTHER_AREAS,THE_BASICS);
end
elseif (csid == 0x60) then -- end quest the basics
player:tradeComplete();
player:addFame(WINDURST,WIN_FAME*120);
player:addTitle(FIVESTAR_PURVEYOR);
if (player:getFreeSlotsCount() <= 1) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,133);
else
player:addItem(133);
player.messageSpecial(ITEM_OBTAINED,133);
player:setVar("QuestTheClueCompDay_var",0); -- completition day of THE CLUE
player:setVar("QuestTheClueCompYear_var",0);
player:setVar("QuestTheBasicsComentary_var",1);
player:completeQuest(OTHER_AREAS,THE_BASICS);
end
elseif (csid == 0x61) then --end commentary quest the basics
player:setVar("QuestTheBasicsComentary_var",0);
end
end; | gpl-3.0 |
everslick/awesome | lib/wibox/widget/base.lua | 2 | 17688 | ---------------------------------------------------------------------------
-- @author Uli Schlachter
-- @copyright 2010 Uli Schlachter
-- @release @AWESOME_VERSION@
-- @module wibox.widget.base
---------------------------------------------------------------------------
local debug = require("gears.debug")
local object = require("gears.object")
local cache = require("gears.cache")
local matrix = require("gears.matrix")
local Matrix = require("lgi").cairo.Matrix
local setmetatable = setmetatable
local pairs = pairs
local type = type
local table = table
local base = {}
-- {{{ Caches
local call_stack = {}
-- Indexes are widgets, allow them to be garbage-collected
local widget_dependencies = setmetatable({}, { __mode = "k" })
-- Don't do this in unit tests
if awesome and awesome.connect_signal then
-- Reset the call stack at each refresh. This fixes things up in case there was
-- an error in some callback and thus put_cache() wasn't called (if this
-- happens, we possibly recorded too many deps, but so what?)
awesome.connect_signal("refresh", function()
call_stack = {}
end)
end
-- When you call get_cache_and_record_deps(), the widget is recorded in a stack
-- until the following put_cache(). All other calls to
-- get_cache_and_record_deps() that happen during this will cause a dependency
-- between the widgets that are involved to be recorded. This information is
-- used by clear_caches() to also clear all caches of dependent widgets.
-- Get the caches for a widget and record its dependencies. All following
-- cache-uses will record this widgets as a dependency. This returns a function
-- that calls the callback of kind `kind` on the widget.
local function get_cache_and_record_deps(widget, kind)
-- Record dependencies (each entry in the call stack depends on `widget`)
local deps = widget_dependencies[widget] or {}
for _, w in pairs(call_stack) do
deps[w] = true
end
widget_dependencies[widget] = deps
-- Add widget to call stack
table.insert(call_stack, widget)
-- Create cache if needed
if not widget._widget_caches[kind] then
widget._widget_caches[kind] = cache.new(function(...)
return widget[kind](widget, ...)
end)
end
return widget._widget_caches[kind]
end
-- Each call to the above function should be followed by a call to this
-- function. Everything in-between is recorded as a dependency (it's
-- complicated...).
local function put_cache(widget)
assert(#call_stack ~= 0)
if table.remove(call_stack) ~= widget then
put_cache(widget)
end
end
-- Clear the caches for `widget` and all widgets that depend on it.
local function clear_caches(widget)
for w in pairs(widget_dependencies[widget] or {}) do
widget_dependencies[w] = {}
w._widget_caches = {}
end
widget_dependencies[widget] = {}
widget._widget_caches = {}
end
-- }}}
--- Figure out the geometry in device coordinate space. This gives only tight
-- bounds if no rotations by non-multiples of 90° are used.
function base.rect_to_device_geometry(cr, x, y, width, height)
return matrix.transform_rectangle(cr.matrix, x, y, width, height)
end
--- Fit a widget for the given available width and height. This calls the
-- widget's `:fit` callback and caches the result for later use. Never call
-- `:fit` directly, but always through this function!
-- @param context The context in which we are fit.
-- @param widget The widget to fit (this uses widget:fit(width, height)).
-- @param width The available width for the widget
-- @param height The available height for the widget
-- @return The width and height that the widget wants to use
function base.fit_widget(context, widget, width, height)
if not widget.visible then
return 0, 0
end
-- Sanitize the input. This also filters out e.g. NaN.
local width = math.max(0, width)
local height = math.max(0, height)
local w, h = 0, 0
if widget.fit then
local cache = get_cache_and_record_deps(widget, "fit")
w, h = cache:get(context, width, height)
put_cache(widget)
else
-- If it has no fit method, calculate based on the size of children
local children = base.layout_widget(context, widget, width, height)
for _, info in ipairs(children or {}) do
local x, y, w2, h2 = matrix.transform_rectangle(info._matrix,
0, 0, info._width, info._height)
w, h = math.max(w, x + w2), math.max(h, y + h2)
end
end
-- Also sanitize the output.
w = math.max(0, math.min(w, width))
h = math.max(0, math.min(h, height))
return w, h
end
--- Lay out a widget for the given available width and height. This calls the
-- widget's `:layout` callback and caches the result for later use. Never call
-- `:layout` directly, but always through this function! However, normally there
-- shouldn't be any reason why you need to use this function.
-- @param context The context in which we are laid out.
-- @param widget The widget to layout (this uses widget:layout(context, width, height)).
-- @param width The available width for the widget
-- @param height The available height for the widget
-- @return The result from the widget's `:layout` callback.
function base.layout_widget(context, widget, width, height)
if not widget.visible then
return
end
-- Sanitize the input. This also filters out e.g. NaN.
local width = math.max(0, width)
local height = math.max(0, height)
if widget.layout then
local cache = get_cache_and_record_deps(widget, "layout")
local result = cache:get(context, width, height)
put_cache(widget)
return result
end
end
--- Set/get a widget's buttons.
-- This function is available on widgets created by @{make_widget}.
function base:buttons(_buttons)
if _buttons then
self.widget_buttons = _buttons
end
return self.widget_buttons
end
-- Handle a button event on a widget. This is used internally and should not be
-- called directly.
function base.handle_button(event, widget, x, y, button, modifiers, geometry)
local function is_any(mod)
return #mod == 1 and mod[1] == "Any"
end
local function tables_equal(a, b)
if #a ~= #b then
return false
end
for k, v in pairs(b) do
if a[k] ~= v then
return false
end
end
return true
end
-- Find all matching button objects
local matches = {}
for k, v in pairs(widget.widget_buttons) do
local match = true
-- Is it the right button?
if v.button ~= 0 and v.button ~= button then match = false end
-- Are the correct modifiers pressed?
if (not is_any(v.modifiers)) and (not tables_equal(v.modifiers, modifiers)) then match = false end
if match then
table.insert(matches, v)
end
end
-- Emit the signals
for k, v in pairs(matches) do
v:emit_signal(event,geometry)
end
end
--- Create widget placement information. This should be used for a widget's
-- `:layout()` callback.
-- @param widget The widget that should be placed.
-- @param mat A cairo matrix transforming from the parent widget's coordinate
-- system. For example, use cairo.Matrix.create_translate(1, 2) to draw a
-- widget at position (1, 2) relative to the parent widget.
-- @param width The width of the widget in its own coordinate system. That is,
-- after applying the transformation matrix.
-- @param height The height of the widget in its own coordinate system. That is,
-- after applying the transformation matrix.
-- @return An opaque object that can be returned from :layout()
function base.place_widget_via_matrix(widget, mat, width, height)
return {
_widget = widget,
_width = width,
_height = height,
_matrix = matrix.copy(mat)
}
end
--- Create widget placement information. This should be used for a widget's
-- `:layout()` callback.
-- @param widget The widget that should be placed.
-- @param x The x coordinate for the widget.
-- @param y The y coordinate for the widget.
-- @param width The width of the widget in its own coordinate system. That is,
-- after applying the transformation matrix.
-- @param height The height of the widget in its own coordinate system. That is,
-- after applying the transformation matrix.
-- @return An opaque object that can be returned from :layout()
function base.place_widget_at(widget, x, y, width, height)
return base.place_widget_via_matrix(widget, Matrix.create_translate(x, y), width, height)
end
--[[--
Create a new widget. All widgets have to be generated via this function so that
the needed signals are added and mouse input handling is set up.
The returned widget will have a :buttons member function that can be used to
register a set of mouse button events with the widget.
To implement your own widget, you can implement some member functions on a
freshly-created widget. Note that all of these functions should be deterministic
in the sense that they will show the same behavior if they are repeatedly called
with the same arguments (same width and height). If your widget is updated and
needs to change, suitable signals have to be emitted. This will be explained
later.
The first callback is :fit. This function is called to select the size of your
widget. The arguments to this function is the available space and it should
return its desired size. Note that this function only provides a hint which is
not necessarily followed. The widget must also be able to draw itself at
different sizes than the one requested.
<pre><code>function widget:fit(context, width, height)
-- Find the maximum square available
local m = math.min(width, height)
return m, m
end</code></pre>
The next callback is :draw. As the name suggests, this function is called to
draw the widget. The arguments to this widget are the context that the widget is
drawn in, the cairo context on which it should be drawn and the widget's size.
The cairo context is set up in such a way that the widget as its top-left corner
at (0, 0) and its bottom-right corner at (width, height). In other words, no
special transformation needs to be done. Note that during this callback a
suitable clip will already be applied to the cairo context so that this callback
will not be able to draw outside of the area that was registered for the widget
by the layout that placed this widget. You should not call
<code>cr:reset_clip()</code>, as redraws will not be handled correctly in this
case.
<pre><code>function widget:draw(wibox, cr, width, height)
cr:move_to(0, 0)
cr:line_to(width, height)
cr:move_to(0, height)
cr:line_to(width, 0)
cr:stroke()
end</code></pre>
There are two signals configured for a widget. When the result that :fit would
return changes, the <code>widget::layout_changed</code> signal has to be
emitted. If this actually causes layout changes, the affected areas will be
redrawn. The other signal is <code>widget::redraw_needed</code>. This signal
signals that :draw has to be called to redraw the widget, but it is safe to
assume that :fit does still return the same values as before. If in doubt, you
can emit both signals to be safe.
If your widget only needs to draw something to the screen, the above is all that
is needed. The following callbacks can be used when implementing layouts which
place other widgets on the screen.
The :layout callback is used to figure out which other widgets should be drawn
relative to this widget. Note that it is allowed to place widgets outside of the
extents of your own widget, for example at a negative position or at twice the
size of this widget. Use this mechanism if your widget needs to draw outside of
its own extents. If the result of this callback changes,
<code>widget::layout_changed</code> has to be emitted. You can use @{fit_widget}
to call the `:fit` callback of other widgets. Never call `:fit` directly! For
example, if you want to place another widget <code>child</code> inside of your
widget, you can do it like this:
<pre><code>-- For readability
local base = wibox.widget.base
function widget:layout(width, height)
local result = {}
table.insert(result, base.place_widget_at(child, width/2, 0, width/2, height)
return result
end</code></pre>
Finally, if you want to influence how children are drawn, there are four
callbacks available that all get similar arguments:
<pre><code>function widget:before_draw_children(context, cr, width, height)
function widget:after_draw_children(context, cr, width, height)
function widget:before_draw_child(context, index, child, cr, width, height)
function widget:after_draw_child(context, index, child, cr, width, height)</code></pre>
All of these are called with the same arguments as the :draw() method. Please
note that a larger clip will be active during these callbacks that also contains
the area of all children. These callbacks can be used to influence the way in
which children are drawn, but they should not cause the drawing to cover a
different area. As an example, these functions can be used to draw children
translucently:
<pre><code>function widget:before_draw_children(wibox, cr, width, height)
cr:push_group()
end
function widget:after_draw_children(wibox, cr, width, height)
cr:pop_group_to_source()
cr:paint_with_alpha(0.5)
end</code></pre>
In pseudo-code, the call sequence for the drawing callbacks during a redraw
looks like this:
<pre><code>widget:draw(wibox, cr, width, height)
widget:before_draw_children(wibox, cr, width, height)
for child do
widget:before_draw_child(wibox, cr, child_index, child, width, height)
cr:save()
-- Draw child and all of its children recursively, taking into account the
-- position and size given to base.place_widget_at() in :layout().
cr:restore()
widget:after_draw_child(wibox, cr, child_index, child, width, height)
end
widget:after_draw_children(wibox, cr, width, height)</code></pre>
@param proxy If this is set, the returned widget will be a proxy for this
widget. It will be equivalent to this widget. This means it
looks the same on the screen.
@tparam[opt] string widget_name Name of the widget. If not set, it will be
set automatically via `gears.object.modulename`.
@see fit_widget
--]]--
function base.make_widget(proxy, widget_name)
local ret = object()
-- This signal is used by layouts to find out when they have to update.
ret:add_signal("widget::layout_changed")
ret:add_signal("widget::redraw_needed")
-- Mouse input, oh noes!
ret:add_signal("button::press")
ret:add_signal("button::release")
ret:add_signal("mouse::enter")
ret:add_signal("mouse::leave")
-- Backwards compatibility
-- TODO: Remove this
ret:add_signal("widget::updated")
ret:connect_signal("widget::updated", function()
ret:emit_signal("widget::layout_changed")
ret:emit_signal("widget::redraw_needed")
end)
-- No buttons yet
ret.widget_buttons = {}
ret.buttons = base.buttons
-- Make buttons work
ret:connect_signal("button::press", function(...)
return base.handle_button("press", ...)
end)
ret:connect_signal("button::release", function(...)
return base.handle_button("release", ...)
end)
if proxy then
ret.fit = function(_, context, width, height)
return base.fit_widget(context, proxy, width, height)
end
ret.layout = function(_, context, width, height)
return { base.place_widget_at(proxy, 0, 0, width, height) }
end
proxy:connect_signal("widget::layout_changed", function()
ret:emit_signal("widget::layout_changed")
end)
proxy:connect_signal("widget::redraw_needed", function()
ret:emit_signal("widget::redraw_needed")
end)
end
-- Set up caches
clear_caches(ret)
ret:connect_signal("widget::layout_changed", function()
clear_caches(ret)
end)
-- Add visible property and setter.
ret.visible = true
function ret:set_visible(b)
if b ~= self.visible then
self.visible = b
self:emit_signal("widget::layout_changed")
-- In case something ignored fit and drew the widget anyway
self:emit_signal("widget::redraw_needed")
end
end
-- Add opacity property and setter.
ret.opacity = 1
function ret:set_opacity(b)
if b ~= self.opacity then
self.opacity = b
self:emit_signal("widget::redraw")
end
end
-- Add __tostring method to metatable.
ret.widget_name = widget_name or object.modulename(3)
local mt = {}
local orig_string = tostring(ret)
mt.__tostring = function(o)
return string.format("%s (%s)", ret.widget_name, orig_string)
end
return setmetatable(ret, mt)
end
--- Generate an empty widget which takes no space and displays nothing
function base.empty_widget()
return base.make_widget()
end
--- Do some sanity checking on widget. This function raises a lua error if
-- widget is not a valid widget.
function base.check_widget(widget)
debug.assert(type(widget) == "table")
for k, func in pairs({ "add_signal", "connect_signal", "disconnect_signal" }) do
debug.assert(type(widget[func]) == "function", func .. " is not a function")
end
end
return base
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Bastok_Markets/TextIDs.lua | 2 | 3742 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6375; -- You cannot obtain the item <item> come back again after sorting your inventory
FULL_INVENTORY_AFTER_TRADE = 6377; -- You cannot obtain the <item>. Try trading again after sorting your inventory
ITEM_OBTAINED = 6378; -- Obtained: <item>
GIL_OBTAINED = 6379; -- Obtained <number> gil
KEYITEM_OBTAINED = 6381; -- Obtained key item: <keyitem>
NOT_HAVE_ENOUGH_GIL = 6383; -- You do not have enough gil
ITEMS_OBTAINED = 6384; -- You obtain <number> <item>!
HOMEPOINT_SET = 6434; -- Home point set!
FISHING_MESSAGE_OFFSET = 7004; -- You can't fish here
-- Conquest System
CONQUEST = 7568; -- You've earned conquest points!
-- Mission Dialogs
YOU_ACCEPT_THE_MISSION = 6444; -- You have accepted the mission.
ORIGINAL_MISSION_OFFSET = 6449; -- You can consult the “Mission” section of the main menu to review your objectives. Speed and efficiency are your priorities. Dismissed.
EXTENDED_MISSION_OFFSET = 7930; -- Go to Ore Street and talk to Medicine Eagle. He says he was there when the commotion started.
-- Other Dialogs
ITEM_DELIVERY_DIALOG = 7451; -- Need something sent to a friend's house? Sending items to your own room? You've come to the right place!
-- Shop Texts
SOMNPAEMN_CLOSED_DIALOG = 7362; -- Sorry, I don't have anything to sell you. I'm trying to start a business selling goods from Sarutabaruta, ...
YAFAFA_CLOSED_DIALOG = 7363; -- Sorry, I don't have anything to sell you. I'm trying to start a business selling goods from Kolshushu, ...
OGGODETT_CLOSED_DIALOG = 7364; -- Sorry, I don't have anything to sell you. I'm trying to start a business selling goods from Aragoneu, ...
TEERTH_SHOP_DIALOG = 7465; -- Welcome to the Goldsmiths' Guild shop. What can I do for you?
VISALA_SHOP_DIALOG = 7466; -- Welcome to the Goldsmiths' Guild shop. How may I help you?
ZHIKKOM_SHOP_DIALOG = 7467; -- Hello! Welcome to the only weaponry store in Bastok, the Dragon's Claws!
CIQALA_SHOP_DIALOG = 7468; -- A weapon is the most precious thing to an adventurer! Well, after his life, of course. Choose wisely.
PERITRAGE_SHOP_DIALOG = 7469; -- Hey! I've got just the thing for you!
BRUNHILDE_SHOP_DIALOG = 7470; -- Welcome to my store! You want armor, you want shields? I've got them all!
CHARGINGCHOKOBO_SHOP_DIALOG = 7471; -- Hello. What piece of armor are you missing?
BALTHILDA_SHOP_DIALOG = 7472; -- Feeling defenseless of late? Brunhilde's Armory has got you covered!
MJOLL_SHOP_DIALOG = 7473; -- Welcome. Have a look and compare! You'll never find better wares anywhere.
OLWYN_SHOP_DIALOG = 7474; -- Welcome to Mjoll's Goods! What can I do for you?
ZAIRA_SHOP_DIALOG = 7475; -- Greetings. What spell are you looking for?
SORORO_SHOP_DIALOG = 7476; -- Hello-mellow, welcome to Sororo's Scribe and Notary! Hmm? No, we sell magic spells! What did you think?
HARMODIOS_SHOP_DIALOG = 7477; -- Add music to your adventuring life! Welcome to Harmodios's.
CARMELIDE_SHOP_DIALOG = 7478; -- Ah, welcome, welcome! What might I interest you in?
RAGHD_SHOP_DIALOG = 7479; -- Give a smile to that special someone! Welcome to Carmelide's.
HORTENSE_SHOP_DIALOG = 7480; -- Hello there! We have instruments and music sheets at Harmodios's!
OGGODETT_OPEN_DIALOG = 7481; -- Hello there! Might I interest you in some specialty goods from Aragoneu?
YAFAFA_OPEN_DIALOG = 7482; -- Hello! I've got some goods from Kolshushu--interested?
SOMNPAEMN_OPEN_DIALOG = 7483; -- Welcome! I have goods straight from Sarutabaruta! What say you? | gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Gusgen_Mines/npcs/_5ge.lua | 2 | 1420 | -----------------------------------
-- Area: Gusgen Mines
-- NPC: Lever E
-- @pos 20 -20.561 143.801
-----------------------------------
package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Gusgen_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--Designation: Door(db name), lever(db name)
--A: 17580370(_5g2), 17580376(_5gc)
--B: 17580369(_5g1), 17508375(_5gb)
--C: 17580368(_5g0), 17508374(_5ga)
--D: 17508373(_5g5), 17580379(_5gf)
--E: 17580372(_5g4), 17580378(_5ge)
--F: 17580371(_5g3), 17580377(_5gd)
--local nID = npc:getID();
--printf("id: %u", nID);
GetNPCByID(17580371):setAnimation(9);--close door F
GetNPCByID(17580372):setAnimation(8);--open door E
GetNPCByID(17580373):setAnimation(9);--close door D
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 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Den_of_Rancor/npcs/_4g4.lua | 2 | 2613 | -----------------------------------
-- Area: Den of Rancor
-- NPC: Lantern (NW)
-- @pos -59 45 24 160
-----------------------------------
package.loaded["scripts/zones/Den_of_Rancor/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Den_of_Rancor/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Trade Crimson Rancor Flame
if(trade:hasItemQty(1139,1) and trade:getItemCount() == 1) then
nw = os.time() - GetServerVariable("[LANTERN]_rancor_nw_last_lit");
if(nw <= LANTERNS_STAY_LIT) then
player:messageSpecial(LANTERN_OFFSET + 7); -- the lantern is already lit
else
player:tradeComplete();
player:addItem(1138); -- Unlit Lantern
--GetNPCByID(17433045):lightFor(LANTERNS_STAY_LIT); -- Light the lantern for x sec
SetServerVariable("[LANTERN]_rancor_nw_last_lit",os.time());
ne = os.time() - GetServerVariable("[LANTERN]_rancor_ne_last_lit");
sw = os.time() - GetServerVariable("[LANTERN]_rancor_sw_last_lit");
se = os.time() - GetServerVariable("[LANTERN]_rancor_se_last_lit");
number_of_lit_lanterns = 1;
if(ne <= LANTERNS_STAY_LIT) then
number_of_lit_lanterns = number_of_lit_lanterns + 1;
end
if(sw <= LANTERNS_STAY_LIT) then
number_of_lit_lanterns = number_of_lit_lanterns + 1;
end
if(se <= LANTERNS_STAY_LIT) then
number_of_lit_lanterns = number_of_lit_lanterns + 1;
end;
if(number_of_lit_lanterns == 1) then
player:messageSpecial(LANTERN_OFFSET + 9); -- the first lantern is lit
elseif(number_of_lit_lanterns == 2) then
player:messageSpecial(LANTERN_OFFSET + 10); -- the second lantern is lit
elseif(number_of_lit_lanterns == 3) then
player:messageSpecial(LANTERN_OFFSET + 11); -- the third lantern is lit
elseif(number_of_lit_lanterns == 4) then
player:messageSpecial(LANTERN_OFFSET + 12); -- All the lanterns are lit
timeGateOpened = math.min(LANTERNS_STAY_LIT - ne,LANTERNS_STAY_LIT - sw,LANTERNS_STAY_LIT - se);
GetNPCByID(17433049):openDoor(timeGateOpened); -- drop gate to Sacrificial Chamber
end;
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
nw = os.time() - GetServerVariable("[LANTERN]_rancor_nw_last_lit");
if(nw <= LANTERNS_STAY_LIT) then
player:messageSpecial(LANTERN_OFFSET + 7); -- The lantern is already lit.
else
player:messageSpecial(LANTERN_OFFSET + 20); -- The flames of rancor have burned out.
end
return 0;
end; | gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/fish_chiefkabob.lua | 3 | 1418 | -----------------------------------------
-- 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) 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 |
Servius/tfa-sw-weapons-repository | Live Addons/servius_uploader_legacy/tfa_shared_resources/lua/effects/servius_stun/init.lua | 4 | 2800 |
TRACER_FLAG_USEATTACHMENT = 0x0002;
SOUND_FROM_WORLD = 0;
CHAN_STATIC = 6;
EFFECT.Speed = 6500;
EFFECT.Length = 64;
--EFFECT.WhizSound = Sound( "nomad/whiz.wav" ); -- by Robinhood76 (http:--www.freesound.org/people/Robinhood76/sounds/96556/)
EFFECT.WhizDistance = 72;
local MaterialMain = Material( "star/effects/blue_shockwave" );
local MaterialFront = Material( "star/effects/blue_shockwave" );
function EFFECT:GetTracerOrigin(data)
-- this is almost a direct port of GetTracerOrigin in fx_tracer.cpp
local start = data:GetStart()
-- use attachment?
if (bit.band(data:GetFlags(), TRACER_FLAG_USEATTACHMENT) == TRACER_FLAG_USEATTACHMENT) then
local entity = data:GetEntity()
if (not IsValid(entity)) then return start end
if (not game.SinglePlayer() and entity:IsEFlagSet(EFL_DORMANT)) then return start end
if (entity:IsWeapon() and entity:IsCarriedByLocalPlayer()) then
-- can't be done, can't call the real function
-- local origin = weapon:GetTracerOrigin();
-- if( origin ) then
-- return origin, angle, entity;
-- end
-- use the view model
local pl = entity:GetOwner()
if (IsValid(pl)) then
local vm = pl:GetViewModel()
if (IsValid(vm) and not LocalPlayer():ShouldDrawLocalPlayer()) then
entity = vm
-- HACK: fix the model in multiplayer
else
if (entity.WorldModel) then
entity:SetModel(entity.WorldModel)
end
end
end
end
local attachment = entity:GetAttachment(data:GetAttachment())
if (attachment) then
start = attachment.Pos
end
end
return start
end
function EFFECT:Init(data)
self.StartPos = self:GetTracerOrigin(data)
self.EndPos = data:GetOrigin()
self.Entity:SetRenderBoundsWS(self.StartPos, self.EndPos)
local diff = (self.EndPos - self.StartPos)
self.Normal = diff:GetNormal()
self.StartTime = 0
self.LifeTime = (diff:Length() + self.Length) / self.Speed
-- whiz by sound
local weapon = data:GetEntity()
if (IsValid(weapon) and (not weapon:IsWeapon() or not weapon:IsCarriedByLocalPlayer())) then
local dist, pos, time = util.DistanceToLine(self.StartPos, self.EndPos, EyePos())
end
end
function EFFECT:Think()
self.LifeTime = self.LifeTime - FrameTime()
self.StartTime = self.StartTime + FrameTime()
return self.LifeTime > 0
end
function EFFECT:Render()
local endDistance = self.Speed * self.StartTime
local startDistance = endDistance - self.Length
startDistance = math.max(0, startDistance)
endDistance = math.max(0, endDistance)
local startPos = self.StartPos + self.Normal * startDistance
local endPos = self.StartPos + self.Normal * endDistance
render.SetMaterial(MaterialFront)
render.DrawSprite(endPos, 35, 35, color_white)
render.SetMaterial(MaterialMain)
render.DrawBeam(startPos, endPos, 10, 0, 1, color_white)
end
| apache-2.0 |
Sonicrich05/FFXI-Server | scripts/globals/spells/bluemagic/ram_charge.lua | 27 | 1737 | -----------------------------------------
-- Spell: Ram Charge
-- Damage varies with TP
-- Spell cost: 79 MP
-- Monster Type: Beasts
-- Spell Type: Physical (Blunt)
-- Blue Magic Points: 4
-- Stat Bonus: HP+5
-- Level: 73
-- Casting Time: 0.5 seconds
-- Recast Time: 34.75 seconds
-- Skillchain Element(s): Fragmentation (can open/close Light with Fusion WSs and spells)
-- Combos: Lizard Killer
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local params = {};
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.tpmod = TPMOD_DAMAGE;
params.dmgtype = DMGTYPE_BLUNT;
params.scattr = SC_FRAGMENTATION;
params.numhits = 1;
params.multiplier = 1.0;
params.tp150 = 1.375;
params.tp300 = 1.75;
params.azuretp = 1.875;
params.duppercap = 75;
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;
damage = BluePhysicalSpell(caster, target, spell, params);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
-- Missing KNOCKBACK effect
return damage;
end; | gpl-3.0 |
RavenX8/osIROSE-new | scripts/mobs/ai/elder_sikuku.lua | 2 | 1076 | registerNpc(555, {
walk_speed = 210,
run_speed = 470,
scale = 110,
r_weapon = 1103,
l_weapon = 0,
level = 183,
hp = 37,
attack = 909,
hit = 549,
def = 507,
res = 930,
avoid = 303,
attack_spd = 100,
is_magic_damage = 1,
ai_type = 295,
give_exp = 229,
drop_type = 474,
drop_money = 30,
drop_item = 70,
union_number = 70,
need_summon_count = 0,
sell_tab0 = 0,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 1700,
npc_type = 7,
hit_material_type = 1,
face_icon = 0,
summon_mob_type = 0,
quest_type = 0,
height = 0
});
function OnInit(entity)
return true
end
function OnCreate(entity)
return true
end
function OnDelete(entity)
return true
end
function OnDead(entity)
end
function OnDamaged(entity)
end | apache-2.0 |
everslick/awesome | lib/awful/prompt.lua | 7 | 22293 | ---------------------------------------------------------------------------
--- Prompt module for awful
--
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2008 Julien Danjou
-- @release @AWESOME_VERSION@
-- @module awful.prompt
---------------------------------------------------------------------------
-- Grab environment we need
local assert = assert
local io = io
local table = table
local math = math
local ipairs = ipairs
local pcall = pcall
local capi =
{
selection = selection
}
local keygrabber = require("awful.keygrabber")
local util = require("awful.util")
local beautiful = require("beautiful")
local prompt = {}
--- Private data
local data = {}
data.history = {}
local search_term = nil
local function itera (inc,a, i)
i = i + inc
local v = a[i]
if v then return i,v end
end
--- Load history file in history table
-- @param id The data.history identifier which is the path to the filename.
-- @param[opt] max The maximum number of entries in file.
local function history_check_load(id, max)
if id and id ~= ""
and not data.history[id] then
data.history[id] = { max = 50, table = {} }
if max then
data.history[id].max = max
end
local f = io.open(id, "r")
-- Read history file
if f then
for line in f:lines() do
if util.table.hasitem(data.history[id].table, line) == nil then
table.insert(data.history[id].table, line)
if #data.history[id].table >= data.history[id].max then
break
end
end
end
f:close()
end
end
end
local function is_word_char(c)
if string.find("[{[(,.:;_-+=@/ ]", c) then
return false
else
return true
end
end
local function cword_start(s, pos)
local i = pos
if i > 1 then
i = i - 1
end
while i >= 1 and not is_word_char(s:sub(i, i)) do
i = i - 1
end
while i >= 1 and is_word_char(s:sub(i, i)) do
i = i - 1
end
if i <= #s then
i = i + 1
end
return i
end
local function cword_end(s, pos)
local i = pos
while i <= #s and not is_word_char(s:sub(i, i)) do
i = i + 1
end
while i <= #s and is_word_char(s:sub(i, i)) do
i = i + 1
end
return i
end
--- Save history table in history file
-- @param id The data.history identifier
local function history_save(id)
if data.history[id] then
local f = io.open(id, "w")
if not f then
local i = 0
for d in id:gmatch(".-/") do
i = i + #d
end
util.mkdir(id:sub(1, i - 1))
f = assert(io.open(id, "w"))
end
for i = 1, math.min(#data.history[id].table, data.history[id].max) do
f:write(data.history[id].table[i] .. "\n")
end
f:close()
end
end
--- Return the number of items in history table regarding the id
-- @param id The data.history identifier
-- @return the number of items in history table, -1 if history is disabled
local function history_items(id)
if data.history[id] then
return #data.history[id].table
else
return -1
end
end
--- Add an entry to the history file
-- @param id The data.history identifier
-- @param command The command to add
local function history_add(id, command)
if data.history[id] and command ~= "" then
local index = util.table.hasitem(data.history[id].table, command)
if index == nil then
table.insert(data.history[id].table, command)
-- Do not exceed our max_cmd
if #data.history[id].table > data.history[id].max then
table.remove(data.history[id].table, 1)
end
history_save(id)
else
-- Bump this command to the end of history
table.remove(data.history[id].table, index)
table.insert(data.history[id].table, command)
history_save(id)
end
end
end
--- Draw the prompt text with a cursor.
-- @tparam table args The table of arguments.
-- @field text The text.
-- @field font The font.
-- @field prompt The text prefix.
-- @field text_color The text color.
-- @field cursor_color The cursor color.
-- @field cursor_pos The cursor position.
-- @field cursor_ul The cursor underline style.
-- @field selectall If true cursor is rendered on the entire text.
local function prompt_text_with_cursor(args)
local char, spacer, text_start, text_end, ret
local text = args.text or ""
local _prompt = args.prompt or ""
local underline = args.cursor_ul or "none"
if args.selectall then
if #text == 0 then char = " " else char = util.escape(text) end
spacer = " "
text_start = ""
text_end = ""
elseif #text < args.cursor_pos then
char = " "
spacer = ""
text_start = util.escape(text)
text_end = ""
else
char = util.escape(text:sub(args.cursor_pos, args.cursor_pos))
spacer = " "
text_start = util.escape(text:sub(1, args.cursor_pos - 1))
text_end = util.escape(text:sub(args.cursor_pos + 1))
end
local cursor_color = util.ensure_pango_color(args.cursor_color)
local text_color = util.ensure_pango_color(args.text_color)
ret = _prompt .. text_start .. "<span background=\"" .. cursor_color ..
"\" foreground=\"" .. text_color .. "\" underline=\"" .. underline ..
"\">" .. char .. "</span>" .. text_end .. spacer
return ret
end
--- Run a prompt in a box.
--
-- The following readline keyboard shortcuts are implemented as expected:
-- <kbd>CTRL+A</kbd>, <kbd>CTRL+B</kbd>, <kbd>CTRL+C</kbd>, <kbd>CTRL+D</kbd>,
-- <kbd>CTRL+E</kbd>, <kbd>CTRL+J</kbd>, <kbd>CTRL+M</kbd>, <kbd>CTRL+F</kbd>,
-- <kbd>CTRL+H</kbd>, <kbd>CTRL+K</kbd>, <kbd>CTRL+U</kbd>, <kbd>CTRL+W</kbd>,
-- <kbd>CTRL+BACKSPACE</kbd>, <kbd>SHIFT+INSERT</kbd>, <kbd>HOME</kbd>,
-- <kbd>END</kbd> and arrow keys.
--
-- The following shortcuts implement additional history manipulation commands
-- where the search term is defined as the substring of the command from first
-- character to cursor position.
--
-- * <kbd>CTRL+R</kbd>: reverse history search, matches any history entry
-- containing search term.
-- * <kbd>CTRL+S</kbd>: forward history search, matches any history entry
-- containing search term.
-- * <kbd>CTRL+UP</kbd>: ZSH up line or search, matches any history entry
-- starting with search term.
-- * <kbd>CTRL+DOWN</kbd>: ZSH down line or search, matches any history
-- entry starting with search term.
-- * <kbd>CTRL+DELETE</kbd>: delete the currently visible history entry from
-- history file. This does not delete new commands or history entries under
-- user editing.
--
-- @tparam table args A table with optional arguments: `fg_cursor`, `bg_cursor`,
-- `ul_cursor`, `prompt`, `text`, `selectall`, `font`, `autoexec`.
-- @param textbox The textbox to use for the prompt.
-- @param exe_callback The callback function to call with command as argument
-- when finished.
-- @param completion_callback The callback function to call to get completion.
-- @param[opt] history_path File path where the history should be
-- saved, set nil to disable history
-- @param[opt] history_max Set the maximum entries in history
-- file, 50 by default
-- @param[opt] done_callback The callback function to always call
-- without arguments, regardless of whether the prompt was cancelled.
-- @param[opt] changed_callback The callback function to call
-- with command as argument when a command was changed.
-- @param[opt] keypressed_callback The callback function to call
-- with mod table, key and command as arguments when a key was pressed.
function prompt.run(args, textbox, exe_callback, completion_callback, history_path, history_max, done_callback, changed_callback, keypressed_callback)
local grabber
local theme = beautiful.get()
if not args then args = {} end
local command = args.text or ""
local command_before_comp
local cur_pos_before_comp
local prettyprompt = args.prompt or ""
local inv_col = args.fg_cursor or theme.fg_focus or "black"
local cur_col = args.bg_cursor or theme.bg_focus or "white"
local cur_ul = args.ul_cursor
local text = args.text or ""
local font = args.font or theme.font
local selectall = args.selectall
search_term=nil
history_check_load(history_path, history_max)
local history_index = history_items(history_path) + 1
-- The cursor position
local cur_pos = (selectall and 1) or text:wlen() + 1
-- The completion element to use on completion request.
local ncomp = 1
if not textbox or not exe_callback then
return
end
textbox:set_font(font)
textbox:set_markup(prompt_text_with_cursor{
text = text, text_color = inv_col, cursor_color = cur_col,
cursor_pos = cur_pos, cursor_ul = cur_ul, selectall = selectall,
prompt = prettyprompt })
local exec = function()
textbox:set_markup("")
history_add(history_path, command)
keygrabber.stop(grabber)
exe_callback(command)
if done_callback then done_callback() end
end
-- Update textbox
local function update()
textbox:set_font(font)
textbox:set_markup(prompt_text_with_cursor{
text = command, text_color = inv_col, cursor_color = cur_col,
cursor_pos = cur_pos, cursor_ul = cur_ul, selectall = selectall,
prompt = prettyprompt })
end
grabber = keygrabber.run(
function (modifiers, key, event)
if event ~= "press" then return end
-- Convert index array to hash table
local mod = {}
for k, v in ipairs(modifiers) do mod[v] = true end
-- Call the user specified callback. If it returns true as
-- the first result then return from the function. Treat the
-- second and third results as a new command and new prompt
-- to be set (if provided)
if keypressed_callback then
local user_catched, new_command, new_prompt =
keypressed_callback(mod, key, command)
if new_command or new_prompt then
if new_command then
command = new_command
end
if new_prompt then
prettyprompt = new_prompt
end
update()
end
if user_catched then
if changed_callback then
changed_callback(command)
end
return
end
end
-- Get out cases
if (mod.Control and (key == "c" or key == "g"))
or (not mod.Control and key == "Escape") then
keygrabber.stop(grabber)
textbox:set_markup("")
history_save(history_path)
if done_callback then done_callback() end
return false
elseif (mod.Control and (key == "j" or key == "m"))
or (not mod.Control and key == "Return")
or (not mod.Control and key == "KP_Enter") then
exec()
-- We already unregistered ourselves so we don't want to return
-- true, otherwise we may unregister someone else.
return
end
-- Control cases
if mod.Control then
selectall = nil
if key == "a" then
cur_pos = 1
elseif key == "b" then
if cur_pos > 1 then
cur_pos = cur_pos - 1
end
elseif key == "d" then
if cur_pos <= #command then
command = command:sub(1, cur_pos - 1) .. command:sub(cur_pos + 1)
end
elseif key == "p" then
if history_index > 1 then
history_index = history_index - 1
command = data.history[history_path].table[history_index]
cur_pos = #command + 2
end
elseif key == "n" then
if history_index < history_items(history_path) then
history_index = history_index + 1
command = data.history[history_path].table[history_index]
cur_pos = #command + 2
elseif history_index == history_items(history_path) then
history_index = history_index + 1
command = ""
cur_pos = 1
end
elseif key == "e" then
cur_pos = #command + 1
elseif key == "r" then
search_term = search_term or command:sub(1, cur_pos - 1)
for i,v in (function(a,i) return itera(-1,a,i) end), data.history[history_path].table, history_index do
if v:find(search_term,1,true) ~= nil then
command=v
history_index=i
cur_pos=#command+1
break
end
end
elseif key == "s" then
search_term = search_term or command:sub(1, cur_pos - 1)
for i,v in (function(a,i) return itera(1,a,i) end), data.history[history_path].table, history_index do
if v:find(search_term,1,true) ~= nil then
command=v
history_index=i
cur_pos=#command+1
break
end
end
elseif key == "f" then
if cur_pos <= #command then
cur_pos = cur_pos + 1
end
elseif key == "h" then
if cur_pos > 1 then
command = command:sub(1, cur_pos - 2) .. command:sub(cur_pos)
cur_pos = cur_pos - 1
end
elseif key == "k" then
command = command:sub(1, cur_pos - 1)
elseif key == "u" then
command = command:sub(cur_pos, #command)
cur_pos = 1
elseif key == "Up" then
search_term = command:sub(1, cur_pos - 1) or ""
for i,v in (function(a,i) return itera(-1,a,i) end), data.history[history_path].table, history_index do
if v:find(search_term,1,true) == 1 then
command=v
history_index=i
break
end
end
elseif key == "Down" then
search_term = command:sub(1, cur_pos - 1) or ""
for i,v in (function(a,i) return itera(1,a,i) end), data.history[history_path].table, history_index do
if v:find(search_term,1,true) == 1 then
command=v
history_index=i
break
end
end
elseif key == "w" or key == "BackSpace" then
local wstart = 1
local wend = 1
local cword_start = 1
local cword_end = 1
while wend < cur_pos do
wend = command:find("[{[(,.:;_-+=@/ ]", wstart)
if not wend then wend = #command + 1 end
if cur_pos >= wstart and cur_pos <= wend + 1 then
cword_start = wstart
cword_end = cur_pos - 1
break
end
wstart = wend + 1
end
command = command:sub(1, cword_start - 1) .. command:sub(cword_end + 1)
cur_pos = cword_start
elseif key == "Delete" then
-- delete from history only if:
-- we are not dealing with a new command
-- the user has not edited an existing entry
if command == data.history[history_path].table[history_index] then
table.remove(data.history[history_path].table, history_index)
if history_index <= history_items(history_path) then
command = data.history[history_path].table[history_index]
cur_pos = #command + 2
elseif history_index > 1 then
history_index = history_index - 1
command = data.history[history_path].table[history_index]
cur_pos = #command + 2
else
command = ""
cur_pos = 1
end
end
end
elseif mod.Mod1 or mod.Mod3 then
if key == "b" then
cur_pos = cword_start(command, cur_pos)
elseif key == "f" then
cur_pos = cword_end(command, cur_pos)
elseif key == "d" then
command = command:sub(1, cur_pos - 1) .. command:sub(cword_end(command, cur_pos))
elseif key == "BackSpace" then
wstart = cword_start(command, cur_pos)
command = command:sub(1, wstart - 1) .. command:sub(cur_pos)
cur_pos = wstart
end
else
if completion_callback then
if key == "Tab" or key == "ISO_Left_Tab" then
if key == "ISO_Left_Tab" then
if ncomp == 1 then return end
if ncomp == 2 then
command = command_before_comp
textbox:set_font(font)
textbox:set_markup(prompt_text_with_cursor{
text = command_before_comp, text_color = inv_col, cursor_color = cur_col,
cursor_pos = cur_pos, cursor_ul = cur_ul, selectall = selectall,
prompt = prettyprompt })
return
end
ncomp = ncomp - 2
elseif ncomp == 1 then
command_before_comp = command
cur_pos_before_comp = cur_pos
end
local matches
command, cur_pos, matches = completion_callback(command_before_comp, cur_pos_before_comp, ncomp)
ncomp = ncomp + 1
key = ""
-- execute if only one match found and autoexec flag set
if matches and #matches == 1 and args.autoexec then
exec()
return
end
else
ncomp = 1
end
end
-- Typin cases
if mod.Shift and key == "Insert" then
local selection = capi.selection()
if selection then
-- Remove \n
local n = selection:find("\n")
if n then
selection = selection:sub(1, n - 1)
end
command = command:sub(1, cur_pos - 1) .. selection .. command:sub(cur_pos)
cur_pos = cur_pos + #selection
end
elseif key == "Home" then
cur_pos = 1
elseif key == "End" then
cur_pos = #command + 1
elseif key == "BackSpace" then
if cur_pos > 1 then
command = command:sub(1, cur_pos - 2) .. command:sub(cur_pos)
cur_pos = cur_pos - 1
end
elseif key == "Delete" then
command = command:sub(1, cur_pos - 1) .. command:sub(cur_pos + 1)
elseif key == "Left" then
cur_pos = cur_pos - 1
elseif key == "Right" then
cur_pos = cur_pos + 1
elseif key == "Up" then
if history_index > 1 then
history_index = history_index - 1
command = data.history[history_path].table[history_index]
cur_pos = #command + 2
end
elseif key == "Down" then
if history_index < history_items(history_path) then
history_index = history_index + 1
command = data.history[history_path].table[history_index]
cur_pos = #command + 2
elseif history_index == history_items(history_path) then
history_index = history_index + 1
command = ""
cur_pos = 1
end
else
-- wlen() is UTF-8 aware but #key is not,
-- so check that we have one UTF-8 char but advance the cursor of # position
if key:wlen() == 1 then
if selectall then command = "" end
command = command:sub(1, cur_pos - 1) .. key .. command:sub(cur_pos)
cur_pos = cur_pos + #key
end
end
if cur_pos < 1 then
cur_pos = 1
elseif cur_pos > #command + 1 then
cur_pos = #command + 1
end
selectall = nil
end
local success = pcall(update)
while not success do
-- TODO UGLY HACK TODO
-- Setting the text failed. Most likely reason is that the user
-- entered a multibyte character and pressed backspace which only
-- removed the last byte. Let's remove another byte.
if cur_pos <= 1 then
-- No text left?!
break
end
command = command:sub(1, cur_pos - 2) .. command:sub(cur_pos)
cur_pos = cur_pos - 1
success = pcall(update)
end
if changed_callback then
changed_callback(command)
end
end)
end
return prompt
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
Dual-Boxing/Jamba | Modules/Jamba-Talk/JambaTalk.lua | 1 | 29121 | --[[
Jamba - Jafula's Awesome Multi-Boxer Assistant
Copyright 2008 - 2015 Michael "Jafula" Miller
License: The MIT License
]]--
-- Create the addon using AceAddon-3.0 and embed some libraries.
local AJM = LibStub( "AceAddon-3.0" ):NewAddon(
"JambaTalk",
"JambaModule-1.0",
"AceConsole-3.0",
"AceEvent-3.0",
"AceHook-3.0"
)
-- Load libraries.
local JambaUtilities = LibStub:GetLibrary( "JambaUtilities-1.0" )
local JambaHelperSettings = LibStub:GetLibrary( "JambaHelperSettings-1.0" )
-- Constants and Locale for this module.
AJM.moduleName = "Jamba-Talk"
AJM.settingsDatabaseName = "JambaTalkProfileDB"
AJM.chatCommand = "jamba-talk"
local L = LibStub( "AceLocale-3.0" ):GetLocale( AJM.moduleName )
AJM.parentDisplayName = L["Chat"]
AJM.moduleDisplayName = L["Talk"]
-- Settings - the values to store and their defaults for the settings database.
AJM.settings = {
profile = {
forwardWhispers = true,
doNotForwardRealIdWhispers = true,
forwardViaWhisper = false,
fakeWhisper = true,
fakeInjectSenderToReplyQueue = true,
fakeInjectOriginatorToReplyQueue = false,
fakeWhisperCompact = false,
whisperMessageArea = "ChatFrame1",
enableChatSnippets = false,
chatSnippets = {},
},
}
-- Configuration.
function AJM:GetConfiguration()
local configuration = {
name = AJM.moduleDisplayName,
handler = AJM,
type = 'group',
childGroups = "tab",
get = "JambaConfigurationGetSetting",
set = "JambaConfigurationSetSetting",
args = {
push = {
type = "input",
name = L["Push Settings"],
desc = L["Push the talk settings to all characters in the team."],
usage = "/jamba-talk push",
get = false,
set = "JambaSendSettings",
},
},
}
return configuration
end
-------------------------------------------------------------------------------------------------------------
-- Command this module sends.
-------------------------------------------------------------------------------------------------------------
AJM.COMMAND_MESSAGE = "JambaTalkMessage"
-------------------------------------------------------------------------------------------------------------
-- Messages module sends.
-------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------
-- Talk Management.
-------------------------------------------------------------------------------------------------------------
function AJM:UpdateChatFrameList()
JambaUtilities:ClearTable( AJM.chatFrameList )
for index = 1, NUM_CHAT_WINDOWS do
local name, fontSize, r, g, b, alpha, shown, locked, docked, uninteractable = GetChatWindowInfo( index )
if (shown == 1) or (docked ~= nil) then
AJM.chatFrameList["ChatFrame"..index] = name
end
end
table.sort( AJM.chatFrameList )
end
function AJM:BeforeJambaProfileChanged()
end
function AJM:OnJambaProfileChanged()
AJM:SettingsRefresh()
end
function AJM:SettingsRefresh()
-- Set values.
AJM.settingsControl.checkBoxForwardWhispers:SetValue( AJM.db.forwardWhispers )
AJM.settingsControl.checkBoxDoNotForwardRealIdWhispers:SetValue( AJM.db.doNotForwardRealIdWhispers )
AJM.settingsControl.checkBoxForwardViaWhisper:SetValue( AJM.db.forwardViaWhisper )
AJM.settingsControl.checkBoxFakeWhispers:SetValue( AJM.db.fakeWhisper )
AJM.settingsControl.checkBoxFakeInjectSenderToReplyQueue:SetValue( AJM.db.fakeInjectSenderToReplyQueue )
AJM.settingsControl.checkBoxFakeInjectOriginatorToReplyQueue:SetValue( AJM.db.fakeInjectOriginatorToReplyQueue )
AJM.settingsControl.checkBoxFakeWhisperCompact:SetValue( AJM.db.fakeWhisperCompact )
AJM.settingsControl.checkBoxEnableChatSnippets:SetValue( AJM.db.enableChatSnippets )
AJM.settingsControl.dropdownMessageArea:SetValue( AJM.db.whisperMessageArea )
-- Set state.
AJM.settingsControl.checkBoxFakeInjectSenderToReplyQueue:SetDisabled( not AJM.db.fakeWhisper )
AJM.settingsControl.checkBoxFakeInjectOriginatorToReplyQueue:SetDisabled( not AJM.db.fakeWhisper )
AJM.settingsControl.checkBoxFakeWhisperCompact:SetDisabled( not AJM.db.fakeWhisper )
AJM.settingsControl.dropdownMessageArea:SetDisabled( not AJM.db.fakeWhisper )
AJM.settingsControl.buttonRefreshChatList:SetDisabled( not AJM.db.fakeWhisper )
AJM.settingsControl.buttonRemove:SetDisabled( not AJM.db.enableChatSnippets )
AJM.settingsControl.buttonAdd:SetDisabled( not AJM.db.enableChatSnippets )
AJM.settingsControl.multiEditBoxSnippet:SetDisabled( not AJM.db.enableChatSnippets )
AJM:SettingsScrollRefresh()
end
-- Settings received.
function AJM:JambaOnSettingsReceived( characterName, settings )
if characterName ~= AJM.characterName then
-- Update the settings.
AJM.db.forwardWhispers = settings.forwardWhispers
AJM.db.doNotForwardRealIdWhispers = settings.doNotForwardRealIdWhispers
AJM.db.fakeWhisper = settings.fakeWhisper
AJM.db.enableChatSnippets = settings.enableChatSnippets
AJM.db.whisperMessageArea = settings.whisperMessageArea
AJM.db.forwardViaWhisper = settings.forwardViaWhisper
AJM.db.fakeWhisperCompact = settings.fakeWhisperCompact
AJM.db.fakeInjectSenderToReplyQueue = settings.fakeInjectSenderToReplyQueue
AJM.db.fakeInjectOriginatorToReplyQueue = settings.fakeInjectOriginatorToReplyQueue
AJM.db.chatSnippets = JambaUtilities:CopyTable( settings.chatSnippets )
-- Refresh the settings.
AJM:SettingsRefresh()
-- Tell the player.
AJM:Print( L["Settings received from A."]( characterName ) )
end
end
-------------------------------------------------------------------------------------------------------------
-- Settings Dialogs.
-------------------------------------------------------------------------------------------------------------
local function SettingsCreateOptions( top )
-- Position and size constants.
local buttonControlWidth = 105
local checkBoxHeight = JambaHelperSettings:GetCheckBoxHeight()
local buttonHeight = JambaHelperSettings:GetButtonHeight()
local editBoxHeight = JambaHelperSettings:GetEditBoxHeight()
local dropdownHeight = JambaHelperSettings:GetDropdownHeight()
local left = JambaHelperSettings:LeftOfSettings()
local headingHeight = JambaHelperSettings:HeadingHeight()
local headingWidth = JambaHelperSettings:HeadingWidth( false )
local horizontalSpacing = JambaHelperSettings:GetHorizontalSpacing()
local verticalSpacing = JambaHelperSettings:GetVerticalSpacing()
local halfWidth = (headingWidth - horizontalSpacing) / 2
local left2 = left + halfWidth + horizontalSpacing
local indent = horizontalSpacing * 10
local movingTop = top
JambaHelperSettings:CreateHeading( AJM.settingsControl, L["Talk Options"], movingTop, false )
movingTop = movingTop - headingHeight
AJM.settingsControl.checkBoxForwardWhispers = JambaHelperSettings:CreateCheckBox(
AJM.settingsControl,
headingWidth,
left,
movingTop,
L["Forward Whispers To Master And Relay Back"],
AJM.SettingsToggleForwardWhispers
)
movingTop = movingTop - checkBoxHeight
AJM.settingsControl.checkBoxDoNotForwardRealIdWhispers = JambaHelperSettings:CreateCheckBox(
AJM.settingsControl,
headingWidth,
left,
movingTop,
L["Do Not Forward RealID Whispers"],
AJM.SettingsToggleDoNotForwardRealIdWhispers
)
movingTop = movingTop - checkBoxHeight
AJM.settingsControl.checkBoxForwardViaWhisper = JambaHelperSettings:CreateCheckBox(
AJM.settingsControl,
headingWidth,
left,
movingTop,
L["Forward Using Normal Whispers"],
AJM.SettingsToggleForwardViaWhisper
)
movingTop = movingTop - checkBoxHeight
AJM.settingsControl.checkBoxFakeWhispers = JambaHelperSettings:CreateCheckBox(
AJM.settingsControl,
headingWidth,
left,
movingTop,
L["Forward Via Fake Whispers For Clickable Links And Players"],
AJM.SettingsToggleFakeWhispers
)
movingTop = movingTop - checkBoxHeight
AJM.settingsControl.dropdownMessageArea = JambaHelperSettings:CreateDropdown(
AJM.settingsControl,
(headingWidth - indent) / 2,
left + indent,
movingTop,
L["Send Fake Whispers To"]
)
AJM.settingsControl.dropdownMessageArea:SetList( AJM.chatFrameList )
AJM.settingsControl.dropdownMessageArea:SetCallback( "OnValueChanged", AJM.SettingsSetMessageArea )
AJM.settingsControl.buttonRefreshChatList = JambaHelperSettings:CreateButton(
AJM.settingsControl,
buttonControlWidth,
left + indent + (headingWidth - indent) / 2 + horizontalSpacing,
movingTop - buttonHeight + 4,
L["Update"],
AJM.SettingsRefreshChatListClick
)
movingTop = movingTop - dropdownHeight - verticalSpacing
AJM.settingsControl.checkBoxFakeInjectSenderToReplyQueue = JambaHelperSettings:CreateCheckBox(
AJM.settingsControl,
headingWidth - indent,
left + indent,
movingTop,
L["Add Forwarder To Reply Queue On Master"],
AJM.SettingsToggleFakeInjectSenderToReplyQueue
)
movingTop = movingTop - checkBoxHeight
AJM.settingsControl.checkBoxFakeInjectOriginatorToReplyQueue = JambaHelperSettings:CreateCheckBox(
AJM.settingsControl,
headingWidth - indent,
left + indent,
movingTop,
L["Add Originator To Reply Queue On Master"],
AJM.SettingsToggleFakeInjectOriginatorToReplyQueue
)
movingTop = movingTop - checkBoxHeight
AJM.settingsControl.checkBoxFakeWhisperCompact = JambaHelperSettings:CreateCheckBox(
AJM.settingsControl,
headingWidth - indent,
left + indent,
movingTop,
L["Only Show Messages With Links"],
AJM.SettingsToggleFakeWhisperCompact
)
movingTop = movingTop - checkBoxHeight
JambaHelperSettings:CreateHeading( AJM.settingsControl, L["Chat Snippets"], movingTop, false )
movingTop = movingTop - headingHeight
AJM.settingsControl.checkBoxEnableChatSnippets = JambaHelperSettings:CreateCheckBox(
AJM.settingsControl,
headingWidth,
left,
movingTop,
L["Enable Chat Snippets"],
AJM.SettingsToggleChatSnippets
)
movingTop = movingTop - checkBoxHeight
AJM.settingsControl.highlightRow = 1
AJM.settingsControl.offset = 1
local list = {}
list.listFrameName = "JambaTalkChatSnippetsSettingsFrame"
list.parentFrame = AJM.settingsControl.widgetSettings.content
list.listTop = movingTop
list.listLeft = left
list.listWidth = headingWidth
list.rowHeight = 20
list.rowsToDisplay = 5
list.columnsToDisplay = 2
list.columnInformation = {}
list.columnInformation[1] = {}
list.columnInformation[1].width = 25
list.columnInformation[1].alignment = "LEFT"
list.columnInformation[2] = {}
list.columnInformation[2].width = 75
list.columnInformation[2].alignment = "LEFT"
list.scrollRefreshCallback = AJM.SettingsScrollRefresh
list.rowClickCallback = AJM.SettingsRowClick
AJM.settingsControl.list = list
JambaHelperSettings:CreateScrollList( AJM.settingsControl.list )
movingTop = movingTop - list.listHeight - verticalSpacing
AJM.settingsControl.buttonAdd = JambaHelperSettings:CreateButton(
AJM.settingsControl,
buttonControlWidth,
left,
movingTop,
L["Add"],
AJM.SettingsAddClick
)
AJM.settingsControl.buttonRemove = JambaHelperSettings:CreateButton(
AJM.settingsControl,
buttonControlWidth,
left + buttonControlWidth + horizontalSpacing,
movingTop,
L["Remove"],
AJM.SettingsRemoveClick
)
movingTop = movingTop - buttonHeight - verticalSpacing
AJM.settingsControl.multiEditBoxSnippet = JambaHelperSettings:CreateMultiEditBox(
AJM.settingsControl,
headingWidth,
left,
movingTop,
L["Snippet Text"],
5
)
AJM.settingsControl.multiEditBoxSnippet:SetCallback( "OnEnterPressed", AJM.SettingsMultiEditBoxChangedSnippet )
local multiEditBoxHeightSnippet = 110
movingTop = movingTop - multiEditBoxHeightSnippet
return movingTop
end
local function SettingsCreate()
AJM.settingsControl = {}
JambaHelperSettings:CreateSettings(
AJM.settingsControl,
AJM.moduleDisplayName,
AJM.parentDisplayName,
AJM.SettingsPushSettingsClick
)
local bottomOfSettings = SettingsCreateOptions( JambaHelperSettings:TopOfSettings() )
AJM.settingsControl.widgetSettings.content:SetHeight( -bottomOfSettings )
-- Help
local helpTable = {}
JambaHelperSettings:CreateHelp( AJM.settingsControl, helpTable, AJM:GetConfiguration() )
end
-------------------------------------------------------------------------------------------------------------
-- Settings Callbacks.
-------------------------------------------------------------------------------------------------------------
function AJM:SettingsScrollRefresh()
FauxScrollFrame_Update(
AJM.settingsControl.list.listScrollFrame,
AJM:GetItemsMaxPosition(),
AJM.settingsControl.list.rowsToDisplay,
AJM.settingsControl.list.rowHeight
)
AJM.settingsControl.offset = FauxScrollFrame_GetOffset( AJM.settingsControl.list.listScrollFrame )
for iterateDisplayRows = 1, AJM.settingsControl.list.rowsToDisplay do
-- Reset.
AJM.settingsControl.list.rows[iterateDisplayRows].columns[1].textString:SetText( "" )
AJM.settingsControl.list.rows[iterateDisplayRows].columns[1].textString:SetTextColor( 1.0, 1.0, 1.0, 1.0 )
AJM.settingsControl.list.rows[iterateDisplayRows].columns[2].textString:SetText( "" )
AJM.settingsControl.list.rows[iterateDisplayRows].columns[2].textString:SetTextColor( 1.0, 1.0, 1.0, 1.0 )
AJM.settingsControl.list.rows[iterateDisplayRows].highlight:SetTexture( 0.0, 0.0, 0.0, 0.0 )
-- Get data.
local dataRowNumber = iterateDisplayRows + AJM.settingsControl.offset
if dataRowNumber <= AJM:GetItemsMaxPosition() then
-- Put data information into columns.
local itemInformation = AJM:GetItemAtPosition( dataRowNumber )
AJM.settingsControl.list.rows[iterateDisplayRows].columns[1].textString:SetText( itemInformation.name )
AJM.settingsControl.list.rows[iterateDisplayRows].columns[2].textString:SetText( itemInformation.snippet )
-- Highlight the selected row.
if dataRowNumber == AJM.settingsControl.highlightRow then
AJM.settingsControl.list.rows[iterateDisplayRows].highlight:SetTexture( 1.0, 1.0, 0.0, 0.5 )
end
end
end
end
function AJM:SettingsRowClick( rowNumber, columnNumber )
if AJM.settingsControl.offset + rowNumber <= AJM:GetItemsMaxPosition() then
AJM.settingsControl.highlightRow = AJM.settingsControl.offset + rowNumber
local itemInformation = AJM:GetItemAtPosition( AJM.settingsControl.highlightRow )
if itemInformation ~= nil then
AJM.settingsControl.multiEditBoxSnippet:SetText( itemInformation.snippet )
end
AJM:SettingsScrollRefresh()
end
end
function AJM:SettingsPushSettingsClick( event )
AJM:JambaSendSettings()
end
function AJM:SettingsSetMessageArea( event, value )
AJM.db.whisperMessageArea = value
AJM:SettingsRefresh()
end
function AJM:SettingsToggleForwardWhispers( event, checked )
AJM.db.forwardWhispers = checked
AJM:SettingsRefresh()
end
function AJM:SettingsToggleDoNotForwardRealIdWhispers( event, checked )
AJM.db.doNotForwardRealIdWhispers = checked
AJM:SettingsRefresh()
end
function AJM:SettingsToggleFakeWhispers( event, checked )
AJM.db.fakeWhisper = checked
AJM:SettingsRefresh()
end
function AJM:SettingsToggleForwardViaWhisper( event, checked )
AJM.db.forwardViaWhisper = checked
AJM:SettingsRefresh()
end
function AJM:SettingsToggleFakeInjectSenderToReplyQueue( event, checked )
AJM.db.fakeInjectSenderToReplyQueue = checked
AJM:SettingsRefresh()
end
function AJM:SettingsToggleFakeInjectOriginatorToReplyQueue( event, checked )
AJM.db.fakeInjectOriginatorToReplyQueue = checked
AJM:SettingsRefresh()
end
function AJM:SettingsToggleFakeWhisperCompact( event, checked )
AJM.db.fakeWhisperCompact = checked
AJM:SettingsRefresh()
end
function AJM:SettingsToggleChatSnippets( event, checked )
AJM.db.enableChatSnippets = checked
AJM:SettingsRefresh()
end
function AJM:SettingsMultiEditBoxChangedSnippet( event, text )
local itemInformation = AJM:GetItemAtPosition( AJM.settingsControl.highlightRow )
if itemInformation ~= nil then
itemInformation.snippet = text
end
AJM:SettingsRefresh()
end
function AJM:SettingsRefreshChatListClick( event )
AJM:UPDATE_CHAT_WINDOWS()
end
function AJM:SettingsAddClick( event )
StaticPopup_Show( "JAMBATALK_ASK_SNIPPET" )
end
function AJM:SettingsRemoveClick( event )
StaticPopup_Show( "JAMBATALK_CONFIRM_REMOVE_CHAT_SNIPPET" )
end
-------------------------------------------------------------------------------------------------------------
-- Popup Dialogs.
-------------------------------------------------------------------------------------------------------------
-- Initialize Popup Dialogs.
local function InitializePopupDialogs()
StaticPopupDialogs["JAMBATALK_ASK_SNIPPET"] = {
text = L["Enter the shortcut text for this chat snippet:"],
button1 = ACCEPT,
button2 = CANCEL,
hasEditBox = 1,
timeout = 0,
whileDead = 1,
hideOnEscape = 1,
OnShow = function( self )
self.editBox:SetText("")
self.button1:Disable()
self.editBox:SetFocus()
end,
OnAccept = function( self )
AJM:AddItem( self.editBox:GetText() )
end,
EditBoxOnTextChanged = function( self )
if not self:GetText() or self:GetText():trim() == "" or self:GetText():find( "%W" ) ~= nil then
self:GetParent().button1:Disable()
else
self:GetParent().button1:Enable()
end
end,
EditBoxOnEnterPressed = function( self )
if self:GetParent().button1:IsEnabled() then
AJM:AddItem( self:GetText() )
end
self:GetParent():Hide()
end,
}
StaticPopupDialogs["JAMBATALK_CONFIRM_REMOVE_CHAT_SNIPPET"] = {
text = L["Are you sure you wish to remove the selected chat snippet?"],
button1 = YES,
button2 = NO,
timeout = 0,
whileDead = 1,
hideOnEscape = 1,
OnAccept = function( self )
AJM:RemoveItem()
end,
}
end
-------------------------------------------------------------------------------------------------------------
-- Addon initialization, enabling and disabling.
-------------------------------------------------------------------------------------------------------------
-- Initialise the module.
function AJM:OnInitialize()
AJM.chatFrameList = {}
AJM:UpdateChatFrameList()
-- Remember the last sender to whisper this character.
AJM.lastSender = nil
AJM.lastSenderIsReal = false
AJM.lastSenderRealID = nil
-- Create the settings control.
SettingsCreate()
-- Initialise the JambaModule part of this module.
AJM:JambaModuleInitialize( AJM.settingsControl.widgetSettings.frame )
-- Hook the SendChatMessage to translate any chat snippets.
AJM:RawHook( "SendChatMessage", true )
-- Initialise the popup dialogs.
InitializePopupDialogs()
-- Populate the settings.
AJM:SettingsRefresh()
AJM:SettingsRowClick( 1, 1 )
end
-- Called when the addon is enabled.
function AJM:OnEnable()
AJM:RegisterEvent( "CHAT_MSG_WHISPER" )
AJM:RegisterEvent( "CHAT_MSG_BN_WHISPER" )
AJM:RegisterEvent( "UPDATE_CHAT_WINDOWS" )
AJM:RegisterEvent( "UPDATE_FLOATING_CHAT_WINDOWS", "UPDATE_CHAT_WINDOWS" )
end
-- Called when the addon is disabled.
function AJM:OnDisable()
end
-------------------------------------------------------------------------------------------------------------
-- JambaTalk functionality.
-------------------------------------------------------------------------------------------------------------
function AJM:UPDATE_CHAT_WINDOWS()
AJM:UpdateChatFrameList()
AJM.settingsControl.dropdownMessageArea:SetList( AJM.chatFrameList )
if AJM.chatFrameList[AJM.db.whisperMessageArea] == nil then
AJM.db.whisperMessageArea = "ChatFrame1"
end
AJM.settingsControl.dropdownMessageArea:SetValue( AJM.db.whisperMessageArea )
end
function AJM:GetItemsMaxPosition()
return #AJM.db.chatSnippets
end
function AJM:GetItemAtPosition( position )
return AJM.db.chatSnippets[position]
end
function AJM:AddItem( name )
local itemInformation = {}
itemInformation.name = name
itemInformation.snippet = ""
table.insert( AJM.db.chatSnippets, itemInformation )
AJM:SettingsRefresh()
AJM:SettingsRowClick( 1, 1 )
end
function AJM:RemoveItem()
table.remove( AJM.db.chatSnippets, AJM.settingsControl.highlightRow )
AJM:SettingsRefresh()
AJM:SettingsRowClick( 1, 1 )
end
-- The SendChatMessage hook.
function AJM:SendChatMessage( ... )
local message, chatType, language, target = ...
if chatType == "WHISPER" then
-- Does this character have chat snippets enabled?
if AJM.db.enableChatSnippets == true then
local snippetName = select( 3, message:find( "^!(%w+)$" ) )
-- If a snippet name was found...
if snippetName then
-- Then look up the associated text.
local messageToSend = AJM:GetTextForSnippet( snippetName )
JambaApi.SendChatMessage( messageToSend, "WHISPER", target, JambaApi.COMMUNICATION_PRIORITY_BULK )
-- Finish with the chat message, i.e. do not let the original handler run.
return true
end
end
end
-- Call the orginal function.
return AJM.hooks["SendChatMessage"]( ... )
end
function AJM:CHAT_MSG_WHISPER( chatType, message, sender, language, channelName, target, flag, ... )
-- Does this character forward whispers?
if AJM.db.forwardWhispers == true then
-- Set a GM flag if this whisper was from a GM.
local isGM = false
if flag == L["GM"] then
isGM = true
end
-- Was the sender the master?
if JambaApi.IsCharacterTheMaster( sender ) == true then
-- Yes, relay the masters message to others.
AJM:ForwardWhisperFromMaster( message )
else
-- Not the master, forward the whisper to the master.
AJM:ForwardWhisperToMaster( message, sender, isGM, false, nil )
end
end
end
function AJM:CHAT_MSG_BN_WHISPER( event, message, sender, a, b, c, d, e, f, g, h, i, j, realFriendID, ... )
-- Does this character forward whispers?
if AJM.db.forwardWhispers == true and AJM.db.doNotForwardRealIdWhispers == false then
-- Is this character NOT the master?
if JambaApi.IsCharacterTheMaster( self.characterName ) == false then
-- Yes, not the master, relay the message to the master.
AJM:ForwardWhisperToMaster( message, sender, false, true, realFriendID )
end
end
end
local function ColourCodeLinks( message )
local realMessage = message
for link in message:gmatch( "|H.*|h" ) do
local realLink = ""
local startFind, endFind = message:find( "|Hitem", 1, true )
-- Is it an item link?
if startFind ~= nil then
-- Yes, is an item link.
local itemQuality = select( 3, GetItemInfo( link ) )
-- If the item is not in our cache, we cannot get the correct item quality / colour and the link will not work.
if itemQuality ~= nil then
realLink = select( 4, GetItemQualityColor( itemQuality ) )..link..FONT_COLOR_CODE_CLOSE
else
realLink = NORMAL_FONT_COLOR_CODE..link..FONT_COLOR_CODE_CLOSE
end
else
-- Not an item link.
-- GetFixedLink is in Blizzard's FrameXML/ItemRef.lua
-- It fixes, quest, achievement, talent, trade, enchant and instancelock links.
realLink = GetFixedLink( link )
end
realMessage = realMessage:replace( link, realLink )
end
return realMessage
end
local function DoesMessageHaveLink( message )
local startFind, endFind = message:find( "|H", 1, true )
return startFind ~= nil
end
local function BuildWhisperCharacterString( originalSender, viaCharacter )
local info = ChatTypeInfo["WHISPER"]
local colorString = format( "|cff%02x%02x%02x", info.r * 255, info.g * 255, info.b * 255 )
return format( "%s|Hplayer:%2$s|h[%2$s]|h%4$s|Hplayer:%3$s|h[%3$s]|h%5$s|r", colorString, originalSender, viaCharacter, L[" (via "], L[")"] )
end
function AJM:ForwardWhisperToMaster( message, sender, isGM, isReal, realFriendID )
-- Don't relay messages to the master or self (causes infinite loop, which causes disconnect).
if (JambaApi.IsCharacterTheMaster( AJM.characterName )) or (AJM.characterName == sender) then
return
end
-- Don't relay messages from the master either (not that this situation should happen).
if JambaApi.IsCharacterTheMaster( sender ) == true then
return
end
-- Build from whisper string, this cannot be a link as player links are not sent by whispers.
local fromCharacterWhisper = sender
if isReal == true then
-- Get the toon name of the character the RealID person is playing, Blizzard will not reveal player real names, so cannot send those.
fromCharacterWhisper = select( 5, BNGetFriendInfoByID( realFriendID ) )..L["(RealID)"]
--local presenceID, presenceName, battleTag, isBattleTagPresence, toonName, toonID, client, isOnline, lastOnline, isAFK, isDND, messageText = BNGetFriendInfoByID( realFriendID )
end
if isGM == true then
fromCharacterWhisper = fromCharacterWhisper..L["<GM>"]
end
-- Whisper the master.
if AJM.db.fakeWhisper == true then
local completeMessage = L[" whispers: "]..message
-- Send in compact format?
if AJM.db.fakeWhisperCompact == true then
-- Does the message contain a link?
if DoesMessageHaveLink( message ) == false then
-- No, don't display the message.
local info = ChatTypeInfo["WHISPER"]
local colorString = format( "|cff%02x%02x%02x", info.r * 255, info.g * 255, info.b * 255 )
completeMessage = L[" "]..colorString..L["whispered you."].."|r"
end
end
if isGM == true then
completeMessage = L[" "]..L["<GM>"]..L[" "]..completeMessage
end
local inject1 = nil
if AJM.db.fakeInjectSenderToReplyQueue == true then
inject1 = AJM.characterName
end
local inject2 = nil
if AJM.db.fakeInjectOriginatorToReplyQueue == true then
inject2 = sender
end
AJM:JambaSendCommandToMaster( AJM.COMMAND_MESSAGE, AJM.db.whisperMessageArea, sender, AJM.characterName, completeMessage, inject1, inject2 )
end
if AJM.db.forwardViaWhisper == true then
-- RealID messages do not wrap links in colour codes (text is always all blue), so wrap link in colour code
-- so normal whisper forwarding with link works.
if (isReal == true) and (DoesMessageHaveLink( message ) == true) then
message = ColourCodeLinks( message )
end
JambaApi.SendChatMessage( fromCharacterWhisper..": "..message, "WHISPER", JambaApi.GetMasterName(), JambaApi.COMMUNICATION_PRIORITY_BULK )
end
-- Remember this sender as the most recent sender.
AJM.lastSender = sender
AJM.lastSenderIsReal = isReal
AJM.lastSenderRealID = realFriendID
end
function AJM:ForwardWhisperFromMaster( messageFromMaster )
-- Who to send to and what to send?
-- Check the message to see if there is a character to whisper to; character name is preceeded by @.
-- No match will return nil for the parameters.
local sendTo, messageToInspect = select( 3, messageFromMaster:find( "^@(%w+)%s*(.*)$" ) )
-- If no sender found in message...
if not sendTo then
-- Then send to last sender.
sendTo = AJM.lastSender
-- Send the full message.
messageToInspect = messageFromMaster
end
-- Check to see if there is a snippet name in the message (text with a leading !).
local messageToSend = messageToInspect
if AJM.db.enableChatSnippets == true then
local snippetName = select( 3, messageToInspect:find( "^!(%w+)$" ) )
-- If a snippet name was found...
if snippetName then
-- Then look up the associated text.
messageToSend = AJM:GetTextForSnippet( snippetName )
end
end
-- If there is a valid character to send to...
if sendTo then
if messageToSend:trim() ~= "" then
-- Send the message.
if AJM.lastSenderIsReal == true and AJM.lastSenderRealID ~= nil then
BNSendWhisper( AJM.lastSenderRealID, messageToSend )
else
JambaApi.SendChatMessage( messageToSend, "WHISPER", sendTo, JambaApi.COMMUNICATION_PRIORITY_BULK )
end
end
-- Remember this sender as the most recent sender.
AJM.lastSender = sendTo
end
end
function AJM:GetTextForSnippet( snippetName )
local snippet = ""
for position, itemInformation in pairs( AJM.db.chatSnippets ) do
if itemInformation.name == snippetName then
snippet = itemInformation.snippet
break
end
end
return snippet
end
function AJM:ProcessReceivedMessage( sender, whisperMessageArea, orginator, forwarder, message, inject1, inject2 )
local chatTimestamp = ""
local info = ChatTypeInfo["WHISPER"]
local colorString = format( "|cff%02x%02x%02x", info.r * 255, info.g * 255, info.b * 255 )
if (CHAT_TIMESTAMP_FORMAT) then
chatTimestamp = colorString..BetterDate( CHAT_TIMESTAMP_FORMAT, time() ).."|r"
end
local fixedMessage = message
for embeddedColourString in message:gmatch( "|c.*|r" ) do
fixedMessage = fixedMessage:replace( embeddedColourString, "|r"..embeddedColourString..colorString )
end
fixedMessage = colorString..fixedMessage.."|r"
if string.sub( whisperMessageArea, 1, 9 ) ~= "ChatFrame" then
whisperMessageArea = "ChatFrame1"
end
_G[whisperMessageArea]:AddMessage( chatTimestamp..BuildWhisperCharacterString( orginator, forwarder )..fixedMessage )
if inject1 ~= nil then
ChatEdit_SetLastTellTarget( inject1, "WHISPER" )
end
if inject2 ~= nil then
ChatEdit_SetLastTellTarget( inject2, "WHISPER" )
end
end
-- A Jamba command has been recieved.
function AJM:JambaOnCommandReceived( characterName, commandName, ... )
if commandName == AJM.COMMAND_MESSAGE then
AJM:ProcessReceivedMessage( characterName, ... )
end
end | mit |
Phu1237/annot-player | lib/luaresolver/lua/luascript/sitelist/sina.lua | 5 | 2752 |
---[[by lostangel 20101117]]
---[[edit 20101117]]
--[[edit 20110314 for video tag]]
--[[edit lostangel 20110402 for subxml return struct]]
require "lalib"
--[[parse single sina url]]
function getTaskAttribute_sina ( str_url, str_tmpfile , pDlg)
if pDlg~=nil then
sShowMessage(pDlg, '¿ªÊ¼½âÎö..');
end
local int_acfpv = getACFPV ( str_url );
-------[[read flv id start]]
local re = dlFile(str_tmpfile, str_url);
if re~=0
then
if pDlg~=nil then
sShowMessage(pDlg, '¶ÁÈ¡ÔÊ¼Ò³Ãæ´íÎó¡£');
end
return;
else
if pDlg~=nil then
sShowMessage(pDlg, 'ÒѶÁÈ¡ÔÊ¼Ò³Ãæ£¬ÕýÔÚ·ÖÎö...');
end
end
--dbgMessage(pDlg, "dl ok");
local file = io.open(str_tmpfile, "r");
if file==nil
then
if pDlg~=nil then
sShowMessage(pDlg, '¶ÁÈ¡ÔÊ¼Ò³Ãæ´íÎó¡£');
end
return;
end
--readin descriptor
local str_line = readUntilFromUTF8(file, "<title>");
local str_title_line = readIntoUntilFromUTF8(file, str_line, "</title>");
local str_title = getMedText(str_title_line, "<title>", "</title>");
--dbgMessage(str_title);
--find embed flash
--str_line = readUntilFromUTF8(file, "<object type=\"application/x-shockwave-flash\" ");
--str_line = readUntilFromUTF8(file, "var video = {");
str_line = readUntilFromUTF8(file, "video : {");
local str_embed = readIntoUntilFromUTF8(file, str_line, "</script>"--[["</object>"]]);
print(str_embed);
if str_embed==nil then
if pDlg~=nil then
sShowMessage(pDlg, "ûÓÐÕÒµ½vid");
end
io.close(file);
return;
end
--dbgMessage(str_embed);
--read id
local str_id = "";
str_id = getMedText(str_embed, "vid :'", "',");
--dbgMessage(str_id);
--read id ok.close file
io.close(file);
if str_id == ""
then
if pDlg~=nil then
sShowMessage(pDlg, '½âÎöFLV ID´íÎó¡£');
end
return;
end
--dbgMessage(str_id);
------------------------------------------------------------[[read flv id end]]
--define subxmlurl
--local str_subxmlurl = "";
--str_subxmlurl = "http://danmaku.us/newflvplayer/xmldata/"..str_id.."/Comment_on.xml";
--realurls
local int_realurlnum = 0;
local tbl_realurls = {};
local tbl_durations = {};
--fetch dynamic url
int_realurlnum, tbl_realurls, tbl_durations = getRealUrls(str_id, str_tmpfile, pDlg);
if pDlg~=nil then
sShowMessage(pDlg, 'Íê³É½âÎö..');
end
local tbl_subxmlurls={};
local tbl_ta = {};
tbl_ta["acfpv"] = int_acfpv;
--tbl_ta["descriptor"] = "sina" .. str_id .. " - " .. str_title;
tbl_ta["descriptor"] = str_title;
tbl_ta["subxmlurl"] = tbl_subxmlurls;
tbl_ta["realurlnum"] = int_realurlnum;
tbl_ta["realurls"] = tbl_realurls;
tbl_ta["durations"] = tbl_durations;
tbl_ta["sizes"] = {};
tbl_ta["oriurl"] = str_url;
local tbl_resig = {};
tbl_resig[string.format("%d",0)] = tbl_ta;
return tbl_resig;
end
| gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Ifrits_Cauldron/npcs/Altar_of_Ashes.lua | 2 | 1912 | ----------------------------------
-- Area: Ifrit's Cauldron
-- NPC: Altar of Ashes
-- @pos: I-9 (X:16, Y:0, Z:-58)
-- Involved in Quest: Greetings to the Guardian
-----------------------------------
require("scripts/zones/Ifrits_Cauldron/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
Guardian = player:getQuestStatus(OUTLANDS,GREETINGS_TO_THE_GUARDIAN);
if(Guardian == QUEST_ACCEPTED and trade:hasItemQty(4596,1)) then
player:messageSpecial(ALTAR_OFFERING,0,4596);
player:setVar("PamamaVar",1); --Set variable to reflect first completion of quest
player:tradeComplete();
elseif(Guardian == QUEST_COMPLETED and trade:hasItemQty(4596,1)) then
player:messageSpecial(ALTAR_OFFERING,0,4596);
player:setVar("PamamaVar",2); --Set variable to reflect repeat of quest, not first time
player:tradeComplete();
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
Guardian = player:getQuestStatus(OUTLANDS,GREETINGS_TO_THE_GUARDIAN);
if(Guardian == QUEST_ACCEPTED and player:getVar("PamamaVar") == 1 or player:getVar("PamamaVar") == 2) then
player:messageSpecial(ALTAR_COMPLETED);
elseif(Guardian == QUEST_ACCEPTED and player:getVar("PamamaVar") == 0) then
player:messageSpecial(ALTAR_INSPECT);
else
player:messageSpecial(ALTAR_STANDARD);
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 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Aht_Urhgan_Whitegate/npcs/Tehf_Kimasnahya.lua | 4 | 2986 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Tehf Kimasnahya
-- Type: Standard NPC
-- @zone: 50
-- @pos: -89.897 -1 6.199
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local gotitall = player:getQuestStatus(AHT_URHGAN,GOT_IT_ALL);
local gotItAllProg = player:getVar("gotitallCS");
local threeMenProg = player:getVar("threemenandaclosetCS");
if(gotitall == QUEST_AVAILABLE) then
player:startEvent(0x0208);
elseif(gotItAllProg == 4) then
player:startEvent(0x020d);
elseif(gotItAllProg == 6) then
player:startEvent(0x020f);
elseif(gotItAllProg >= 7 and player:getVar("Wait1DayForgotitallCS_date") < os.time() and player:needToZone() == false) then
player:startEvent(0x0210);
elseif(gotItAllProg >= 7) then
player:startEvent(0x021b);
elseif(gotItAllProg >= 1 and gotItAllProg <= 3) then
player:startEvent(0x0209);
elseif(threeMenProg == 5) then
player:startEvent(0x034b);
elseif(threeMenProg == 6) then
player:startEvent(0x034c);
else
player:startEvent(0x0211);
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 == 0x0208)then
player:addQuest(AHT_URHGAN,GOT_IT_ALL);
player:setVar("gotitallCS",1);
elseif(csid == 0x020d and option == 0)then
player:setVar("gotitallCS",5);
player:delKeyItem(VIAL_OF_LUMINOUS_WATER);
elseif(csid == 0x020f)then
player:setVar("gotitallCS",7);
player:setVar("Wait1DayForgotitallCS_date", getMidnight());
player:needToZone(true);
elseif(csid == 0x021b)then
player:setVar("gotitallCS",8);
elseif(csid == 0x0210)then
if(player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18257);
else
player:setVar("Wait1DayForgotitallCS_date",0);
player:setVar("gotitallCS",0);
player:addItem(18257); -- Bibiki Seashell
player:messageSpecial(ITEM_OBTAINED,18257);
player:completeQuest(AHT_URHGAN,GOT_IT_ALL);
end
elseif(csid == 0x034b and option == 1)then
player:setVar("threemenandaclosetCS",6);
end
end;
| gpl-3.0 |
RavenX8/osIROSE-new | scripts/mobs/ai/dusk_crystal.lua | 2 | 1060 | registerNpc(433, {
walk_speed = 0,
run_speed = 0,
scale = 200,
r_weapon = 0,
l_weapon = 0,
level = 85,
hp = 400,
attack = 260,
hit = 300,
def = 330,
res = 430,
avoid = 80,
attack_spd = 130,
is_magic_damage = 0,
ai_type = 253,
give_exp = 0,
drop_type = 0,
drop_money = 0,
drop_item = 0,
union_number = 0,
need_summon_count = 0,
sell_tab0 = 0,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 800,
npc_type = 0,
hit_material_type = 2,
face_icon = 0,
summon_mob_type = 0,
quest_type = 0,
height = 0
});
function OnInit(entity)
return true
end
function OnCreate(entity)
return true
end
function OnDelete(entity)
return true
end
function OnDead(entity)
end
function OnDamaged(entity)
end | apache-2.0 |
Sonicrich05/FFXI-Server | scripts/zones/Windurst_Walls/Zone.lua | 28 | 2946 | -----------------------------------
--
-- Zone: Windurst_Walls (239)
--
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/zones/Windurst_Walls/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
zone:registerRegion(1, -2,-17,140, 2,-16,142);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
-- MOG HOUSE EXIT
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
position = math.random(1,5) - 123;
player:setPos(-257.5,-5.05,position,0);
if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then
cs = 0x7534;
end
player:setVar("PlayerMainJob",0);
elseif (ENABLE_ASA == 1 and player:getCurrentMission(ASA) == A_SHANTOTTO_ASCENSION
and (prevZone == 238 or prevZone == 241) and player:getMainLvl()>=10) then
cs = 0x01fe;
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)
switch (region:GetRegionID()): caseof
{
[1] = function (x) -- Heaven's Tower enter portal
player:startEvent(0x56);
end,
}
end;
-----------------------------------
-- onRegionLeave
-----------------------------------
function onRegionLeave(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x56) then
player:setPos(0,0,-22.40,192,242);
elseif (csid == 0x7534 and option == 0) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
elseif (csid == 0x01fe) then
player:startEvent(0x0202);
elseif (csid == 0x0202) then
player:completeMission(ASA,A_SHANTOTTO_ASCENSION);
player:addMission(ASA,BURGEONING_DREAD);
player:setVar("ASA_Status",0);
end
end; | gpl-3.0 |
projectbismark/luci-bismark | applications/luci-diag-devinfo/luasrc/controller/luci_diag/devinfo_common.lua | 14 | 5674 | --[[
Luci diag - Diagnostics controller module
(c) 2009 Daniel Dickinson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
module("luci.controller.luci_diag.devinfo_common", package.seeall)
require("luci.i18n")
require("luci.util")
require("luci.sys")
require("luci.cbi")
require("luci.model.uci")
local translate = luci.i18n.translate
local DummyValue = luci.cbi.DummyValue
local SimpleSection = luci.cbi.SimpleSection
function index()
return -- no-op
end
function run_processes(outnets, cmdfunc)
i = next(outnets, nil)
while (i) do
outnets[i]["output"] = luci.sys.exec(cmdfunc(outnets, i))
i = next(outnets, i)
end
end
function parse_output(devmap, outnets, haslink, type, mini, debug)
local curnet = next(outnets, nil)
luci.i18n.loadc("diag_devinfo")
while (curnet) do
local output = outnets[curnet]["output"]
local subnet = outnets[curnet]["subnet"]
local ports = outnets[curnet]["ports"]
local interface = outnets[curnet]["interface"]
local netdevs = {}
devlines = luci.util.split(output)
if not devlines then
devlines = {}
table.insert(devlines, output)
end
local j = nil
j = next(devlines, j)
local found_a_device = false
while (j) do
if devlines[j] and ( devlines[j] ~= "" ) then
found_a_device = true
local devtable
local row = {}
devtable = luci.util.split(devlines[j], ' | ')
row["ip"] = devtable[1]
if (not mini) then
row["mac"] = devtable[2]
end
if ( devtable[4] == 'unknown' ) then
row["vendor"] = devtable[3]
else
row["vendor"] = devtable[4]
end
row["type"] = devtable[5]
if (not mini) then
row["model"] = devtable[6]
end
if (haslink) then
row["config_page"] = devtable[7]
end
if (debug) then
row["raw"] = devlines[j]
end
table.insert(netdevs, row)
end
j = next(devlines, j)
end
if not found_a_device then
local row = {}
row["ip"] = curnet
if (not mini) then
row["mac"] = ""
end
if (type == "smap") then
row["vendor"] = luci.i18n.translate("No SIP devices")
else
row["vendor"] = luci.i18n.translate("No devices detected")
end
row["type"] = luci.i18n.translate("check other networks")
if (not mini) then
row["model"] = ""
end
if (haslink) then
row["config_page"] = ""
end
if (debug) then
row["raw"] = output
end
table.insert(netdevs, row)
end
local s
if (type == "smap") then
if (mini) then
s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("SIP devices discovered for") .. " " .. curnet)
else
local interfacestring = ""
if ( interface ~= "" ) then
interfacestring = ", " .. interface
end
s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("SIP devices discovered for") .. " " .. curnet .. " (" .. subnet .. ":" .. ports .. interfacestring .. ")")
end
s.template = "diag/smapsection"
else
if (mini) then
s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("Devices discovered for") .. " " .. curnet)
else
local interfacestring = ""
if ( interface ~= "" ) then
interfacestring = ", " .. interface
end
s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("Devices discovered for") .. " " .. curnet .. " (" .. subnet .. interfacestring .. ")")
end
end
s:option(DummyValue, "ip", translate("IP Address"))
if (not mini) then
s:option(DummyValue, "mac", translate("MAC Address"))
end
s:option(DummyValue, "vendor", translate("Vendor"))
s:option(DummyValue, "type", translate("Device Type"))
if (not mini) then
s:option(DummyValue, "model", translate("Model"))
end
if (haslink) then
s:option(DummyValue, "config_page", translate("Link to Device"))
end
if (debug) then
s:option(DummyValue, "raw", translate("Raw"))
end
curnet = next(outnets, curnet)
end
end
function get_network_device(interface)
local state = luci.model.uci.cursor_state()
state:load("network")
local dev
return state:get("network", interface, "ifname")
end
function cbi_add_networks(field)
uci.cursor():foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
field:value(section[".name"])
end
end
)
field.titleref = luci.dispatcher.build_url("admin", "network", "network")
end
function config_devinfo_scan(map, scannet)
local o
o = scannet:option(luci.cbi.Flag, "enable", translate("Enable"))
o.optional = false
o.rmempty = false
o = scannet:option(luci.cbi.Value, "interface", translate("Interface"))
o.optional = false
luci.controller.luci_diag.devinfo_common.cbi_add_networks(o)
local scansubnet
scansubnet = scannet:option(luci.cbi.Value, "subnet", translate("Subnet"))
scansubnet.optional = false
o = scannet:option(luci.cbi.Value, "timeout", translate("Timeout"), translate("Time to wait for responses in seconds (default 10)"))
o.optional = true
o = scannet:option(luci.cbi.Value, "repeat_count", translate("Repeat Count"), translate("Number of times to send requests (default 1)"))
o.optional = true
o = scannet:option(luci.cbi.Value, "sleepreq", translate("Sleep Between Requests"), translate("Milliseconds to sleep between requests (default 100)"))
o.optional = true
end
| apache-2.0 |
SnakeSVx/spacebuild | lua/includes/modules/hashmap.lua | 5 | 7305 | --=============================================================================--
-- Addon: CAF
-- Author: SnakeSVx
-- Version: 0.1
--
-- A really simple module to allow the creation of Java like HashMaps
--
--=============================================================================--
local table = table
local setmetatable = setmetatable
local type = type
local tostring = tostring
local ErrorNoHalt = ErrorNoHalt
local IsValid = IsValid
local pairs = pairs
module( "HashMap" )
local list = {}
list.__index = list
--[[
Possible Types to check
- All default checktypes (number, string, vector, table, colour, nil, angle)
- ent (Entities, includes players, vehicles, weapons, NPC's)
- entonly (players, vehicles, weapons and npc's not allowed)
- npc (NPC's)
- player (players)
- vehicle (vehicles)
- weapon (weapons)
]]
--[[
Create ( type , isfunc)
type is optional, if a type is given this will be checked against the item before adding it to the internal Table
isfunc is option, needs to be true if type is custom function
This will set up the new ArrayList
]]
function list:Create( thetype, isfunc, thetype2, isfunc2 )
self:SetCheckType(thetype, isfunc, thetype2, isfunc2)
self.table = {}
end
--[[
SetCheckType( type, isfunc, type2, isfunc2)
type is optional, if no type is given, the checking will be disabled
isfunc is option, needs to be true if thetype is custom function
Sets the type to check the item for (won't check the old values in the table !!!)
]]
function list:SetCheckType(thetype, isfunc, thetype2, isfunc2)
if thetype and isfunc then
self.hasKeyType = true
self.keytype = nil
self.customKeyCheck = true
self.func = thetype
elseif thetype and type(thetype) == "string" then
self.hasKeyType = true
self.keytype = thetype
else
self.hasKeyType = false
self.keytype = nil
end
if thetype2 and isfunc then
self.hasValueType = true
self.valuetype = nil
self.customValueCheck = true
self.valuefunc = thetype2
elseif thetype2 and type(thetype2) == "string" then
self.hasValueType = true
self.valuetype = thetype2
else
self.hasValueType = false
self.valuetype = nil
end
end
--[[
CheckType ( item )
item is required,, this is the item you want to check
This function will return true if this item is allowed into the ArrayList, false otherwise
]]
function list:CheckKeyType( item )
if self.hasKeyType then
if self.customKeyCheck then
local ok, err = pcall(self.keyfunc, item)
if not ok then
return false, err
else
return err
end
elseif type(item) == self.keytype then
return true
else
if self.keytype == "ent" then
return IsValid(item)
elseif self.keytype == "player" then
return IsValid(item) and item:IsPlayer()
elseif self.keytype == "vehicle" then
return IsValid(item) and item:IsVehicle()
elseif self.keytype == "npc" then
return IsValid(item) and item:IsNPC()
elseif self.keytype == "weapon" then
return IsValid(item) and item:IsWeapon()
elseif self.keytype == "entonly" then
return IsValid(item) and not item:IsPlayer() and not item:IsVehicle() and not item:IsNPC() and not item:IsWeapon()
end
end
return false
end
return true
end
function list:CheckValueType( item )
if self.hasValueType then
if self.customValueCheck then
local ok, err = pcall(self.valuefunc, item)
if not ok then
return false, err
else
return err
end
elseif type(item) == self.valuetype then
return true
else
if self.valuetype == "ent" then
return IsValid(item)
elseif self.valuetype == "player" then
return IsValid(item) and item:IsPlayer()
elseif self.valuetype == "vehicle" then
return IsValid(item) and item:IsVehicle()
elseif self.valuetype == "npc" then
return IsValid(item) and item:IsNPC()
elseif self.valuetype == "weapon" then
return IsValid(item) and item:IsWeapon()
elseif self.valuetype == "entonly" then
return IsValid(item) and not item:IsPlayer() and not item:IsVehicle() and not item:IsNPC() and not item:IsWeapon()
end
end
return false
end
return true
end
--[[
Clear()
This will clear the inner table
]]
function list:Clear()
self.table = {}
end
--[[
ContainsValue(item)
Item is required
Returns true/false
]]
function list:ContainsValue( item )
return table.HasValue(self.table, item)
end
--[[
ContainsKey(key)
key is required
Returns true/false
]]
function list:ContainsKey( key )
return self.table[key]
end
--[[
Get( index)
Index is a number and is required
returns the Item at this index or nil
]]
function list:Get( index )
return self.table[index]
end
--[[
IsEmpty()
Returns true/false
]]
function list:IsEmpty()
return table.Count(self.table) == 0
end
--[[
KeySet()
Returns a table with all the keys in it
]]
function list:KeySet()
local tmp = {}
if not self:IsEmpty() then
for k, v in pairs(self.table) do
table.insert(tmp, k)
end
end
return tmp
end
--[[
Put( key, item )
item is required, the item you want to add
key is required
This functions will try to add the given item to the HashMap, returns true if succesfull
]]
function list:Put( key, item )
local ok = (self:CheckKeyType( key ) and self:CheckValueType( item ))
if ok then
self.table[key] = item
end
return ok
end
--[[
Putall(Table)
Table is required
This functions will try to add the given items to the ArrayList, returns true if succesfull
Existing values will be overriden if a matching key is in the to add table
]]
function list:PutAll( htable )
local ok = true
local amount = 0
for k, v in pairs(htable) do
if not self:Put(k, v) then
ok = false
amount = amount + 1
end
end
return ok, tostring(amount).."was the wrong type"
end
--[[
GetCheckType()
Returns the current type this Table checks for
]]
function list:GetKeyCheckType()
if self.customKeyCheck then
return true, self.keyfunc
end
return false, self.keytype
end
--[[
GetCheckType()
Returns the current type this Table checks for
]]
function list:GetValueCheckType()
if self.customValueCheck then
return true, self.valuefunc
end
return false, self.valuetype
end
--[[
Remove(key)
The key of the to item to remove
Removes the item at the specified key
]]
function list:Remove( key )
self.table[key] = nil
end
--[[
Size()
Returns the size of the ArrayList
]]
function list:Size()
return table.Count(self.table)
end
--[[
Values()
Returns all of the values in a table
]]
function list:Values()
local tmp = {}
if not self:IsEmpty() then
for k,v in pairs(self.table) do
table.insert(tmp, v)
end
end
return tmp
end
--[[
ToTable()
Returns a copy of the the inner table
]]
function list:ToTable()
local tab = {}
if not self:IsEmpty() then
tab = table.Copy(self.table)
end
return tab
end
---------------------------------------------------------
--[[
HashMap.Create( type, isfunc)
Call this to create a new HashMap type(s) is optional
isfunc is option, needs to be true if type is custom function
Returns the new HashMap object
]]
function Create( thetype, isfunc, thetype2, isfunc2 )
tmp = {}
setmetatable( tmp, list )
tmp:Create(thetype, isfunc, thetype2, isfunc2 )
return tmp
end
| apache-2.0 |
Servius/tfa-sw-weapons-repository | Live Addons/servius_uploader/[TFA] Extended Pack/lua/weapons/tfa_e11_extended/shared.lua | 1 | 4646 | if ( SERVER ) then
AddCSLuaFile( "shared.lua" )
end
if ( CLIENT ) then
SWEP.PrintName = "E-11"
SWEP.Author = "TFA, Servius"
SWEP.ViewModelFOV = 60
SWEP.Slot = 2
SWEP.SlotPos = 3
--SWEP.WepSelectIcon = surface.GetTextureID("HUD/killicons/DC15A")
--killicon.Add( "weapon_752_dc15a", "HUD/killicons/DC15A", Color( 255, 80, 0, 255 ) )
end
SWEP.Base = "tfa_3dscoped_base"
SWEP.Category = "TFA Star Wars"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.HoldType = "ar2"
SWEP.ViewModelFOV = 60
SWEP.ViewModelFlip = false
SWEP.ViewModel = "models/weapons/synbf3/c_e11.mdl"
SWEP.WorldModel = "models/weapons/synbf3/w_e11.mdl"
SWEP.ShowViewModel = true
SWEP.ShowWorldModel = true
SWEP.UseHands = true
SWEP.Primary.Sound = Sound ("weapons/e11/e11_fire.ogg");
SWEP.Primary.ReloadSound = Sound ("weapons/shared/battlefront_standard_reload.ogg");
SWEP.Weight = 5
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
SWEP.Primary.Recoil = 0.5
SWEP.Primary.Damage = 50
SWEP.Primary.NumShots = 1
-- Selective Fire Stuff
SWEP.SelectiveFire = true --Allow selecting your firemode?
SWEP.DisableBurstFire = false --Only auto/single?
SWEP.OnlyBurstFire = false --No auto, only burst/single?
SWEP.DefaultFireMode = "" --Default to auto or whatev
SWEP.FireModeName = nil --Change to a text value to override it
SWEP.Primary.Spread = 0.0125
SWEP.Primary.IronAccuracy = .002 -- Ironsight accuracy, should be the same for shotguns
SWEP.Primary.SpreadMultiplierMax = 2 --How far the spread can expand when you shoot.
--Range Related
SWEP.Primary.Range = -1 -- The distance the bullet can travel in source units. Set to -1 to autodetect based on damage/rpm.
SWEP.Primary.RangeFalloff = -1 -- The percentage of the range the bullet damage starts to fall off at. Set to 0.8, for example, to start falling off after 80% of the range.
--Penetration Related
SWEP.MaxPenetrationCounter = 1 --The maximum number of ricochets. To prevent stack overflows.
SWEP.Primary.ClipSize = 45
SWEP.Primary.RPM = 300
SWEP.Primary.DefaultClip = 150
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = "ar2"
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.Secondary.IronFOV = 70
SWEP.IronSightsPos = Vector(-3.221, -0, 2.559)
SWEP.IronSightsAng = Vector(0, 0, 0)
SWEP.VElements = {
["element_scope"] = { type = "Model", model = "models/rtcircle.mdl", bone = "v_e11_reference001", rel = "", pos = Vector(-1.25, -3.4, 4.65), angle = Angle(0, 90, 0), size = Vector(0.35, 0.35, 0.35), color = Color(255, 255, 255, 255), surpresslightning = false, material = "!tfa_rtmaterial", skin = 0, bodygroup = {} }
}
SWEP.WElements = {
["element_scope"] = { type = "Model", model = "models/rtcircle.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(-1.201, 1.6, -5.45), angle = Angle(165, 0, 0), size = Vector(0.349, 0.349, 0.349), color = Color(255, 255, 255, 255), surpresslightning = false, material = "!tfa_rtmaterial", skin = 0, bodygroup = {} }
}
SWEP.BlowbackVector = Vector(0,-3,0.025)
SWEP.Blowback_Only_Iron = false
SWEP.DoProceduralReload = false
SWEP.ProceduralReloadTime = 2.5
----Swft Base Code
SWEP.TracerCount = 1
SWEP.MuzzleFlashEffect = ""
SWEP.TracerName = "rw_sw_laser_red"
SWEP.Secondary.IronFOV = 70
SWEP.Primary.KickUp = 0.2
SWEP.Primary.KickDown = 0.1
SWEP.Primary.KickHorizontal = 0.1
SWEP.Primary.KickRight = 0.1
SWEP.DisableChambering = true
SWEP.ImpactDecal = "FadingScorch"
SWEP.ImpactEffect = "effect_sw_impact" --Impact Effect
SWEP.RunSightsPos = Vector(2.127, 0, 1.355)
SWEP.RunSightsAng = Vector(-15.775, 10.023, -5.664)
SWEP.BlowbackEnabled = true
SWEP.BlowbackVector = Vector(0,-3,0.1)
SWEP.Blowback_Shell_Enabled = false
SWEP.Blowback_Shell_Effect = ""
SWEP.ThirdPersonReloadDisable=false
SWEP.Primary.DamageType = DMG_SHOCK
SWEP.DamageType = DMG_SHOCK
--3dScopedBase stuff
SWEP.RTMaterialOverride = -1
SWEP.RTScopeAttachment = -1
SWEP.Scoped_3D = true
SWEP.ScopeReticule = "scope/gdcw_red_nobar"
SWEP.Secondary.ScopeZoom = 8
SWEP.ScopeReticule_Scale = {2.5,2.5}
SWEP.Secondary.UseACOG = false --Overlay option
SWEP.Secondary.UseMilDot = false --Overlay option
SWEP.Secondary.UseSVD = false --Overlay option
SWEP.Secondary.UseParabolic = false --Overlay option
SWEP.Secondary.UseElcan = false --Overlay option
SWEP.Secondary.UseGreenDuplex = false --Overlay option
if surface then
SWEP.Secondary.ScopeTable = nil --[[
{
scopetex = surface.GetTextureID("scope/gdcw_closedsight"),
reticletex = surface.GetTextureID("scope/gdcw_acogchevron"),
dottex = surface.GetTextureID("scope/gdcw_acogcross")
}
]]--
end
DEFINE_BASECLASS( SWEP.Base ) | apache-2.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Windurst_Waters_[S]/npcs/Kristen.lua | 4 | 1042 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Kristen
-- Type: Standard NPC
-- @zone: 94
-- @pos: 2.195 -2 60.296
--
-- 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(0x0194);
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 |
nrodriguez/SpellGainz | libs/AceGUI-3.0/widgets/AceGUIContainer-Window.lua | 52 | 9726 | local AceGUI = LibStub("AceGUI-3.0")
-- Lua APIs
local pairs, assert, type = pairs, assert, type
-- WoW APIs
local PlaySound = PlaySound
local CreateFrame, UIParent = CreateFrame, UIParent
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: GameFontNormal
----------------
-- Main Frame --
----------------
--[[
Events :
OnClose
]]
do
local Type = "Window"
local Version = 4
local function frameOnClose(this)
this.obj:Fire("OnClose")
end
local function closeOnClick(this)
PlaySound("gsTitleOptionExit")
this.obj:Hide()
end
local function frameOnMouseDown(this)
AceGUI:ClearFocus()
end
local function titleOnMouseDown(this)
this:GetParent():StartMoving()
AceGUI:ClearFocus()
end
local function frameOnMouseUp(this)
local frame = this:GetParent()
frame:StopMovingOrSizing()
local self = frame.obj
local status = self.status or self.localstatus
status.width = frame:GetWidth()
status.height = frame:GetHeight()
status.top = frame:GetTop()
status.left = frame:GetLeft()
end
local function sizerseOnMouseDown(this)
this:GetParent():StartSizing("BOTTOMRIGHT")
AceGUI:ClearFocus()
end
local function sizersOnMouseDown(this)
this:GetParent():StartSizing("BOTTOM")
AceGUI:ClearFocus()
end
local function sizereOnMouseDown(this)
this:GetParent():StartSizing("RIGHT")
AceGUI:ClearFocus()
end
local function sizerOnMouseUp(this)
this:GetParent():StopMovingOrSizing()
end
local function SetTitle(self,title)
self.titletext:SetText(title)
end
local function SetStatusText(self,text)
-- self.statustext:SetText(text)
end
local function Hide(self)
self.frame:Hide()
end
local function Show(self)
self.frame:Show()
end
local function OnAcquire(self)
self.frame:SetParent(UIParent)
self.frame:SetFrameStrata("FULLSCREEN_DIALOG")
self:ApplyStatus()
self:EnableResize(true)
self:Show()
end
local function OnRelease(self)
self.status = nil
for k in pairs(self.localstatus) do
self.localstatus[k] = nil
end
end
-- called to set an external table to store status in
local function SetStatusTable(self, status)
assert(type(status) == "table")
self.status = status
self:ApplyStatus()
end
local function ApplyStatus(self)
local status = self.status or self.localstatus
local frame = self.frame
self:SetWidth(status.width or 700)
self:SetHeight(status.height or 500)
if status.top and status.left then
frame:SetPoint("TOP",UIParent,"BOTTOM",0,status.top)
frame:SetPoint("LEFT",UIParent,"LEFT",status.left,0)
else
frame:SetPoint("CENTER",UIParent,"CENTER")
end
end
local function OnWidthSet(self, width)
local content = self.content
local contentwidth = width - 34
if contentwidth < 0 then
contentwidth = 0
end
content:SetWidth(contentwidth)
content.width = contentwidth
end
local function OnHeightSet(self, height)
local content = self.content
local contentheight = height - 57
if contentheight < 0 then
contentheight = 0
end
content:SetHeight(contentheight)
content.height = contentheight
end
local function EnableResize(self, state)
local func = state and "Show" or "Hide"
self.sizer_se[func](self.sizer_se)
self.sizer_s[func](self.sizer_s)
self.sizer_e[func](self.sizer_e)
end
local function Constructor()
local frame = CreateFrame("Frame",nil,UIParent)
local self = {}
self.type = "Window"
self.Hide = Hide
self.Show = Show
self.SetTitle = SetTitle
self.OnRelease = OnRelease
self.OnAcquire = OnAcquire
self.SetStatusText = SetStatusText
self.SetStatusTable = SetStatusTable
self.ApplyStatus = ApplyStatus
self.OnWidthSet = OnWidthSet
self.OnHeightSet = OnHeightSet
self.EnableResize = EnableResize
self.localstatus = {}
self.frame = frame
frame.obj = self
frame:SetWidth(700)
frame:SetHeight(500)
frame:SetPoint("CENTER",UIParent,"CENTER",0,0)
frame:EnableMouse()
frame:SetMovable(true)
frame:SetResizable(true)
frame:SetFrameStrata("FULLSCREEN_DIALOG")
frame:SetScript("OnMouseDown", frameOnMouseDown)
frame:SetScript("OnHide",frameOnClose)
frame:SetMinResize(240,240)
frame:SetToplevel(true)
local titlebg = frame:CreateTexture(nil, "BACKGROUND")
titlebg:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Title-Background]])
titlebg:SetPoint("TOPLEFT", 9, -6)
titlebg:SetPoint("BOTTOMRIGHT", frame, "TOPRIGHT", -28, -24)
local dialogbg = frame:CreateTexture(nil, "BACKGROUND")
dialogbg:SetTexture([[Interface\Tooltips\UI-Tooltip-Background]])
dialogbg:SetPoint("TOPLEFT", 8, -24)
dialogbg:SetPoint("BOTTOMRIGHT", -6, 8)
dialogbg:SetVertexColor(0, 0, 0, .75)
local topleft = frame:CreateTexture(nil, "BORDER")
topleft:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
topleft:SetWidth(64)
topleft:SetHeight(64)
topleft:SetPoint("TOPLEFT")
topleft:SetTexCoord(0.501953125, 0.625, 0, 1)
local topright = frame:CreateTexture(nil, "BORDER")
topright:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
topright:SetWidth(64)
topright:SetHeight(64)
topright:SetPoint("TOPRIGHT")
topright:SetTexCoord(0.625, 0.75, 0, 1)
local top = frame:CreateTexture(nil, "BORDER")
top:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
top:SetHeight(64)
top:SetPoint("TOPLEFT", topleft, "TOPRIGHT")
top:SetPoint("TOPRIGHT", topright, "TOPLEFT")
top:SetTexCoord(0.25, 0.369140625, 0, 1)
local bottomleft = frame:CreateTexture(nil, "BORDER")
bottomleft:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
bottomleft:SetWidth(64)
bottomleft:SetHeight(64)
bottomleft:SetPoint("BOTTOMLEFT")
bottomleft:SetTexCoord(0.751953125, 0.875, 0, 1)
local bottomright = frame:CreateTexture(nil, "BORDER")
bottomright:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
bottomright:SetWidth(64)
bottomright:SetHeight(64)
bottomright:SetPoint("BOTTOMRIGHT")
bottomright:SetTexCoord(0.875, 1, 0, 1)
local bottom = frame:CreateTexture(nil, "BORDER")
bottom:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
bottom:SetHeight(64)
bottom:SetPoint("BOTTOMLEFT", bottomleft, "BOTTOMRIGHT")
bottom:SetPoint("BOTTOMRIGHT", bottomright, "BOTTOMLEFT")
bottom:SetTexCoord(0.376953125, 0.498046875, 0, 1)
local left = frame:CreateTexture(nil, "BORDER")
left:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
left:SetWidth(64)
left:SetPoint("TOPLEFT", topleft, "BOTTOMLEFT")
left:SetPoint("BOTTOMLEFT", bottomleft, "TOPLEFT")
left:SetTexCoord(0.001953125, 0.125, 0, 1)
local right = frame:CreateTexture(nil, "BORDER")
right:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
right:SetWidth(64)
right:SetPoint("TOPRIGHT", topright, "BOTTOMRIGHT")
right:SetPoint("BOTTOMRIGHT", bottomright, "TOPRIGHT")
right:SetTexCoord(0.1171875, 0.2421875, 0, 1)
local close = CreateFrame("Button", nil, frame, "UIPanelCloseButton")
close:SetPoint("TOPRIGHT", 2, 1)
close:SetScript("OnClick", closeOnClick)
self.closebutton = close
close.obj = self
local titletext = frame:CreateFontString(nil, "ARTWORK")
titletext:SetFontObject(GameFontNormal)
titletext:SetPoint("TOPLEFT", 12, -8)
titletext:SetPoint("TOPRIGHT", -32, -8)
self.titletext = titletext
local title = CreateFrame("Button", nil, frame)
title:SetPoint("TOPLEFT", titlebg)
title:SetPoint("BOTTOMRIGHT", titlebg)
title:EnableMouse()
title:SetScript("OnMouseDown",titleOnMouseDown)
title:SetScript("OnMouseUp", frameOnMouseUp)
self.title = title
local sizer_se = CreateFrame("Frame",nil,frame)
sizer_se:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",0,0)
sizer_se:SetWidth(25)
sizer_se:SetHeight(25)
sizer_se:EnableMouse()
sizer_se:SetScript("OnMouseDown",sizerseOnMouseDown)
sizer_se:SetScript("OnMouseUp", sizerOnMouseUp)
self.sizer_se = sizer_se
local line1 = sizer_se:CreateTexture(nil, "BACKGROUND")
self.line1 = line1
line1:SetWidth(14)
line1:SetHeight(14)
line1:SetPoint("BOTTOMRIGHT", -8, 8)
line1:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border")
local x = 0.1 * 14/17
line1:SetTexCoord(0.05 - x, 0.5, 0.05, 0.5 + x, 0.05, 0.5 - x, 0.5 + x, 0.5)
local line2 = sizer_se:CreateTexture(nil, "BACKGROUND")
self.line2 = line2
line2:SetWidth(8)
line2:SetHeight(8)
line2:SetPoint("BOTTOMRIGHT", -8, 8)
line2:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border")
local x = 0.1 * 8/17
line2:SetTexCoord(0.05 - x, 0.5, 0.05, 0.5 + x, 0.05, 0.5 - x, 0.5 + x, 0.5)
local sizer_s = CreateFrame("Frame",nil,frame)
sizer_s:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-25,0)
sizer_s:SetPoint("BOTTOMLEFT",frame,"BOTTOMLEFT",0,0)
sizer_s:SetHeight(25)
sizer_s:EnableMouse()
sizer_s:SetScript("OnMouseDown",sizersOnMouseDown)
sizer_s:SetScript("OnMouseUp", sizerOnMouseUp)
self.sizer_s = sizer_s
local sizer_e = CreateFrame("Frame",nil,frame)
sizer_e:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",0,25)
sizer_e:SetPoint("TOPRIGHT",frame,"TOPRIGHT",0,0)
sizer_e:SetWidth(25)
sizer_e:EnableMouse()
sizer_e:SetScript("OnMouseDown",sizereOnMouseDown)
sizer_e:SetScript("OnMouseUp", sizerOnMouseUp)
self.sizer_e = sizer_e
--Container Support
local content = CreateFrame("Frame",nil,frame)
self.content = content
content.obj = self
content:SetPoint("TOPLEFT",frame,"TOPLEFT",12,-32)
content:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-12,13)
AceGUI:RegisterAsContainer(self)
return self
end
AceGUI:RegisterWidgetType(Type,Constructor,Version)
end
| gpl-3.0 |
OuTopos/hate | lib/hate/viewports.lua | 1 | 1689 | local hate = require((...):match("(.+)%.[^%.]+$") .. ".table")
local viewports = {}
local function new()
local self = {}
self.x = 0
self.y = 0
self.r = 0
self.sx = 1
self.sy = 1
self.ox = 0
self.oy = 0
self.kx = 0
self.ky = 0
local width, height = love.graphics.getDimensions()
-- CAMERAS
local cameras = {}
function self.newCamera()
local camera = hate.cameras.new(self)
table.insert(cameras, camera)
return camera
end
-- CANVAS
local canvas = love.graphics.newCanvas(width, height)
local function newCanvas()
canvas = love.graphics.newCanvas(width, height)
end
-- SET SIZE
function self.setSize(w, h)
width = w or width
height = h or height
newCanvas()
for k = 1, #cameras do
cameras[k].width = width
cameras[k].height = height
end
end
-- RESIZE & ZOOM
function self.resize(width, height)
print("KÖR EN RESIZE")
self.width = width or love.window.getWidth()
self.height = height or love.window.getHeight()
setupCanvases()
end
function self.update(dt)
for k = 1, #cameras do
cameras[k].update()
end
end
function self.draw()
-- set canvas
love.graphics.setCanvas(canvas)
love.graphics.clear()
for k = 1, #cameras do
cameras[k].draw()
end
-- unset canvas
love.graphics.setCanvas()
-- draw canvas
love.graphics.draw(canvas, self.x, self.y, self.r, self.sx, self.sy, self.ox, self.oy, self.kx, self.ky)
end
table.insert(viewports, self)
return self
end
local function update(dt)
for k = 1, #viewports do
viewports[k].update(dt)
end
end
local function draw()
for k = #viewports, 1, -1 do
viewports[k].draw()
end
end
return {
new = new,
update = update,
draw = draw
} | gpl-3.0 |
ArnaudSiebens/AutoActionCam | Libs/AceGUI-3.0/widgets/AceGUIContainer-Window.lua | 52 | 9726 | local AceGUI = LibStub("AceGUI-3.0")
-- Lua APIs
local pairs, assert, type = pairs, assert, type
-- WoW APIs
local PlaySound = PlaySound
local CreateFrame, UIParent = CreateFrame, UIParent
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: GameFontNormal
----------------
-- Main Frame --
----------------
--[[
Events :
OnClose
]]
do
local Type = "Window"
local Version = 4
local function frameOnClose(this)
this.obj:Fire("OnClose")
end
local function closeOnClick(this)
PlaySound("gsTitleOptionExit")
this.obj:Hide()
end
local function frameOnMouseDown(this)
AceGUI:ClearFocus()
end
local function titleOnMouseDown(this)
this:GetParent():StartMoving()
AceGUI:ClearFocus()
end
local function frameOnMouseUp(this)
local frame = this:GetParent()
frame:StopMovingOrSizing()
local self = frame.obj
local status = self.status or self.localstatus
status.width = frame:GetWidth()
status.height = frame:GetHeight()
status.top = frame:GetTop()
status.left = frame:GetLeft()
end
local function sizerseOnMouseDown(this)
this:GetParent():StartSizing("BOTTOMRIGHT")
AceGUI:ClearFocus()
end
local function sizersOnMouseDown(this)
this:GetParent():StartSizing("BOTTOM")
AceGUI:ClearFocus()
end
local function sizereOnMouseDown(this)
this:GetParent():StartSizing("RIGHT")
AceGUI:ClearFocus()
end
local function sizerOnMouseUp(this)
this:GetParent():StopMovingOrSizing()
end
local function SetTitle(self,title)
self.titletext:SetText(title)
end
local function SetStatusText(self,text)
-- self.statustext:SetText(text)
end
local function Hide(self)
self.frame:Hide()
end
local function Show(self)
self.frame:Show()
end
local function OnAcquire(self)
self.frame:SetParent(UIParent)
self.frame:SetFrameStrata("FULLSCREEN_DIALOG")
self:ApplyStatus()
self:EnableResize(true)
self:Show()
end
local function OnRelease(self)
self.status = nil
for k in pairs(self.localstatus) do
self.localstatus[k] = nil
end
end
-- called to set an external table to store status in
local function SetStatusTable(self, status)
assert(type(status) == "table")
self.status = status
self:ApplyStatus()
end
local function ApplyStatus(self)
local status = self.status or self.localstatus
local frame = self.frame
self:SetWidth(status.width or 700)
self:SetHeight(status.height or 500)
if status.top and status.left then
frame:SetPoint("TOP",UIParent,"BOTTOM",0,status.top)
frame:SetPoint("LEFT",UIParent,"LEFT",status.left,0)
else
frame:SetPoint("CENTER",UIParent,"CENTER")
end
end
local function OnWidthSet(self, width)
local content = self.content
local contentwidth = width - 34
if contentwidth < 0 then
contentwidth = 0
end
content:SetWidth(contentwidth)
content.width = contentwidth
end
local function OnHeightSet(self, height)
local content = self.content
local contentheight = height - 57
if contentheight < 0 then
contentheight = 0
end
content:SetHeight(contentheight)
content.height = contentheight
end
local function EnableResize(self, state)
local func = state and "Show" or "Hide"
self.sizer_se[func](self.sizer_se)
self.sizer_s[func](self.sizer_s)
self.sizer_e[func](self.sizer_e)
end
local function Constructor()
local frame = CreateFrame("Frame",nil,UIParent)
local self = {}
self.type = "Window"
self.Hide = Hide
self.Show = Show
self.SetTitle = SetTitle
self.OnRelease = OnRelease
self.OnAcquire = OnAcquire
self.SetStatusText = SetStatusText
self.SetStatusTable = SetStatusTable
self.ApplyStatus = ApplyStatus
self.OnWidthSet = OnWidthSet
self.OnHeightSet = OnHeightSet
self.EnableResize = EnableResize
self.localstatus = {}
self.frame = frame
frame.obj = self
frame:SetWidth(700)
frame:SetHeight(500)
frame:SetPoint("CENTER",UIParent,"CENTER",0,0)
frame:EnableMouse()
frame:SetMovable(true)
frame:SetResizable(true)
frame:SetFrameStrata("FULLSCREEN_DIALOG")
frame:SetScript("OnMouseDown", frameOnMouseDown)
frame:SetScript("OnHide",frameOnClose)
frame:SetMinResize(240,240)
frame:SetToplevel(true)
local titlebg = frame:CreateTexture(nil, "BACKGROUND")
titlebg:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Title-Background]])
titlebg:SetPoint("TOPLEFT", 9, -6)
titlebg:SetPoint("BOTTOMRIGHT", frame, "TOPRIGHT", -28, -24)
local dialogbg = frame:CreateTexture(nil, "BACKGROUND")
dialogbg:SetTexture([[Interface\Tooltips\UI-Tooltip-Background]])
dialogbg:SetPoint("TOPLEFT", 8, -24)
dialogbg:SetPoint("BOTTOMRIGHT", -6, 8)
dialogbg:SetVertexColor(0, 0, 0, .75)
local topleft = frame:CreateTexture(nil, "BORDER")
topleft:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
topleft:SetWidth(64)
topleft:SetHeight(64)
topleft:SetPoint("TOPLEFT")
topleft:SetTexCoord(0.501953125, 0.625, 0, 1)
local topright = frame:CreateTexture(nil, "BORDER")
topright:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
topright:SetWidth(64)
topright:SetHeight(64)
topright:SetPoint("TOPRIGHT")
topright:SetTexCoord(0.625, 0.75, 0, 1)
local top = frame:CreateTexture(nil, "BORDER")
top:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
top:SetHeight(64)
top:SetPoint("TOPLEFT", topleft, "TOPRIGHT")
top:SetPoint("TOPRIGHT", topright, "TOPLEFT")
top:SetTexCoord(0.25, 0.369140625, 0, 1)
local bottomleft = frame:CreateTexture(nil, "BORDER")
bottomleft:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
bottomleft:SetWidth(64)
bottomleft:SetHeight(64)
bottomleft:SetPoint("BOTTOMLEFT")
bottomleft:SetTexCoord(0.751953125, 0.875, 0, 1)
local bottomright = frame:CreateTexture(nil, "BORDER")
bottomright:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
bottomright:SetWidth(64)
bottomright:SetHeight(64)
bottomright:SetPoint("BOTTOMRIGHT")
bottomright:SetTexCoord(0.875, 1, 0, 1)
local bottom = frame:CreateTexture(nil, "BORDER")
bottom:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
bottom:SetHeight(64)
bottom:SetPoint("BOTTOMLEFT", bottomleft, "BOTTOMRIGHT")
bottom:SetPoint("BOTTOMRIGHT", bottomright, "BOTTOMLEFT")
bottom:SetTexCoord(0.376953125, 0.498046875, 0, 1)
local left = frame:CreateTexture(nil, "BORDER")
left:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
left:SetWidth(64)
left:SetPoint("TOPLEFT", topleft, "BOTTOMLEFT")
left:SetPoint("BOTTOMLEFT", bottomleft, "TOPLEFT")
left:SetTexCoord(0.001953125, 0.125, 0, 1)
local right = frame:CreateTexture(nil, "BORDER")
right:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
right:SetWidth(64)
right:SetPoint("TOPRIGHT", topright, "BOTTOMRIGHT")
right:SetPoint("BOTTOMRIGHT", bottomright, "TOPRIGHT")
right:SetTexCoord(0.1171875, 0.2421875, 0, 1)
local close = CreateFrame("Button", nil, frame, "UIPanelCloseButton")
close:SetPoint("TOPRIGHT", 2, 1)
close:SetScript("OnClick", closeOnClick)
self.closebutton = close
close.obj = self
local titletext = frame:CreateFontString(nil, "ARTWORK")
titletext:SetFontObject(GameFontNormal)
titletext:SetPoint("TOPLEFT", 12, -8)
titletext:SetPoint("TOPRIGHT", -32, -8)
self.titletext = titletext
local title = CreateFrame("Button", nil, frame)
title:SetPoint("TOPLEFT", titlebg)
title:SetPoint("BOTTOMRIGHT", titlebg)
title:EnableMouse()
title:SetScript("OnMouseDown",titleOnMouseDown)
title:SetScript("OnMouseUp", frameOnMouseUp)
self.title = title
local sizer_se = CreateFrame("Frame",nil,frame)
sizer_se:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",0,0)
sizer_se:SetWidth(25)
sizer_se:SetHeight(25)
sizer_se:EnableMouse()
sizer_se:SetScript("OnMouseDown",sizerseOnMouseDown)
sizer_se:SetScript("OnMouseUp", sizerOnMouseUp)
self.sizer_se = sizer_se
local line1 = sizer_se:CreateTexture(nil, "BACKGROUND")
self.line1 = line1
line1:SetWidth(14)
line1:SetHeight(14)
line1:SetPoint("BOTTOMRIGHT", -8, 8)
line1:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border")
local x = 0.1 * 14/17
line1:SetTexCoord(0.05 - x, 0.5, 0.05, 0.5 + x, 0.05, 0.5 - x, 0.5 + x, 0.5)
local line2 = sizer_se:CreateTexture(nil, "BACKGROUND")
self.line2 = line2
line2:SetWidth(8)
line2:SetHeight(8)
line2:SetPoint("BOTTOMRIGHT", -8, 8)
line2:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border")
local x = 0.1 * 8/17
line2:SetTexCoord(0.05 - x, 0.5, 0.05, 0.5 + x, 0.05, 0.5 - x, 0.5 + x, 0.5)
local sizer_s = CreateFrame("Frame",nil,frame)
sizer_s:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-25,0)
sizer_s:SetPoint("BOTTOMLEFT",frame,"BOTTOMLEFT",0,0)
sizer_s:SetHeight(25)
sizer_s:EnableMouse()
sizer_s:SetScript("OnMouseDown",sizersOnMouseDown)
sizer_s:SetScript("OnMouseUp", sizerOnMouseUp)
self.sizer_s = sizer_s
local sizer_e = CreateFrame("Frame",nil,frame)
sizer_e:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",0,25)
sizer_e:SetPoint("TOPRIGHT",frame,"TOPRIGHT",0,0)
sizer_e:SetWidth(25)
sizer_e:EnableMouse()
sizer_e:SetScript("OnMouseDown",sizereOnMouseDown)
sizer_e:SetScript("OnMouseUp", sizerOnMouseUp)
self.sizer_e = sizer_e
--Container Support
local content = CreateFrame("Frame",nil,frame)
self.content = content
content.obj = self
content:SetPoint("TOPLEFT",frame,"TOPLEFT",12,-32)
content:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-12,13)
AceGUI:RegisterAsContainer(self)
return self
end
AceGUI:RegisterWidgetType(Type,Constructor,Version)
end
| gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Windurst_Woods/npcs/Nikkoko.lua | 5 | 1035 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Nikkoko
-- Type: Craftsman
-- @zone: 241
-- @pos: -32.810 -3.25 -113.680
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x271e);
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 |
d909b/GADEL-Snake | Tools/BuildScripts/lua-lib/penlight-1.0.2/lua/pl/class.lua | 12 | 5169 | --- Provides a reuseable and convenient framework for creating classes in Lua.
-- Two possible notations:
--
-- B = class(A)
-- class.B(A)
--
-- The latter form creates a named class.
--
-- See the Guide for further @{01-introduction.md.Simplifying_Object_Oriented_Programming_in_Lua|discussion}
-- @module pl.class
local error, getmetatable, io, pairs, rawget, rawset, setmetatable, tostring, type =
_G.error, _G.getmetatable, _G.io, _G.pairs, _G.rawget, _G.rawset, _G.setmetatable, _G.tostring, _G.type
-- this trickery is necessary to prevent the inheritance of 'super' and
-- the resulting recursive call problems.
local function call_ctor (c,obj,...)
-- nice alias for the base class ctor
local base = rawget(c,'_base')
if base then
local parent_ctor = rawget(base,'_init')
if parent_ctor then
obj.super = function(obj,...)
call_ctor(base,obj,...)
end
end
end
local res = c._init(obj,...)
obj.super = nil
return res
end
local function is_a(self,klass)
local m = getmetatable(self)
if not m then return false end --*can't be an object!
while m do
if m == klass then return true end
m = rawget(m,'_base')
end
return false
end
local function class_of(klass,obj)
if type(klass) ~= 'table' or not rawget(klass,'is_a') then return false end
return klass.is_a(obj,klass)
end
local function _class_tostring (obj)
local mt = obj._class
local name = rawget(mt,'_name')
setmetatable(obj,nil)
local str = tostring(obj)
setmetatable(obj,mt)
if name then str = name ..str:gsub('table','') end
return str
end
local function tupdate(td,ts)
for k,v in pairs(ts) do
td[k] = v
end
end
local function _class(base,c_arg,c)
c = c or {} -- a new class instance, which is the metatable for all objects of this type
-- the class will be the metatable for all its objects,
-- and they will look up their methods in it.
local mt = {} -- a metatable for the class instance
if type(base) == 'table' then
-- our new class is a shallow copy of the base class!
tupdate(c,base)
c._base = base
-- inherit the 'not found' handler, if present
if rawget(c,'_handler') then mt.__index = c._handler end
elseif base ~= nil then
error("must derive from a table type",3)
end
c.__index = c
setmetatable(c,mt)
c._init = nil
if base and rawget(base,'_class_init') then
base._class_init(c,c_arg)
end
-- expose a ctor which can be called by <classname>(<args>)
mt.__call = function(class_tbl,...)
local obj = {}
setmetatable(obj,c)
if rawget(c,'_init') then -- explicit constructor
local res = call_ctor(c,obj,...)
if res then -- _if_ a ctor returns a value, it becomes the object...
obj = res
setmetatable(obj,c)
end
elseif base and rawget(base,'_init') then -- default constructor
-- make sure that any stuff from the base class is initialized!
call_ctor(base,obj,...)
end
if base and rawget(base,'_post_init') then
base._post_init(obj)
end
if not rawget(c,'__tostring') then
c.__tostring = _class_tostring
end
return obj
end
-- Call Class.catch to set a handler for methods/properties not found in the class!
c.catch = function(handler)
c._handler = handler
mt.__index = handler
end
c.is_a = is_a
c.class_of = class_of
c._class = c
return c
end
--- create a new class, derived from a given base class.
-- Supporting two class creation syntaxes:
-- either `Name = class(base)` or `class.Name(base)`
-- @function class
-- @param base optional base class
-- @param c_arg optional parameter to class ctor
-- @param c optional table to be used as class
local class
class = setmetatable({},{
__call = function(fun,...)
return _class(...)
end,
__index = function(tbl,key)
if key == 'class' then
io.stderr:write('require("pl.class").class is deprecated. Use require("pl.class")\n')
return class
end
local env = _G
return function(...)
local c = _class(...)
c._name = key
rawset(env,key,c)
return c
end
end
})
class.properties = class()
function class.properties._class_init(klass)
klass.__index = function(t,key)
-- normal class lookup!
local v = klass[key]
if v then return v end
-- is it a getter?
v = rawget(klass,'get_'..key)
if v then
return v(t)
end
-- is it a field?
return rawget(t,'_'..key)
end
klass.__newindex = function (t,key,value)
-- if there's a setter, use that, otherwise directly set table
local p = 'set_'..key
local setter = klass[p]
if setter then
setter(t,value)
else
rawset(t,key,value)
end
end
end
return class
| bsd-3-clause |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/server.lua | 2 | 3271 | -----------------------------------
-- Note from Tenjou:
-- now you can customize it a little more in the settings!
--
-----------------------------------
require("scripts/globals/conquest");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/globals/mobs");
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/titles");
-----------------------------------
-- OnServerStart
-----------------------------------
function onServerStart()
if (EXPLORER_MOOGLE == 1) then
SetExplorerMoogles();
end
if (FIELD_MANUALS == 1) then
SetFieldManual();
end
SetRegionalConquestOverseers()
-- Charybdis PH alternates, remove one
DespawnMob(17498518);
-- Timed Spawns
SetTimedSpawns();
-- Spawns Silk Caterpillar (temporary until someone implements a way to make it spawn properly)
SpawnMob(17227782,300,660);
end;
-----------------------------------
-- SetExplorerMoogles
----------------------------------
function SetExplorerMoogles()
local Moogles =
{
17723639, -- Northern_San_d'Oria
17735848, -- Bastok_Mines
17760442, -- Port_Windurst
17793123, -- Selbina
17797245, -- Mhaura
}
i = 1;
while i <= (table.getn(Moogles)) do
npc = GetNPCByID(Moogles[i]);
npc:setStatus(0);
i = i + 1;
end
end;
-----------------------------------
-- SetFieldManual
----------------------------------
function SetFieldManual()
local FieldManuals =
{
17187512,17187513,17191493,17191494,
17195670,17195671,17199744,17199745,
17199746,17203876,17203877,17207858,
17207859,17212072,17212073,17212074,
17216140,17216141,17220158,17220159,
17224344,17224345,17228368,17228369,
17232272,17232273,17232274,17232275,
17236336,17236337,17240507,17240508,
17244644,17244645,17244646,17248814,
17248815,17248816,17253022,17253023,
17253024,17257067,17257068,17257069,
17261191,17261192,17265284,17265285,
17265286,17269253,17269254,17273410,
17273411,17277203,17277204,17281639,
17281640,17281641,17281642,17285689,
17285690,17285691,17289788,17289789,
17289790,17293768,17293769,17297484,
17301585,17301586,17310097,17310098,
17310099,17310100,17310101,17310102,
}
i = 1;
while i <= (table.getn(FieldManuals)) do
npc = GetNPCByID(FieldManuals[i]);
npc:setStatus(0);
i = i + 1;
end
end;
----------------------------------
-- SetTimedSpawns
----------------------------------
function SetTimedSpawns()
local NMs =
{
17649693, -- Mysticmaker Profblix
17645578, -- Bune
17240413, -- Kreutzet
17490234, -- Guivre
17289575, -- King Vinegarroon
17244539, -- Cactrot Rapido
17244372, -- Centurio_XII-I
17408018, -- Fafnir
17596720, -- Serket
17596506, -- Old Two-Wings
17596507, -- Skewer Sam
17269106, -- Roc
17297440, -- Behemoth
17228242, -- Simurgh
17301537, -- Adamantoise
17568127 -- Morbolger
}
i = 1;
while i <= (table.getn(NMs)) do
UpdateNMSpawnPoint(NMs[i]);
SpawnMob(NMs[i], '', math.random((900),(10800))); --15-180 minutes
i = i + 1;
end
end; | gpl-3.0 |
nimaghorbani/newbot | bot/utils.lua | 646 | 23489 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(msg.to.id)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local groups = 'groups'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(msg.to.id)] then
var = true
end
return var
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "global bans !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "User "..result.from.id.." Unbanned")
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered")
else
return 'Use This in Your Groups'
end
end
| gpl-2.0 |
Servius/tfa-sw-weapons-repository | In Development/servius_development/tfa_training_weapons/expanded_pack/lua/weapons/tfa_752_ihr_training/shared.lua | 1 | 2391 | if ( SERVER ) then
AddCSLuaFile( "shared.lua" )
end
if ( CLIENT ) then
SWEP.PrintName = "Imperial Heavy Repeater"
SWEP.Author = "TFA, Servius"
SWEP.ViewModelFOV = 50
SWEP.Slot = 2
SWEP.SlotPos = 3
SWEP.WepSelectIcon = surface.GetTextureID("HUD/killicons/IHR")
killicon.Add( "tfa_752_ihr", "HUD/killicons/IHR", Color( 255, 80, 0, 255 ) )
end
SWEP.HoldType = "ar2"
SWEP.Base = "tfa_swsft_base_servius_training"
SWEP.Category = "TFA Star Wars: Training"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.ViewModel = "models/weapons/v_IHR.mdl"
SWEP.WorldModel = "models/weapons/w_IHR.mdl"
SWEP.Weight = 5
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
SWEP.Primary.Sound = Sound ("weapons/ihr/IHR_fire.ogg");
SWEP.Primary.ReloadSound = Sound ("weapons/shared/standard_reload.ogg");
SWEP.Primary.Recoil = 0.5
SWEP.Primary.Damage = 40
SWEP.Primary.NumShots = 1
SWEP.Primary.Spread = 0.08
SWEP.Primary.IronAccuracy = .03 -- Ironsight accuracy, should be the same for shotguns
SWEP.Primary.ClipSize = 45
SWEP.Primary.RPM = 425
--= 180
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = "battery"
SWEP.TracerName = "effect_sw_laser_yellow"
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.IronSightsPos = Vector (-4.7, -6, 0.3)
SWEP.IronSightsAng = Vector (-1,0,0)
function SWEP:Think()
local ClipPercentage = ((100/self.Primary.ClipSize)*self.Weapon:Clip1());
if (ClipPercentage < 1) then
self.Owner:GetViewModel():SetSkin( 10 )
return
end
if (ClipPercentage < 11) then
self.Owner:GetViewModel():SetSkin( 9 )
return
end
if (ClipPercentage < 21) then
self.Owner:GetViewModel():SetSkin( 8 )
return
end
if (ClipPercentage < 31) then
self.Owner:GetViewModel():SetSkin( 7 )
return
end
if (ClipPercentage < 41) then
self.Owner:GetViewModel():SetSkin( 6 )
return
end
if (ClipPercentage < 51) then
self.Owner:GetViewModel():SetSkin( 5 )
return
end
if (ClipPercentage < 61) then
self.Owner:GetViewModel():SetSkin( 4 )
return
end
if (ClipPercentage < 71) then
self.Owner:GetViewModel():SetSkin( 3 )
return
end
if (ClipPercentage < 81) then
self.Owner:GetViewModel():SetSkin( 2 )
return
end
if (ClipPercentage < 91) then
self.Owner:GetViewModel():SetSkin( 1 )
return
end
if (ClipPercentage < 101) then
self.Owner:GetViewModel():SetSkin( 0 )
end
end | apache-2.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Northern_San_dOria/npcs/Lucretia.lua | 2 | 1090 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Lucretia
-- Guild Merchant NPC: Blacksmithing Guild
-- @zone: 231
-- @pos: -193.729 3.999 159.412
--
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:sendGuild(526,8,23,2)) then
player:showText(npc,LUCRETIA_SHOP_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
mohammadkabir1/kabirBot | plugins/twitter_send.lua | 627 | 1555 | do
local OAuth = require "OAuth"
local consumer_key = ""
local consumer_secret = ""
local access_token = ""
local access_token_secret = ""
local client = OAuth.new(consumer_key, consumer_secret, {
RequestToken = "https://api.twitter.com/oauth/request_token",
AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"},
AccessToken = "https://api.twitter.com/oauth/access_token"
}, {
OAuthToken = access_token,
OAuthTokenSecret = access_token_secret
})
function run(msg, matches)
if consumer_key:isempty() then
return "Twitter Consumer Key is empty, write it in plugins/twitter_send.lua"
end
if consumer_secret:isempty() then
return "Twitter Consumer Secret is empty, write it in plugins/twitter_send.lua"
end
if access_token:isempty() then
return "Twitter Access Token is empty, write it in plugins/twitter_send.lua"
end
if access_token_secret:isempty() then
return "Twitter Access Token Secret is empty, write it in plugins/twitter_send.lua"
end
if not is_sudo(msg) then
return "You aren't allowed to send tweets"
end
local response_code, response_headers, response_status_line, response_body =
client:PerformRequest("POST", "https://api.twitter.com/1.1/statuses/update.json", {
status = matches[1]
})
if response_code ~= 200 then
return "Error: "..response_code
end
return "Tweet sent"
end
return {
description = "Sends a tweet",
usage = "!tw [text]: Sends the Tweet with the configured account.",
patterns = {"^!tw (.+)"},
run = run
}
end
| gpl-2.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Kazham/npcs/Romaa_Mihgo.lua | 2 | 1029 | -----------------------------------
-- Area: Kazham
-- NPC: Romaa Mihgo
-- Type: Standard NPC
-- @zone: 250
-- @pos: 29.000 -13.023 -176.500
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0107);
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 |
bright-things/ionic-luci | applications/luci-app-asterisk/luasrc/model/cbi/asterisk/trunk_sip.lua | 68 | 2351 | -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local ast = require("luci.asterisk")
--
-- SIP trunk info
--
if arg[2] == "info" then
form = SimpleForm("asterisk", "SIP Trunk Information")
form.reset = false
form.submit = "Back to overview"
local info, keys = ast.sip.peer(arg[1])
local data = { }
for _, key in ipairs(keys) do
data[#data+1] = {
key = key,
val = type(info[key]) == "boolean"
and ( info[key] and "yes" or "no" )
or ( info[key] == nil or #info[key] == 0 )
and "(none)"
or tostring(info[key])
}
end
itbl = form:section(Table, data, "SIP Trunk %q" % arg[1])
itbl:option(DummyValue, "key", "Key")
itbl:option(DummyValue, "val", "Value")
function itbl.parse(...)
luci.http.redirect(
luci.dispatcher.build_url("admin", "asterisk", "trunks")
)
end
return form
--
-- SIP trunk config
--
elseif arg[1] then
cbimap = Map("asterisk", "Edit SIP Trunk")
peer = cbimap:section(NamedSection, arg[1])
peer.hidden = {
type = "peer",
qualify = "yes",
}
back = peer:option(DummyValue, "_overview", "Back to trunk overview")
back.value = ""
back.titleref = luci.dispatcher.build_url("admin", "asterisk", "trunks")
sipdomain = peer:option(Value, "host", "SIP Domain")
sipport = peer:option(Value, "port", "SIP Port")
function sipport.cfgvalue(...)
return AbstractValue.cfgvalue(...) or "5060"
end
username = peer:option(Value, "username", "Authorization ID")
password = peer:option(Value, "secret", "Authorization Password")
password.password = true
outboundproxy = peer:option(Value, "outboundproxy", "Outbound Proxy")
outboundport = peer:option(Value, "outboundproxyport", "Outbound Proxy Port")
register = peer:option(Flag, "register", "Register with peer")
register.enabled = "yes"
register.disabled = "no"
regext = peer:option(Value, "registerextension", "Extension to register (optional)")
regext:depends({register="1"})
didval = peer:option(ListValue, "_did", "Number of assigned DID numbers")
didval:value("", "(none)")
for i=1,24 do didval:value(i) end
dialplan = peer:option(ListValue, "context", "Dialplan Context")
dialplan:value(arg[1] .. "_inbound", "(default)")
cbimap.uci:foreach("asterisk", "dialplan",
function(s) dialplan:value(s['.name']) end)
return cbimap
end
| apache-2.0 |
Sonicrich05/FFXI-Server | scripts/zones/RuAun_Gardens/npcs/qm4.lua | 16 | 1444 | -----------------------------------
-- Area: Ru'Aun Gardens
-- NPC: ??? (Suzaku's Spawn)
-- Allows players to spawn the HNM Suzaku with a Gem of the South and a Summerstone.
-- @pos -514 -70 -264 130
-----------------------------------
package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/RuAun_Gardens/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Trade Gem of the South and Summerstone
if (GetMobAction(17309983) == 0 and trade:hasItemQty(1420,1) and trade:hasItemQty(1421,1) and trade:getItemCount() == 2) then
player:tradeComplete();
SpawnMob(17309983,300):updateClaim(player); -- Spawn Suzaku
player:showText(npc,SKY_GOD_OFFSET + 7);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(SKY_GOD_OFFSET + 3);
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 |
Sonicrich05/FFXI-Server | scripts/zones/Port_Windurst/npcs/Yujuju.lua | 17 | 2619 | -----------------------------------
-- Area: Port Windurst
-- NPC: Yujuju
-- Involved In Quest: Making Headlines
-- @pos 201.523 -4.785 138.978 240
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
function testflag(set,flag)
return (set % (2*flag) >= flag)
end
local MakingHeadlines = player:getQuestStatus(WINDURST,MAKING_HEADLINES);
local WildcatWindurst = player:getVar("WildcatWindurst");
if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,19) == false) then
player:startEvent(0x026d);
elseif (player:getCurrentMission(COP) == THE_ROAD_FORKS and player:getVar("MEMORIES_OF_A_MAIDEN_Status")==9) then
player:startEvent(0x0250);--COP event
elseif (MakingHeadlines == 1) then
local prog = player:getVar("QuestMakingHeadlines_var");
-- Variable to track if player has talked to 4 NPCs and a door
-- 1 = Kyume
-- 2 = Yujuju
-- 4 = Hiwom
-- 8 = Umumu
-- 16 = Mahogany Door
if (testflag(tonumber(prog),2) == false) then
player:startEvent(0x013a); -- Get Scoop
else
player:startEvent(0x013b); -- After receiving scoop
end
else
player:startEvent(0x0154); -- Standard Conversation
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x013a) then
prog = player:getVar("QuestMakingHeadlines_var");
player:addKeyItem(PORT_WINDURST_SCOOP);
player:messageSpecial(KEYITEM_OBTAINED,PORT_WINDURST_SCOOP);
player:setVar("QuestMakingHeadlines_var",prog+2);
elseif (csid == 0x0250) then
player:setVar("MEMORIES_OF_A_MAIDEN_Status",10);
elseif (csid == 0x026d) then
player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",19,true);
end
end;
| gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Northern_San_dOria/npcs/Mevaloud.lua | 6 | 1369 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Mevaloud
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0295);
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 |
Sonicrich05/FFXI-Server | scripts/globals/items/smoldering_salisbury_steak.lua | 36 | 1686 | -----------------------------------------
-- ID: 5924
-- Item: Smoldering Salisbury Steak
-- Food Effect: 180 Min, All Races
-----------------------------------------
-- HP +30
-- Strength +7
-- Intelligence -5
-- Attack % 20 Cap 160
-- Ranged Attack %20 Cap 160
-- Dragon Killer +5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5924);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 30);
target:addMod(MOD_STR, 7);
target:addMod(MOD_INT, -5);
target:addMod(MOD_FOOD_ATTP, 20);
target:addMod(MOD_FOOD_ATT_CAP, 160);
target:addMod(MOD_FOOD_RATTP, 20);
target:addMod(MOD_FOOD_RATT_CAP, 160);
target:addMod(MOD_DRAGON_KILLER, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 30);
target:delMod(MOD_STR, 7);
target:delMod(MOD_INT, -5);
target:delMod(MOD_FOOD_ATTP, 20);
target:delMod(MOD_FOOD_ATT_CAP, 160);
target:delMod(MOD_FOOD_RATTP, 20);
target:delMod(MOD_FOOD_RATT_CAP, 160);
target:delMod(MOD_DRAGON_KILLER, 5);
end;
| gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Dynamis-Xarcabard/mobs/Animated_Longsword.lua | 2 | 1295 | -----------------------------------
-- Area: Dynamis Xarcabard
-- NPC: Animated_Longsword
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob,target)
mob:addMod(MOD_STUNRES,75); -- Not full resist
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
if(GetServerVariable("[DynaXarcabard]Boss_Trigger") == 32767) then
SetDropRate(111,1573,100);
else
SetDropRate(111,1573,0);
end
SpawnMob(17330355,120):updateEnmity(target);
SpawnMob(17330356,120):updateEnmity(target);
SpawnMob(17330357,120):updateEnmity(target);
SpawnMob(17330362,120):updateEnmity(target);
SpawnMob(17330363,120):updateEnmity(target);
SpawnMob(17330364,120):updateEnmity(target);
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
DespawnMob(17330355);
DespawnMob(17330356);
DespawnMob(17330357);
DespawnMob(17330362);
DespawnMob(17330363);
DespawnMob(17330364);
end; | gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/zones/Chamber_of_Oracles/TextIDs.lua | 4 | 1386 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6383; -- Obtained: <item>
GIL_OBTAINED = 6384; -- Obtained <number> gil
KEYITEM_OBTAINED = 6386; -- Obtained key item: <keyitem>
-- Other Texts
YOU_CANNOT_ENTER_THE_BATTLEFIELD = 7199; -- You cannot enter the battlefield at present. Please wait a little longer.
-- Mission Texts
PLACED_INTO_THE_PEDESTAL = 7603; -- It appears that something should be placed into this pedestal.
YOU_PLACE_THE = 7604; -- You place theinto the pedestal.
IS_SET_IN_THE_PEDESTAL = 7605; -- Theis set in the pedestal.
HAS_LOST_ITS_POWER = 7606; -- Thehas lost its power.
-- Maat dialog
YOU_DECIDED_TO_SHOW_UP = 7625; -- So, you decided to show up.
LOOKS_LIKE_YOU_WERENT_READY = 7626; -- Looks like you weren't ready for me, were you?
YOUVE_COME_A_LONG_WAY = 7627; -- Hm. That was a mighty fine display of skill there, Player Name. You've come a long way...
TEACH_YOU_TO_RESPECT_ELDERS = 7628; -- I'll teach you to respect your elders!
TAKE_THAT_YOU_WHIPPERSNAPPER = 7629; -- Take that, you whippersnapper!
THAT_LL_HURT_IN_THE_MORNING = 7631; -- Ungh... That'll hurt in the morning...
-- conquest Base
CONQUEST_BASE = 7038; -- Tallying conquest results...
| gpl-3.0 |
Servius/tfa-sw-weapons-repository | Live Addons/servius_uploader/[TFA][AT] Shared Resources Pack/lua/entities/sent_swrc_hoth/shared.lua | 3 | 3658 | AddCSLuaFile( )
DEFINE_BASECLASS( "base_anim" )
ENT.IsDODSTNT = true
ENT.TotalExplosions = 1
ENT.AutomaticFrameAdvance = true
util.PrecacheModel( "models/props/starwars/weapons/hoth_bomb.mdl" )
util.PrecacheSound( "buttons/spark6.wav" )
util.PrecacheSound( "ambient/fire/mtov_flame2.wav" )
if CLIENT then
ENT.Mat = Material( "sprites/redglow1" )
ENT.Mat2 = Material( "cable/redlaser" )
ENT.LP = Vector( -.5, 1, 2 )
end
function ENT:SetupDataTables( )
self:NetworkVar( "Float", 0, "Defuse" )
self:NetworkVar( "Float", 1, "Fuse" )
self:NetworkVar( "Int", 0, "BurnAdjust" )
self:NetworkVar( "Bool", 0, "Live" )
end
function ENT:Draw( )
local bone, n, light
bone = self:GetAttachment( self:LookupAttachment( "wick" ) )
if not bone then
return
end
self:DrawModel( )
if self:GetDefuse( ) < 1 then
--if self.BurnSound then
--self.BurnSound:PlayEx( .5, 170 )
--end
else
if self.BurnSound then
self.BurnSound:Stop( )
end
end
end
function ENT:OnRemove( )
if self.BurnSound then
self.BurnSound:Stop( )
end
end
function ENT:Use(activator, caller)
self.Entity:ActivateX(1)
end
function ENT:ActivateX( scale )
if not self:GetLive( ) then
self:SetLive( true )
self:SetBurnAdjust( scale or 1 )
seq = self:LookupSequence( "w_tnt_wick" )
self:ResetSequence( seq )
self:SetPlaybackRate( 1 / self:GetBurnAdjust( ) )
if not self.BurnSound then
self.BurnSound = CreateSound( self, Sound( "weapons/sw_detonator.wav" ) )
end
self.BurnSound:Play( )
end
end
function ENT:OnTakeDamage( info )
self:TakePhysicsDamage( info )
if info and self:IsValid( ) and not self.Refuse then
if info:IsExplosionDamage( ) then
self:Explode( )
end
end
end
function ENT:Initialize( )
self:SetModel( "models/props/starwars/weapons/hoth_bomb.mdl" )
if SERVER then
self:SetDefuse( 0 )
self:SetFuse( 0 )
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:PhysWake( )
end
end
function ENT:Think( )
local now, delta
if CLIENT then
return
end
now = CurTime( )
delta = now - ( self.LastThink or now )
self.LastThink = now
if self:GetLive( ) then
if not self.Used then
self:SetDefuse( math.Clamp( self:GetDefuse( ) - delta * .5, 0, 1 ) )
end
end
if self:GetDefuse( ) >= 1 and self:GetLive( ) then
self:SetLive( false )
self:EmitSound( "buttons/spark6.wav", 100, 63 )
self:SetPlaybackRate( 0 )
end
if self:GetLive( ) then
self:SetFuse( math.Clamp( self:GetFuse( ) + delta / ( self:GetBurnAdjust( ) * 19 ), 0, 1 ) )
if self:GetFuse( ) >= 0.20 and SERVER then
self:SetLive( false )
self:Explode( )
end
end
if self:GetLive( ) and self:WaterLevel( ) > 0 then
self:SetLive( false )
self:SetDefuse( 1 )
end
self.Used = false
end
local function Spin( vector, up, right, forward )
local ang
ang = ( vector * 1 ):Angle( )
ang:RotateAroundAxis( ang:Up( ), math.random( -up / 2 , up / 2 ) )
ang:RotateAroundAxis( ang:Right( ), math.random( -right / 2 , right / 2 ) )
ang:RotateAroundAxis( ang:Forward( ), math.random( -forward / 2 , forward / 2 ) )
return ang:Forward( )
end
function ENT:Explode( )
if self.Refuse then
return
end
self.Refuse = true
for k, v in pairs (ents.FindInSphere(self.Entity:GetPos(), 250)) do
v:Fire("EnableMotion", "", math.random(0, 0.5))
end
local explode = ents.Create( "env_explosion" )
explode:SetPos( self:GetPos() )
explode:SetKeyValue( "iMagnitude", "250" )
explode:EmitSound( "weapon_AWP.Single", 100, 100 )
explode:Spawn()
explode:Activate()
explode:Fire( "Explode", "", 0 )
self:Remove()
end | apache-2.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Southern_San_dOria/npcs/Katharina.lua | 6 | 1054 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Katharina
-- General Info NPC
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
require("scripts/globals/settings");
function onTrigger(player,npc)
player:startEvent(0x377);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--print("CSID:",csid);
--print("RESULT:",option);
end; | gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Northern_San_dOria/npcs/Esqualea.lua | 6 | 1369 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Esqualea
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x029e);
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 |
Sonicrich05/FFXI-Server | scripts/globals/items/plate_of_royal_sautee.lua | 35 | 1749 | -----------------------------------------
-- ID: 4295
-- Item: plate_of_royal_sautee
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Strength 5
-- Agility 1
-- Intelligence -2
-- Attack % 20
-- Attack Cap 80
-- Ranged ATT % 20
-- Ranged ATT Cap 80
-- Stun Resist 5
-----------------------------------------
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,4295);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 5);
target:addMod(MOD_AGI, 1);
target:addMod(MOD_INT, -2);
target:addMod(MOD_FOOD_ATTP, 20);
target:addMod(MOD_FOOD_ATT_CAP, 80);
target:addMod(MOD_FOOD_RATTP, 20);
target:addMod(MOD_FOOD_RATT_CAP, 80);
target:addMod(MOD_STUNRES, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 5);
target:delMod(MOD_AGI, 1);
target:delMod(MOD_INT, -2);
target:delMod(MOD_FOOD_ATTP, 20);
target:delMod(MOD_FOOD_ATT_CAP, 80);
target:delMod(MOD_FOOD_RATTP, 20);
target:delMod(MOD_FOOD_RATT_CAP, 80);
target:delMod(MOD_STUNRES, 5);
end;
| gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/globals/items/charred_salisbury_steak.lua | 36 | 1683 | -----------------------------------------
-- ID: 5925
-- Item: Charred Salisbury Steak
-- Food Effect: 240 Min, All Races
-----------------------------------------
-- HP +32
-- Strength +8
-- Intelligence -6
-- Attack % 22 Cap 165
-- Ranged Attack %22 Cap 165
-- Dragon Killer +6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5925);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 32);
target:addMod(MOD_STR, 8);
target:addMod(MOD_INT, -6);
target:addMod(MOD_FOOD_ATTP, 22);
target:addMod(MOD_FOOD_ATT_CAP, 165);
target:addMod(MOD_FOOD_RATTP, 22);
target:addMod(MOD_FOOD_RATT_CAP, 165);
target:addMod(MOD_DRAGON_KILLER, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 32);
target:delMod(MOD_STR, 8);
target:delMod(MOD_INT, -6);
target:delMod(MOD_FOOD_ATTP, 22);
target:delMod(MOD_FOOD_ATT_CAP, 165);
target:delMod(MOD_FOOD_RATTP, 22);
target:delMod(MOD_FOOD_RATT_CAP, 165);
target:delMod(MOD_DRAGON_KILLER, 6);
end;
| gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/zones/Monarch_Linn/npcs/Spatial_Displacement.lua | 19 | 2455 | -----------------------------------
-- Area: Monarch_Linn
-- NPC: Spatial Displacement
-- @pos -35 -1 -539 31
-----------------------------------
package.loaded["scripts/zones/Monarch_LinnTextIDs"] = nil;
-----------------------------------
require("scripts/globals/bcnm");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/zones/Monarch_Linn/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
if (TradeBCNM(player,player:getZoneID(),trade,npc)) then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--printf("npcID : %u",npcID);
local npcID = npc:getID();
local X = player:getXPos();
local Z = player:getZPos();
if (X > 12.934 and X < 24.934) then
if (player:getPreviousZone() == 30) then
player:startEvent(0x0B); -- To Riv Site A
elseif (player:getPreviousZone() == 29) then
player:startEvent(0x0A); -- To Riv Site B
end
elseif ((X > -524.521 and X < -512.521) or (X > 75.524 and X < 87.524) or (X > 675.271 and X < 687.271)) then
player:startEvent(0x7d03); -- leave the battlefield
elseif (X > -25.684 and X < -13.684) then -- post-battlefield exit
player:startEvent(0x0007);
elseif (EventTriggerBCNM(player,npc)) then -- enter the battlefield
return 1;
else
player:messageSpecial(GLOWING_MIST); -- needs confirmation
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("onUpdate CSID: %u",csid);
--printf("onUpdate RESULT: %u",option);
if (EventUpdateBCNM(player,csid,option)) then
return;
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if (csid == 0x0B and option == 1) then
player:setPos(-508.582,-8.471,-387.670,92,30); -- To Riv Site A (Retail confirmed)
elseif (csid == 0x0A and option == 1) then
player:setPos(-533.690,-20.5,503.656,224,29); -- To Riv Site B (Retail confirmed)
elseif (csid == 0x0007 and option ==1) then
player:setPos(-538.526,-29.5,359.219,255,25); -- back to Misareaux Coast (Retail confirmed)
elseif (EventFinishBCNM(player,csid,option)) then
return;
end
end; | gpl-3.0 |
daVoodooShuffle/OpenRA | mods/d2k/maps/harkonnen-01a/harkonnen01a.lua | 10 | 5266 | --[[
Copyright 2007-2017 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
AtreidesReinforcements = { }
AtreidesReinforcements["easy"] =
{
{ "light_inf", "light_inf" }
}
AtreidesReinforcements["normal"] =
{
{ "light_inf", "light_inf" },
{ "light_inf", "light_inf", "light_inf" },
{ "light_inf", "trike" },
}
AtreidesReinforcements["hard"] =
{
{ "light_inf", "light_inf" },
{ "trike", "trike" },
{ "light_inf", "light_inf", "light_inf" },
{ "light_inf", "trike" },
{ "trike", "trike" }
}
AtreidesEntryWaypoints = { AtreidesWaypoint1.Location, AtreidesWaypoint2.Location, AtreidesWaypoint3.Location, AtreidesWaypoint4.Location }
AtreidesAttackDelay = DateTime.Seconds(30)
AtreidesAttackWaves = { }
AtreidesAttackWaves["easy"] = 1
AtreidesAttackWaves["normal"] = 5
AtreidesAttackWaves["hard"] = 12
ToHarvest = { }
ToHarvest["easy"] = 2500
ToHarvest["normal"] = 3000
ToHarvest["hard"] = 3500
HarkonnenReinforcements = { "light_inf", "light_inf", "light_inf", "trike" }
HarkonnenEntryPath = { HarkonnenWaypoint.Location, HarkonnenRally.Location }
Messages =
{
"Build a concrete foundation before placing your buildings.",
"Build a Wind Trap for power.",
"Build a Refinery to collect Spice.",
"Build a Silo to store additional Spice."
}
IdleHunt = function(actor)
if not actor.IsDead then
Trigger.OnIdle(actor, actor.Hunt)
end
end
Tick = function()
if AtreidesArrived and atreides.HasNoRequiredUnits() then
player.MarkCompletedObjective(KillAtreides)
end
if player.Resources > ToHarvest[Map.LobbyOption("difficulty")] - 1 then
player.MarkCompletedObjective(GatherSpice)
end
-- player has no Wind Trap
if (player.PowerProvided <= 20 or player.PowerState ~= "Normal") and DateTime.GameTime % DateTime.Seconds(32) == 0 then
HasPower = false
Media.DisplayMessage(Messages[2], "Mentat")
else
HasPower = true
end
-- player has no Refinery and no Silos
if HasPower and player.ResourceCapacity == 0 and DateTime.GameTime % DateTime.Seconds(32) == 0 then
Media.DisplayMessage(Messages[3], "Mentat")
end
if HasPower and player.Resources > player.ResourceCapacity * 0.8 and DateTime.GameTime % DateTime.Seconds(32) == 0 then
Media.DisplayMessage(Messages[4], "Mentat")
end
UserInterface.SetMissionText("Harvested resources: " .. player.Resources .. "/" .. ToHarvest[Map.LobbyOption("difficulty")], player.Color)
end
WorldLoaded = function()
player = Player.GetPlayer("Harkonnen")
atreides = Player.GetPlayer("Atreides")
InitObjectives()
Trigger.OnRemovedFromWorld(HarkonnenConyard, function()
local refs = Utils.Where(Map.ActorsInWorld, function(actor) return actor.Type == "refinery" end)
if #refs == 0 then
atreides.MarkCompletedObjective(KillHarkonnen)
else
Trigger.OnAllRemovedFromWorld(refs, function()
atreides.MarkCompletedObjective(KillHarkonnen)
end)
end
end)
Media.DisplayMessage(Messages[1], "Mentat")
Trigger.AfterDelay(DateTime.Seconds(25), function()
Media.PlaySpeechNotification(player, "Reinforce")
Reinforcements.Reinforce(player, HarkonnenReinforcements, HarkonnenEntryPath)
end)
WavesLeft = AtreidesAttackWaves[Map.LobbyOption("difficulty")]
SendReinforcements()
end
SendReinforcements = function()
local units = AtreidesReinforcements[Map.LobbyOption("difficulty")]
local delay = Utils.RandomInteger(AtreidesAttackDelay - DateTime.Seconds(2), AtreidesAttackDelay)
AtreidesAttackDelay = AtreidesAttackDelay - (#units * 3 - 3 - WavesLeft) * DateTime.Seconds(1)
if AtreidesAttackDelay < 0 then AtreidesAttackDelay = 0 end
Trigger.AfterDelay(delay, function()
Reinforcements.Reinforce(atreides, Utils.Random(units), { Utils.Random(AtreidesEntryWaypoints) }, 10, IdleHunt)
WavesLeft = WavesLeft - 1
if WavesLeft == 0 then
Trigger.AfterDelay(DateTime.Seconds(1), function() AtreidesArrived = true end)
else
SendReinforcements()
end
end)
end
InitObjectives = function()
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
KillHarkonnen = atreides.AddPrimaryObjective("Kill all Harkonnen units.")
GatherSpice = player.AddPrimaryObjective("Harvest " .. tostring(ToHarvest[Map.LobbyOption("difficulty")]) .. " Solaris worth of Spice.")
KillAtreides = player.AddSecondaryObjective("Eliminate all Atreides units and reinforcements\nin the area.")
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerLost(player, function()
Trigger.AfterDelay(DateTime.Seconds(1), function()
Media.PlaySpeechNotification(player, "Lose")
end)
end)
Trigger.OnPlayerWon(player, function()
Trigger.AfterDelay(DateTime.Seconds(1), function()
Media.PlaySpeechNotification(player, "Win")
end)
end)
end
| gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/North_Gustaberg/npcs/Quellebie_RK.lua | 4 | 2899 | -----------------------------------
-- Area: North Gustaberg
-- NPC: Quellebie, R.K.
-- Border Conquest Guards
-- @pos -520.704 38.75 560.258 106
-----------------------------------
package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/North_Gustaberg/TextIDs");
guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border
region = GUSTABERG;
csid = 0x7ffa;
-----------------------------------
-- 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
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
duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
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
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 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Port_San_dOria/npcs/Bricorsant.lua | 6 | 1319 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Bricorsant
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x23a);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/globals/items/serving_of_yellow_curry.lua | 35 | 2067 | -----------------------------------------
-- ID: 4517
-- Item: serving_of_yellow_curry
-- Food Effect: 3hours, All Races
-----------------------------------------
-- Health Points 20
-- Strength 5
-- Agility 2
-- Intelligence -4
-- HP Recovered While Healing 2
-- MP Recovered While Healing 1
-- Attack 20% (caps @ 75)
-- Ranged Attack 20% (caps @ 75)
-- Resist Sleep
-- Resist Stun
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4517);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 5);
target:addMod(MOD_AGI, 2);
target:addMod(MOD_INT, -4);
target:addMod(MOD_HPHEAL, 2);
target:addMod(MOD_MPHEAL, 1);
target:addMod(MOD_FOOD_ATTP, 20);
target:addMod(MOD_FOOD_ATT_CAP, 75);
target:addMod(MOD_FOOD_RATTP, 20);
target:addMod(MOD_FOOD_RATT_CAP, 75);
target:addMod(MOD_SLEEPRES, 7);
target:addMod(MOD_STUNRES, 7);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 5);
target:delMod(MOD_AGI, 2);
target:delMod(MOD_INT, -4);
target:delMod(MOD_HPHEAL, 2);
target:delMod(MOD_MPHEAL, 1);
target:delMod(MOD_FOOD_ATTP, 20);
target:delMod(MOD_FOOD_ATT_CAP, 75);
target:delMod(MOD_FOOD_RATTP, 20);
target:delMod(MOD_FOOD_RATT_CAP, 75);
target:delMod(MOD_SLEEPRES, 7);
target:delMod(MOD_STUNRES, 7);
end;
| gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/zones/Southern_San_dOria/npcs/Aravoge_TK.lua | 28 | 4900 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Aravoge, T.K.
-- X Grant Signet
-- X Recharge Emperor Band, Empress Band, or Chariot Band
-- X Accepts traded Crystals to fill up the Rank bar to open new Missions.
-- X Sells items in exchange for Conquest Points
-- X Start Supply Run Missions and offers a list of already-delivered supplies.
-- Start an Expeditionary Force by giving an E.F. region insignia to you.
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/conquest");
require("scripts/globals/common");
require("scripts/zones/Southern_San_dOria/TextIDs");
local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, JEUNO
local guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border
local size = table.getn(SandInv);
local inventory = SandInv;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getNation() == guardnation and player:getVar("supplyQuest_started") > 0 and supplyRunFresh(player) == 0) then
player:showText(npc,CONQUEST + 40); -- "We will dispose of those unusable supplies."
local region = player:getVar("supplyQuest_region");
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1,getSupplyKey(region));
player:setVar("supplyQuest_started",0);
player:setVar("supplyQuest_region",0);
player:setVar("supplyQuest_fresh",0);
else
local Menu1 = getArg1(guardnation,player);
local Menu2 = getExForceAvailable(guardnation,player);
local Menu3 = conquestRanking();
local Menu4 = getSupplyAvailable(guardnation,player);
local Menu5 = player:getNationTeleport(guardnation);
local Menu6 = getArg6(player);
local Menu7 = player:getCP();
local Menu8 = getRewardExForce(guardnation,player);
player:startEvent(0x7ffa,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdateCSID: %u",csid);
-- printf("onUpdateOPTION: %u",option);
if (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
CPVerify = 1;
if (player:getCP() >= inventory[Item + 1]) then
CPVerify = 0;
end;
player:updateEvent(2,CPVerify,inventory[Item + 2]);
break;
end;
end;
end;
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinishCSID: %u",csid);
-- printf("onFinishOPTION: %u",option);
if (option == 1) then
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 >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
if (player:getFreeSlotsCount() >= 1) then
-- Logic to impose limits on exp bands
if (option >= 32933 and option <= 32935) then
if (checkConquestRing(player) > 0) then
player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]);
break;
else
player:setVar("CONQUEST_RING_TIMER",getConquestTally());
end
end
if (player:getNation() == guardnation) then
itemCP = inventory[Item + 1];
else
if (inventory[Item + 1] <= 8000) then
itemCP = inventory[Item + 1] * 2;
else
itemCP = inventory[Item + 1] + 8000;
end;
end;
if (player:hasItem(inventory[Item + 2]) == false) then
player:delCP(itemCP);
player:addItem(inventory[Item + 2],1);
player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end;
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end;
break;
end;
end;
elseif (option >= 65541 and option <= 65565) then -- player chose supply quest.
local region = option - 65541;
player:addKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED,getSupplyKey(region));
player:setVar("supplyQuest_started",vanaDay());
player:setVar("supplyQuest_region",region);
player:setVar("supplyQuest_fresh",getConquestTally());
end;
end; | gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/zones/LaLoff_Amphitheater/mobs/Ark_Angel_EV.lua | 27 | 1471 | -----------------------------------
-- Area: LaLoff Amphitheater
-- NPC: Ark Angel EV
-----------------------------------
require("scripts/globals/status");
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
function onMobInitialize(mob)
mob:addMod(MOD_REGAIN, 50);
end;
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
local mobid = mob:getID()
for member = mobid-4, mobid+3 do
if (GetMobAction(member) == 16) then
GetMobByID(member):updateEnmity(target);
end
end
local hp = math.random(40,60)
mob:setLocalVar("Benediction", hp);
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
local battletime = mob:getBattleTime();
local invtime = mob:getLocalVar("Invincible");
local bhp = mob:getLocalVar("Benediction");
if (battletime > invtime + 150) then
mob:useMobAbility(438);
mob:setLocalVar("Invincible", battletime);
elseif (mob:getHPP() < bhp) then
mob:useMobAbility(433);
mob:setLocalVar("Benediction", 0);
end
end;
-----------------------------------
-- onMobDeath Action
-----------------------------------
function onMobDeath(mob,killer)
end;
| gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Quicksand_Caves/mobs/Centurio_IV-VII.lua | 2 | 1073 | -- Centurio IV-VII
-- by ReaperX (Convert to DSP by Hypnotoad)
-- Pops in Bastok mission 8-1 "The Chains that Bind Us"
require("scripts/globals/settings");
require("scripts/zones/Quicksand_Caves/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
-- print(mob:getName());
end;
function onMobDeath(mob,killer)
if(killer:getCurrentMission(BASTOK) == THE_CHAINS_THAT_BIND_US) and (killer:getVar("MissionStatus") == 1) then
SetServerVariable("Bastok8-1LastClear", os.time());
end
end;
function onMobEngaged(mob, target)
end;
function onMobDisengage(mob)
-- printf("Disengaging Centurio");
local self = mob:getID();
DespawnMob(self, 120);
end;
function onMobDespawn(mob)
-- printf("Despawning Centurio");
local mobsup = GetServerVariable("BastokFight8_1");
SetServerVariable("BastokFight8_1",mobsup - 1);
if(GetServerVariable("BastokFight8_1") == 0) then
-- printf("No more mobs: last is Centurio");
local npc = GetNPCByID(17629728);
npc:setStatus(0); -- Reappear
end
end;
| gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/zones/West_Ronfaure/npcs/Colmaie.lua | 19 | 1122 | -----------------------------------
-- Area: West Ronfaure
-- NPC: Colmaie
-- Type: Standard NPC
-- @pos -133.627 -61.999 272.373 100
-----------------------------------
package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local thePickpocket = player:getQuestStatus(SANDORIA, THE_PICKPOCKET);
if (thePickpocket > 0) then
player:showText(npc, 7263);
else
player:showText(npc, COLMAIE_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/globals/items/icefish.lua | 18 | 1317 | -----------------------------------------
-- ID: 4470
-- Item: icefish
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 3
-- Mind -5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 7) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4470);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 3);
target:addMod(MOD_MND, -5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 3);
target:delMod(MOD_MND, -5);
end;
| gpl-3.0 |
Sonicrich05/FFXI-Server | scripts/zones/West_Ronfaure/npcs/Phairet.lua | 17 | 2450 | -----------------------------------
-- Area: West Ronfaure
-- NPC: Phairet
-- Involved in Quest: The Trader in the Forest
-- @pos -57 -1 -501 100
-----------------------------------
package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/West_Ronfaure/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local theTraderInTheforest = player:getQuestStatus(SANDORIA,THE_TRADER_IN_THE_FOREST);
if (theTraderInTheforest == QUEST_ACCEPTED) then
if (trade:hasItemQty(592,1) == true and trade:getItemCount() == 1) then -- Trade Supplies Order
player:startEvent(0x007c);
end
elseif (theTraderInTheforest == QUEST_COMPLETED) then
if (trade:getGil() == 50) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4367);
else
player:tradeComplete();
player:addItem(4367);
player:messageSpecial(ITEM_OBTAINED,4367); -- Clump of Batagreens
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local theTraderInTheforest = player:getQuestStatus(SANDORIA,THE_TRADER_IN_THE_FOREST);
local hasBatagreens = player:hasItem(4367); -- Clump of Batagreens
if (theTraderInTheforest == QUEST_ACCEPTED) then
if (hasBatagreens == true) then
player:startEvent(0x007d);
else
player:startEvent(0x0075);
end
elseif (theTraderInTheforest == QUEST_COMPLETED or hasBatagreens == false) then
player:startEvent(0x007f,4367);
else
player:startEvent(0x0075);
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 == 0x007c) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4367);
else
player:tradeComplete();
player:addItem(4367);
player:messageSpecial(ITEM_OBTAINED, 4367);
end
end
end; | gpl-3.0 |
fruitwasp/DarkRP | gamemode/modules/fadmin/fadmin/playeractions/voicemute/cl_init.lua | 10 | 3196 | hook.Add("PlayerBindPress", "FAdmin_voicemuted", function(ply, bind, pressed)
if ply:FAdmin_GetGlobal("FAdmin_voicemuted") and string.find(string.lower(bind), "voicerecord") then return true end
-- The voice muting is not done clientside, this is just so people know they can't talk
end)
FAdmin.StartHooks["VoiceMute"] = function()
FAdmin.Messages.RegisterNotification{
name = "voicemute",
hasTarget = true,
message = {"instigator", " voice muted ", "targets", " ", "extraInfo.1"},
readExtraInfo = function()
local time = net.ReadUInt(16)
return {time == 0 and FAdmin.PlayerActions.commonTimes[time] or string.format("for %s", FAdmin.PlayerActions.commonTimes[time] or (time .. " seconds"))}
end
}
FAdmin.Messages.RegisterNotification{
name = "voiceunmute",
hasTarget = true,
message = {"instigator", " voice unmuted ", "targets"}
}
FAdmin.Access.AddPrivilege("Voicemute", 2)
FAdmin.Commands.AddCommand("Voicemute", nil, "<Player>")
FAdmin.Commands.AddCommand("UnVoicemute", nil, "<Player>")
FAdmin.ScoreBoard.Player:AddActionButton(function(ply)
if ply:FAdmin_GetGlobal("FAdmin_voicemuted") then return "Unmute voice globally" end
return "Mute voice globally"
end,
function(ply)
if ply:FAdmin_GetGlobal("FAdmin_voicemuted") then return "fadmin/icons/voicemute" end
return "fadmin/icons/voicemute", "fadmin/icons/disable"
end,
Color(255, 130, 0, 255),
function(ply) return FAdmin.Access.PlayerHasPrivilege(LocalPlayer(), "Voicemute", ply) end,
function(ply, button)
if not ply:FAdmin_GetGlobal("FAdmin_voicemuted") then
FAdmin.PlayerActions.addTimeMenu(function(secs)
RunConsoleCommand("_FAdmin", "Voicemute", ply:UserID(), secs)
button:SetImage2("null")
button:SetText("Unmute voice globally")
button:GetParent():InvalidateLayout()
end)
else
RunConsoleCommand("_FAdmin", "UnVoicemute", ply:UserID())
end
button:SetImage2("fadmin/icons/disable")
button:SetText("Mute voice globally")
button:GetParent():InvalidateLayout()
end)
FAdmin.ScoreBoard.Player:AddActionButton(function(ply)
return ply.FAdminMuted and "Unmute voice" or "Mute voice"
end,
function(ply)
if ply.FAdminMuted then return "fadmin/icons/voicemute" end
return "fadmin/icons/voicemute", "fadmin/icons/disable"
end,
Color(255, 130, 0, 255),
true,
function(ply, button)
ply:SetMuted(not ply.FAdminMuted)
ply.FAdminMuted = not ply.FAdminMuted
if ply.FAdminMuted then button:SetImage2("null") button:SetText("Unmute voice") button:GetParent():InvalidateLayout() return end
button:SetImage2("fadmin/icons/disable")
button:SetText("Mute voice")
button:GetParent():InvalidateLayout()
end)
FAdmin.ScoreBoard.Main.AddPlayerRightClick("Mute/Unmute", function(ply, Panel)
ply:SetMuted(not ply.FAdminMuted)
ply.FAdminMuted = not ply.FAdminMuted
end)
end
| mit |
Sonicrich05/FFXI-Server | scripts/zones/RuLude_Gardens/npcs/Marshal.lua | 38 | 1032 | -----------------------------------
-- Area: Ru'Lude Gardens
-- NPC: Marshal
-- Type: Marshal
-- @zone: 243
-- @pos 41.143 -0.998 -26.566
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x002c);
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 |
Sonicrich05/FFXI-Server | scripts/zones/Chateau_dOraguille/npcs/Curilla.lua | 17 | 5152 | -----------------------------------
-- Area: Chateau d'Oraguille
-- NPC: Curilla
-- Starts and Finishes Quest: The General's Secret, Enveloped in Darkness, Peace for the Spirit, Lure of the Wildcat (San d'Oria)
-- @pos 27 0.1 0.1 233
-----------------------------------
package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Chateau_dOraguille/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local mLvL = player:getMainLvl();
local mJob = player:getMainJob();
local theGeneralSecret = player:getQuestStatus(SANDORIA,THE_GENERAL_S_SECRET);
local envelopedInDarkness = player:getQuestStatus(SANDORIA,ENVELOPED_IN_DARKNESS);
local peaceForTheSpirit = player:getQuestStatus(SANDORIA,PEACE_FOR_THE_SPIRIT);
local WildcatSandy = player:getVar("WildcatSandy");
if (player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,15) == false) then
player:startEvent(0x0232);
elseif (theGeneralSecret == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 2) then
player:startEvent(0x0037); -- Start Quest "The General's Secret"
elseif (mJob == 5 and mLvL >= AF2_QUEST_LEVEL and player:getQuestStatus(SANDORIA,THE_CRIMSON_TRIAL) == QUEST_COMPLETED and envelopedInDarkness == QUEST_AVAILABLE) then
player:startEvent(0x005E); -- Start Quest "Enveloped in Darkness"
elseif (player:hasKeyItem(OLD_POCKET_WATCH) and player:hasKeyItem(OLD_BOOTS) == false) then
player:startEvent(0x005D);
elseif (player:hasKeyItem(OLD_BOOTS) and player:getVar("needs_crawler_blood") == 0) then
player:startEvent(0x0065);
elseif (player:getVar("needs_crawler_blood") == 1) then
player:startEvent(0x0075);
elseif (mJob == 5 and mLvL >= AF2_QUEST_LEVEL and envelopedInDarkness == QUEST_COMPLETED and peaceForTheSpirit == QUEST_AVAILABLE) then
player:startEvent(0x006D); -- Start Quest "Peace for the Spirit"
elseif (peaceForTheSpirit == QUEST_ACCEPTED) then
player:startEvent(0x006C); -- Standard dialog during Peace of the spirit
elseif (peaceForTheSpirit == QUEST_ACCEPTED and (player:getVar("peaceForTheSpiritCS") >= 2 and player:getVar("peaceForTheSpiritCS") <= 4)) then
player:startEvent(0x0071);
elseif (peaceForTheSpirit == QUEST_ACCEPTED and player:getVar("peaceForTheSpiritCS") == 5) then
player:startEvent(0x0033);
elseif (theGeneralSecret == QUEST_ACCEPTED and player:hasKeyItem(CURILLAS_BOTTLE_EMPTY)) then
player:startEvent(0x0035);
elseif (theGeneralSecret == QUEST_ACCEPTED and player:hasKeyItem(CURILLAS_BOTTLE_FULL)) then
player:startEvent(0x0036);
elseif (envelopedInDarkness == QUEST_COMPLETED and peaceForTheSpirit == QUEST_AVAILABLE) then
player:startEvent(0x0072); -- Standard dialog after Enveloped in darkness
elseif (peaceForTheSpirit == QUEST_COMPLETED) then
player:startEvent(0x0034); -- Standard dialog after Peace of the spirit
else
player:startEvent(0x0212); -- 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 == 0x0037 and option == 1) then
player:addQuest(SANDORIA,THE_GENERAL_S_SECRET)
player:addKeyItem(CURILLAS_BOTTLE_EMPTY);
player:messageSpecial(KEYITEM_OBTAINED,CURILLAS_BOTTLE_EMPTY);
elseif (csid == 0x0036) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,16409); -- Lynx Baghnakhs
else
player:delKeyItem(CURILLAS_BOTTLE_FULL);
player:addItem(16409);
player:messageSpecial(ITEM_OBTAINED,16409); -- Lynx Baghnakhs
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA,THE_GENERAL_S_SECRET);
end
elseif (csid == 0x005E and option == 1) then
player:addQuest(SANDORIA,ENVELOPED_IN_DARKNESS);
player:addKeyItem(OLD_POCKET_WATCH);
player:messageSpecial(KEYITEM_OBTAINED,OLD_POCKET_WATCH);
elseif (csid == 0x006D and option == 1) then
player:addQuest(SANDORIA,PEACE_FOR_THE_SPIRIT);
player:setVar("needs_crawler_blood",0);
elseif (csid == 0x0065) then
player:setVar("needs_crawler_blood",1);
elseif (csid == 0x0232) then
player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",15,true);
end
end;
| gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Windurst_Waters_[S]/npcs/Yasmina.lua | 2 | 1059 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Yasmina
-- Type: Chocobo Renter
-- @zone: 94
-- @pos: -34.972 -5.815 221.845
--
-- 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(0x0006, 10, 10);
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 |
RavenX8/osIROSE-new | scripts/mobs/ai/jewel_golem.lua | 2 | 1944 | registerNpc(161, {
walk_speed = 250,
run_speed = 700,
scale = 200,
r_weapon = 0,
l_weapon = 0,
level = 47,
hp = 74,
attack = 253,
hit = 164,
def = 168,
res = 102,
avoid = 57,
attack_spd = 90,
is_magic_damage = 0,
ai_type = 9,
give_exp = 167,
drop_type = 179,
drop_money = 1,
drop_item = 70,
union_number = 70,
need_summon_count = 0,
sell_tab0 = 0,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 220,
npc_type = 10,
hit_material_type = 2,
face_icon = 0,
summon_mob_type = 0,
quest_type = 0,
height = 0
});
registerNpc(924, {
walk_speed = 250,
run_speed = 500,
scale = 260,
r_weapon = 0,
l_weapon = 0,
level = 62,
hp = 2593,
attack = 222,
hit = 179,
def = 202,
res = 87,
avoid = 79,
attack_spd = 80,
is_magic_damage = 0,
ai_type = 167,
give_exp = 0,
drop_type = 3,
drop_money = 0,
drop_item = 100,
union_number = 100,
need_summon_count = 33,
sell_tab0 = 33,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 250,
npc_type = 0,
hit_material_type = 2,
face_icon = 0,
summon_mob_type = 0,
quest_type = 0,
height = 0
});
function OnInit(entity)
return true
end
function OnCreate(entity)
return true
end
function OnDelete(entity)
return true
end
function OnDead(entity)
end
function OnDamaged(entity)
end | apache-2.0 |
Sonicrich05/FFXI-Server | scripts/zones/Temenos/bcnms/Central_Temenos_3rd_Floor.lua | 19 | 1076 | -----------------------------------
-- Area: Temenos
-- Name:
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
SetServerVariable("[C_Temenos_3rd]UniqueID",GenerateLimbusKey());
HideArmouryCrates(GetInstanceRegion(1305),TEMENOS);
HideTemenosDoor(GetInstanceRegion(1305));
player:setVar("Limbus_Trade_Item-T",0);
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
player:setVar("limbusbitmap",0);
player:setVar("characterLimbusKey",GetServerVariable("[C_Temenos_3rd]UniqueID"));
player:setVar("LimbusID",1305);
player:delKeyItem(COSMOCLEANSE);
player:delKeyItem(WHITE_CARD);
end;
-- Leaving by every mean possible, given by the LeaveCode
-- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3)
-- 4=Finish he dynamis
function onBcnmLeave(player,instance,leavecode)
--print("leave code "..leavecode);
if (leavecode == 4) then
player:setPos(580,-1.5,4.452,192);
ResetPlayerLimbusVariable(player)
end
end; | gpl-3.0 |
kidaa/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Beaucedine_Glacier/Zone.lua | 3 | 1891 | -----------------------------------
--
-- Zone: Beaucedine_Glacier (111)
--
-----------------------------------
package.loaded[ "scripts/zones/Beaucedine_Glacier/TextIDs"] = nil;
require( "scripts/zones/Beaucedine_Glacier/TextIDs");
require( "scripts/globals/missions");
require( "scripts/globals/icanheararainbow");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize( zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn( player, prevZone)
cs = -1;
if(prevZone == 134) then -- warp player to a correct position after dynamis
player:setPos(-284.751,-39.923,-422.948,235);
end
if( player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos( -247.911, -82.165, 260.207, 248);
end
if( player:getCurrentMission( COP) == DESIRES_OF_EMPTINESS and player:getVar( "PromathiaStatus") == 9) then
cs = 0x00CE;
elseif( triggerLightCutscene( player)) then -- Quest: I Can Hear A Rainbow
cs = 0x0072;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter( player, region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate( player, csid, option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0072) 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 == 0x00CE) then
player:setVar("PromathiaStatus",10);
elseif( csid == 0x0072) then
lightCutsceneFinish( player); -- Quest: I Can Hear A Rainbow
end
end;
| gpl-3.0 |
rlowrance/re | lua/incorporate-errors.lua | 1 | 26715 | -- incorporate-errors.lua
-- Read an estimated file and completed matrix file in order to build
-- a new estimates file correcting all the estimates using the errors
-- in the completed matrix file.
-- Input files:
-- ERRORS/all-estimates-mc.csv : apn x month error estimates
-- OBS/analysis/RESULTS/estimates-laufer.csv : apn x quarter price estimates
-- Output files:
-- ANALYSIS/RESULTS/estimates-stage2.csv
-- ANALYSIS/RESULTS/log.txt
-- CSV file schema
-- all-laufer.csv: apn, date, radius, estimatedPrice
-- where dates are midpoints in quarters
-- years = 2000, 2001, ..., 2009
-- all-estimates-mc.csv: apn, date, radius, estimatedPrice
-- where dates are mid points of each month
-- estimates-completed.csv: apn, date, radiues, stage2Price
-- where dates are mid points of each quarter
require 'affirm'
require 'assertEqual'
require 'createResultsDirectoryName'
require 'CsvUtils'
require 'IncompleteMatrix'
require 'Log'
require 'makeVerbose'
require 'parseCommandLine'
require 'printOptions'
require 'TimerCpu'
--------------------------------------------------------------------------------
-- IncorporateErrors: CONSTRUCTION
--------------------------------------------------------------------------------
torch.class('IncorporateErrors')
function IncorporateErrors:__init()
-- define option defaults and explanations
self.optionDefaults = {}
self.optionExplanations = {}
local function def(option, default, explanation)
self.optionDefaults[option] = default
self.optionExplanations[option] = explanation
end
def('algo', '', 'Name of algorithm; in {knn, kwavg, llr}')
def('dataDir', '../../data/','Path to data directory')
def('obs', '', 'Observation set')
def('test', 0, 'Set to 1 for testing (truncate input)')
def('write', 0, 'Whether to write the estimates')
end -- __init
--------------------------------------------------------------------------------
-- IncoporateErrors: PUBLIC METHODS
--------------------------------------------------------------------------------
function IncorporateErrors:getOptionDefaults()
-- return table of option names and default values for each
return self.optionDefaults
end
function IncorporateErrors:getOptionExplanations()
-- return table of option names and explanations for each
return self.optionExplanations
end
function IncorporateErrors:worker(options, mainProgramName)
-- main program
local v = makeVerbose(true, 'IncorporateErrors:worker')
v('options', options)
v('mainProgramName', mainProgramName)
affirm.isTable(options, 'options')
affirm.isString(mainProgramName, 'mainProgramName')
self:_validateOptions(options)
--setRandomSeeds(options.seed)
local paths = self:_setupPaths(options, mainProgramName)
local log = self:_startLogging(paths.dirResults)
-- log the command line parameters
printOptions(options, log)
-- log paths used
log:log(' ')
log:log('Paths used')
for k, v in pairs(paths) do
log:log('%-20s = %s', k, v)
end
local errors = self:_readErrors(options, log, paths)
local prices = self:_readPrices(options, log, paths)
local stage2Estimates = self:_incorporateErrrors(errors,
options,
prices,
log)
self:_writeStage2Estimates(log, options, paths, stage2Estimates)
printOptions(options, log)
log:log('torch.initialSeed()', torch.initialSeed())
if options.test == 1 then
log:log('TESTING')
end
log:log('consider commiting the source code')
log:log('\nfinished')
log:close()
end -- worker
--------------------------------------------------------------------------------
-- IncorporateErrors: PRIVATE METHODS
--------------------------------------------------------------------------------
function IncorporateErrors:_isMidQuarter(date)
-- return true iff date is mid quarter
local day = string.sub(date, 7, 8)
if day ~= '15' then
return false
end
local month = string.sub(date, 5, 6)
if month == '02' or month == '05' or month == '08' or month == '11' then
return true
else
return false
end
end -- _isMidQuarter
function IncorporateErrors:_parseFields(line, log, hasRadius)
-- given input line, return ok, apn, date, number
-- where
-- ok = true, indicates other values are OK
-- ok = false, indicates other values are not supplied
local v = makeVerbose(true, 'IncorporateErrors:_parseFields')
v('line', line)
local hasRadius = hasRadius or false
local apn, date, numberString
if hasRadius then
apn, date, numberString =
string.match(line, '(%d+),(%d+),%d+,([%-%d%.]+)')
else
apn, date, numberString =
string.match(line, '(%d+),(%d+),([%-%d%.]+)')
end
v('apn,date,number', apn, date, numberString)
if apn == nil or
date == nil or
numberString == nil then
log:log('not parsed: %s', line)
return false
end
if string.len(apn) ~= 10 then
log:log('apn not 10 characters: %s', apn)
return false
end
if string.len(date) ~= 8 then
log:log('date not 8 character: %s', date)
return false
end
if string.sub(date, 7, 8) ~= '15' then
log:log('date not mid month: %s', date)
return false
end
local number = tonumber(numberString)
if not number then
log:log('not a number: %s', numberString)
return false
end
return true, apn, date, number
end -- _parseFields
function IncorporateErrors:_readApnDateNumber(path, options, log)
-- read input file
-- return table with key==apn..date value==number containing
-- just values at mid quarter
-- ARGS
-- path : string, path to input CSV file
-- fields in the CSV file are: apn, date, ignored, number
-- options : table of options
-- log : Log instance
-- RETURNS
-- table : table with
-- key == apn .. date (both strings)
-- value == the number in the file
local v = makeVerbose(true, 'IncorporateErrors:_readApnDateNumber')
v('path', path)
v('options', options)
v('log', log)
local input = io.open(path)
if input == nil then
error('unable to open CSV; path = ' .. path)
end
local header = input:read()
print('header', header)
result = {}
local countInput = 0
local countNotMidQuarter = 0
local countUsed = 0
for line in input:lines('*l') do
countInput = countInput + 1
if options.test == 1 and
countInput > 1000
then
break
end
local ok, apn, date, number = self:_parseFields(line, log)
v('ok,apn,date,number', ok, apn, date, number)
if ok then
if self:_isMidQuarter(date) then
result[apn..date] = number
countUsed = countUsed + 1
if countInput % 1000000 == 0 then
print(
string.format('used: countInput %d apn %s date %s number %f',
countInput, apn, date, number))
end
else
countNotMidQuarter = countNotMidQuarter + 1
end
else
-- bad input record
halt() -- for now, later log and count
end
end
log:log('File contained %d data records', countInput)
log:log(' %d were not for the mid-quarter date, hence not used',
countNotMidQuarter)
log:log(' %d of these were for mid-quarter date, hence use', countUsed)
return result
end -- _readApnDateNumber
function IncorporateErrors:_readErrors(options, log, paths)
-- read the file with the completed error matrix
-- return table key == apn..date value == the error
return self:_readApnDateNumber(paths.fileErrors, options, log)
end -- _readErrors
function IncorporateErrors:_readPrices(options, log, paths)
local hasRadius = true
return self:_readApnDateNumber(paths.fileStage1, options, log, hasRadius)
end -- _readPrices
function IncorporateErrors:_setupPaths(options, programName)
-- establish paths to directories and files
-- ARGS
-- options: table of parsed command line parameters
-- programName : string, name of the lua executable
-- RETURNS table of paths with these fields
-- fileErrors : string, path to error file
-- fileStage1 : string, path to stage 1 estimates
-- dirResults : string, path to results directory
local v = makeVerbose(false, 'IncorporateErrors:_setupPaths')
v('options', options)
v('programName', programName)
affirm.isTable(options, 'options')
affirm.isString(programName, 'programName')
local dirObs = options.dataDir .. 'generated-v4/obs' .. options.obs .. '/'
local dirAnalysis = dirObs .. 'analysis/'
local paths = {}
-- replace .'s in program name with -'s
paths.dirResults =
dirAnalysis ..
createResultsDirectoryName(string.gsub(programName, '%.', '-'),
options,
self.optionDefaults) .. '/'
local function radius()
if options.algo == 'knn' and options.obs == '1A' then
return '76'
else
error('unimplemented algo/obs combination')
end
end -- radius
local function rank()
if options.algo == 'knn' and options.obs == '1A' then
return '1'
else
error('unimplemented algo/obs combination')
end
end -- rank
paths.fileErrors =
dirAnalysis ..
'complete-matrix-lua,' ..
'algo=' .. options.algo .. ',' ..
'col=month,' ..
'obs=' .. options.obs .. ',' ..
'radius=' .. radius() .. ',' ..
'rank=' .. rank() .. ',' ..
'which=complete,' ..
'write=1,' ..
'yearFirst=1984/' ..
'all-estimates-mc.csv'
paths.fileStage1 =
dirAnalysis ..
'create-estimates-lua,' ..
'algo=' .. options.algo .. ',' ..
'obs=' .. options.obs .. ',' ..
'radius=' .. radius() .. ',' ..
'which=mc/' ..
'estimates-mc.csv'
v('paths', paths)
return paths
end -- _setupPaths
function IncorporateErrors:_startLogging(dirResults)
-- create log object and results directory; start logging
-- ARG
-- dirResults: string, path to directory
-- RETURN
-- log: instance of Log
assert(dirResults)
local command = 'mkdir ' .. dirResults .. ' -p' -- no error if exists
if not os.execute(command) then
print('results directory not created', command)
os.exit(false) -- exit with return status EXIT_FAILURE
end
-- create log file
pathLogFile = dirResults .. 'log.txt'
local log = Log(pathLogFile)
log:log('log started on ' .. os.date())
return log
end -- _startLogging
function IncorporateErrors:_optionError(msg)
-- report an error in an option
-- print all the options available
print('AN ERROR WAS FOUND IN AN OPTION')
print(msg)
print('\nAvailable options, defaults, and explanations are')
local sortedKeys = sortedKeys(options)
for i = 1,#sortedKeys do
local name = sortedKeys[i]
local default = self.optionDefaults[name]
local explanation = self.optionExplanations[name]
print(string.format('%17s %-12s %s',
name, tostring(default), explanation))
end
error('invalid option: ' .. msg)
end -- _optionError
function IncorporateErrors:_validateOptions(options)
-- validate options that were supplied and set default values for those not
-- supplied
-- validate that no extra options were supplied
-- check for extra options
for name in pairs(options) do
if self.optionDefaults[name] == nil then
self:_optionError('extra option: ' .. name)
end
end
-- supply defaults for any missing option values
for name, default in pairs(self.optionDefaults) do
if options[name] == nil then
options[name] = default
end
end
-- validate all the option values
-- check for missing required options
function missing(name)
self:_optionError('missing option -' .. name)
end
if options.algo == '' then missing('algo') end
if options.dataDir == '' then missing('dataDir') end
if options.obs == '' then missing('obs') end
-- check for allowed parameter values
if not check.isString(options.algo) or
not options.algo == 'knn'
then
self:_optionError('algo must be knn (for now)')
end
if not check.isString(options.dataDir) then
self:_optionValue('dataDir must be a string')
end
if not check.isString(options.obs) or
not (options.obs == '1A' or
options.obs == '2R' or
options.obs == '2A')
then
self:_optionValue('obs must be 1A, 2R, or 2A')
end
if not check.isInteger(options.test) or
not (options.test == 0 or
options.test == 1)
then
self:_optionValue('test must be 0 or 1')
end
if not check.isInteger(options.write) or
not (options.write == 0 or
options.write == 1)
then
self:_optionValue('write must be 0 or 1')
end
end -- _validateOptions
--------------------------------------------------------------------------------
-- MAIN
--------------------------------------------------------------------------------
local incorporateErrors = IncorporateErrors()
local options = parseCommandLine(arg,
'incorporate errors into estimates',
incorporateErrors:getOptionDefaults(),
incorporateErrors:getOptionExplanations())
incorporateErrors:worker(options,
'incorporate-errors.lua')
-------------------------- OLD CODE BELOW ME
--------------------------------------------------------------------------------
-- continue: print msg and wait for keystroke
--------------------------------------------------------------------------------
function continue(...)
print(...)
print('hit ENTER to continue')
io.read()
end
--------------------------------------------------------------------------------
-- printParams
--------------------------------------------------------------------------------
-- print or log parameters
function printParams(params, log)
if log then
log:log('Command line parameters')
else
print('Command line parameters')
end
keys = {}
for k in pairs(params) do
keys[#keys + 1] = k
end
table.sort(keys)
for i = 1, #keys do
local key = keys[i]
local value = params[key]
local line = string.format('%17s %s', key, value)
if log then
log:log(line)
else
print(line)
end
end
end
--------------------------------------------------------------------------------
-- readCommandLine: parse and validate command line
--------------------------------------------------------------------------------
-- ARGS
-- arg : Lua's command line arg object
-- RETURNS:
-- cmd : object used to parse the args
-- params : table of parameters found
function readCommandLine(arg)
cmd = torch.CmdLine()
cmd:text('Incorporate errors into stage 1 estimates')
cmd:text()
cmd:text('Run from lua directory')
cmd:text()
cmd:text('Options')
cmd:option('-algo', '', 'for now, "knn"')
cmd:option('-dataDir', '../../data/', 'Path to data directory')
cmd:option('-obs', '', 'obs set, only "1A" for now')
cmd:option('-inRank', 0, 'ID for error input file')
cmd:option('-inTimeSgd', 0, 'seconds used in complete-matrix')
-- parse command line
params = cmd:parse(arg)
-- check for missing required command line parameters
if params.algo == '' then
error('missing -algo parameters')
end
if params.obs == '' then
error('missing -obs parameter')
end
function check(name, allowed)
local value = params[name]
if value == 0 then
error('missing parameter -' .. name)
end
if not (value == math.floor(value)) then
error(string.format('parameter %s must be an integer', name))
end
if value ~= allowed then
error(string.format('parameter -%s must be %d', name, max))
end
end
-- check for presence on command line and allowed values
check('inRank', 1) -- for now, just 1 allowed value
if params.inTimeSgd == 0 then
error('missing parameter -inTimeSgd')
end
if params.obs == nil then
error('must supply -obs parameter')
end
return cmd, params
end
--------------------------------------------------------------------------------
-- setupDirectories
--------------------------------------------------------------------------------
-- determine directories
-- ARGS:
-- cmd : CmdLine object used to parse args
-- params : table of parsed command line parameters
-- RESULTS:
-- dirInErrors : string
-- dirInPrices : string
-- dirResults : string
function setupDirectories(cmd, params)
local programName = 'incorporate-errors-lua'
local dirObs = params.dataDir .. 'generated-v4/obs' .. params.obs .. '/'
local dirAnalysis = dirObs .. 'analysis/'
local dirFeatures = dirObs .. 'features/'
local function makeInDirErrors(rank, timeSgd)
assert(rank)
assert(timeSgd)
local result =
dirAnalysis ..
'complete-matrix-lua,' ..
'algo=' .. params.algo .. ',' ..
'col=month,' ..
'learningRate=0.1,' ..
'learningRateDecay=0.1,' ..
'obs=1A,' ..
'radius=76,' ..
'rank=' .. tostring(rank) .. ',' ..
'timeLbfgs=600,' ..
'timeSgd=' .. tostring(timeSgd) .. ',' ..
'which=complete,' ..
'write=yes,' ..
'yearFirst=1984' ..
'/'
return result
end
local dirInErrors = makeInDirErrors(params.inRank,
params.inTimeSgd)
local dirInPrices =
dirAnalysis ..
'create-estimates-lua,' ..
'algo=' .. params.algo .. ',' ..
'obs=' .. params.obs .. ',' ..
'radius=76,' ..
'which=laufer' ..
'/'
local dirResults = dirAnalysis .. cmd:string(programName,
params,
{}) .. '/'
return dirInErrors, dirInPrices, dirResults
end -- setupDirectories
--------------------------------------------------------------------------------
-- startLogging: create log file and results directory; start logging
--------------------------------------------------------------------------------
-- ARG
-- dirResults: string, path to directory
-- RETURN
-- log: instance of Log
function startLogging(dirResults)
local command = 'mkdir ' .. dirResults .. ' -p' -- no error if exists
if not os.execute(command) then
print('results directory not created', command)
os.exit(false) -- exit with return status EXIT_FAILURE
end
-- create log file
pathLogFile = dirResults .. 'log.txt'
local log = Log(pathLogFile)
log:log('log started on ' .. os.date())
return log
end
--------------------------------------------------------------------------------
-- printTableHead: print first 10 records of table
--------------------------------------------------------------------------------
-- t is a table of tables
function printTableHead(name, t)
print()
print(name)
local count = 0
for k, v in pairs(t) do
print(k, v)
count = count + 1
if (count > 10) then break end
end
end
--------------------------------------------------------------------------------
-- isMidQuarter
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- readFileApnDateRadiusNumber
--------------------------------------------------------------------------------
-- return table[apn..date] = number constructed from values in CSV file
function readFileApnDateRadiusNumber(name, path, log)
local trace = true
log:log('reading %s file', name)
local input = io.open(path)
if input == nil then
error('unable to open CSV; path = ' .. path)
end
local header = input:read()
print('header', header)
result = {}
local countInput = 0
local countNotMidQuarter = 0
local countUsed = 0
for line in input:lines('*l') do
countInput = countInput + 1
local ok, apn, date, number = parseFields(line, log)
if ok then
if isMidQuarter(date) then
result[apn..date] = number
countUsed = countUsed + 1
if countInput % 1000000 == 0 then
print(
string.format('used: countInput %d apn %s date %s number %f',
countInput, apn, date, number))
end
else
countNotMidQuarter = countNotMidQuarter + 1
end
else
-- bad input record
halt() -- for now, later log and count
end
end
log:log('File contained %d data records', countInput)
log:log(' %d were not for the mid-quarter date, hence not used',
countNotMidQuarter)
log:log(' %d of these were for mid-quarter date, hence use', countUsed)
return result
end
--------------------------------------------------------------------------------
-- readErrors
--------------------------------------------------------------------------------
-- read the completed error matrix from a CSV file
-- create table[apn..date] = error for only mid-quarter dates
function readErrors(path, log)
return readFileApnDateRadiusNumber('errors', path, log)
end
--------------------------------------------------------------------------------
-- readPrices
--------------------------------------------------------------------------------
-- read the price estimates from the laufer estimates file
-- create table[apn..date] = price, which will contain mid-quarter data only
function readPrices(path, log)
return readFileApnDateRadiusNumber('prices', path, log)
end
--------------------------------------------------------------------------------
-- incorporateErrors
--------------------------------------------------------------------------------
-- merge tables errors and prices
-- return new table with updated prices table[apn..date] = updatedPrice
-- errors were computed as
-- error = actual - estimate
-- We want to determine hat(actual), so we compute
-- actual = error + estimate
function incorporateErrors(errors, prices, log)
log:log('incorporating errors into price estimates')
local stage2 = {}
local countErrorFound = 0
local countErrorNotFound = 0
local countPrices = 0
for apnDate, estimate in pairs(prices) do
countPrices = countPrices + 1
local error = errors[apnDate]
if error then
countErrorFound = countErrorFound + 1
stage2[apnDate] = error + estimate
if countErrorFound <= 10 then
log:log('apnDate %s estimate %f error %f stage2Estimate %f',
apnDate, estimate, error, stage2[apnDate])
end
else
countErrorNotFound = countErrorNotFound + 1
end
end
log:log('There were %d prices', countPrices)
log:log('Of which')
log:log(' %d had corresponding errors', countErrorFound)
log:log(' %d did not have corresponding errors', countErrorNotFound)
return stage2
end
--------------------------------------------------------------------------------
-- writeStage2Estimates
--------------------------------------------------------------------------------
-- write the stage2 estimates to a CSV file
function writeStage2Estimates(estimates, path, radius, log)
local trace = false
log:log('Writing stage 2 estimates to %s', path)
local output = io.open(path, 'w')
if output == nil then
print('unable to open output CSV; path = ' .. path)
end
-- write header
output:write('apn,date,radius,estimate\n')
-- write each data record
local countWritten = 0
for apnDate, estimate in pairs(estimates) do
local apn = string.sub(apnDate, 1, 10)
local date = string.sub(apnDate, 11, 18)
assert(apn, apn)
assert(date, date)
assert(string.len(apn) == 10)
assert(string.len(date) == 8)
local line =
string.format('%s,%s,%d,%f\n',
apn, date, radius, estimate)
if trace then
print('output line', line)
end
local ok, error = output:write(line)
if ok == nil then
print('error in writing line:', line)
print('error message:', error)
exit(false)
end
countWritten = countWritten + 1
if countWritten % 100000 == 0 then
log:log('wrote data record %d: %s', countWritten, line)
end
end
log:log('Wrote %d data records', countWritten)
output:close()
end -- writeStage2Estimates
--------------------------------------------------------------------------------
-- main program
--------------------------------------------------------------------------------
local cmd, params = readCommandLine(arg)
local dirInErrors, dirInPrices, dirResults =
setupDirectories(cmd, params)
-- start log and log command line parameters
local log = startLogging(dirResults)
printParams(params, log)
-- set paths to input and output files and log them
print('dirInErrors', dirInErrors)
local pathInErrors = dirInErrors .. 'all-estimates-mc.csv'
local pathInPrices = dirInPrices .. 'estimates-laufer.csv'
local pathOutEstimates = dirResults .. 'estimates-stage2.csv'
function logPath(name, value)
log:log('%-20s = %s', name, value)
end
log:log('\nPath to input and output files')
logPath('pathInErrors', pathInErrors)
logPath('pathInPrices', pathInPrices)
logPath('pathOutEstimates', pathOutEstimates)
local skipReadErrors = false
if not skipReadErrors then
errors = readErrors(pathInErrors, log)
printTableHead('errors', errors)
else
log:log('skipped reading errors')
end
prices = readPrices(pathInPrices, log)
printTableHead('prices', prices)
stage2Estimates = incorporateErrors(errors, prices, log)
printTableHead('stage2Estimates', stage2Estimates)
local radius = 76
writeStage2Estimates(stage2Estimates, pathOutEstimates, radius, log)
printParams(params, log)
log:log('\nfinished')
log:close()
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.