content
stringlengths 5
1.05M
|
---|
Graphics = {}
function Graphics.init()
print("Graphics.init()")
end
Screen = {}
function Screen.flip()
print("Screen.flip()")
end
function Screen.waitVblankStart()
print("Screen.waitVblankStart()")
end
|
-- Event Logger
-- Author: Thalassicus
-- (with modifications by robk adding TRACE level and logging
-- to a database table)
------------------------------------------------------------
TRACE = "TRACE"
DEBUG = "DEBUG"
INFO = "INFO"
WARN = "WARN"
ERROR = "ERROR"
FATAL = "FATAL"
local LEVEL = {
[TRACE] = 1,
[DEBUG] = 2,
[INFO] = 3,
[WARN] = 4,
[ERROR] = 5,
[FATAL] = 6,
}
LoggerType = {};
function LoggerType:new()
local logger = {};
setmetatable(logger, self);
self.__index = self;
logger.level = LEVEL.INFO;
logger.db = Modding.OpenSaveData();
logger.setLevel = function (self, level)
self.level = level;
end
logger.log = function (self, level, message)
-- INFO gets logged to the table regardless of the console log level but only if the
-- Logging table is ready.
if (LEVEL[level] >= LEVEL[INFO] and
MapModData.BattleRoyaleData.LogTableExists == true and
logger.db ~= nil)
then
local insert = 'INSERT INTO BRDataLog("Timestamp", "Level", "Message") ' ..
'VALUES(' .. os.time() ..',"' .. level .. '","' .. message .. '")';
for row in logger.db.Query(insert) do end;
end
if LEVEL[level] < LEVEL[self.level] then
return false;
end
print(level .. ": " .. message);
return true;
end
logger.trace = function (logger, message) return logger:log(TRACE, message) end
logger.debug = function (logger, message) return logger:log(DEBUG, message) end
logger.info = function (logger, message) return logger:log(INFO, message) end
logger.warn = function (logger, message) return logger:log(WARN, message) end
logger.error = function (logger, message) return logger:log(ERROR, message) end
logger.fatal = function (logger, message) return logger:log(FATAL, message) end
return logger;
end
|
TUTORIALS['en'][#TUTORIALS['en'] + 1] = {
name = "Game Options",
afterSeparator = true,
contents = {
{type = CONTENT_TYPES.IMAGE, value = "/images/tutorial/game_options.png"},
{type = CONTENT_TYPES.TEXT, value = "This is the game options window and can be accessed via the button on the top panel\n\n1 - Game - In this section you can configure general options of the game\n\n2 - Console - This option can be found referring to console messages, eg what information you want to be shown in the messages\n\n3 - Graphics - This is the section where you can make adjustments related to the game graphics\n\n4 - Audio - Section responsible for the game sound settings, such as channels volume."},
}
}
|
pg = pg or {}
pg.enemy_data_statistics_218 = {
[12600106] = {
cannon = 0,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 20001,
air = 0,
rarity = 1,
dodge = 0,
torpedo = 0,
durability_growth = 6800,
antiaircraft = 0,
reload_growth = 0,
dodge_growth = 0,
speed = 30,
star = 1,
hit = 8,
antisub_growth = 0,
air_growth = 0,
hit_growth = 120,
base = 90,
durability = 650,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
antiaircraft_growth = 0,
luck = 0,
battle_unit_type = 20,
id = 12600106,
antisub = 0,
armor = 0,
appear_fx = {
"appearsmall"
}
},
[12600107] = {
cannon = 0,
battle_unit_type = 35,
rarity = 1,
speed_growth = 0,
pilot_ai_template_id = 20001,
air = 0,
luck = 0,
dodge = 0,
wave_fx = "danchuanlanghuaxiao2",
cannon_growth = 0,
speed = 15,
reload_growth = 0,
dodge_growth = 0,
id = 12600107,
star = 1,
hit = 8,
antisub_growth = 0,
air_growth = 0,
reload = 150,
base = 70,
durability = 250,
armor_growth = 0,
torpedo_growth = 800,
luck_growth = 0,
hit_growth = 120,
armor = 0,
torpedo = 15,
durability_growth = 2550,
antisub = 0,
antiaircraft = 0,
antiaircraft_growth = 0,
appear_fx = {
"appearsmall"
},
equipment_list = {
1000860
}
},
[12600108] = {
cannon = 40,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 80000,
air = 0,
rarity = 1,
dodge = 0,
torpedo = 85,
durability_growth = 2550,
antiaircraft = 0,
reload_growth = 0,
dodge_growth = 0,
hit_growth = 1200,
star = 1,
hit = 81,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 15,
base = 80,
durability = 60,
armor_growth = 0,
torpedo_growth = 1000,
luck_growth = 0,
speed = 30,
luck = 0,
id = 12600108,
antiaircraft_growth = 0,
antisub = 0,
armor = 0,
appear_fx = {
"appearsmall"
},
equipment_list = {
1000865
}
},
[12600109] = {
cannon = 17,
reload = 150,
speed_growth = 0,
cannon_growth = 1000,
pilot_ai_template_id = 20004,
air = 0,
rarity = 2,
dodge = 7,
torpedo = 11,
durability_growth = 29980,
antiaircraft = 32,
reload_growth = 0,
dodge_growth = 102,
hit_growth = 210,
star = 3,
hit = 14,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 60,
base = 285,
durability = 780,
armor_growth = 0,
torpedo_growth = 700,
luck_growth = 0,
speed = 18,
luck = 0,
id = 12600109,
antiaircraft_growth = 1400,
antisub = 0,
armor = 0,
appear_fx = {
"appearsmall"
},
equipment_list = {
1100040,
1100571,
1100455,
1100541,
1100205
}
},
[12600110] = {
cannon = 28,
hit_growth = 210,
rarity = 2,
speed_growth = 0,
pilot_ai_template_id = 20004,
air = 0,
luck = 0,
dodge = 3,
cannon_growth = 1200,
speed = 18,
reload = 150,
reload_growth = 0,
dodge_growth = 48,
id = 12600110,
star = 3,
hit = 18,
antisub_growth = 0,
air_growth = 0,
torpedo = 0,
base = 316,
durability = 1020,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
battle_unit_type = 65,
armor = 0,
durability_growth = 49600,
antiaircraft = 32,
antisub = 0,
antiaircraft_growth = 1680,
appear_fx = {
"appearsmall"
},
equipment_list = {
1100041,
1100570,
1100550,
1100715
},
buff_list = {
{
ID = 50510,
LV = 1
}
}
},
[12600111] = {
cannon = 5,
reload = 150,
speed_growth = 0,
cannon_growth = 350,
pilot_ai_template_id = 20004,
air = 32,
rarity = 1,
dodge = 5,
torpedo = 0,
durability_growth = 39200,
antiaircraft = 38,
reload_growth = 0,
dodge_growth = 72,
hit_growth = 210,
star = 2,
hit = 14,
antisub_growth = 0,
air_growth = 1250,
battle_unit_type = 70,
base = 317,
durability = 890,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 22,
luck = 0,
id = 12600111,
antiaircraft_growth = 1540,
antisub = 0,
armor = 0,
appear_fx = {
"appearsmall"
},
equipment_list = {
1100780,
1100785,
1100076,
1100790,
1100540
}
},
[12600121] = {
cannon = 18,
reload = 150,
speed_growth = 0,
cannon_growth = 500,
rarity = 3,
air = 0,
torpedo = 34,
dodge = 14,
durability_growth = 105600,
antiaircraft = 65,
luck = 0,
reload_growth = 0,
dodge_growth = 264,
hit_growth = 210,
star = 4,
hit = 14,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 90,
base = 382,
durability = 840,
armor_growth = 0,
torpedo_growth = 1800,
luck_growth = 0,
speed = 20,
armor = 0,
id = 12600121,
antiaircraft_growth = 1440,
antisub = 0,
appear_fx = {
"appearQ"
},
equipment_list = {
1100175,
1100315,
1101501,
1101505,
1101510
}
},
[12600131] = {
cannon = 50,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
rarity = 3,
air = 0,
torpedo = 105,
dodge = 14,
durability_growth = 0,
antiaircraft = 125,
luck = 0,
reload_growth = 0,
dodge_growth = 198,
hit_growth = 210,
star = 4,
hit = 14,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 95,
base = 313,
durability = 5200,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 18,
armor = 0,
id = 12600131,
antiaircraft_growth = 0,
antisub = 0,
appear_fx = {
"appearQ"
},
equipment_list = {
614001,
614002,
614003,
614004
}
},
[12600141] = {
cannon = 5,
prefab = "srDD2",
reload = 150,
cannon_growth = 500,
speed_growth = 0,
air = 0,
rarity = 2,
dodge = 0,
torpedo = 25,
durability_growth = 5120,
antiaircraft = 20,
reload_growth = 0,
dodge_growth = 0,
luck = 0,
star = 2,
hit = 12,
antisub_growth = 0,
air_growth = 0,
hit_growth = 172,
base = 123,
durability = 200,
armor_growth = 0,
torpedo_growth = 1800,
luck_growth = 0,
speed = 15,
armor = 0,
battle_unit_type = 25,
antisub = 0,
id = 12600141,
antiaircraft_growth = 1080,
equipment_list = {
1000591,
1000596,
1000601
}
},
[12600142] = {
cannon = 11,
prefab = "srCL2",
reload = 150,
cannon_growth = 700,
speed_growth = 0,
air = 0,
rarity = 2,
dodge = 0,
torpedo = 16,
durability_growth = 11680,
antiaircraft = 35,
reload_growth = 0,
dodge_growth = 0,
luck = 0,
star = 2,
hit = 12,
antisub_growth = 0,
air_growth = 0,
hit_growth = 172,
base = 124,
durability = 310,
armor_growth = 0,
torpedo_growth = 1300,
luck_growth = 0,
speed = 15,
armor = 0,
battle_unit_type = 30,
antisub = 0,
id = 12600142,
antiaircraft_growth = 1560,
equipment_list = {
1000606,
1000611
}
},
[12600143] = {
cannon = 17,
prefab = "srCA2",
reload = 150,
cannon_growth = 1200,
speed_growth = 0,
air = 0,
rarity = 2,
dodge = 0,
torpedo = 11,
durability_growth = 20000,
antiaircraft = 25,
reload_growth = 0,
dodge_growth = 0,
luck = 0,
star = 2,
hit = 12,
antisub_growth = 0,
air_growth = 0,
hit_growth = 172,
base = 125,
durability = 460,
armor_growth = 0,
torpedo_growth = 800,
luck_growth = 0,
speed = 15,
armor = 0,
battle_unit_type = 35,
antisub = 0,
id = 12600143,
antiaircraft_growth = 1200,
equipment_list = {
1000616,
1000621,
1000625
}
},
[12600144] = {
cannon = 28,
prefab = "srBB2",
reload = 150,
cannon_growth = 1500,
speed_growth = 0,
air = 0,
rarity = 2,
dodge = 0,
torpedo = 0,
durability_growth = 41600,
antiaircraft = 30,
reload_growth = 0,
dodge_growth = 0,
luck = 0,
star = 2,
hit = 12,
antisub_growth = 0,
air_growth = 0,
hit_growth = 172,
base = 126,
durability = 1020,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 15,
armor = 0,
battle_unit_type = 60,
antisub = 0,
id = 12600144,
antiaircraft_growth = 1440,
equipment_list = {
1000631,
1000636,
1000641
}
},
[12600145] = {
cannon = 5,
prefab = "srCV2",
reload = 150,
cannon_growth = 400,
speed_growth = 0,
air = 32,
rarity = 2,
dodge = 0,
torpedo = 0,
durability_growth = 34400,
antiaircraft = 25,
reload_growth = 0,
dodge_growth = 0,
luck = 0,
star = 2,
hit = 12,
antisub_growth = 0,
air_growth = 1500,
hit_growth = 172,
base = 127,
durability = 880,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
speed = 15,
armor = 0,
battle_unit_type = 65,
antisub = 0,
id = 12600145,
antiaircraft_growth = 1320,
bound_bone = {
cannon = {
{
1.8,
1.14,
0
}
},
torpedo = {
{
1.07,
0.24,
0
}
},
antiaircraft = {
{
1.8,
1.14,
0
}
},
plane = {
{
1.8,
1.14,
0
}
}
},
equipment_list = {
1000646,
1000651,
1000656,
1000661
}
},
[12600146] = {
cannon = 0,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 20001,
air = 0,
rarity = 1,
dodge = 0,
torpedo = 0,
durability_growth = 6800,
antiaircraft = 0,
reload_growth = 0,
dodge_growth = 0,
speed = 30,
star = 1,
hit = 8,
antisub_growth = 0,
air_growth = 0,
hit_growth = 120,
base = 90,
durability = 700,
armor_growth = 0,
torpedo_growth = 0,
luck_growth = 0,
antiaircraft_growth = 0,
luck = 0,
battle_unit_type = 20,
id = 12600146,
antisub = 0,
armor = 0,
appear_fx = {
"appearsmall"
}
},
[12600147] = {
cannon = 0,
battle_unit_type = 35,
rarity = 1,
speed_growth = 0,
pilot_ai_template_id = 20001,
air = 0,
luck = 0,
dodge = 0,
wave_fx = "danchuanlanghuaxiao2",
cannon_growth = 0,
speed = 15,
reload_growth = 0,
dodge_growth = 0,
id = 12600147,
star = 1,
hit = 8,
antisub_growth = 0,
air_growth = 0,
reload = 150,
base = 70,
durability = 265,
armor_growth = 0,
torpedo_growth = 800,
luck_growth = 0,
hit_growth = 120,
armor = 0,
torpedo = 24,
durability_growth = 2550,
antisub = 0,
antiaircraft = 0,
antiaircraft_growth = 0,
appear_fx = {
"appearsmall"
},
equipment_list = {
1000861
}
},
[12600148] = {
cannon = 50,
reload = 150,
speed_growth = 0,
cannon_growth = 0,
pilot_ai_template_id = 80000,
air = 0,
rarity = 1,
dodge = 0,
torpedo = 100,
durability_growth = 2550,
antiaircraft = 0,
reload_growth = 0,
dodge_growth = 0,
hit_growth = 1000,
star = 1,
hit = 100,
antisub_growth = 0,
air_growth = 0,
battle_unit_type = 15,
base = 80,
durability = 70,
armor_growth = 0,
torpedo_growth = 1000,
luck_growth = 0,
speed = 30,
luck = 0,
id = 12600148,
antiaircraft_growth = 0,
antisub = 0,
armor = 0,
appear_fx = {
"appearsmall"
},
equipment_list = {
1000866
}
}
}
return
|
---@class Video
C_VideoOptions = {}
---@return GxAdapterInfoDetails adapters
function C_VideoOptions.GetGxAdapterInfo() end
---@class GxAdapterInfoDetails
---@field name string
---@field isLowPower bool
---@field isExternal bool
local GxAdapterInfoDetails = {}
|
Locales['en'] = {
['press_collect_coke'] = 'Press ~INPUT_PICKUP~ to collect cocaine',
['press_process_coke'] = 'Press ~INPUT_PICKUP~ to process cocaine',
['press_sell_coke'] = 'Press ~INPUT_PICKUP~ to sell cocaine',
['press_collect_meth'] = 'Press ~INPUT_PICKUP~ to collect meth',
['press_process_meth'] = 'Press ~INPUT_PICKUP~ to process meth',
['press_sell_meth'] = 'Press ~INPUT_PICKUP~ to sell meth',
['press_collect_weed'] = 'Press ~INPUT_PICKUP~ to collect weed',
['press_process_weed'] = 'Press ~INPUT_PICKUP~ to process weed',
['press_sell_weed'] = 'Press ~INPUT_PICKUP~ to sell weed',
['press_collect_opium'] = 'Press ~INPUT_PICKUP~ to collect opium',
['press_process_opium'] = 'Press ~INPUT_PICKUP~ to process opium',
['press_sell_opium'] = 'Press ~INPUT_PICKUP~ to sell opium',
['act_imp_police'] = 'you cannot participate illegal activities unless there\'s enough cops online: ~o~%s~s~/~y~%s~s~ online',
['inv_full_coke'] = 'you can no longer collect Cocaine, your inventory is ~r~full~s~',
['pickup_in_prog'] = '~y~Pickup in progress~s~...',
['too_many_pouches'] = 'you have too many bag',
['not_enough_coke'] = 'you do not have enough coke to ~r~pack~s~',
['packing_in_prog'] = '~y~Packaging in progress~s~...',
['no_pouchs_sale'] = 'You have no more bag for ~r~sale~s~',
['sold_one_coke'] = 'you\'ve sold ~y~x1~s~ ~y~Cocaine bag~s~',
['sale_in_prog'] = '~g~Sale in progress~s~...',
['inv_full_meth'] = 'you can no longer collect Meth, your inventory is ~r~full~s~',
['not_enough_meth'] = 'you do not have enough Meth to ~r~pack~s~',
['sold_one_meth'] = 'you\'ve sold ~g~x1 Meth bag(1G)~s~',
['inv_full_weed'] = 'you can no longer collect Weed, your inventory is ~r~full~s~',
['not_enough_weed'] = 'you do not have enough Weed to ~r~pack~s~',
['sold_one_weed'] = 'you\'ve sold ~g~x1 Weed bag(1G)~s~',
['used_one_weed'] = 'you used 1G ~b~weed',
['inv_full_opium'] = 'you can no longer collect opium, your inventory is ~r~full~s~',
['not_enough_opium'] = 'you do not have enough opium to ~r~pack~s~',
['sold_one_opium'] = 'you\'ve sold ~g~x1 opium bag(1G)~s~',
['used_one_opium'] = 'you used 1 bag of ~b~opium',
['exit_marker'] = 'Press ~INPUT_PICKUP~ to cancel the ~y~process~s~',
['no_pouches_weed_sale'] = 'You do not have any bag of weed(1G) to sell',
['no_pouches_coke_sale'] = 'You do not have any bag of coke(1G) to sell',
['no_pouches_meth_sale'] = 'You do not have any bag of meth(1G) to sell',
['no_pouches_opium_sale'] = 'You do not have any bag of meth(1G) to sell',
['controls_cooldown'] = 'You must wait 5 minutes before you can do this again.',
}
|
AddCSLuaFile()
SWEP.PrintName = "Magic Wand Rewrite"
SWEP.Category = "Harry Potter"
SWEP.Purpose = ""
SWEP.Weight = 5
SWEP.Spawnable = true
SWEP.UseHands = true
SWEP.DrawAmmo = false
SWEP.ViewModelFOV = 56
SWEP.Slot = 2
SWEP.SlotPos = 5
SWEP.Primary.ClipSize = -1
SWEP.Primary.DefaultClip = -1
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = "none"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.ViewModel = Model("models/hpwrewrite/c_magicwand.mdl")
SWEP.WorldModel = Model("models/hpwrewrite/w_magicwand.mdl")
SWEP.BobScale = 0.26
SWEP.SwayScale = 0.8
AccessorFunc(SWEP, "m_hpw_accuracy_penalty", "HPWAccuracyPenalty", FORCE_NUMBER)
--local setup = CreateConVar("hpwrewrite_setup", "0", { FCVAR_ARCHIVE, FCVAR_PROTECTED, FCVAR_REPLICATED })
if CLIENT then
killicon.Add("weapon_hpwr_stick", "hpwrewrite/killicon", Color(255, 80, 0, 255))
hook.Add("OnContextMenuOpen", "hpwrewrite_wand_handler_open", function()
local self = LocalPlayer():GetActiveWeapon()
if HpwRewrite.IsValidWand(self) then
self.HpwRewrite.ShouldSetPos = true
self.HpwRewrite.Select = true
end
end)
hook.Add("OnContextMenuClose", "hpwrewrite_wand_handler_close", function()
local self = LocalPlayer():GetActiveWeapon()
if HpwRewrite.IsValidWand(self) then
self.HpwRewrite.Select = false
end
end)
--[[net.Receive("hpwrewrite_setup", function(len)
if not HpwRewrite.CheckAdmin(ply) or not ply:IsSuperAdmin() or setup:GetBool() then return end
local time = SysTime()
local win = HpwRewrite.VGUI:CreateWindow(800, 425)
local alpha = 0
win.Paint = function(self, w, h)
Derma_DrawBackgroundBlur(self, time)
alpha = math.Approach(alpha, 150, RealFrameTime() * 60)
local col = Color(255, 255, 255, alpha)
draw.RoundedBox(0, 0, 0, ScrW(), ScrH(), col)
end
win.PaintOver = function() end
local lab = HpwRewrite.VGUI:CreateLabel("Should we enable spell learning?", nil, nil, win)
lab:SetFont("HPW_guibiggest")
lab:Dock(TOP)
lab:InvalidateParent(true)
lab:SetColor(HpwRewrite.Colors.DarkGrey2)
lab:SetContentAlignment(5)
lab:SizeToContents()
local yes = HpwRewrite.VGUI:CreateButton("Yes!", 85, 155, 300, 200, win, function()
net.Start("hpwrewrite_setup")
net.WriteBit(false)
net.SendToServer()
win:Close()
end)
yes.MainColor = Color(50, 160, 50)
yes.EnterColor = Color(50, 200, 50)
yes:SetFont("HPW_guibiggest")
local no = HpwRewrite.VGUI:CreateButton("No!", 410, 155, 300, 200, win, function()
net.Start("hpwrewrite_setup")
net.WriteBit(true)
net.SendToServer()
win:Close()
end)
no.MainColor = Color(160, 50, 50)
no.EnterColor = Color(200, 50, 50)
no:SetFont("HPW_guibiggest")
end)]]
function SWEP:AdjustMouseSensitivity()
if HpwRewrite.FM:GetValue(self.Owner) then return 0.3 end
end
SWEP.WepSelectIcon = surface.GetTextureID("vgui/hpwrewrite/selection/wep_sel")
function SWEP:DrawWeaponSelection(x, y, wide, tall, alpha)
x = x + wide / 2
y = y + tall / 2
tall = tall * 0.75
x = x - tall / 2
y = y - tall / 2 - 10
surface.SetDrawColor(255, 255, 255, alpha)
surface.SetTexture(self.WepSelectIcon)
surface.DrawTexturedRect(x, y, tall, tall)
end
function SWEP:FirstCellPos()
return ScrW() / 2 - 305 + HpwRewrite.CVars.XOffset:GetInt(), ScrH() - 130 + HpwRewrite.CVars.YOffset:GetInt()
end
local cellSize = 68
function SWEP:GetCellPosition(index)
local x, y = self:FirstCellPos()
return x + (index - 1) * cellSize + 32, y + 32
end
function SWEP:CalculateCellOffset()
local mx, my = input.GetCursorPos()
local x, y = self:FirstCellPos()
local st1 = (my - y) / cellSize
local st2 = (mx - x) / cellSize
if st2 > 9 or st2 < 0 then return 0 end
if st1 > 1 or st1 < 0 then return 0 end
return math.Clamp(math.floor(st2) + 1, 1, 9)
end
local glow = Material("hpwrewrite/sprites/magicsprite")
function SWEP:DrawSpriteStuff(vm)
local obj = vm:LookupBone("spritemagic")
local pos = self.Owner:EyePos()
local val = 1
local curskin = HpwRewrite:GetPlayerSkin(self.Owner, self:GetWandCurrentSkin())
if curskin then curskin:DrawMagicSprite(self, vm, obj) end
if self.HpwRewrite.SpriteAlpha > 0 then
local curspell = HpwRewrite:GetPlayerSpell(self.Owner, self:GetWandCurrentSpell())
if curspell and curspell.Name == self.HpwRewrite.LastAttackerSpellName then curspell:DrawMagicSprite(self, vm, obj) end
self.HpwRewrite.SpriteAlpha = math.Approach(self.HpwRewrite.SpriteAlpha, 0, FrameTime() * self.HpwRewrite.SpriteTime)
else
return
end
if obj then
local m = vm:GetBoneMatrix(obj)
if m then
pos = m:GetTranslation()
if curskin and curskin.AdjustSpritePosition then
pos = pos + curskin:AdjustSpritePosition(vm, m, curspell)
end
val = self.HpwRewrite.SpriteColor.a / 255
self.HpwRewrite.SpriteColor.a = Lerp(FrameTime() * 16, self.HpwRewrite.SpriteColor.a, self.HpwRewrite.SpriteAlpha)
render.SetMaterial(glow)
local white = Color(255, 255, 255, self.HpwRewrite.SpriteColor.a)
local sin = math.sin(CurTime() * 24) * 0.3
for i = 1, 8 do
local size = (i * 3 * val + sin) * self.HpwRewrite.SpriteSize
render.DrawSprite(pos, size, size, self.HpwRewrite.SpriteColor)
render.DrawSprite(pos, 7 * val * self.HpwRewrite.SpriteSize, 7 * val * self.HpwRewrite.SpriteSize, white)
end
end
end
local dlight = DynamicLight(vm:EntIndex())
if dlight then
dlight.pos = pos + Vector(3, 0, 0) -- Moved a bit to solve light inside wand bug
dlight.r = self.HpwRewrite.SpriteColor.r
dlight.g = self.HpwRewrite.SpriteColor.g
dlight.b = self.HpwRewrite.SpriteColor.b
dlight.brightness = 2
dlight.Decay = 1000
dlight.Style = 5
dlight.Size = 160 * val
dlight.DieTime = CurTime() + 0.1
end
end
-- Better than DrawWorldModel
-- TODO: fix wand:DrawModel()
--[[hook.Add("PostDrawOpaqueRenderables", "hpwrewrite_weapon_spritedrawing_handler", function()
for k, v in pairs(ents.FindByClass(HpwRewrite.WandClass)) do
if not v:GetNoDraw() then
v:DrawModel()
if IsValid(v.Owner) then
v:DrawSpriteStuff(v)
local curskin = HpwRewrite:GetPlayerSkin(v.Owner, v:GetWandCurrentSkin())
if curskin then curskin:DrawWorldModel(v) end
local curspell = HpwRewrite:GetPlayerSpell(v.Owner, v:GetWandCurrentSpell())
if curspell then curspell:DrawWorldModel(v) end
end
end
end
end)]]
-- TODO: Leave it empty
function SWEP:DrawWorldModel()
self:DrawModel()
if IsValid(self.Owner) then
self:DrawSpriteStuff(self)
local curskin = HpwRewrite:GetPlayerSkin(self.Owner, self:GetWandCurrentSkin())
if curskin then curskin:DrawWorldModel(self) end
local curspell = HpwRewrite:GetPlayerSpell(self.Owner, self:GetWandCurrentSpell())
if curspell then curspell:DrawWorldModel(self) end
end
end
function SWEP:PostDrawViewModel(vm, wep, ply)
local curskin = HpwRewrite:GetPlayerSkin(self.Owner, self:GetWandCurrentSkin())
if curskin then curskin:PostDrawViewModel(self, vm) end
local curspell = HpwRewrite:GetPlayerSpell(self.Owner, self:GetWandCurrentSpell())
if curspell then curspell:PostDrawViewModel(self, vm) end
cam.IgnoreZ(true)
self:DrawSpriteStuff(vm)
cam.IgnoreZ(false)
end
local spellbar = Material("vgui/hpwrewrite/spellbar")
local leftBar = Material("vgui/hpwrewrite/leftbar")
local leftBarEmpty = Material("vgui/hpwrewrite/leftbarempty")
local gradient = Material("vgui/gradient_up")
local centerGradient = Material("gui/center_gradient")
local waitBeforeHide = 0
local hintMenu = HpwRewrite.Language:GetWord("#menu_hint")
local treeWord = HpwRewrite.Language:GetWord("#spelltreeword")
local curSpellWord = HpwRewrite.Language:GetWord("#curspell")
local quickBarHint = HpwRewrite.Language:GetWord("#quick_bar_hint")
function SWEP:DrawHUD()
if HpwRewrite.CVars.NoHud:GetBool() then return end
-- Spells
if HpwRewrite.CVars.DrawSpellBar:GetBool() then
local x, y = self:FirstCellPos()
for i = 1, 9 do
local x = x + (i - 1) * cellSize
local w, h = 64, 64
local bind = HpwRewrite.BM.Binds[i]
local spell, key
if bind then
spell = bind.Spell
key = bind.Key
end
HpwRewrite:DrawSpellRect(spell, key, x, y, w, h)
end
end
local xoffset = HpwRewrite.CVars.XOffset:GetInt()
local yoffset = HpwRewrite.CVars.YOffset:GetInt()
local x = ScrW() / 2 - 305 + xoffset
local y = ScrH() - 62 + yoffset
local mmorpg = HpwRewrite.CVars.MmorpgStyle:GetBool()
-- Spellbar
if HpwRewrite.CVars.DrawCurrentSpell:GetBool() then
if mmorpg then
surface.SetMaterial(spellbar)
surface.SetDrawColor(Color(255, 255, 255, 255))
surface.DrawTexturedRect(x - 3, y - 75, 616, 220)
else
draw.RoundedBox(0, x, y, 608, 70, Color(0, 0, 0, 150))
end
local spellName = self:GetWandCurrentSpell()
if spellName == "" then spellName = "None" end
local text = curSpellWord .. spellName
draw.SimpleText(text, "HPW_font2", x + 17, y + 13, HpwRewrite.Colors.Black, TEXT_ALIGN_LEFT)
draw.SimpleText(text, "HPW_font2", x + 16, y + 12, HpwRewrite.Colors.White, TEXT_ALIGN_LEFT)
end
if self.HpwRewrite.PrintHelp and HpwRewrite.CVars.DrawHint:GetBool() and not self.HpwRewrite.Select then
draw.SimpleText(Format(hintMenu, HpwRewrite.BM.Keys[HpwRewrite.CVars.MenuKey:GetInt()] or "NONE"), "HPW_font3", x + 305, y - 108, Color(255, 255, 255, 150 + math.sin(CurTime() * 4) * 100), TEXT_ALIGN_CENTER)
elseif self.HpwRewrite.Select then
draw.SimpleText(treeWord .. HpwRewrite.BM.CurTree, "HPW_font3", x + 305, y - 108, Color(255, 255, 255, 150 + math.sin(CurTime() * 4) * 100), TEXT_ALIGN_CENTER)
end
if self.HpwRewrite.Select and HpwRewrite.CVars.DrawSelHint:GetBool() then
draw.SimpleText(quickBarHint, "HPW_font3", ScrW() / 2, 64, Color(255, 255, 255, 200 + math.sin(CurTime() * 4) * 55), TEXT_ALIGN_CENTER)
end
-- Left side accuracy bar
local accVal = self:GetHPWAccuracyValue()
if waitBeforeHide and accVal > 0 then
waitBeforeHide = nil
elseif not waitBeforeHide then
waitBeforeHide = CurTime() + 1.5
end
if accVal > 0 or (waitBeforeHide and CurTime() < waitBeforeHide) then
local mainH = 147
local length = math.floor(accVal * mainH)
local w = ScrW()
local h = ScrH()
local colVal = accVal * 255
if mmorpg then
local x = x - 30
local y = y - mainH / 2 + 1
local color = Color(colVal, 255 - colVal, 0, 255 - colVal)
surface.SetDrawColor(HpwRewrite.Colors.White)
surface.SetMaterial(leftBar)
surface.DrawTexturedRect(x, y, 30, mainH)
draw.RoundedBox(0, x + 4, y + length + 10, 20, mainH - 16 - length, color)
surface.SetMaterial(gradient)
surface.DrawTexturedRect(x + 4, y + length + 5, 20, 6)
surface.SetDrawColor(HpwRewrite.Colors.White)
surface.SetMaterial(leftBarEmpty)
surface.DrawTexturedRect(x, y, 30, mainH)
if accVal > 0.6 then
surface.SetDrawColor(Color(255, 0, 0, 90 + math.sin(CurTime() * 16) * 80))
surface.SetMaterial(centerGradient)
surface.DrawTexturedRect(x, y, 30, mainH)
end
else
local x = x - 24
local y = y - mainH / 2 + 5
local color = Color(colVal, 255 - colVal, 0, 255 - colVal)
draw.RoundedBox(0, x, y, 20, mainH - 9, Color(0, 0, 0, 200))
draw.RoundedBox(0, x, y + length, 20, mainH - 9 - length, color)
if accVal > 0.6 then
draw.RoundedBox(0, x, y, 20, mainH, Color(255, 0, 0, 90 + math.sin(CurTime() * 16) * 80))
end
end
end
end
-- Wand net system is too big
net.Receive("HpwRewriteSpriteSend", function(len)
local stuff = tobool(net.ReadBit())
local wep = net.ReadEntity()
if not wep:IsValid() then return end
if not wep.HpwRewrite then HpwRewrite:LogDebug("Wand table doesn't exist!") return end
-- if the server knows that player used the same spell as before we won't receive anymore data (Saving a lot of bits)
if stuff then
wep.HpwRewrite.SpriteAlpha = 255
return
end
-- Other data
local r = net.ReadUInt(8)
local g = net.ReadUInt(8)
local b = net.ReadUInt(8)
local time = net.ReadUInt(11)
local size = net.ReadFloat()
local name = net.ReadString()
wep.HpwRewrite.SpriteAlpha = 255
wep.HpwRewrite.SpriteColor = Color(r, g, b, (wep.HpwRewrite.SpriteColor.a))
wep.HpwRewrite.SpriteTime = time
wep.HpwRewrite.SpriteSize = size
wep.HpwRewrite.LastAttackerSpellName = name
end)
else
util.AddNetworkString("HpwRewriteSpriteSend")
--[[util.AddNetworkString("hpwrewrite_setup")
net.Receive("hpwrewrite_setup", function(len, ply)
if not HpwRewrite.CheckAdmin(ply) or not ply:IsSuperAdmin() then return end
local val = tostring(net.ReadBit())
if val != "0" and val != "1" then print("Wrong argument! Expected", "1/0", "Got", val) return end
RunConsoleCommand("hpwrewrite_sv_nolearning", val)
RunConsoleCommand("hpwrewrite_setup", "1")
end)]]
function SWEP:RequestSprite(name, col, time, size, forcedata)
if self.HpwRewrite.BlockSprite then return end
size = size or 1
local noData = name == self.HpwRewrite.LastAttackerSpellName
if forcedata then noData = false end
net.Start("HpwRewriteSpriteSend")
net.WriteBit(noData)
net.WriteEntity(self)
if not noData then
net.WriteUInt(col.r, 8)
net.WriteUInt(col.g, 8)
net.WriteUInt(col.b, 8)
net.WriteUInt(time, 11)
net.WriteFloat(size)
net.WriteString(name)
end
net.Broadcast()
self.HpwRewrite.LastAttackerSpellName = name
end
function SWEP:UpdateClientsideSkin(ply)
net.Start("hpwrewrite_vm_wm")
net.WriteEntity(self)
net.WriteString(self.ViewModel)
net.WriteString(self.WorldModel)
if IsValid(ply) then
net.Send(ply)
else
net.Broadcast()
end
end
function SWEP:HPWSetWandSkin(name)
local wep = self.Owner:GetActiveWeapon()
if wep != self then HpwRewrite:LogDebug(self.Owner:Name() .. "'s weapon isn't wand, cannot change skin!") return end
local isDefSkin = false
-- Skip checking and giving skin if name is DefaultSkin
if name == HpwRewrite.DefaultSkin then
HpwRewrite:PlayerGiveSpell(self.Owner, HpwRewrite.DefaultSkin, nil, true)
isDefSkin = true
else
if not HpwRewrite:CanUseSpell(self.Owner, name) then
if self:GetWandCurrentSkin() == name then self:HPWSetWandSkin(HpwRewrite.DefaultSkin) end
return
end
end
local oldskin = self:GetWandCurrentSkin()
local skin = HpwRewrite:GetPlayerSkin(self.Owner, name)
if not skin then print(name .. " does not exist!") return end
HpwRewrite:LogDebug(self.Owner:Name() .. " changing skin to " .. name)
if not skin:PreSkinSelect(self) then
HpwRewrite:LogDebug(self.Owner:Name() .. " attempted to change his skin to " .. name)
if not isDefSkin then return end
end
self:Holster(nil, true)
self:SetHoldType(skin.HoldType)
local vm = skin.ViewModel
local wm = skin.WorldModel
self.ViewModel = vm
self.WorldModel = wm
self.Owner:GetViewModel():SetWeaponModel(vm, self)
self:SetWandCurrentSkin(name)
self:UpdateClientsideSkin()
self:Deploy(true)
skin:OnSkinSelect(self)
oldskin = HpwRewrite:GetPlayerSkin(self.Owner, oldskin)
if oldskin then oldskin:OnSkinHolster(self) end
self:CheckSpellUseable(self:GetWandCurrentSpell())
-- Notifying those people who has problems with models from .gma
-- It should help them
if game.SinglePlayer() and not HpwRewrite.CVars.ErrorNotify:GetBool() and not util.IsValidModel(skin.ViewModel) then
HpwRewrite:DoNotify(self.Owner, "Seems like the wand addon was not installed correctly! Try to deinstall and install it then restart the game several times.", 1, 14)
RunConsoleCommand("hpwrewrite_sv_error_notify", "1")
end
return true
end
function SWEP:HPWSetCurrentSpell(name)
local oldspellname = self:GetWandCurrentSpell()
if not HpwRewrite:CanUseSpell(self.Owner, name) then
if name == oldspellname then self:HPWRemoveCurSpell() end
HpwRewrite:LogDebug(self.Owner:Name() .. " attempted to change his spell to " .. name)
return
end
if name == oldspellname then return true end -- true
local oldspell = HpwRewrite:GetPlayerSpell(self.Owner, oldspellname)
local newspell = HpwRewrite:GetPlayerSpell(self.Owner, name)
if not newspell:OnSelect(self) then
HpwRewrite:LogDebug(self.Owner:Name() .. " attempted to change his spell to " .. name)
return
end
self.Primary.Automatic = false
if newspell.AutoFire then
self.Primary.Automatic = true
end
if oldspell then oldspell:OnHolster(self) end
self:SetWandCurrentSpell(name)
HpwRewrite:LogDebug(self.Owner:Name() .. " changed spell to " .. name)
return true
end
function SWEP:HPWRemoveCurSpell()
local oldspell = HpwRewrite:GetPlayerSpell(self.Owner, self:GetWandCurrentSpell())
if oldspell then oldspell:OnHolster(self) end
self.Primary.Automatic = false
self:SetWandCurrentSpell("")
end
function SWEP:HPWGetAimEntity(distance, mins, maxs)
distance = distance or 1000
local ply = self.Owner
local tr
local pos1 = ply:GetShootPos()
local pos2 = ply:GetShootPos() + ply:GetAimVector() * distance
if mins and maxs then
tr = util.TraceHull({
start = pos1,
endpos = pos2,
filter = ply,
mins = mins,
maxs = maxs
})
else
tr = util.TraceLine({
start = pos1,
endpos = pos2,
filter = ply
})
end
if self.HoldingSelfCast then return ply, tr end
return tr.Entity, tr
end
function SWEP:HPWDecreaseAccuracy(amount)
-- 0 accuracy is the best one
if not self.HpwRewrite.Accuracy then self.HpwRewrite.Accuracy = 0 end
if not HpwRewrite.CVars.NoAccuracy:GetBool() then
if self.GetHPWAccuracyPenalty then amount = amount * self:GetHPWAccuracyPenalty() end -- useless if
self.HpwRewrite.Accuracy = math.Approach(self.HpwRewrite.Accuracy, 1, amount)
self.HpwRewrite.CooldownAccuracy = CurTime() + 1.2
end
end
function SWEP:ApplyAccuracyPenalty(vec)
-- TODO: check if its quite optimized
vec:Rotate(AngleRand() * (self.HpwRewrite.Accuracy or 0) * 0.06)
end
function SWEP:HPWSpawnSpell(curspell)
local pos = self:GetSpellSpawnPosition()
local dir = (self.Owner:GetEyeTrace().HitPos - pos):GetNormal()
self:ApplyAccuracyPenalty(dir)
local ent = ents.Create("entity_hpwand_flyingspell")
ent:SetPos(pos)
ent:SetAngles(dir:Angle())
ent:SetFlyDirection(dir)
ent:SetSpellData(curspell)
ent:SetupOwner(self.Owner)
ent:Spawn()
curspell:OnSpellSpawned(self, ent)
if curspell.CanSelfCast and self.HoldingSelfCast then
local data = { }
data.HitEntity = self.Owner
data.HitPos = self.Owner:LocalToWorld(self.Owner:OBBCenter())
data.Speed = 0
data.HitNormal = Vector(0, 0, 0)
ent:PhysicsCollide(data, ent:GetPhysicsObject())
end
self:HPWDecreaseAccuracy(curspell.AccuracyDecreaseVal)
self.HoldingSelfCast = false
end
function SWEP:HPWDoSprite(curspell)
local col = curspell.SpriteColor
if col then
local force = false
if curspell.ForceSpriteSending then force = true end
self:RequestSprite(curspell.Name, col, curspell.SpriteTime or 600, curspell.SpriteSize, force)
end
end
function SWEP:HPWDoSpell(curspell)
self:HPWSpawnSpell(curspell)
self:HPWDoSprite(curspell)
end
function SWEP:AnimationSpeedTimer(speed, seconds)
if speed <= 0 then return end
self.HpwRewrite.AnimationSpeed = speed
timer.Create("hpwrewrite_adnimation_" .. self:EntIndex(), seconds, 1, function()
if IsValid(self) then self.HpwRewrite.AnimationSpeed = 1 end
end)
end
function SWEP:CanContinue(curspell)
return IsValid(self.Owner) and self == self.Owner:GetActiveWeapon() and curspell and HpwRewrite:CanUseSpell(self.Owner, curspell.Name)
end
function SWEP:AttackSpell(curspell)
if curspell:OnFire(self) then
if curspell.UseClientsideOnFire then
net.Start("hpwrewrite_ClientsidePrimaryAttack")
net.WriteEntity(self)
net.WriteUInt(curspell.UniqueID, 9) -- 2^9 = 512 will there be more than 512 spells?
if curspell.ClientsideOnFireShouldBroadcast then
net.Broadcast()
else
net.Send(self.Owner)
end
end
if curspell.ApplyDelay then
timer.Simple(self:HPWSeqDuration2() * curspell.ApplyDelay, function()
if IsValid(self) and self:CanContinue(curspell) then self:HPWDoSpell(curspell) end
end)
else
self:HPWDoSpell(curspell)
end
else
self:HPWDoSprite(curspell)
self:HPWDecreaseAccuracy(curspell.AccuracyDecreaseVal) -- for spells without entity
end
end
-- TODO: add more sounds
local sounds = {
"hpwrewrite/wand/maincast.wav"
}
function SWEP:PlayCastSound()
local name = table.Random(sounds)
local override = false
local skin = HpwRewrite:GetPlayerSkin(self.Owner, self:GetWandCurrentSkin())
if skin then
local cast
cast, override = skin:GetCastSound(self)
if override then return end
if cast then name = cast end
end
self:EmitSound(name, 70, math.random(95, 105), 1, CHAN_WEAPON)
end
end
function SWEP:SetupDataTables()
self:NetworkVar("String", 0, "WandCurrentSpell")
self:NetworkVar("String", 1, "WandCurrentSkin")
self:NetworkVar("Float", 0, "WandNextIdle")
self:NetworkVar("Float", 1, "HPWAccuracyValue") -- for clientside only
end
function SWEP:GetSpellSpawnPosition()
local ang = self.Owner:EyeAngles()
local pos = self.Owner:EyePos() + ang:Right() * 2 + ang:Forward() * 16
if HpwRewrite.CVars.AlwaysCenter:GetBool() then
pos = self.Owner:EyePos() + ang:Forward() * 10
else
local skin = HpwRewrite:GetPlayerSkin(self.Owner, self:GetWandCurrentSkin())
if skin then
pos = skin:GetSpellPosition(self, pos)
end
end
return pos
end
function SWEP:CheckSpellUseable(name)
if not HpwRewrite:CanUseSpell(self.Owner, name) then
if SERVER then
if self:GetWandCurrentSkin() == name then self:HPWSetWandSkin(HpwRewrite.DefaultSkin) end
if self:GetWandCurrentSpell() == name then self:HPWRemoveCurSpell() end
end
return false
end
return true
end
function SWEP:HPWSeqDuration2()
return self.HpwRewrite.SequenceDuration
end
function SWEP:HPWSendAnimation(act)
self.HpwRewrite.SequenceDuration = 1 -- TODO: choose whether leave it or delete
if not act then return end
if not game.SinglePlayer() and not IsFirstTimePredicted() then return end
local vm = self.Owner:GetViewModel()
if not IsValid(vm) then return end
local seq = vm:SelectWeightedSequence(act)
if not seq or seq == -1 then return end
vm:SendViewModelMatchingSequence(seq)
local val = self.HpwRewrite.AnimationSpeed * HpwRewrite.CVars.AnimSpeed:GetFloat()
vm:SetPlaybackRate(1 * val)
self.HpwRewrite.SequenceDuration = vm:SequenceDuration(seq) / val
self:SetWandNextIdle(CurTime() + self.HpwRewrite.SequenceDuration)
end
function SWEP:Initialize()
if self.HpwRewrite then table.Empty(self.HpwRewrite) end
self.HpwRewrite = { }
self.HpwRewrite.SequenceDuration = 0
self.HpwRewrite.AnimationSpeed = 1
self.HpwRewrite.BlockSprite = false
self.HpwRewrite.LastAttackerSpellName = nil
if CLIENT then
self.HpwRewrite.PrintHelp = true
self.HpwRewrite.Select = false
self.HpwRewrite.ShouldSetPos = false
self.HpwRewrite.CurrentSpellPr = ""
self.HpwRewrite.SpriteAlpha = 0
self.HpwRewrite.SpriteTime = 1
self.HpwRewrite.SpriteSize = 1
self.HpwRewrite.SpriteColor = Color(0, 0, 0, 0)
if LocalPlayer() == self.Owner then
if not HpwRewrite.CVars.DisableMsg:GetBool() and not HpwRewrite.MessagePrinted then
HpwRewrite:DoNotify("You can disable magic wand hints in SpawnMenu > Options > Wand Settings > Client > Disable popup hints", 3, 13)
timer.Simple(3, function()
if not HpwRewrite.CVars.DisableMsg:GetBool() then
HpwRewrite:DoNotify("Need help? Go to SpawnMenu > Options > Wand Settings > Online Help", 3, 18)
end
end)
if HpwRewrite.CVars.NoLearning:GetBool() then
if self.Owner:IsSuperAdmin() then
timer.Simple(8, function()
if not HpwRewrite.CVars.DisableMsg:GetBool() then
HpwRewrite:DoNotify("You can enable learning in SpawnMenu > Options > Wand Settings > Server > Disable learning", 3, 14)
end
end)
end
else
timer.Simple(7, function()
if not HpwRewrite.CVars.DisableMsg:GetBool() then
HpwRewrite:DoNotify("To get spells go to SpawnMenu > Entities > Harry Potter Spell Books and spawn books", 3, 17)
end
end)
if self.Owner:IsSuperAdmin() then
timer.Simple(14, function()
if not HpwRewrite.CVars.DisableMsg:GetBool() then
HpwRewrite:DoNotify("You can disable learning in SpawnMenu > Options > Wand Settings > Server > Disable learning", 3, 14)
end
end)
end
end
HpwRewrite.MessagePrinted = true
else
HpwRewrite:LogDebug("Popup hints are disabled or already printed")
end
end
else
self.HpwRewrite.ShouldBlockMouse = false
timer.Simple(0, function()
if not IsValid(self) then return end
if not IsValid(self.Owner) then return end
self.HpwRewrite.ShouldBlockMouse = tobool(self.Owner:GetInfoNum("hpwrewrite_cl_blockleftmouse", 0))
end)
self.HpwRewrite.Accuracy = 0
self.HpwRewrite.UpdateAccuracy = 0
self.HpwRewrite.CooldownAccuracy = 0
self:SetHPWAccuracyPenalty(1)
self:SetHPWAccuracyValue(0)
-- Annoying window to setup learning config
-- Leave it under comment
--[[local ply = self.Owner
if HpwRewrite.CheckAdmin(ply) and ply:IsSuperAdmin() and not setup:GetBool() then
net.Start("hpwrewrite_setup")
net.Send(ply)
RunConsoleCommand("hpwrewrite_setup", "1")
end]]
end
end
function SWEP:EmptySpellAttack()
self.Owner:SetAnimation(PLAYER_ATTACK1)
self:HPWSendAnimation(ACT_VM_PRIMARYATTACK)
self:SetNextPrimaryFire(CurTime() + self:HPWSeqDuration2())
if SERVER then
self:RequestSprite("", ColorRand(), 500, 0.6, true)
for i = 1, math.random(4, 8) do
timer.Simple(math.Rand(0, 0.4), function()
if IsValid(self) and IsValid(self.Owner) then
sound.Play("ambient/energy/zap" .. math.random(1, 3) .. ".wav", self:GetPos(), 60, math.random(200, 255))
end
end)
end
local tr = util.TraceLine({
start = self.Owner:GetShootPos(),
endpos = self.Owner:GetShootPos() + self.Owner:GetAimVector() * 256,
filter = self.Owner
})
local ent = tr.Entity
if IsValid(ent) and not (ent:IsNPC() or ent:IsPlayer()) then
local phys = ent:GetPhysicsObject()
if IsValid(phys) then
phys:ApplyForceOffset(self.Owner:GetAimVector() * math.Clamp(phys:GetMass() * 100, 1, 700), tr.HitPos)
ent:TakeDamage(5, self.Owner, self)
end
end
end
end
function SWEP:OnRemove()
timer.Remove("hpwrewrite_skinhelper" .. self:EntIndex())
if IsValid(self.Owner) then
local lastSpell = self:GetWandCurrentSpell()
if lastSpell != "" then self.Owner:SetPData("WeaponHpwrStick_LastSpell", lastSpell) end
local lastSkin = self:GetWandCurrentSkin()
if lastSkin != "" then self.Owner:SetPData("WeaponHpwrStick_LastSkin", lastSkin) end
end
end
function SWEP:Holster(wep, anim)
self:OnRemove()
if CLIENT then
self.HpwRewrite.Select = false
end
local curspell = HpwRewrite:GetPlayerSpell(self.Owner, self:GetWandCurrentSpell())
if curspell then curspell:OnWandHolster(self) end
return true
end
function SWEP:Deploy(anim)
if self.Owner:IsNPC() then print("Wand won't handle NPC owner! Removing...") self:Remove() return end
if not self.Owner:IsPlayer() then print("Wand owner should be a player! Removing...") self:Remove() return end
if not self.HpwRewrite then
self.HpwRewrite = { }
ErrorNoHalt("Wand's HpwRewrite table has been initialized in the Deploy function! Please, contact addon's developers\n")
end
self:HPWSendAnimation(ACT_VM_DRAW)
self:SetNextPrimaryFire(CurTime() + self:HPWSeqDuration2())
if SERVER then
if not self.Owner.HpwRewrite then
self.Owner.HpwRewrite = { }
HpwRewrite:LogDebug(self.Owner:Name() .. " HpwRewrite namespace has been initialized in SWEP")
print("Your HpwRewrite table has been initialized in the Deploy function! Please, contact addon's developers")
end
if not anim then
-- TODO: do something to remove this timer
-- Seems like gmod doesn't like doing it in the same frame as you deploy
timer.Create("hpwrewrite_skinhelper" .. self:EntIndex(), FrameTime(), 1, function()
if not IsValid(self) or not IsValid(self.Owner) then return end
if not self.Owner:GetPData("WeaponHpwrStick_LastSkin") then
self.Owner:SetPData("WeaponHpwrStick_LastSkin", HpwRewrite.DefaultSkin)
end
self:HPWSetWandSkin(self.Owner:GetPData("WeaponHpwrStick_LastSkin"))
end)
end
local oldspell = self.Owner:GetPData("WeaponHpwrStick_LastSpell")
if oldspell then
self:HPWSetCurrentSpell(oldspell)
end
local curspell = HpwRewrite:GetPlayerSpell(self.Owner, self:GetWandCurrentSpell())
if curspell then curspell:OnWandDeploy(self) end
end
return true
end
function SWEP:MakeSparks(col, lifetime)
local ef = EffectData()
ef:SetEntity(self.Owner)
ef:SetStart(Vector(col.r, col.g, col.b))
ef:SetScale(lifetime)
util.Effect("EffectHpwRewriteSparks", ef, true, true)
end
function SWEP:PrimaryAttack(spellName)
if self.Owner:InVehicle() and not self.Owner:GetAllowWeaponsInVehicle() then return end
if self.HpwRewrite.ShouldBlockMouse and not spellName then return end
if CurTime() < self:GetNextPrimaryFire() then return end
if HpwRewrite.FM:GetValue(self.Owner) then return end
-- Protection
self:SetNextPrimaryFire(CurTime() + 1.5)
-- Check if we have skin
local skintab = HpwRewrite:GetPlayerSkin(self.Owner, self:GetWandCurrentSkin())
if not skintab then
if SERVER then self:HPWSetWandSkin(HpwRewrite.DefaultSkin) end
return
end
-- Quick attack
if SERVER and spellName then
if self:HPWSetCurrentSpell(spellName) then
if game.SinglePlayer() then self:CallOnClient("PrimaryAttack") end
else
HpwRewrite:LogDebug(self.Owner:Name() .. " attempted to use quick attack with " .. spellName)
return
end
end
-- Making anims, checking if we can attack
local curspell = self:GetWandCurrentSpell()
local name = curspell
if not self:CheckSpellUseable(name) then self:EmptySpellAttack() return end
curspell = HpwRewrite:GetPlayerSpell(self.Owner, name)
if not curspell then self:EmptySpellAttack() return end
self.HpwRewrite.AnimationSpeed = curspell.AnimSpeedCoef or 1
self.HoldingSelfCast = curspell.ShouldReverseSelfCast
self.HpwRewrite.DidAnimations = false
if curspell.PlayAnimation then
self.Owner:SetAnimation(PLAYER_ATTACK1)
local newAnim = curspell:GetAnimations(self)
if newAnim then
self:HPWSendAnimation(ACT_VM_PRIMARYATTACK) -- if theres no newAnim
self:HPWSendAnimation(newAnim)
else
if skintab.ForceAnim then
self:HPWSendAnimation(table.Random(skintab.ForceAnim))
else
self:HPWSendAnimation(ACT_VM_PRIMARYATTACK)
end
if curspell.ForceAnim then self:HPWSendAnimation(table.Random(curspell.ForceAnim)) end
end
if curspell.CanSelfCast then
if HpwRewrite:IsHoldingSelfCast(self.Owner) then
if SERVER then
timer.Create("hpwrewrite_timer_selfcastspr" .. self:EntIndex(), self:HPWSeqDuration2() * 0.7, 1, function()
if IsValid(self) and self:CanContinue(curspell) then
self:HPWDoSprite(curspell)
end
end)
end
self.HoldingSelfCast = not curspell.ShouldReverseSelfCast
end
if curspell.DoSelfCastAnim then
if HpwRewrite:IsHoldingSelfCast(self.Owner) then
if not curspell.ShouldReverseSelfCast then
self:HPWSendAnimation(ACT_VM_HITCENTER)
end
else
if curspell.ShouldReverseSelfCast then
self:HPWSendAnimation(ACT_VM_HITCENTER)
end
end
end
end
self:SetNextPrimaryFire(CurTime() + self:HPWSeqDuration2())
self.HpwRewrite.DidAnimations = true
end
if curspell.ForceDelay then self:SetNextPrimaryFire(CurTime() + curspell.ForceDelay) end
-- Fire, fire, FIRE !!!
if SERVER and not self.Owner.HpwRewrite.BlockSpelling then -- The second expression is for Mimblewimble and so on
skintab:OnFire(self)
if curspell:PreFire(self) then
if curspell.DoSparks then
self:MakeSparks(curspell.SpriteColor, curspell.SparksLifeTime or 0.4)
end
if curspell.ApplyFireDelay then
timer.Simple(self:HPWSeqDuration2() * curspell.ApplyFireDelay, function()
if IsValid(self) and self:CanContinue(curspell) then self:AttackSpell(curspell) end
end)
else
self:AttackSpell(curspell)
end
if curspell.ShouldSay and not HpwRewrite.CVars.NoSay:GetBool() then
self.Owner:Say((curspell.WhatToSay or name) .. "!")
end
end
end
self.HpwRewrite.AnimationSpeed = 1
self.HpwRewrite.DidAnimations = false
end
function SWEP:Think()
if not IsValid(self.Owner) then return end
local idle = self:GetWandNextIdle()
if idle > 0 and CurTime() > idle then
self:HPWSendAnimation(ACT_VM_IDLE)
end
local curspell = HpwRewrite:GetPlayerSpell(self.Owner, self:GetWandCurrentSpell())
if curspell then curspell:Think(self) end
local curskin = HpwRewrite:GetPlayerSkin(self.Owner, self:GetWandCurrentSkin())
if curskin then curskin:Think(self) end
if SERVER then
if self.HpwRewrite.Accuracy and self.HpwRewrite.CooldownAccuracy then
if CurTime() > self.HpwRewrite.CooldownAccuracy then
self.HpwRewrite.Accuracy = math.Approach(self.HpwRewrite.Accuracy, 0, FrameTime() * 0.35)
end
if not self.HpwRewrite.UpdateAccuracy then self.HpwRewrite.UpdateAccuracy = 0 end
if CurTime() > self.HpwRewrite.UpdateAccuracy then
self:SetHPWAccuracyValue(self.HpwRewrite.Accuracy)
self.HpwRewrite.UpdateAccuracy = CurTime() + 0.1
end
end
end
-- Selecting
if CLIENT and LocalPlayer() == self.Owner then
if HpwRewrite.FM:GetValue() then return end
-- Selecting spell by mouse and context menu
if vgui.CursorVisible() and self.HpwRewrite.Select and not HpwRewrite.CVars.NoChoosing:GetBool() and HpwRewrite.CVars.DrawSpellBar:GetBool() and not HpwRewrite.CVars.NoHud:GetBool() then
local bind = HpwRewrite.BM.Binds[self:CalculateCellOffset()]
if self.HpwRewrite.ShouldSetPos then
local spell
for k, v in pairs(HpwRewrite.BM.Binds) do
if v.Spell == self:GetWandCurrentSpell() then
spell = k
break
end
end
if spell then
local x, y = self:GetCellPosition(spell)
input.SetCursorPos(x, y)
end
self.HpwRewrite.ShouldSetPos = false
end
if bind and bind.Spell != self.HpwRewrite.CurrentSpellPr then
HpwRewrite:RequestSpell(bind.Spell)
self.HpwRewrite.CurrentSpellPr = bind.Spell
end
end
-- Main menu
if not vgui.CursorVisible() then
if not self.HpwRewrite.WasMenuKeyPressed then self.HpwRewrite.WasMenuKeyPressed = false end
local key = HpwRewrite.CVars.MenuKey:GetInt()
local oldpressed = self.HpwRewrite.WasMenuKeyPressed
self.HpwRewrite.WasMenuKeyPressed = key >= 107 and input.IsMouseDown(key) or input.IsKeyDown(key)
if oldpressed != self.HpwRewrite.WasMenuKeyPressed and self.HpwRewrite.WasMenuKeyPressed then
if self:GetWandCurrentSkin() == "" then
HpwRewrite:RequestSpell(HpwRewrite.DefaultSkin)
end
HpwRewrite.VGUI:OpenNewSpellManager()
if self.HpwRewrite.PrintHelp then self.HpwRewrite.PrintHelp = false end
end
end
end
if self.OldOwner != nil and self.OldOwner != self.Owner then
self:Initialize()
end
self.OldOwner = self.Owner
self:NextThink(CurTime())
return true
end
function SWEP:SecondaryAttack()
end
|
vRP = Proxy.getInterface("vRP")
vRPclient = Tunnel.getInterface("vRP", "vrp_scoreboard")
local idVisable = true
local jobVisable = true
RegisterNetEvent("vrp_scoreboard:firstjoin")
AddEventHandler("vrp_scoreboard:firstjoin",function(connectedPlayers)
UpdatePlayerTable(connectedPlayers)
end)
Citizen.CreateThread(function()
Citizen.Wait(500)
SendNUIMessage({
action = 'updateServerInfo',
maxPlayers = GetConvarInt('sv_maxclients', 64),
uptime = 'unknown',
playTime = '00h 00m'
})
end)
RegisterNetEvent('esx_scoreboard:updateConnectedPlayers')
AddEventHandler('esx_scoreboard:updateConnectedPlayers', function(connectedPlayers)
UpdatePlayerTable(connectedPlayers)
end)
RegisterNetEvent('esx_scoreboard:updatePing')
AddEventHandler('esx_scoreboard:updatePing', function(connectedPlayers)
SendNUIMessage({
action = 'updatePing',
players = connectedPlayers
})
end)
RegisterNetEvent('esx_scoreboard:toggleID')
AddEventHandler('esx_scoreboard:toggleID', function(state)
if state then
idVisable = state
else
idVisable = not idVisable
end
SendNUIMessage({
action = 'toggleID',
state = idVisable
})
end)
RegisterNetEvent('esx_scoreboard:toggleJob')
AddEventHandler('esx_scoreboard:toggleJob', function(state)
if state then
jobVisable = state
else
jobVisable = not jobVisable
end
SendNUIMessage({
action = 'toggleJob',
state = jobVisable
})
end)
RegisterNetEvent('uptime:tick')
AddEventHandler('uptime:tick', function(uptime)
SendNUIMessage({
action = 'updateServerInfo',
uptime = uptime
})
end)
function UpdatePlayerTable(connectedPlayers)
local formattedPlayerList, num = {}, 1
local ems, police, taxi, mechanic, advokat, players = 0, 0, 0, 0, 0, 0, 0
for k,v in pairs(connectedPlayers) do
if num == 1 then
table.insert(formattedPlayerList, ('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td>'):format(v.name, v.id, v.job, v.ping))
num = 2
elseif num == 2 then
table.insert(formattedPlayerList, ('<td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>'):format(v.name, v.id, v.job, v.ping))
num = 1
end
players = players + 1
if v.job == 'Regionschef' or v.job == 'Viceregionschef' or v.job == 'Overlæge' or v.job == 'Akutlæge' or v.job == 'Ambulanceredder' or v.job == 'Redderelev' then
ems = ems + 1
elseif v.job == 'Rigspolitichef' or v.job == 'Vicerigspolitichef' or v.job == 'Politiinspektør' or v.job == 'Vicepolitiinspektør' or v.job == 'Civilbetjent' or v.job == 'Specialenhed' or v.job == 'Politikommissær' or v.job == 'Politiassistent' or v.job == 'Politibetjent' or v.job == 'Politielev' then
police = police + 1
elseif v.job == 'Taxa chauffør' then
taxi = taxi + 1
elseif v.job == 'Mekaniker' then
mechanic = mechanic + 1
elseif v.job == 'Advokat' then
advokat = advokat + 1
elseif v.job == 'realestateagent' then
estate = estate + 1
end
end
if num == 1 then
table.insert(formattedPlayerList, '</tr>')
end
SendNUIMessage({
action = 'updatePlayerList',
players = table.concat(formattedPlayerList)
})
SendNUIMessage({
action = 'updatePlayerJobs',
jobs = {ems = ems, police = police, taxi = taxi, mechanic = mechanic, advokat = advokat, player_count = players}
})
SendNUIMessage({
action = 'toggleJob',
state = jobVisable
})
SendNUIMessage({
action = 'toggleID',
state = idVisable
})
end
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
if IsControlJustReleased(0, 212) then
TriggerServerEvent("vrp_scoreboard:askperm")
Citizen.Wait(200)
-- D-pad up on controllers works, too!
elseif IsControlJustReleased(0, 172) and not IsInputDisabled(0) then
TriggerServerEvent("vrp_scoreboard:askperm")
Citizen.Wait(200)
end
end
end)
RegisterNetEvent("vrp_scoreboard:permgranted")
AddEventHandler("vrp_scoreboard:permgranted",function()
ToggleScoreBoard()
end)
-- Close scoreboard when game is paused
Citizen.CreateThread(function()
while true do
Citizen.Wait(300)
if IsPauseMenuActive() and not IsPaused then
IsPaused = true
SendNUIMessage({
action = 'close'
})
elseif not IsPauseMenuActive() and IsPaused then
IsPaused = false
end
end
end)
function ToggleScoreBoard()
SendNUIMessage({
action = 'toggle'
})
end
Citizen.CreateThread(function()
local playMinute, playHour = 0, 0
while true do
Citizen.Wait(1000 * 60) -- every minute
playMinute = playMinute + 1
if playMinute == 60 then
playMinute = 0
playHour = playHour + 1
end
SendNUIMessage({
action = 'updateServerInfo',
playTime = string.format("%02dh %02dm", playHour, playMinute)
})
end
end)
|
require "prefabutil"
local function onhammered(inst, worker)
if inst:HasTag("fire") and inst.components.burnable then
inst.components.burnable:Extinguish()
end
inst.components.lootdropper:DropLoot()
SpawnPrefab("collapse_small").Transform:SetPosition(inst.Transform:GetWorldPosition())
inst.SoundEmitter:PlaySound("dontstarve/common/destroy_wood")
inst:Remove()
end
local function CheckRain(inst)
if not inst:HasTag("burnt") then
if not inst.task then
inst.task = inst:DoPeriodicTask(1, CheckRain)
end
inst.AnimState:SetPercent("meter", GetSeasonManager():GetPOP())
end
end
local function onhit(inst, worker)
if inst.task then
inst.task:Cancel()
inst.task = nil
end
inst.AnimState:PlayAnimation("hit")
--the global animover handler will restart the check task
end
local assets =
{
Asset("ANIM", "anim/rain_meter.zip"),
}
local prefabs =
{
"collapse_small",
}
local function onbuilt(inst)
if inst.task then
inst.task:Cancel()
inst.task = nil
end
inst.AnimState:PlayAnimation("place")
--the global animover handler will restart the check task
end
local function makeburnt(inst)
if inst.task then
inst.task:Cancel()
inst.task = nil
end
end
local function onsave(inst, data)
if inst:HasTag("burnt") or inst:HasTag("fire") then
data.burnt = true
end
end
local function onload(inst, data)
if data and data.burnt then
inst.components.burnable.onburnt(inst)
end
end
local function fn(Sim)
local inst = CreateEntity()
local trans = inst.entity:AddTransform()
local anim = inst.entity:AddAnimState()
inst.entity:AddSoundEmitter()
local minimap = inst.entity:AddMiniMapEntity()
minimap:SetIcon( "rainometer.png" )
MakeObstaclePhysics(inst, .4)
anim:SetBank("rain_meter")
anim:SetBuild("rain_meter")
anim:SetPercent("meter", 0)
inst:AddComponent("inspectable")
inst:AddComponent("lootdropper")
inst:AddComponent("workable")
inst.components.workable:SetWorkAction(ACTIONS.HAMMER)
inst.components.workable:SetWorkLeft(4)
inst.components.workable:SetOnFinishCallback(onhammered)
inst.components.workable:SetOnWorkCallback(onhit)
MakeSnowCovered(inst, .01)
inst:ListenForEvent("onbuilt", onbuilt)
inst:ListenForEvent("animover", CheckRain)
CheckRain(inst)
inst:AddTag("structure")
MakeMediumBurnable(inst, nil, nil, true)
MakeSmallPropagator(inst)
inst.OnSave = onsave
inst.OnLoad = onload
inst:ListenForEvent("burntup", makeburnt)
return inst
end
return Prefab( "common/objects/rainometer", fn, assets, prefabs),
MakePlacer("common/rainometer_placer", "rain_meter", "rain_meter", "idle" )
|
local helpers = require('test.functional.helpers')(after_each)
local Screen = require('test.functional.ui.screen')
local clear, feed = helpers.clear, helpers.feed
local eval, eq, neq = helpers.eval, helpers.eq, helpers.neq
local execute, source, expect = helpers.execute, helpers.source, helpers.expect
local meths = helpers.meths
if helpers.pending_win32(pending) then return end
describe('completion', function()
local screen
before_each(function()
clear()
screen = Screen.new(60, 8)
screen:attach()
screen:set_default_attr_ids({
[0] = {bold=true, foreground=Screen.colors.Blue},
[1] = {background = Screen.colors.LightMagenta},
[2] = {background = Screen.colors.Grey},
[3] = {bold = true},
[4] = {bold = true, foreground = Screen.colors.SeaGreen},
[5] = {foreground = Screen.colors.Red},
[6] = {background = Screen.colors.Black},
[7] = {foreground = Screen.colors.White, background = Screen.colors.Red},
[8] = {reverse = true},
[9] = {bold = true, reverse = true},
})
end)
describe('v:completed_item', function()
it('is empty dict until completion', function()
eq({}, eval('v:completed_item'))
end)
it('is empty dict if the candidate is not inserted', function()
feed('ifoo<ESC>o<C-x><C-n>')
screen:expect([[
foo |
foo^ |
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- Keyword Local completion (^N^P) The only match} |
]])
feed('<C-e>')
screen:expect([[
foo |
^ |
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- INSERT --} |
]])
feed('<ESC>')
eq({}, eval('v:completed_item'))
end)
it('returns expected dict in normal completion', function()
feed('ifoo<ESC>o<C-x><C-n>')
eq('foo', eval('getline(2)'))
eq({word = 'foo', abbr = '', menu = '', info = '', kind = ''},
eval('v:completed_item'))
end)
it('is readonly', function()
screen:try_resize(80, 8)
feed('ifoo<ESC>o<C-x><C-n><ESC>')
execute('let v:completed_item.word = "bar"')
neq(nil, string.find(eval('v:errmsg'), '^E46: '))
execute('let v:errmsg = ""')
execute('let v:completed_item.abbr = "bar"')
neq(nil, string.find(eval('v:errmsg'), '^E46: '))
execute('let v:errmsg = ""')
execute('let v:completed_item.menu = "bar"')
neq(nil, string.find(eval('v:errmsg'), '^E46: '))
execute('let v:errmsg = ""')
execute('let v:completed_item.info = "bar"')
neq(nil, string.find(eval('v:errmsg'), '^E46: '))
execute('let v:errmsg = ""')
execute('let v:completed_item.kind = "bar"')
neq(nil, string.find(eval('v:errmsg'), '^E46: '))
execute('let v:errmsg = ""')
end)
it('returns expected dict in omni completion', function()
source([[
function! TestOmni(findstart, base) abort
return a:findstart ? 0 : [{'word': 'foo', 'abbr': 'bar',
\ 'menu': 'baz', 'info': 'foobar', 'kind': 'foobaz'},
\ {'word': 'word', 'abbr': 'abbr', 'menu': 'menu', 'info': 'info', 'kind': 'kind'}]
endfunction
setlocal omnifunc=TestOmni
]])
feed('i<C-x><C-o>')
eq('foo', eval('getline(1)'))
screen:expect([[
foo^ |
{2:bar foobaz baz }{0: }|
{1:abbr kind menu }{0: }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- Omni completion (^O^N^P) }{4:match 1 of 2} |
]])
eq({word = 'foo', abbr = 'bar', menu = 'baz',
info = 'foobar', kind = 'foobaz'},
eval('v:completed_item'))
end)
end)
describe('completeopt', function()
before_each(function()
source([[
function! TestComplete() abort
call complete(1, ['foo'])
return ''
endfunction
]])
end)
it('inserts the first candidate if default', function()
execute('set completeopt+=menuone')
feed('ifoo<ESC>o')
screen:expect([[
foo |
^ |
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- INSERT --} |
]])
feed('<C-x>')
-- the ^X prompt, only test this once
screen:expect([[
foo |
^ |
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- ^X mode (^]^D^E^F^I^K^L^N^O^Ps^U^V^Y)} |
]])
feed('<C-n>')
screen:expect([[
foo |
foo^ |
{2:foo }{0: }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- Keyword Local completion (^N^P) The only match} |
]])
feed('bar<ESC>')
eq('foobar', eval('getline(2)'))
feed('o<C-r>=TestComplete()<CR>')
screen:expect([[
foo |
foobar |
foo^ |
{2:foo }{0: }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- INSERT --} |
]])
eq('foo', eval('getline(3)'))
end)
it('selects the first candidate if noinsert', function()
execute('set completeopt+=menuone,noinsert')
feed('ifoo<ESC>o<C-x><C-n>')
screen:expect([[
foo |
^ |
{2:foo }{0: }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- Keyword Local completion (^N^P) The only match} |
]])
feed('<C-y>')
screen:expect([[
foo |
foo^ |
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- INSERT --} |
]])
feed('<ESC>')
eq('foo', eval('getline(2)'))
feed('o<C-r>=TestComplete()<CR>')
screen:expect([[
foo |
foo |
^ |
{2:foo }{0: }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- INSERT --} |
]])
feed('<C-y><ESC>')
eq('foo', eval('getline(3)'))
end)
it('does not insert the first candidate if noselect', function()
execute('set completeopt+=menuone,noselect')
feed('ifoo<ESC>o<C-x><C-n>')
screen:expect([[
foo |
^ |
{1:foo }{0: }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- Keyword Local completion (^N^P) }{5:Back at original} |
]])
feed('b')
screen:expect([[
foo |
b^ |
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- Keyword Local completion (^N^P) }{5:Back at original} |
]])
feed('ar<ESC>')
eq('bar', eval('getline(2)'))
feed('o<C-r>=TestComplete()<CR>')
screen:expect([[
foo |
bar |
^ |
{1:foo }{0: }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- INSERT --} |
]])
feed('bar<ESC>')
eq('bar', eval('getline(3)'))
end)
it('does not select/insert the first candidate if noselect and noinsert', function()
execute('set completeopt+=menuone,noselect,noinsert')
feed('ifoo<ESC>o<C-x><C-n>')
screen:expect([[
foo |
^ |
{1:foo }{0: }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- Keyword Local completion (^N^P) }{5:Back at original} |
]])
feed('<ESC>')
screen:expect([[
foo |
^ |
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
|
]])
eq('', eval('getline(2)'))
feed('o<C-r>=TestComplete()<CR>')
screen:expect([[
foo |
|
^ |
{1:foo }{0: }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- INSERT --} |
]])
feed('<ESC>')
screen:expect([[
foo |
|
^ |
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
|
]])
eq('', eval('getline(3)'))
end)
it('does not change modified state if noinsert', function()
execute('set completeopt+=menuone,noinsert')
execute('setlocal nomodified')
feed('i<C-r>=TestComplete()<CR><ESC>')
eq(0, eval('&l:modified'))
end)
it('does not change modified state if noselect', function()
execute('set completeopt+=menuone,noselect')
execute('setlocal nomodified')
feed('i<C-r>=TestComplete()<CR><ESC>')
eq(0, eval('&l:modified'))
end)
end)
describe('completeopt+=noinsert does not add blank undo items', function()
before_each(function()
source([[
function! TestComplete() abort
call complete(1, ['foo', 'bar'])
return ''
endfunction
]])
execute('set completeopt+=noselect,noinsert')
execute('inoremap <right> <c-r>=TestComplete()<cr>')
end)
local tests = {
['<up>, <down>, <cr>'] = {'<down><cr>', '<up><cr>'},
['<c-n>, <c-p>, <c-y>'] = {'<c-n><c-y>', '<c-p><c-y>'},
}
for name, seq in pairs(tests) do
it('using ' .. name, function()
feed('iaaa<esc>')
feed('A<right>' .. seq[1] .. '<esc>')
feed('A<right><esc>A<right><esc>')
feed('A<cr>bbb<esc>')
feed('A<right>' .. seq[2] .. '<esc>')
feed('A<right><esc>A<right><esc>')
feed('A<cr>ccc<esc>')
feed('A<right>' .. seq[1] .. '<esc>')
feed('A<right><esc>A<right><esc>')
local expected = {
{'foo', 'bar', 'foo'},
{'foo', 'bar', 'ccc'},
{'foo', 'bar'},
{'foo', 'bbb'},
{'foo'},
{'aaa'},
{''},
}
for i = 1, #expected do
if i > 1 then
feed('u')
end
eq(expected[i], eval('getline(1, "$")'))
end
for i = #expected, 1, -1 do
if i < #expected then
feed('<c-r>')
end
eq(expected[i], eval('getline(1, "$")'))
end
end)
end
end)
describe("refresh:always", function()
before_each(function()
source([[
function! TestCompletion(findstart, base) abort
if a:findstart
let line = getline('.')
let start = col('.') - 1
while start > 0 && line[start - 1] =~ '\a'
let start -= 1
endwhile
return start
else
let ret = []
for m in split("January February March April May June July August September October November December")
if m =~ a:base " match by regex
call add(ret, m)
endif
endfor
return {'words':ret, 'refresh':'always'}
endif
endfunction
set completeopt=menuone,noselect
set completefunc=TestCompletion
]])
end )
it('completes on each input char', function ()
feed('i<C-x><C-u>')
screen:expect([[
^ |
{1:January }{6: }{0: }|
{1:February }{6: }{0: }|
{1:March }{6: }{0: }|
{1:April }{2: }{0: }|
{1:May }{2: }{0: }|
{1:June }{2: }{0: }|
{3:-- User defined completion (^U^N^P) }{5:Back at original} |
]])
feed('u')
screen:expect([[
u^ |
{1:January }{0: }|
{1:February }{0: }|
{1:June }{0: }|
{1:July }{0: }|
{1:August }{0: }|
{0:~ }|
{3:-- User defined completion (^U^N^P) }{5:Back at original} |
]])
feed('g')
screen:expect([[
ug^ |
{1:August }{0: }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- User defined completion (^U^N^P) }{5:Back at original} |
]])
feed('<Down>')
screen:expect([[
ug^ |
{2:August }{0: }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- User defined completion (^U^N^P) The only match} |
]])
feed('<C-y>')
screen:expect([[
August^ |
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- INSERT --} |
]])
expect('August')
end)
it("repeats correctly after backspace #2674", function ()
feed('o<C-x><C-u>Ja')
screen:expect([[
|
Ja^ |
{1:January }{0: }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- User defined completion (^U^N^P) }{5:Back at original} |
]])
feed('<BS>')
screen:expect([[
|
J^ |
{1:January }{0: }|
{1:June }{0: }|
{1:July }{0: }|
{0:~ }|
{0:~ }|
{3:-- User defined completion (^U^N^P) }{5:Back at original} |
]])
feed('<C-n>')
screen:expect([[
|
January^ |
{2:January }{0: }|
{1:June }{0: }|
{1:July }{0: }|
{0:~ }|
{0:~ }|
{3:-- User defined completion (^U^N^P) }{4:match 1 of 3} |
]])
feed('<C-n>')
screen:expect([[
|
June^ |
{1:January }{0: }|
{2:June }{0: }|
{1:July }{0: }|
{0:~ }|
{0:~ }|
{3:-- User defined completion (^U^N^P) }{4:match 2 of 3} |
]])
feed('<Esc>')
screen:expect([[
|
Jun^e |
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
|
]])
feed('.')
screen:expect([[
|
June |
Jun^e |
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
|
]])
expect([[
June
June]])
end)
end)
describe('with a lot of items', function()
before_each(function()
source([[
function! TestComplete() abort
call complete(1, map(range(0,100), "string(v:val)"))
return ''
endfunction
]])
execute("set completeopt=menuone,noselect")
end)
it("works", function()
feed('i<C-r>=TestComplete()<CR>')
screen:expect([[
^ |
{1:0 }{6: }{0: }|
{1:1 }{2: }{0: }|
{1:2 }{2: }{0: }|
{1:3 }{2: }{0: }|
{1:4 }{2: }{0: }|
{1:5 }{2: }{0: }|
{3:-- INSERT --} |
]])
feed('7')
screen:expect([[
7^ |
{1:7 }{6: }{0: }|
{1:70 }{6: }{0: }|
{1:71 }{6: }{0: }|
{1:72 }{2: }{0: }|
{1:73 }{2: }{0: }|
{1:74 }{2: }{0: }|
{3:-- INSERT --} |
]])
feed('<c-n>')
screen:expect([[
7^ |
{2:7 }{6: }{0: }|
{1:70 }{6: }{0: }|
{1:71 }{6: }{0: }|
{1:72 }{2: }{0: }|
{1:73 }{2: }{0: }|
{1:74 }{2: }{0: }|
{3:-- INSERT --} |
]])
feed('<c-n>')
screen:expect([[
70^ |
{1:7 }{6: }{0: }|
{2:70 }{6: }{0: }|
{1:71 }{6: }{0: }|
{1:72 }{2: }{0: }|
{1:73 }{2: }{0: }|
{1:74 }{2: }{0: }|
{3:-- INSERT --} |
]])
end)
it('can be navigated with <PageDown>, <PageUp>', function()
feed('i<C-r>=TestComplete()<CR>')
screen:expect([[
^ |
{1:0 }{6: }{0: }|
{1:1 }{2: }{0: }|
{1:2 }{2: }{0: }|
{1:3 }{2: }{0: }|
{1:4 }{2: }{0: }|
{1:5 }{2: }{0: }|
{3:-- INSERT --} |
]])
feed('<PageDown>')
screen:expect([[
^ |
{1:0 }{6: }{0: }|
{1:1 }{2: }{0: }|
{1:2 }{2: }{0: }|
{2:3 }{0: }|
{1:4 }{2: }{0: }|
{1:5 }{2: }{0: }|
{3:-- INSERT --} |
]])
feed('<PageDown>')
screen:expect([[
^ |
{1:5 }{6: }{0: }|
{1:6 }{2: }{0: }|
{2:7 }{0: }|
{1:8 }{2: }{0: }|
{1:9 }{2: }{0: }|
{1:10 }{2: }{0: }|
{3:-- INSERT --} |
]])
feed('<Down>')
screen:expect([[
^ |
{1:5 }{6: }{0: }|
{1:6 }{2: }{0: }|
{1:7 }{2: }{0: }|
{2:8 }{0: }|
{1:9 }{2: }{0: }|
{1:10 }{2: }{0: }|
{3:-- INSERT --} |
]])
feed('<PageUp>')
screen:expect([[
^ |
{1:2 }{6: }{0: }|
{1:3 }{2: }{0: }|
{2:4 }{0: }|
{1:5 }{2: }{0: }|
{1:6 }{2: }{0: }|
{1:7 }{2: }{0: }|
{3:-- INSERT --} |
]])
feed('<PageUp>') -- stop on first item
screen:expect([[
^ |
{2:0 }{6: }{0: }|
{1:1 }{2: }{0: }|
{1:2 }{2: }{0: }|
{1:3 }{2: }{0: }|
{1:4 }{2: }{0: }|
{1:5 }{2: }{0: }|
{3:-- INSERT --} |
]])
feed('<PageUp>') -- when on first item, unselect
screen:expect([[
^ |
{1:0 }{6: }{0: }|
{1:1 }{2: }{0: }|
{1:2 }{2: }{0: }|
{1:3 }{2: }{0: }|
{1:4 }{2: }{0: }|
{1:5 }{2: }{0: }|
{3:-- INSERT --} |
]])
feed('<PageUp>') -- when unselected, select last item
screen:expect([[
^ |
{1:95 }{2: }{0: }|
{1:96 }{2: }{0: }|
{1:97 }{2: }{0: }|
{1:98 }{2: }{0: }|
{1:99 }{2: }{0: }|
{2:100 }{6: }{0: }|
{3:-- INSERT --} |
]])
feed('<PageUp>')
screen:expect([[
^ |
{1:94 }{2: }{0: }|
{1:95 }{2: }{0: }|
{2:96 }{0: }|
{1:97 }{2: }{0: }|
{1:98 }{2: }{0: }|
{1:99 }{6: }{0: }|
{3:-- INSERT --} |
]])
feed('<cr>')
screen:expect([[
96^ |
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- INSERT --} |
]])
end)
end)
it('disables folding during completion', function ()
execute("set foldmethod=indent")
feed('i<Tab>foo<CR><Tab>bar<Esc>gg')
screen:expect([[
^foo |
bar |
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
|
]])
feed('A<C-x><C-l>')
screen:expect([[
foo^ |
bar |
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- Whole line completion (^L^N^P) }{7:Pattern not found} |
]])
eq(-1, eval('foldclosed(1)'))
end)
it('popupmenu is not interrupted by events', function ()
execute("set complete=.")
feed('ifoobar fooegg<cr>f<c-p>')
screen:expect([[
foobar fooegg |
fooegg^ |
{1:foobar }{0: }|
{2:fooegg }{0: }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- Keyword completion (^N^P) }{4:match 1 of 2} |
]])
eval('1 + 1')
-- popupmenu still visible
screen:expect([[
foobar fooegg |
fooegg^ |
{1:foobar }{0: }|
{2:fooegg }{0: }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- Keyword completion (^N^P) }{4:match 1 of 2} |
]])
feed('<c-p>')
-- Didn't restart completion: old matches still used
screen:expect([[
foobar fooegg |
foobar^ |
{2:foobar }{0: }|
{1:fooegg }{0: }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- Keyword completion (^N^P) }{4:match 2 of 2} |
]])
end)
describe('from the commandline window', function()
it('is cleared after CTRL-C', function ()
feed('q:')
feed('ifoo faa fee f')
screen:expect([[
|
{8:[No Name] }|
{0::}foo faa fee f^ |
{0::~ }|
{0::~ }|
{0::~ }|
{9:[Command Line] }|
{3:-- INSERT --} |
]] )
feed('<c-x><c-n>')
screen:expect([[
|
{8:[No Name] }|
{0::}foo faa fee foo^ |
{0::~ }{2: foo }{0: }|
{0::~ }{1: faa }{0: }|
{0::~ }{1: fee }{0: }|
{9:[Command Line] }|
{3:-- Keyword Local completion (^N^P) }{4:match 1 of 3} |
]])
feed('<c-c>')
screen:expect([[
|
{8:[No Name] }|
{0::}foo faa fee foo |
{0::~ }|
{0::~ }|
{0::~ }|
{9:[Command Line] }|
:foo faa fee foo^ |
]])
end)
end)
describe('with numeric items', function()
before_each(function()
source([[
function! TestComplete() abort
call complete(1, g:_complist)
return ''
endfunction
]])
meths.set_option('completeopt', 'menuone,noselect')
meths.set_var('_complist', {{
word=0,
abbr=1,
menu=2,
kind=3,
info=4,
icase=5,
dup=6,
empty=7,
}})
end)
it('shows correct variant as word', function()
feed('i<C-r>=TestComplete()<CR>')
screen:expect([[
^ |
{1:1 3 2 }{0: }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{0:~ }|
{3:-- INSERT --} |
]])
end)
end)
end)
describe('External completion popupmenu', function()
local screen
local items, selected, anchor
before_each(function()
clear()
screen = Screen.new(60, 8)
screen:attach({rgb=true, popupmenu_external=true})
screen:set_default_attr_ids({
[1] = {bold=true, foreground=Screen.colors.Blue},
[2] = {bold = true},
})
screen:set_on_event_handler(function(name, data)
if name == "popupmenu_show" then
local row, col
items, selected, row, col = unpack(data)
anchor = {row, col}
elseif name == "popupmenu_select" then
selected = data[1]
elseif name == "popupmenu_hide" then
items = nil
end
end)
end)
it('works', function()
source([[
function! TestComplete() abort
call complete(1, ['foo', 'bar', 'spam'])
return ''
endfunction
]])
local expected = {
{'foo', '', '', ''},
{'bar', '', '', ''},
{'spam', '', '', ''},
}
feed('o<C-r>=TestComplete()<CR>')
screen:expect([[
|
foo^ |
{1:~ }|
{1:~ }|
{1:~ }|
{1:~ }|
{1:~ }|
{2:-- INSERT --} |
]], nil, nil, function()
eq(expected, items)
eq(0, selected)
eq({1,0}, anchor)
end)
feed('<c-p>')
screen:expect([[
|
^ |
{1:~ }|
{1:~ }|
{1:~ }|
{1:~ }|
{1:~ }|
{2:-- INSERT --} |
]], nil, nil, function()
eq(expected, items)
eq(-1, selected)
eq({1,0}, anchor)
end)
-- down moves the selection in the menu, but does not insert anything
feed('<down><down>')
screen:expect([[
|
^ |
{1:~ }|
{1:~ }|
{1:~ }|
{1:~ }|
{1:~ }|
{2:-- INSERT --} |
]], nil, nil, function()
eq(expected, items)
eq(1, selected)
eq({1,0}, anchor)
end)
feed('<cr>')
screen:expect([[
|
bar^ |
{1:~ }|
{1:~ }|
{1:~ }|
{1:~ }|
{1:~ }|
{2:-- INSERT --} |
]], nil, nil, function()
eq(nil, items) -- popupmenu was hidden
end)
end)
end)
|
if AkDebugLoad then print("Loading Bus ...") end
-----------------------
-- Bushaltestellen
-----------------------
---@class Bus
Bus = {}
--- Oeffnet die Tueren eines Busses (Fahrzeugverband)
-- @param bus Fahrzeugverband
--
function Bus.openDoors(bus)
assert(bus, "bus wurde nicht angegeben.")
-- Ikarus Busse und andere?
EEPSetTrainAxis(bus, "Tuer1", 100)
if (math.random(0, 1) > 0) then EEPSetTrainAxis(bus, "Tuer2", 100) end
if (math.random(0, 1) > 0) then EEPSetTrainAxis(bus, "Tuer3", 100) end
if (math.random(0, 1) > 0) then EEPSetTrainAxis(bus, "Tuer4", 100) end
end
--- Schliesst die Tueren eines Busses (Fahrzeugverband)
-- @param bus Fahrzeugverband
--
function Bus.closeDoors(bus)
assert(bus, "bus wurde nicht angegeben.")
-- Ikarus Busse und andere?
EEPSetTrainAxis(bus, "Tuer1", 0)
EEPSetTrainAxis(bus, "Tuer2", 0)
EEPSetTrainAxis(bus, "Tuer3", 0)
EEPSetTrainAxis(bus, "Tuer4", 0)
end
--- Schaltet den Fahrer und die Fahrgaeste ein
-- @param fahrzeugverband
--
function Bus.initialisiere(fahrzeugverband)
EEPSetTrainAxis(fahrzeugverband, "Fahrer", 100)
EEPSetTrainAxis(fahrzeugverband, "Fahrgast", 100)
end
-- luacheck: push ignore FAHRZEUG_INITIALISIERE
--- Funktion fuer den Aufruf direkt in EEP
-- @param fahrzeug wird von EEP automatisch gefuellt
--
function FAHRZEUG_INITIALISIERE(fahrzeug) Bus.initialisiere(fahrzeug) end
-- luacheck: pop
|
local dyes = {
{"white", "White"},
{"grey", "Grey"},
{"black", "Black"},
{"red", "Red"},
{"yellow", "Yellow"},
{"green", "Green"},
{"cyan", "Cyan"},
{"blue", "Blue"},
{"magenta", "Magenta"},
{"orange", "Orange"},
{"violet", "Violet"},
{"brown", "Brown"},
{"pink", "Pink"},
{"dark_grey", "Dark Grey"},
{"dark_green", "Dark Green"},
}
for i = 1, #dyes do
local name, desc = unpack(dyes[i])
minetest.register_node("wool:" .. name, {
description = desc .. " Wool",
tiles = {"wool_" .. name .. ".png"},
is_ground_content = false,
groups = {snappy = 2, choppy = 2, oddly_breakable_by_hand = 3,
flammable = 3, wool = 1},
sounds = default.node_sound_defaults(),
})
minetest.register_craft{
type = "shapeless",
output = "wool:" .. name,
recipe = {"group:dye,color_" .. name, "group:wool"},
}
end
-- Legacy
-- Backwards compatibility with jordach's 16-color wool mod
minetest.register_alias("wool:dark_blue", "wool:blue")
minetest.register_alias("wool:gold", "wool:yellow")
|
local localization =
{
ATT_STR_STATISTICS = "Estatística",
ATT_STR_NAME = "Nome",
ATT_STR_GUILD = "Guilda",
ATT_STR_TOTAL = "Total",
ATT_STR_TAXES = "Taxas",
ATT_STR_INTERNAL = "Interno",
ATT_STR_ITEMCOUNT = "# Itens",
ATT_STR_TODAY = "Hoje",
ATT_STR_YESTERDAY = "Ontem",
ATT_STR_TWO_DAYS_AGO = "Dois dias antes",
ATT_STR_THIS_WEEK = "Esta semana",
ATT_STR_LAST_WEEK = "Semana anterior",
ATT_STR_PRIOR_WEEK = "Duas semanas atrás",
ATT_STR_7_DAYS = "7 dias",
ATT_STR_10_DAYS = "10 dias",
ATT_STR_14_DAYS = "14 dias",
ATT_STR_30_DAYS = "30 dias",
ATT_STR_FILTER_TEXT_TOOLTIP = "Filtro de texto para nomes de usuário ou guilda",
ATT_STR_FILTER_SUBSTRING_TOOLTIP = "Muda a pesquisa da guia atual para a guia secundária ou vice-versa. Substitui os caracteres em letras maiúsculas em minúsculas.",
}
ZO_ShallowTableCopy(localization, ArkadiusTradeTools.Modules.Statistics.Localization)
|
local replicaset_uuid = {'cbf06940-0790-498b-948d-042b62cf3d29',
'ac522f65-aa94-4134-9f64-51ee384f1a54'}
local name_to_uuid = {
bad_uuid_1_a = '8a274925-a26d-47fc-9e1b-af88ce939412',
bad_uuid_1_b = '3de2e3e1-9ebe-4d0d-abb1-26d301b84633',
bad_uuid_2_a = '1e02ae8a-afc0-4e91-ba34-843a356b8ed7',
bad_uuid_2_b = '001688c3-66f8-4a31-8e19-036c17d489c2',
}
local shard_cfg = {
sharding = {
[replicaset_uuid[1]] = {
replicas = {
[name_to_uuid.bad_uuid_1_a] = {
uri = 'storage:[email protected]:3301',
name = 'bad_uuid_1_a',
master = true
},
[name_to_uuid.bad_uuid_1_b] = {
uri = 'storage:[email protected]:3302',
name = 'bad_uuid_1_b'
}
}
},
[replicaset_uuid[2]] = {
replicas = {
[name_to_uuid.bad_uuid_2_a] = {
uri = 'storage:[email protected]:3303',
name = 'bad_uuid_2_a',
master = true
},
[name_to_uuid.bad_uuid_2_b] = {
uri = 'storage:[email protected]:3304',
name = 'bad_uuid_2_b'
}
}
},
}
}
return {cfg = shard_cfg, replicaset_uuid = replicaset_uuid,
name_to_uuid = name_to_uuid, replication_connect_quorum = 0}
|
:: # Copyright 2013, Big Switch Networks, Inc.
:: #
:: # LoxiGen is licensed under the Eclipse Public License, version 1.0 (EPL), with
:: # the following special exception:
:: #
:: # LOXI Exception
:: #
:: # As a special exception to the terms of the EPL, you may distribute libraries
:: # generated by LoxiGen (LoxiGen Libraries) under the terms of your choice, provided
:: # that copyright and licensing notices generated by LoxiGen are not altered or removed
:: # from the LoxiGen Libraries and the notice provided below is (i) included in
:: # the LoxiGen Libraries, if distributed in source code form and (ii) included in any
:: # documentation for the LoxiGen Libraries, if distributed in binary form.
:: #
:: # Notice: "Copyright 2013, Big Switch Networks, Inc. This library was generated by the LoxiGen Compiler."
:: #
:: # You may not use this file except in compliance with the EPL or LOXI Exception. You may obtain
:: # a copy of the EPL at:
:: #
:: # http://www.eclipse.org/legal/epl-v10.html
:: #
:: # Unless required by applicable law or agreed to in writing, software
:: # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
:: # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
:: # EPL for the specific language governing permissions and limitations
:: # under the EPL.
::
OFReader = {}
OFReader.new = function(buf, offset)
local self = {}
offset = offset or 0
self.read = function(len)
local r = buf(offset, len)
offset = offset + len
return r
end
self.read_all = function()
local r = buf(offset, buf:len() - offset)
offset = buf:len()
return r
end
self.peek = function(off, len)
return buf(offset + off, len)
end
self.peek_all = function(off)
return buf(offset + off, buf:len() - offset - off)
end
self.skip = function(len)
offset = offset + len
end
self.is_empty = function()
return offset == buf:len()
end
self.slice = function(len)
r = OFReader.new(buf(offset, len))
offset = offset + len
return r
end
self.skip_align = function()
offset = math.floor((offset + 7)/8)*8
end
return self
end
|
return {'iddergem'}
|
local createEnum = import("../createEnum")
return createEnum("VirtualInputMode", {
None = 0,
Recording = 1,
Playing = 2,
})
|
local PULSE_SCAN = script:GetCustomProperty("PULSE_SCAN"):WaitForObject()
local PULSE_SCAN_ORIGIN_Y = PULSE_SCAN.y
function Tick(deltaTime)
PULSE_SCAN.y = PULSE_SCAN_ORIGIN_Y + math.sin(time() * 0.35) * 101
end
|
-----------------------------------
-- Area: Western Altepa Desert (125)
-- Mob: Maharaja
-- Note: Popped by qm1
-- Involved in Quest: Inheritance
-- !pos -652.3 0.2 -341.5 125
-----------------------------------
require("scripts/globals/wsquest")
require("scripts/globals/status")
-----------------------------------
function onMobInitialize(mob)
mob:setMobMod(tpz.mobMod.EXP_BONUS, -100)
mob:setMobMod(tpz.mobMod.IDLE_DESPAWN, 180)
end
function onMobDeath(mob, player, isKiller)
tpz.wsquest.handleWsnmDeath(tpz.wsquest.ground_strike, player)
end
|
lust = require 'tests/lust'
Rx = require 'rx'
for _, fn in pairs({'describe', 'it', 'test', 'expect', 'spy', 'before', 'after'}) do
_G[fn] = lust[fn]
end
observableSpy = function(observable)
local observer = Rx.Observer.create(_, function() end, _)
local onNext = spy(observer, '_onNext')
local onError = spy(observer, '_onError')
local onCompleted = spy(observer, '_onCompleted')
observable:subscribe(observer)
return onNext, onError, onCompleted
end
lust.paths['produce'] = {
'nothing',
'error',
f = function(observable, ...)
local args = {...}
local values
if type(args[1]) ~= 'table' then
values = {}
for i = 1, math.max(#args, 1) do
table.insert(values, {args[i]})
end
else
values = args[1]
end
local onNext, onError, onCompleted = observableSpy(observable)
expect(observable).to.be.an(Rx.Observable)
expect(onNext).to.equal(values)
expect(#onError).to.equal(0)
expect(#onCompleted).to.equal(1)
return true
end
}
lust.paths['nothing'] = {
f = function(observable)
local onNext, onError, onCompleted = observableSpy(observable)
expect(observable).to.be.an(Rx.Observable)
expect(#onNext).to.equal(0)
expect(#onError).to.equal(0)
expect(#onCompleted).to.equal(1)
return true
end
}
lust.paths['error'] = {
f = function(observable)
local _, onError = observableSpy(observable)
expect(observable).to.be.an(Rx.Observable)
expect(#onError).to.equal(1)
return true
end
}
table.insert(lust.paths['to'], 'produce')
if arg[1] then
arg[1] = arg[1]:gsub('^(tests/)', ''):gsub('%.lua$', '')
dofile('tests/' .. arg[1] .. '.lua')
else
local files = {
'observer',
'observable',
'subscription',
'subject',
'asyncsubject',
'behaviorsubject',
'replaysubject'
}
for i, file in ipairs(files) do
dofile('tests/' .. file .. '.lua')
if next(files, i) then
print()
end
end
end
local red = string.char(27) .. '[31m'
local green = string.char(27) .. '[32m'
local normal = string.char(27) .. '[0m'
if lust.errors > 0 then
io.write(red .. lust.errors .. normal .. ' failed, ')
end
print(green .. lust.passes .. normal .. ' passed')
if lust.errors > 0 then os.exit(1) end
|
-- =============================================================================
-- URL: https://github.com/sainnhe/amora
-- Filename: lua/lualine/themes/amora.lua
-- Author: sainnhe
-- Email: [email protected]
-- License: MIT License
-- =============================================================================
local configuration = vim.fn['amora#get_configuration']()
local palette = vim.fn['amora#get_palette'](configuration.style)
return {
normal = {
a = {bg = palette.bg_blue[1], fg = palette.bg0[1], gui = 'bold'},
b = {bg = palette.bg4[1], fg = palette.fg[1]},
c = {bg = palette.bg1[1], fg = palette.fg[1]}
},
insert = {
a = {bg = palette.bg_green[1], fg = palette.bg0[1], gui = 'bold'},
b = {bg = palette.bg4[1], fg = palette.fg[1]},
c = {bg = palette.bg1[1], fg = palette.fg[1]}
},
visual = {
a = {bg = palette.bg_red[1], fg = palette.bg0[1], gui = 'bold'},
b = {bg = palette.bg4[1], fg = palette.fg[1]},
c = {bg = palette.bg1[1], fg = palette.fg[1]}
},
replace = {
a = {bg = palette.orange[1], fg = palette.bg0[1], gui = 'bold'},
b = {bg = palette.bg4[1], fg = palette.fg[1]},
c = {bg = palette.bg1[1], fg = palette.fg[1]}
},
command = {
a = {bg = palette.yellow[1], fg = palette.bg0[1], gui = 'bold'},
b = {bg = palette.bg4[1], fg = palette.fg[1]},
c = {bg = palette.bg1[1], fg = palette.fg[1]}
},
terminal = {
a = {bg = palette.purple[1], fg = palette.bg0[1], gui = 'bold'},
b = {bg = palette.bg3[1], fg = palette.fg[1]},
c = {bg = palette.bg1[1], fg = palette.fg[1]}
},
inactive = {
a = {bg = palette.bg1[1], fg = palette.grey[1]},
b = {bg = palette.bg1[1], fg = palette.grey[1]},
c = {bg = palette.bg1[1], fg = palette.grey[1]}
}
}
|
/******************************************************************************\
Server Information
\******************************************************************************/
__e2setcost(1)
e2function string map()
return game.GetMap()
end
local hostname = GetConVar("hostname")
e2function string hostname()
return hostname:GetString()
end
e2function string hostip()
return game.GetIPAddress()
end
local sv_lan = GetConVar("sv_lan")
e2function number isLan()
return sv_lan:GetBool() and 1 or 0
end
e2function string gamemode()
return gmod.GetGamemode().Name
end
e2function string serverUUID()
return WireLib.GetServerUUID()
end
e2function number isSinglePlayer()
return game.SinglePlayer() and 1 or 0
end
e2function number isDedicated()
return game.IsDedicated() and 1 or 0
end
e2function number numPlayers()
return player.GetCount()
end
e2function number maxPlayers()
return game.MaxPlayers()
end
local sv_gravity = GetConVar("sv_gravity")
e2function number gravity()
return sv_gravity:GetFloat()
end
e2function vector propGravity()
return physenv.GetGravity()
end
e2function number airDensity()
return physenv.GetAirDensity()
end
e2function number maxFrictionMass()
return physenv.GetPerformanceSettings()["MaxFrictionMass"]
end
e2function number minFrictionMass()
return physenv.GetPerformanceSettings()["MinFrictionMass"]
end
e2function number speedLimit()
return physenv.GetPerformanceSettings()["MaxVelocity"]
end
e2function number angSpeedLimit()
return physenv.GetPerformanceSettings()["MaxAngularVelocity"]
end
e2function number tickInterval()
return engine.TickInterval()
end
|
-- example_api的前端展示, 仅用于测试接口数据的展示, 可忽略这个文件
local ngx = require "ngx"
local loadfile_to_ram = require "utils".loadfile_to_ram
local waf = require "waf"
local response = require "response"
local ngx_var = ngx.var
local ngx_log = ngx.log
local ngx_ERR = ngx.ERR
local ngx_re_sub = ngx.re.sub
local _M = {}
_M.name = "example_api2"
_M._VERSION = "0.1"
_M.access = function()
waf.deny_ip_access()
end
_M.content = function()
response.say_ok({"This is example_api2"})
end
return _M
|
hs.hotkey.bind({"cmd", "alt"}, "V", function() hs.eventtap.keyStrokes(hs.pasteboard.getContents()) end)
-- local function keyCode(key)
-- return function() hs.eventtap.keyStroke({}, key) end
-- end
--
-- hs.hotkey.bind({"shift", "ctrl"}, 'h', keyCode('left') , nil, keyCode('left'))
-- hs.hotkey.bind({"shift", "ctrl"}, 'j', keyCode('down') , nil, keyCode('down') )
-- hs.hotkey.bind({"shift", "ctrl"}, 'k', keyCode('up') , nil, keyCode('up') )
-- hs.hotkey.bind({"shift", "ctrl"}, 'l', keyCode('right'), nil, keyCode('right') )
--
--
-- hattip https://github.com/lodestone/hyper-hacks
-- hattip https://gist.github.com/ttscoff/cce98a711b5476166792d5e6f1ac5907
-- -- A global variable for the sub-key Hyper Mode
-- k = hs.hotkey.modal.new({}, 'F18')
-- -- Hyper+key for all the below are setup somewhere
-- -- The handler already exists, usually in Keyboard Maestro
-- -- we just have to get the right keystroke sent
-- hyperBindings = {'c','m','a','r','d','g','s','f','TAB','v','b'}
-- for i,key in ipairs(hyperBindings) do
-- k:bind({}, key, nil, function() hs.eventtap.keyStroke({'cmd','alt','shift','ctrl'}, key)
-- k.triggered = true
-- end)
-- end
-- -- Enter Hyper Mode when F19 (left control) is pressed
-- pressedF19 = function()
-- k.triggered = false
-- k:enter()
-- end
-- -- Leave Hyper Mode when F19 (left control) is pressed,
-- -- send ESCAPE if no other keys are pressed.
-- releasedF19 = function()
-- k:exit()
-- if not k.triggered then
-- hs.eventtap.keyStroke({}, 'ESCAPE')
-- end
-- end
-- -- Bind the Hyper key
-- f19 = hs.hotkey.bind({}, 'F19', pressedF19, releasedF19)
-- -- vi cursor movement commands
-- movements = {
-- { 'h', {}, 'LEFT'},
-- { 'j', {}, 'DOWN'},
-- { 'k', {}, 'UP'},
-- { 'l', {}, 'RIGHT'},
-- { '0', {'cmd'}, 'LEFT'}, -- beginning of line
-- { '4', {'cmd'}, 'RIGHT'}, -- end of line
-- { 'b', {'alt'}, 'LEFT'}, -- back word
-- { 'w', {'alt'}, 'RIGHT'}, -- forward word
-- }
-- for i,bnd in ipairs(movements) do
-- hs.hotkey.bind({'ctrl'}, bnd[1], function()
-- hs.eventtap.keyStroke(bnd[2],bnd[3])
-- end)
-- end
-- -- Reload config when any lua file in config directory changes
-- function reloadConfig(files)
-- doReload = false
-- for _,file in pairs(files) do
-- if file:sub(-4) == '.lua' then
-- doReload = true
-- end
-- end
-- if doReload then
-- hs.reload()
-- end
-- end
-- local myWatcher = hs.pathwatcher.new(os.getenv('HOME') .. '/.hammerspoon/', reloadConfig):start()
-- hs.alert.show('Config loaded')
--
-- Window resizers
--
-- hs.hotkey.bind(k, "Left", function()
-- local win = hs.window.focusedWindow()
-- local f = win:frame()
-- local screen = win:screen()
-- local max = screen:frame()
-- f.x = max.x
-- f.y = max.y
-- f.w = max.w / 2
-- f.h = max.h
-- win:setFrame(f)
-- end)
-- hs.hotkey.bind(k, "Right", function()
-- local win = hs.window.focusedWindow()
-- local f = win:frame()
-- local screen = win:screen()
-- local max = screen:frame()
-- f.x = max.x + (max.w / 2)
-- f.y = max.y
-- f.w = max.w / 2
-- f.h = max.h
-- win:setFrame(f)
-- end)
-- hs.hotkey.bind(hyper,"Up", function()
-- local win = hs.window.focusedWindow()
-- local f = win:frame()
-- local screen = win:screen()
-- local max = screen:frame()
-- f.x = max.x
-- f.y = max.y
-- f.w = max.w / 3
-- f.h = max.h
-- win:setFrame(f)
-- end)
-- hs.hotkey.bind(hyper,"Down", function()
-- local win = hs.window.focusedWindow()
-- local f = win:frame()
-- local screen = win:screen()
-- local max = screen:frame()
-- f.x = max.x + (max.w / 3 * 2)
-- f.y = max.y
-- f.w = max.w / 3
-- f.h = max.h
-- win:setFrame(f)
-- end)
--
-- Workspaces
--
-- hs.hotkey.bind(hyper,"F1", function()
-- local macbook = "Color LCD"
-- local thunderbolt = "Thunderbolt Display"
-- local windowLayout = {
-- {"Google Chrome", nil, thunderbolt, hs.layout.left50, nil, nil},
-- {"iTerm", nil, thunderbolt, hs.layout.right50, nil, nil},
-- {"Messages", nil, thunderbolt, hs.layout.left30, nil, nil},
-- {"Tweetbot", nil, thunderbolt, hs.layout.left30, nil, nil},
-- {"Gitter", nil, thunderbolt, hs.layout.left30, nil, nil},
-- {"nvALT", nil, thunderbolt, hs.layout.right25, nil, nil},
-- {"PureCloud", nil, macbook, hs.layout.right50, nil, nil},
-- {"Microsoft Outlook", nil, macbook, hs.layout.left50, nil, nil},
-- }
-- hs.layout.apply(windowLayout)
-- end)
-- hs.hotkey.bind(hyper,"F2", function()
-- local iMac = "iMac"
-- local windowLayout = {
-- {"Google Chrome", nil, iMac, hs.layout.left50, nil, nil},
-- {"iTerm", nil, iMac, hs.layout.right50, nil, nil},
-- {"Messages", nil, iMac, hs.layout.left30, nil, nil},
-- {"Tweetbot", nil, iMac, hs.layout.left30, nil, nil},
-- {"Gitter", nil, iMac, hs.layout.left30, nil, nil},
-- {"nvALT", nil, iMac, hs.layout.right25, nil, nil},
-- }
-- hs.layout.apply(windowLayout)
-- end)
-- hs.hotkey.bind(hyper,"F3", function()
-- local macbook = "Color LCD"
-- local windowLayout = {
-- {"Vivaldi", nil, macbook, hs.layout.left60, nil, nil},
-- {"iTerm", nil, macbook, hs.layout.right35, nil, nil},
-- {"Messages", nil, macbook, hs.layout.right40, nil, nil},
-- {"Tweetbot", nil, macbook, hs.layout.right40, nil, nil},
-- {"Gitter", nil, macbook, hs.layout.right40, nil, nil},
-- {"nvALT", nil, macbook, hs.layout.right40, nil, nil},
-- }
-- hs.layout.apply(windowLayout)
-- end)
hs.hotkey.bind({"cmd", "alt", "ctrl", "shift"}, "P", function()
local macbook = "Color LCD"
local thunderbolt = "Thunderbolt Display"
local thunderboltMain = hs.screen.allScreens()[0]
local thunderboltRight = hs.screen.allScreens()[3]
if (hs.screen.allScreens()[1]:name() == thunderbolt) then
print(thunderboltMain)
local windowLayout = {
{"Firefox", nil, thunderboltRight, hs.layout.left50, nil, nil},
{"Safari", nil, thunderboltRight, hs.layout.left50, nil, nil},
{"Google Chrome", nil, thunderboltRight, hs.layout.left50, nil, nil},
{"iTunes", nil, thunderboltRight, hs.layout.left50, nil, nil},
{"AutoCAD 2017", nil, thunderboltMain, hs.layout.maximized, nil, nil},
{"iTerm", nil, thunderboltMain, hs.layout.maximized, nil, nil},
{"Xcode", nil, thunderboltMain, hs.layout.maximized, nil, nil},
{"Sublime Text", nil, thunderboltMain, hs.layout.right50, nil, nil},
{"Reminders", nil, thunderboltRight, hs.layout.right30, nil, nil},
{"Calendar", nil, thunderboltRight, hs.layout.right50, nil, nil},
{"Discord", nil, macbook, hs.layout.right50, nil, nil},
{"PureCloud", nil, macbook, hs.layout.right50, nil, nil},
{"Mail", nil, macbook, hs.layout.left50, nil, nil},
{"Slack", nil, macbook, hs.layout.left50, nil, nil},
{"Gitter", nil, macbook, hs.layout.left50, nil, nil},
{"Messages", nil, macbook, hs.layout.right30, nil, nil},
{"Tweetbot", nil, macbook, hs.layout.right30, nil, nil},
{"nvALT", nil, thunderboltRight, hs.layout.left30, nil, nil},
{"pwSafe", nil, macbook, hs.layout.left50, nil, nil},
{"Skim", nil, thunderboltRight, hs.layout.right50, nil, nil},
{"Preview", nil, thunderboltRight, hs.layout.right50, nil, nil},
}
hs.layout.apply(windowLayout)
else
print(macbook)
local windowLayout = {
{"Firefox", nil, macbook, hs.layout.left50, nil, nil},
{"Safari", nil, macbook, hs.layout.left50, nil, nil},
{"Google Chrome", nil, macbook, hs.layout.left50, nil, nil},
{"iTunes", nil, macbook, hs.layout.left50, nil, nil},
{"AutoCAD 2017", nil, macbook, hs.layout.maximized, nil, nil},
{"iTerm", nil, macbook, hs.layout.maximized, nil, nil},
{"Xcode", nil, macbook, hs.layout.maximized, nil, nil},
{"Sublime Text", nil, macbook, hs.layout.right50, nil, nil},
{"Reminders", nil, macbook, hs.layout.right30, nil, nil},
{"Calendar", nil, macbook, hs.layout.right50, nil, nil},
{"Discord", nil, macbook, hs.layout.right50, nil, nil},
{"PureCloud", nil, macbook, hs.layout.right50, nil, nil},
{"Mail", nil, macbook, hs.layout.left50, nil, nil},
{"Slack", nil, macbook, hs.layout.left50, nil, nil},
{"Gitter", nil, macbook, hs.layout.left50, nil, nil},
{"Messages", nil, macbook, hs.layout.right30, nil, nil},
{"Tweetbot", nil, macbook, hs.layout.right30, nil, nil},
{"nvALT", nil, macbook, hs.layout.left30, nil, nil},
{"pwSafe", nil, macbook, hs.layout.left30, nil, nil},
{"Skim", nil, macbook, hs.layout.right50, nil, nil},
{"Preview", nil, macbook, hs.layout.right50, nil, nil},
}
hs.layout.apply(windowLayout)
end
end)
-- --
-- -- Turn off Animations.
-- --
-- hs.window.animationDuration = 0
-- -- Inspired by https://github.com/jasoncodes/dotfiles/blob/master/hammerspoon/control_escape.lua
-- -- You'll also have to install Karabiner Elements and map caps_lock to left_control there
-- len = function(t)
-- local length = 0
-- for k, v in pairs(t) do
-- length = length + 1
-- end
-- return length
-- end
-- send_escape = false
-- prev_modifiers = {}
-- modifier_handler = function(evt)
-- -- evt:getFlags() holds the modifiers that are currently held down
-- local curr_modifiers = evt:getFlags()
-- if curr_modifiers["ctrl"] and len(curr_modifiers) == 1 and len(prev_modifiers) == 0 then
-- -- We need this here because we might have had additional modifiers, which
-- -- we don't want to lead to an escape, e.g. [Ctrl + Cmd] —> [Ctrl] —> [ ]
-- send_escape = true
-- elseif prev_modifiers["ctrl"] and len(curr_modifiers) == 0 and send_escape then
-- send_escape = false
-- hs.eventtap.keyStroke({}, "ESCAPE")
-- else
-- send_escape = false
-- end
-- prev_modifiers = curr_modifiers
-- return false
-- end
-- -- Call the modifier_handler function anytime a modifier key is pressed or released
-- modifier_tap = hs.eventtap.new({hs.eventtap.event.types.flagsChanged}, modifier_handler)
-- modifier_tap:start()
-- -- If any non-modifier key is pressed, we know we won't be sending an escape
-- non_modifier_tap = hs.eventtap.new({hs.eventtap.event.types.keyDown}, function(evt)
-- send_escape = false
-- return false
-- end)
-- non_modifier_tap:start()
|
local ROW_HEIGHT = 20
local COL_WIDTH = 100
local BORDER_WIDTH = 1
local BORDER_COLOR = Color3.new(1,1,1)
local STD_BG_COLOR = Color3.new(0.25, 0.75, 0.75)
local ALT_BG_COLOR = Color3.new(0.25, 0.25, 0.75)
local TEXT_COLOR = Color3.new(1, 1, 1)
local SORTED_TITLE_COLOR = Color3.new(1,0,1)
local BG_TRANSPARENCY = 0.9
local COL_WIDTHS = {50,50,50,65,120,-335}
local COL_KEYS = { "Method", "Status", "Time", "RequestType", "URL"}
local COL_TITLES = {"No.", "Method", "Status", "Time(ms)", "RequestType", "URL"}
local MAX_ROW = 256
pcall(function ()
MAX_ROW = tonumber(settings():GetFVariable("HttpAnalyticsMaxHistory"))
end)
--////////////////////////////////////
--
-- UIListGridItemClass
-- a single grid in the list
-- it has a 'Frame' to show background and 'TextLabel' to show text
--
--////////////////////////////////////
local UIListGridItemClass = {}
UIListGridItemClass.__index = UIListGridItemClass
function UIListGridItemClass.new(parentFrame, pos, size, bgColor)
local self = {}
setmetatable(self, UIListGridItemClass)
self._parent = parentFrame
self._frame = Instance.new("Frame")
self._frame.Position = pos
self._frame.Size = size
self._frame.BorderColor3 = BORDER_COLOR
self._frame.BorderSizePixel = BORDER_WIDTH
self._frame.BackgroundTransparency = BG_TRANSPARENCY
self._frame.ZIndex = self._parent.ZIndex + 1
self._frame.BackgroundColor3 = bgColor
self._frame.Parent = self._parent
self._label = Instance.new("TextLabel")
self._label.TextColor3 = TEXT_COLOR
self._label.Position = UDim2.new(0, 5, 0, 0)
self._label.Size = UDim2.new(1, -10, 1, 0)
self._label.BackgroundTransparency = 1
self._label.TextXAlignment = Enum.TextXAlignment.Left
self._label.ZIndex = self._parent.ZIndex + 1
self._label.Parent = self._frame
return self
end
function UIListGridItemClass:setValue( value )
if self._label == nil then
return
end
local valueType = type(value)
local text
if valueType == "string" then
text = value
elseif valueType == "number" then
if value - math.floor(value) > 0 then
text = string.format("%.02f", value)
else
text = tostring(value)
end
else
text = tostring(value)
end
self._label.Text = text
end
function UIListGridItemClass:getFrame()
return self._frame
end
--////////////////////////////////////
--
-- UIListClass
-- to show lua tables in UI
-- creates and manager UIListGridItemClass instance
--
--////////////////////////////////////
local UIListClass = {}
UIListClass.__index = UIListClass
-- callbackClicked(row, col, frame) 'frame' is the 'Frame' instance be clicked
function UIListClass.new(parentFrame, callbackClicked)
local self = {}
setmetatable(self, UIListClass)
self._parent = parentFrame
self._frame = Instance.new("Frame")
self._frame.Name = "UIListClass"
self._frame.Position = UDim2.new(0,1,0,1)
self._frame.Size = UDim2.new(1,0,0,0)
self._frame.ZIndex = self._parent.ZIndex
self._frame.BorderSizePixel = 0
self._frame.Parent = self._parent
self._columnWidths = {COL_WIDTH}
self._rowHeight = ROW_HEIGHT
self._rows = {}
self._callbackClicked = callbackClicked
return self
end
function UIListClass:setColumns(names, widths)
self:setColumnWidths(widths)
self:setRow(1, names)
end
function UIListClass:setColumnWidths( widths )
self._columnWidths = widths
end
function UIListClass:setRow( index, values )
if #self._rows + 1 < index then
return
elseif #self._rows < index then
self:addRow(values)
else
local row = self._rows[index]
for i,v in ipairs(row) do
v:setValue(values[i])
end
end
end
function UIListClass:addRow( values )
local index = #self._rows+1
local row = {}
for i = 1, #values do
if i > #self._columnWidths then
break
end
local pos = self:getItemPosition(index, i)
local size = self:getItemSize(index,i)
local bgColor
if (index % 2 == 1) then
bgColor = STD_BG_COLOR
else
bgColor = ALT_BG_COLOR
end
local item = UIListGridItemClass.new(self._frame, pos, size, bgColor)
-- set click callback
local itemFrame = item:getFrame()
itemFrame.InputBegan:connect(function(input)
-- set the frame's background color and call _callbackClicked
if input.UserInputType == Enum.UserInputType.MouseButton1 then
if self._callbackClicked ~= nil then
self._callbackClicked(index, i, itemFrame)
end
end
end)
item:setValue(values[i])
table.insert(row, item)
end
table.insert(self._rows, row)
end
function UIListClass:getItemPosition( row, col )
local offsetX = 0
local offsetY = 0
for i = 1, col-1 do
offsetX = offsetX + self._columnWidths[i]
end
for i = 1, row-1 do
offsetY = offsetY + self._rowHeight
end
return UDim2.new(0, offsetX, 0, offsetY)
end
function UIListClass:getItemSize( row, col )
if self._columnWidths[col] < 0 then
return UDim2.new(1, -self._columnWidths[col], 0, self._rowHeight)
else
return UDim2.new(0, self._columnWidths[col], 0, self._rowHeight)
end
end
function UIListClass:getHeightInPix()
return self._rowHeight * #self._rows
end
function UIListClass:getFrame()
return self._frame
end
--////////////////////////////////////
--
-- HttpResultList
-- manage http results data and set data to UIListClass then the http results will show in UI
-- call HttpResultListClass:addHttpResult to add a row of http result to UI
--
--////////////////////////////////////
local HttpResultListClass = {}
HttpResultListClass.__index = HttpResultListClass
function HttpResultListClass.new( parentFrame, heightChange, callbackClicked)
local self = {}
setmetatable(self, HttpResultListClass)
self._sortedColumn = 1
self._list = UIListClass.new(parentFrame, callbackClicked)
self._heightChangedCallback = heightChange
self._rowValues = {}
self._counter = 0
self._sortedTitleLastColor = nil
self._sortedTitleFrame = nil
return self
end
function HttpResultListClass:sort(col,frame)
if col == self._sortedColumn then
return
end
if col < 1 or
#self._rowValues < 2 or
col > #self._rowValues[1] then
return
end
self._sortedColumn = col
self._sortedTitleLastColor = frame.BackgroundColor3
if self._sortedTitleFrame ~= nil then
self._sortedTitleFrame.BackgroundColor3 = self._sortedTitleLastColor
end
self._sortedTitleFrame = frame
self._sortedTitleFrame.BackgroundColor3 = SORTED_TITLE_COLOR
table.sort(self._rowValues, function (row1, row2)
return row1[self._sortedColumn] < row2[self._sortedColumn]
end)
for i,values in ipairs(self._rowValues) do
self._list:setRow(i+1, values)
end
end
-- insert 'valuse'. If '_rowValues' is ordered, will keep the order
function HttpResultListClass:insert(values)
if self._sortedColumn == 0 or #self._rowValues == 0 then
table.insert(self._rowValues, values)
return
else
-- insert to an ordered table
-- find a right position in the ordered table
local posInsert = #self._rowValues + 1
for i=1,#self._rowValues do
if self._rowValues[i][self._sortedColumn] > values[self._sortedColumn] then
posInsert = i
break
end
end
-- inser the 'values' at posInsert
-- move the all items after posInsert back off one position
table.insert(self._rowValues, posInsert, values)
end
end
-- remove the the oldest item
function HttpResultListClass:remove()
local removeIndex = 1
if self._sortedColumn > 1 then
local removeCounterValue = self._counter - MAX_ROW + 1
for i,v in ipairs(self._rowValues) do
if v[1] == removeCounterValue then
removeIndex = i
break
end
end -- end for
end
table.remove(self._rowValues, removeIndex)
end
function HttpResultListClass:addRow(values)
local isHeightUpdate = false
if #self._rowValues < MAX_ROW then
self:insert(values)
isHeightUpdate = true
else
self:remove()
self:insert(values)
end
for i,values in ipairs(self._rowValues) do
self._list:setRow(i+1, values)
end
if isHeightUpdate and self._heightChangedCallback ~= nil then
self._heightChangedCallback(self._list:getHeightInPix())
end
end
-- add a row of http result to list
function HttpResultListClass:addHttpResult(httpResult)
if httpResult["Hiden"] == true then
return
end
if #self._rowValues == 0 then
self._list:setColumns(COL_TITLES, COL_WIDTHS)
end
local values = {self._counter+1}
for _,v in ipairs(COL_KEYS) do
table.insert(values, httpResult[v])
end
table.insert(values, httpResult["Response"])
self:addRow(values)
self._counter = self._counter+1
end
function HttpResultListClass:getHeightInPix()
return self._list:getHeightInPix()
end
function HttpResultListClass:getFrame()
return self._list:getFrame()
end
function HttpResultListClass:getValues(row)
return self._rowValues[row]
end
--////////////////////////////////////
--
-- HttpAnalyticsTable
-- how many requests have been made, how many requests have failed,
-- average, min, and max response time for per developer facing RequestType
--
--////////////////////////////////////
local HttpAnalyticsTableClass = {}
HttpAnalyticsTableClass.__index = HttpAnalyticsTableClass
local HTTP_ANALYTICS_TITTLES = {"RequestType","RequestCount","FailedCount",
"AverageTime(ms)","MinTime(ms)","MaxTime(ms)"}
local HTTP_ANALYTICS_KEYS = {"RequestType","RequestCount","FailedCount",
"AverageTime","MinTime","MaxTime"}
local HTTP_ANALYTICS_WIDTHS = {120, 90, 90, 110, 90, 90}
function HttpAnalyticsTableClass.new( parentFrame,callback )
local self = {}
setmetatable(self, HttpAnalyticsTableClass)
self._list = UIListClass.new(parentFrame)
self._tableData = {}
self._tableData.size = 0
self._heightChangedCallback = callback
return self
end
-- http analyzer data
-- show how many requests have been made, how many requests have failed,
-- average, min, and max response time for per developer facing RequestType
function HttpAnalyticsTableClass:addHttpResult( httpResult )
if self._tableData.size == 0 then
self._list:setColumns(HTTP_ANALYTICS_TITTLES, HTTP_ANALYTICS_WIDTHS)
end
local record = self._tableData[httpResult.RequestType]
local isHeightUpdate = false
if record == nil then
self._tableData[httpResult.RequestType] = {
RequestType = httpResult.RequestType,
RequestCount = 1,
FailedCount = 0,
AverageTime = httpResult.Time,
MinTime = httpResult.Time,
MaxTime = httpResult.Time,
index = self._tableData.size + 1
}
self._tableData.size = self._tableData.size + 1
if httpResult.Status >= 400 then
self._tableData[httpResult.RequestType].FailedCount = 1
end
record = self._tableData[httpResult.RequestType]
isHeightUpdate = true
else
record.RequestCount = record.RequestCount + 1
if httpResult.Status >= 400 then
record.FailedCount = record.FailedCount + 1
end
record.AverageTime = (record.AverageTime*record.RequestCount
+ httpResult.Time - record.AverageTime)/record.RequestCount
if httpResult.Time < record.MinTime then
record.MinTime = httpResult.Time
end
if httpResult.Time > record.MaxTime then
record.MaxTime = httpResult.Time
end
end
local values = {}
for _,v in ipairs(HTTP_ANALYTICS_KEYS) do
table.insert(values, record[v])
end
self._list:setRow(record.index+1, values)
if isHeightUpdate and self._heightChangedCallback ~= nil then
self._heightChangedCallback(self:getHeightInPix())
end
end
function HttpAnalyticsTableClass:getHeightInPix()
return self._list:getHeightInPix()
end
function HttpAnalyticsTableClass:getFrame()
return self._list:getFrame()
end
--////////////////////////////////////
--
-- HttpResponseViewClass
-- show response header and body
--
--////////////////////////////////////
local RESPONSE_TITLE_SIZE = 12
local RESPONSE_TITLE_COLOR = Color3.new(0.8,0.8,1)
local RESPONSE_TITLE_INDENTATION = 4
local RESPONSE_TEXT_INDENTATION = 10
local CANT_RENDER_MSG = "\n Some content can't be rendered as text."
local BODY_TITTLE = "Response Body:"
local HttpResponseViewClass = {}
HttpResponseViewClass.__index = HttpResponseViewClass
function HttpResponseViewClass.new( parentFrame,callback )
local self = {}
setmetatable(self, HttpResponseViewClass)
self._frame = Instance.new("Frame")
self._frame.Position = UDim2.new(0, 2, 0, 2)
self._frame.Size = UDim2.new(1, -4, 10, 0)
self._frame.BackgroundTransparency = 1
self._frame.ZIndex = parentFrame.ZIndex+1
self._frame.Visible = false
self._frame.InputBegan:connect(function(input)
if input.UserInputType == Enum.UserInputType.MouseButton1 then
self._bodyTitle.Visible = false
self._bodyLabel.Visible = false
self._frame.Visible = false
callback(false)
end
end)
self._frame.Parent = parentFrame
self._bodyTitle = Instance.new("TextLabel")
self._bodyTitle.Name = "self._bodyTitle"
self._bodyTitle.Position = UDim2.new(0, RESPONSE_TITLE_INDENTATION, 0, RESPONSE_TITLE_INDENTATION)
self._bodyTitle.Size = UDim2.new(1, 0, 0, 50)
self._bodyTitle.TextSize = RESPONSE_TITLE_SIZE
self._bodyTitle.TextColor3 = RESPONSE_TITLE_COLOR
self._bodyTitle.TextXAlignment = Enum.TextXAlignment.Left
self._bodyTitle.TextYAlignment = Enum.TextYAlignment.Top
self._bodyTitle.ZIndex = self._frame.ZIndex
self._bodyTitle.BackgroundTransparency = 1
self._bodyTitle.Visible = false
self._bodyTitle.TextWrap = true
self._bodyTitle.Text = BODY_TITTLE
self._bodyTitle.Parent = self._frame
self._bodyLabel = Instance.new("TextLabel")
self._bodyLabel.Name = "self._bodyLabel"
self._bodyLabel.Position = UDim2.new(0, RESPONSE_TEXT_INDENTATION, 0, 29)
self._bodyLabel.Size = UDim2.new(1, -2*RESPONSE_TEXT_INDENTATION, 1, 0)
self._bodyLabel.TextWrap = true
self._bodyLabel.TextXAlignment = Enum.TextXAlignment.Left
self._bodyLabel.TextYAlignment = Enum.TextYAlignment.Top
self._bodyLabel.TextColor3 = TEXT_COLOR
self._bodyLabel.ZIndex = self._frame.ZIndex
self._bodyLabel.BackgroundTransparency = 1
self._bodyLabel.Visible = false
self._bodyLabel.Parent = self._frame
return self
end
-- show labels and update the postion
function HttpResponseViewClass:show(body)
local utf8Length,pos= utf8.len(body)
if utf8Length == nil then
if pos ~= nil then
body = body:sub(1, pos-1)
end
-- tell developers something can't be rendered as text
self._bodyTitle.Text = BODY_TITTLE .. CANT_RENDER_MSG
else
self._bodyTitle.Text = BODY_TITTLE
end
self._bodyLabel.Text = body
self._bodyTitle.Position = UDim2.new(0, RESPONSE_TITLE_INDENTATION, 0, RESPONSE_TITLE_INDENTATION)
self._bodyLabel.Position = UDim2.new(0, RESPONSE_TEXT_INDENTATION, 0,
self._bodyTitle.Position.Y.Offset + self._bodyTitle.TextBounds.Y)
self._bodyTitle.Visible = true
self._bodyLabel.Visible = true
self._frame.Visible = true
end
function HttpResponseViewClass:getHeightInPix()
return RESPONSE_TITLE_INDENTATION + self._bodyTitle.TextBounds.Y +
self._bodyLabel.TextBounds.Y
end
function HttpResponseViewClass:isVisible()
return self._frame.Visible
end
--////////////////////////////////////
--
-- HttpAnalyzer
-- contain the HttpAnalyticsTable and HttpResultList
-- get data from uper layer, update the position of HttpResultList
--
--////////////////////////////////////
local SPACE_TABLE_LIST = 3
local HttpAnalyzerClass = {}
HttpAnalyzerClass.__index = HttpAnalyzerClass
function HttpAnalyzerClass.new( parentFrame,callback )
local self = {}
setmetatable(self, HttpAnalyzerClass)
self._responseView = HttpResponseViewClass.new(parentFrame, function (isShowed, height)
if not isShowed then
self._httpAnalyticsFrame.Visible = true
self._httpResultListFrame.Visible = true
end
self:heightChange()
end)
local analyticsTableHeightChange = function (newHeight)
self:updatePosition()
end
local resultListHeightChange = function (newHeight)
self:heightChange()
end
local resultListClicked = function(row, col, frame)
if self._responseView:isVisible() then
return
end
if row == 1 then
self._httpResultList:sort(col,frame)
else
local values = self._httpResultList:getValues(row-1)
self:showResponse(values)
end
end
self._httpAnalyticsTable = HttpAnalyticsTableClass.new(parentFrame, analyticsTableHeightChange)
self._httpResultList = HttpResultListClass.new(parentFrame, resultListHeightChange, resultListClicked)
self._httpAnalyticsFrame = self._httpAnalyticsTable:getFrame()
self._httpResultListFrame = self._httpResultList:getFrame()
self._heightChangedCallback = callback
return self
end
function HttpAnalyzerClass:updatePosition()
local tableHeight = self._httpAnalyticsTable:getHeightInPix()
self._httpResultListFrame.Position = UDim2.new(0,1,0,tableHeight+SPACE_TABLE_LIST)
self:heightChange()
end
function HttpAnalyzerClass:heightChange()
if self._heightChangedCallback ~= nil then
self._heightChangedCallback(self:getHeightInPix())
end
end
-- add a row of http result to list
-- and update the analyzer data on table
function HttpAnalyzerClass:addHttpResult( httpResult )
self._httpAnalyticsTable:addHttpResult(httpResult)
self._httpResultList:addHttpResult(httpResult)
end
function HttpAnalyzerClass:getHeightInPix()
if self._responseView:isVisible() then
return self._responseView:getHeightInPix()
else
return self._httpAnalyticsTable:getHeightInPix() +
self._httpResultList:getHeightInPix() + SPACE_TABLE_LIST
end
end
function HttpAnalyzerClass:showResponse(values)
self._httpAnalyticsFrame.Visible = false
self._httpResultListFrame.Visible = false
self._responseView:show(values[#values])
self:heightChange()
end
return HttpAnalyzerClass
|
-- RainbowBlades
--
-- knob1:
-- knob2:
-- knob3:
-- knob4:
-- knob5: COEF_ROTATION_DEG
local compat = require("compat")
local color = require("color")
local lfo = require("lfo")
NUM_SAMPLES = 256
W = of.getWidth()
H = of.getHeight()
W2 = W / 2
H2 = H / 2
W4 = W / 4
H4 = H / 4
C = glm.vec3(W2, H2, 0)
-- Mode constants
COLOR_BLACK = of.Color.fromHsb(116, 0, 10)
COEF_BAR_WIDTH = 30
COEF_ROTATION_DEG = 45
COEF_NUM_BARS = 25
COEF_COLOR_SATURATION = 150
COEF_TIME_ACCELERATION = 15
COEF_SINE_SLICES = 15
COEF_SINE_SLICE_WIDTH = 5
COEF_BAR_OPACITY = 50
PALETTE = {
of.Color.fromHsb(color.map360(360), color.map100(67), color.map100(98), COEF_COLOR_SATURATION),
of.Color.fromHsb(color.map360(339), color.map100(68), color.map100(90), COEF_COLOR_SATURATION),
of.Color.fromHsb(color.map360(288), color.map100(66), color.map100(86), COEF_COLOR_SATURATION),
of.Color.fromHsb(color.map360(255), color.map100(67), color.map100(95), COEF_COLOR_SATURATION),
of.Color.fromHsb(color.map360(228), color.map100(69), color.map100(96), COEF_COLOR_SATURATION),
of.Color.fromHsb(color.map360(208), color.map100(85), color.map100(90), COEF_COLOR_SATURATION),
of.Color.fromHsb(color.map360(188), color.map100(89), color.map100(75), COEF_COLOR_SATURATION),
of.Color.fromHsb(color.map360(162), color.map100(90), color.map100(72), COEF_COLOR_SATURATION),
of.Color.fromHsb(color.map360(131), color.map100(66), color.map100(75), COEF_COLOR_SATURATION),
of.Color.fromHsb(color.map360(85), color.map100(85), color.map100(79), COEF_COLOR_SATURATION),
of.Color.fromHsb(color.map360(42), color.map100(98), color.map100(98), COEF_COLOR_SATURATION),
of.Color.fromHsb(color.map360(27), color.map100(92), color.map100(99), COEF_COLOR_SATURATION),
}
-- Mode state
Bars = {}
ColorRotate = 0
Time = 0
Acceleration = 10
SineLFO = lfo.sineGenerator(1000, 10)
local function populateBars()
for i = 0, COEF_NUM_BARS - 1 do
local bar = {
rect = of.Rectangle(i * COEF_BAR_WIDTH, 0, COEF_BAR_WIDTH, of.getHeight()),
color = of.Color.fromHsb(61, 3, 235),
}
table.insert(Bars, bar)
end
end
function setup()
compat:setup()
print("RainbowBlades")
populateBars()
end
function update()
compat:update()
Time = Time + 1
-- Repopulate bars if quantity is changed
if #Bars ~= COEF_NUM_BARS then
populateBars()
end
-- It's a sine of the times
local accMod = COEF_TIME_ACCELERATION * math.sin(Time)
Acceleration = math.floor(Acceleration + accMod)
if Time % of.clamp(Acceleration, 10, 20) == 0 then
ColorRotate = ColorRotate + 1
end
for i, bar in ipairs(Bars) do
bar.rect.height = of.getHeight()
bar.color = PALETTE[((i + ColorRotate) % #PALETTE) + 1]
end
end
function draw()
compat:draw()
of.setBackgroundColor(COLOR_BLACK)
of.pushMatrix()
-- Skew entire canvas diagonally
of.rotateDeg(COEF_ROTATION_DEG)
of.translate(-of.getWidth() / 20, -of.getHeight() / 2)
for _, bar in ipairs(Bars) do
-- Bounding rectangles drawn behind in with opacity
of.setColor(color.withAlpha(bar.color, COEF_BAR_OPACITY))
of.drawRectRounded(
of.Rectangle(
bar.rect.x,
bar.rect.y,
of.clamp(
(bar.rect.width / 3) + SineLFO(of.getElapsedTimeMillis()),
0,
bar.rect.width * 0.5
),
bar.rect.height
),
10
)
-- Sharp-edged dagger shapes drawn as paths over rectangles
local path = of.Path()
path:moveTo(bar.rect.x, bar.rect.y)
path:setColor(bar.color)
path:setFillColor(bar.color)
path:setFilled(true)
for j = 1, COEF_SINE_SLICES do
local to = glm.vec2(
bar.rect.x + SineLFO(of.getElapsedTimeMillis()),
(bar.rect.height / COEF_SINE_SLICES) * j
)
path:curveTo(to)
end
path:close()
path:draw()
end
of.popMatrix()
end
|
f = function (a)
return a * 3;
end
|
-- libquvi-scripts v0.9.20131012
-- Copyright (C) 2012 Toni Gundogdu <[email protected]>
--
-- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>.
--
-- This program is free software: you can redistribute it and/or
-- modify it under the terms of the GNU Affero 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 Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General
-- Public License along with this program. If not, see
-- <http://www.gnu.org/licenses/>.
--
local M = {}
--[[
Construct a dictionary containing the stream properties.
These, except the URL, are set to empty (or 0) values.
Parameters:
url .. Media stream URL
Returns:
A dictionary with the default values
]]--
function M.stream_new(url)
local r = {
url = url or '',
fmt_id = '',
video = {
bitrate_kbit_s = '',
encoding = '',
height = 0,
width = 0
},
audio = {
bitrate_kbit_s = '',
encoding = ''
},
flags = {
best = false
}
}
return r
end
function M.swap_best(a,b)
a.flags.best, b.flags.best = b.flags.best, a.flags.best
return b
end
return M
-- vim: set ts=2 sw=2 tw=72 expandtab:
|
expose(
'[setting up tests Globals]',
function()
require 'cherry.libs.math'
_G.inspect = require('cherry.libs.inspect')
_G.display = require('mocks.display')
_G.App = require('mocks.app')
_G.audio = require('mocks.audio')
_G.composer = require('mocks.composer')
_G.http = require('mocks.http')
_G.file = require('mocks.file')
_G.native = require('mocks.native')
_G.network = require('mocks.network')
_G.notifications = require('mocks.notifications')
_G.physics = require('mocks.physics')
_G.Runtime = require('mocks.runtime')
_G.system = require('mocks.system')
_G.transition = require('mocks.transition')
_G.FONTS = {default = ''}
_G.easing = {}
_G.timer = {
performWithDelay = function(time, func)
func()
end
}
_G.DEBUG = os.getenv('DEBUG') -- make busted verbose=true
if (_G.DEBUG) then
require('cherry.libs.logger')
else
_G.log = function()
end
end
end
)
|
local Menu = require("nui.menu")
local Text = require("nui.text")
local helper = require("tests.nui")
local spy = require("luassert.spy")
local eq, feedkeys, tbl_pick = helper.eq, helper.feedkeys, helper.tbl_pick
describe("nui.menu", function()
local callbacks
local popup_options
before_each(function()
callbacks = {
on_change = function() end,
}
popup_options = {
relative = "win",
position = "50%",
}
end)
describe("size", function()
it("respects o.min_width", function()
local min_width = 3
local items = {
Menu.item("A"),
Menu.separator("*"),
Menu.item("B"),
}
local menu = Menu(popup_options, {
lines = items,
min_width = min_width,
})
menu:mount()
eq(vim.api.nvim_win_get_width(menu.winid), min_width)
eq(vim.api.nvim_buf_get_lines(menu.bufnr, 0, -1, false), {
"A",
" * ",
"B",
})
end)
it("respects o.max_width", function()
local max_width = 6
local items = {
Menu.item("Item 1"),
Menu.separator("*"),
Menu.item("Item Number Two"),
}
local menu = Menu(popup_options, {
lines = items,
max_width = max_width,
})
menu:mount()
eq(vim.api.nvim_win_get_width(menu.winid), max_width)
eq(vim.api.nvim_buf_get_lines(menu.bufnr, 0, -1, false), {
"Item 1",
" * ",
"Item …",
})
end)
it("respects o.min_height", function()
local min_height = 3
local items = {
Menu.item("A"),
Menu.separator("*"),
Menu.item("B"),
}
local menu = Menu(popup_options, {
lines = items,
min_height = min_height,
})
menu:mount()
eq(vim.api.nvim_win_get_height(menu.winid), min_height)
end)
it("respects o.max_height", function()
local max_height = 2
local items = {
Menu.item("A"),
Menu.separator("*"),
Menu.item("B"),
}
local menu = Menu(popup_options, {
lines = items,
max_height = max_height,
})
menu:mount()
eq(vim.api.nvim_win_get_height(menu.winid), max_height)
end)
end)
it("calls o.on_change item focus is changed", function()
local on_change = spy.on(callbacks, "on_change")
local lines = {
Menu.item("Item 1", { id = 1 }),
Menu.item("Item 2", { id = 2 }),
}
local menu = Menu(popup_options, {
lines = lines,
on_change = on_change,
})
menu:mount()
-- initial focus
assert.spy(on_change).called_with(lines[1], menu)
on_change:clear()
feedkeys("j", "x")
assert.spy(on_change).called_with(lines[2], menu)
on_change:clear()
feedkeys("j", "x")
assert.spy(on_change).called_with(lines[1], menu)
on_change:clear()
feedkeys("k", "x")
assert.spy(on_change).called_with(lines[2], menu)
on_change:clear()
end)
describe("item", function()
it("is prepared using o.prepare_item if provided", function()
local items = {
Menu.item("A"),
Menu.separator("*"),
Menu.item("B"),
}
local function prepare_item(item)
return "-" .. item.text .. "-"
end
local menu = Menu(popup_options, {
lines = items,
prepare_item = prepare_item,
})
menu:mount()
eq(vim.api.nvim_buf_get_lines(menu.bufnr, 0, -1, false), vim.tbl_map(prepare_item, items))
end)
it("is prepared when o.prepare_item is not provided", function()
local items = {
Menu.item("A"),
Menu.separator("*"),
Menu.item("B"),
}
popup_options.border = "single"
local menu = Menu(popup_options, {
lines = items,
})
menu:mount()
eq(vim.api.nvim_buf_get_lines(menu.bufnr, 0, -1, false), {
"A",
"─*──",
"B",
})
end)
it("is skipped respecting o.should_skip_item if provided", function()
local on_change = spy.on(callbacks, "on_change")
local items = {
Menu.item("-"),
Menu.item("A", { id = 1 }),
Menu.item("-"),
Menu.item("B", { id = 2 }),
Menu.item("-"),
}
local menu = Menu(popup_options, {
lines = items,
on_change = on_change,
should_skip_item = function(item)
return not item.id
end,
})
menu:mount()
assert.spy(on_change).called_with(items[2], menu)
on_change:clear()
feedkeys("j", "x")
assert.spy(on_change).called_with(items[4], menu)
on_change:clear()
feedkeys("j", "x")
assert.spy(on_change).called_with(items[2], menu)
on_change:clear()
end)
it("supports NuiText", function()
local hl_group = "NuiMenuTest"
local text = "text"
local items = {
Menu.item(Text(text, hl_group)),
}
local menu = Menu(popup_options, {
lines = items,
})
menu:mount()
eq(vim.api.nvim_buf_get_lines(menu.bufnr, 0, -1, false), { text })
local linenr = 1
local line = vim.api.nvim_buf_get_lines(menu.bufnr, linenr - 1, linenr, false)[linenr]
local byte_start = string.find(line, text)
local extmarks = vim.api.nvim_buf_get_extmarks(menu.bufnr, menu.ns_id, linenr - 1, linenr, {
details = true,
})
eq(type(byte_start), "number")
eq(#extmarks, 1)
eq(extmarks[1][2], linenr - 1)
eq(extmarks[1][4].end_col - extmarks[1][3], #text)
eq(tbl_pick(extmarks[1][4], { "end_row", "hl_group" }), {
end_row = linenr - 1,
hl_group = hl_group,
})
end)
end)
end)
|
fx_version 'bodacious'
games { 'gta5' }
author 'Cloudy'
description 'Online Interiors'
version '1.0.3'
dependency 'bob74_ipl'
client_scripts{
-- IPL Scripts --
'files/maps/ipl_edits/after_hours/nightclub/client.lua',
'files/maps/ipl_edits/after_hours/nightclub_exteriors/client.lua',
'files/maps/ipl_edits/bikers/businesses/cocaine/client.lua',
'files/maps/ipl_edits/bikers/businesses/counterfeit_cash/client.lua',
'files/maps/ipl_edits/bikers/businesses/document_forgery/client.lua',
'files/maps/ipl_edits/bikers/businesses/meth/client.lua',
'files/maps/ipl_edits/bikers/businesses/weed/client.lua',
'files/maps/ipl_edits/bikers/clubhouses/clubhouse_1/client.lua',
'files/maps/ipl_edits/bikers/clubhouses/clubhouse_2/client.lua',
'files/maps/ipl_edits/bikers/gang/client.lua',
'files/maps/ipl_edits/doomsday/facility/client.lua',
'files/maps/ipl_edits/finance_felony/offices/arcadius_business_centre/client.lua',
'files/maps/ipl_edits/finance_felony/offices/lom_bank/client.lua',
'files/maps/ipl_edits/finance_felony/offices/maze_bank/client.lua',
'files/maps/ipl_edits/finance_felony/offices/maze_bank_west/client.lua',
'files/maps/ipl_edits/finance_felony/organization/client.lua',
'files/maps/ipl_edits/gunrunning/bunker/client.lua',
'files/maps/ipl_edits/gunrunning/yacht/client.lua',
'files/maps/ipl_edits/heists/aircraft_carrier/client.lua',
'files/maps/ipl_edits/heists/yacht/client.lua',
'files/maps/ipl_edits/import_export/garages/arcadius_business_centre/client.lua',
'files/maps/ipl_edits/import_export/garages/lom_bank/client.lua',
'files/maps/ipl_edits/import_export/garages/maze_bank/client.lua',
'files/maps/ipl_edits/import_export/garages/maze_bank_west/client.lua',
'files/maps/ipl_edits/import_export/vehicle_warehouse/client.lua',
'files/maps/ipl_edits/smugglers/hanger/client.lua',
-- Teleport Scripts --
'files/teleports/client.lua',
-- Blip Script --
'files/blips/client.lua'
}
|
Howtoplay = Area:extend()
function Howtoplay:new()
Howtoplay.super.new(self)
self.x = 0
self.y = 0
self.text = Text(0, 10, "Move the cursor(s) with the Arrow Keys\nMove the blocks with WASD", Options.fonts.normal)
self.text.color = {0, 0, 0}
self.text.align.x = "center"
self.text.limit = WIDTH
self:addScenery(self.text)
self.data = Util.createData(5, 5)
self.field = Shifter(self.data, 400, 80)
self:addScenery(self.field)
self.flux = flux.group()
end
function Howtoplay:update(dt)
Howtoplay.super.update(self, dt)
if Key:isPressed("escape") and not self.tween then
self.tween = self.flux:to(self, .5, {x = WIDTH})
:oncomplete(function () game:toState(self.menu) end)
self.menu = Menu(true)
end
self.flux:update(dt)
end
function Howtoplay:draw()
love.graphics.push()
love.graphics.push()
love.graphics.translate(self.x, self.y)
Howtoplay.super.draw(self)
love.graphics.pop()
if self.menu then
love.graphics.translate(self.x - WIDTH, 0)
self.menu:draw()
end
love.graphics.pop()
end
function Howtoplay:__tostring()
return lume.tostring(self, "Howtoplay")
end
|
require("moonsc").import_tags()
-- Testing that in case of early binding variables are assigned
-- values at init time, before the state containing them is visited
return _scxml{ initial="s0",
_state{ id="s0",
_transition{ cond="var1==1", target="pass" },
_transition{ target="fail" },
},
_state{ id="s1",
_datamodel{ _data{ id="var1", expr="1" }},
},
_final{id='pass'},
_final{id='fail'},
}
|
VERSION = "1.0.0"
PLUGIN_NAME = "prettier"
local micro = import("micro")
local config = import("micro/config")
local shell = import("micro/shell")
local ioutil = import("io/ioutil")
local filepath = import("path/filepath")
function init()
-- format on save
config.RegisterCommonOption("prettier", "formatOnSave", true)
-- require a .prettierrc.js in current working directory
config.RegisterCommonOption("prettier", "requireConfig", true)
-- print success message in InfoBar
config.RegisterCommonOption("prettier", "successMessage", true)
-- prints error messages if enabled
config.RegisterCommonOption("prettier", "debug", false)
config.MakeCommand("prettier", prettier, config.NoComplete)
config.AddRuntimeFile("prettier", config.RTHelp, "help/prettier.md")
end
function prettier(bp)
bp:Save()
if checkConfig(bp) == false then
-- no config found, don't run
-- if requireConfig is set to false, don't care and run always
return
end
local output, err = shell.ExecCommand("prettier", "-w", bp.Buf.Path)
if err then
if setting(bp, "debug") then
micro.InfoBar():Message(err)
end
return
end
bp.Buf:ReOpen()
if setting(bp, "successMessage") then
micro.InfoBar():Message("Prettier: " .. output)
end
end
-- on save
function onSave(bp)
if setting(bp, "formatOnSave") then
prettier(bp)
end
return true
end
-- checks if a prettier config exists
function checkConfig(bp)
if setting(bp, "requireConfig") == false then
return true
end
local filename = filepath.Abs(".prettierrc.js")
local _, err = ioutil.ReadFile(filename)
if err ~= nil then
if setting(bp, "debug") then
micro.InfoBar():Message(err)
end
else
-- a prettier config was found
return true
end
return false
end
-- get setting
function setting(bp, name)
return bp.Buf.Settings["prettier" .. "." .. name]
end
|
print("-----Players-----")
for i,v in pairs(game:GetService("Players").LocalPlayer:GetChildren()) do
print(v.Name)
end
|
tigers_fury_warrior = {
cast = function(player)
local magic = 90
if (not player:canCast(1, 1, 0)) then
return
end
if (player.magic < magic) then
player:sendMinitext("You do not have enough mana.")
return
end
if player:checkIfCast(lesserFuries) or player.rage > 1 then
player:sendMinitext("This spell is already active.")
return
end
player.magic = player.magic - magic
player:playSound(4)
player:sendMinitext("You cast Tiger's Fury.")
player:setDuration("tigers_fury_warrior", 625000)
player:sendAnimation(11)
player:sendAction(6, 35)
player:calcStat()
end,
recast = function(player)
player.rage = 3
player:sendStatus()
end,
uncast = function(player)
player.rage = 1
player:sendStatus()
end,
requirements = function(player)
local level = 24
local items = {Item("antler").id, Item("fox_fur").id, 0}
local itemAmounts = {5, 15, 250}
local description = "An attack with great rage."
return level, items, itemAmounts, description
end
}
filling_the_soul_warrior = {
cast = function(player)
local magic = 90
if (not player:canCast(1, 1, 0)) then
return
end
if (player.magic < magic) then
player:sendMinitext("You do not have enough mana.")
return
end
if player:checkIfCast(lesserFuries) or player.rage > 1 then
player:sendMinitext("This spell is already active.")
return
end
player.magic = player.magic - magic
player:playSound(4)
player:sendMinitext("You cast Filling the Soul.")
player:setDuration("filling_the_soul_warrior", 625000)
player:sendAnimation(103)
player:sendAction(6, 35)
player:calcStat()
end,
recast = function(player)
player.rage = 3
player:sendStatus()
end,
uncast = function(player)
player.rage = 1
player:sendStatus()
end,
requirements = function(player)
local level = 24
local items = {Item("antler").id, Item("fox_fur").id, 0}
local itemAmounts = {5, 15, 250}
local description = "An attack with great rage."
return level, items, itemAmounts, description
end
}
spirit_of_the_wild_warrior = {
cast = function(player)
local magic = 90
if (not player:canCast(1, 1, 0)) then
return
end
if (player.magic < magic) then
player:sendMinitext("You do not have enough mana.")
return
end
if player:checkIfCast(lesserFuries) or player.rage > 1 then
player:sendMinitext("This spell is already active.")
return
end
player.magic = player.magic - magic
player:playSound(4)
player:sendMinitext("You cast Spirit of the Wild.")
player:setDuration("spirit_of_the_wild_warrior", 625000)
player:sendAnimation(106)
player:sendAction(6, 35)
player:calcStat()
end,
recast = function(player)
player.rage = 3
player:sendStatus()
end,
uncast = function(player)
player.rage = 1
player:sendStatus()
end,
requirements = function(player)
local level = 24
local items = {Item("antler").id, Item("fox_fur").id, 0}
local itemAmounts = {5, 15, 250}
local description = "An attack with great rage."
return level, items, itemAmounts, description
end
}
ohaengs_grace_warrior = {
cast = function(player)
local magic = 90
if (not player:canCast(1, 1, 0)) then
return
end
if (player.magic < magic) then
player:sendMinitext("You do not have enough mana.")
return
end
if player:checkIfCast(lesserFuries) or player.rage > 1 then
player:sendMinitext("This spell is already active.")
return
end
player.magic = player.magic - magic
player:playSound(70)
player:sendMinitext("You cast Ohaeng's Grace.")
player:setDuration("ohaengs_grace_warrior", 625000)
player:sendAnimation(59)
player:sendAction(6, 35)
player:calcStat()
end,
recast = function(player)
player.rage = 3
player:sendStatus()
end,
uncast = function(player)
player.rage = 1
player:sendStatus()
end,
requirements = function(player)
local level = 24
local items = {Item("antler").id, Item("fox_fur").id, 0}
local itemAmounts = {5, 15, 250}
local description = "An attack with great rage."
return level, items, itemAmounts, description
end
}
|
require 'nn'
function createOutputUnit(input_size, output_size)
local model = nn.Sequential()
model:add(nn.Linear(input_size, output_size))
model:add(nn.LogSoftMax())
return model
end
|
-- Rafraichissement du diff time et du web_cli
print("\n time_table.lua aj190408.1924 \n")
function get_timetable()
-- http.get("http://192.168.4.1/?line1="..zlength.."m", nil, function(code, data)
print("get_timetable: ")
http.get("http://transport.opendata.ch/v1/connections?from=Cheseaux&to=Lausanne-Flon&fields[]=connections/from/departure", nil, function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code, data)
jp= 50 h1=string.sub (data,jp,jp+7)
jp= 100 h2=string.sub (data,jp,jp+7)
jp= 150 h3=string.sub (data,jp,jp+7)
jp= 200 h4=string.sub (data,jp,jp+7)
print(h1,h2,h3,h4)
refresh_display()
end
end)
end
function refresh_display()
print("coucou 1")
-- tm = rtctime.epoch2cal(rtctime.get() + 3600) -- heure d'été
tm = rtctime.epoch2cal(rtctime.get() + 7200) -- heure d'hiver
h0 = string.format("%02d:%02d:%02d", tm["hour"], tm["min"], tm["sec"])
print("Il est "..h0)
print("h2, h3",h2,h3)
d1=zround((diff_time(h2, h0)/180),0)
d2=zround((diff_time(h3, h0)/180),0)
print(d1,d2)
xfois1 = d2 xfois2 =d1
if d1==0 then
print("coucou 2")
get_timetable()
print("coucou 3")
-- refresh_display()
print("coucou 4")
end
end
function start_refresh_display()
tm = rtctime.epoch2cal(rtctime.get() + 7200)
h0 = string.format("%02d:%02d:%02d", tm["hour"], tm["min"], tm["sec"])
print("Il est "..h0)
tm = time2sec(h0)
print("tm: ",tm)
if tm >= 71000 then
ztmr_start_refresh_display:unregister()
get_timetable()
-- refresh_display()
end
end
zTm_start_refresh_display = 1*1000
ztmr_start_refresh_display = tmr.create()
tmr.alarm(ztmr_start_refresh_display, zTm_start_refresh_display, tmr.ALARM_AUTO, start_refresh_display)
zTm_refresh_display = 10*1000
ztmr_refresh_display = tmr.create()
--get_timetable()
--refresh_display()
--tmr.alarm(ztmr_refresh_display, zTm_refresh_display, tmr.ALARM_AUTO, refresh_display)
--[[
get_timetable()
refresh_display()
]]
|
local R = require "rigel"
local SOC = require "generators.soc"
local C = require "generators.examplescommon"
local harness = require "generators.harnessSOC"
local RS = require "rigelSimple"
local RM = require "generators.modules"
local G = require "generators.core"
require "types".export()
local SDF = require "sdf"
local Zynq = require "generators.zynq"
local regs = SOC.axiRegs({},SDF{1,1024}):instantiate("regs")
local noc = Zynq.SimpleNOC(2,nil,{{regs.read,regs.write}}):instantiate("ZynqNOC")
noc.extern=true
local inp = R.input(R.HandshakeTrigger)
local inpFO = G.FanOut{2}(inp)
local inp0, inp1 = inpFO[0], inpFO[1]
--print("INPOFO",inpFO,inp0,inp1)
local a = SOC.readBurst("frame_128.raw",128,64,u(8),8,nil,nil,noc.read)(inp0)
local bb = SOC.readBurst("frame_128_inv.raw",128,64,u(8),8,nil,nil,noc.read1)(inp1)
local out = G.FanIn{true}(a,bb)
out = RS.HS(RM.SoAtoAoS(8,1,{u(8),u(8)}))(out)
out = RS.HS(RM.map(C.sum(u(8),u(8),u(8)),8))(out)
--out = RS.HS(C.cast(ar(u(8),8),b(64)))(out)
out = SOC.writeBurst("out/soc_2in",128,64,u(8),8,1,nil,noc.write)(out)
local fn = RM.lambda("FN",inp,out)
harness({regs.start,fn,regs.done},nil,{regs})
|
project "MQWeb"
kind "ConsoleApp"
language "C++"
targetname "mqweb"
location ( solution().location )
configuration "Debug"
targetsuffix "d"
configuration { }
files {
"src/*.cpp"
, "include/**.h"
}
flags {
"NoPCH"
}
configuration "Debug"
defines { "DEBUG" }
flags { "Symbols" }
configuration "windows"
flags { "WinMain" }
defines {
"_WINDOWS",
"_USRDLL",
"WIN32",
"_CRT_SECURE_NO_DEPRECATE"
}
configuration { "windows", "codelite or codeblock" }
defines {
"Foundation_Config_INCLUDED"
}
configuration { }
libdirs {
poco_lib_dir
}
-- Set the include paths
includedirs {
poco_dir .. "/Foundation/include"
, poco_dir .. "/Util/include"
, poco_dir .. "/Net/include"
, poco_dir .. "/XML/include"
, poco_dir .. "/JSON/include"
, poco_dir .. "/Data/include"
, poco_dir .. "/Data/SQLite/include"
, "include"
, "../MQ/include"
, mq_inc
}
configuration "Debug"
links {
"mqd"
, "PocoNetd"
, "PocoUtild"
, "PocoJSONd"
, "PocoXMLd"
, "PocoDataSQLited"
, "PocoDatad"
, "PocoFoundationd"
}
configuration "Release"
links {
"mq"
, "PocoNet"
, "PocoUtil"
, "PocoJSON"
, "PocoXML"
, "PocoDataSQLite"
, "PocoData"
, "PocoFoundation"
}
configuration "windows"
links {
"shell32"
, "oleaut32"
, "comdlg32"
, "comctl32"
, "rpcrt4"
, "gdi32"
, "ole32"
, "advapi32"
, "user32"
, "wsock32"
, "iphlpapi"
}
if ( poco_static ) then
configuration "linux"
links {
"pthread"
, "dl"
, "rt"
}
end
|
function onCreate()
setPropertyFromClass('GameOverSubstate', 'characterName', 'nyu-death'); --Character json file for the death animation
setPropertyFromClass('GameOverSubstate', 'deathSoundName', 'fnf_loss_sfx'); --put in mods/sounds/
setPropertyFromClass('GameOverSubstate', 'loopSoundName', 'gameOver'); --put in mods/music/
setPropertyFromClass('GameOverSubstate', 'endSoundName', 'gameOverEnd'); --put in mods/music/
end
function onUpdate()
if not middleScroll then
setPropertyFromGroup('opponentStrums', 0, 'x', -5000);
setPropertyFromGroup('opponentStrums', 1, 'x', -5000);
setPropertyFromGroup('opponentStrums', 2, 'x', -5000);
setPropertyFromGroup('opponentStrums', 3, 'x', -5000);
end
end
|
return {
name = "logd/examples",
version = "0.0.1",
dependencies = {
"luvit/[email protected]",
"creationix/[email protected]",
}
}
|
object_building_mustafar_dungeon_mining_tunnel_02_must_mining_tunnel_02 = object_building_mustafar_dungeon_mining_tunnel_02_shared_must_mining_tunnel_02:new {
}
ObjectTemplates:addTemplate(object_building_mustafar_dungeon_mining_tunnel_02_must_mining_tunnel_02, "object/building/mustafar/dungeon/mining_tunnel_02/must_mining_tunnel_02.iff")
|
--[[
Container class
Use as a parent for controls which can be scrolled.
Clips contents.
By Phil Garner
May 2017
]]--
local Container = {}
Container.__index = Container
function Container:new(id, x, y, theme)
local win = {
props = {
id = id
,resizable = false
,width = theme:get("images").bg_image:getWidth()
,height = theme:get("images").bg_image:getHeight()
,left = x
,top = y
,scrollx = 0
,scrolly = 0
,opacity = 1
,alwaysontop = false
,bg_autosize = false -- If not autosize, then it tiles when the Container exceeds the background image size.
,theme = theme
,canvas = nil
,quad = nil
,windows = {}
,window_focusid = ""
,hidden = false
,hasFocus = false
}
}
setmetatable(win, Container)
win:render()
return win
end
function Container:set(prop, val)
self.props[prop] = val
return true
end
function Container:get(prop)
if self.props[prop] == nil then
return false
end
return self.props[prop]
end
function Container:find(id)
local wnd = self:get("windows")
for i=1, #wnd do
if wnd[i]:get("id") == id then
return i
end
end
return false
end
function Container:size(w, h)
if w <= 0 then w = 1 end
if h <= 0 then h = 1 end
self:set("width", w)
self:set("height", h)
self:render()
end
-- Master method
function Container:focus()
self:set("hasFocus", true)
self:onfocus()
end
-- User defined method.
function Container:onfocus()
end
-- Master method
function Container:blur()
self:set("hasFocus", false)
self:onblur()
end
-- User defined method.
function Container:onblur()
end
-- Master method
function Container:resize()
self:onresize()
end
-- User defined method.
function Container:onresize()
end
-- Master method
function Container:click(x, y, button, istouch)
local wnd = self:get("windows")
local wx = self:get("left")
local wy = self:get("top")
for i=1, #wnd do
if x >= wnd[i]:get("left") + wx and y >= wnd[i]:get("top") + wy and x <= wnd[i]:get("left") + wnd[i]:get("width") + wx and y <= wnd[i]:get("top") + wnd[i]:get("height") + wy then
wnd[i]:onclick(x, y, button, istouch)
return
end
end
self:onclick(x, y, button, istouch)
end
-- User defined method.
function Container:onclick(x, y, button, istouch)
-- print(self:get("id"))
-- print("click")
end
-- Master method
function Container:load()
self:onload()
end
-- User defined method.
function Container:onload()
end
-- Master method
function Container:unload()
self:set("canvas", nil)
self:onunload()
end
-- User defined method.
function Container:onunload()
end
-- Love2d Hook Methods
function Container:mousepressed(x, y, button, istouch)
-- print(self:get("id"))
-- print("mousedown")
end
function Container:mousemoved(x, y, dx, dy, istouch)
-- print(self:get("id"))
-- print("mousemoved")
end
function Container:mousereleased(x, y, button, istouch)
-- print(self:get("id"))
-- print("mouseup")
end
function Container:update(dt)
local wins = self:get("windows")
if #wins > 0 then
for i=#wins, 1, -1 do
wins[i]:update(dt)
end
end
end
function Container:keypressed(key, scancode)
local wins = self:get("windows")
if #wins > 0 then
for i=1, #wins do
if wins[i]:get("hasFocus") then
wins[i]:keypressed(key, scancode)
return
end
end
end
end
function Container:textinput(t)
local wins = self:get("windows")
if #wins > 0 then
for i=1, #wins do
if wins[i]:get("hasFocus") then
wins[i]:textinput(t)
return
end
end
end
end
function Container:draw(x, y)
if x == nil then x = 0 end
if y == nil then y = 0 end
local scx, scy, scw, sch = love.graphics.getScissor( )
local nw = self:get("width")
local nh = self:get("height")
if nw + self:get("left") + x < scw + scx
and nh + self:get("top") + y < sch + scy
then
love.graphics.setScissor(self:get("left") + x, self:get("top") + y, nw, nh)
end
love.graphics.draw(self:get("canvas"), self:get("left") + x, self:get("top") + y)
local wins = self:get("windows")
if #wins > 0 then
for i=#wins, 1, -1 do
wins[i]:draw(self:get("left") + x, self:get("top") + y)
end
end
love.graphics.setScissor(scx, scy, scw, sch)
end
-- Pre-render Container for draw method. Call this when your Container is dirty.
function Container:render(scale)
if scale == nil then scale = 1 end
local canv = love.graphics.newCanvas(self:get("width"), self:get("height"))
local thm = self:get("theme")
local q = love.graphics.newQuad(
0
,0
,self:get("width") - thm:get("images").textbox_nw:getWidth() - thm:get("images").textbox_ne:getWidth()
,self:get("height") - thm:get("images").textbox_nw:getHeight() - thm:get("images").textbox_ne:getHeight()
,thm:get("images").textbox_bg:getWidth() - thm:get("images").textbox_nw:getWidth() - thm:get("images").textbox_ne:getWidth()
,thm:get("images").textbox_bg:getHeight() - thm:get("images").textbox_nw:getHeight() - thm:get("images").textbox_ne:getHeight()
)
local qnw = love.graphics.newQuad(
0
,0
,thm:get("images").textbox_nw:getWidth()
,thm:get("images").textbox_nw:getHeight()
,thm:get("images").textbox_nw:getWidth()
,thm:get("images").textbox_nw:getHeight()
)
local qne = love.graphics.newQuad(
0
,0
,thm:get("images").textbox_ne:getWidth()
,thm:get("images").textbox_ne:getHeight()
,thm:get("images").textbox_ne:getWidth()
,thm:get("images").textbox_ne:getHeight()
)
local qsw = love.graphics.newQuad(
0
,0
,thm:get("images").textbox_sw:getWidth()
,thm:get("images").textbox_sw:getHeight()
,thm:get("images").textbox_sw:getWidth()
,thm:get("images").textbox_sw:getHeight()
)
local qse = love.graphics.newQuad(
0
,0
,thm:get("images").textbox_se:getWidth()
,thm:get("images").textbox_se:getHeight()
,thm:get("images").textbox_se:getWidth()
,thm:get("images").textbox_se:getHeight()
)
local be = love.graphics.newQuad(
0
,0
,thm:get("images").textbox_se:getWidth()
,self:get("height") - thm:get("images").textbox_se:getHeight() - thm:get("images").textbox_se:getHeight()
,thm:get("images").textbox_e:getWidth()
,thm:get("images").textbox_e:getHeight()
)
local bw = love.graphics.newQuad(
0
,0
,thm:get("images").textbox_w:getWidth()
,self:get("height") - thm:get("images").textbox_se:getHeight() - thm:get("images").textbox_ne:getHeight()
,thm:get("images").textbox_w:getWidth()
,thm:get("images").textbox_w:getHeight()
)
local bs = love.graphics.newQuad(
0
,0
,self:get("width") - thm:get("images").textbox_se:getWidth() - thm:get("images").textbox_ne:getWidth()
,thm:get("images").textbox_s:getHeight()
,thm:get("images").textbox_s:getWidth()
,thm:get("images").textbox_s:getHeight()
)
local bn = love.graphics.newQuad(
0
,0
,self:get("width") - thm:get("images").textbox_se:getWidth() - thm:get("images").textbox_ne:getWidth()
,thm:get("images").textbox_n:getHeight()
,thm:get("images").textbox_n:getWidth()
,thm:get("images").textbox_n:getHeight()
)
love.graphics.setCanvas(canv)
love.graphics.draw(thm:get("images").textbox_bg, q, thm:get("images").textbox_nw:getWidth(), thm:get("images").textbox_nw:getHeight())
love.graphics.draw(thm:get("images").textbox_ne, qne, self:get("width") - thm:get("images").textbox_ne:getWidth(), 0)
love.graphics.draw(thm:get("images").textbox_nw, qnw, 0, 0)
love.graphics.draw(thm:get("images").textbox_sw, qsw, 0, self:get("height") - thm:get("images").textbox_sw:getHeight())
love.graphics.draw(thm:get("images").textbox_se, qse, self:get("width") - thm:get("images").textbox_se:getWidth(), self:get("height") - thm:get("images").textbox_se:getHeight())
love.graphics.draw(thm:get("images").textbox_w, bw, 0, thm:get("images").textbox_nw:getHeight())
love.graphics.draw(thm:get("images").textbox_e, be, self:get("width") - thm:get("images").border_e:getWidth(), thm:get("images").textbox_ne:getHeight())
love.graphics.draw(thm:get("images").textbox_s, bs, thm:get("images").textbox_sw:getWidth(), self:get("height") - thm:get("images").textbox_s:getHeight())
love.graphics.draw(thm:get("images").textbox_n, bn, thm:get("images").textbox_nw:getWidth(), 0)
love.graphics.setCanvas()
self:set("canvas", love.graphics.newImage(canv:newImageData()))
self:set("quad", q)
end
return Container
|
ESX = nil
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
fuelCost = 150
RegisterServerEvent('frfuel:fuelAdded')
AddEventHandler('frfuel:fuelAdded', function(amount)
TriggerEvent('es:getPlayerFromId', source, function(xPlayer)--ESX
if (xPlayer) then
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Le prix de l'essence est de " .. fuelCost) --FR
--TriggerClientEvent('chatMessage', source, "SYSTEM", {255, 0, 0}, "The price of gasoline is" .. fuelCost) -- EN
litres = math.random(1, 10)
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "votre plein est de " .. litres .. " litres d'essence") --FR
--TriggerClientEvent('chatMessage', source, "SYSTEM", {255, 0, 0}, "Your full is " .. round(amount) .. " Liters of gasoline") --EN
if litres == 1 then
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Le plein vous a coûté 150$") --FR
local xPlayer = ESX.GetPlayerFromId(source)
if xPlayer.get('money') >= 150 then
xPlayer.removeMoney(150)
elseif xPlayer.get('bank') >= 150 then
xPlayer.removeAccountMoney('bank', 150)
else
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Vous n'avez pas assez d'argent ")
end
elseif litres == 2 then
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Le plein vous a coûté 60$") --FR
local xPlayer = ESX.GetPlayerFromId(source)
if xPlayer.get('money') >= 60 then
xPlayer.removeMoney(60)
elseif xPlayer.get('bank') >= 60 then
xPlayer.removeAccountMoney('bank', 60)
else
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Vous n'avez pas assez d'argent ")
end
elseif litres == 3 then
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Le plein vous a coûté 90$") --FR
local xPlayer = ESX.GetPlayerFromId(source)
if xPlayer.get('money') >= 90 then
xPlayer.removeMoney(90)
elseif xPlayer.get('bank') >= 90 then
xPlayer.removeAccountMoney('bank', 90)
else
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Vous n'avez pas assez d'argent ")
end
elseif litres == 4 then
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Le plein vous a coûté 120$") --FR
local xPlayer = ESX.GetPlayerFromId(source)
if xPlayer.get('money') >= 120 then
xPlayer.removeMoney(120)
elseif xPlayer.get('bank') >= 120 then
xPlayer.removeAccountMoney('bank', 120)
else
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Vous n'avez pas assez d'argent ")
end
elseif litres == 5 then
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Le plein vous a coûté 150$") --FR
local xPlayer = ESX.GetPlayerFromId(source)
if xPlayer.get('money') >= 150 then
xPlayer.removeMoney(150)
elseif xPlayer.get('bank') >= 150 then
xPlayer.removeAccountMoney('bank', 150)
else
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Vous n'avez pas assez d'argent ")
end
elseif litres == 150 then
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Le plein vous a coûté 180$") --FR
local xPlayer = ESX.GetPlayerFromId(source)
if xPlayer.get('money') >= 180 then
xPlayer.removeMoney(180)
elseif xPlayer.get('bank') >= 180 then
xPlayer.removeAccountMoney('bank', 180)
else
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Vous n'avez pas assez d'argent ")
end
elseif litres == 7 then
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Le plein vous a coûté 210$") --FR
local xPlayer = ESX.GetPlayerFromId(source)
if xPlayer.get('money') >= 210 then
xPlayer.removeMoney(210)
elseif xPlayer.get('bank') >= 210 then
xPlayer.removeAccountMoney('bank', 210)
else
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Vous n'avez pas assez d'argent ")
end
elseif litres == 8 then
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Le plein vous a coûté 240$") --FR
local xPlayer = ESX.GetPlayerFromId(source)
if xPlayer.get('money') >= 240 then
xPlayer.removeMoney(240)
elseif xPlayer.get('bank') >= 240 then
xPlayer.removeAccountMoney('bank', 240)
else
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Vous n'avez pas assez d'argent ")
end
elseif litres == 9 then
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Le plein vous a coûté 270$") --FR
local xPlayer = ESX.GetPlayerFromId(source)
if xPlayer.get('money') >= 270 then
xPlayer.removeMoney(270)
elseif xPlayer.get('bank') >= 270 then
xPlayer.removeAccountMoney('bank', 270)
else
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Vous n'avez pas assez d'argent ")
end
elseif litres == 10 then
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Le plein vous a coûté 300$") --FR
local xPlayer = ESX.GetPlayerFromId(source)
if xPlayer.get('money') >= 300 then
xPlayer.removeMoney(300)
elseif xPlayer.get('bank') >= 300 then
xPlayer.removeAccountMoney('bank', 300)
else
TriggerClientEvent('chatMessage', source, "Essence", {255, 0, 0}, "Vous n'avez pas assez d'argent ")
end
end
end
end)
end)
function round(num, numDecimalPlaces)
local mult = 5^(numDecimalPlaces or 0)
return math.random(1, 10)
end
|
local class = require 'middleclass'
local base = class('hj212.params.value.base')
function base:initialize(name, value)
self._name = name
self._value = value
end
function base:value_name()
return self._name
end
function base:value()
return self._value
end
function base:set_value(value)
self._value = value
end
function base:encode()
assert(nil, "Not implemented")
end
function base:decode(raw)
assert(nil, "Not implemented")
end
return base
|
object_tangible_furniture_flooring_tile_frn_flooring_tile_s62 = object_tangible_furniture_flooring_tile_shared_frn_flooring_tile_s62:new {
}
ObjectTemplates:addTemplate(object_tangible_furniture_flooring_tile_frn_flooring_tile_s62, "object/tangible/furniture/flooring/tile/frn_flooring_tile_s62.iff")
|
--=====================================================================
--
-- bufferline.lua -
--
-- Created by liubang on 2022/03/02 16:58
-- Last Modified: 2022/03/02 16:58
--
--=====================================================================
local bufferline = require 'bufferline'
local options = {
options = {
numbers = 'both',
buffer_close_icon = '',
modified_icon = '',
close_icon = '',
show_close_icon = false,
left_trunc_marker = '',
right_trunc_marker = '',
max_name_length = 14,
max_prefix_length = 13,
tab_size = 20,
show_tab_indicators = true,
enforce_regular_tabs = false,
view = 'multiwindow',
show_buffer_close_icons = true,
separator_style = 'thin',
always_show_bufferline = true,
diagnostics = false,
themable = true,
},
}
bufferline.setup(options)
|
-----------------------------------db oper begin------------------------
--local name = require("game.db.keyNameCfg")
--local M = {}
--local function getKey(pid,mapId)
--return "p"..pid.."_"..name.enemy.."_"..mapId
--end
--function M.newEnemyTbl(armyId,mapId,timeIdx,armyAttrT,heroAttrT,bleed,maxBleed,food,coin,morale,skillIds,heroId,fHeroId1,fHeroId2,posX,posY,targetArr)
--local dbArmyTbl = require("sgame.db.dbArmyTbl")
--return dbArmyTbl.newArmyTbl(armyId,mapId,timeIdx,armyAttrT,heroAttrT,bleed,maxBleed,food,coin,morale,skillIds,heroId,fHeroId1,fHeroId2,posX,posY,targetArr)
--end
--function M.createEnemyByCfg(npcCfg,timeIdx)
--local armyId = npcCfg.enemy_id
--local mapId = npcCfg.map_id
--local _ = timeIdx
--local armyAttrT = npcCfg.army_attr
--local heroAttrT = npcCfg.hero_attr
--local bleed = npcCfg.bleed
--local maxBleed = npcCfg.max_bleed
--local food = npcCfg.food
--local coin = npcCfg.coin
--local morale = npcCfg.morale
--local skillIds = npcCfg.skill_ids
--local heroId = npcCfg.hero_ids[1]
--local fHeroId1 = npcCfg.hero_ids[2] or 0
--local fHeroId2 = npcCfg.hero_ids[3] or 0
--local posX = npcCfg.pos[1]
--local posY = npcCfg.pos[2]
--local target = npcCfg.target
--local strategy = npcCfg.strategy
--local t = M.newEnemyTbl(armyId,mapId,timeIdx,armyAttrT,heroAttrT,bleed,maxBleed,food,coin,morale,skillIds,heroId,fHeroId1,fHeroId2,posX,posY,target,strategy)
--return t
--end
--function M.getEnemyTbl(pid,mapId,enemyId)
--local ssdbutils = require("utils.db.ssdbutils")
--local key = getKey(pid,mapId)
--local t = ssdbutils.execute("hgets",key,enemyId)
--return t
--end
--function M.setEnemyTbl(pid,mapId,enemyTbl)
--local ssdbutils = require("utils.db.ssdbutils")
--local key = getKey(pid,mapId)
--return ssdbutils.sendExecute("hsets",key,enemyTbl.enemyId,enemyTbl)
--end
--function M.getEnemyTblT(pid,mapId)
--local ssdbutils = require("utils.db.ssdbutils")
--local key = getKey(pid,mapId)
--local t = ssdbutils.execute("hgetalls",key)
--return t
--end
--function M.setEnemyTblT(pid,mapId,enemyTblT)
--local ssdbutils = require("utils.db.ssdbutils")
--local key = getKey(pid,mapId)
--return ssdbutils.sendExecute("hsetalls",key,enemyTblT)
--end
-----------------------------------db oper end------------------------
--return M
|
local conf = require('conf').t
local res = require 'resources'
local lg = love.graphics
local _=false
local X=true
local lives=3
local score=88888
local pots={X,X,X,X,X,X,X}
local sploshes={X,X,X,X,X,X,X}
local foods={
{X,X,X,X,X,X,X},
{X,X,X,X,X,X,X},
{X,X,X,X,X,X,X},
{X,X,X,X,X,X,X},
{X,X,X,X,X,X,X}}
function love.load()
end
local playing = false
local gameover = false
local slowness = nil
local emptyLines = nil
local function reset()
lives=3
score=0
pots={_,_,_,X,_,_,_}
sploshes={_,_,_,_,_,_,_}
foods={
{_,_,_,_,_,_,_},
{_,_,_,_,_,_,_},
{_,_,_,_,_,_,_},
{_,_,_,_,_,_,_},
{_,_,_,_,_,_,_}}
playing = true
end
local lx = 173
local ly = 130
local potw = 22
function love.draw()
local lgw, lgh = lg.getDimensions()
local sx = lgw/conf.window.width
local sy = lgh/conf.window.height
local scale = math.min(1, math.min(sx, sy))
lgw, lgh = lgw/scale, lgh/scale
lg.scale(scale, scale)
local x0 = math.floor(math.max(0, (lgw-res.img.bg:getWidth())/2))
local y0 = math.floor(math.max(0, (lgh-res.img.bg:getHeight())/2))
lg.setColor(1,1,1)
lg.draw(res.img.bg, x0, y0)
lg.setFont(res.font.lcd)
lg.setColor(res.palette.on)
lg.printf(score, x0, y0+105, 335, 'right')
for line,v in ipairs(foods) do
for food, visible in ipairs(v) do
if visible then lg.draw(res.img.food[food], x0+lx, y0+ly+(line-1)*34) end
end
end
for pot, visible in ipairs(pots) do
if visible then lg.draw(res.img.pot, x0+lx+5+(pot-1)*potw, y0+310) end
end
for splosh, visible in ipairs(sploshes) do
if visible then lg.draw(res.img.splosh, x0+lx+5+(splosh-1)*potw, y0+335) end
end
for cook=0, lives-1 do
lg.draw(res.img.cook, x0+lx+cook*25, y0+100)
end
end
local t=0
local currentEmptyLines=999
function love.update(dt)
if not playing then return end
t=t+dt
slowness = math.max(0.1, 0+70/(score+100))
emptyLines = math.max(0, math.ceil(4-(score+30)/40))
if t<slowness then return end
t=t-slowness
--print(score, slowness, emptyLines)
sploshes={_,_,_,_,_,_,_}
for pos, foodPresent in ipairs(foods[#foods]) do
if foodPresent then
if pots[pos] then
score = score+1
res.sfx.hit.src:play()
else
sploshes[pos] = X
lives = lives - 1
if lives == 0 then
playing=false
gameover=true
res.sfx.gameover.src:play()
else
res.sfx.fail.src:play()
end
end
end
end
table.remove(foods, #foods)
currentEmptyLines = currentEmptyLines + 1
table.insert(foods, 1, {_,_,_,_,_,_,_})
if currentEmptyLines > emptyLines then
foods[1][love.math.random(7)] = X
currentEmptyLines=0
end
end
local function left()
if not pots[1] then
--res.sfx.move.src:play()
table.remove(pots, 1)
table.insert(pots, _)
end
end
local function right()
if not pots[#pots] then
--res.sfx.move.src:play()
table.remove(pots, #pots)
table.insert(pots, 1, _)
end
end
function love.keypressed(key)
if key == 'escape' then love.event.quit()
elseif not playing and not gameover then reset()
elseif key == 'left' then left()
elseif key == 'right' then right() end
end
function love.mousereleased(x, _y, button)
if button == 1 then
if not playing and not gameover then reset()
elseif x<lg:getWidth()*0.45 then left()
elseif x>lg:getWidth()*0.55 then right() end
end
end
function love.joystickreleased(_joystick, button)
if not playing and not gameover then reset() end
if button == 4 or button == 5 or button == 7 then left() end
if button == 2 or button == 6 or button == 8 then right() end
end
function love.joystickhat(_joystick, _hat, direction )
if not playing and not gameover then reset() end
if direction == 'l' then left() end
if direction == 'r' then right() end
end
--[[ breaks android
function love.joystickaxis(_joystick, axis, value )
if not playing and not gameover then reset()
elseif axis == 1 then
if value < 0 then left() end
if value > 0 then right() end
end
end
--]]
|
-- .npc entry
local BAG_VENDOR_IRONFORGE = 5132
local BAG_VENDOR_STORMWIND = 1321
local BAG_VENDOR_DARNASSUS = 4230
local BAG_VENDOR_EXODAR = 16709
local BAG_VENDOR_OGRIMMAR = 3369
local BAG_VENDOR_UNDERCITY = 4590
local BAG_VENDOR_THUNDER_BLUFF = 8364
local BAG_VENDOR_SILVERMOON = 16690
local BAG_NETHERWEAVE = 21841
local BAG_FROSTWEAVE = 41599
local vendors = {BAG_VENDOR_IRONFORGE, BAG_VENDOR_STORMWIND, BAG_VENDOR_DARNASSUS, BAG_VENDOR_EXODAR, BAG_VENDOR_OGRIMMAR, BAG_VENDOR_UNDERCITY, BAG_VENDOR_THUNDER_BLUFF, BAG_VENDOR_SILVERMOON}
-- Add bags
for i = 1, 8 do
AddVendorItem(vendors[i], BAG_NETHERWEAVE, 0, 0, 0)
AddVendorItem(vendors[i], BAG_FROSTWEAVE, 0, 0, 0)
end
-- Remove bags
-- for i = 1, 8 do
-- VendorRemoveItem(vendors[i], BAG_NETHERWEAVE)
-- VendorRemoveItem(vendors[i], BAG_FROSTWEAVE)
-- end
|
-----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Churacoco
-- Type: Standard NPC
-- !pos -76.139 -4.499 20.986 94
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
player:startEvent(434)
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
|
PLUGIN:SetGlobalAlias("cwCTO");
cwCTO.sociostatusColors = {
GREEN = Color(0, 255, 0),
BLUE = Color(0, 128, 255),
YELLOW = Color(255, 255, 0),
RED = Color(255, 0, 0),
BLACK = Color(128, 128, 128)
};
-- Biosignal change enums, used for player/admin command language variations.
cwCTO.ERROR_NONE = 0;
cwCTO.ERROR_NOT_COMBINE = 1;
cwCTO.ERROR_ALREADY_ENABLED = 2;
cwCTO.ERROR_ALREADY_DISABLED = 3;
-- Movement violation enums, used when networking cameras.
cwCTO.VIOLATION_RUNNING = 0;
cwCTO.VIOLATION_JOGGING = 1;
cwCTO.VIOLATION_JUMPING = 2;
cwCTO.VIOLATION_CROUCHING = 3;
cwCTO.VIOLATION_FALLEN_OVER = 4;
-- Camera controlling enums.
cwCTO.CAMERA_VIEW = 0;
cwCTO.CAMERA_DISABLE = 1;
cwCTO.CAMERA_ENABLE = 2;
Clockwork.kernel:IncludePrefixed("cl_hooks.lua");
Clockwork.kernel:IncludePrefixed("sv_plugin.lua");
-- Called when the Clockwork shared variables are added.
--[[function cwCTO:ClockworkAddSharedVars(globalVars, playerVars)
playerVars:Bool("IsBiosignalGone");
end;]]
Clockwork.player:AddCharacterData("IsBiosignalGone", NWTYPE_BOOL, false);
Clockwork.player:AddCharacterData("IsCIDTagGone", NWTYPE_BOOL, false);
Clockwork.player:AddCharacterData("citizenid", NWTYPE_STRING); -- network CIDs
if (SERVER) then
Clockwork.config:Add("cto_biosignal_unobstruct", true, true);
Clockwork.config:Add("cto_biosignal_distance", 0, true);
Clockwork.config:Add("cto_expire_biosignals", 120, true);
Clockwork.config:Add("cto_expire_requests", 60, true);
Clockwork.config:Add("cto_use_tag_system", true, true);
Clockwork.config:Add("cto_citizen_distance", 2048, true);
else
Clockwork.config:AddToSystem("Biosignals Unobstructed", "cto_biosignal_unobstruct", "Whether or not biosignals/cameras should be visible through walls. Requests, losses, violations, etc are exempt.", true);
Clockwork.config:AddToSystem("Biosignal Maximum Distance", "cto_biosignal_distance", "The maximum distance to see biosignals/cameras. Requests, losses, violations, etc are exempt. Set to 0 for infinite.", 0, 20000);
Clockwork.config:AddToSystem("Biosignal Expiry Time", "cto_expire_biosignals", "Time in seconds until a lost biosignal disappears.", 10, 3600);
Clockwork.config:AddToSystem("Request Expiry Time", "cto_expire_requests", "Time in seconds until a request disappears.", 10, 3600);
Clockwork.config:AddToSystem("Use CID Tag System", "cto_use_tag_system", "Whether or not to use the CID tag visor system.", true);
Clockwork.config:AddToSystem("Citizen Data Maximum Distance", "cto_citizen_distance", "The maximum distance to see movement violations and CID tags.", 64, 65536);
end;
function cwCTO:isCameraEnabled(camera)
return (camera:GetSequenceName(camera:GetSequence()) == "idlealert");
end;
|
--[[ File
@description:
This class is for system initialization.
@version: V0.01
@author: Fangyi Zhang email:[email protected]
@acknowledgement:
ARC Centre of Excellence for Robotic Vision (ACRV)
Queensland Univsersity of Technology (QUT)
@history:
V0.00 03/06/2016 developed the first version
V0.01 30/05/2017 enabled the setting for actions through external parameters
]]
dmn = {}
require 'torch'
require 'nn'
require 'nngraph'
require 'net/nnutils'
require 'net/Scale'
require 'net/Rectifier'
require 'learner/SupervisedLearner'
require 'learner/SupervisedFinetuner'
require 'learner/ADTLearner'
require 'image'
package.cpath = package.cpath .. ";./external_lib/?.so" -- Include external libs
-- Modified by Fangyi Zhang
-- to separate the learning core from Atari game engine and interface
function torchSetup(_opt)
_opt = _opt or {}
local opt = table.copy(_opt)
assert(opt)
-- preprocess options:
--- convert options strings to tables
if opt.agent_params then
opt.agent_params = str_to_table(opt.agent_params)
opt.agent_params.gpu = opt.gpu
opt.agent_params.best = opt.best
opt.agent_params.verbose = opt.verbose
if opt.network ~= '' then
opt.agent_params.network = opt.network
end
if opt.p_network ~= '' then
opt.agent_params.p_network = opt.p_network
end
if opt.real_dataset ~= '' then
opt.agent_params.real_dataset = opt.real_dataset
end
end
--- general setup
opt.tensorType = opt.tensorType or 'torch.FloatTensor'
torch.setdefaulttensortype(opt.tensorType) -- Set the default tensor type
if not opt.threads then
opt.threads = 4
end
torch.setnumthreads(opt.threads)
if not opt.verbose then
opt.verbose = 10
end
if opt.verbose >= 1 then
print('Torch Threads:', torch.getnumthreads())
end
--- set gpu device
if opt.gpu and opt.gpu >= 0 then
require 'cutorch'
require 'cunn'
if opt.gpu == 0 then
local gpu_id = tonumber(os.getenv('GPU_ID'))
if gpu_id then opt.gpu = gpu_id+1 end
end
if opt.gpu > 0 then cutorch.setDevice(opt.gpu) end
opt.gpu = cutorch.getDevice()
print('Using GPU device id:', opt.gpu-1)
else
opt.gpu = -1
if opt.verbose >= 1 then
print('Using CPU code only. GPU device id:', opt.gpu)
end
end
--- set up random number generators
-- removing lua RNG; seeding torch RNG with opt.seed and setting cutorch
-- RNG seed to the first uniform random int32 from the previous RNG;
-- this is preferred because using the same seed for both generators
-- may introduce correlations; we assume that both torch RNGs ensure
-- adequate dispersion for different seeds.
math.random = nil
opt.seed = opt.seed or 1
torch.manualSeed(opt.seed)
if opt.verbose >= 1 then
print('Torch Seed:', torch.initialSeed())
end
local firstRandInt = torch.random()
if opt.gpu >= 0 then
cutorch.manualSeed(firstRandInt)
if opt.verbose >= 1 then
print('CUTorch Seed:', cutorch.initialSeed())
end
end
return opt
end
-- Modified by Fangyi Zhang
-- to separate the learning core from Atari game engine and interface
-- and to connect to new simulation environments, lua-sim and matlab-sim
function setup(_opt)
assert(_opt)
--preprocess options:
--- convert options strings to tables
_opt.agent_params = str_to_table(_opt.agent_params)
if _opt.agent_params.transition_params then
_opt.agent_params.transition_params =
str_to_table(_opt.agent_params.transition_params)
end
--- first things first
local opt = torchSetup(_opt)
local gameActions = {}
local n_actions = _opt.agent_params.n_actions or 15
for i=1,n_actions do -- 7dof
gameActions[i] = i
end
-- agent options
_opt.agent_params.actions = gameActions
_opt.agent_params.gpu = _opt.gpu
_opt.agent_params.best = _opt.best
-- If a t7 pre-trained network is provided, the network settings in agent_params will be replaced.
if _opt.network ~= '' then
_opt.agent_params.network = _opt.network
end
if _opt.p_network ~= '' then
_opt.agent_params.p_network = _opt.p_network
end
if _opt.real_dataset ~= '' then
_opt.agent_params.real_dataset = _opt.real_dataset
end
_opt.agent_params.verbose = _opt.verbose
local agent = dmn[_opt.agent](_opt.agent_params)
if opt.verbose >= 1 then
print('Set up Torch using these options:')
for k, v in pairs(opt) do
print(k, v)
end
end
-- return gameActions, agent, opt
return gameActions, agent, opt
end
--- other functions
function str_to_table(str)
if type(str) == 'table' then
return str
end
if not str or type(str) ~= 'string' then
if type(str) == 'table' then
return str
end
return {}
end
local ttr
if str ~= '' then
local ttx=tt
loadstring('tt = {' .. str .. '}')()
ttr = tt
tt = ttx
else
ttr = {}
end
return ttr
end
function table.copy(t)
if t == nil then return nil end
local nt = {}
for k, v in pairs(t) do
if type(v) == 'table' then
nt[k] = table.copy(v)
else
nt[k] = v
end
end
setmetatable(nt, table.copy(getmetatable(t)))
return nt
end
|
-- NVIM-COMPE PLUGIN
-- -----------------
local u = require 'core.utils'
local map = u.map
require('compe').setup {
enabled = true,
autocomplete = true,
debug = false,
min_length = 1,
preselect = 'always',
-- allow_prefix_unmatch = false,
throttle_time = 80,
source_timeout = 200,
-- resolve_timeout = 800,
incomplete_delay = 400,
max_abbr_width = 100,
max_kind_width = 100,
max_menu_width = 100,
documentation = {
border = { '┌', '─', '┐', '│', '┘', '─', '└', '│' },
},
source = {
path = true,
buffer = true,
calc = true,
vsnip = true,
nvim_lsp = true,
nvim_lua = true,
spell = false,
tags = true,
snippets_nvim = false,
},
}
local function check_back_space()
local col = vim.fn.col '.' - 1
if col == 0 or vim.fn.getline('.'):sub(col, col):match '%s' then
return true
else
return false
end
end
--- Move to prev/next item in completion menuone
--- Jump to prev/next snippet's placeholder
_G.tab_complete = function()
if vim.fn.pumvisible() == 1 then
return u.t '<C-n>'
elseif vim.fn.call('vsnip#available', { 1 }) == 1 then
return u.t '<Plug>(vsnip-expand-or-jump)'
elseif check_back_space() then
return u.t '<Tab>'
else
return vim.fn['compe#complete']()
end
end
_G.s_tab_complete = function()
if vim.fn.pumvisible() == 1 then
return u.t '<C-p>'
elseif vim.fn.call('vsnip#jumpable', { -1 }) == 1 then
return u.t '<Plug>(vsnip-jump-prev)'
else
return u.t '<S-Tab>'
end
end
map('i', '<TAB>', 'v:lua.tab_complete()', { noremap = false, expr = true })
map('i', '<S-TAB>', 'v:lua.s_tab_complete()', { noremap = false, expr = true })
map('s', '<TAB>', 'v:lua.tab_complete()', { noremap = false, expr = true })
map('s', '<S-TAB>', 'v:lua.s_tab_complete()', { noremap = false, expr = true })
map('i', '<C-Space>', [[compe#complete()]], { expr = true })
-- map('i', '<CR>', [[compe#confirm('<CR>')]], {expr = true})
map('i', '<C-e>', [[compe#close('<C-e>')]], { expr = true })
-- map('i', '<C-f>', [[compe#scroll({'delta': +4 })]], { expr = true})
-- map('i', '<C-d>', [[compe#scroll({'delta': -4 })]], { expr = true})
--
vim.cmd [[autocmd User CompeConfirmDone silent! lua vim.lsp.buf.signature_help()]]
|
-- example script demonstrating HTTP pipelining
init = function(args)
local r = {}
r[1] = wrk.format(nil, "/")
r[2] = wrk.format(nil, "/")
r[3] = wrk.format(nil, "/")
r[4] = wrk.format(nil, "/")
r[5] = wrk.format(nil, "/")
r[6] = wrk.format(nil, "/")
r[7] = wrk.format(nil, "/")
r[8] = wrk.format(nil, "/")
r[9] = wrk.format(nil, "/")
r[10] = wrk.format(nil, "/")
r[11] = wrk.format(nil, "/")
r[12] = wrk.format(nil, "/")
r[13] = wrk.format(nil, "/")
r[14] = wrk.format(nil, "/")
r[15] = wrk.format(nil, "/")
r[16] = wrk.format(nil, "/")
r[17] = wrk.format(nil, "/")
r[18] = wrk.format(nil, "/")
r[19] = wrk.format(nil, "/")
r[20] = wrk.format(nil, "/")
r[21] = wrk.format(nil, "/")
r[22] = wrk.format(nil, "/")
r[23] = wrk.format(nil, "/")
r[24] = wrk.format(nil, "/")
req = table.concat(r)
end
request = function()
return req
end
|
-- client cvars to control deathmsgs
local hud_deathnotice_time = CreateClientConVar("hud_deathnotice_time", "6", true, false)
local hud_deathnotice_limit = CreateClientConVar("hud_deathnotice_limit", "5", true, false)
local PANEL = {}
Derma_Hook(PANEL, "Paint", "Paint", "GameNotice")
Derma_Hook(PANEL,"ApplySchemeSettings", "Scheme", "GameNotice")
Derma_Hook(PANEL, "PerformLayout", "Layout", "GameNotice")
function PANEL:Init()
self.m_bHighlight = false
self.Padding = 8
self.Spacing = 8
self.Items = {}
end
function PANEL:AddEntityText( txt )
if type(txt) == "string" then
return false
elseif type(txt) == "Player" then
self:AddText( txt:Nick(), team.GetColor(txt:Team()) )
if txt == LocalPlayer() then
self.m_bHighlight = true
end
return true
end
if txt:IsValid() then
self:AddText(txt:GetClass(), GAMEMODE.DeathNoticeDefaultColor)
else
self:AddText(tostring(txt))
end
end
function PANEL:AddItem(item)
table.insert(self.Items, item)
self:InvalidateLayout(true)
end
function PANEL:AddText(txt, color)
if self:AddEntityText(txt) then
return
end
local txt = tostring(txt)
local lbl = vgui.Create("DLabel", self)
Derma_Hook(lbl, "ApplySchemeSettings", "Scheme", "GameNoticeLabel")
lbl:ApplySchemeSettings()
lbl:SetText(txt)
-- localised ent death
if string.Left(txt, 1) == "#" and not color then
color = GAMEMODE.DeathNoticeDefaultColor
end
if GAMEMODE.DeathNoticeTextColor and not color then
color = GAMEMODE.DeathNoticeTextColor
end
if not color then
color = color_white
end
lbl:SetTextColor(color)
self:AddItem(lbl)
end
function PANEL:AddIcon(txt)
if killicon.Exists(txt) then
local icon = vgui.Create("DKillIcon", self)
icon:SetName(txt)
icon:SizeToContents()
self:AddItem(icon)
else
self:AddText("killed")
end
end
function PANEL:PerformLayout()
local x = self.Padding
local height = self.Padding * 0.5
for k, v in pairs(self.Items) do
v:SetPos(x, self.Padding * 0.5)
v:SizeToContents()
x = x + v:GetWide() + self.Spacing
height = math.max(height, v:GetTall() + self.Padding)
end
self:SetSize(x + self.Padding, height)
end
derma.DefineControl("GameNotice", "", PANEL, "DPanel")
|
---@class SandboxOptions.DoubleSandboxOption : zombie.SandboxOptions.DoubleSandboxOption
---@field protected translation String
---@field protected tableName String
---@field protected shortName String
---@field protected bCustom boolean
---@field protected pageName String
SandboxOptions_DoubleSandboxOption = {}
---@public
---@return boolean
function SandboxOptions_DoubleSandboxOption:isCustom() end
---@public
---@return String
function SandboxOptions_DoubleSandboxOption:getShortName() end
---@public
---@return String
function SandboxOptions_DoubleSandboxOption:getTableName() end
---@public
---@param arg0 String
---@return SandboxOptions.SandboxOption
function SandboxOptions_DoubleSandboxOption:setTranslation(arg0) end
---@public
---@param arg0 KahluaTable
---@return void
function SandboxOptions_DoubleSandboxOption:toTable(arg0) end
---@public
---@return ConfigOption
function SandboxOptions_DoubleSandboxOption:asConfigOption() end
---@public
---@return String
function SandboxOptions_DoubleSandboxOption:getTooltip() end
---@public
---@param arg0 String
---@return SandboxOptions.SandboxOption
function SandboxOptions_DoubleSandboxOption:setPageName(arg0) end
---@public
---@return void
function SandboxOptions_DoubleSandboxOption:setCustom() end
---@public
---@return String
function SandboxOptions_DoubleSandboxOption:getPageName() end
---@public
---@return String
function SandboxOptions_DoubleSandboxOption:getTranslatedName() end
---@public
---@param arg0 KahluaTable
---@return void
function SandboxOptions_DoubleSandboxOption:fromTable(arg0) end
|
--[[
***********************************************************
glob.lua
This particular file has been released in the public domain
and is therefore free of any restriction. You are allowed
to credit me as the original author, but this is not
required.
This file was setup/modified in:
2018
If the law of your country does not support the concept
of a product being released in the public domain, while
the original author is still alive, or if his death was
not longer than 70 years ago, you can deem this file
"(c) Jeroen Broks - licensed under the CC0 License",
with basically comes down to the same lack of
restriction the public domain offers. (YAY!)
***********************************************************
Version 18.05.20
]]
local function glob(pattern) -- Only local to prevent conflicts between the var in which this is returned and function itself.
local success,data = JCRXCall({'glob',pattern})
assert(success,data)
return mysplit(data,"\n")
end
function cdglob(pdir,pattern)
local dir = replace(pdir,"\\","/")
-- $IF $WINDOWS
if (not dir) or dir=="" then dir="C:/" end
-- $FI
-- $IF !$WINDOWS
if (not dir) or dir=="" then dir="/" end
-- $FI
if not suffixed(dir,"/") then dir=dir.."/" end
if dir=="~/" then dir = os.getenv("HOME").."/" end
print("cd.glob: "..dir..pattern)
local data=glob(dir..pattern)
for i=1,#data do
data[i]=right(data[i],#data[i]-#dir)
end
return data
end
return glob
|
--[[
Avitab Integration for Laminar's 747-400
By Ilias Tselios
]]--
avitabEnable = find_dataref("avitab/panel_enabled")
avitabPower = find_dataref("avitab/panel_powered")
avitabBrit = find_dataref("avitab/brightness")
lowEICASpage = find_dataref("laminar/B747/dsp/synoptic_display")
lowEICASbrit = find_dataref("sim/cockpit2/electrical/instrument_brightness_ratio")
function avitabShow()
if lowEICASpage == 5 then
avitabEnable = 1
else
avitabEnable = 0
end
avitabBrit = lowEICASbrit[10]
end
function after_physics()
avitabShow()
end
|
local player = require("player")
local enemy = require("enemy")
local Ball = {}
Ball.width = 10
Ball.height = 10
Ball.x = WINDOW_WIDTH / 2 - Ball.width / 2 -- place player paddle on the right side
Ball.y = WINDOW_HEIGHT / 2 - Ball.height / 2 -- center the ball on screen at start
Ball.xVelocity = 100
Ball.yVelocity = 100
function Ball:stayInWindow()
if self.y < 0 then
self.yVelocity = self.yVelocity * -1 -- when we reach the top we flip our speed to go the other way
end
if self.y + self.height > WINDOW_HEIGHT then
self.yVelocity = self.yVelocity * -1 -- when we reach the bottom we flip our speed to go the other way
end
end
function Ball:detectCollision(entity)
if self.x + self.width > entity.x then
self.xVelocity = self.xVelocity * -1
end
if self.x < entity.x + entity.width then
self.xVelocity = self.xVelocity * -1
end
end
function Ball:draw()
love.graphics.rectangle("fill", self.x, self.y, self.width, self.height)
end
function Ball:update(dt)
self:stayInWindow()
self:detectCollision(player)
self:detectCollision(enemy)
self.x = self.x + self.xVelocity * dt
self.y = self.y + self.yVelocity * dt
end
return Ball
|
object_draft_schematic_space_engine_collection_reward_engine_01_mk2 = object_draft_schematic_space_engine_shared_collection_reward_engine_01_mk2:new {
}
ObjectTemplates:addTemplate(object_draft_schematic_space_engine_collection_reward_engine_01_mk2, "object/draft_schematic/space/engine/collection_reward_engine_01_mk2.iff")
|
-------------------------------------------------------------------------------------------------
-- Grid2 AceGUI widgets to be used in AceConfigTables, using dialogControl property.
-------------------------------------------------------------------------------------------------
local AceGUI= LibStub("AceGUI-3.0", true)
-------------------------------------------------------------------------------------------------
-- Modified Multiline Editbox that vertical fills the parent container even in AceConfigDialog Flow layouts.
-- The multiline editbox must be the last defined element in an AceConfigTable.
-------------------------------------------------------------------------------------------------
do
local WidgetType, container = "Grid2ExpandedEditBox"
local function Resize(frame, width, height)
if not container then -- container used as recursion lock
container = frame.obj.parent
frame.obj:SetHeight( frame:GetTop() - container.frame:GetBottom() - 2 )
container = nil
end
end
AceGUI:RegisterWidgetType( WidgetType, function()
local widget = AceGUI:Create("MultiLineEditBox")
widget.type = WidgetType
widget.frame:HookScript("OnSizeChanged", Resize)
return widget
end , 1)
end
-------------------------------------------------------------------------------------------------
-- Custom "description" AceConfigDialog control
-- Title displayed on top of the configuration panel for items like statuses, indicators, etc
-- optional action icons displayed on the top right can be defined.
-- AceConfigTable option usage example:
-- iconsTable = {
-- size = 32, padding = 2, spacing = 4 , offsetx = 0, offsety = 0, anchor = 'TOPRIGHT',
-- [1] = { image = "Path to icon texture", tooltip = "Delete Item", func = deleteFunction },
-- [2] = { image = "Path to icon texture", tooltip = 'Create Item', func = createFunction },
-- } )
-- description = {
-- type = "description", dialogControl = "Grid2Title",
-- order = 0, width = "full", fontSize = "large",
-- image = icon, imageWidth = 34, imageHeight = 34, name = "Title", desc = "Tooltip",
-- arg = iconsTable || { icons = iconsTable },
-- }
-------------------------------------------------------------------------------------------------
do
local Type, Version = "Grid2Title", 1
-- tooltips management
local function ShowTooltip(frame, text)
local tooltip = AceGUI.tooltip
tooltip:SetOwner(frame, "ANCHOR_NONE")
tooltip:ClearAllPoints()
tooltip:SetPoint("TOP",frame,"BOTTOM", 0, -8)
tooltip:ClearLines()
if text:find( "^spell:%d+$" ) then
tooltip:SetHyperlink(text)
else
tooltip:SetText(text , 1, 1, 1, 1, true)
end
tooltip:Show()
end
local function OnEnter(frame)
local desc = frame.obj.userdata.option.desc
if desc then
ShowTooltip(frame, desc)
end
end
local function OnLeave(frame)
AceGUI.tooltip:Hide()
end
local function OnIconEnter(self)
local option = self.parentObj.options[self.index]
if option.tooltip then
ShowTooltip(self.frame, option.tooltip)
end
end
local function OnIconClick(self)
local option = self.parentObj.options[self.index]
if option.func then
option.func( self.parentObj.userdata, self.index )
end
end
-- create action icons when AceConfigTable userdata configuration is available
local function OnShow(frame)
local self = frame.obj
local options = self.userdata and self.userdata.option
if options then
frame:SetScript("OnShow",nil)
self.options = options.arg and options.arg.icons or options.arg
if self.options then
self:AcquireIcons()
end
end
end
local methods = {
["OnAcquire"] = function(self)
self:SetWidth(200)
self:SetText()
self:SetColor()
self:SetFontObject()
self:SetJustifyH("LEFT")
self:SetJustifyV("TOP")
self:SetImage()
self:SetImageSize(32,32)
self.frame:SetScript("OnShow",OnShow)
end,
["OnRelease"] = function(self)
for _,icon in ipairs(self.icons) do
icon.index, icon.parentObj = nil, nil
icon:Release()
end
wipe(self.icons)
self.options = nil
end,
["SetImageSize"] = function(self, width, height)
self.image:SetWidth(width)
self.image:SetHeight(height)
self:SetHeight(height+3)
end,
["SetImage"] = function(self, path,...)
self.image:SetTexture(path)
local n = select("#", ...)
if n == 4 or n == 8 then
self.image:SetTexCoord(...)
else
self.image:SetTexCoord(0, 1, 0, 1)
end
end,
["SetText"] = function(self, text)
self.label:SetText(text)
end,
["SetColor"]= function(self, r, g, b)
self.label:SetVertexColor(r or 1, g or 1, b or 1)
end,
["SetFont"] = function(self, font, height, flags)
self.label:SetFont(font, height, flags)
end,
["SetFontObject"] = function(self, font)
self:SetFont((font or GameFontHighlightSmall):GetFont())
end,
["SetJustifyH"] = function(self, justifyH)
self.label:SetJustifyH(justifyH)
end,
["SetJustifyV"] = function(self, justifyV)
self.label:SetJustifyV(justifyV)
end,
["AcquireIcons"] = function(self)
local options = self.options
local spacing = options.spacing or 0
local iconSize = options.size or 32
local offsetx = options.offsetx or 0
local offsety = options.offsety or 0
local anchor = options.anchor or 'TOPRIGHT'
local imgSize = iconSize - (options.padding or 0)*2
local multx = string.find(anchor,'LEFT') and (iconSize+spacing) or -(iconSize+spacing)
for i,option in ipairs(options) do
local icon = AceGUI:Create("Icon")
icon.index = i
icon.parentObj = self
icon:SetImage(option.image)
icon:SetImageSize(imgSize,imgSize)
icon:SetHeight(iconSize)
icon:SetWidth(iconSize)
icon:SetCallback( "OnClick", OnIconClick )
icon:SetCallback( "OnEnter", OnIconEnter )
icon:SetCallback( "OnLeave", OnLeave )
icon.frame:SetParent( self.frame )
icon.frame:SetPoint( anchor, (i-1)*multx+offsetx, offsety )
icon.image:ClearAllPoints()
icon.image:SetPoint( "CENTER" )
icon.frame:Show()
self.icons[i] = icon
end
end
}
local function Constructor()
local frame = CreateFrame("Frame", nil, UIParent)
frame:EnableMouse(true)
frame:SetScript("OnEnter", OnEnter)
frame:SetScript("OnLeave", OnLeave)
frame:Hide()
local image = frame:CreateTexture(nil, "BACKGROUND")
image:SetPoint("TOPLEFT")
local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontHighlightSmall")
label:SetPoint("LEFT", image, "RIGHT", 4, 0)
local line = frame:CreateTexture(nil, "BACKGROUND")
line:SetHeight(6)
line:SetPoint("BOTTOMLEFT", 0, -4)
line:SetPoint("BOTTOMRIGHT", 0, -4)
line:SetTexture(137057) -- Interface\\Tooltips\\UI-Tooltip-Border
line:SetTexCoord(0.81, 0.94, 0.5, 1)
local widget = { label = label, image = image, frame = frame, type = Type, line = line, icons = {} }
for method, func in pairs(methods) do
widget[method] = func
end
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
end
|
--[[
Skyblock for Minetest
Copyright (c) 2015 cornernote, Brett O'Donnell <[email protected]>
Source Code: https://github.com/cornernote/minetest-skyblock
License: GPLv3
]]--
local modpath = minetest.get_modpath('skyblock_levels')
skyblock.max_level = 6
dofile(modpath..'/skyblock.craft_guide.lua')
dofile(modpath..'/skyblock.feats.lua')
dofile(modpath..'/skyblock.levels.lua')
for lvl = 1, skyblock.max_level do
dofile(modpath..'/skyblock.levels.' .. lvl .. '.lua')
skyblock.log("Level " .. lvl .. " loaded")
end
dofile(modpath..'/register_abm.lua')
dofile(modpath..'/register_craft.lua')
dofile(modpath..'/register_command.lua')
dofile(modpath..'/register_node.lua')
dofile(modpath..'/register_misc.lua')
-- log that we started
skyblock.log('[MOD] '..minetest.get_current_modname()..' -- loaded from '..minetest.get_modpath(minetest.get_current_modname()))
|
package.path = package.path .. ";../src/?.lua"
require "NeuralNetwork"
require "serialize"
function love.load(arg)
math.randomseed( os.time() )
nn = NeuralNetwork(2,4,1)
count = 0
step = 50
size = 10
dataset = {
{ input = {1,0}, output ={1} },
{ input = {1,1}, output ={0} },
{ input = {0,1}, output ={1} },
{ input = {0,0}, output ={0} },
}
testValue = {}
for i=1,love.graphics.getWidth(),step do
for j=1,love.graphics.getHeight(),step do
data = {
x=i+step/2,
y=j+step/2,
i=(i+step/2)/love.graphics.getWidth(),
j=(j+step/2)/love.graphics.getHeight();
}
data.guess = nn:feed({data.i,data.j})
table.insert(testValue,data)
end
end
end
function love.update(dt)
if love.keyboard.isDown('escape') then
love.event.push('quit')
end
if love.keyboard.isDown('return') then
for i=1,10 do
count = count+1
local data = dataset[math.random(1,4)]
nn:train(data.input,data.output)
end
for i,v in ipairs(testValue) do
v.guess = nn:feed({v.i,v.j})
end
end
end
function love.keypressed( key, scancode, isrepeat )
if key == 's' and isrepeat == false then
nn:serialize('save_nn.lua')
end
if key == 'r' and isrepeat == false then
nn = NeuralNetwork.deserialize('save_nn.lua')
for i,v in ipairs(testValue) do
v.guess = nn:feed({v.i,v.j})
end
end
end
function love.draw(dt)
for i,v in ipairs(testValue) do
drawPoint(v.x,v.y,v.guess)
end
love.graphics.setColor({1,1,1})
love.graphics.print(count)
end
function drawPoint(x,y,guess)
love.graphics.setColor(guess:get(1,1) > 0.5 and {1,0,0} or {0,1,0})
love.graphics.circle("fill", x, y, size)
end
|
apoen = {"новачаницу", "кованицу"}
plural = {"новчанице", "кованице"}
od = " од "
valute = {"динар. ", "динара, "}
|
-- Pet class
local pet = {}
local pet_mt = {
__name = "pet";
__index = pet;
}
local function cast_pet(t)
return setmetatable(t, pet_mt)
end
local function new_pet(name)
return cast_pet({
name = name;
photoUrls = {};
tags = {};
})
end
return {
cast = cast_pet;
new = new_pet;
}
|
-- Mon Jul 16 23:34:53 2018
-- (c) Alexander Veledzimovich
-- model KADZEN
local Tmr = require('lib/tmr')
local cmp = require('lib/lovcmp')
local fc = require('lib/fct')
local fl = require('lib/lovfl')
local imd = require('lib/lovimd')
local wrld = require('lib/lovwrld')
local obj = require('game/obj')
local set = require('game/set')
local unpack = table.unpack or unpack
local Model = {}
-- static cmp
Model.getRandOffsetXY = cmp.getRandOffsetXY
Model.getEmptyTile = cmp.getEmptyTile
-- particle
Model.objectParticle=cmp.objectParticle
function Model:new()
cmp.GRAVITY = {x=0,y=0}
cmp.TILESIZE = set.TILESIZE
self.tmr = Tmr:new()
self.levels = {{maze='sidewinder',mons={star=9,tank=0,hunter=0},
key={set.MIDTILEWID-2,set.MIDTILEWID+2,
set.MIDTILEHEI,set.TILEHEI-1,num=1},
ammo={set.MIDTILEWID-4,set.MIDTILEWID+4,
2,set.TILEHEI-1,num=3},
hp={2,set.MIDTILEWID-4,
2,set.TILEHEI-1,num=1},
upgrade={set.MIDTILEWID+4,set.TILEWID-4,
2,set.TILEHEI-1,num=1}},
{maze='backtracking',mons={star=7,tank=2,hunter=0},
key={set.MIDTILEWID-4,set.MIDTILEWID+4,
set.MIDTILEHEI+6,set.TILEHEI-1,num=1},
ammo={2,set.MIDTILEWID-4,
2,set.TILEHEI-1,num=4},
hp={set.MIDTILEWID+4,set.TILEWID-1,
2,set.MIDTILEHEI-2,num=1},
upgrade={set.MIDTILEWID+4,set.TILEWID-1,
set.MIDTILEHEI+2,set.TILEHEI-1,num=1}},
{maze='eller',mons={star=4,tank=3,hunter=2},
key={set.MIDTILEWID-2,set.MIDTILEWID+2,
set.MIDTILEHEI+4,set.TILEHEI-1,num=1},
ammo={set.MIDTILEWID-4,set.MIDTILEWID+4,
2,set.MIDTILEHEI,num=4},
hp={2,set.MIDTILEWID-2,
set.MIDTILEHEI+2,set.TILEHEI-1,num=1},
upgrade={set.MIDTILEWID+2,set.TILEWID-1,
set.MIDTILEHEI+2,set.TILEHEI-1,num=1}},
{maze='hall',mons={star=3,tank=3,hunter=3},
key={2,set.TILEWID-1,
2,set.MIDTILEHEI-4,num=1},
ammo={2,set.TILEWID-1,
set.MIDTILEHEI+4,set.TILEHEI-1,num=5},
hp={2,set.MIDTILEWID-4,
2,set.MIDTILEHEI,num=1},
upgrade={set.MIDTILEWID+4,set.TILEWID-1,
2,set.MIDTILEHEI,num=1}},
}
set.AUD['game']:setVolume(0)
set.AUD['game']:setLooping(true)
set.AUD['game']:play()
self:restart()
end
function Model:restart()
self.avatar = nil
self.pause = false
self.level = 0
self:reset()
local olddata = fl.loadLove(set.SAVE) or {hp={val=1},ammo={val=1},
dist={val=1},chip={val=0}}
self.stat = olddata
self.score = {['star']={val=0},['tank']={val=0},['hunter']={val=0}}
Ctrl:unbind('space')
Ctrl:bind('space','start',function() self:startgame() end)
self.startfire = false
self.sfirex = set.MIDWID+156
self.sfirey = set.MIDHEI+264
self.sfire = self:objectParticle(10, {set.WHITEF,set.ORANGE,set.WHITEHF},
'circle', {0.05,0.8},{0,0.4},256)
View:set_start_scr()
self.tmr:tween(2, self, {fade=1})
local ix, iy = self.sfirex, self.sfirey+14
self.tmr:every(0.1,function() self:initfire(ix,iy,0.07,20) end)
end
function Model:reset()
self.tmr:clear()
if self.objects then
for i=#self.objects,1,-1 do
if self.objects[i].tmr then self.objects[i].tmr:clear() end
end
end
self.objects = {}
self.particles = {}
obj.Monster.pool = {}
-- clear batch sprites tables
obj.Floor:clear()
obj.Wall:clear()
self.fade = 0
self.maze = nil
self.items = nil
end
function Model:set_pause(pause)
if View:get_screen()=='game_scr' then
self.pause = pause or not self.pause
View:set_label('PAUSE',self.pause)
end
end
function Model:spawn(object,index)
if index then table.insert(self.objects,index,object)
else self.objects[#self.objects+1] = object end
end
function Model:destroy(object)
for i=#self.objects,1,-1 do
if self.objects[i]==object then table.remove(self.objects,i) break end
end
end
function Model:get_objects() return self.objects end
function Model:get_object(object,x,y)
local objects = {}
for i=1,#self.objects do
if self.objects[i].tilex==x and self.objects[i].tiley==y then
if self.objects[i]~=object then
objects[#objects+1]=self.objects[i]
end
end
end
return objects
end
function Model:get_particles() return self.particles end
function Model:set_avatar(avatar) self.avatar=avatar end
function Model:get_avatar() return self.avatar end
function Model:get_fade() return self.fade end
function Model:get_maze() return self.maze end
function Model:get_mazetile(x,y) return self.maze[y][x] end
function Model:set_mazetile(x,y,tag) self.maze[y][x]=tag end
function Model:get_itemstile(x,y) return self.items[y][x] end
function Model:set_itemstile(x,y,tag) self.items[y][x]=tag end
function Model:set_score(type)
self.score[type].val = self.score[type].val + 1
end
function Model:get_level() return self.level end
function Model:get_score() return self.score end
function Model.save_gamestat(hp,ammo,dist,chip)
fl.saveLove(set.SAVE,string.format('return {hp={val=%i},ammo={val=%i},dist={val=%i},chip={val=%i}}',hp,ammo,dist,chip))
end
function Model:get_stat()
return self.stat.hp.val,self.stat.ammo.val,
self.stat.dist.val,self.stat.chip.val
end
function Model:set_stat()
self.avatar:set_hp(self.stat.hp.val)
self.avatar:set_ammo(self.stat.ammo.val)
self.avatar:set_weapon(self.stat.dist.val)
self.avatar:set_chip(self.stat.chip.val)
end
function Model:save_stat()
self.stat.hp.val = self.avatar:get_hp()
self.stat.ammo.val = self.avatar:get_ammo()
self.stat.dist.val = self.avatar:get_weapondist()
self.stat.chip.val = self.avatar:get_chip()
end
function Model:set_bonus(bonus,val,tag,type,door)
local xval, yval
for _=1,val.num do
repeat
xval=love.math.random(val[1],val[2])
yval=love.math.random(val[3],val[4])
until self.items[yval][xval]==wrld.FLOOR
if type~='hall' then
self.items[yval][xval] = tag
bonus{x=math.floor(xval*set.TILESIZE),
y=math.floor(yval*set.TILESIZE),door=door}
end
end
return {xval,yval}
end
function Model:doorside(tile,wall)
local empty = self.getEmptyTile(self.maze,tile,wall)
local side
if fc.isval('left',empty) then side='CW' end
if fc.isval('up',empty) then side='VFLIP' end
if fc.isval('right',empty) then side='CCW' end
if fc.isval('down',empty) then side='HFLIP' end
return side
end
function Model:wallside(tile,wall)
local wall_sprite=obj.Wall:getSprite()
local empty = self.getEmptyTile(self.maze,tile,wall)
local image
if #empty==0 then
image = wall_sprite.quads[1]
elseif #empty==1 then
if empty[1]=='down' then
image = wall_sprite.quads[5]
elseif empty[1]=='right' then
image = wall_sprite.quads[4]
elseif empty[1]=='up' then
image = wall_sprite.quads[3]
else
image = wall_sprite.quads[2]
end
elseif #empty==2 then
if ((empty[1]=='up' and empty[2]=='down') or
(empty[2]=='up' and empty[1]=='down')) then
image = wall_sprite.quads[11]
elseif ((empty[1]=='left' and empty[2]=='up') or
(empty[2]=='left' and empty[1]=='up')) then
image = wall_sprite.quads[8]
elseif ((empty[1]=='right' and empty[2]=='up') or
(empty[2]=='right' and empty[1]=='up'))then
image = wall_sprite.quads[9]
elseif ((empty[1]=='right' and empty[2]=='down') or
(empty[2]=='right' and empty[1]=='down')) then
image = wall_sprite.quads[6]
elseif ((empty[1]=='left' and empty[2]=='down') or
(empty[2]=='left' and empty[1]=='down'))then
image = wall_sprite.quads[7]
else
image = wall_sprite.quads[10]
end
elseif #empty==3 then
if not fc.isval('up',empty) then
image = wall_sprite.quads[14]
elseif not fc.isval('left',empty) then
image = wall_sprite.quads[13]
elseif not fc.isval('right',empty) then
image = wall_sprite.quads[15]
else
image = wall_sprite.quads[12]
end
else
image = wall_sprite.quads[16]
end
return image
end
function Model:set_maze(type,mons,keynum,ammonum,hpnum,upgradenum)
if type=='sidewinder' then
self.maze = wrld.sidewinder(set.WID,set.HEI, set.TILESIZE)
elseif type=='eller' then
self.maze = wrld.eller(set.WID,set.HEI, set.TILESIZE)
elseif type=='backtracking' then
self.maze = wrld.backtracking(set.WID,set.HEI, set.TILESIZE)
elseif type=='hall' then
self.maze=wrld.hall(set.WID,set.HEI, set.TILESIZE)
else
return
end
local exittile
local starttile
local floor_sprite=obj.Floor:getSprite()
local wall_sprite=obj.Wall:getSprite()
for tiley=1,#self.maze do
for tilex=1,#self.maze[1] do
local x = math.floor((tilex)*set.TILESIZE)
local y = math.floor((tiley)*set.TILESIZE)
local randfloor=love.math.random(#floor_sprite.quads-1)
floor_sprite.table:add(floor_sprite.quads[randfloor],
x-set.TILESIZE/2, y-set.TILESIZE/2,0,
set.SCALE,set.SCALE)
if self.maze[tiley][tilex]==wrld.WALL then
local image
local empty = self.getEmptyTile(self.maze,
{tilex,tiley},wrld.WALL)
if ((tilex==1 or tilex==set.TILEWID) or
(tiley==1 or tiley==set.TILEHEI)) then
image = wall_sprite.quads[16]
elseif tilex==2 then
if #empty==3 then
image = wall_sprite.quads[16]
else
image = wall_sprite.quads[15]
end
elseif tilex==set.TILEWID-1 then
image = wall_sprite.quads[13]
elseif tiley==set.TILEHEI-1 then
image = wall_sprite.quads[14]
elseif tiley==2 then
image = wall_sprite.quads[12]
else
image=self:wallside({tilex,tiley},wrld.WALL)
end
local id = wall_sprite.table:add(image,
x-set.TILESIZE/2, y-set.TILESIZE/2,0,
set.SCALE,set.SCALE)
obj.Wall{x=x, y=y,sid=id}
elseif self.maze[tiley][tilex]==wrld.START then
obj.Start{x=x,y=y}
starttile={tilex,tiley}
elseif self.maze[tiley][tilex]==wrld.FIN then
local side = self:doorside({tilex,tiley},wrld.WALL)
obj.Fin.imgdata = imd.rotate(obj.Fin.all_data[1],side)
obj.Fin.img_open = imd.rotate(obj.Fin.all_data[2],side)
obj.Fin.dstdata = imd.splash(obj.Fin.img_open,
20,set.TILESIZE)
if type~='hall' then
obj.Fin{x=x,y=y}
end
exittile = {tilex,tiley}
end
end
end
self.items=fc.copy(self.maze)
local keytile = self:set_bonus(obj.Key,keynum,'K',type,exittile)
local ammotile = self:set_bonus(obj.Ammo,ammonum,'A')
local hptile = self:set_bonus(obj.Hp,hpnum,'H')
local upgradetile = self:set_bonus(obj.Upgrade,upgradenum,'U')
-- create monsters
for _=1, mons.star do
obj.Star{x=math.floor(exittile[1]*set.TILESIZE),
y=math.floor(exittile[2]*set.TILESIZE)}
end
for _=1, mons.tank do
obj.Tank{x=math.floor(keytile[1]*set.TILESIZE),
y=math.floor(keytile[2]*set.TILESIZE)}
end
for _=1, mons.hunter do
obj.Hunter{x=math.floor(ammotile[1]*set.TILESIZE),
y=math.floor(ammotile[2]*set.TILESIZE),
oldgoal={hptile,upgradetile,ammotile,exittile,
{set.MIDTILEWID,2},{set.MIDTILEWID,set.TILEHEI-1},
{2,set.MIDTILEHEI},{set.TILEWID-1,set.MIDTILEHEI}}}
end
self:set_avatar(obj.Kadzen{
x=math.floor(starttile[1]*set.TILESIZE),
y=math.floor(starttile[2]*set.TILESIZE)})
self:set_stat()
end
function Model:market()
love.mouse.setVisible(true)
View:set_market_scr()
self.tmr:tween(2, self, {fade=0})
end
function Model:nextmaze()
self.level=self.level+1
self:reset()
self:set_maze(self.levels[self.level].maze,
self.levels[self.level].mons,
self.levels[self.level].key,
self.levels[self.level].ammo,
self.levels[self.level].hp,
self.levels[self.level].upgrade)
View:set_level_scr(self.level)
self.tmr:tween(2, self, {fade=1})
end
function Model:nextlevel()
View:set_game_scr()
end
function Model:initfire(x,y,size,speed)
local ifire = self:objectParticle(1, {set.BLACK,set.ORANGE,set.WHITEHF},
set.IMG['fire'], {0.05,0.5},{0,size},128)
ifire.particle:setPosition(x,y)
ifire.particle:setSpeed(0,speed)
ifire.particle:setDirection(-1.5)
ifire.particle:emit(50)
end
function Model:startgame()
Ctrl:unbind('space')
Ctrl:bind('space','fire')
self.startfire = true
self.tmr:clear()
self:initfire(self.sfirex,self.sfirey+12,0.15,300)
set.AUD['start']:play()
set.AUD['tnt']:setVolume(0.2)
set.AUD['tnt']:play()
self.tmr:tween(2,self,{sfirex=self.sfirex-15,sfirey=self.sfirey+12,fade=0},
'linear',function() self:nextmaze() end)
end
function Model:update(dt)
if View:get_screen()=='ui_scr' then
if self.startfire then
self.sfire.particle:setPosition(self.sfirex,self.sfirey)
self.sfire.particle:emit(30)
end
for particle in pairs(self.particles) do
particle:update(dt)
end
end
if View:get_screen()=='game_scr' then
if self.pause then return end
-- particle
for particle in pairs(self.particles) do
particle:update(dt)
if particle:getCount()==0 then
particle:reset()
end
end
-- collision
for i=1,#self.objects do
if self.objects[i].tag~=wrld.WALL and not self.objects[i].dead then
self.objects[i].lastcoll = {}
self.objects[i]:collision(self.maze)
if #self.objects[i].lastcoll == 0 then
self.objects[i].collide=nil
end
end
end
-- objects
for i=1,#self.objects do
local object=self.objects[i]
if object and not object.dead and object.update then
object:update(dt)
end
end
end
set.AUD['game']:setVolume(self.fade)
View:get_ui().Manager.update(dt)
end
function Model:endgame(dead)
self.tmr:tween(2, self, {fade=0})
self:save_stat()
if dead then
View:set_fin_scr('GAME OVER')
self.save_gamestat(1,1,1,self.stat.chip.val)
else
View:set_fin_scr('KADZEN WIN')
local hp,ammo,dist,chip = Model:get_stat()
self.save_gamestat(hp,ammo,dist,chip)
end
Ctrl:unbind('space')
Ctrl:bind('space','start',function() self:restart() end)
end
return Model
|
-- See LICENSE for terms
local mod_TurnOff
local mod_SkipGrids
local mod_SkipPassages
-- fired when settings are changed/init
local function ModOptions()
mod_TurnOff = CurrentModOptions:GetProperty("TurnOff")
mod_SkipGrids = CurrentModOptions:GetProperty("SkipGrids")
mod_SkipPassages = CurrentModOptions:GetProperty("SkipPassages")
end
-- load default/saved settings
OnMsg.ModsReloaded = ModOptions
-- fired when option is changed
function OnMsg.ApplyModOptions(id)
if id == CurrentModId then
ModOptions()
end
end
local skip_grid = {
"CableConstructionSite",
"GridSwitchConstructionSite",
"PipeConstructionSite",
}
local skips = {
"MirrorSphereBuilding",
"BlackCubeMonolith",
"CrystalsBuilding",
"Sinkhole",
}
function OnMsg.ConstructionSitePlaced(site)
if not mod_TurnOff then
return
end
if site.building_class_proto:IsKindOfClasses(skips)
or (mod_SkipPassages and site:IsKindOf("PassageConstructionSite"))
or (mod_SkipGrids and site:IsKindOfClasses(skip_grid))
then
return
end
RebuildInfopanel(site)
site:SetUIWorking(false)
end
GlobalVar("ChoGGi_ConstructionSitesStartOff_cleanup", false)
-- remove after a few months (aug 2020)
function OnMsg.LoadGame()
if ChoGGi_ConstructionSitesStartOff_cleanup then
return
end
local objs = MapGet("map", "ConstructionSite")
for i = 1, #objs do
local obj = objs[i]
if obj.building_class_proto:IsKindOfClasses(skips) then
obj:SetUIWorking(true)
end
end
ChoGGi_ConstructionSitesStartOff_cleanup = true
end
|
-- https://zzamboni.org/post/my-hammerspoon-configuration-with-commentary/
hs.loadSpoon("SpoonInstall")
spoon.SpoonInstall.use_syncinstall = true
Install=spoon.SpoonInstall
hs.loadSpoon('ControlEscape'):start() -- Load Hammerspoon bits from https://github.com/jasonrudolph/ControlEscape.spoon
require('windows')
hs.notify.show("Welcome to Hammerspoon", "Have fun!", "")
|
local puller = require 'lifter_puller.puller'
local event = require 'lifter_puller.event'
function _assert(test, ...)
if not test then
error(string.format(...), 2)
end
end
describe('Puller', function ()
describe('should parse decl', function ()
it('with all values', function ()
local p = puller.new('<?xml version="1.2" encoding="utf-8" standalone="no" ?>')
local e = assert(p:next())
_assert(e.ty == event.event_type.declaration, 'expected decl found %s', e.ty)
_assert(e.version == '1.2', 'expected version 1.2 found %s', e.version)
_assert(e.encoding == 'utf-8', 'expected utf-8 found %s', e.encoding)
_assert(e.standalone == false, 'expected standalone to be false found %s', e.standalone)
end)
end)
describe('should parse doctype', function()
it('empty with all values', function ()
local p = puller.new('<!DOCTYPE name PUBLIC "first_value" "second_value">')
local e = assert(p:next())
_assert(e.ty == event.event_type.doctype, 'expected empty doctype, found %s', e.ty)
_assert(e.name == 'name', 'expected name of name found "%s"', e.name)
_assert(e.external_id == 'PUBLIC', 'expected external_id of PUBLIC found "%s"', e.external_id)
_assert(e.external_value[1] == 'first_value', 'expected external value first_value found "%s"', e.external_value[2])
_assert(e.external_value[2] == 'second_value', 'expected external value second_value found "%s"', e.external_value[2])
end)
it('empty with SYSTEM', function ()
local p = puller.new('<!DOCTYPE name SYSTEM "first_value">')
local e = assert(p:next())
_assert(e.ty == event.event_type.doctype, 'expected empty doctype, found %s', e.ty)
_assert(e.name == 'name', 'expected name of name found "%s"', e.name)
_assert(e.external_id == 'SYSTEM', 'expected external_id of SYSTEM found "%s"', e.external_id)
_assert(e.external_value[1] == 'first_value', 'expected external value first_value found "%s"', e.external_value[2])
end)
it('not empty, one entity, not system or public', function ()
local p = puller.new([[<!DOCTYPE svg [
<!ENTITY name "value">
]>]])
local e1 = assert(p:next())
_assert(e1.ty == event.event_type.doctype_start, 'expected %s found %s', event.event_type.doctype_start, e1.ty)
_assert(e1.name == 'svg', 'expecte svg found %s', e1.name)
_assert(e1.external_id == nil, 'expecte nil found %s', e1.external_id)
_assert(#e1.external_value == 0, 'expecte 0 found %s', #e1.external_value)
local e2 = assert(p:next())
_assert(e2.ty == event.event_type.entity_declaration, 'expected %s found %s', event.event_type.entity_declaration, e2.ty)
_assert(e2.name == 'name', 'Expected name found `%s`', e2.name)
_assert(e2.external_value == 'value', 'expected value found `%s`', e2.external_value)
end)
it('not empty, one entity, with NDATA', function ()
local p = puller.new([[<!DOCTYPE svg [
<!ENTITY name SYSTEM "value" NDATA ndata>
]>]])
local e1 = assert(p:next())
_assert(e1.ty == event.event_type.doctype_start, 'expected %s found %s', event.event_type.doctype_start, e1.ty)
_assert(e1.name == 'svg', 'expecte svg found %s', e1.name)
_assert(#e1.external_value == 0, 'expecte 0 found %s', #e1.external_value)
local e2 = assert(p:next())
_assert(e2.ty == event.event_type.entity_declaration, 'expected %s found %s', event.event_type.entity_declaration, e2.ty)
_assert(e2.name == 'name', 'Expected name found `%s`', e2.name)
_assert(e2.external_id == 'SYSTEM', 'expecte SYSTEM found %s', e2.external_id)
_assert(e2.external_value[1] == 'value', 'expecte value found %s', e2.external_value[1])
_assert(e2.external_value[2] == nil, 'expecte nil found %s', e2.external_value[2])
_assert(e2.ndata == 'ndata', 'expected ndata found %s', e2.ndata)
end)
it('not empty, entity, system and public', function ()
local p = puller.new([[<!DOCTYPE svg [
<!ENTITY system SYSTEM "system_value">
<!ENTITY public PUBLIC "public_value1" "public_value2">
]>]])
local e1 = assert(p:next())
_assert(e1.ty == event.event_type.doctype_start, 'expected %s found %s', event.event_type.doctype_start, e1.ty)
_assert(e1.name == 'svg', 'expecte svg found %s', e1.name)
_assert(e1.external_id == nil, 'expecte nil found %s', e1.external_id)
_assert(#e1.external_value == 0, 'expecte 0 found %s', #e1.external_value)
local e2 = assert(p:next())
_assert(e2.ty == event.event_type.entity_declaration, 'expected %s found %s', event.event_type.entity_declaration, e2.ty)
_assert(e2.external_id == 'SYSTEM', 'Expected SYSTEM found `%s`', e2.external_id)
_assert(e2.name == 'system', 'Expected system found `%s`', e2.name)
_assert(e2.external_value[1] == 'system_value', 'expected system_value found `%s`', e2.external_value[1])
local e3 = assert(p:next())
_assert(e3.ty == event.event_type.entity_declaration, 'expected %s found %s', event.event_type.entity_declaration, e2.ty)
_assert(e3.name == 'public', 'Expected system found `%s`', e3.name)
_assert(e3.external_id == 'PUBLIC', 'Expected PUBLIC found `%s`', e3.external_id)
_assert(e3.external_value[1] == 'public_value1', 'expected public_value1 found `%s`', e3.external_value[1])
_assert(e3.external_value[2] == 'public_value2', 'expected public_value2 found `%s`', e3.external_value[2])
local e4 = assert(p:next())
_assert(e4.ty == event.event_type.doctype_end, 'expected %s found %s', event.event_type.doctype_end, e4.ty)
end)
it('not empty, entity with %', function ()
local p = puller.new([[<!DOCTYPE svg [
<!ENTITY % name1 SYSTEM "value">
]>]])
local e1 = assert(p:next())
_assert(e1.ty == event.event_type.doctype_start, 'expected %s found %s', event.event_type.doctype_start, e1.ty)
_assert(e1.name == 'svg', 'expecte svg found %s', e1.name)
_assert(e1.external_id == nil, 'expecte nil found %s', e1.external_id)
_assert(#e1.external_value == 0, 'expecte 0 found %s', #e1.external_value)
local e2 = assert(p:next())
_assert(e2.ty == event.event_type.entity_declaration, 'expected %s found %s', event.event_type.entity_declaration, e2.ty)
_assert(e2.external_id == 'SYSTEM', 'Expected SYSTEM found `%s`', e2.external_id)
_assert(e2.name == 'name1', 'Expected system found `%s`', e2.name)
_assert(e2.external_value[1] == 'value', 'expected system_value found `%s`', e2.external_value[1])
local e3 = assert(p:next())
_assert(e3.ty == event.event_type.doctype_end, 'expected %s found %s', event.event_type.doctype_end, e3.ty)
end)
end)
describe('should parse comments', function()
it('single line comment', function()
local p = puller.new('<!-- This is a comment! -->')
local e = assert(p:next())
_assert(e.ty == event.event_type.comment, 'expected comment found %s', e.ty)
_assert(e.text == ' This is a comment! ', 'bad comment text found "%s"', e.text)
end)
end)
describe('should parse processing instruction', function()
it('with content', function()
local p = puller.new('<?target content?>')
local e = assert(p:next())
_assert(e.ty == event.event_type.processing_instruction, 'expected pi found %s', e.ty)
_assert(e.target == 'target', 'bad target found "%s"', e.target)
_assert(e.content == 'content', 'bad content found "%s"', e.content)
end)
it('without content', function()
local p = puller.new('<?target?>')
local e = assert(p:next())
_assert(e.ty == event.event_type.processing_instruction, 'expected pi found %s', e.ty)
_assert(e.target == 'target', 'bad target found "%s"', e.target)
_assert(e.content == nil, 'bad content found "%s"', e.content)
end)
end)
describe('should parse cdata', function ()
local p = puller.new('<p><![CDATA[cdata]]></p>')
local e1 = assert(p:next())
_assert(e1.ty == event.event_type.open_tag, '')
_assert(e1.name == 'p', 'expected `p` found `%s`', e1.name)
local e2 = assert(p:next())
_assert(e2.ty == event.event_type.tag_end, 'expected %s found %s', event.event_type.tag_end, e2.ty)
local e3 = assert(p:next())
_assert(e3.ty == event.event_type.cdata, 'expecting %s found %s', event.event_type.tag_end, e3.ty)
_assert(e3.text == 'cdata', 'expected cdata found %s', e3.text)
local e4 = assert(p:next())
_assert(e4.ty == event.event_type.close_tag, 'Expected %s, found `%s`', event.event_type.close_tag, e4.ty)
_assert(e4.name == 'p', 'exepected p found `%s`', e4.name)
end)
describe('should parse elements', function ()
it('should handle self closing', function ()
local p = puller.new('<self-closing />')
local e1 = assert(p:next())
_assert(e1.ty == event.event_type.open_tag, 'expected %s found %s', event.event_type.open_tag, e1.ty)
_assert(e1.name == 'self-closing', 'expected self-closing found `%s`', e1.name)
local e2 = assert(p:next())
_assert(e2.ty == event.event_type.tag_end, 'expected %s found %s', event.event_type.tag_end, e2.ty)
_assert(e2.is_empty, 'expected close tag to be empty found %s', e2.is_empty)
end)
it('should handle complicated name start', function ()
local p = puller.new('<𐌺_ />')
local e1 = assert(p:next())
_assert(e1.ty == event.event_type.open_tag, 'expected %s found %s', event.event_type.open_tag, e1.ty)
_assert(e1.name == '𐌺_', 'expected 𐌺_ found `%s`', e1.name)
local e2 = assert(p:next())
_assert(e2.ty == event.event_type.tag_end, 'expected %s found %s', event.event_type.tag_end, e2.ty)
_assert(e2.is_empty, 'expected close tag to be empty found %s', e2.is_empty)
end)
it('should handle complicated name continue', function ()
local p = puller.new('<a_𐌺 />')
local e1 = assert(p:next())
_assert(e1.ty == event.event_type.open_tag, 'expected %s found %s', event.event_type.open_tag, e1.ty)
_assert(e1.name == 'a_𐌺', 'expected a_𐌺 found `%s`', e1.name)
local e2 = assert(p:next())
_assert(e2.ty == event.event_type.tag_end, 'expected %s found %s', event.event_type.tag_end, e2.ty)
_assert(e2.is_empty, 'expected close tag to be empty found %s', e2.is_empty)
end)
it('should handle prefixed names', function ()
local p = puller.new('<prefix:name></prefix:name>')
local e1 = assert(p:next())
_assert(e1.ty == event.event_type.open_tag, 'expected %s found %s', event.event_type.open_tag, e1.ty)
_assert(e1.prefix == 'prefix', 'expected prefix found `%s`', e1.prefix)
_assert(e1.name == 'name', 'expected self-closing found `%s`', e1.name)
local e2 = assert(p:next())
_assert(e2.ty == event.event_type.tag_end, 'expected %s found %s', event.event_type.tag_end, e2.ty)
_assert(e2.is_empty == false, 'expected not empty found `%s`', e2.is_empty)
local e3 = assert(p:next())
_assert(e3.ty == event.event_type.close_tag, 'expected %s found %s', event.event_type.close_tag, e3.ty)
_assert(e3.prefix == 'prefix', 'expected prefix found `%s`', e3.prefix)
_assert(e3.name == 'name', 'expected self-closing found `%s`', e3.name)
end)
it('should handle attributes', function ()
local p = puller.new('<name attr="value"></name>')
local e1 = assert(p:next())
_assert(e1.ty == event.event_type.open_tag, 'expected %s found %s', event.event_type.open_tag, e1.ty)
_assert(e1.name == 'name', 'expected self-closing found `%s`', e1.name)
local e2 = assert(p:next())
_assert(e2.ty == event.event_type.attribute, 'expected %s found %s', event.event_type.attribute, e2.ty)
_assert(e2.name == 'attr', 'expected attr found `%s`', e2.name)
_assert(e2.value == 'value', 'expected value found `%s`', e2.value)
local e3 = assert(p:next())
_assert(e3.ty == event.event_type.tag_end, 'expected %s found %s', event.event_type.tag_end, e3.ty)
_assert(e3.is_empty == false, 'expected not empty found `%s`', e3.is_empty)
local e4 = assert(p:next())
_assert(e4.ty == event.event_type.close_tag, 'expected %s found %s', event.event_type.close_tag, e4.ty)
_assert(e4.name == 'name', 'expected self-closing found `%s`', e4.name)
end)
it('should handle attributes with prefix', function ()
local p = puller.new('<name attr="value" prefix:attr="value"></name>')
local e1 = assert(p:next())
_assert(e1.ty == event.event_type.open_tag, 'expected %s found %s', event.event_type.open_tag, e1.ty)
_assert(e1.name == 'name', 'expected self-closing found `%s`', e1.name)
local e2 = assert(p:next())
_assert(e2.ty == event.event_type.attribute, 'expected %s found %s', event.event_type.attribute, e2.ty)
_assert(e2.name == 'attr', 'expected attr found `%s`', e2.name)
_assert(e2.value == 'value', 'expected value found `%s`', e2.value)
local e2 = assert(p:next())
_assert(e2.ty == event.event_type.attribute, 'expected %s found %s', event.event_type.attribute, e2.ty)
_assert(e2.prefix == 'prefix', 'expected prefix found `%s`', e2.prefix)
_assert(e2.name == 'attr', 'expected attr found `%s`', e2.name)
_assert(e2.value == 'value', 'expected value found `%s`', e2.value)
local e3 = assert(p:next())
_assert(e3.ty == event.event_type.tag_end, 'expected %s found %s', event.event_type.tag_end, e3.ty)
_assert(e3.is_empty == false, 'expected not empty found `%s`', e3.is_empty)
local e4 = assert(p:next())
_assert(e4.ty == event.event_type.close_tag, 'expected %s found %s', event.event_type.close_tag, e4.ty)
_assert(e4.name == 'name', 'expected self-closing found `%s`', e4.name)
end)
it('should handle non-empty tags', function ()
local text = 'I am some text content inside of some tags'
local p = puller.new(string.format('<name attr="value" prefix:attr="value">%s</name>', text))
local e1 = assert(p:next())
_assert(e1.ty == event.event_type.open_tag, 'expected %s found %s', event.event_type.open_tag, e1.ty)
_assert(e1.name == 'name', 'expected self-closing found `%s`', e1.name)
local e2 = assert(p:next())
_assert(e2.ty == event.event_type.attribute, 'expected %s found %s', event.event_type.attribute, e2.ty)
_assert(e2.name == 'attr', 'expected attr found `%s`', e2.name)
_assert(e2.value == 'value', 'expected value found `%s`', e2.value)
local e2 = assert(p:next())
_assert(e2.ty == event.event_type.attribute, 'expected %s found %s', event.event_type.attribute, e2.ty)
_assert(e2.prefix == 'prefix', 'expected prefix found `%s`', e2.prefix)
_assert(e2.name == 'attr', 'expected attr found `%s`', e2.name)
_assert(e2.value == 'value', 'expected value found `%s`', e2.value)
local e3 = assert(p:next())
_assert(e3.ty == event.event_type.tag_end, 'expected %s found %s', event.event_type.tag_end, e3.ty)
_assert(e3.is_empty == false, 'expected not empty found `%s`', e3.is_empty)
local e4 = assert(p:next())
_assert(e4.ty == event.event_type.text, 'expected %s found %s', event.event_type.text, e4.ty)
_assert(e4.text == text, 'expected `%s` found `%s`', text, e4.text)
local e5 = assert(p:next())
_assert(e5.ty == event.event_type.close_tag, 'expected %s found %s', event.event_type.close_tag, e5.ty)
_assert(e5.name == 'name', 'expected self-closing found `%s`', e5.name)
end)
end)
end)
|
local Bullet = require("bullet")
function love.load()
love.keyboard.setKeyRepeat(true)
local w, h = love.graphics.getDimensions()
local image = love.graphics.newImage("graphics/boss.png")
local bulletImage = love.graphics.newImage("graphics/bullet.png")
bullet = Bullet(image, bulletImage, math.floor(w/2)-image:getWidth(), math.floor(h/2)-image:getHeight())
-- To use default values and no images, comment the previous line and uncomment the following one
--bullet = Bullet()
end
function love.update(dt)
bullet:update(dt)
end
function love.draw()
bullet:draw()
end
function love.keypressed(key)
if (key == "escape") then
love.event.quit("restart")
end
bullet:keypressed(key)
end
|
udg_LEADERBOARD = nil
udg_LVL = 0
udg_CurrentlyOnMap = 0.0
udg_UnitToSpawn = 0
udg_LevelHero = 0
udg_ConnectedPlayers = nil
udg_EmptyPlayers = nil
udg_TempUnitGroup = nil
udg_Kills = __jarray(0)
udg_TempInt = 0
udg_SpawnAreas = {}
udg_TempPoint = nil
udg_OutsideClockwise = 0
udg_OutsideCounterClockwise = 0
udg_InsideClockwise = 0
udg_InsideCounterClockwise = 0
udg_UnknownDirection = 0
udg_OutsideToInside = 0
udg_InsideToOutside = 0
udg_SpawningCalc = 0
udg_GroupInside = nil
udg_GroupOutside = nil
udg_SpawningGroup = false
udg_SpawnCounter = 0
udg_SpawningRate = 0.0
udg_NextSpawnTracker = 0.0
udg_EmptySpawnCounter = 0
udg_HardVotes = __jarray(0)
udg_InsaneVotes = __jarray(0)
udg_HardCount = 0
udg_InsaneCount = 0
udg_NumberToSpawn = __jarray(0)
udg_WaveUnits = __jarray(0)
udg_TempString = ""
udg_SoundToPlay = nil
udg_LoseValue = 0.0
udg_TempReal = 0.0
udg_TempUnit = nil
udg_PredictLevel = 0
udg_TempPlayerGroup = nil
udg_RangeCalc = 0.0
udg_RangeCount = 0.0
udg_FrostTowers = __jarray(0)
udg_SiegeTowers = __jarray(0)
udg_PoisonTowers = __jarray(0)
udg_ChaosTowers = __jarray(0)
udg_AirTowers = __jarray(0)
udg_TempUnitType = 0
udg_DarkSummoner = {}
udg_Bouton = {}
udg_DialogueBouton = nil
gg_rct_Corner1 = nil
gg_rct_Corner2 = nil
gg_rct_Corner3 = nil
gg_rct_Corner4 = nil
gg_rct_Corner5 = nil
gg_rct_Corner6 = nil
gg_rct_Corner7 = nil
gg_rct_Corner8 = nil
gg_rct_Enters2 = nil
gg_rct_Enters3 = nil
gg_rct_Enters6 = nil
gg_rct_Enters7 = nil
gg_rct_InsideBottom = nil
gg_rct_InsideBottomLeft = nil
gg_rct_InsideBottomRight = nil
gg_rct_InsideLeft = nil
gg_rct_InsideRight = nil
gg_rct_InsideTop = nil
gg_rct_InsideTopLeft = nil
gg_rct_InsideTopRight = nil
gg_rct_OutsideBottom = nil
gg_rct_OutsideBottomLeft = nil
gg_rct_OutsideBottomRight = nil
gg_rct_OutsideLeft = nil
gg_rct_OutsideRight = nil
gg_rct_OutsideTop = nil
gg_rct_OutsideTopLeft = nil
gg_rct_OutsideTopRight = nil
gg_rct_Rect_010 = nil
gg_rct_Spawn1 = nil
gg_rct_Spawn2 = nil
gg_rct_Spawn3 = nil
gg_rct_Spawn4 = nil
gg_rct_Spawn5 = nil
gg_rct_Spawn6 = nil
gg_rct_Spawn7 = nil
gg_rct_Spawn8 = nil
gg_rct_TestArea = nil
gg_snd_PurgeTarget = nil
gg_snd_Wave_Air = nil
gg_snd_Wave_Immune = nil
gg_snd_Wave_Normal = nil
gg_snd_Wave_Hero = nil
gg_snd_Wave_Boss = nil
gg_snd_Game_Mode = nil
gg_snd_Hint = nil
gg_snd_TheHornOfCenarius = nil
gg_trg_Adding_to_Quests = nil
gg_trg_Help_System_Want_help = nil
gg_trg_Help_System_Immun = nil
gg_trg_Help_System_Air = nil
gg_trg_Help_System_Hero = nil
gg_trg_Enemy_DiesWithValue = nil
gg_trg_Enemy_DiesNoValue = nil
gg_trg_PlayerQuit = nil
gg_trg_Update_Leaderboard = nil
gg_trg_NumberInMapCheck = nil
gg_trg_Lose_Condition = nil
gg_trg_SetupLeaderBoard = nil
gg_trg_sell = nil
gg_trg_Downgrade = nil
gg_trg_Initialization = nil
gg_trg_Downgrade_Init = nil
gg_trg_Leave_Red = nil
gg_trg_Leave_Blue = nil
gg_trg_Leave_Teal = nil
gg_trg_Leave_Purple = nil
gg_trg_Leave_Yellow = nil
gg_trg_Leave_Orange = nil
gg_trg_Leave_Green = nil
gg_trg_Leave_Pink = nil
gg_trg_Red = nil
gg_trg_RedCorner = nil
gg_trg_OutsideTL = nil
gg_trg_OutsideLeft = nil
gg_trg_Blue = nil
gg_trg_BlueCorner = nil
gg_trg_BlueEnters = nil
gg_trg_InsideTL = nil
gg_trg_InsideLeft = nil
gg_trg_Teal = nil
gg_trg_TealCorner = nil
gg_trg_TealEnters = nil
gg_trg_InsideTR = nil
gg_trg_InsideTop = nil
gg_trg_Purple = nil
gg_trg_PurpleCorner = nil
gg_trg_OutsideTR = nil
gg_trg_OutsideTop = nil
gg_trg_Yellow = nil
gg_trg_YellowCorner = nil
gg_trg_OutsideBL = nil
gg_trg_OutsideBottom = nil
gg_trg_Orange = nil
gg_trg_OrangeCorner = nil
gg_trg_OrangeEnters = nil
gg_trg_InsideBL = nil
gg_trg_InsideBottom = nil
gg_trg_Green = nil
gg_trg_GreenCorner = nil
gg_trg_GreenEnters = nil
gg_trg_InsideBR = nil
gg_trg_InsideRight = nil
gg_trg_Pink = nil
gg_trg_PinkCorner = nil
gg_trg_OutsideBR = nil
gg_trg_OutsideRight = nil
gg_trg_Immune = nil
gg_trg_Air = nil
gg_trg_Next = nil
gg_trg_Help = nil
gg_trg_Commands = nil
gg_trg_GetLevelInfo = nil
gg_trg_MessageWelcome = nil
gg_trg_VoteWarning = nil
gg_trg_RegisterVoteNormal = nil
gg_trg_RegisterVoteHard = nil
gg_trg_RegisterVoteInsane = nil
gg_trg_CountVotes = nil
gg_trg_RangeCheck = nil
gg_trg_SpawnWaves = nil
gg_trg_SetupWave = nil
gg_trg_WavesWarning = nil
gg_trg_WaveTimeManager = nil
gg_trg_Victory = nil
gg_unit_u000_0010 = nil
gg_unit_u000_0011 = nil
gg_unit_u000_0012 = nil
gg_unit_u000_0035 = nil
gg_unit_u000_0014 = nil
gg_unit_u000_0037 = nil
gg_unit_u000_0016 = nil
gg_unit_u000_0017 = nil
gg_unit_u000_0018 = nil
gg_unit_u000_0019 = nil
gg_unit_u000_0020 = nil
gg_unit_u000_0038 = nil
gg_unit_u000_0036 = nil
gg_unit_u000_0023 = nil
gg_unit_u000_0024 = nil
gg_unit_u000_0025 = nil
gg_unit_u000_0026 = nil
gg_unit_u000_0027 = nil
gg_unit_u000_0034 = nil
gg_unit_u000_0029 = nil
gg_unit_u000_0030 = nil
gg_unit_u000_0033 = nil
gg_unit_u000_0032 = nil
gg_unit_u000_0040 = nil
gg_trg_InitVariables = nil
function InitGlobals()
local i = 0
udg_LVL = 0
udg_CurrentlyOnMap = 0.0
udg_LevelHero = 0
udg_ConnectedPlayers = CreateForce()
udg_EmptyPlayers = CreateForce()
udg_TempUnitGroup = CreateGroup()
i = 0
while (true) do
if ((i > 13)) then break end
udg_Kills[i] = 0
i = i + 1
end
udg_TempInt = 0
udg_OutsideClockwise = 4
udg_OutsideCounterClockwise = 1
udg_InsideClockwise = 2
udg_InsideCounterClockwise = 3
udg_UnknownDirection = 0
udg_OutsideToInside = 5
udg_InsideToOutside = 6
udg_SpawningCalc = 0
udg_GroupInside = CreateForce()
udg_GroupOutside = CreateForce()
udg_SpawningGroup = false
udg_SpawnCounter = 0
udg_SpawningRate = 0.0
udg_NextSpawnTracker = 0.0
udg_EmptySpawnCounter = 0
i = 0
while (true) do
if ((i > 8)) then break end
udg_HardVotes[i] = 0
i = i + 1
end
i = 0
while (true) do
if ((i > 8)) then break end
udg_InsaneVotes[i] = 0
i = i + 1
end
udg_HardCount = 0
udg_InsaneCount = 0
i = 0
while (true) do
if ((i > 40)) then break end
udg_NumberToSpawn[i] = 0
i = i + 1
end
udg_TempString = ""
udg_LoseValue = 900.00
udg_TempReal = 0.0
udg_PredictLevel = 0
udg_TempPlayerGroup = CreateForce()
udg_RangeCalc = 0.0
udg_RangeCount = 0.0
i = 0
while (true) do
if ((i > 1)) then break end
udg_DarkSummoner[i] = nil
i = i + 1
end
udg_DialogueBouton = DialogCreate()
end
function InitSounds()
gg_snd_PurgeTarget = CreateSound("Abilities\\Spells\\Orc\\Purge\\PurgeTarget1.wav", false, false, true, 10, 10, "DefaultEAXON")
SetSoundParamsFromLabel(gg_snd_PurgeTarget, "Purge")
SetSoundDuration(gg_snd_PurgeTarget, 2095)
SetSoundChannel(gg_snd_PurgeTarget, 0)
gg_snd_Wave_Air = CreateSound("Sound\\Music\\mp3Music\\Tension.mp3", false, false, false, 10, 10, "DefaultEAXON")
SetSoundDuration(gg_snd_Wave_Air, 19565)
SetSoundChannel(gg_snd_Wave_Air, 0)
SetSoundVolume(gg_snd_Wave_Air, 127)
SetSoundPitch(gg_snd_Wave_Air, 1.0)
gg_snd_Wave_Immune = CreateSound("Sound\\Music\\mp3Music\\NightElfVictory.mp3", false, false, false, 10, 10, "DefaultEAXON")
SetSoundDuration(gg_snd_Wave_Immune, 22021)
SetSoundChannel(gg_snd_Wave_Immune, 0)
SetSoundVolume(gg_snd_Wave_Immune, 127)
SetSoundPitch(gg_snd_Wave_Immune, 1.2)
gg_snd_Wave_Normal = CreateSound("Sound\\Music\\mp3Music\\OrcDefeat.mp3", false, false, false, 20, 10, "DefaultEAXON")
SetSoundDuration(gg_snd_Wave_Normal, 39262)
SetSoundChannel(gg_snd_Wave_Normal, 0)
SetSoundVolume(gg_snd_Wave_Normal, 100)
SetSoundPitch(gg_snd_Wave_Normal, 1.5)
gg_snd_Wave_Hero = CreateSound("Sound\\Music\\mp3Music\\Doom.mp3", false, false, false, 10, 10, "DefaultEAXON")
SetSoundDuration(gg_snd_Wave_Hero, 66115)
SetSoundChannel(gg_snd_Wave_Hero, 0)
SetSoundVolume(gg_snd_Wave_Hero, 127)
SetSoundPitch(gg_snd_Wave_Hero, 1.3)
gg_snd_Wave_Boss = CreateSound("Sound\\Music\\mp3Music\\Comradeship.mp3", false, false, false, 10, 10, "DefaultEAXON")
SetSoundDuration(gg_snd_Wave_Boss, 124865)
SetSoundChannel(gg_snd_Wave_Boss, 0)
SetSoundVolume(gg_snd_Wave_Boss, 127)
SetSoundPitch(gg_snd_Wave_Boss, 1.0)
gg_snd_Game_Mode = CreateSound("Sound\\Interface\\Rescue.wav", false, false, false, 10, 10, "DefaultEAXON")
SetSoundParamsFromLabel(gg_snd_Game_Mode, "Rescue")
SetSoundDuration(gg_snd_Game_Mode, 3796)
gg_snd_Hint = CreateSound("Sound\\Interface\\Hint.wav", false, false, false, 10, 10, "")
SetSoundParamsFromLabel(gg_snd_Hint, "Hint")
SetSoundDuration(gg_snd_Hint, 2005)
gg_snd_TheHornOfCenarius = CreateSound("Sound\\Ambient\\DoodadEffects\\TheHornOfCenarius.wav", false, false, false, 10, 10, "DefaultEAXON")
SetSoundParamsFromLabel(gg_snd_TheHornOfCenarius, "HornOfCenariusSound")
SetSoundDuration(gg_snd_TheHornOfCenarius, 12120)
end
function CreateNeutralPassive()
local p = Player(PLAYER_NEUTRAL_PASSIVE)
local u
local unitID
local t
local life
gg_unit_u000_0010 = CreateUnit(p, FourCC("u000"), -4879.8, 5372.4, 180.000)
gg_unit_u000_0011 = CreateUnit(p, FourCC("u000"), -5863.1, 5389.8, 0.000)
gg_unit_u000_0012 = CreateUnit(p, FourCC("u000"), -5354.0, 5912.3, 270.000)
gg_unit_u000_0014 = CreateUnit(p, FourCC("u000"), -325.5, 741.6, 180.000)
gg_unit_u000_0016 = CreateUnit(p, FourCC("u000"), -799.7, 1281.5, 270.000)
gg_unit_u000_0017 = CreateUnit(p, FourCC("u000"), -804.4, 285.5, 90.000)
gg_unit_u000_0018 = CreateUnit(p, FourCC("u000"), -298.9, -734.9, 180.000)
gg_unit_u000_0019 = CreateUnit(p, FourCC("u000"), -1282.2, -717.5, 0.000)
gg_unit_u000_0020 = CreateUnit(p, FourCC("u000"), -773.1, -195.0, 270.000)
gg_unit_u000_0023 = CreateUnit(p, FourCC("u000"), -5872.3, -5384.6, 0.000)
gg_unit_u000_0024 = CreateUnit(p, FourCC("u000"), -5363.2, -4862.2, 270.000)
gg_unit_u000_0025 = CreateUnit(p, FourCC("u000"), -5367.9, -5858.2, 90.000)
gg_unit_u000_0026 = CreateUnit(p, FourCC("u000"), 5848.9, -5368.2, 180.000)
gg_unit_u000_0027 = CreateUnit(p, FourCC("u000"), 4865.6, -5350.7, 0.000)
gg_unit_u000_0029 = CreateUnit(p, FourCC("u000"), 5370.0, -5824.3, 90.000)
gg_unit_u000_0030 = CreateUnit(p, FourCC("u000"), 5834.5, 5341.5, 180.000)
gg_unit_u000_0032 = CreateUnit(p, FourCC("u000"), 5360.3, 5881.4, 270.000)
gg_unit_u000_0033 = CreateUnit(p, FourCC("u000"), 5355.5, 4885.4, 90.000)
gg_unit_u000_0034 = CreateUnit(p, FourCC("u000"), 257.0, -768.9, 0.000)
gg_unit_u000_0035 = CreateUnit(p, FourCC("u000"), 766.1, -246.5, 270.000)
gg_unit_u000_0036 = CreateUnit(p, FourCC("u000"), 761.4, -1242.5, 90.000)
gg_unit_u000_0037 = CreateUnit(p, FourCC("u000"), 1259.9, 762.8, 180.000)
gg_unit_u000_0038 = CreateUnit(p, FourCC("u000"), 276.6, 780.3, 0.000)
gg_unit_u000_0040 = CreateUnit(p, FourCC("u000"), 781.0, 306.7, 90.000)
end
function CreatePlayerBuildings()
end
function CreatePlayerUnits()
end
function CreateAllUnits()
CreatePlayerBuildings()
CreateNeutralPassive()
CreatePlayerUnits()
end
function CreateRegions()
local we
gg_rct_Corner1 = Rect(-5472.0, 3744.0, -5216.0, 3936.0)
gg_rct_Corner2 = Rect(-1888.0, 672.0, -1696.0, 928.0)
gg_rct_Corner3 = Rect(640.0, 1728.0, 1024.0, 1920.0)
gg_rct_Corner4 = Rect(3712.0, 5248.0, 3936.0, 5536.0)
gg_rct_Corner5 = Rect(-3936.0, -5504.0, -3744.0, -5184.0)
gg_rct_Corner6 = Rect(-928.0, -1920.0, -640.0, -1696.0)
gg_rct_Corner7 = Rect(1696.0, -1024.0, 1888.0, -608.0)
gg_rct_Corner8 = Rect(5216.0, -3936.0, 5472.0, -3744.0)
gg_rct_Enters2 = Rect(-1984.0, 2688.0, -1568.0, 2880.0)
gg_rct_Enters3 = Rect(2720.0, 1600.0, 2912.0, 1952.0)
gg_rct_Enters6 = Rect(-2912.0, -1984.0, -2720.0, -1600.0)
gg_rct_Enters7 = Rect(1600.0, -2944.0, 1984.0, -2752.0)
gg_rct_InsideBottom = Rect(-96.0, -2912.0, 96.0, -2752.0)
gg_rct_InsideBottomLeft = Rect(-2912.0, -2944.0, -2688.0, -2752.0)
gg_rct_InsideBottomRight = Rect(2720.0, -2880.0, 2880.0, -2720.0)
gg_rct_InsideLeft = Rect(-2912.0, -64.0, -2752.0, 64.0)
gg_rct_InsideRight = Rect(2752.0, -64.0, 2912.0, 64.0)
gg_rct_InsideTop = Rect(-96.0, 2720.0, 96.0, 2912.0)
gg_rct_InsideTopLeft = Rect(-2912.0, 2784.0, -2816.0, 2912.0)
gg_rct_InsideTopRight = Rect(2720.0, 2720.0, 2880.0, 2880.0)
gg_rct_OutsideBottom = Rect(-96.0, -3904.0, 96.0, -3744.0)
gg_rct_OutsideBottomLeft = Rect(-3936.0, -3936.0, -3744.0, -3744.0)
gg_rct_OutsideBottomRight = Rect(3744.0, -3936.0, 3936.0, -3776.0)
gg_rct_OutsideLeft = Rect(-3936.0, -96.0, -3712.0, 96.0)
gg_rct_OutsideRight = Rect(3744.0, -96.0, 3936.0, 64.0)
gg_rct_OutsideTop = Rect(-64.0, 3840.0, 64.0, 3936.0)
gg_rct_OutsideTopLeft = Rect(-3936.0, 3744.0, -3744.0, 3904.0)
gg_rct_OutsideTopRight = Rect(3712.0, 3744.0, 3936.0, 3904.0)
gg_rct_Rect_010 = Rect(-6016.0, -6144.0, 5920.0, 5856.0)
gg_rct_Spawn1 = Rect(-5600.0, 5120.0, -5152.0, 5600.0)
gg_rct_Spawn2 = Rect(-1024.0, 512.0, -512.0, 992.0)
gg_rct_Spawn3 = Rect(544.0, 512.0, 992.0, 1024.0)
gg_rct_Spawn4 = Rect(5152.0, 5152.0, 5632.0, 5600.0)
gg_rct_Spawn5 = Rect(-5632.0, -5632.0, -5120.0, -5120.0)
gg_rct_Spawn6 = Rect(-1024.0, -1024.0, -544.0, -544.0)
gg_rct_Spawn7 = Rect(512.0, -1024.0, 1024.0, -512.0)
gg_rct_Spawn8 = Rect(5152.0, -5632.0, 5632.0, -5120.0)
gg_rct_TestArea = Rect(-192.0, -192.0, 192.0, 192.0)
end
function Trig_InitVariables_Actions()
udg_DarkSummoner[1] = gg_unit_u000_0011
udg_DarkSummoner[2] = gg_unit_u000_0012
udg_DarkSummoner[3] = gg_unit_u000_0010
udg_DarkSummoner[4] = gg_unit_u000_0016
udg_DarkSummoner[5] = gg_unit_u000_0014
udg_DarkSummoner[6] = gg_unit_u000_0017
udg_DarkSummoner[7] = gg_unit_u000_0038
udg_DarkSummoner[8] = gg_unit_u000_0040
udg_DarkSummoner[9] = gg_unit_u000_0037
udg_DarkSummoner[10] = gg_unit_u000_0032
udg_DarkSummoner[11] = gg_unit_u000_0030
udg_DarkSummoner[12] = gg_unit_u000_0033
udg_DarkSummoner[13] = gg_unit_u000_0024
udg_DarkSummoner[14] = gg_unit_u000_0023
udg_DarkSummoner[15] = gg_unit_u000_0025
udg_DarkSummoner[16] = gg_unit_u000_0019
udg_DarkSummoner[17] = gg_unit_u000_0020
udg_DarkSummoner[18] = gg_unit_u000_0018
udg_DarkSummoner[19] = gg_unit_u000_0035
udg_DarkSummoner[20] = gg_unit_u000_0034
udg_DarkSummoner[21] = gg_unit_u000_0036
udg_DarkSummoner[22] = gg_unit_u000_0027
udg_DarkSummoner[23] = gg_unit_u000_0026
udg_DarkSummoner[24] = gg_unit_u000_0029
end
function InitTrig_InitVariables()
gg_trg_InitVariables = CreateTrigger()
TriggerAddAction(gg_trg_InitVariables, Trig_InitVariables_Actions)
end
function InitCustomTriggers()
InitTrig_InitVariables()
end
function RunInitializationTriggers()
ConditionalTriggerExecute(gg_trg_InitVariables)
end
function InitCustomPlayerSlots()
SetPlayerStartLocation(Player(0), 0)
ForcePlayerStartLocation(Player(0), 0)
SetPlayerColor(Player(0), ConvertPlayerColor(0))
SetPlayerRacePreference(Player(0), RACE_PREF_NIGHTELF)
SetPlayerRaceSelectable(Player(0), false)
SetPlayerController(Player(0), MAP_CONTROL_USER)
SetPlayerStartLocation(Player(1), 1)
ForcePlayerStartLocation(Player(1), 1)
SetPlayerColor(Player(1), ConvertPlayerColor(1))
SetPlayerRacePreference(Player(1), RACE_PREF_NIGHTELF)
SetPlayerRaceSelectable(Player(1), false)
SetPlayerController(Player(1), MAP_CONTROL_USER)
SetPlayerStartLocation(Player(2), 2)
ForcePlayerStartLocation(Player(2), 2)
SetPlayerColor(Player(2), ConvertPlayerColor(2))
SetPlayerRacePreference(Player(2), RACE_PREF_NIGHTELF)
SetPlayerRaceSelectable(Player(2), false)
SetPlayerController(Player(2), MAP_CONTROL_USER)
SetPlayerStartLocation(Player(3), 3)
ForcePlayerStartLocation(Player(3), 3)
SetPlayerColor(Player(3), ConvertPlayerColor(3))
SetPlayerRacePreference(Player(3), RACE_PREF_NIGHTELF)
SetPlayerRaceSelectable(Player(3), false)
SetPlayerController(Player(3), MAP_CONTROL_USER)
SetPlayerStartLocation(Player(4), 4)
ForcePlayerStartLocation(Player(4), 4)
SetPlayerColor(Player(4), ConvertPlayerColor(4))
SetPlayerRacePreference(Player(4), RACE_PREF_NIGHTELF)
SetPlayerRaceSelectable(Player(4), false)
SetPlayerController(Player(4), MAP_CONTROL_USER)
SetPlayerStartLocation(Player(5), 5)
ForcePlayerStartLocation(Player(5), 5)
SetPlayerColor(Player(5), ConvertPlayerColor(5))
SetPlayerRacePreference(Player(5), RACE_PREF_NIGHTELF)
SetPlayerRaceSelectable(Player(5), false)
SetPlayerController(Player(5), MAP_CONTROL_USER)
SetPlayerStartLocation(Player(6), 6)
ForcePlayerStartLocation(Player(6), 6)
SetPlayerColor(Player(6), ConvertPlayerColor(6))
SetPlayerRacePreference(Player(6), RACE_PREF_NIGHTELF)
SetPlayerRaceSelectable(Player(6), false)
SetPlayerController(Player(6), MAP_CONTROL_USER)
SetPlayerStartLocation(Player(7), 7)
ForcePlayerStartLocation(Player(7), 7)
SetPlayerColor(Player(7), ConvertPlayerColor(7))
SetPlayerRacePreference(Player(7), RACE_PREF_NIGHTELF)
SetPlayerRaceSelectable(Player(7), false)
SetPlayerController(Player(7), MAP_CONTROL_USER)
SetPlayerStartLocation(Player(10), 8)
ForcePlayerStartLocation(Player(10), 8)
SetPlayerColor(Player(10), ConvertPlayerColor(10))
SetPlayerRacePreference(Player(10), RACE_PREF_UNDEAD)
SetPlayerRaceSelectable(Player(10), false)
SetPlayerController(Player(10), MAP_CONTROL_COMPUTER)
SetPlayerStartLocation(Player(11), 9)
ForcePlayerStartLocation(Player(11), 9)
SetPlayerColor(Player(11), ConvertPlayerColor(11))
SetPlayerRacePreference(Player(11), RACE_PREF_UNDEAD)
SetPlayerRaceSelectable(Player(11), false)
SetPlayerController(Player(11), MAP_CONTROL_COMPUTER)
end
function InitCustomTeams()
SetPlayerTeam(Player(0), 0)
SetPlayerState(Player(0), PLAYER_STATE_ALLIED_VICTORY, 1)
SetPlayerTeam(Player(1), 0)
SetPlayerState(Player(1), PLAYER_STATE_ALLIED_VICTORY, 1)
SetPlayerTeam(Player(2), 0)
SetPlayerState(Player(2), PLAYER_STATE_ALLIED_VICTORY, 1)
SetPlayerTeam(Player(3), 0)
SetPlayerState(Player(3), PLAYER_STATE_ALLIED_VICTORY, 1)
SetPlayerTeam(Player(4), 0)
SetPlayerState(Player(4), PLAYER_STATE_ALLIED_VICTORY, 1)
SetPlayerTeam(Player(5), 0)
SetPlayerState(Player(5), PLAYER_STATE_ALLIED_VICTORY, 1)
SetPlayerTeam(Player(6), 0)
SetPlayerState(Player(6), PLAYER_STATE_ALLIED_VICTORY, 1)
SetPlayerTeam(Player(7), 0)
SetPlayerState(Player(7), PLAYER_STATE_ALLIED_VICTORY, 1)
SetPlayerAllianceStateAllyBJ(Player(0), Player(1), true)
SetPlayerAllianceStateAllyBJ(Player(0), Player(2), true)
SetPlayerAllianceStateAllyBJ(Player(0), Player(3), true)
SetPlayerAllianceStateAllyBJ(Player(0), Player(4), true)
SetPlayerAllianceStateAllyBJ(Player(0), Player(5), true)
SetPlayerAllianceStateAllyBJ(Player(0), Player(6), true)
SetPlayerAllianceStateAllyBJ(Player(0), Player(7), true)
SetPlayerAllianceStateAllyBJ(Player(1), Player(0), true)
SetPlayerAllianceStateAllyBJ(Player(1), Player(2), true)
SetPlayerAllianceStateAllyBJ(Player(1), Player(3), true)
SetPlayerAllianceStateAllyBJ(Player(1), Player(4), true)
SetPlayerAllianceStateAllyBJ(Player(1), Player(5), true)
SetPlayerAllianceStateAllyBJ(Player(1), Player(6), true)
SetPlayerAllianceStateAllyBJ(Player(1), Player(7), true)
SetPlayerAllianceStateAllyBJ(Player(2), Player(0), true)
SetPlayerAllianceStateAllyBJ(Player(2), Player(1), true)
SetPlayerAllianceStateAllyBJ(Player(2), Player(3), true)
SetPlayerAllianceStateAllyBJ(Player(2), Player(4), true)
SetPlayerAllianceStateAllyBJ(Player(2), Player(5), true)
SetPlayerAllianceStateAllyBJ(Player(2), Player(6), true)
SetPlayerAllianceStateAllyBJ(Player(2), Player(7), true)
SetPlayerAllianceStateAllyBJ(Player(3), Player(0), true)
SetPlayerAllianceStateAllyBJ(Player(3), Player(1), true)
SetPlayerAllianceStateAllyBJ(Player(3), Player(2), true)
SetPlayerAllianceStateAllyBJ(Player(3), Player(4), true)
SetPlayerAllianceStateAllyBJ(Player(3), Player(5), true)
SetPlayerAllianceStateAllyBJ(Player(3), Player(6), true)
SetPlayerAllianceStateAllyBJ(Player(3), Player(7), true)
SetPlayerAllianceStateAllyBJ(Player(4), Player(0), true)
SetPlayerAllianceStateAllyBJ(Player(4), Player(1), true)
SetPlayerAllianceStateAllyBJ(Player(4), Player(2), true)
SetPlayerAllianceStateAllyBJ(Player(4), Player(3), true)
SetPlayerAllianceStateAllyBJ(Player(4), Player(5), true)
SetPlayerAllianceStateAllyBJ(Player(4), Player(6), true)
SetPlayerAllianceStateAllyBJ(Player(4), Player(7), true)
SetPlayerAllianceStateAllyBJ(Player(5), Player(0), true)
SetPlayerAllianceStateAllyBJ(Player(5), Player(1), true)
SetPlayerAllianceStateAllyBJ(Player(5), Player(2), true)
SetPlayerAllianceStateAllyBJ(Player(5), Player(3), true)
SetPlayerAllianceStateAllyBJ(Player(5), Player(4), true)
SetPlayerAllianceStateAllyBJ(Player(5), Player(6), true)
SetPlayerAllianceStateAllyBJ(Player(5), Player(7), true)
SetPlayerAllianceStateAllyBJ(Player(6), Player(0), true)
SetPlayerAllianceStateAllyBJ(Player(6), Player(1), true)
SetPlayerAllianceStateAllyBJ(Player(6), Player(2), true)
SetPlayerAllianceStateAllyBJ(Player(6), Player(3), true)
SetPlayerAllianceStateAllyBJ(Player(6), Player(4), true)
SetPlayerAllianceStateAllyBJ(Player(6), Player(5), true)
SetPlayerAllianceStateAllyBJ(Player(6), Player(7), true)
SetPlayerAllianceStateAllyBJ(Player(7), Player(0), true)
SetPlayerAllianceStateAllyBJ(Player(7), Player(1), true)
SetPlayerAllianceStateAllyBJ(Player(7), Player(2), true)
SetPlayerAllianceStateAllyBJ(Player(7), Player(3), true)
SetPlayerAllianceStateAllyBJ(Player(7), Player(4), true)
SetPlayerAllianceStateAllyBJ(Player(7), Player(5), true)
SetPlayerAllianceStateAllyBJ(Player(7), Player(6), true)
SetPlayerAllianceStateVisionBJ(Player(0), Player(1), true)
SetPlayerAllianceStateVisionBJ(Player(0), Player(2), true)
SetPlayerAllianceStateVisionBJ(Player(0), Player(3), true)
SetPlayerAllianceStateVisionBJ(Player(0), Player(4), true)
SetPlayerAllianceStateVisionBJ(Player(0), Player(5), true)
SetPlayerAllianceStateVisionBJ(Player(0), Player(6), true)
SetPlayerAllianceStateVisionBJ(Player(0), Player(7), true)
SetPlayerAllianceStateVisionBJ(Player(1), Player(0), true)
SetPlayerAllianceStateVisionBJ(Player(1), Player(2), true)
SetPlayerAllianceStateVisionBJ(Player(1), Player(3), true)
SetPlayerAllianceStateVisionBJ(Player(1), Player(4), true)
SetPlayerAllianceStateVisionBJ(Player(1), Player(5), true)
SetPlayerAllianceStateVisionBJ(Player(1), Player(6), true)
SetPlayerAllianceStateVisionBJ(Player(1), Player(7), true)
SetPlayerAllianceStateVisionBJ(Player(2), Player(0), true)
SetPlayerAllianceStateVisionBJ(Player(2), Player(1), true)
SetPlayerAllianceStateVisionBJ(Player(2), Player(3), true)
SetPlayerAllianceStateVisionBJ(Player(2), Player(4), true)
SetPlayerAllianceStateVisionBJ(Player(2), Player(5), true)
SetPlayerAllianceStateVisionBJ(Player(2), Player(6), true)
SetPlayerAllianceStateVisionBJ(Player(2), Player(7), true)
SetPlayerAllianceStateVisionBJ(Player(3), Player(0), true)
SetPlayerAllianceStateVisionBJ(Player(3), Player(1), true)
SetPlayerAllianceStateVisionBJ(Player(3), Player(2), true)
SetPlayerAllianceStateVisionBJ(Player(3), Player(4), true)
SetPlayerAllianceStateVisionBJ(Player(3), Player(5), true)
SetPlayerAllianceStateVisionBJ(Player(3), Player(6), true)
SetPlayerAllianceStateVisionBJ(Player(3), Player(7), true)
SetPlayerAllianceStateVisionBJ(Player(4), Player(0), true)
SetPlayerAllianceStateVisionBJ(Player(4), Player(1), true)
SetPlayerAllianceStateVisionBJ(Player(4), Player(2), true)
SetPlayerAllianceStateVisionBJ(Player(4), Player(3), true)
SetPlayerAllianceStateVisionBJ(Player(4), Player(5), true)
SetPlayerAllianceStateVisionBJ(Player(4), Player(6), true)
SetPlayerAllianceStateVisionBJ(Player(4), Player(7), true)
SetPlayerAllianceStateVisionBJ(Player(5), Player(0), true)
SetPlayerAllianceStateVisionBJ(Player(5), Player(1), true)
SetPlayerAllianceStateVisionBJ(Player(5), Player(2), true)
SetPlayerAllianceStateVisionBJ(Player(5), Player(3), true)
SetPlayerAllianceStateVisionBJ(Player(5), Player(4), true)
SetPlayerAllianceStateVisionBJ(Player(5), Player(6), true)
SetPlayerAllianceStateVisionBJ(Player(5), Player(7), true)
SetPlayerAllianceStateVisionBJ(Player(6), Player(0), true)
SetPlayerAllianceStateVisionBJ(Player(6), Player(1), true)
SetPlayerAllianceStateVisionBJ(Player(6), Player(2), true)
SetPlayerAllianceStateVisionBJ(Player(6), Player(3), true)
SetPlayerAllianceStateVisionBJ(Player(6), Player(4), true)
SetPlayerAllianceStateVisionBJ(Player(6), Player(5), true)
SetPlayerAllianceStateVisionBJ(Player(6), Player(7), true)
SetPlayerAllianceStateVisionBJ(Player(7), Player(0), true)
SetPlayerAllianceStateVisionBJ(Player(7), Player(1), true)
SetPlayerAllianceStateVisionBJ(Player(7), Player(2), true)
SetPlayerAllianceStateVisionBJ(Player(7), Player(3), true)
SetPlayerAllianceStateVisionBJ(Player(7), Player(4), true)
SetPlayerAllianceStateVisionBJ(Player(7), Player(5), true)
SetPlayerAllianceStateVisionBJ(Player(7), Player(6), true)
SetPlayerTeam(Player(10), 1)
SetPlayerState(Player(10), PLAYER_STATE_ALLIED_VICTORY, 1)
SetPlayerTeam(Player(11), 1)
SetPlayerState(Player(11), PLAYER_STATE_ALLIED_VICTORY, 1)
SetPlayerAllianceStateAllyBJ(Player(10), Player(11), true)
SetPlayerAllianceStateAllyBJ(Player(11), Player(10), true)
SetPlayerAllianceStateVisionBJ(Player(10), Player(11), true)
SetPlayerAllianceStateVisionBJ(Player(11), Player(10), true)
end
function InitAllyPriorities()
SetStartLocPrioCount(0, 1)
SetStartLocPrio(0, 0, 1, MAP_LOC_PRIO_HIGH)
SetStartLocPrioCount(1, 1)
SetStartLocPrio(1, 0, 0, MAP_LOC_PRIO_HIGH)
SetStartLocPrioCount(2, 1)
SetStartLocPrio(2, 0, 3, MAP_LOC_PRIO_HIGH)
SetStartLocPrioCount(3, 1)
SetStartLocPrio(3, 0, 2, MAP_LOC_PRIO_HIGH)
SetStartLocPrioCount(4, 1)
SetStartLocPrio(4, 0, 5, MAP_LOC_PRIO_HIGH)
SetStartLocPrioCount(5, 1)
SetStartLocPrio(5, 0, 4, MAP_LOC_PRIO_HIGH)
SetStartLocPrioCount(6, 1)
SetStartLocPrio(6, 0, 7, MAP_LOC_PRIO_HIGH)
SetStartLocPrioCount(7, 1)
SetStartLocPrio(7, 0, 6, MAP_LOC_PRIO_HIGH)
end
function main()
SetCameraBounds(-6016.0 + GetCameraMargin(CAMERA_MARGIN_LEFT), -6016.0 + GetCameraMargin(CAMERA_MARGIN_BOTTOM), 6016.0 - GetCameraMargin(CAMERA_MARGIN_RIGHT), 6016.0 - GetCameraMargin(CAMERA_MARGIN_TOP), -6016.0 + GetCameraMargin(CAMERA_MARGIN_LEFT), 6016.0 - GetCameraMargin(CAMERA_MARGIN_TOP), 6016.0 - GetCameraMargin(CAMERA_MARGIN_RIGHT), -6016.0 + GetCameraMargin(CAMERA_MARGIN_BOTTOM))
SetDayNightModels("Environment\\DNC\\DNCLordaeron\\DNCLordaeronTerrain\\DNCLordaeronTerrain.mdl", "Environment\\DNC\\DNCLordaeron\\DNCLordaeronUnit\\DNCLordaeronUnit.mdl")
NewSoundEnvironment("Default")
SetAmbientDaySound("VillageDay")
SetAmbientNightSound("VillageNight")
SetMapMusic("Music", true, 0)
InitSounds()
CreateRegions()
CreateAllUnits()
InitBlizzard()
InitGlobals()
InitCustomTriggers()
RunInitializationTriggers()
end
function config()
SetMapName("TRIGSTR_001")
SetMapDescription("TRIGSTR_003")
SetPlayers(10)
SetTeams(10)
SetGamePlacement(MAP_PLACEMENT_TEAMS_TOGETHER)
DefineStartLocation(0, -3840.0, 3776.0)
DefineStartLocation(1, -1792.0, 2752.0)
DefineStartLocation(2, 2816.0, 1728.0)
DefineStartLocation(3, 3840.0, 3776.0)
DefineStartLocation(4, -3840.0, -3840.0)
DefineStartLocation(5, -2752.0, -1792.0)
DefineStartLocation(6, 1792.0, -2816.0)
DefineStartLocation(7, 3840.0, -3776.0)
DefineStartLocation(8, 0.0, -448.0)
DefineStartLocation(9, 0.0, 0.0)
InitCustomPlayerSlots()
InitCustomTeams()
InitAllyPriorities()
end
|
-- converts an item entirely to another
function build(directory, config, parameters, level, seed)
if not config.convertsTo then
sb.logWarn("Item \"" .. (config.itemName or config.objectName) .. "\" has no conversion specified")
return config, parameters
end
local cfg = { }
for k, v in pairs(config) do cfg[k] = v end
cfg.convertsTo = nil cfg.builder = nil
cfg.itemName = config.convertsTo
cfg.objectName = config.convertsTo
return cfg, parameters
end
|
Menu = {
Name = "MatchEnd",
Script = {
_class = "MatchEndScript"
},
Items = {
{
Name = "Restart",
Text = "Restart",
},
{
Name = "SelectArena",
Text = "Select Arena",
},
{
Name = "SelectTeam",
Text = "Select Team",
},
{
Name = "MainMenu",
Text = "Main Menu",
},
},
Sounds = "@Interface/MenuSounds.lua::MenuSoundsDefault"
}
SelectedStyle = {
}
|
#!/usr/bin/env lua
local unix = require"unix"
local tmap = {
b = unix.S_ISBLK,
c = unix.S_ISCHR,
d = unix.S_ISDIR,
l = unix.S_ISLNK,
s = unix.S_ISSOCK,
p = unix.S_ISFIFO,
f = unix.S_ISREG,
}
local function tname(mode)
for name, f in pairs(tmap) do
if f(mode) then
return name
end
end
return "-"
end -- tname
local tmp = unix.opendir(io.open(... or ".", "r"))
local dir = unix.opendir(tmp) --> can open from existing handle
tmp:close()
for name, type in dir:files("name", "type") do
print(tname(type), name)
end
dir:close()
|
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file bit.lua
--
-- define module: bit
local bit = bit or {}
-- bit/and operation
function bit.band(a, b)
return a & b
end
-- bit/or operation
function bit.bor(a, b)
return a | b
end
-- bit/xor operation
function bit.bxor(a, b)
return a ~ b
end
-- bit/not operation
function bit.bnot(a)
return ~a
end
-- bit/lshift operation
function bit.lshift(a, b)
return a << b
end
-- bit/rshift operation
function bit.rshift(a, b)
return a >> b
end
-- tobit operation
function bit.tobit(x)
return x & 0xffffffff
end
-- tohex operation
function bit.tohex(x, n)
n = n or 8
local up
if n <= 0 then
if n == 0 then return '' end
up = true
n = - n
end
x = x & (16 ^ n - 1)
return ('%0'..n..(up and 'X' or 'x')):format(x)
end
-- return module: bit
return bit
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:28' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
--
--[[ Market List Fragment ]]--
--
local MARKET_LIST_ENTRY_MARKET_PRODUCT = 1
local MARKET_LIST_ENTRY_HEADER = 2
ZO_MarketListFragment_Keyboard = ZO_SimpleSceneFragment:Subclass()
function ZO_MarketListFragment_Keyboard:New(...)
local fragment = ZO_SimpleSceneFragment.New(self, ...)
fragment:Initialize(...)
return fragment
end
function ZO_MarketListFragment_Keyboard:Initialize(control, owner)
self.control = control
self.owner = owner
self.list = control:GetNamedChild("List")
self.listHeader = control:GetNamedChild("ListHeader")
self.contentHeader = control:GetNamedChild("ContentHeader")
-- initialize the scroll list
ZO_ScrollList_Initialize(self.list)
local function SetupEntry(...)
self:SetupEntry(...)
end
local function OnEntryReset(...)
self:OnEntryReset(...)
end
local function SetupHeaderEntry(...)
self:SetupHeaderEntry(...)
end
local function OnHeaderEntryReset(...)
self:OnHeaderEntryReset(...)
end
local NO_ON_HIDDEN_CALLBACK = nil
local NO_SELECT_SOUND = nil
ZO_ScrollList_AddDataType(self.list, MARKET_LIST_ENTRY_MARKET_PRODUCT, "ZO_MarketListEntry", ZO_MARKET_LIST_ENTRY_HEIGHT, SetupEntry, NO_ON_HIDDEN_CALLBACK, NO_SELECT_SOUND, OnEntryReset)
ZO_ScrollList_AddDataType(self.list, MARKET_LIST_ENTRY_HEADER, "ZO_MarketListHeader", ZO_MARKET_LIST_ENTRY_HEIGHT, SetupHeaderEntry, NO_ON_HIDDEN_CALLBACK, NO_SELECT_SOUND, OnHeaderEntryReset)
ZO_ScrollList_AddResizeOnScreenResize(self.list)
self.scrollData = ZO_ScrollList_GetDataList(self.list)
-- create closures to use for the mouse functions of all row entries
self.onRowMouseEnter = function(...) self:OnMouseEnter(...) end
self.onRowMouseExit = function(...) self:OnMouseExit(...) end
self.onRowMouseUp = function(...) self:OnMouseUp(...) end
end
function ZO_MarketListFragment_Keyboard:SetupEntry(rowControl, data)
rowControl.data = data
rowControl.nameControl:SetText(zo_strformat(SI_MARKET_PRODUCT_NAME_FORMATTER, data.name))
rowControl.iconControl:SetTexture(data.icon)
if data.stackCount > 1 then
rowControl.stackCount:SetText(data.stackCount)
rowControl.stackCount:SetHidden(false)
else
rowControl.stackCount:SetHidden(true)
end
local r, g, b = GetInterfaceColor(INTERFACE_COLOR_TYPE_ITEM_QUALITY_COLORS, data.displayQuality)
rowControl.nameControl:SetColor(r, g, b, 1)
rowControl:SetHandler("OnMouseEnter", self.onRowMouseEnter)
rowControl:SetHandler("OnMouseExit", self.onRowMouseExit)
rowControl:SetHandler("OnMouseUp", self.onRowMouseUp)
end
function ZO_MarketListFragment_Keyboard:OnEntryReset(rowControl, data)
local highlight = rowControl.highlight
if highlight.animation then
highlight.animation:PlayFromEnd(highlight.animation:GetDuration())
end
local icon = rowControl.iconControl
if icon.animation then
icon.animation:PlayInstantlyToStart()
end
rowControl.data = nil
ZO_ObjectPool_DefaultResetControl(rowControl)
end
function ZO_MarketListFragment_Keyboard:SetupHeaderEntry(rowControl, data)
rowControl.data = data
local headerString = data.headerName or ""
if data.headerColor then
headerString = data.headerColor:Colorize(headerString)
end
rowControl.nameControl:SetText(zo_strformat(SI_MARKET_LIST_ENTRY_HEADER_FORMATTER, headerString))
end
function ZO_MarketListFragment_Keyboard:OnHeaderEntryReset(rowControl, data)
rowControl.data = nil
ZO_ObjectPool_DefaultResetControl(rowControl)
end
function ZO_MarketListFragment_Keyboard:SetupListHeader(headerString)
if headerString == nil or headerString == "" then
self.listHeader:SetHidden(true)
-- we want to position the list up to where the header starts
self.list:ClearAnchors()
self.list:SetAnchor(TOPLEFT, self.listHeader, TOPLEFT, 0, 0)
else
self.listHeader:SetHidden(false)
self.list:ClearAnchors()
self.list:SetAnchor(TOPLEFT, self.listHeader, BOTTOMLEFT, 0, 15)
self.listHeader:SetText(headerString)
end
end
function ZO_MarketListFragment_Keyboard:ShowCrownCrateContents(marketProductData)
self.contentHeader:SetText(zo_strformat(SI_MARKET_PRODUCT_NAME_FORMATTER, marketProductData:GetDisplayName()))
self:SetupListHeader(GetString(SI_MARKET_CRATE_LIST_HEADER))
local marketProducts = ZO_Market_Shared.GetCrownCrateContentsProductInfo(marketProductData:GetId())
table.sort(marketProducts, function(...)
return ZO_Market_Shared.CompareCrateMarketProducts(...)
end)
self:ShowMarketProducts(marketProducts)
end
function ZO_MarketListFragment_Keyboard:ShowMarketProductBundleContents(marketProductData)
self.contentHeader:SetText(zo_strformat(SI_MARKET_PRODUCT_NAME_FORMATTER, marketProductData:GetDisplayName()))
self:SetupListHeader(nil)
local marketProducts = ZO_Market_Shared.GetMarketProductBundleChildProductInfo(marketProductData:GetId())
table.sort(marketProducts, function(...)
return ZO_Market_Shared.CompareBundleMarketProducts(...)
end)
self:ShowMarketProducts(marketProducts)
end
-- marketProducts is a table of Market Product info
function ZO_MarketListFragment_Keyboard:ShowMarketProducts(marketProducts)
ZO_ScrollList_Clear(self.list)
ZO_ScrollList_ResetToTop(self.list)
local lastHeaderName = nil
for index, productInfo in ipairs(marketProducts) do
-- check if we should add a header
local productHeader = productInfo.headerName
if productHeader and lastHeaderName ~= productHeader then
local headerData =
{
headerName = productHeader,
headerColor = productInfo.headerColor,
}
table.insert(self.scrollData, ZO_ScrollList_CreateDataEntry(MARKET_LIST_ENTRY_HEADER, headerData))
lastHeaderName = productHeader
end
local productId = productInfo.productId
local displayQuality = productInfo.displayQuality or ITEM_DISPLAY_QUALITY_NORMAL
local rowData =
{
productId = productId,
name = GetMarketProductDisplayName(productId),
icon = GetMarketProductIcon(productId),
stackCount = productInfo.stackCount,
displayQuality = displayQuality,
}
table.insert(self.scrollData, ZO_ScrollList_CreateDataEntry(MARKET_LIST_ENTRY_MARKET_PRODUCT, rowData))
end
ZO_ScrollList_Commit(self.list)
end
function ZO_MarketListFragment_Keyboard:CanPreview()
if self.selectedRow ~= nil then
local productId = self.selectedRow.data.productId
return CanPreviewMarketProduct(productId)
end
return false
end
function ZO_MarketListFragment_Keyboard:IsActivelyPreviewing()
if self.selectedRow ~= nil then
local productId = self.selectedRow.data.productId
return IsPreviewingMarketProduct(productId)
end
return false
end
function ZO_MarketListFragment_Keyboard:GetPreviewState()
local isPreviewing = IsCurrentlyPreviewing()
local canPreview = false
local isActivePreview = false
if self.selectedRow ~= nil then
canPreview = IsCharacterPreviewingAvailable() and self:CanPreview()
if isPreviewing and self:IsActivelyPreviewing() then
isActivePreview = true
end
end
return isPreviewing, canPreview, isActivePreview
end
function ZO_MarketListFragment_Keyboard:IsReadyToPreview()
local _, canPreview, isActivePreview = self:GetPreviewState()
return canPreview and not isActivePreview
end
function ZO_MarketListFragment_Keyboard:GetSelectedProductId()
if self.selectedRow ~= nil then
return self.selectedRow.data.productId
end
return 0
end
local function SetListHighlightHidden(control, hidden)
local highlight = control.highlight
if not highlight.animation then
highlight.animation = ANIMATION_MANAGER:CreateTimelineFromVirtual("ShowOnMouseOverLabelAnimation", highlight)
end
if hidden then
highlight.animation:PlayBackward()
else
highlight.animation:PlayForward()
end
end
function ZO_MarketListFragment_Keyboard:OnMouseEnter(control)
SetListHighlightHidden(control, false)
local icon = control.iconControl
if not icon.animation then
icon.animation = ANIMATION_MANAGER:CreateTimelineFromVirtual("IconSlotMouseOverAnimation", icon)
end
icon.animation:PlayForward()
local offsetX = -15
local offsetY = 0
InitializeTooltip(ItemTooltip, control, RIGHT, offsetX, offsetY, LEFT)
ItemTooltip:SetMarketProduct(control.data.productId)
self.selectedRow = control
self.owner:RefreshActions()
end
function ZO_MarketListFragment_Keyboard:OnMouseExit(control)
SetListHighlightHidden(control, true)
local icon = control.iconControl
if icon.animation then
icon.animation:PlayBackward()
end
ClearTooltip(ItemTooltip)
self.selectedRow = nil
self.owner:RefreshActions()
end
function ZO_MarketListFragment_Keyboard:OnMouseUp(control, button)
if button == MOUSE_BUTTON_INDEX_LEFT and self:IsReadyToPreview() then
self.owner:PreviewMarketProduct(self:GetSelectedProductId())
end
end
|
-- RoactMaterial global configuration.
-- Changing these settings affects the functioning of the entire library.
local Configuration = {
-- The Roact library.
Roact = require(script.Parent.Parent.Roact);
-- The RoactAnimate library.
RoactAnimate = require(script.Parent.Parent.RoactAnimate);
-- Various warnings in the components.
Warnings = {};
}
return Configuration
|
--[[
Author: Noya, physics by BMD
Date: 02.02.2015.
Spawns spirits for exorcism and applies the modifier that takes care of its logic
]]
function ExorcismStart( event )
local caster = event.caster
local ability = event.ability
local playerID = caster:GetPlayerID()
local radius = ability:GetLevelSpecialValueFor( "radius", ability:GetLevel() - 1 )
local duration = ability:GetLevelSpecialValueFor( "duration", ability:GetLevel() - 1 )
local spirits = ability:GetLevelSpecialValueFor( "spirits", ability:GetLevel() - 1 )
local delay_between_spirits = ability:GetLevelSpecialValueFor( "delay_between_spirits", ability:GetLevel() - 1 )
local unit_name = "npc_dummy_blank"
-- Witchcraft level
local witchcraft_ability = caster:FindAbilityByName("death_prophet_witchcraft_datadriven")
if not witchcraft_ability then
caster:FindAbilityByName("death_prophet_witchcraft")
end
-- If witchcraft ability found, get the number of extra spirits and increase
if witchcraft_ability then
local extra_spirits = witchcraft_ability:GetLevelSpecialValueFor( "exorcism_1_extra_spirits", witchcraft_ability:GetLevel() - 1 )
if extra_spirits then
spirits = spirits + extra_spirits
end
end
-- Initialize the table to keep track of all spirits
caster.spirits = {}
print("Spawning "..spirits.." spirits")
for i=1,spirits do
Timers:CreateTimer(i * delay_between_spirits, function()
local unit = CreateUnitByName(unit_name, caster:GetAbsOrigin(), true, caster, caster, caster:GetTeamNumber())
-- The modifier takes care of the physics and logic
ability:ApplyDataDrivenModifier(caster, unit, "modifier_exorcism_spirit", {})
-- Add the spawned unit to the table
table.insert(caster.spirits, unit)
-- Initialize the number of hits, to define the heal done after the ability ends
unit.numberOfHits = 0
-- Double check to kill the units, remove this later
Timers:CreateTimer(duration+10, function() if unit and IsValidEntity(unit) then unit:RemoveSelf() end end)
end)
end
end
-- Movement logic for each spirit
-- Units have 4 states:
-- acquiring: transition after completing one target-return cycle.
-- target_acquired: tracking an enemy or point to collide
-- returning: After colliding with an enemy, move back to the casters location
-- end: moving back to the caster to be destroyed and heal
function ExorcismPhysics( event )
local caster = event.caster
local unit = event.target
local ability = event.ability
local radius = ability:GetLevelSpecialValueFor( "radius", ability:GetLevel() - 1 )
local duration = ability:GetLevelSpecialValueFor( "duration", ability:GetLevel() - 1 )
local spirit_speed = ability:GetLevelSpecialValueFor( "spirit_speed", ability:GetLevel() - 1 )
local min_damage = ability:GetLevelSpecialValueFor( "min_damage", ability:GetLevel() - 1 )
local max_damage = ability:GetLevelSpecialValueFor( "max_damage", ability:GetLevel() - 1 )
local max_damage = ability:GetLevelSpecialValueFor( "max_damage", ability:GetLevel() - 1 )
local average_damage = ability:GetLevelSpecialValueFor( "average_damage", ability:GetLevel() - 1 )
local give_up_distance = ability:GetLevelSpecialValueFor( "give_up_distance", ability:GetLevel() - 1 )
local max_distance = ability:GetLevelSpecialValueFor( "max_distance", ability:GetLevel() - 1 )
local heal_percent = ability:GetLevelSpecialValueFor( "heal_percent", ability:GetLevel() - 1 ) * 0.01
local min_time_between_attacks = ability:GetLevelSpecialValueFor( "min_time_between_attacks", ability:GetLevel() - 1 )
local abilityDamageType = ability:GetAbilityDamageType()
local abilityTargetType = ability:GetAbilityTargetType()
local particleDamage = "particles/units/heroes/hero_death_prophet/death_prophet_exorcism_attack.vpcf"
local particleDamageBuilding = "particles/units/heroes/hero_death_prophet/death_prophet_exorcism_attack_building.vpcf"
--local particleNameHeal = "particles/units/heroes/hero_nyx_assassin/nyx_assassin_vendetta_start_sparks_b.vpcf"
-- Make the spirit a physics unit
Physics:Unit(unit)
-- General properties
unit:PreventDI(true)
unit:SetAutoUnstuck(false)
unit:SetNavCollisionType(PHYSICS_NAV_NOTHING)
unit:FollowNavMesh(false)
unit:SetPhysicsVelocityMax(spirit_speed)
unit:SetPhysicsVelocity(spirit_speed * RandomVector(1))
unit:SetPhysicsFriction(0)
unit:Hibernate(false)
unit:SetGroundBehavior(PHYSICS_GROUND_LOCK)
-- Initial default state
unit.state = "acquiring"
-- This is to skip frames
local frameCount = 0
-- Store the damage done
unit.damage_done = 0
-- Store the interval between attacks, starting at min_time_between_attacks
unit.last_attack_time = GameRules:GetGameTime() - min_time_between_attacks
-- Color Debugging for points and paths. Turn it false later!
local Debug = false
local pathColor = Vector(255,255,255) -- White to draw path
local targetColor = Vector(255,0,0) -- Red for enemy targets
local idleColor = Vector(0,255,0) -- Green for moving to idling points
local returnColor = Vector(0,0,255) -- Blue for the return
local endColor = Vector(0,0,0) -- Back when returning to the caster to end
local draw_duration = 3
-- Find one target point at random which will be used for the first acquisition.
local point = caster:GetAbsOrigin() + RandomVector(RandomInt(radius/2, radius))
-- This is set to repeat on each frame
unit:OnPhysicsFrame(function(unit)
-- Move the unit orientation to adjust the particle
unit:SetForwardVector( ( unit:GetPhysicsVelocity() ):Normalized() )
-- Current positions
local source = caster:GetAbsOrigin()
local current_position = unit:GetAbsOrigin()
-- Print the path on Debug mode
if Debug then DebugDrawCircle(current_position, pathColor, 0, 2, true, draw_duration) end
local enemies = nil
-- Use this if skipping frames is needed (--if frameCount == 0 then..)
frameCount = (frameCount + 1) % 3
-- Movement and Collision detection are state independent
-- MOVEMENT
-- Get the direction
local diff = point - unit:GetAbsOrigin()
diff.z = 0
local direction = diff:Normalized()
-- Calculate the angle difference
local angle_difference = RotationDelta(VectorToAngles(unit:GetPhysicsVelocity():Normalized()), VectorToAngles(direction)).y
-- Set the new velocity
if math.abs(angle_difference) < 5 then
-- CLAMP
local newVel = unit:GetPhysicsVelocity():Length() * direction
unit:SetPhysicsVelocity(newVel)
elseif angle_difference > 0 then
local newVel = RotatePosition(Vector(0,0,0), QAngle(0,10,0), unit:GetPhysicsVelocity())
unit:SetPhysicsVelocity(newVel)
else
local newVel = RotatePosition(Vector(0,0,0), QAngle(0,-10,0), unit:GetPhysicsVelocity())
unit:SetPhysicsVelocity(newVel)
end
-- COLLISION CHECK
local distance = (point - current_position):Length()
local collision = distance < 50
-- MAX DISTANCE CHECK
local distance_to_caster = (source - current_position):Length()
if distance > max_distance then
unit:SetAbsOrigin(source)
unit.state = "acquiring"
end
-- STATE DEPENDENT LOGIC
-- Damage, Healing and Targeting are state dependent.
-- Update the point in all frames
-- Acquiring...
-- Acquiring -> Target Acquired (enemy or idle point)
-- Target Acquired... if collision -> Acquiring or Return
-- Return... if collision -> Acquiring
-- Acquiring finds new targets and changes state to target_acquired with a current_target if it finds enemies or nil and a random point if there are no enemies
if unit.state == "acquiring" then
-- This is to prevent attacking the same target very fast
local time_between_last_attack = GameRules:GetGameTime() - unit.last_attack_time
--print("Time Between Last Attack: "..time_between_last_attack)
-- If enough time has passed since the last attack, attempt to acquire an enemy
if time_between_last_attack >= min_time_between_attacks then
-- If the unit doesn't have a target locked, find enemies near the caster
enemies = FindUnitsInRadius(caster:GetTeamNumber(), source, nil, radius, DOTA_UNIT_TARGET_TEAM_ENEMY,
abilityTargetType, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)
-- Check the possible enemies
-- Focus the last attacked target if there's any
local last_targeted = caster.last_targeted
local target_enemy = nil
for _,enemy in pairs(enemies) do
-- If the caster has a last_targeted and this is in range of the ghost acquisition, set to attack it
if last_targeted and enemy == last_targeted then
target_enemy = enemy
end
end
-- Else if we don't have a target_enemy from the last_targeted, get one at random
if not target_enemy then
target_enemy = enemies[RandomInt(1, #enemies)]
end
-- Keep track of it, set the state to target_acquired
if target_enemy then
unit.state = "target_acquired"
unit.current_target = target_enemy
point = unit.current_target:GetAbsOrigin()
print("Acquiring -> Enemy Target acquired: "..unit.current_target:GetUnitName())
-- If no enemies, set the unit to collide with a random idle point.
else
unit.state = "target_acquired"
unit.current_target = nil
unit.idling = true
point = source + RandomVector(RandomInt(radius/2, radius))
--print("Acquiring -> Random Point Target acquired")
if Debug then DebugDrawCircle(point, idleColor, 100, 25, true, draw_duration) end
end
-- not enough time since the last attack, get a random point
else
unit.state = "target_acquired"
unit.current_target = nil
unit.idling = true
point = source + RandomVector(RandomInt(radius/2, radius))
print("Waiting for attack time. Acquiring -> Random Point Target acquired")
if Debug then DebugDrawCircle(point, idleColor, 100, 25, true, draw_duration) end
end
-- If the state was to follow a target enemy, it means the unit can perform an attack.
elseif unit.state == "target_acquired" then
-- Update the point of the target's current position
if unit.current_target then
point = unit.current_target:GetAbsOrigin()
if Debug then DebugDrawCircle(point, targetColor, 100, 25, true, draw_duration) end
end
-- Give up on the target if the distance goes over the give_up_distance
if distance_to_caster > give_up_distance then
unit.state = "acquiring"
--print("Gave up on the target, acquiring a new target.")
end
-- Do physical damage here, and increase hit counter.
if collision then
-- If the target was an enemy and not a point, the unit collided with it
if unit.current_target ~= nil then
-- Damage, units will still try to collide with attack immune targets but the damage wont be applied
if not unit.current_target:IsAttackImmune() then
local damage_table = {}
local spirit_damage = RandomInt(min_damage,max_damage)
damage_table.victim = unit.current_target
damage_table.attacker = caster
damage_table.damage_type = abilityDamageType
damage_table.damage = spirit_damage
ApplyDamage(damage_table)
-- Calculate how much physical damage was dealt
local targetArmor = unit.current_target:GetPhysicalArmorValue()
local damageReduction = ((0.06 * targetArmor) / (1 + 0.06 * targetArmor))
local damagePostReduction = spirit_damage * (1 - damageReduction)
unit.damage_done = unit.damage_done + damagePostReduction
-- Damage particle, different for buildings
if unit.current_target.InvulCount == 0 then
local particle = ParticleManager:CreateParticle(particleDamageBuilding, PATTACH_ABSORIGIN, unit.current_target)
ParticleManager:SetParticleControl(particle, 0, unit.current_target:GetAbsOrigin())
ParticleManager:SetParticleControlEnt(particle, 1, unit.current_target, PATTACH_POINT_FOLLOW, "attach_hitloc", unit.current_target:GetAbsOrigin(), true)
elseif unit.damage_done > 0 then
local particle = ParticleManager:CreateParticle(particleDamage, PATTACH_ABSORIGIN, unit.current_target)
ParticleManager:SetParticleControl(particle, 0, unit.current_target:GetAbsOrigin())
ParticleManager:SetParticleControlEnt(particle, 1, unit.current_target, PATTACH_POINT_FOLLOW, "attach_hitloc", unit.current_target:GetAbsOrigin(), true)
end
-- Increase the numberOfHits for this unit
unit.numberOfHits = unit.numberOfHits + 1
-- Fire Sound on the target unit
unit.current_target:EmitSound("Hero_DeathProphet.Exorcism.Damage")
-- Set to return
unit.state = "returning"
point = source
--print("Returning to caster after dealing ",unit.damage_done)
-- Update the attack time of the unit.
unit.last_attack_time = GameRules:GetGameTime()
--unit.enemy_collision = true
end
-- In other case, its a point, reacquire target or return to the caster (50/50)
else
if RollPercentage(50) then
unit.state = "acquiring"
--print("Attempting to acquire a new target")
else
unit.state = "returning"
point = source
--print("Returning to caster after idling")
end
end
end
-- If it was a collision on a return (meaning it reached the caster), change to acquiring so it finds a new target
elseif unit.state == "returning" then
-- Update the point to the caster's current position
point = source
if Debug then DebugDrawCircle(point, returnColor, 100, 25, true, draw_duration) end
if collision then
unit.state = "acquiring"
end
-- if set the state to end, the point is also the caster position, but the units will be removed on collision
elseif unit.state == "end" then
point = source
if Debug then DebugDrawCircle(point, endColor, 100, 25, true, 2) end
-- Last collision ends the unit
if collision then
-- Heal is calculated as: a percentage of the units average attack damage multiplied by the amount of attacks the spirit did.
local heal_done = unit.numberOfHits * average_damage* heal_percent
caster:Heal(heal_done, ability)
caster:EmitSound("Hero_DeathProphet.Exorcism.Heal")
--print("Healed ",heal_done)
unit:SetPhysicsVelocity(Vector(0,0,0))
unit:OnPhysicsFrame(nil)
unit:ForceKill(false)
end
end
end)
end
-- Change the state to end when the modifier is removed
function ExorcismEnd( event )
local caster = event.caster
local targets = caster.spirits
print("Exorcism End")
caster:StopSound("Hero_DeathProphet.Exorcism")
for _,unit in pairs(targets) do
if unit and IsValidEntity(unit) then
unit.state = "end"
end
end
-- Reset the last_targeted
caster.last_targeted = nil
end
-- Updates the last_targeted enemy, to focus the ghosts on it.
function ExorcismAttack( event )
local caster = event.caster
local target = event.target
caster.last_targeted = target
--print("LAST TARGET: "..target:GetUnitName())
end
-- Kill all units when the owner dies or the spell is cast while the first one is still going
function ExorcismDeath( event )
local caster = event.caster
local targets = caster.spirits or {}
print("Exorcism Death")
caster:StopSound("Hero_DeathProphet.Exorcism")
for _,unit in pairs(targets) do
if unit and IsValidEntity(unit) then
unit:SetPhysicsVelocity(Vector(0,0,0))
unit:OnPhysicsFrame(nil)
-- Kill
unit:ForceKill(false)
end
end
end
|
EditorPickupCriminalDeployables = EditorPickupCriminalDeployables or class(MissionScriptEditor)
function EditorPickupCriminalDeployables:create_element()
self.super.create_element(self)
self._element.class = "ElementPickupCriminalDeployables"
end
function EditorPickupCriminalDeployables:_build_panel()
self:_create_panel()
self:Info("Picks up every player placed sentry gun equipment on the map and gives them back to their owners.")
end
|
local path = (...):gsub('%.[^%.]+$', '')
path = path:sub(1,path:match("^.*()%."))
local Class = require(path.."thirdparty.hump.class")
local Element = require(path.."elements.element")
local Text = Class {}
Text:include(Element)
function Text:init(element, parent, gui)
Element.init(self, element, parent, gui)
-- Display
self.default_properties.display = "block"
-- Font
self.default_properties.font_path = "inherit"
self.default_properties.font_size = "inherit"
self.default_properties.line_height = "inherit"
self.default_properties.text_align = "inherit"
self.default_properties.text_shadow = "inherit"
-- Color
self.default_properties.text_color = "inherit"
self.default_properties.text_shadow_color = "inherit"
end
return Text
|
local layerBase = require("games/common2/module/layerBase");
--[[
弹幕
]]
local OnlookerMyBarrageLayer = class(layerBase);
OnlookerMyBarrageLayer.ctor = function(self)
local seat = PlayerSeat.getInstance():getOnlookerSeat();
if self.m_viewConfig[seat] then
self:addView(seat,self.m_viewConfig[seat]);
end
end
OnlookerMyBarrageLayer.dtor = function(self)
end
OnlookerMyBarrageLayer.parseViewConfig = function(self)
local config = table.verify(GameProcessManager2.getInstance():getGameConfig());
local seat = PlayerSeat.getInstance():getOnlookerSeat();
local viewConfig = {
["onlooker"] = {
[seat] = {
path = "games/common2/onlooker/module/onlookerMyBarrage/onlookerMyBarrageView";
viewLayer = "view/kScreen_1280_800/games/common2/onlooker/onlooker_my_barrage_layout";
};
};
["normal"] = {};
};
return viewConfig;
end
return OnlookerMyBarrageLayer;
|
----
-- Different mod utilities.
--
-- Most of them are expected to be used in the gameplay console.
--
-- **Source Code:** [https://github.com/victorpopkov/dst-mod-keep-moving](https://github.com/victorpopkov/dst-mod-keep-moving)
--
-- @module Utils
--
-- @author Victor Popkov
-- @copyright 2020
-- @license MIT
-- @release 0.1.0-alpha
----
local Utils = {}
--
-- Helpers
--
local function DebugError(...)
return _G.KeepMovingDebug and _G.KeepMovingDebug:DebugError(...)
end
local function DebugString(...)
return _G.KeepMovingDebug and _G.KeepMovingDebug:DebugString(...)
end
--- Debugging
-- @section debugging
--- Adds debug methods to the destination class.
--
-- Checks the global environment if the `KeepMovingDebug` (`Debug`) is available and adds the
-- corresponding methods from there. Otherwise, adds all the corresponding functions as empty ones.
--
-- @tparam table dest Destination class
function Utils.AddDebugMethods(dest)
local methods = {
"DebugError",
"DebugInit",
"DebugString",
"DebugStringStart",
"DebugStringStop",
"DebugTerm",
}
if _G.KeepMovingDebug then
for _, v in pairs(methods) do
dest[v] = function(_, ...)
if _G.KeepMovingDebug and _G.KeepMovingDebug[v] then
return _G.KeepMovingDebug[v](_G.KeepMovingDebug, ...)
end
end
end
else
for _, v in pairs(methods) do
dest[v] = function()
end
end
end
end
--- General
-- @section general
--- Checks if HUD has an input focus.
-- @tparam EntityScript inst Player instance
-- @treturn boolean
function Utils.IsHUDFocused(inst)
return not Utils.ChainGet(inst, "HUD", "HasInputFocus", true)
end
--- Chain
-- @section chain
--- Gets chained field.
--
-- Simplifies the last chained field retrieval like:
--
-- return TheWorld
-- and TheWorld.net
-- and TheWorld.net.components
-- and TheWorld.net.components.shardstate
-- and TheWorld.net.components.shardstate.GetMasterSessionId
-- and TheWorld.net.components.shardstate:GetMasterSessionId
--
-- Or it's value:
--
-- return TheWorld
-- and TheWorld.net
-- and TheWorld.net.components
-- and TheWorld.net.components.shardstate
-- and TheWorld.net.components.shardstate.GetMasterSessionId
-- and TheWorld.net.components.shardstate:GetMasterSessionId()
--
-- It also supports net variables and tables acting as functions.
--
-- @usage Utils.ChainGet(TheWorld, "net", "components", "shardstate", "GetMasterSessionId") -- (function) 0x564445367790
-- @usage Utils.ChainGet(TheWorld, "net", "components", "shardstate", "GetMasterSessionId", true) -- (string) D000000000000000
-- @tparam table src
-- @tparam string|boolean ...
-- @treturn function|userdata|table
function Utils.ChainGet(src, ...)
if src and (type(src) == "table" or type(src) == "userdata") then
local args = { ... }
local execute = false
if args[#args] == true then
table.remove(args, #args)
execute = true
end
local previous = src
for i = 1, #args do
if src[args[i]] then
previous = src
src = src[args[i]]
else
return
end
end
if execute and previous then
if type(src) == "function" then
return src(previous)
elseif type(src) == "userdata" or type(src) == "table" then
if type(src.value) == "function" then
-- netvar
return src:value()
elseif getmetatable(src.value) and getmetatable(src.value).__call then
-- netvar (for testing)
return src.value(src)
elseif getmetatable(src) and getmetatable(src).__call then
-- table acting as a function
return src(previous)
end
end
return
end
return src
end
end
--- Validates chained fields.
--
-- Simplifies the chained fields checking like below:
--
-- return TheWorld
-- and TheWorld.net
-- and TheWorld.net.components
-- and TheWorld.net.components.shardstate
-- and TheWorld.net.components.shardstate.GetMasterSessionId
-- and true
-- or false
--
-- @usage Utils.ChainValidate(TheWorld, "net", "components", "shardstate", "GetMasterSessionId") -- (boolean) true
-- @tparam table src
-- @tparam string|boolean ...
-- @treturn boolean
function Utils.ChainValidate(src, ...)
return Utils.ChainGet(src, ...) and true or false
end
--- Locomotor
-- @section locomotor
--- Checks if the locomotor is available.
--
-- Can be used to check whether the movement prediction (lag compensation) is enabled or not as the
-- locomotor component is not available when it's disabled.
--
-- @tparam EntityScript inst Player instance
-- @treturn boolean
function Utils.IsLocomotorAvailable(inst)
return Utils.ChainGet(inst, "components", "locomotor") ~= nil
end
--- Runs in a certain direction.
--
-- Calculates an angle and calls `RunInDirection` from the locomotor component when it's available.
-- Otherwise sends the corresponding `RPC.DirectWalking`.
--
-- @tparam EntityScript inst Player instance
-- @tparam Vector3 pt Destination point
-- @treturn[1] Vector3 Direction vector
-- @treturn[1] number Direction angle
function Utils.RunInPointDirection(inst, pt)
local locomotor = Utils.ChainGet(inst, "components", "locomotor")
local angle = inst:GetAngleToPoint(pt)
local offset = inst:GetPosition() - pt
local dir = offset:GetNormalized()
dir.x = -dir.x
dir.z = -dir.z
if locomotor then
inst.Transform:SetRotation(angle)
locomotor:RunInDirection(angle)
else
SendRPCToServer(RPC.DirectWalking, dir.x, dir.z)
end
return dir, angle
end
--- Walks to a certain point.
--
-- Prepares a `WALKTO` action for `PlayerController.DoAction` when the locomotor component is
-- available. Otherwise sends the corresponding `RPC.LeftClick`.
--
-- @tparam EntityScript inst Player instance
-- @tparam Vector3 pt Destination point
function Utils.WalkToPoint(inst, pt)
local player_controller = Utils.ChainGet(inst, "components", "playercontroller")
if not player_controller then
DebugError("Player controller is not available")
return
end
if player_controller.locomotor then
player_controller:DoAction(BufferedAction(inst, nil, ACTIONS.WALKTO, nil, pt))
else
SendRPCToServer(RPC.LeftClick, ACTIONS.WALKTO.code, pt.x, pt.z)
end
end
--- Stops moving.
--
-- Calls `Stop` from the locomotor component when it's available. Otherwise sends an
-- `RPC.StopWalking`.
--
-- @tparam EntityScript inst Player instance
function Utils.StopMoving(inst)
local locomotor = Utils.ChainGet(inst, "components", "locomotor")
if locomotor then
locomotor:Stop()
else
SendRPCToServer(RPC.StopWalking)
end
end
--- Save data
-- @section savedata
--- Gets the save data path.
--
-- Returns one of the following paths based on the server type:
--
-- - `server_temp/server_save` (local game)
-- - `client_temp/server_save` (dedicated server)
--
-- @treturn string
function Utils.SaveDataGetPath()
return TheWorld and TheWorld.ismastersim
and "server_temp/server_save"
or "client_temp/server_save"
end
--- Loads the save data.
--
-- Returns the data which is stored on the client-side.
--
-- @treturn table
function Utils.SaveDataLoad()
local success, save_data
local path = Utils.SaveDataGetPath()
DebugString("[save_data]", "Path:", path)
TheSim:GetPersistentString(path, function(success_load, str)
if success_load then
DebugString("[save_data]", "Loaded successfully")
success, save_data = RunInSandboxSafe(str)
if success then
DebugString("[save_data]", "Data extracted successfully")
DebugString("[save_data]", "Seed:", save_data.meta.seed)
DebugString("[save_data]", "Version:", save_data.meta.saveversion)
return save_data
else
DebugError("[save_data]", "Data extraction has failed")
return false
end
else
DebugError("[save_data]", "Load has failed")
return false
end
end)
return save_data
end
--- Table
-- @section table
--- Counts the number of elements inside the table.
-- @tparam table t Table
-- @treturn number
function Utils.TableCount(t)
if type(t) ~= "table" then
return false
end
local result = 0
for _ in pairs(t) do
result = result + 1
end
return result
end
--- Thread
-- @section thread
--- Starts a new thread.
--
-- Just a convenience wrapper for the `StartThread`.
--
-- @tparam string id Thread ID
-- @tparam function fn Thread function
-- @tparam function whl While function
-- @tparam[opt] function init Initialization function
-- @tparam[opt] function term Termination function
-- @treturn table
function Utils.ThreadStart(id, fn, whl, init, term)
return StartThread(function()
DebugString("Thread started")
if init then
init()
end
while whl() do
fn()
end
if term then
term()
end
Utils.ThreadClear()
end, id)
end
--- Clears a thread.
-- @tparam table thread Thread
function Utils.ThreadClear(thread)
local task = scheduler:GetCurrentTask()
if thread or task then
if thread and not task then
DebugString("[" .. thread.id .. "]", "Thread cleared")
else
DebugString("Thread cleared")
end
thread = thread ~= nil and thread or task
KillThreadsWithID(thread.id)
thread:SetList(nil)
end
end
return Utils
|
require("games/common2/match/matchMechine/matchMechineConfig");
require("games/common2/mechine/mechineLog");
local MatchMechineOperation = class();
MatchMechineOperation.ctor = function(self,uid)
self.m_lastState = MatchMechineConfig.STATUS_NONE;
self.m_curState = MatchMechineConfig.STATUS_NONE;
self.m_curSubState = self.m_curState;
self.m_uid = uid or UserBaseInfoIsolater.getInstance():getUserId();
local data = {};
data.tag = "MatchMechineOperation.ctor";
data.time = os.date();
data.curState = self.m_curState;
data.lastState = self.m_lastState;
data.self = tostring(self);
MechineLog.getInstance():d(MechineLog.TAG4,self.m_uid,data);
end
MatchMechineOperation.dtor = function(self)
self:resetState("MatchMechineOperation.dtor");
end
MatchMechineOperation.getStates = function(self)
return self.m_curState,self.m_lastState,self.m_curSubState;
end
MatchMechineOperation.resetState = function(self,tag)
local uid = self.m_uid;
local data = {};
data.tag = tag or "MatchMechineOperation.resetState";
data.time = os.date();
data.curState = self.m_curState;
data.lastState = self.m_lastState;
data.self = tostring(self);
data.nextState = MatchMechineOperation.STATUS_NONE;
MechineLog.getInstance():d(MechineLog.TAG4,uid,data);
self.m_lastState = MatchMechineConfig.STATUS_NONE;
self.m_curState = MatchMechineConfig.STATUS_NONE;
self.m_curSubState = self.m_curState;
end
MatchMechineOperation.checkStateValid = function(self,action,info,isFast,tag)
if MatchMechineOperation.stateChangeConfig[action] == self.m_curState
and action ~= MatchMechineConfig.ACTION_EXIT_SUCCESS then
return true;
end
local config = MatchMechineOperation.stateCheckConfig[self.m_curState];
local state = self.m_curState;
local flag;--当前状态机是否有处理
if config then
for k,v in pairs(config) do
if v[1] == action then
state = v[2] or state;
flag = true;
break;
end
end
end
local uid = self.m_uid;
local data = {};
data.action = action;
data.info = info;
data.isFast = isFast;
data.tag = tag;
data.time = os.date();
data.type = flag and "handle" or "no_handle";
data.curState = self.m_curState;
data.lastState = self.m_lastState;
data.nextState = state;
data.self = tostring(self);
MechineLog.getInstance():d(MechineLog.TAG4,uid,data);
if flag then
self.m_lastState = self.m_curState;
self.m_curState = state;
self:refreshSubState(state,action);
self:updatePlayerInfo(self.m_curState,self.m_lastState,action,info,isFast);--
else
local isAmend,isReport = self:amendmentStatus(action,info,isFast);
if isReport then
local tmp = table.verify(MatchIsolater.getInstance():getMatchData());
local data = {};
data.userId = uid;
data.matchId = tmp.id;
MechineLog.getInstance():d(MechineLog.TAG4,uid,data);
MechineLog.getInstance():reportLog(MechineLog.TAG4,uid,true);
end
if not isAmend then
MechineManage.getInstance():receiveAction(GameMechineConfig.ACTION_NS_STATUS_ERROR);
MechineManage.getInstance():receiveAction(GameMechineConfig.ACTION_REFRESH_MAINSTATUS,
GameMechineConfig.STATUS_RECONNECT, -1);
end
end
end
-- 修正状态错误
MatchMechineOperation.amendmentStatus = function(self,action,info,isFast)
local isAmend = true;
local isReport = true;
local state = MatchMechineOperation.stateChangeConfig[action];
if state then --会引起状态变化的动作,可能让界面卡死,固先将其作为有效动作,执行后修正状态
self.m_lastState = self.m_curState;
self.m_curState = state;
self:refreshSubState(state,action);
self:updatePlayerInfo(self.m_curState,self.m_lastState,action,info,isFast);
if state == MatchMechineConfig.STATUS_FINISH
or state == MatchMechineConfig.STATUS_NONE then --比赛已结束,已无修正必要
isAmend = false;
end
else --不会引起状态变化的动作,直接修正状态
end
return isAmend,isReport;
end
MatchMechineOperation.refreshSubState = function(self,state,action)
local subConfig = MatchMechineOperation.subStateChangeConfig[state];
local subState = state;
if subConfig then
subState = subConfig[action] or self.m_curSubState;
end
self.m_curSubState = subState;
end
-- 更新数据
MatchMechineOperation.updatePlayerInfo = function(self,curstate,laststate,action,info,isFast)
if MatchMechineOperation.actionConfig[action] then
MatchMechineOperation.actionConfig[action](self,curstate,laststate,action,info,isFast);
end
end
-- 发送广播,当前状态、上一次的状态、动作、本地座位号、用户id、返回信息、是否为快速响应
MatchMechineOperation.sendBroadCastMsg = function(self,curState,lastState,action,info,isFast)
local localseat = PlayerSeat.getInstance():getMyLocalSeat();
local uid = self.m_uid;
if curState ~= lastState then --比赛状态改变,广播状态更改
EventDispatcher.getInstance():dispatch(MatchMechineConfig.NOTIFY_STATUS,curState,lastState,action,localseat,uid,info,isFast);
else
EventDispatcher.getInstance():dispatch(MatchMechineConfig.NOTIFY_ACTION,
action,localseat,uid,info,isFast);
end
end
MatchMechineOperation.createMatchViews = function(self,viewName,isFast)
if viewName then
local action = MatchMechineConfig.ACTION_CREATE_MATCH_VIEWS;
local info = {};
info.viewName = viewName;
self:sendBroadCastMsg(nil,nil,action,info,isFast);
end
end
---------------------------------------------------------------------------------------------------------------
MatchMechineOperation.onSignupMatchSuccess = function(self,curstate,laststate,action,info,isFast)
if not isFast then
self:createMatchViews(MatchMechineConfig.VIEW_LOADING);
end
self:sendBroadCastMsg(curstate,laststate,action,info,isFast);
end
MatchMechineOperation.onSignupXianShiMatchSuccess = function(self,curstate,laststate,action,info,isFast)
self:sendBroadCastMsg(curstate,laststate,action,info,isFast);
end
MatchMechineOperation.onMatchStart = function(self,curstate,laststate,action,info,isFast)
self:sendBroadCastMsg(curstate,laststate,action,info,isFast);
end
MatchMechineOperation.onExitMatch = function(self,curstate,laststate,action,info,isFast)
MatchIsolater.getInstance():setSignMatchId(nil);
self:sendBroadCastMsg(curstate,laststate,action,info,isFast);
end
MatchMechineOperation.onGetStageInfo = function(self,curstate,laststate,action,info,isFast)
self:sendBroadCastMsg(curstate,laststate,action,info,isFast);
end
MatchMechineOperation.onMatchGameOver = function(self,curstate,laststate,action,info,isFast)
if not isFast then
self:createMatchViews(MatchMechineConfig.VIEW_GAMEOVER);
end
self:sendBroadCastMsg(curstate,laststate,action,info,isFast);
end
MatchMechineOperation.onWaitTable = function(self,curstate,laststate,action,info,isFast)
self:createMatchViews(MatchMechineConfig.VIEW_WAIT_TABLE,isFast);
self:sendBroadCastMsg(curstate,laststate,action,info,isFast);
end
MatchMechineOperation.onRoundOver = function(self,curstate,laststate,action,info,isFast)
if not isFast then
self:createMatchViews(MatchMechineConfig.VIEW_ROUNDOVER);
end
self:sendBroadCastMsg(curstate,laststate,action,info,isFast);
end
MatchMechineOperation.onMatchFinsh = function(self,curstate,laststate,action,info,isFast)
self:createMatchViews(MatchMechineConfig.VIEW_OVER);
self:sendBroadCastMsg(curstate,laststate,action,info,isFast);
end
MatchMechineOperation.onMatchReward = function(self,curstate,laststate,action,info,isFast)
self:createMatchViews(MatchMechineConfig.VIEW_OVER);
self:sendBroadCastMsg(curstate,laststate,action,info,isFast);
end
MatchMechineOperation.onGetReviveNotify = function(self,curstate,laststate,action,info,isFast)
self:createMatchViews(MatchMechineConfig.VIEW_REVIVE);
self:sendBroadCastMsg(curstate,laststate,action,info,isFast);
end
MatchMechineOperation.onReviveFailed = function(self,curstate,laststate,action,info,isFast)
self:sendBroadCastMsg(curstate,laststate,action,info,isFast);
end
MatchMechineOperation.onReviveSuccess = function(self,curstate,laststate,action,info,isFast)
self:sendBroadCastMsg(curstate,laststate,action,info,isFast);
end
MatchMechineOperation.onGetPlayerScore = function(self,curstate,laststate,action,info,isFast)
self:sendBroadCastMsg(curstate,laststate,action,info,isFast);
end
MatchMechineOperation.onRequestExitMatch = function(self,curstate,laststate,action,info,isFast)
self:createMatchViews(MatchMechineConfig.VIEW_EXIT,isFast);
self:sendBroadCastMsg(curstate,laststate,action,info,isFast);
end
MatchMechineOperation.onReconnectMatchInGame = function(self,curstate,laststate,action,info,isFast)
self:sendBroadCastMsg(curstate,laststate,action,info,isFast);
end
MatchMechineOperation.stateCheckConfig = {
--[current status] = {{action,next status}};
[MatchMechineConfig.STATUS_NONE] = {
{MatchMechineConfig.ACTION_SIGNUP_SUCCESS,MatchMechineConfig.STATUS_LOADING},
{MatchMechineConfig.ACTION_SIGNUP_XIANSHI_SUCCESS,nil},
{MatchMechineConfig.ACTION_EXIT_SUCCESS,nil},
{MatchMechineConfig.ACTION_RESET,nil},
};
[MatchMechineConfig.STATUS_LOADING] = {
{MatchMechineConfig.ACTION_START,MatchMechineConfig.STATUS_PLAYING},
{MatchMechineConfig.ACTION_REQUEST_EXIT,nil},
{MatchMechineConfig.ACTION_EXIT_SUCCESS,MatchMechineConfig.STATUS_NONE},
{MatchMechineConfig.ACTION_RESET,MatchMechineConfig.STATUS_NONE},
};
[MatchMechineConfig.STATUS_PLAYING] = {
{MatchMechineConfig.ACTION_GAME_OVER,MatchMechineConfig.STATUS_WAITING},
{MatchMechineConfig.ACTION_EXIT_SUCCESS,MatchMechineConfig.STATUS_NONE},
{MatchMechineConfig.ACTION_RESET,MatchMechineConfig.STATUS_NONE},
{MatchMechineConfig.ACTION_REQUEST_RECONNECT_INGAME,nil},
{MatchMechineConfig.ACTION_FINISH,MatchMechineConfig.STATUS_FINISH},
};
[MatchMechineConfig.STATUS_WAITING] = {
{MatchMechineConfig.ACTION_WAIT_TABLE,nil},
{MatchMechineConfig.ACTION_GAME_OVER,nil},
{MatchMechineConfig.ACTION_ROUND_OVER,nil},
{MatchMechineConfig.ACTION_REQUEST_EXIT,nil},
{MatchMechineConfig.ACTION_GET_REVIVE_NOTIFY,nil},
{MatchMechineConfig.ACTION_REVIVE_FAILED,nil},
{MatchMechineConfig.ACTION_REVIVE_SUCCESS,nil},
{MatchMechineConfig.ACTION_START,MatchMechineConfig.STATUS_PLAYING},
{MatchMechineConfig.ACTION_FINISH,MatchMechineConfig.STATUS_FINISH},
{MatchMechineConfig.ACTION_EXIT_SUCCESS,MatchMechineConfig.STATUS_NONE},
{MatchMechineConfig.ACTION_RESET,MatchMechineConfig.STATUS_NONE},
};
[MatchMechineConfig.STATUS_FINISH] = {
{MatchMechineConfig.ACTION_GAME_OVER,nil},
{MatchMechineConfig.ACTION_FINISH_REWARD,nil},
{MatchMechineConfig.ACTION_SIGNUP_SUCCESS,MatchMechineConfig.STATUS_LOADING},
{MatchMechineConfig.ACTION_SIGNUP_XIANSHI_SUCCESS,nil},
{MatchMechineConfig.ACTION_EXIT_SUCCESS,MatchMechineConfig.STATUS_NONE},
{MatchMechineConfig.ACTION_RESET,MatchMechineConfig.STATUS_NONE},
};
};
--会引起状态变化的动作
MatchMechineOperation.stateChangeConfig = {
[MatchMechineConfig.ACTION_RESET] = MatchMechineConfig.STATUS_NONE;
[MatchMechineConfig.ACTION_EXIT_SUCCESS] = MatchMechineConfig.STATUS_NONE;
[MatchMechineConfig.ACTION_SIGNUP_SUCCESS] = MatchMechineConfig.STATUS_LOADING;
[MatchMechineConfig.ACTION_START] = MatchMechineConfig.STATUS_PLAYING;
[MatchMechineConfig.ACTION_GAME_OVER] = MatchMechineConfig.STATUS_WAITING;
[MatchMechineConfig.ACTION_FINISH] = MatchMechineConfig.STATUS_FINISH;
};
MatchMechineOperation.subStateChangeConfig = {
[MatchMechineConfig.STATUS_WAITING] = {
[MatchMechineConfig.ACTION_GAME_OVER] = MatchMechineConfig.STATUS_WAITING_GAMEOVER;
[MatchMechineConfig.ACTION_ROUND_OVER] = MatchMechineConfig.STATUS_WAITING_ROUNDOVER;
[MatchMechineConfig.ACTION_GET_REVIVE_NOTIFY] = MatchMechineConfig.STATUS_WAITING_REVIVE;
[MatchMechineConfig.ACTION_REVIVE_SUCCESS] = MatchMechineConfig.STATUS_WAITING_GAMEOVER;
[MatchMechineConfig.ACTION_REVIVE_FAILED] = MatchMechineConfig.STATUS_WAITING_FINISH;
[MatchMechineConfig.ACTION_WAIT_TABLE] = MatchMechineConfig.STATUS_WAITING_TABLE;
};
};
MatchMechineOperation.actionConfig = {
[MatchMechineConfig.ACTION_SIGNUP_SUCCESS] = MatchMechineOperation.onSignupMatchSuccess,
[MatchMechineConfig.ACTION_SIGNUP_XIANSHI_SUCCESS] = MatchMechineOperation.onSignupXianShiMatchSuccess,
[MatchMechineConfig.ACTION_START] = MatchMechineOperation.onMatchStart,
[MatchMechineConfig.ACTION_RESET] = MatchMechineOperation.resetState;
[MatchMechineConfig.ACTION_EXIT_SUCCESS] = MatchMechineOperation.onExitMatch,
[MatchMechineConfig.ACTION_GAME_OVER] = MatchMechineOperation.onMatchGameOver,
[MatchMechineConfig.ACTION_WAIT_TABLE] = MatchMechineOperation.onWaitTable;
[MatchMechineConfig.ACTION_ROUND_OVER] = MatchMechineOperation.onRoundOver,
[MatchMechineConfig.ACTION_FINISH] = MatchMechineOperation.onMatchFinsh,
[MatchMechineConfig.ACTION_FINISH_REWARD] = MatchMechineOperation.onMatchReward,
[MatchMechineConfig.ACTION_GET_REVIVE_NOTIFY] = MatchMechineOperation.onGetReviveNotify,
[MatchMechineConfig.ACTION_REVIVE_FAILED] = MatchMechineOperation.onReviveFailed,
[MatchMechineConfig.ACTION_REVIVE_SUCCESS] = MatchMechineOperation.onReviveSuccess,
[MatchMechineConfig.ACTION_REQUEST_EXIT] = MatchMechineOperation.onRequestExitMatch,
[MatchMechineConfig.ACTION_REQUEST_RECONNECT_INGAME] = MatchMechineOperation.onReconnectMatchInGame,
};
return MatchMechineOperation;
|
object_tangible_deed_pet_deed_pit_droid_deed = object_tangible_deed_pet_deed_shared_pit_droid_deed:new {
}
ObjectTemplates:addTemplate(object_tangible_deed_pet_deed_pit_droid_deed, "object/tangible/deed/pet_deed/pit_droid_deed.iff")
|
require("dapui").setup()
require('dap-go').setup()
require("nvim-dap-virtual-text").setup()
local dap = require("dap")
local dapui = require("dapui")
dap.listeners.after.event_initialized["dapui_config"] = function()
dapui.open()
end
dap.listeners.before.event_terminated["dapui_config"] = function()
dapui.close()
end
dap.listeners.before.event_exited["dapui_config"] = function()
dapui.close()
end
|
local requestQueueSize = 256
-------------------------------------------------
local httpService = game:GetService'HttpService'
local replicatedStorage = game:GetService'ReplicatedStorage'
local players = game:GetService'Players'
local folder = Instance.new("Folder")
local event = Instance.new("RemoteEvent")
local request = Instance.new("RemoteEvent")
local response = Instance.new("RemoteEvent")
local bullet = Instance.new("RemoteEvent")
local module = {}
local sockets = {}
-------------------------------------------------
function generateId()
return httpService:GenerateGUID(false)
end
local notNil = {__index = function (s, i)
local t={} rawset(s, i, t) return t
end}
local function assert(condition, message)
if not condition == true then
error(message, 3)
end
end
-- CONNECTION -----------------------------------
local connection = {}
connection.__index = connection
connection.__mode = "v"
function connection:Disconnect()
for i = 1, #self.Listeners do
if self.Listeners[i][1] == self.Id then
table.remove(self.Listeners, i)
break
end
end
self.Listeners = nil
end
connection.disconnect = connection.Disconnect
function createCallbacks(listeners)
local callbacks = {}
for i = 1, #listeners do
table.insert(callbacks, coroutine.wrap(listeners[i][2]))
end
return callbacks
end
function createConnection(listeners, listener)
local id = generateId()
table.insert(listeners, 1, {id, listener})
return setmetatable({
Id = id,
Listeners = listeners,
}, connection)
end
-- SIGNAL ---------------------------------------
local signal = {}
signal.__index = signal
function signal:Connect(listener)
return createConnection(self.Listeners, listener)
end
function signal:Wait()
table.insert(self.Threads, coroutine.running())
local output repeat
output = {coroutine.yield()}
local success = table.remove(output, 1)
until success == true
coroutine.yield()
return unpack(output)
end
function signal:Fire(...)
for i = #self.Threads, 1, -1 do
-- self.Threads[i](true, ...)
coroutine.resume(self.Threads[i], true, ...)
table.remove(self.Threads, i)
end
local threads = createCallbacks(self.Listeners)
for i = 1, #threads do
threads[i](...)
end
end
signal.connect = signal.Connect
signal.wait = signal.Wait
function createSignal()
return setmetatable({
Threads = {},
Listeners = {}
}, signal)
end
-- SOCKET GROUP ---------------------------------
local group = {}
function group.__tostring(self)
return self.Name
end
function createGroup(socket, name)
return setmetatable({
Name = name,
Socket = socket
}, group)
end
-- SERVER SOCKET --------------------------------
local socket = {}
socket.__index = socket
socket.__newindex = function (_, index)
error(index .. " is not a valid member of Socket", 0)
end
function socket:Listen(name, listener)
assert(self.Alive, "Socket is dead")
if not self.Callbacks[name] then
self:SetCallback(name, listener)
end
local connection = createConnection(self.Listeners[name], listener)
self:ExecuteEventQueue(name)
return connection
end
function socket:Emit(name, ...)
assert(self.Alive, "Socket is dead")
event:FireClient(self.Player, name, ...)
end
function socket:RunListeners(name, ...)
if self.Alive then
local listeners = self.Listeners[name]
if #listeners > 0 then
local threads = createCallbacks(listeners)
for i = 1, #threads do
threads[i](...)
end
else
local queue = self.Queue.Events[name]
if #queue < requestQueueSize then
table.insert(queue, {...})
else
warn("Max event queue reached for", name, "event will not be queued")
end
end
end
end
function socket:ExecuteEventQueue(name)
local queue = self.Queue.Events[name]
while #queue > 0 do
local args = queue[1]
self:RunListeners(name, unpack(args))
table.remove(queue, 1)
end
end
function socket:SetCallback(name, callback)
assert(self.Alive, "Socket is dead")
self.Callbacks[name] = callback
self:ExecuteRequestQueue(name)
end
function socket:Request(name, ...)
assert(self.Alive, "Socket is dead")
local id = generateId()
request:FireClient(self.Player, id, name, ...)
local args
if self.Responses[id] then
args = self.Responses[id]
else
repeat
args = {response.OnServerEvent:wait()}
local player = table.remove(args, 1)
local responseId = table.remove(args, 1)
until player == self.Player and responseId == id
end
return unpack(args)
end
function socket:RunCallback(name, requestId, ...)
if self.Alive then
local callback = self.Callbacks[name]
if callback then
response:FireClient(self.Player, requestId, callback(...))
else
local queue = self.Queue.Requests[name]
if #queue < requestQueueSize then
table.insert(queue, {requestId, ...})
else
warn("Max event queue reached for", name, "event will not be queued")
end
end
end
end
function socket:ExecuteRequestQueue(name)
local queue = self.Queue.Requests[name]
while #queue > 0 do
local args = queue[1]
local requestId = table.remove(args, 1)
local thread = coroutine.wrap(socket.RunCallback)
thread(self, name, requestId, unpack(args))
table.remove(queue, 1)
end
end
function socket:GetGroup(name)
assert(self.Alive, "Socket is dead")
local group = self.Groups[name]
if not group then
group = createGroup(self, name)
self.Groups[name] = group
end
return group
end
function socket:JoinRoom(name)
assert(self.Alive, "Socket is dead")
local room = module.Rooms[name]
for i = 1, #room do
if room[i] == self then
return
end
end
table.insert(room, self)
end
function socket:LeaveRoom(name)
assert(self.Alive, "Socket is dead")
local room = module.Rooms[name]
for i = 1, #room do
if room[i] == self then
table.remove(room, i)
return
end
end
end
function socket.__tostring(self)
return "Socket " .. tostring(self.Player)
end
function socket:Destroy()
self.Listeners = nil
self.Callbacks = nil
self.Queue = nil
self.Responses = nil
self.Rooms = nil
self.Groups = nil
self.Player = nil
self.Alive = false
end
function socket:Disconnect(msg)
assert(self.Alive, "Socket is dead")
self.Alive = false
self.Player:Kick(msg or "You have been disconnected")
end
socket.Connect = socket.Listen
socket.connect = socket.Listen
socket.Invoke = socket.Request
socket.Fire = socket.Emit
function createSocket(player)
return setmetatable({
Player = player,
Listeners = setmetatable({}, notNil),
Callbacks = {},
Queue = {
Requests = setmetatable({}, notNil),
Events = setmetatable({}, notNil)
},
Responses = {},
Groups = {},
Rooms = {},
Alive = true,
Disconnected = createSignal()
}, socket)
end
-------------------------------------------------
local groupSeperator = ":::"
group.__index = function (self, index)
local property = rawget(self.Socket, index)
if property then
return property
else
local method = rawget(group, index)
if method then
return method
else
local fn = function (group, name, ...)
return socket[index](group.Socket, group.Name .. groupSeperator .. name, ...)
end
rawset(group, index, fn)
return fn
end
end
end
-- MODULE --------------------------------------
local weak = {__mode="v"}
local notNilWeak = {__index = function (s, i)
local t=setmetatable({}, weak) rawset(s, i, t) return t
end}
module.Connected = createSignal()
module.Rooms = setmetatable({}, notNilWeak)
module.Callbacks = {}
function module:GetSocket(player)
return sockets[player]
end
function module:GetSockets()
local s = {}
for _, v in pairs(sockets) do
table.insert(s, v)
end
return s
end
function module:Emit(name, ...)
event:FireAllClients(name, ...)
end
function module:Request(name, ...)
local id = generateId()
local args = {...}
module.Callbacks[id] = table.remove(args)
request:FireAllClients(id, name, unpack(args))
end
function module:EmitRoom(room, name, ...)
for i = 1, #room do
if room[i].Alive then
event:FireClient(room[i].Player, name, ...)
end
end
end
function module:RequestRoom(room, name, ...)
local id = generateId()
local args = {...}
module.Callbacks[id] = table.remove(args)
for i = 1, #room do
if room[i].Alive then
request:FireClient(room[i].Player, id, name, unpack(args))
end
end
end
function module:EmitClients(players, name, ...)
for i = 1, #players do
event:FireClient(players[i], name, ...)
end
end
function module:RequestClients(players, name, ...)
local id = generateId()
local args = {...}
module.Callbacks[id] = table.remove(args)
for i = 1, #players do
request:FireClient(players[i], id, name, unpack(args))
end
end
module.Fire = module.Emit
module.Invoke = module.Request
module.FireRoom = module.EmitRoom
module.InvokeRoom = module.RequestRoom
module.FireClients = module.EmitClients
module.InvokeClients = module.RequestClients
-------------------------------------------------
event.OnServerEvent:connect(function (player, name, ...)
local socket = sockets[player]
if socket then
socket:RunListeners(name, ...)
elseif name == nil then
socket = createSocket(player)
sockets[player] = socket
module.Connected:Fire(socket)
spawn(function()
local Connecting = true
while Connecting and wait(4) do
local HasConnected = sockets[player].Player:FindFirstChild("Connected")
print("Status -", HasConnected)
if HasConnected == nil then
print("Reconnecting Socket")
module.Connected:Fire(socket)
else
Connecting = false
HasConnected:Destroy()
print("Connection Restored")
end
end
end)
else
error("Socket does not exist")
end
end)
request.OnServerEvent:connect(function (player, requestId, name, ...)
local socket = sockets[player]
if socket then
socket:RunCallback(name, requestId, ...)
else
error("Socket does not exist")
end
end)
response.OnServerEvent:connect(function (player, requestId, ...)
local callback = module.Callbacks[requestId]
local socket = sockets[player]
if callback then
callback(socket, ...)
elseif socket then
socket.Responses[requestId] = {...}
wait(1)
socket.Responses[requestId] = nil
end
end)
players.PlayerRemoving:connect(function (player)
local socket = sockets[player]
sockets[player] = nil
socket.Disconnected:Fire()
socket:Destroy()
end)
-------------------------------------------------
event.Name = "Event"
request.Name = "Request"
response.Name = "Response"
bullet.Name = "Bullets"
folder.Name = "Sockets"
event.Parent = folder
request.Parent = folder
response.Parent = folder
bullet.Parent = folder
folder.Parent = replicatedStorage
return module
|
-- ModFreakz
-- For support, previews and showcases, head to https://discord.gg/XnJSSUJwnD
-- Only edit this.
local sellAnywhere = false
local useBlip = true
local salesYard = vector3(-47.91,-1683.03,29.31)
local salesRadius = 20.0
-- Stop editing here... unless you know what you're doing.
NewEvent = function(net,func,name,...)
if net then RegisterNetEvent(name); end
AddEventHandler(name, function(...) func(source,...); end)
end
local TSC = GRPCore.TriggerServerCallback
local TSE = TriggerServerEvent
local isConfirming = false
local forSale = {}
function GetVecDist(v1,v2)
if not v1 or not v2 or not v1.x or not v2.x then return 0; end
return math.sqrt( ( (v1.x or 0) - (v2.x or 0) )*( (v1.x or 0) - (v2.x or 0) )+( (v1.y or 0) - (v2.y or 0) )*( (v1.y or 0) - (v2.y or 0) )+( (v1.z or 0) - (v2.z or 0) )*( (v1.z or 0) - (v2.z or 0) ) )
end
function DrawText3D(x,y,z, text, scaleB)
if not scaleB then scaleB = 1; end
local onScreen,_x,_y = World3dToScreen2d(x,y,z)
local px,py,pz = table.unpack(GetGameplayCamCoord())
local dist = GetDistanceBetweenCoords(px,py,pz, x,y,z, 1)
local scale = (((1/dist)*2)*(1/GetGameplayCamFov())*100)*scaleB
if onScreen then
-- Formalize the text
SetTextColour(220, 220, 220, 255)
SetTextScale(0.0*scale, 0.40*scale)
SetTextFont(4)
SetTextProportional(1)
SetTextCentre(true)
-- Diplay the text
SetTextEntry("STRING")
AddTextComponentString(text)
EndTextCommandDisplayText(_x, _y)
end
end
Citizen.CreateThread(function(...)
while not GRPCore do
TriggerEvent('grp:getSharedObject', function(obj) GRPCore = obj; end)
Citizen.Wait(0)
end
TSC('vehsales:GetStartData', function(retTab) forSale = retTab; end)
while not GRPCore.IsPlayerLoaded() do Citizen.Wait(0); end
playerData = GRPCore.GetPlayerData()
local lastPlate = 'SUKDIK'
local drawText = 'YUTU'
local lastTimer = GetGameTimer()
if not sellAnywhere and useBlip then
local blip = AddBlipForCoord(salesYard.x, salesYard.y, salesYard.z)
SetBlipSprite (blip, 225)
SetBlipDisplay (blip, 3)
SetBlipScale (blip, 0.7)
SetBlipColour (blip, 42)
SetBlipAsShortRange (blip, false)
SetBlipHighDetail (blip, true)
BeginTextCommandSetBlipName ("STRING")
AddTextComponentString ("Stanley's Used Cars")
EndTextCommandSetBlipName (blip)
end
while true do
Citizen.Wait(0)
local closest,closestDist
local plyPos = GetEntityCoords(GetPlayerPed(-1))
for k,v in pairs(forSale) do
local dist = GetVecDist(plyPos,v.loc)
if not closestDist or dist < closestDist then
closestDist = dist
closest = v
end
end
if closestDist and closestDist < 10 then
if not lastPlate or closest.vehProps.plate ~= lastPlate then
isConfirming = false
if closest.owner ~= playerData.identifier then
drawText = "[~b~"..GetDisplayNameFromVehicleModel(closest.vehProps.model).."~s~] Aperte [~b~E~s~] para comprar. [$~b~"..closest.price.."~s~]"
else
drawText = "[~b~"..GetDisplayNameFromVehicleModel(closest.vehProps.model).."~s~] Aperte [~b~E~s~] para recuperar seu veículo! [$~b~"..closest.price.."~s~]"
end
local turbs = 'No'
if closest.vehProps.modTurbo and closest.vehProps.modTurbo > 0 then turbs = 'Yes'; end
drawTextB = "[Turbo : ~b~"..turbs.."~s~] [Engine : ~b~"..tostring(closest.vehProps.modEngine).."~s~] [Gearbox : ~b~"..tostring(closest.vehProps.modTransmission).."~s~]"
drawTextC = "[Suspension : ~b~"..tostring(closest.vehProps.modSuspension).."~s~] [Armor : ~b~"..tostring(closest.vehProps.modArmor).."~s~] [Brakes : ~b~"..tostring(closest.vehProps.modBrakes).."~s~]"
lastPlate = closest.vehProps.plate
end
DrawText3D(closest.loc.x,closest.loc.y,closest.loc.z + 1.0, drawText)
DrawText3D(closest.loc.x,closest.loc.y,closest.loc.z + 0.9, drawTextB)
DrawText3D(closest.loc.x,closest.loc.y,closest.loc.z + 0.8, drawTextC)
if IsControlJustPressed(0,38) and closestDist < 5.0 and GetGameTimer() - lastTimer > 150 then
lastTimer = GetGameTimer()
if not isConfirming then
if closest.owner ~= playerData.identifier then
drawText = "[~b~"..GetDisplayNameFromVehicleModel(closest.vehProps.model).."~s~] Aperte [~b~E~s~] novamente para confirmar esta compra. [$~b~"..closest.price.."~s~]"
else
lastPlate = false
BuyVehicle(closest)
end
isConfirming = true
else
lastPlate = false
isConfirming = false
BuyVehicle(closest)
end
end
else
lastPlate = false
isConfirming = false
end
end
end)
function AddCar(source,vehId,loc,price,props,id)
local veh = NetworkGetEntityFromNetworkId(vehId)
SetEntityAsMissionEntity(veh,true,true)
SetVehicleDoorsLocked(veh,2)
SetVehicleDoorsLockedForAllPlayers(veh,true)
SetEntityInvincible(veh,true)
table.insert(forSale,{veh = vehId, loc = loc, price = price, vehProps = props, owner = id})
end
function BuyVehicle(closest)
TSC('vehsales:TryBuy', function(can,msg)
if can then
TriggerEvent('DoLongHudText', msg, 1)
TSE('vehsales:BuyVeh',closest)
else
TriggerEvent('DoLongHudText', msg, 1)
end
end,closest)
end
function SellCar(price)
if not price or not price[1] then TriggerEvent('DoLongHudText', "Você precisa inserir um preço.", 1); return; end
if type(price) == "table" then price = tonumber(price[1]); end
if not price or type(price) ~= "number" or price <= 0 then TriggerEvent('DoLongHudText', "Stop fucking around.", 2); return; end
if not IsPedInAnyVehicle(GetPlayerPed(-1),false) then TriggerEvent('DoLongHudText', "You must be in a vehicle.", 2); return; end
if not sellAnywhere and GetVecDist(GetEntityCoords(GetPlayerPed(-1)),salesYard) > salesRadius then TriggerEvent('DoLongHudText', "Você deve estar no pátio de vendas para fazer isso.", 2); return; end
local veh = GetVehiclePedIsIn(GetPlayerPed(-1),false)
local vehProps = GRPCore.Game.GetVehicleProperties(veh)
TSC('vehsales:TrySell', function(canSell,msg)
if not canSell then
TriggerEvent('DoLongHudText', msg, 1)
else
TaskLeaveVehicle(GetPlayerPed(-1),veh,0)
TaskEveryoneLeaveVehicle(veh)
local vehId = NetworkGetNetworkIdFromEntity(veh)
TSE('vehsales:AddSale',vehId,GetEntityCoords(veh),price,vehProps)
end
end, vehProps)
end
function RemoveVeh(source,veh)
local vehi = veh
local veh = NetworkGetEntityFromNetworkId(veh.veh)
SetEntityAsMissionEntity(veh,true,true)
SetVehicleDoorsLocked(veh,0)
SetVehicleDoorsLockedForAllPlayers(veh,false)
SetEntityInvincible(veh,false)
for k,v in pairs(forSale) do
if v.vehProps.plate == vehi.vehProps.plate then forSale[k] = nil; end
end
end
RegisterCommand('sellCar', function(source,args) SellCar(args); end)
NewEvent(true,AddCar,'vehsales:AddToSale')
NewEvent(true,RemoveVeh,'vehsales:RemoveFromSale')
|
local class = require(game.ReplicatedStorage.BehaviorTree.middleclass)
local Registry = require(game.ReplicatedStorage.BehaviorTree.registry)
local Node = require(game.ReplicatedStorage.BehaviorTree.node_types.node)
local BranchNode = class('BranchNode', Node)
function BranchNode:start(object)
if not self.nodeRunning then
self:setObject(object)
self.actualTask = 1
end
end
function BranchNode:run(object)
if self.actualTask <= #self.nodes then
self:_run(object)
end
end
function BranchNode:_run(object)
if not self.nodeRunning then
self.node = Registry.getNode(self.nodes[self.actualTask])
self.node:start(object)
self.node:setControl(self)
end
self.node:run(object)
end
function BranchNode:running()
self.nodeRunning = true
self.control:running()
end
function BranchNode:success()
self.nodeRunning = false
self.node:finish(self.object)
self.node = nil
end
function BranchNode:fail()
self.nodeRunning = false
self.node:finish(self.object);
self.node = nil
end
return BranchNode
|
if SERVER then AddCSLuaFile() end
fw.dep(SHARED, "notif")
fw.dep(SERVER, "hook")
file.CreateDir(fw.config.dataDir)
local Player = FindMetaTable("Player")
-- Player:GetFWData()
-- @param amount:number - the amount of money to add
-- @ret amount:number player's current balance
if SERVER then
ndoc.table.fwPlayers = {}
local playerData = ndoc.table.fwPlayers
function Player:GetFWData()
return playerData[self:EntIndex()]
end
else
local playerData = {}
ndoc.observe(ndoc.table, 'wait for fwPlayers', function()
playerData = ndoc.table.fwPlayers or {}
end, ndoc.compilePath('fwPlayers'))
local noData = setmetatable({}, {__newindex = function(self, key) rawset(self, key, nil) end})
function Player:GetFWData()
return playerData[self:EntIndex()] or noData
end
end
fw.include_sv "data_sv.lua"
|
object_static_structure_content_meatlump_meatlump_graffiti_aur_s02 = object_static_structure_content_meatlump_shared_meatlump_graffiti_aur_s02:new {
}
ObjectTemplates:addTemplate(object_static_structure_content_meatlump_meatlump_graffiti_aur_s02, "object/static/structure/content/meatlump/meatlump_graffiti_aur_s02.iff")
|
function init(virtual)
if not virtual then
storage.state = storage.state or false
self.nodeMap = { "top", "right", "bottom", "left" }
checkNodes()
end
end
function onNodeConnectionChange()
checkNodes()
end
function onInboundNodeChange(args)
checkNodes()
end
function checkNodes()
if entity.getInboundNodeLevel(0) ~= storage.state then
storage.state = entity.getInboundNodeLevel(0)
entity.setAllOutboundNodes(false)
if storage.state then
local choice = math.random(0, 3)
entity.setOutboundNodeLevel(choice, true)
entity.setAnimationState("randState", self.nodeMap[choice + 1])
else
entity.setAnimationState("randState", "off")
end
end
end
|
--- Buff模块:
-- @module BuffMgr
-- @copyright Lilith Games, Avatar Team
-- @author Dead Ratman
---@module BuffMgr
local BuffMgr, this = ModuleUtil.New('BuffMgr', ClientBase)
local BuffDataList = {}
local buffDataTable = {}
local defPlayerData = {
AvatarHeadSize = 1,
AvatarWidth = 1,
AvatarHeight = 1,
HeadEffect = {},
BodyEffect = {},
HandEffect = {},
FootEffect = {},
EntiretyEffect = {},
WalkSpeed = 6,
JumpUpVelocity = 8,
GravityScale = 2,
SkinID = 0,
EnableEquipable = true
}
function BuffMgr:Init()
print('BuffMgr:Init')
this:NodeRef()
this:DataInit()
this:EventBind()
end
--节点引用
function BuffMgr:NodeRef()
end
--数据变量声明
function BuffMgr:DataInit()
print(table.dump(Data.Player.attr))
--[[invoke(
function()
this:GetBuffEventHandler(1, 10)
end,
6
)]]
end
--节点事件绑定
function BuffMgr:EventBind()
end
--获得Buff
function BuffMgr:GetBuffEventHandler(_buffID, _dur)
if _buffID ~= 0 then
if Config.Buff[_buffID].NeedSound == true then
SoundUtil.Play2DSE(localPlayer.UserId, 109)
end
if BuffDataList[_buffID] then
BuffDataList[_buffID].curTime = _dur
else
BuffDataList[_buffID] = {
curTime = _dur
}
this:RemoveCoverBuff(Config.Buff[_buffID].BuffCoverIDList)
end
buffDataTable = table.deepcopy(defPlayerData)
for k, v in pairs(Config.Buff[_buffID]) do
if string.find(tostring(k), '_Cover') and defPlayerData[string.gsub(k, '_Cover', '')] then ---覆盖
buffDataTable[string.gsub(k, '_Cover', '')] = v
--print(string.gsub(k, "_Cover", ""))
--print(buffDataTable[string.gsub(k, "_Cover", "")])
end
end
this:GetAllBuffData()
PlayerCtrl:PlayerAttrUpdate()
else
return
end
end
--移除Buff
function BuffMgr:RemoveBuffEventHandler(_buffID)
if BuffDataList[_buffID] then
BuffDataList[_buffID] = nil
buffDataTable = table.deepcopy(defPlayerData)
this:GetAllBuffData()
PlayerCtrl:PlayerAttrUpdate()
end
end
--清除所有Buff
function BuffMgr:BuffClear()
BuffDataList = {}
buffDataTable = table.deepcopy(defPlayerData)
this:GetAllBuffData()
PlayerCtrl:PlayerAttrUpdate()
end
--移除互斥Buff
function BuffMgr:RemoveCoverBuff(_buffIDList)
for k, v in pairs(_buffIDList) do
if BuffDataList[v] then
BuffDataList[v] = nil
end
end
end
--获得所有Buff的效果数据
function BuffMgr:GetAllBuffData()
for buffID, buffData in pairs(BuffDataList) do
for k, v in pairs(Config.Buff[buffID]) do
if string.find(tostring(k), '_Overlay') and defPlayerData[string.gsub(k, '_Overlay', '')] then ---叠加
if type(Data.Player.attr[string.gsub(k, '_Overlay', '')]) == 'table' then ---表类型
--print(v, buffID)
if v ~= '' then
table.insert(buffDataTable[string.gsub(k, '_Overlay', '')], v)
end
elseif type(Data.Player.attr[string.gsub(k, '_Overlay', '')]) == 'number' then ---数值类型
buffDataTable[string.gsub(k, '_Overlay', '')] = buffDataTable[string.gsub(k, '_Overlay', '')] * v
end
end
end
end
for k, v in pairs(buffDataTable) do
Data.Player.attr[k] = v
end
--print(table.dump(buffDataTable))
end
--按时间消退Buff
function BuffMgr:FadeBuffByTime(dt)
for k, v in pairs(BuffDataList) do
if v.curTime > 0 then
v.curTime = v.curTime - dt
elseif v.curTime > -1 then
this:RemoveBuffEventHandler(k)
--BuffDataList[k] = nil
end
end
end
function BuffMgr:Update(dt, tt)
this:FadeBuffByTime(dt)
end
return BuffMgr
|
logger = {}
function logger.logEvent(evt)
print("Event :: " .. evt)
end
return logger
|
-- Addon: WoWeuCN-Quests
-- Author: qqytqqyt
-- Credit to: Platine (e-mail: [email protected]) https://wowpopolsku.pl
-- Local variables
local WoWeuCN_Quests_version = GetAddOnMetadata("WoWeuCN_Quests", "Version");
local WoWeuCN_AddonPrefix = "WoWeuCN";
local WoWeuCN_Quests_onDebug = false;
local WoWeuCN_Quests_name = UnitName("player");
local WoWeuCN_Quests_class, WoWeuCN_Quests_class_file, WoWeuCN_Quests_class_Id = UnitClass("player");
local WoWeuCN_Quests_race, WoWeuCN_Quests_race_file, WoWeuCN_Quests_race_Id = UnitRace("player");
local WoWeuCN_Quests_sex = UnitSex("player"); -- 1:neutral, 2:male, 3:female
local WoWeuCN_Quests_waitTable = {};
local WoWeuCN_Quests_waitFrame = nil;
local WoWeuCN_Quests_MessOrig = {
details = "Description",
objectives = "Quest Objectives",
rewards = "Rewards",
itemchoose1= "You will be able to choose one of these rewards:",
itemchoose2= "Choose one of these rewards:",
itemreceiv1= "You will also receive:",
itemreceiv2= "You receiving the reward:",
learnspell = "Learn Spell:",
reqmoney = "Required Money:",
reqitems = "Required items:",
experience = "Experience:",
currquests = "Current Quests",
avaiquests = "Available Quests", };
local WoWeuCN_Quests_quest_EN = {
id = 0,
title = "",
details = "",
objectives = "",
progress = "",
completion = "",
itemchoose = "",
itemreceive = "",
descriptionFont = "",
descriptionSize = 13,
headlineFont = "",
headlineSize = 18};
local WoWeuCN_Quests_quest_LG = {
id = 0,
title = "",
details = "",
objectives = "",
progress = "",
completion = "",
itemchoose = "",
itemreceive = "", };
local last_time = GetTime();
local last_text = 0;
local curr_trans = "1";
local curr_goss = "X";
local curr_hash = 0;
local Original_Font1, Original_Font1_Size = GameFontNormal:GetFont();
local Original_Font2, Original_Font2_Size = QuestInfoDescriptionText:GetFont();
local p_race = {
[1] = { W1="人类", W2="人类" },
[2] = { W1="兽人", W2="兽人" },
[3] = { W1="矮人", W2="矮人" },
[4] = { W1="暗夜精灵", W2="暗夜精灵" },
[5] = { W1="亡灵", W2="亡灵" },
[6] = { W1="牛头人", W2="牛头人" },
[7] = { W1="侏儒", W2="侏儒" },
[8] = { W1="巨魔", W2="巨魔" },
[9] = { W1="地精", W2="地精" },
[10] = { W1="血精灵", W2="血精灵" },
[11] = { W1="德莱尼", W2="德莱尼" },
[22] = { W1="狼人", W2="狼人" },
[24] = { W1="熊猫人", W2="熊猫人" },
[25] = { W1="熊猫人", W2="熊猫人" },
[26] = { W1="熊猫人", W2="熊猫人" },
[27] = { W1="夜之子", W2="夜之子" },
[28] = { W1="至高岭牛头人", W2="至高岭牛头人" },
[29] = { W1="虚空精灵", W2="虚空精灵" },
[30] = { W1="光铸德莱尼", W2="光铸德莱尼" },
[31] = { W1="赞达拉巨魔", W2="赞达拉巨魔" },
[32] = { W1="库尔提拉斯人", W2="库尔提拉斯人" },
[34] = { W1="黑铁矮人", W2="黑铁矮人" },
[35] = { W1="狐人", W2="狐人" },
[36] = { W1="玛格汉兽人", W2="玛格汉兽人" },
[37] = { W1="机械侏儒", W2="机械侏儒" }, }
local p_class = {
[1] = { W1="战士", W2="战士" },
[2] = { W1="圣骑士", W2="圣骑士" },
[3] = { W1="猎人", W2="猎人" },
[4] = { W1="盗贼", W2="盗贼"},
[5] = { W1="牧师", W2="牧师" },
[6] = { W1="死亡骑士", W2="死亡骑士" },
[7] = { W1="萨满", W2="萨满" },
[8] = { W1="法师", W2="法师" },
[9] = { W1="术士", W2="术士" },
[10] = { W1="武僧", W2="武僧" },
[11] = { W1="德鲁伊", W2="德鲁伊" },
[12] = { W1="恶魔猎手", W2="恶魔猎手" },
}
if (p_race[WoWeuCN_Quests_race_Id]) then
player_race = { W1=p_race[WoWeuCN_Quests_race_Id].W1, W2=p_race[WoWeuCN_Quests_race_Id].W2 };
else
player_race = { W1=WoWeuCN_Quests_race, W2=WoWeuCN_Quests_race };
print ("|cff55ff00WoWeuCN_Quests - 新种族: "..WoWeuCN_Quests_race);
end
if (p_class[WoWeuCN_Quests_class_Id]) then
player_class = { W1=p_class[WoWeuCN_Quests_class_Id].W1, W2=p_class[WoWeuCN_Quests_class_Id].W2 };
else
player_class = { W1=WoWeuCN_Quests_class, W2=WoWeuCN_Quests_class };
print ("|cff55ff00WoWeuCN_Quests - 新职业: "..WoWeuCN_Quests_class_Id);
end
-- Global variables initialtion
function WoWeuCN_Quests_CheckVars()
if (not WoWeuCN_Quests_PS) then
WoWeuCN_Quests_PS = {};
end
if (not WoWeuCN_Quests_LastAnnounceDate) then
WoWeuCN_Quests_LastAnnounceDate = 0;
end
if (not WoWeuCN_Quests_SAVED) then
WoWeuCN_Quests_SAVED = {};
end
if (not WoWeuCN_Quests_MISSING) then
WoWeuCN_Quests_MISSING = {};
end
-- Initiation - active
if (not WoWeuCN_Quests_PS["active"]) then
WoWeuCN_Quests_PS["active"] = "1";
end
-- Initiation - title translation
if (not WoWeuCN_Quests_PS["transtitle"] ) then
WoWeuCN_Quests_PS["transtitle"] = "1";
end
if (not WoWeuCN_Quests_PS["transobjectives"] ) then
WoWeuCN_Quests_PS["transobjectives"] = "1";
end
-- Special variable of the GetQuestID function availability
if ( WoWeuCN_Quests_PS["isGetQuestID"] ) then
isGetQuestID=WoWeuCN_Quests_PS["isGetQuestID"];
end;
if (not WoWeuCN_Quests_PS["other1"] ) then
WoWeuCN_Quests_PS["other1"] = "1";
end;
if (not WoWeuCN_Quests_PS["other2"] ) then
WoWeuCN_Quests_PS["other2"] = "1";
end;
if (not WoWeuCN_Quests_PS["other3"] ) then
WoWeuCN_Quests_PS["other3"] = "1";
end;
-- Path version info
if (not WoWeuCN_Quests_PS["patch"]) then
WoWeuCN_Quests_PS["patch"] = GetBuildInfo();
end
-- Saved variables per character
if (not WoWeuCN_Quests_PC) then
WoWeuCN_Quests_PC = {};
end
end
local QTR_waitFrame = nil;
local QTR_waitTable = {};
function QTR_wait(delay, func, ...)
if(type(delay)~="number" or type(func)~="function") then
return false;
end
if (QTR_waitFrame == nil) then
QTR_waitFrame = CreateFrame("Frame","QTR_WaitFrame", UIParent);
QTR_waitFrame:SetScript("onUpdate",function (self,elapse)
local count = #QTR_waitTable;
local i = 1;
while(i<=count) do
local waitRecord = tremove(QTR_waitTable,i);
local d = tremove(waitRecord,1);
local f = tremove(waitRecord,1);
local p = tremove(waitRecord,1);
if(d>elapse) then
tinsert(QTR_waitTable,i,{d-elapse,f,p});
i = i + 1;
else
count = count - 1;
f(unpack(p));
end
end
end);
end
tinsert(QTR_waitTable,{delay,func,{...}});
return true;
end
local function scanAuto(startIndex, attempt, counter)
if (startIndex > 80000) then
return;
end
for i = startIndex, startIndex + 100 do
qcQuestInformationTooltip:SetOwner(UIParent, "ANCHOR_NONE")
qcQuestInformationTooltip:ClearLines()
qcQuestInformationTooltip:SetHyperlink('quest:' .. i)
qcQuestInformationTooltip:Show()
local text = EnumerateTooltipLines(qcQuestInformationTooltip)
if (text ~= '' and text ~= nil) then
WoWeuCN_Quests_QuestToolTips[i .. ''] = text
print(i)
end
end
print(attempt)
print(counter)
WoWeuCN_Quests_QuestIndex = startIndex
if (counter >= 5) then
QTR_wait(0.5, scanAuto, startIndex + 100, attempt + 1, 0)
else
QTR_wait(0.5, scanAuto, startIndex, attempt + 1, counter + 1)
end
end
local function scanCacheAuto(startIndex, attempt, counter)
if (startIndex > 80000) then
return;
end
if (counter == 0) then
print(startIndex)
end
for i = startIndex, startIndex + 150 do
local title = C_QuestLog.GetTitleForQuestID(tostring(i))
if (title ~= '' and title ~= nil) then
print(title)
end
end
WoWeuCN_Quests_QuestIndex = startIndex
if (counter >= 5) then
WoWeuCN_Quests_wait(0.2, scanCacheAuto, startIndex + 150, attempt + 1, 0)
else
WoWeuCN_Quests_wait(0.2, scanCacheAuto, startIndex, attempt + 1, counter + 1)
end
end
-- Checks the availability of Wow's special function: GetQuestID()
function DetectEmuServer()
WoWeuCN_Quests_PS["isGetQuestID"]="0";
isGetQuestID="0";
-- funkcja GetQuestID() występuje tylko na serwerach Blizzarda
if ( GetQuestID() ) then
WoWeuCN_Quests_PS["isGetQuestID"]="1";
isGetQuestID="1";
end
end
-- scann
local function EnumerateTooltipLines_helper(...)
local texts = '';
local hasTitleSet = false
local hasObjectivesSet = false
for i = 1, select("#", ...) do
local region = select(i, ...)
--print(region:GetObjectType())
if region and region:GetObjectType() == "FontString" then
local text = region:GetText() -- string or nil
--print(text)
if (text ~= nil) then
if (hasTitleSet ~= true and text ~= " ")
then
text = "{{" .. text .. "}}"
hasTitleSet = true
end
if (i > 3 and hasObjectivesSet ~= true and text ~= " ")
then
text = "{{" .. text .. "}}"
hasObjectivesSet = true
end
print(i)
print(text)
texts = texts .. text
end
end
end
return texts
end
function EnumerateTooltipLines(tooltip) -- good for script handlers that pass the tooltip as the first argument.
return EnumerateTooltipLines_helper(tooltip:GetRegions())
end
function qcQuestInformationTooltipSetup() -- *
qcQuestInformationTooltip = CreateFrame("GameTooltip", "qcQuestInformationTooltip", UIParent, "GameTooltipTemplate")
qcQuestInformationTooltip:SetFrameStrata("TOOLTIP")
end
-- commands
function WoWeuCN_Quests_SlashCommand(msg)
if (msg=="on" or msg=="ON") then
if (WoWeuCN_Quests_PS["active"]=="1") then
print ("WOWeuCN - 翻译模块已启用.");
else
print ("|cffffff00WOWeuCN - 翻译模块已启用.");
WoWeuCN_Quests_PS["active"] = "1";
WoWeuCN_Quests_ToggleButton0:Enable();
WoWeuCN_Quests_ToggleButton1:Enable();
WoWeuCN_Quests_ToggleButton2:Enable();
WoWeuCN_Quests_Translate_On(1);
end
elseif (msg=="off" or msg=="OFF") then
if (WoWeuCN_Quests_PS["active"]=="0") then
print ("WOWeuCN - 翻译模块已关闭.");
else
print ("|cffffff00WOWeuCN - 翻译模块已关闭.");
WoWeuCN_Quests_PS["active"] = "0";
WoWeuCN_Quests_ToggleButton0:Disable();
WoWeuCN_Quests_ToggleButton1:Disable();
WoWeuCN_Quests_ToggleButton2:Disable();
WoWeuCN_Quests_Translate_Off(1);
end
-- title option
elseif (msg=="title on" or msg=="TITLE ON" or msg=="title 1") then
if (WoWeuCN_Quests_PS["transtilte"]=="1") then
print ("WOWeuCN - 翻译标题 : 启用.");
else
print ("|cffffff00WOWeuCN - 翻译标题 : 启用.");
WoWeuCN_Quests_PS["transtitle"] = "1";
QuestInfoTitleHeader:SetFont(WoWeuCN_Quests_Font1, 18);
end
elseif (msg=="title off" or msg=="TITLE OFF" or msg=="title 0") then
if (WoWeuCN_Quests_PS["transtilte"]=="0") then
print ("WOWeuCN - 翻译标题 : 禁用.");
else
print ("|cffffff00WOWeuCN - 翻译标题 : 禁用.");
WoWeuCN_Quests_PS["transtitle"] = "0";
end
elseif (msg=="title" or msg=="TITLE") then
if (WoWeuCN_Quests_PS["transtilte"]=="1") then
print ("WOWeuCN - 翻译标题状态 : 启用.");
else
print ("WOWeuCN - 翻译标题状态 : 禁用.");
end
-- objectives option
elseif (msg=="objectives on" or msg=="OBJECTIVES ON" or msg=="objectives 1") then
if (WoWeuCN_Quests_PS["transobjectives"]=="1") then
print ("WOWeuCN - 翻译任务目标 : 启用.");
else
print ("|cffffff00WOWeuCN - 翻译任务目标 : 启用.");
WoWeuCN_Quests_PS["transobjectives"] = "1";
end
elseif (msg=="objectives off" or msg=="OBJECTIVES OFF" or msg=="objectives 0") then
if (WoWeuCN_Quests_PS["transobjectives"]=="0") then
print ("WOWeuCN - 翻译任务目标 : 禁用.");
else
print ("|cffffff00WOWeuCN - 翻译任务目标 : 禁用.");
WoWeuCN_Quests_PS["transobjectives"] = "0";
end
elseif (msg=="objectives" or msg=="OBJECTIVES") then
if (WoWeuCN_Quests_PS["transobjectives"]=="1") then
print ("WOWeuCN - 翻译任务目标状态 : 启用.");
else
print ("WOWeuCN - 翻译任务目标状态 : 禁用.");
end
-- dev scan
elseif (msg=="back" or msg=="BACK") then
WoWeuCN_Quests_QuestIndex = WoWeuCN_Quests_QuestIndex - 500;
print(WoWeuCN_Quests_QuestIndex);
elseif (msg=="reset" or msg=="RESET") then
WoWeuCN_Quests_QuestIndex = 1;
print("Reset");
elseif (msg=="clear" or msg=="CLEAR") then
WoWeuCN_Quests_QuestIndex = 1;
WoWeuCN_Quests_QuestToolTips = {}
print("Clear");
elseif (msg=="scan" or msg=="SCAN") then
if (WoWeuCN_Quests_QuestToolTips == nil) then
WoWeuCN_Quests_QuestToolTips = {}
end
if (WoWeuCN_Quests_QuestIndex == nil) then
WoWeuCN_Quests_QuestIndex = 1
end
for i = WoWeuCN_Quests_QuestIndex, WoWeuCN_Quests_QuestIndex + 500 do
qcQuestInformationTooltip:SetOwner(UIParent, "ANCHOR_NONE")
qcQuestInformationTooltip:ClearLines()
qcQuestInformationTooltip:SetHyperlink('quest:' .. i)
qcQuestInformationTooltip:Show()
local text = EnumerateTooltipLines(qcQuestInformationTooltip)
if (text ~= '' and text ~= nil) then
WoWeuCN_Quests_QuestToolTips[i .. ''] = text
print(i)
end
end
WoWeuCN_Quests_QuestIndex = WoWeuCN_Quests_QuestIndex + 500
elseif (msg=="scanauto" or msg=="SCANAUTO") then
if (WoWeuCN_Quests_QuestToolTips == nil) then
WoWeuCN_Quests_QuestToolTips = {}
end
if (WoWeuCN_Quests_QuestIndex == nil) then
WoWeuCN_Quests_QuestIndex = 1
end
WoWeuCN_Quests_QuestIndex = 60000
QTR_wait(0.1, scanAuto, WoWeuCN_Quests_QuestIndex, 1, 0)
elseif (msg=="scancacheauto" or msg=="SCANCACHEAUTO") then
if (WoWeuCN_Quests_QuestToolTips == nil) then
WoWeuCN_Quests_QuestToolTips = {}
end
if (WoWeuCN_Quests_QuestIndex == nil) then
WoWeuCN_Quests_QuestIndex = 1
end
WoWeuCN_Quests_QuestIndex = 60000
QTR_wait(0.1, scanCacheAuto, WoWeuCN_Quests_QuestIndex, 1, 0)
elseif (msg=="") then
InterfaceOptionsFrame_Show();
InterfaceOptionsFrame_OpenToCategory("WoWeuCN-Quests");
else
print ("WOWeuCN - 指令说明:");
print (" /woweucn on - 启用翻译模块");
print (" /woweucn off - 禁用翻译模块");
print (" /woweucn title on - 启用标题翻译");
print (" /woweucn title off - 禁用标题翻译");
print (" /woweucn objectives on - 启用任务目标翻译");
print (" /woweucn objectives off - 禁用任务目标翻译");
end
end
function WoWeuCN_Quests_SetCheckButtonState()
WoWeuCN_QuestsCheckButton0:SetChecked(WoWeuCN_Quests_PS["active"]=="1");
WoWeuCN_QuestsCheckButton3:SetChecked(WoWeuCN_Quests_PS["transtitle"]=="1");
WoWeuCN_QuestsCheckButton4:SetChecked(WoWeuCN_Quests_PS["transobjectives"]=="1");
WoWeuCN_QuestsCheckOther1:SetChecked(WoWeuCN_Quests_PS["other1"]=="1");
WoWeuCN_QuestsCheckOther2:SetChecked(WoWeuCN_Quests_PS["other2"]=="1");
WoWeuCN_QuestsCheckOther3:SetChecked(WoWeuCN_Quests_PS["other3"]=="1");
end
function WoweuCN_LoadOriginalHeaders()
if QuestInfoDescriptionHeader:GetText() ~= nil and QuestInfoDescriptionHeader:GetText() ~= WoWeuCN_Quests_MessOrig.details and QuestInfoDescriptionHeader:GetText() ~= WoWeuCN_Quests_Messages.details then
WoWeuCN_Quests_MessOrig.details = QuestInfoDescriptionHeader:GetText()
end
if QuestInfoObjectivesHeader:GetText() ~= nil and QuestInfoObjectivesHeader:GetText() ~= WoWeuCN_Quests_MessOrig.objectives and QuestInfoObjectivesHeader:GetText() ~= WoWeuCN_Quests_Messages.objectives then
WoWeuCN_Quests_MessOrig.objectives = QuestInfoObjectivesHeader:GetText()
end
if QuestInfoRewardsFrame.Header:GetText() ~= nil and QuestInfoRewardsFrame.Header:GetText() ~= WoWeuCN_Quests_MessOrig.rewards and QuestInfoRewardsFrame.Header:GetText() ~= WoWeuCN_Quests_Messages.rewards then
WoWeuCN_Quests_MessOrig.rewards = QuestInfoRewardsFrame.Header:GetText()
end
if QuestInfoRewardsFrame.ItemChooseText:GetText() ~= nil and QuestInfoRewardsFrame.ItemChooseText:GetText() ~= WoWeuCN_Quests_MessOrig.itemchoose1 and QuestInfoRewardsFrame.ItemChooseText:GetText() ~= WoWeuCN_Quests_Messages.itemchoose1 then
WoWeuCN_Quests_MessOrig.itemchoose1 = QuestInfoRewardsFrame.ItemChooseText:GetText()
end
if QuestInfoRewardsFrame.ItemReceiveText:GetText() ~= nil and QuestInfoRewardsFrame.ItemReceiveText:GetText() ~= WoWeuCN_Quests_MessOrig.itemreceiv1 and QuestInfoRewardsFrame.ItemReceiveText:GetText() ~= WoWeuCN_Quests_Messages.itemreceiv1 then
WoWeuCN_Quests_MessOrig.itemreceiv1 = QuestInfoRewardsFrame.ItemReceiveText:GetText()
end
if QuestInfoSpellObjectiveLearnLabel:GetText() ~= nil and QuestInfoSpellObjectiveLearnLabel:GetText() ~= WoWeuCN_Quests_MessOrig.learnspell and QuestInfoSpellObjectiveLearnLabel:GetText() ~= WoWeuCN_Quests_Messages.learnspell then
WoWeuCN_Quests_MessOrig.learnspell = QuestInfoSpellObjectiveLearnLabel:GetText()
end
if QuestProgressRequiredMoneyText:GetText() ~= nil and QuestProgressRequiredMoneyText:GetText() ~= WoWeuCN_Quests_MessOrig.reqmoney and QuestProgressRequiredMoneyText:GetText() ~= WoWeuCN_Quests_Messages.reqmoney then
WoWeuCN_Quests_MessOrig.reqmoney = QuestProgressRequiredMoneyText:GetText()
end
if QuestProgressRequiredItemsText:GetText() ~= nil and QuestProgressRequiredItemsText:GetText() ~= WoWeuCN_Quests_MessOrig.reqitems and QuestProgressRequiredItemsText:GetText() ~= WoWeuCN_Quests_Messages.reqitems then
WoWeuCN_Quests_MessOrig.reqitems = QuestProgressRequiredItemsText:GetText()
end
end
function WoWeuCN_Quests_BlizzardOptions()
-- Create main frame for information text
local WoWeuCN_QuestsOptions = CreateFrame("FRAME", "WoWeuCN_Quests_Options");
WoWeuCN_QuestsOptions.name = "WoWeuCN-Quests";
WoWeuCN_QuestsOptions.refresh = function (self) WoWeuCN_Quests_SetCheckButtonState() end;
InterfaceOptions_AddCategory(WoWeuCN_QuestsOptions);
local WoWeuCN_QuestsOptionsHeader = WoWeuCN_QuestsOptions:CreateFontString(nil, "ARTWORK");
WoWeuCN_QuestsOptionsHeader:SetFontObject(GameFontNormalLarge);
WoWeuCN_QuestsOptionsHeader:SetJustifyH("LEFT");
WoWeuCN_QuestsOptionsHeader:SetJustifyV("TOP");
WoWeuCN_QuestsOptionsHeader:ClearAllPoints();
WoWeuCN_QuestsOptionsHeader:SetPoint("TOPLEFT", 16, -16);
WoWeuCN_QuestsOptionsHeader:SetText("WoWeuCN-Quests, ver. "..WoWeuCN_Quests_version.." ("..WoWeuCN_Quests_base..") by qqytqqyt © 2020");
WoWeuCN_QuestsOptionsHeader:SetFont(WoWeuCN_Quests_Font2, 16);
local WoWeuCN_QuestsPlayer = WoWeuCN_QuestsOptions:CreateFontString(nil, "ARTWORK");
WoWeuCN_QuestsPlayer:SetFontObject(GameFontNormalLarge);
WoWeuCN_QuestsPlayer:SetJustifyH("LEFT");
WoWeuCN_QuestsPlayer:SetJustifyV("TOP");
WoWeuCN_QuestsPlayer:ClearAllPoints();
WoWeuCN_QuestsPlayer:SetPoint("TOPRIGHT", WoWeuCN_QuestsOptionsHeader, "TOPRIGHT", 0, -22);
WoWeuCN_QuestsPlayer:SetText("作者 : "..WoWeuCN_Quests_Messages.author);
WoWeuCN_QuestsPlayer:SetFont(WoWeuCN_Quests_Font2, 16);
local WoWeuCN_QuestsCheckButton0 = CreateFrame("CheckButton", "WoWeuCN_QuestsCheckButton0", WoWeuCN_QuestsOptions, "OptionsCheckButtonTemplate");
WoWeuCN_QuestsCheckButton0:SetPoint("TOPLEFT", WoWeuCN_QuestsOptionsHeader, "BOTTOMLEFT", 0, -44);
WoWeuCN_QuestsCheckButton0:SetScript("OnClick", function(self) if (WoWeuCN_Quests_PS["active"]=="1") then WoWeuCN_Quests_PS["active"]="0" else WoWeuCN_Quests_PS["active"]="1" end; end);
WoWeuCN_QuestsCheckButton0Text:SetFont(WoWeuCN_Quests_Font2, 13);
WoWeuCN_QuestsCheckButton0Text:SetText(WoWeuCN_Quests_Interface.active);
local WoWeuCN_QuestsOptionsMode1 = WoWeuCN_QuestsOptions:CreateFontString(nil, "ARTWORK");
WoWeuCN_QuestsOptionsMode1:SetFontObject(GameFontWhite);
WoWeuCN_QuestsOptionsMode1:SetJustifyH("LEFT");
WoWeuCN_QuestsOptionsMode1:SetJustifyV("TOP");
WoWeuCN_QuestsOptionsMode1:ClearAllPoints();
WoWeuCN_QuestsOptionsMode1:SetPoint("TOPLEFT", WoWeuCN_QuestsCheckButton0, "BOTTOMLEFT", 30, -20);
WoWeuCN_QuestsOptionsMode1:SetFont(WoWeuCN_Quests_Font2, 13);
WoWeuCN_QuestsOptionsMode1:SetText(WoWeuCN_Quests_Interface.options1);
local WoWeuCN_QuestsCheckButton3 = CreateFrame("CheckButton", "WoWeuCN_QuestsCheckButton3", WoWeuCN_QuestsOptions, "OptionsCheckButtonTemplate");
WoWeuCN_QuestsCheckButton3:SetPoint("TOPLEFT", WoWeuCN_QuestsOptionsMode1, "BOTTOMLEFT", 0, -5);
WoWeuCN_QuestsCheckButton3:SetScript("OnClick", function(self) if (WoWeuCN_Quests_PS["transtitle"]=="0") then WoWeuCN_Quests_PS["transtitle"]="1" else WoWeuCN_Quests_PS["transtitle"]="0" end; end);
WoWeuCN_QuestsCheckButton3Text:SetFont(WoWeuCN_Quests_Font2, 13);
WoWeuCN_QuestsCheckButton3Text:SetText(WoWeuCN_Quests_Interface.transtitle);
local WoWeuCN_QuestsCheckButton4 = CreateFrame("CheckButton", "WoWeuCN_QuestsCheckButton4", WoWeuCN_QuestsOptions, "OptionsCheckButtonTemplate");
WoWeuCN_QuestsCheckButton4:SetPoint("TOPLEFT", WoWeuCN_QuestsOptionsMode1, "BOTTOMLEFT", 0, -25);
WoWeuCN_QuestsCheckButton4:SetScript("OnClick", function(self) if (WoWeuCN_Quests_PS["transobjectives"]=="0") then WoWeuCN_Quests_PS["transobjectives"]="1" else WoWeuCN_Quests_PS["transobjectives"]="0" end; end);
WoWeuCN_QuestsCheckButton4Text:SetFont(WoWeuCN_Quests_Font2, 13);
WoWeuCN_QuestsCheckButton4Text:SetText(WoWeuCN_Quests_Interface.transobjectives);
end
function WoWeuCN_Quests_SaveQuest(event)
if (event=="QUEST_DETAIL") then
WoWeuCN_Quests_SAVED[WoWeuCN_Quests_quest_EN.id.." TITLE"]=GetTitleText(); -- save original title to future translation
WoWeuCN_Quests_SAVED[WoWeuCN_Quests_quest_EN.id.." DESCRIPTION"]=GetQuestText(); -- save original text to future translation
WoWeuCN_Quests_SAVED[WoWeuCN_Quests_quest_EN.id.." OBJECTIVE"]=GetObjectiveText(); -- save original text to future translation
end
if (event=="QUEST_PROGRESS") then
WoWeuCN_Quests_SAVED[WoWeuCN_Quests_quest_EN.id.." PROGRESS"]=GetProgressText(); -- save original text to future translation
end
if (event=="QUEST_COMPLETE") then
WoWeuCN_Quests_SAVED[WoWeuCN_Quests_quest_EN.id.." COMPLETE"]=GetRewardText(); -- save original text to future translation
end
if (WoWeuCN_Quests_SAVED[WoWeuCN_Quests_quest_EN.id.." TITLE"]==nil) then
WoWeuCN_Quests_SAVED[WoWeuCN_Quests_quest_EN.id.." TITLE"]=GetTitleText(); -- save title in case of End only
end
WoWeuCN_Quests_SAVED[WoWeuCN_Quests_quest_EN.id.." PLAYER"]=WoWeuCN_Quests_name..'@'..WoWeuCN_Quests_race..'@'..WoWeuCN_Quests_class; -- save player data
end
function WoWeuCN_Quests_wait(delay, func, ...)
if(type(delay)~="number" or type(func)~="function") then
return false;
end
if (WoWeuCN_Quests_waitFrame == nil) then
WoWeuCN_Quests_waitFrame = CreateFrame("Frame","WoWeuCN_Quests_WaitFrame", UIParent);
WoWeuCN_Quests_waitFrame:SetScript("onUpdate",function (self,elapse)
local count = #WoWeuCN_Quests_waitTable;
local i = 1;
while(i<=count) do
local waitRecord = tremove(WoWeuCN_Quests_waitTable,i);
local d = tremove(waitRecord,1);
local f = tremove(waitRecord,1);
local p = tremove(waitRecord,1);
if(d>elapse) then
tinsert(WoWeuCN_Quests_waitTable,i,{d-elapse,f,p});
i = i + 1;
else
count = count - 1;
f(unpack(p));
end
end
end);
end
tinsert(WoWeuCN_Quests_waitTable,{delay,func,{...}});
return true;
end
function WoWeuCN_Quests_ON_OFF()
if (curr_trans=="1") then
curr_trans="0";
WoWeuCN_Quests_Translate_Off(1);
else
curr_trans="1";
WoWeuCN_Quests_Translate_On(1);
end
end
-- First function called after the add-in has been loaded
function WoWeuCN_Quests_OnLoad()
WoWeuCN_Quests = CreateFrame("Frame");
WoWeuCN_Quests:SetScript("OnEvent", WoWeuCN_Quests_OnEvent);
WoWeuCN_Quests:RegisterEvent("ADDON_LOADED");
WoWeuCN_Quests:RegisterEvent("QUEST_ACCEPTED");
WoWeuCN_Quests:RegisterEvent("QUEST_DETAIL");
WoWeuCN_Quests:RegisterEvent("QUEST_PROGRESS");
WoWeuCN_Quests:RegisterEvent("QUEST_COMPLETE");
-- WoWeuCN_Quests:RegisterEvent("QUEST_FINISHED");
-- WoWeuCN_Quests:RegisterEvent("QUEST_GREETING");
-- Quest ID button in QuestFrame
WoWeuCN_Quests_ToggleButton0 = CreateFrame("Button",nil, QuestFrame, "UIPanelButtonTemplate");
WoWeuCN_Quests_ToggleButton0:SetWidth(150);
WoWeuCN_Quests_ToggleButton0:SetHeight(20);
WoWeuCN_Quests_ToggleButton0:SetText("Quest ID=?");
WoWeuCN_Quests_ToggleButton0:Show();
WoWeuCN_Quests_ToggleButton0:ClearAllPoints();
WoWeuCN_Quests_ToggleButton0:SetPoint("TOPLEFT", QuestFrame, "TOPLEFT", 92, -25);
WoWeuCN_Quests_ToggleButton0:SetScript("OnClick", WoWeuCN_Quests_ON_OFF);
-- Quest ID button in Quest Log Popup Detail Frame
WoWeuCN_Quests_ToggleButton1 = CreateFrame("Button", nil, QuestLogPopupDetailFrame, "UIPanelButtonTemplate");
WoWeuCN_Quests_ToggleButton1:SetWidth(150);
WoWeuCN_Quests_ToggleButton1:SetHeight(20);
WoWeuCN_Quests_ToggleButton1:SetText("Quest ID=?");
WoWeuCN_Quests_ToggleButton1:Show();
WoWeuCN_Quests_ToggleButton1:ClearAllPoints();
WoWeuCN_Quests_ToggleButton1:SetPoint("TOPLEFT", QuestLogPopupDetailFrame, "TOPLEFT", 40, -31);
WoWeuCN_Quests_ToggleButton1:SetScript("OnClick", WoWeuCN_Quests_ON_OFF);
-- Quest ID button in QuestMapDetailsScrollFrame
WoWeuCN_Quests_ToggleButton2 = CreateFrame("Button", nil, QuestMapDetailsScrollFrame, "UIPanelButtonTemplate");
WoWeuCN_Quests_ToggleButton2:SetWidth(150);
WoWeuCN_Quests_ToggleButton2:SetHeight(20);
WoWeuCN_Quests_ToggleButton2:SetText("Quest ID=?");
WoWeuCN_Quests_ToggleButton2:Show();
WoWeuCN_Quests_ToggleButton2:ClearAllPoints();
WoWeuCN_Quests_ToggleButton2:SetPoint("TOPLEFT", QuestMapDetailsScrollFrame, "TOPLEFT", 116, 29);
WoWeuCN_Quests_ToggleButton2:SetScript("OnClick", WoWeuCN_Quests_ON_OFF);
-- function called after clicking on the quest name in QuestTracker
hooksecurefunc(QUEST_TRACKER_MODULE, "OnBlockHeaderClick", WoWeuCN_Quests_PrepareReload);
-- Function called after clicking on the quest name in QuestMapFrame
hooksecurefunc("QuestMapFrame_ShowQuestDetails", WoWeuCN_Quests_PrepareReload);
qcQuestInformationTooltipSetup();
WoweuCN_LoadOriginalHeaders();
end
-- Specifies the current quest ID number from various methods
function WoWeuCN_Quests_GetQuestID()
if (WoWeuCN_Quests_onDebug) then
print('WANTED ID');
end
local quest_ID;
if (QuestMapDetailsScrollFrame:IsVisible() and ((quest_ID==nil) or (quest_ID==0))) then
quest_ID = QuestMapFrame.DetailsFrame.questID;
end
if (QuestLogPopupDetailFrame:IsVisible() and ((quest_ID==nil) or (quest_ID==0))) then
quest_ID = QuestLogPopupDetailFrame.questID;
end
if (quest_ID==nil) then
if ( isGetQuestID=="1" ) then
quest_ID = GetQuestID();
end
end
if (quest_ID==nil) then
if (WoWeuCN_Quests_onDebug) then
print('ID not found');
end
quest_ID=0;
else
if (WoWeuCN_Quests_onDebug) then
print('Found ID='..tostring(quest_ID));
end
end
return (quest_ID);
end
function WoWeuCN_Quests_PrepareReload()
WoWeuCN_Quests_QuestPrepare('');
end;
-- Even handlers
function WoWeuCN_Quests_OnEvent(self, event, name, ...)
if (WoWeuCN_Quests_onDebug) then
print('OnEvent-event: '..event);
end
if (event=="ADDON_LOADED" and name=="WoWeuCN_Quests") then
SlashCmdList["WOWEUCN_QUESTS"] = function(msg) WoWeuCN_Quests_SlashCommand(msg); end
SLASH_WOWEUCN_QUESTS1 = "/woweucn-quests";
SLASH_WOWEUCN_QUESTS2 = "/woweucn";
WoWeuCN_Quests_CheckVars();
-- Create interface Options in Blizzard-Interface-Addons
WoWeuCN_Quests_BlizzardOptions();
QTR_wait(2, Broadcast)
WoWeuCN_Quests:UnregisterEvent("ADDON_LOADED");
WoWeuCN_Quests.ADDON_LOADED = nil;
if (not isGetQuestID) then
DetectEmuServer();
end
elseif (event=="QUEST_DETAIL" or event=="QUEST_PROGRESS" or event=="QUEST_COMPLETE") then
if ( QuestFrame:IsVisible()) then
WoWeuCN_Quests_QuestPrepare(event);
end
end
end
local function OnEvent(self, event, prefix, text, channel, sender, ...)
if event == "CHAT_MSG_ADDON" and prefix == WoWeuCN_AddonPrefix then
if text == "VERSION" then
C_ChatInfo.SendAddonMessage(WoWeuCN_AddonPrefix, "WoWeuCN-Quests ver. "..WoWeuCN_Quests_version, channel)
else
--print(text .. " " .. sender)
end
end
end
function Broadcast()
print ("|cffffff00WoWeuCN-Quests ver. "..WoWeuCN_Quests_version.." - "..WoWeuCN_Quests_Messages.loaded);
local regionCode = GetCurrentRegion()
if (regionCode ~= 3) then
print ("|cffffff00本插件主要服务欧洲服务器玩家。你所在的服务器区域支持中文客户端,如有需要请搜索战网修改客户端语言教程修改语言,直接使用中文进行游戏。|r");
return
end
C_ChatInfo.RegisterAddonMessagePrefix(WoWeuCN_AddonPrefix)
local f = CreateFrame("Frame")
f:RegisterEvent("CHAT_MSG_ADDON")
f:SetScript("OnEvent", OnEvent)
local name,title,_,enabled = GetAddOnInfo('WoWeuCN_Tooltips')
if (title == nil) then
local addonName = _G["GREEN_FONT_COLOR_CODE"] .. "Tooltips Translator - Chinese|r"
print ("|cffffff00欢迎使用任务汉化插件。如需法术/道具等汉化请安装 " .. addonName .. " 翻译插件。|r");
end
if (time() - WoWeuCN_Quests_LastAnnounceDate < WowenCN_Quests_WeekDiff) then
return
end
WoWeuCN_Quests_LastAnnounceDate = time()
local realmName = GetRealmName()
end
-- QuestLogPopupDetailFrame or QuestMapDetailsScrollFrame window opened
function WoWeuCN_Quests_QuestPrepare(questEvent)
q_ID = WoWeuCN_Quests_GetQuestID();
str_ID = tostring(q_ID);
WoWeuCN_Quests_quest_EN.id = q_ID;
WoWeuCN_Quests_quest_LG.id = q_ID;
if ( WoWeuCN_Quests_PS["active"]=="1" ) then -- Translation activated
WoWeuCN_Quests_ToggleButton0:Enable();
WoWeuCN_Quests_ToggleButton1:Enable();
WoWeuCN_Quests_ToggleButton2:Enable();
curr_trans = "1";
if ( WoWeuCN_Quests_QuestData[str_ID] ) then -- Display only when there is a translation
WoWeuCN_Quests_quest_LG.title = WoWeuCN_Quests_ExpandUnitInfo(WoWeuCN_Quests_QuestData[str_ID]["Title"]);
WoWeuCN_Quests_quest_EN.title = GetTitleText();
if (WoWeuCN_Quests_quest_EN.title=="") then
WoWeuCN_Quests_quest_EN.title = C_QuestLog.GetTitleForQuestID(str_ID);
end
WoWeuCN_Quests_quest_LG.details = WoWeuCN_Quests_ExpandUnitInfo(WoWeuCN_Quests_QuestData[str_ID]["Description"]);
WoWeuCN_Quests_quest_LG.objectives = WoWeuCN_Quests_ExpandUnitInfo(WoWeuCN_Quests_QuestData[str_ID]["Objectives"]);
if (questEvent=="QUEST_DETAIL") then
WoWeuCN_Quests_quest_EN.details = GetQuestText();
WoWeuCN_Quests_quest_EN.objectives = GetObjectiveText();
WoWeuCN_Quests_quest_EN.itemchoose = WoWeuCN_Quests_MessOrig.itemchoose1;
WoWeuCN_Quests_quest_LG.itemchoose = WoWeuCN_Quests_Messages.itemchoose1;
WoWeuCN_Quests_quest_EN.itemreceive = WoWeuCN_Quests_MessOrig.itemreceiv1;
WoWeuCN_Quests_quest_LG.itemreceive = WoWeuCN_Quests_Messages.itemreceiv1;
--if (strlen(WoWeuCN_Quests_quest_EN.details)>0 and strlen(WoWeuCN_Quests_quest_LG.details)==0) then
-- WoWeuCN_Quests_MISSING[WoWeuCN_Quests_quest_EN.id.." DESCRIPTION"]=WoWeuCN_Quests_quest_EN.details; -- save missing translation part
--end
--if (strlen(WoWeuCN_Quests_quest_EN.objectives)>0 and strlen(WoWeuCN_Quests_quest_LG.objectives)==0) then
-- WoWeuCN_Quests_MISSING[WoWeuCN_Quests_quest_EN.id.." OBJECTIVE"]=WoWeuCN_Quests_quest_EN.objectives; -- save missing translation part
--end
else
if (WoWeuCN_Quests_quest_LG.details ~= QuestInfoDescriptionText:GetText()) then
WoWeuCN_Quests_quest_EN.details = QuestInfoDescriptionText:GetText();
end
if (WoWeuCN_Quests_quest_LG.objectives ~= QuestInfoObjectivesText:GetText()) then
WoWeuCN_Quests_quest_EN.objectives = QuestInfoObjectivesText:GetText();
end
end
if (questEvent=="QUEST_PROGRESS") then
WoWeuCN_Quests_quest_EN.progress = GetProgressText();
WoWeuCN_Quests_quest_LG.progress = WoWeuCN_Quests_ExpandUnitInfo(WoWeuCN_Quests_QuestData[str_ID]["Progress"]);
--if (strlen(WoWeuCN_Quests_quest_EN.progress)>0 and strlen(WoWeuCN_Quests_quest_LG.progress)==0) then
-- WoWeuCN_Quests_MISSING[WoWeuCN_Quests_quest_EN.id.." PROGRESS"]=WoWeuCN_Quests_quest_EN.progress; -- save missing translation part
--end
--if (strlen(WoWeuCN_Quests_quest_LG.progress)==0) then -- The content is empty and the Progress window has been opened
-- WoWeuCN_Quests_quest_LG.progress = '';
--end
end
if (questEvent=="QUEST_COMPLETE") then
WoWeuCN_Quests_quest_EN.completion = GetRewardText();
WoWeuCN_Quests_quest_LG.completion = WoWeuCN_Quests_ExpandUnitInfo(WoWeuCN_Quests_QuestData[str_ID]["Completion"]);
WoWeuCN_Quests_quest_EN.itemchoose = WoWeuCN_Quests_MessOrig.itemchoose2;
WoWeuCN_Quests_quest_LG.itemchoose = WoWeuCN_Quests_Messages.itemchoose2;
WoWeuCN_Quests_quest_EN.itemreceive = WoWeuCN_Quests_MessOrig.itemreceiv2;
WoWeuCN_Quests_quest_LG.itemreceive = WoWeuCN_Quests_Messages.itemreceiv2;
--if (strlen(WoWeuCN_Quests_quest_EN.completion)>0 and strlen(WoWeuCN_Quests_quest_LG.completion)==0) then
-- WoWeuCN_Quests_MISSING[WoWeuCN_Quests_quest_EN.id.." COMPLETE"]=WoWeuCN_Quests_quest_EN.completion; -- save missing translation part
--end
end
-- missing data
if (WoWeuCN_Quests_quest_EN.details ~= nil and strlen(WoWeuCN_Quests_quest_EN.details)>0 and strlen(WoWeuCN_Quests_quest_LG.details)==0) then
WoWeuCN_Quests_quest_LG.details = WoWeuCN_Quests_quest_EN.details;
QuestInfoDescriptionHeader:SetFont(Original_Font1, 18);
QuestInfoDescriptionText:SetFont(Original_Font2, Original_Font2_Size);
end
if (WoWeuCN_Quests_quest_EN.objectives ~= nil and strlen(WoWeuCN_Quests_quest_EN.objectives)>0 and strlen(WoWeuCN_Quests_quest_LG.objectives)==0) then
WoWeuCN_Quests_quest_LG.objectives = WoWeuCN_Quests_quest_EN.objectives;
QuestInfoObjectivesHeader:SetFont(Original_Font1, 18);
QuestInfoObjectivesText:SetFont(Original_Font2, Original_Font2_Size);
end
if (WoWeuCN_Quests_quest_EN.progress ~= nil and strlen(WoWeuCN_Quests_quest_EN.progress)>0 and strlen(WoWeuCN_Quests_quest_LG.progress)==0) then
WoWeuCN_Quests_quest_LG.progress = WoWeuCN_Quests_quest_EN.progress;
QuestProgressText:SetFont(Original_Font2, Original_Font2_Size);
end
if (WoWeuCN_Quests_quest_EN.completion ~= nil and strlen(WoWeuCN_Quests_quest_EN.completion)>0 and strlen(WoWeuCN_Quests_quest_LG.completion)==0) then
WoWeuCN_Quests_quest_LG.completion = WoWeuCN_Quests_quest_EN.completion;
QuestInfoRewardText:SetFont(Original_Font2, Original_Font2_Size);
end
WoWeuCN_Quests_ToggleButton0:SetText("Quest ID="..WoWeuCN_Quests_quest_LG.id.." ("..WoWeuCN_Quests_lang..")");
WoWeuCN_Quests_ToggleButton1:SetText("Quest ID="..WoWeuCN_Quests_quest_LG.id.." ("..WoWeuCN_Quests_lang..")");
WoWeuCN_Quests_ToggleButton2:SetText("Quest ID="..WoWeuCN_Quests_quest_LG.id.." ("..WoWeuCN_Quests_lang..")");
WoWeuCN_Quests_Translate_On(1);
else -- Quest cannot be translated
WoWeuCN_Quests_ToggleButton0:Disable();
WoWeuCN_Quests_ToggleButton1:Disable();
WoWeuCN_Quests_ToggleButton2:Disable();
WoWeuCN_Quests_ToggleButton0:SetText("Quest ID="..str_ID);
WoWeuCN_Quests_ToggleButton1:SetText("Quest ID="..str_ID);
WoWeuCN_Quests_ToggleButton2:SetText("Quest ID="..str_ID);
WoWeuCN_Quests_Translate_On(0);
--WoWeuCN_Quests_SaveQuest(questEvent);
end -- The quest is translated in the database
else -- Translations off...
WoWeuCN_Quests_ToggleButton0:Disable();
WoWeuCN_Quests_ToggleButton1:Disable();
WoWeuCN_Quests_ToggleButton2:Disable();
if ( WoWeuCN_Quests_QuestData[str_ID] ) then -- ...but there is a translation in the database
WoWeuCN_Quests_ToggleButton1:SetText("Quest ID="..str_ID);
WoWeuCN_Quests_ToggleButton2:SetText("Quest ID="..str_ID);
else
WoWeuCN_Quests_ToggleButton1:SetText("Quest ID="..str_ID);
WoWeuCN_Quests_ToggleButton2:SetText("Quest ID="..str_ID);
end
end -- Translation actviated
end
-- Displays the translation
function WoWeuCN_Quests_Translate_On(typ)
WoweuCN_LoadOriginalHeaders()
if (WoWeuCN_Quests_PS["transtitle"]=="1") then -- view translated title
QuestInfoTitleHeader:SetFont(WoWeuCN_Quests_Font1, 18);
QuestProgressTitleText:SetFont(WoWeuCN_Quests_Font1, 18);
end
if (WoWeuCN_Quests_PS["transobjectives"]=="1") then
QuestInfoObjectivesHeader:SetFont(WoWeuCN_Quests_Font1, 18);
QuestInfoObjectivesHeader:SetText(WoWeuCN_Quests_Messages.objectives);
QuestInfoObjectivesText:SetFont(WoWeuCN_Quests_Font2, 13);
end
QuestInfoRewardsFrame.Header:SetFont(WoWeuCN_Quests_Font1, 18);
QuestInfoRewardsFrame.Header:SetText(WoWeuCN_Quests_Messages.rewards);
QuestInfoDescriptionHeader:SetFont(WoWeuCN_Quests_Font1, 18);
QuestInfoDescriptionHeader:SetText(WoWeuCN_Quests_Messages.details);
QuestProgressRequiredItemsText:SetFont(WoWeuCN_Quests_Font1, 18);
QuestProgressRequiredItemsText:SetText(WoWeuCN_Quests_Messages.reqitems);
QuestInfoRewardsFrame.ItemChooseText:SetFont(WoWeuCN_Quests_Font2, 13);
QuestInfoRewardsFrame.ItemReceiveText:SetFont(WoWeuCN_Quests_Font2, 13);
QuestInfoSpellObjectiveLearnLabel:SetFont(WoWeuCN_Quests_Font2, 13);
QuestInfoSpellObjectiveLearnLabel:SetText(WoWeuCN_Quests_Messages.learnspell);
QuestInfoXPFrame.ReceiveText:SetFont(WoWeuCN_Quests_Font2, 13);
QuestInfoXPFrame.ReceiveText:SetText(WoWeuCN_Quests_Messages.experience);
-- MapQuestInfoRewardsFrame.ItemChooseText:SetFont(WoWeuCN_Quests_Font2, 11);
-- MapQuestInfoRewardsFrame.ItemReceiveText:SetFont(WoWeuCN_Quests_Font2, 11);
-- MapQuestInfoRewardsFrame.ItemChooseText:SetText(WoWeuCN_Quests_Messages.itemchoose1);
-- MapQuestInfoRewardsFrame.ItemReceiveText:SetText(WoWeuCN_Quests_Messages.itemreceiv1);
if (typ==1) then -- pełne przełączenie (jest tłumaczenie)
QuestInfoRewardsFrame.ItemChooseText:SetText(WoWeuCN_Quests_Messages.itemchoose1);
QuestInfoRewardsFrame.ItemReceiveText:SetText(WoWeuCN_Quests_Messages.itemreceiv1);
numer_ID = WoWeuCN_Quests_quest_LG.id;
str_ID = tostring(numer_ID);
if (numer_ID>0 and WoWeuCN_Quests_QuestData[str_ID]) then -- restore translated subtitle version
if (WoWeuCN_Quests_PS["transtitle"]=="1") then
QuestInfoTitleHeader:SetText(WoWeuCN_Quests_quest_LG.title);
QuestProgressTitleText:SetText(WoWeuCN_Quests_quest_LG.title);
end
WoWeuCN_Quests_ToggleButton0:SetText("Quest ID="..WoWeuCN_Quests_quest_LG.id.." ("..WoWeuCN_Quests_lang..")");
WoWeuCN_Quests_ToggleButton1:SetText("Quest ID="..WoWeuCN_Quests_quest_LG.id.." ("..WoWeuCN_Quests_lang..")");
WoWeuCN_Quests_ToggleButton2:SetText("Quest ID="..WoWeuCN_Quests_quest_LG.id.." ("..WoWeuCN_Quests_lang..")");
if (WoWeuCN_Quests_quest_LG.details ~= WoWeuCN_Quests_quest_EN.details) then
QuestInfoDescriptionText:SetFont(WoWeuCN_Quests_Font2, 13);
QuestInfoDescriptionText:SetText(WoWeuCN_Quests_quest_LG.details);
end
if (WoWeuCN_Quests_PS["transobjectives"]=="1" and WoWeuCN_Quests_quest_LG.objectives ~= WoWeuCN_Quests_quest_EN.objectives) then
QuestInfoObjectivesText:SetFont(WoWeuCN_Quests_Font2, 13);
QuestInfoObjectivesText:SetText(WoWeuCN_Quests_quest_LG.objectives);
end
if (WoWeuCN_Quests_quest_LG.progress ~= WoWeuCN_Quests_quest_EN.progress) then
QuestProgressText:SetText(WoWeuCN_Quests_quest_LG.progress);
QuestProgressText:SetFont(WoWeuCN_Quests_Font2, 13);
end
if (WoWeuCN_Quests_quest_LG.completion ~= WoWeuCN_Quests_quest_EN.completion) then
QuestInfoRewardText:SetText(WoWeuCN_Quests_quest_LG.completion);
QuestInfoRewardText:SetFont(WoWeuCN_Quests_Font2, 13);
end
-- QuestInfoRewardsFrame.ItemChooseText:SetText(WoWeuCN_Quests_quest_LG.itemchoose);
-- QuestInfoRewardsFrame.ItemReceiveText:SetText(WoWeuCN_Quests_quest_LG.itemreceive);
end
else
QuestInfoTitleHeader:SetFont(Original_Font1, 18);
QuestProgressTitleText:SetFont(Original_Font1, 18);
QuestInfoObjectivesHeader:SetFont(Original_Font1, 18);
QuestInfoObjectivesHeader:SetText(WoWeuCN_Quests_MessOrig.objectives);
QuestInfoRewardsFrame.Header:SetFont(Original_Font1, 18);
QuestInfoRewardsFrame.Header:SetText(WoWeuCN_Quests_MessOrig.rewards);
QuestInfoDescriptionHeader:SetFont(Original_Font1, 18);
QuestInfoDescriptionHeader:SetText(WoWeuCN_Quests_MessOrig.details);
QuestProgressRequiredItemsText:SetFont(Original_Font1, 18);
QuestProgressRequiredItemsText:SetText(WoWeuCN_Quests_MessOrig.reqitems);
QuestInfoDescriptionText:SetFont(Original_Font2, Original_Font2_Size);
QuestInfoObjectivesText:SetFont(Original_Font2, Original_Font2_Size);
QuestProgressText:SetFont(Original_Font2, Original_Font2_Size);
QuestInfoRewardText:SetFont(Original_Font2, Original_Font2_Size);
QuestInfoRewardsFrame.ItemChooseText:SetFont(Original_Font2, Original_Font2_Size);
QuestInfoRewardsFrame.ItemReceiveText:SetFont(Original_Font2, Original_Font2_Size);
end
end
-- Displays the original text
function WoWeuCN_Quests_Translate_Off(typ)
QuestInfoTitleHeader:SetFont(Original_Font1, 18);
QuestProgressTitleText:SetFont(Original_Font1, 18);
QuestInfoObjectivesHeader:SetFont(Original_Font1, 18);
QuestInfoObjectivesHeader:SetText(WoWeuCN_Quests_MessOrig.objectives);
QuestInfoRewardsFrame.Header:SetFont(Original_Font1, 18);
QuestInfoRewardsFrame.Header:SetText(WoWeuCN_Quests_MessOrig.rewards);
QuestInfoDescriptionHeader:SetFont(Original_Font1, 18);
QuestInfoDescriptionHeader:SetText(WoWeuCN_Quests_MessOrig.details);
QuestProgressRequiredItemsText:SetFont(Original_Font1, 18);
QuestProgressRequiredItemsText:SetText(WoWeuCN_Quests_MessOrig.reqitems);
QuestInfoDescriptionText:SetFont(Original_Font2, Original_Font2_Size);
QuestInfoObjectivesText:SetFont(Original_Font2, Original_Font2_Size);
QuestProgressText:SetFont(Original_Font2, Original_Font2_Size);
QuestInfoRewardText:SetFont(Original_Font2, Original_Font2_Size);
QuestInfoRewardsFrame.ItemChooseText:SetFont(Original_Font2, Original_Font2_Size);
QuestInfoRewardsFrame.ItemReceiveText:SetFont(Original_Font2, Original_Font2_Size);
-- MapQuestInfoRewardsFrame.ItemReceiveText:SetFont(Original_Font2, 11);
-- MapQuestInfoRewardsFrame.ItemChooseText:SetFont(Original_Font2, 11);
QuestInfoSpellObjectiveLearnLabel:SetFont(Original_Font2, Original_Font2_Size);
QuestInfoSpellObjectiveLearnLabel:SetText(WoWeuCN_Quests_MessOrig.learnspell);
QuestInfoXPFrame.ReceiveText:SetFont(Original_Font2, Original_Font2_Size);
QuestInfoXPFrame.ReceiveText:SetText(WoWeuCN_Quests_MessOrig.experience);
if (typ==1) then -- pełne przełączenie (jest tłumaczenie)
QuestInfoRewardsFrame.ItemChooseText:SetText(WoWeuCN_Quests_MessOrig.itemchoose1);
QuestInfoRewardsFrame.ItemReceiveText:SetText(WoWeuCN_Quests_MessOrig.itemreceiv1);
numer_ID = WoWeuCN_Quests_quest_EN.id;
if (numer_ID>0 and WoWeuCN_Quests_QuestData[str_ID]) then -- restore original subtitle version
WoWeuCN_Quests_ToggleButton0:SetText("Quest ID="..WoWeuCN_Quests_quest_EN.id);
WoWeuCN_Quests_ToggleButton1:SetText("Quest ID="..WoWeuCN_Quests_quest_EN.id);
WoWeuCN_Quests_ToggleButton2:SetText("Quest ID="..WoWeuCN_Quests_quest_EN.id);
QuestInfoTitleHeader:SetText(WoWeuCN_Quests_quest_EN.title);
QuestProgressTitleText:SetText(WoWeuCN_Quests_quest_EN.title);
QuestInfoDescriptionText:SetText(WoWeuCN_Quests_quest_EN.details);
QuestInfoObjectivesText:SetText(WoWeuCN_Quests_quest_EN.objectives);
QuestProgressText:SetText(WoWeuCN_Quests_quest_EN.progress);
QuestInfoRewardText:SetText(WoWeuCN_Quests_quest_EN.completion);
end
end
end
-- replace special characters in the text
function WoWeuCN_Quests_ExpandUnitInfo(msg)
msg = string.gsub(msg, "NEW_LINE", "\n");
msg = string.gsub(msg, "{name}", WoWeuCN_Quests_name);
-- player gender YOUR_GENDER(x;y)
local nr_1, nr_2, nr_3 = 0;
local WoWeuCN_Quests_forma = "";
local nr_poz = string.find(msg, "YOUR_GENDER"); -- gdy nie znalazł, jest: nil
while (nr_poz and nr_poz>0) do
nr_1 = nr_poz + 1;
while (string.sub(msg, nr_1, nr_1) ~= "(") do
nr_1 = nr_1 + 1;
end
if (string.sub(msg, nr_1, nr_1) == "(") then
nr_2 = nr_1 + 1;
while (string.sub(msg, nr_2, nr_2) ~= ";") do
nr_2 = nr_2 + 1;
end
if (string.sub(msg, nr_2, nr_2) == ";") then
nr_3 = nr_2 + 1;
while (string.sub(msg, nr_3, nr_3) ~= ")") do
nr_3 = nr_3 + 1;
end
if (string.sub(msg, nr_3, nr_3) == ")") then
if (WoWeuCN_Quests_sex==3) then -- female form
WoWeuCN_Quests_forma = string.sub(msg,nr_2+1,nr_3-1);
else -- male form
WoWeuCN_Quests_forma = string.sub(msg,nr_1+1,nr_2-1);
end
msg = string.sub(msg,1,nr_poz-1) .. WoWeuCN_Quests_forma .. string.sub(msg,nr_3+1);
end
end
end
nr_poz = string.find(msg, "YOUR_GENDER");
end
if (WoWeuCN_Quests_sex==3) then
msg = string.gsub(msg, "{race}", player_race.W2);
msg = string.gsub(msg, "{class}", player_class.W2);
else
msg = string.gsub(msg, "{race}", player_race.W1);
msg = string.gsub(msg, "{class}", player_class.W1);
end
return msg;
end
|
function permgen (a, n)
n = n or #a -- default for 'n' is size of 'a'
if n <= 1 then -- nothing to change?
coroutine.yield(a)
else
for i = 1, n do
-- put i-th element as the last one
a[n], a[i] = a[i], a[n]
-- generate all permutations of the other elements
permgen(a, n - 1)
-- restore i-th element
a[n], a[i] = a[i], a[n]
end
end
end
function permutations (a)
local co = coroutine.create(function () permgen(a) end)
return function () -- iterator
local code, res = coroutine.resume(co)
return res
end
end
for p in permutations{"a", "b", "c"} do
print(table.concat(p, ","))
end
|
local api = mines
-- Creates a mine given it's name, it's positions, it's list of nodes and their percents, and it's rate at which to regenerate in
api.create_mine = function (mine_name, posA, posB, node_list, regen)
if _mines.tools.addPercent(node_list) > 100 then
_mines.tools.log("Percent exceeds 100, got "..tonumber(_mines.tools.addPercent(node_list)).."%")
return {success=false, errmsg="Percent exceeds 100, got "..tonumber(_mines.tools.addPercent(node_list)).."%", val=nil}
end
local m = minetest.deserialize(_mines.store:get_string("mines")) or {}
m[mine_name] = {
nodes= node_list, -- "node:name=percent", ...
posA= posA, -- Point 1
posB= posB, -- Point 2
regen= regen, -- How many "ticks" till this mine regenerates
timer=0, -- Current time (Set to regen when 0 or below 0, then spawn in terrain)
tp= "", -- If defined, where to place players who were in the mine while it was about to regenerate
-- Should I also add owner? (maybe that as a priv?)
-- Just like spawning to this mine via /mines <mine_name> (omit mine_name to get list of mines)
-- Using priv for spawning to particular mines? (maybe)
}
_mines.store:set_string("mines", minetest.serialize(m))
return {success=true, errmsg="", val=nil}
end
-- Removes a mine and ALL it's data, just given the mine's name
api.remove_mine = function (mine_name)
local m = minetest.deserialize(_mines.store:get_string("mines")) or {}
if _mines.tools.tableContainsValue(m, mine_name) then
local idx = 1
for ind, val in pairs(m) do
if ind == mine_name then
break
end
idx = idx + 1
end
table.remove(m, idx)
_mines.store:set_string("mines", minetest.serialize(m))
return {success=true, errmsg="", val=nil}
end
_mines.tools.log("Failed removing mine called '"..mine_name.."', wasn't found.")
return {success=false, errmsg="Failed removing mine called '"..mine_name.."', wasn't found.", val=nil}
end
-- Returns ALL of the mine's data, just given the mine's name
api.info_mine = function (mine_name)
local m = minetest.deserialize(_mines.store:get_string("mines")) or {}
if _mines.tools.tableContainsValue(m, mine_name) then
return {success=true, errmsg="", val=m[mine_name]}
end
_mines.tools.log("Failed getting info on mine called '"..mine_name.."', wasn't found.")
return {success=false, errmsg="Failed getting info on mine called '"..mine_name.."', wasn't found.", val=nil}
end
-- Sets the teleport point for spawning to a public mine and used to teleport players out of a mine that's regenerating
-- Just give it the mine's name and the position
api.set_mine_tp = function (mine_name, pos)
local m = minetest.deserialize(_mines.store:get_string("mines")) or {}
if _mines.tools.tableContainsValue(m, mine_name) then
m[mine_name].tp = _mines.tools.pos2str(pos)
_mines.store:set_string("mines", minetest.serialize(m))
return {success=true, errmsg="", val=nil}
end
_mines.tools.log("Failed setting mine teleport on mine called '"..mine_name.."', wasn't found.")
return {success=false, errmsg="Failed setting mine teleport on mine called '"..mine_name.."', wasn't found.", val=nil}
end
-- Adds a node to a mine, given mine's name, node's itemstring and node's percent chance to be spawned in
api.add_node = function (mine_name, node, perc)
local m = minetest.deserialize(_mines.store:get_string("mines")) or {}
if _mines.tools.tableContainsValue(m, mine_name) then
local tmp_nodes = m[mine_name].nodes or {}
table.insert(tmp_nodes, tostring(node).."="..tostring(_mines.tools.makePercent(perc)))
local tmp_perc = _mines.tools.addPercent(tmp_nodes)
if tmp_perc > 100 then
_mines.tools.log("Percent exceeds 100, got "..tostring(tmp_perc).."%")
return {success=false, errmsg="Percent exceeds 100, got "..tostring(tmp_perc).."%", val=nil}
end
m[mine_name].nodes = tmp_nodes
_mines.store:set_string("mines", minetest.serialize(m))
return {success=true, errmsg="", val=nil}
end
_mines.tools.log("Failed adding a node into mine called '"..mine_name.."', wasn't found.")
return {success=false, errmsg="Failed adding a node into mine called '"..mine_name.."', wasn't found.", val=nil}
end
-- Removes a node from a mine, given mine's name and node's itemstring
api.remove_node = function (mine_name, node)
local m = minetest.deserialize(_mines.store:get_string("mines")) or {}
if _mines.tools.tableContainsValue(m, mine_name) then
local tmp_nodes = m[mine_name].nodes or {}
local idx = -1
for idex, value in ipairs(tmp_nodes) do
tmp_val = _mines.tools.split(value, "=")
if _mines.tools.contains(tmp_val, node) then
idx = idex
end
end
if idx ~= -1 then
table.remove(tmp_nodes, idex)
m[mine_name].nodes = tmp_nodes
_mines.store:set_string("mines", minetest.serialize(m))
return {success=true, errmsg="", val=nil}
else
_mines.tools.log("Failed removing node '"..node.."' from '"..mine_name.."', as node wasn't found.")
return {success=false, errmsg="Failed removing node '"..node.."' from '"..mine_name.."', as node wasn't found.", val=nil}
end
end
_mines.tools.log("Failed adding a node into mine called '"..mine_name.."', wasn't found.")
return {success=false, errmsg="Failed adding a node into mine called '"..mine_name.."', wasn't found.", val=nil}
end
|
sith_house_loot_deed = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "Sith Meditation Room House Blueprint",
directObjectTemplate = "object/tangible/loot/loot_schematic/sith_house_loot_schem.iff",
craftingValues = {
},
customizationStringNames = {},
customizationValues = {}
}
addLootItemTemplate("sith_house_loot_deed", sith_house_loot_deed)
|
local function one(rec)
return 1
end
local function add(a, b)
return a + b
end
function count(stream)
return stream : map(one) : reduce(add)
end
function count_extra(stream, extra_parameter)
return stream : map(one) : reduce(add)
end
function count_less()
return stream : map(one) : reduce(add);
end
local function having_ge_threshold(bin_having, ge_threshold)
return function(rec)
if rec[bin_having] < ge_threshold then
return false
end
return true
end
end
local function count_bins(group_by_bin)
return function(group, rec)
if rec[group_by_bin] then
local bin_name = rec[group_by_bin]
group[bin_name] = (group[bin_name] or 0) + 1
end
return group
end
end
local function add_values(val1, val2)
return val1 + val2
end
local function reduce_groups(a, b)
return map.merge(a, b, add_values)
end
function group_count(stream, group_by_bin, bin_having, ge_threshold)
if bin_having and ge_threshold then
local myfilter = having_ge_threshold(bin_having, ge_threshold)
return stream : filter(myfilter) : aggregate(map{}, count_bins(group_by_bin)) : reduce(reduce_groups)
else
return stream : aggregate(map{}, count_bins(group_by_bin)) : reduce(reduce_groups)
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.